Compare commits

...
94 Commits
Author SHA1 Message Date
rodrigo ecf692502f Fix localizacao prova
Signed-off-by: Rodrigo Martins <rodrigo.sousa.577@gmail.com>
2025-04-23 00:12:44 -03:00
rodrigo c72d4aad99 tenta fix pdfservice.js 2025-04-22 19:09:56 -03:00
rodrigo 8488bd7b84 tenta fix pdfservice.js 2025-04-22 16:37:51 -03:00
rodrigo 00a9fb9557 tenta fix pdfservice.js 2025-04-22 16:35:46 -03:00
rodrigo 0908378ca0 tenta fix pdfservice.js 2025-04-22 16:31:56 -03:00
rodrigo 46f538332e tenta fix pdfservice.js 2025-04-22 16:18:53 -03:00
rodrigo 494ad6ef9e tenta fix pdfservice.js 2025-04-22 16:08:41 -03:00
rodrigo 0a48bb414a tenta fix pdfservice.js 2025-04-22 16:04:34 -03:00
rodrigo 06f2d473e3 tenta fix pdfservice.js 2025-04-22 15:51:55 -03:00
rodrigo 5698266d3e tenta fix pdfservice.js 2025-04-22 15:29:53 -03:00
rodrigo 41d3963d67 tenta fix pdfservice.js 2025-04-22 15:24:39 -03:00
rodrigo 9b2e51732f tenta fix pdfservice.js 2025-04-22 15:22:23 -03:00
rodrigo 43cc832274 tenta fix pdfservice.js 2025-04-22 15:19:48 -03:00
rodrigo 4a189f82b2 tenta fix pdfservice.js 2025-04-22 15:16:40 -03:00
rodrigo f1f1ee4826 tenta fix pdfservice.js 2025-04-22 15:13:24 -03:00
rodrigo 705ef97ff8 tenta fix pdfservice.js 2025-04-22 15:09:42 -03:00
rodrigo 5b25414b9c tenta fix pdfservice.js 2025-04-22 15:06:49 -03:00
rodrigo e753ec8718 tenta fix pdfservice.js 2025-04-22 15:02:16 -03:00
rodrigo e208346614 tenta fix pdfservice.js 2025-04-22 15:00:47 -03:00
rodrigo 854531bce0 tenta fix pdfservice.js 2025-04-22 14:59:24 -03:00
rodrigo 597236c525 tenta fix pdfservice.js 2025-04-22 14:49:30 -03:00
rodrigo 6fdfc99e7d tenta fix pdfservice.js 2025-04-22 14:44:00 -03:00
rodrigo 045124be2f tenta fix pdfservice.js 2025-04-22 14:25:13 -03:00
rodrigo 8c3cd7a3bf tenta fix pdfservice.js 2025-04-22 12:17:20 -03:00
rodrigo 566ef2e123 tenta fix pdfservice.js 2025-04-22 12:14:27 -03:00
rodrigo 49dba7c9be tenta fix pdfservice.js 2025-04-22 12:06:42 -03:00
rodrigo 3529bffbbb tenta fix pdfservice.js 2025-04-22 12:04:19 -03:00
rodrigo db0c011b8b tenta fix pdfservice.js 2025-04-22 12:02:12 -03:00
rodrigo 19f0187227 tenta fix pdfservice.js 2025-04-22 11:57:14 -03:00
rodrigo 20b2f0e3c9 tenta fix pdfservice.js 2025-04-22 11:33:45 -03:00
rodrigo bbff8eb317 tenta fix pdfservice.js 2025-04-22 11:25:45 -03:00
rodrigo 06165db8bb tenta fix pdfservice.js 2025-04-22 11:19:59 -03:00
rodrigo 3966728ad4 tenta fix pdfservice.js 2025-04-22 11:14:37 -03:00
rodrigo 4708b9ec82 tenta fix pdfservice.js 2025-04-22 11:05:46 -03:00
rodrigo 1214171946 tenta fix pdfservice.js 2025-04-22 10:59:26 -03:00
rodrigo ce795cba58 tenta fix pdfservice.js 2025-04-22 10:54:57 -03:00
rodrigo 942222df6a tenta fix pdfservice.js 2025-04-22 10:53:11 -03:00
rodrigo 7f3313f3f3 tenta fix pdfservice.js 2025-04-22 10:50:44 -03:00
rodrigo a208caec55 tenta fix pdfservice.js 2025-04-22 10:47:12 -03:00
rodrigo e21dea582c tenta fix pdfservice.js 2025-04-22 10:44:51 -03:00
rodrigo c485960759 tenta fix pdfservice.js 2025-04-22 10:42:13 -03:00
rodrigo 79db5cc065 tenta fix pdfservice.js 2025-04-22 10:25:03 -03:00
rodrigo 92239d0a99 tenta fix pdfservice.js 2025-04-22 10:21:45 -03:00
rodrigo fefc6ce434 tenta fix pdfservice.js 2025-04-22 10:18:45 -03:00
rodrigo ac2891ce0d tenta fix pdfservice.js 2025-04-22 10:16:47 -03:00
rodrigo 07b677be29 tenta fix pdfservice.js 2025-04-22 10:14:11 -03:00
rodrigo bd70c10047 tenta fix pdfservice.js 2025-04-22 10:09:39 -03:00
rodrigo 85977d7229 tenta fix pdfservice.js 2025-04-22 10:04:59 -03:00
rodrigo 3406723bd4 tenta fix pdfservice.js 2025-04-22 10:01:02 -03:00
rodrigo cb47df6e88 tenta fix pdfservice.js 2025-04-22 09:56:28 -03:00
rodrigo 0121f67c65 tenta fix pdfservice.js 2025-04-22 09:51:56 -03:00
rodrigo a2bff3baeb tenta fix pdfservice.js 2025-04-22 09:46:30 -03:00
rodrigo defd9b33f5 tenta fix pdfservice.js 2025-04-21 23:11:33 -03:00
rodrigo 8abf8791be tenta fix pdfservice.js 2025-04-21 23:07:18 -03:00
rodrigo 5798152f7b tenta fix pdfservice.js 2025-04-21 23:05:41 -03:00
rodrigo 4726ce1dfa tenta fix pdfservice.js 2025-04-21 23:01:05 -03:00
rodrigo 00a9e698c6 tenta fix pdfservice.js 2025-04-21 22:57:55 -03:00
rodrigo bb5c9e25e2 tenta fix pdfservice.js 2025-04-21 22:50:08 -03:00
rodrigo a946f86cae tenta fix pdfservice.js 2025-04-21 22:46:09 -03:00
rodrigo 7656ff9807 tenta fix pdfservice.js 2025-04-21 22:42:44 -03:00
rodrigo ad3130a160 tenta fix pdfservice.js 2025-04-21 22:38:21 -03:00
rodrigo eeeae75919 tenta fix pdfservice.js 2025-04-21 22:08:29 -03:00
rodrigo 287ed34abf tenta fix pdfservice.js 2025-04-21 22:04:31 -03:00
rodrigo bd67cf49cc tenta fix pdfservice.js 2025-04-21 22:00:48 -03:00
rodrigo 3d044a962a tenta fix pdfservice.js 2025-04-21 21:58:18 -03:00
rodrigo 2a49dab8d5 tenta fix pdfservice.js 2025-04-21 21:51:48 -03:00
rodrigo 17078adc45 tenta fix pdfservice.js 2025-04-21 21:48:31 -03:00
rodrigo bf277416ff tenta fix pdfservice.js 2025-04-21 21:27:07 -03:00
rodrigo 5705978424 tenta fix pdfservice.js 2025-04-21 21:23:43 -03:00
rodrigo b0b7fba0f6 tenta fix pdfservice.js 2025-04-21 21:12:26 -03:00
rodrigo 0a651f94c0 tenta fix pdfservice.js 2025-04-21 21:09:46 -03:00
rodrigo 8cf2c23774 tenta fix pdfservice.js 2025-04-21 21:07:06 -03:00
rodrigo 2475bc6797 tenta fix pdfservice.js 2025-04-21 21:04:27 -03:00
rodrigo 570f3408c9 tenta fix pdfservice.js 2025-04-21 21:00:52 -03:00
rodrigo 8d12d45621 tenta fix pdfservice.js 2025-04-21 20:58:54 -03:00
rodrigo 3edd6ed317 tenta fix pdfservice.js 2025-04-21 20:55:41 -03:00
rodrigo fb17405fe9 tenta fix pdfservice.js 2025-04-21 20:47:49 -03:00
rodrigo f0fee9d22e tenta fix pdfservice.js 2025-04-21 20:37:34 -03:00
rodrigo f14f7ac3fd tenta fix pdfservice.js 2025-04-21 20:36:43 -03:00
rodrigo 76fa2c91ab tenta fix pdfservice.js 2025-04-21 20:35:21 -03:00
rodrigo 7e16bc8919 tenta fix pdfservice.js 2025-04-21 20:24:54 -03:00
rodrigo f3ff4f8939 tenta fix pdfservice.js 2025-04-21 20:22:23 -03:00
rodrigo e91294df22 tenta fix pdfservice.js 2025-04-21 20:17:45 -03:00
rodrigo 8a09720030 tenta fix pdfservice.js 2025-04-21 20:15:22 -03:00
rodrigo 3ccccc6792 tenta fix pdfservice.js 2025-04-21 20:06:37 -03:00
rodrigo f310f07987 tenta fix pdfservice.js 2025-04-21 19:52:13 -03:00
rodrigo e179fb33d7 tenta fix pdfservice.js 2025-04-21 19:48:27 -03:00
rodrigo 3a3c64f1b3 tenta fix pdfservice.js 2025-04-21 19:46:16 -03:00
rodrigo 73b571be71 tenta fix pdfservice.js 2025-04-21 19:42:27 -03:00
rodrigo 5786af03d5 tenta fix pdfservice.js 2025-04-21 19:39:03 -03:00
rodrigo 926a2934e4 tenta fix pdfservice.js 2025-04-21 19:36:52 -03:00
rodrigo a202bdc445 tenta fix pdfservice.js 2025-04-21 19:34:25 -03:00
rodrigo 6d487b5834 tenta fix pdfservice.js 2025-04-21 19:31:33 -03:00
rodrigo 4c4591fee5 fix atendimentos.ts
Signed-off-by: Rodrigo Martins <rodrigo.sousa.577@gmail.com>
2025-04-13 18:55:34 -03:00
35 changed files with 1762 additions and 378 deletions

No files matched your search

+1
View File
@@ -7,3 +7,4 @@ dist
.DS_Store
coverage
.vscode
storage/
+10 -3
View File
@@ -1,11 +1,18 @@
FROM node:20-slim
# Configurar Puppeteer para usar o Chromium do sistema
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
# Instalar dependências do sistema
RUN apt-get update && apt-get install -y \
chromium \
RUN apt-get update && apt-get install -y chromium \
libgconf-2-4 \
postgresql-client \
&& rm -rf /var/lib/apt/lists/*
&& rm -rf /var/lib/apt/lists/* \
&& ln -sf /usr/bin/chromium /usr/bin/chromium-browser
# Verificar a instalação do Chromium
RUN chromium --version
# Criar diretório da aplicação
WORKDIR /usr/src/app
+13
View File
@@ -0,0 +1,13 @@
version: '3.8'
services:
backend:
build: .
ports:
- "5000:5000"
environment:
- NODE_ENV=production
- CHROME_BIN=/usr/bin/google-chrome-stable
# ... outras variáveis de ambiente existentes ...
volumes:
- .:/usr/src/app
- /usr/src/app/node_modules
+228 -35
View File
@@ -36,6 +36,7 @@
"multer": "^1.4.5-lts.1",
"opentimestamps-javascript": "^1.0.1",
"pdf-lib": "^1.17.1",
"pdfkit": "^0.13.0",
"puppeteer": "^24.5.0",
"qrcode": "^1.5.3",
"react": "^18.2.0",
@@ -2101,6 +2102,15 @@
"win32"
]
},
"node_modules/@swc/helpers": {
"version": "0.3.17",
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.3.17.tgz",
"integrity": "sha512-tb7Iu+oZ+zWJZ3HJqwx8oNwSDIU440hmVMDPhpACWQWnrZHK99Bxs70gT1L2dnr5Hg50ZRWEFkQCAnOVVV0z1Q==",
"license": "MIT",
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@tailwindcss/node": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.1.1.tgz",
@@ -3592,7 +3602,6 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.2.tgz",
"integrity": "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.3",
@@ -3833,7 +3842,6 @@
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz",
"integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"possible-typed-array-names": "^1.0.0"
@@ -4195,6 +4203,15 @@
"integrity": "sha512-cKV8tMCEpQs4hK/ik71d6LrPOnpkpGBR0wzxqr68g2m/LB2GxVYQroAjMJZRVM1Y4BCjCKc3vAamxSzOY2RP+w==",
"license": "MIT"
},
"node_modules/brotli": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/brotli/-/brotli-1.3.3.tgz",
"integrity": "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.1.2"
}
},
"node_modules/browserslist": {
"version": "4.24.4",
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.24.4.tgz",
@@ -4390,7 +4407,6 @@
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.8.tgz",
"integrity": "sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.0",
@@ -4701,6 +4717,15 @@
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/clone": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",
"integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==",
"license": "MIT",
"engines": {
"node": ">=0.8"
}
},
"node_modules/clsx": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
@@ -4986,6 +5011,12 @@
"node": "*"
}
},
"node_modules/crypto-js": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz",
"integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==",
"license": "MIT"
},
"node_modules/css-box-model": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/css-box-model/-/css-box-model-1.2.1.tgz",
@@ -5131,6 +5162,38 @@
"node": ">=0.10.0"
}
},
"node_modules/deep-equal": {
"version": "2.2.3",
"resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-2.2.3.tgz",
"integrity": "sha512-ZIwpnevOurS8bpT4192sqAowWM76JDKSHYzMLty3BZGSswgq6pBaH3DhCSW5xVAZICZyKdOBPjwww5wfgT/6PA==",
"license": "MIT",
"dependencies": {
"array-buffer-byte-length": "^1.0.0",
"call-bind": "^1.0.5",
"es-get-iterator": "^1.1.3",
"get-intrinsic": "^1.2.2",
"is-arguments": "^1.1.1",
"is-array-buffer": "^3.0.2",
"is-date-object": "^1.0.5",
"is-regex": "^1.1.4",
"is-shared-array-buffer": "^1.0.2",
"isarray": "^2.0.5",
"object-is": "^1.1.5",
"object-keys": "^1.1.1",
"object.assign": "^4.1.4",
"regexp.prototype.flags": "^1.5.1",
"side-channel": "^1.0.4",
"which-boxed-primitive": "^1.0.2",
"which-collection": "^1.0.1",
"which-typed-array": "^1.1.13"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/deep-is": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
@@ -5142,7 +5205,6 @@
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz",
"integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==",
"dev": true,
"license": "MIT",
"dependencies": {
"es-define-property": "^1.0.0",
@@ -5160,7 +5222,6 @@
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz",
"integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==",
"dev": true,
"license": "MIT",
"dependencies": {
"define-data-property": "^1.0.1",
@@ -5271,6 +5332,12 @@
"integrity": "sha512-yRtvFD8Oyk7C9Os3GmnFZLu53yAfsnyw1s+mLmHHUK0GQEc9zthHWvS1r67Zqzm5t7v56PILHIVZ7kmFMaL2yQ==",
"license": "BSD-3-Clause"
},
"node_modules/dfa": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz",
"integrity": "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==",
"license": "MIT"
},
"node_modules/didyoumean": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz",
@@ -5566,6 +5633,26 @@
"node": ">= 0.4"
}
},
"node_modules/es-get-iterator": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/es-get-iterator/-/es-get-iterator-1.1.3.tgz",
"integrity": "sha512-sPZmqHBe6JIiTfN5q2pEi//TwxmAFHwj/XEuYjTuse78i8KxaqMTTzxPoFKuzRpDpTJ+0NAbpfenkmH2rePtuw==",
"license": "MIT",
"dependencies": {
"call-bind": "^1.0.2",
"get-intrinsic": "^1.1.3",
"has-symbols": "^1.0.3",
"is-arguments": "^1.1.1",
"is-map": "^2.0.2",
"is-set": "^2.0.2",
"is-string": "^1.0.7",
"isarray": "^2.0.5",
"stop-iteration-iterator": "^1.0.0"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/es-iterator-helpers": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/es-iterator-helpers/-/es-iterator-helpers-1.2.1.tgz",
@@ -6487,11 +6574,27 @@
}
}
},
"node_modules/fontkit": {
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/fontkit/-/fontkit-1.9.0.tgz",
"integrity": "sha512-HkW/8Lrk8jl18kzQHvAw9aTHe1cqsyx5sDnxncx652+CIfhawokEPkeM3BoIC+z/Xv7a0yMr0f3pRRwhGH455g==",
"license": "MIT",
"dependencies": {
"@swc/helpers": "^0.3.13",
"brotli": "^1.3.2",
"clone": "^2.1.2",
"deep-equal": "^2.0.5",
"dfa": "^1.2.0",
"restructure": "^2.0.1",
"tiny-inflate": "^1.0.3",
"unicode-properties": "^1.3.1",
"unicode-trie": "^2.0.0"
}
},
"node_modules/for-each": {
"version": "0.3.5",
"resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz",
"integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==",
"dev": true,
"license": "MIT",
"dependencies": {
"is-callable": "^1.2.7"
@@ -6658,7 +6761,6 @@
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz",
"integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
@@ -6929,7 +7031,6 @@
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz",
"integrity": "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
@@ -6952,7 +7053,6 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz",
"integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==",
"dev": true,
"license": "MIT",
"dependencies": {
"es-define-property": "^1.0.0"
@@ -7198,7 +7298,6 @@
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz",
"integrity": "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==",
"dev": true,
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
@@ -7255,11 +7354,26 @@
"node": ">= 0.10"
}
},
"node_modules/is-arguments": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.2.0.tgz",
"integrity": "sha512-7bVbi0huj/wrIAOzb8U1aszg9kdi3KN/CyU19CTI7tAoZYEZoL9yCDXpbXN+uPsuWnP02cyug1gleqq+TU+YCA==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"has-tostringtag": "^1.0.2"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/is-array-buffer": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz",
"integrity": "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bind": "^1.0.8",
@@ -7303,7 +7417,6 @@
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.1.0.tgz",
"integrity": "sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"has-bigints": "^1.0.2"
@@ -7332,7 +7445,6 @@
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.2.2.tgz",
"integrity": "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.3",
@@ -7355,7 +7467,6 @@
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz",
"integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
@@ -7401,7 +7512,6 @@
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.1.0.tgz",
"integrity": "sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
@@ -7485,7 +7595,6 @@
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz",
"integrity": "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
@@ -7508,7 +7617,6 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.1.1.tgz",
"integrity": "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.3",
@@ -7525,7 +7633,6 @@
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz",
"integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
@@ -7544,7 +7651,6 @@
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.3.tgz",
"integrity": "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
@@ -7557,7 +7663,6 @@
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.4.tgz",
"integrity": "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.3"
@@ -7573,7 +7678,6 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz",
"integrity": "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.3",
@@ -7590,7 +7694,6 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.1.1.tgz",
"integrity": "sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
@@ -7630,7 +7733,6 @@
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.2.tgz",
"integrity": "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
@@ -7659,7 +7761,6 @@
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.4.tgz",
"integrity": "sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.3",
@@ -7676,7 +7777,6 @@
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz",
"integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==",
"dev": true,
"license": "MIT"
},
"node_modules/isexe": {
@@ -8209,6 +8309,25 @@
"node": ">=10"
}
},
"node_modules/linebreak": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz",
"integrity": "sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==",
"license": "MIT",
"dependencies": {
"base64-js": "0.0.8",
"unicode-trie": "^2.0.0"
}
},
"node_modules/linebreak/node_modules/base64-js": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.8.tgz",
"integrity": "sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/lines-and-columns": {
"version": "1.2.4",
"resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz",
@@ -8845,11 +8964,26 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/object-is": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.6.tgz",
"integrity": "sha512-F8cZ+KfGlSGi09lJT7/Nd6KJZ9ygtvYC0/UYYLI9nmQKLMnydpB9yvbv9K1uSkEu7FU9vYPmVwLg328tX+ot3Q==",
"license": "MIT",
"dependencies": {
"call-bind": "^1.0.7",
"define-properties": "^1.2.1"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/object-keys": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",
"integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
@@ -8859,7 +8993,6 @@
"version": "4.1.7",
"resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.7.tgz",
"integrity": "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bind": "^1.0.8",
@@ -9271,6 +9404,18 @@
"integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==",
"license": "0BSD"
},
"node_modules/pdfkit": {
"version": "0.13.0",
"resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.13.0.tgz",
"integrity": "sha512-AW79eHU5eLd2vgRDS9z3bSoi0FA+gYm+100LLosrQQMLUzOBGVOhG7ABcMFpJu7Bpg+MT74XYHi4k9EuU/9EZw==",
"license": "MIT",
"dependencies": {
"crypto-js": "^4.0.0",
"fontkit": "^1.8.1",
"linebreak": "^1.0.2",
"png-js": "^1.0.0"
}
},
"node_modules/pend": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz",
@@ -9322,6 +9467,11 @@
"node": ">= 6"
}
},
"node_modules/png-js": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/png-js/-/png-js-1.0.0.tgz",
"integrity": "sha512-k+YsbhpA9e+EFfKjTCH3VW6aoKlyNYI6NYdTfDL4CIvFnvsuO84ttonmZE7rc+v23SLTH8XX+5w/Ak9v0xGY4g=="
},
"node_modules/pngjs": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
@@ -9335,7 +9485,6 @@
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
"integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
@@ -10617,7 +10766,6 @@
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz",
"integrity": "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bind": "^1.0.8",
@@ -10789,6 +10937,12 @@
"node": ">=4"
}
},
"node_modules/restructure": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/restructure/-/restructure-2.0.1.tgz",
"integrity": "sha512-e0dOpjm5DseomnXx2M5lpdZ5zoHqF1+bqdMJUohoYVVQa7cBdnk7fdmeI6byNWP/kiME72EeTiSypTCVnpLiDg==",
"license": "MIT"
},
"node_modules/reusify": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
@@ -10957,7 +11111,6 @@
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.1.0.tgz",
"integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==",
"dev": true,
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
@@ -11075,7 +11228,6 @@
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz",
"integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==",
"dev": true,
"license": "MIT",
"dependencies": {
"define-data-property": "^1.1.4",
@@ -11093,7 +11245,6 @@
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz",
"integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"define-data-property": "^1.1.4",
@@ -11443,6 +11594,19 @@
"node": ">=0.10.0"
}
},
"node_modules/stop-iteration-iterator": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz",
"integrity": "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"internal-slot": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/streamsearch": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
@@ -11916,6 +12080,12 @@
"node": ">=0.8"
}
},
"node_modules/tiny-inflate": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz",
"integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==",
"license": "MIT"
},
"node_modules/tiny-invariant": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
@@ -12273,6 +12443,32 @@
"devOptional": true,
"license": "MIT"
},
"node_modules/unicode-properties": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz",
"integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.3.0",
"unicode-trie": "^2.0.0"
}
},
"node_modules/unicode-trie": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz",
"integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==",
"license": "MIT",
"dependencies": {
"pako": "^0.2.5",
"tiny-inflate": "^1.0.0"
}
},
"node_modules/unicode-trie/node_modules/pako": {
"version": "0.2.9",
"resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz",
"integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==",
"license": "MIT"
},
"node_modules/unload": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/unload/-/unload-2.2.0.tgz",
@@ -12606,7 +12802,6 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz",
"integrity": "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==",
"dev": true,
"license": "MIT",
"dependencies": {
"is-bigint": "^1.1.0",
@@ -12654,7 +12849,6 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.2.tgz",
"integrity": "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==",
"dev": true,
"license": "MIT",
"dependencies": {
"is-map": "^2.0.3",
@@ -12679,7 +12873,6 @@
"version": "1.1.19",
"resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.19.tgz",
"integrity": "sha512-rEvr90Bck4WZt9HHFC4DJMsjvu7x+r6bImz0/BrbWb7A2djJ8hnZMrWnHo9F8ssv0OMErasDhftrfROTyqSDrw==",
"dev": true,
"license": "MIT",
"dependencies": {
"available-typed-arrays": "^1.0.7",
+1 -6
View File
@@ -49,6 +49,7 @@
"multer": "^1.4.5-lts.1",
"opentimestamps-javascript": "^1.0.1",
"pdf-lib": "^1.17.1",
"pdfkit": "^0.13.0",
"puppeteer": "^24.5.0",
"qrcode": "^1.5.3",
"react": "^18.2.0",
@@ -111,11 +112,5 @@
"--disable-gpu",
"--window-size=1920x1080"
]
},
"puppeteerOptions": {
"browserFetcher": {
"platform": "win32",
"downloadPath": ".cache/puppeteer"
}
}
}
+9
View File
@@ -0,0 +1,9 @@
-- Identificar registros com UUID inválido
SELECT id, uuid_column
FROM atendimento
WHERE uuid_column !~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$';
-- Atualizar registros com UUID inválido
UPDATE atendimento
SET uuid_column = gen_random_uuid()
WHERE uuid_column !~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$';
+1
View File
@@ -79,6 +79,7 @@ const router = createBrowserRouter(
<Route path="/atendimentos" element={<AtendimentosPage />} />
<Route path="/atendimentos/:id" element={<AtendimentoDetalhes />} />
<Route path="/tarefas" element={<TarefasPage />} />
<Route path="/usuarios" element={<UsuariosPage />} />
<Route path="/processos-administrativos" element={<ProtectedRoute roles={['ADVOGADO_ADMIN', 'ADVOGADO', 'ASSISTENTE']}><ProcessoAdministrativoList /></ProtectedRoute>} />
<Route path="/processos-administrativos/:id" element={<ProtectedRoute roles={['ADVOGADO_ADMIN', 'ADVOGADO', 'ASSISTENTE']}><ProcessoAdminDetalhes /></ProtectedRoute>} />
<Route path="/provas/upload" element={<ProvaUpload />} />
+19 -11
View File
@@ -200,7 +200,7 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
// Monitorar o valor do CEP para autopreenchimento
const cepValue = watch("cep");
// Função para buscar dados do CEP - versão com gerenciamento de estados do componente
// Função para buscar dados do CEP - versão corrigida
const fetchAddressByCep = useCallback(async (cep: string) => {
if (!cep || cep.length !== 8) return;
@@ -213,7 +213,6 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
if (response.data && !response.data.erro) {
// Usar estado local para garantir re-renderização imediata
// Forçar preenchimento dos campos e atualização da interface
const endereco = response.data.logradouro || "";
const bairro = response.data.bairro || "";
const cidade = response.data.localidade || "";
@@ -225,8 +224,7 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
setValue("cidade", cidade, { shouldValidate: true });
setValue("estado", estado, { shouldValidate: true });
// Garantir re-renderização do componente
// Esta é a parte crucial: forçar o componente a re-renderizar com novo estado
// Atualizar o estado para re-renderização do componente
setEnderecoState({
endereco,
bairro,
@@ -235,13 +233,23 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
preenchido: true,
});
// Focar no próximo campo
setTimeout(() => {
const numeroInput = document.querySelector(
'input[name="numero"]'
) as HTMLInputElement;
if (numeroInput) numeroInput.focus();
}, 100);
// Focar no próximo campo apenas se o usuário não estiver digitando ativamente
// Esta alteração evita interromper o fluxo natural de preenchimento
const activeElement = document.activeElement;
const isUserTyping =
activeElement &&
(activeElement.tagName === 'INPUT' || activeElement.tagName === 'SELECT') &&
activeElement !== document.querySelector('input[name="cep"]');
// Só focar no campo número se o usuário não estiver digitando em outro campo
if (!isUserTyping) {
setTimeout(() => {
const numeroInput = document.querySelector(
'input[name="numero"]'
) as HTMLInputElement;
if (numeroInput) numeroInput.focus();
}, 100);
}
} else {
console.error("CEP não encontrado");
alert("CEP não encontrado. Por favor, verifique o CEP informado.");
+10 -2
View File
@@ -17,6 +17,7 @@ import {
ShieldCheckIcon,
CurrencyDollarIcon,
CalculatorIcon,
BriefcaseIcon,
} from "@heroicons/react/24/outline";
import { Menu, Transition } from "@headlessui/react";
import api from "../../services/api";
@@ -58,8 +59,15 @@ export const MainLayout: React.FC = () => {
const menuItems = [
{ path: "/dashboard", label: "Dashboard", icon: HomeIcon },
{ path: "/processos", label: "Processos", icon: ScaleIcon },
{ path: "/processos-administrativos", label: "Proc.Adm", icon: ScaleIcon },
{
path: null,
label: "Processos",
icon: ScaleIcon,
subitems: [
{ path: "/processos", label: "Judiciais", icon: ScaleIcon },
{ path: "/processos-administrativos", label: "Proc. Admin.", icon: DocumentCheckIcon }
]
},
{
path: null,
label: "Provas",
+26 -2
View File
@@ -21,6 +21,13 @@ interface ProvaStatus {
};
ipAddress?: string;
clientPort?: string;
locationInfo?: {
latitude?: number;
longitude?: number;
};
latitude?: number;
longitude?: number;
location_permission?: string;
};
}
@@ -212,11 +219,28 @@ export function PublicProvaStatus() {
</div>
{/* Adicionar geolocalização se disponível */}
{(status.metadata?.latitude !== undefined || status.metadata?.longitude !== undefined) && (
{(
(status.metadata?.latitude !== undefined && status.metadata?.latitude !== null) ||
(status.metadata?.longitude !== undefined && status.metadata?.longitude !== null) ||
(status.metadata?.locationInfo?.latitude !== undefined && status.metadata?.locationInfo?.latitude !== null) ||
(status.metadata?.locationInfo?.longitude !== undefined && status.metadata?.locationInfo?.longitude !== null)
) && (
<div>
<p className="text-sm text-gray-500">Geolocalização</p>
<p className="text-gray-700">
Coordenadas: {status.metadata.latitude || 'N/A'}, {status.metadata.longitude || 'N/A'}
Coordenadas: {
status.metadata?.latitude !== undefined && status.metadata?.latitude !== null
? status.metadata.latitude
: status.metadata?.locationInfo?.latitude !== undefined && status.metadata?.locationInfo?.latitude !== null
? status.metadata.locationInfo.latitude
: 'N/A'
}, {
status.metadata?.longitude !== undefined && status.metadata?.longitude !== null
? status.metadata.longitude
: status.metadata?.locationInfo?.longitude !== undefined && status.metadata?.locationInfo?.longitude !== null
? status.metadata.locationInfo.longitude
: 'N/A'
}
</p>
<p className="text-xs text-gray-500">
Permissão: {status.metadata.location_permission || 'não especificada'}
+31 -27
View File
@@ -161,26 +161,6 @@ export function PublicVerificarProva() {
result.prova.dataCriacao)}
/>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<dt className="text-sm font-medium text-gray-500">IP:</dt>
<dd className="mt-1 text-base text-gray-900 break-words">
{result.verificacao?.ip ||
result.prova.metadata?.connectionInfo?.forwardedIp ||
(result.prova.metadata?.headers?.['x-forwarded-for'] ?
result.prova.metadata.headers['x-forwarded-for'].split(',')[0].trim() :
result.prova.metadata?.ipAddress) ||
'Não disponível'}
</dd>
</div>
<div>
<dt className="text-sm font-medium text-gray-500">Porta:</dt>
<dd className="mt-1 text-base text-gray-900 break-words">
{result.verificacao?.porta ||
result.prova.metadata?.clientPort ||
result.prova.metadata?.connectionInfo?.socketPort ||
'Não disponível'}
</dd>
</div>
</div>
</div>
</div>
@@ -231,14 +211,21 @@ export function PublicVerificarProva() {
}
/>
{/* Garantir exibição da porta */}
{/* Garantir exibição da porta capturada no JSON da prova */}
<DetailItem
label="Porta de Conexão"
value={
result.prova.metadata.clientPort ||
(result.prova.metadata.connectionInfo?.socketPort ?
result.prova.metadata.connectionInfo.socketPort : '61465')
}
result.prova.metadata.connectionInfo?.socketPort ||
(result.prova.metadata.userInfo?.ipAddress &&
(() => {
const ip = result.prova.metadata.userInfo.ipAddress;
const match = typeof ip === 'string' ? ip.match(/:(\d+)$/) : null;
return match ? match[1] : undefined;
})()
) ||
'Não disponível'
}
/>
{/* Adicionar família IP */}
@@ -278,11 +265,28 @@ export function PublicVerificarProva() {
/>
)}
{/* Exibir geolocalização se disponível */}
{(result.prova.metadata.latitude !== undefined || result.prova.metadata.longitude !== undefined) && (
{/* Exibir geolocalização capturada na prova */}
{(
(result.prova.metadata?.latitude !== undefined && result.prova.metadata?.latitude !== null) ||
(result.prova.metadata?.longitude !== undefined && result.prova.metadata?.longitude !== null) ||
(result.prova.metadata?.locationInfo?.latitude !== undefined && result.prova.metadata?.locationInfo?.latitude !== null) ||
(result.prova.metadata?.locationInfo?.longitude !== undefined && result.prova.metadata?.locationInfo?.longitude !== null)
) && (
<DetailItem
label="Coordenadas"
value={`${result.prova.metadata.latitude || 'N/A'}, ${result.prova.metadata.longitude || 'N/A'}`}
value={`${
result.prova.metadata?.latitude !== undefined && result.prova.metadata?.latitude !== null
? result.prova.metadata.latitude
: result.prova.metadata?.locationInfo?.latitude !== undefined && result.prova.metadata?.locationInfo?.latitude !== null
? result.prova.metadata.locationInfo.latitude
: 'N/A'
}, ${
result.prova.metadata?.longitude !== undefined && result.prova.metadata?.longitude !== null
? result.prova.metadata.longitude
: result.prova.metadata?.locationInfo?.longitude !== undefined && result.prova.metadata?.locationInfo?.longitude !== null
? result.prova.metadata.locationInfo.longitude
: 'N/A'
}`}
/>
)}
+4 -1
View File
@@ -220,7 +220,10 @@ export const VerificarProva: React.FC = () => {
Porta:
</Typography>
<Typography gutterBottom>
{prova.verificacao?.porta || prova.prova?.metadata?.clientPort || 'Não disponível'}
{prova.prova?.metadata?.clientPort ||
prova.prova?.metadata?.connectionInfo?.socketPort ||
prova.prova?.metadata?.userInfo?.ipAddress?.split(':')[1] ||
'Não disponível'}
</Typography>
</Grid>
</Grid>
+77 -2
View File
@@ -55,6 +55,13 @@ const orgaoJulgadorRepository = new OrgaoJulgadorRepository();
const custaProcessualRepository = new CustaProcessualRepository();
const honorarioRepository = new HonorarioRepository();
// Atualizar a função isValidUUID para ser mais robusta
const isValidUUID = (uuid: string | null | undefined): boolean => {
if (!uuid) return false;
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
return uuidRegex.test(uuid);
};
// Middleware para extrair usuário do token
// Remover este middleware pois já temos o auth.ts
// const extractUser = (req: any, res: any, next: any) => { ... }
@@ -1000,9 +1007,9 @@ app.post("/api/atendimentos", authMiddleware, async (req, res) => {
conteudo,
cliente: { connect: { id: clienteId } },
usuario: { connect: { id: req.user!.id } },
...(processoId && { processo: { connect: { id: processoId } } }),
...(processoId && { processo: { connect: { id: processoId } } }), // Adicionar vírgula aqui
status: 'ATIVO',
dataAtualizacao: new Date(),
dataAtualizacao: new Date()
},
include: {
cliente: true,
@@ -1337,6 +1344,74 @@ app.delete("/api/agendamentos/:id", authMiddleware, async (req, res) => {
}
});
// Atualizar a rota de agendamentos
app.get("/api/atendimentos/agendamentos", async (req, res) => {
try {
const { data } = req.query;
if (!data || typeof data !== 'string') {
return res.status(400).json({ error: 'Data inválida' });
}
const dataConsulta = new Date(data);
// Validar se a data é válida
if (isNaN(dataConsulta.getTime())) {
return res.status(400).json({ error: 'Formato de data inválido' });
}
// Definir início e fim do dia
const inicioDia = new Date(dataConsulta.setHours(0, 0, 0, 0));
const fimDia = new Date(dataConsulta.setHours(23, 59, 59, 999));
// Buscar na tabela correta com filtros apropriados
const agendamentos = await prisma.agendamentoAtendimento.findMany({
where: {
data: {
gte: inicioDia,
lte: fimDia
}
},
include: {
cliente: {
select: {
id: true,
nome: true,
cpfCnpj: true,
telefone: true
}
},
usuario: {
select: {
id: true,
nome: true
}
}
},
orderBy: {
data: 'asc'
}
});
// Filtrar apenas agendamentos com UUIDs válidos
const validAgendamentos = agendamentos.filter(agendamento =>
isValidUUID(agendamento.id) &&
isValidUUID(agendamento.clienteId) &&
isValidUUID(agendamento.usuarioId)
);
console.log(`Encontrados ${validAgendamentos.length} agendamentos válidos para ${data}`);
res.json(validAgendamentos);
} catch (error) {
console.error('Erro ao buscar agendamentos:', error);
res.status(500).json({
error: 'Erro ao buscar agendamentos',
details: error instanceof Error ? error.message : 'Erro desconhecido'
});
}
});
// Erro handling middleware
app.use(
(
+18 -3
View File
@@ -28,6 +28,17 @@ router.post('/upload', upload.array('files'), async (req, res) => {
} : null;
// Metadata avançada seguindo RFC 3227
// Corrigir: priorizar latitude/longitude do frontend se vierem preenchidas
let latitude: number | undefined = undefined;
let longitude: number | undefined = undefined;
if (
typeof req.body.latitude !== 'undefined' && req.body.latitude !== null && req.body.latitude !== '' &&
typeof req.body.longitude !== 'undefined' && req.body.longitude !== null && req.body.longitude !== ''
) {
latitude = Number(req.body.latitude);
longitude = Number(req.body.longitude);
}
const metadata = {
userAgent: req.body.user_agent,
language: req.body.language,
@@ -40,7 +51,11 @@ router.post('/upload', upload.array('files'), async (req, res) => {
forwardedIp: forwarded,
socketAddress: socketInfo?.address,
socketPort: socketInfo?.port,
remoteFamily: req.socket.remoteFamily
// Corrigir: determinar família do IP real
remoteFamily: (() => {
const ip = (req.ip || req.socket.remoteAddress || '').toString();
return ip.includes(':') ? 'IPv6' : 'IPv4';
})()
},
timestamp: new Date(),
modification_times: req.body.modification_times,
@@ -50,8 +65,8 @@ router.post('/upload', upload.array('files'), async (req, res) => {
platform: req.body.platform,
cookies_enabled: req.body.cookies_enabled,
browser_plugins: req.body.browser_plugins,
latitude: req.body.latitude,
longitude: req.body.longitude,
latitude, // sempre priorizar o valor do frontend
longitude,
location_permission: req.body.location_permission,
client_timestamp: req.body.client_timestamp,
headers: {
+634
View File
@@ -0,0 +1,634 @@
import puppeteer from 'puppeteer';
import { prisma } from '../prismaClient';
import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
import fs from 'fs/promises';
import path from 'path';
/**
* Serviço para geração e manipulação de arquivos PDF
*/
export class PdfService {
/**
* Cria um documento PDF básico
* @returns Documento PDF
*/
async criarDocumento() {
return await PDFDocument.create();
}
/**
* Carrega um documento PDF existente
* @param pdfBytes - Bytes do PDF
* @returns Documento PDF
*/
async carregarDocumento(pdfBytes: Uint8Array) {
return await PDFDocument.load(pdfBytes);
}
/**
* Adiciona uma página ao documento
* @param doc - Documento PDF
* @param tamanho - Tamanho da página (padrão: A4)
* @returns Página adicionada
*/
adicionarPagina(doc: any, tamanho = [595.28, 841.89]) {
return doc.addPage(tamanho);
}
/**
* Salva o documento como buffer
* @param doc - Documento PDF
* @returns Buffer do PDF
*/
async salvarComoBuffer(doc: any): Promise<Buffer> {
const pdfBytes = await doc.save();
return Buffer.from(pdfBytes);
}
/**
* Carrega uma fonte padrão
* @param doc - Documento PDF
* @param fonte - Nome da fonte padrão
* @returns Fonte carregada
*/
async carregarFonte(doc: any, fonte: StandardFonts) {
return await doc.embedFont(fonte);
}
/**
* Desenha texto em uma página
* @param pagina - Página do PDF
* @param texto - Texto a ser desenhado
* @param x - Posição X
* @param y - Posição Y
* @param fonte - Fonte a ser usada
* @param tamanho - Tamanho da fonte
* @param cor - Cor do texto (padrão: preto)
*/
desenharTexto(
pagina: any,
texto: string,
x: number,
y: number,
fonte: any,
tamanho: number,
cor = rgb(0, 0, 0)
) {
pagina.drawText(texto, {
x,
y,
font: fonte,
size: tamanho,
color: cor,
});
}
/**
* Cria um cabeçalho para o documento
* @param pagina - Página do PDF
* @param titulo - Título do cabeçalho
* @param fonte - Fonte a ser usada
* @param margemSuperior - Margem superior
* @param margem - Margem lateral
* @returns Posição Y após o cabeçalho
*/
criarCabecalho(
pagina: any,
titulo: string,
fonte: any,
margemSuperior: number,
margem: number
): number {
const yPos = pagina.getHeight() - margemSuperior;
this.desenharTexto(
pagina,
titulo,
margem,
yPos,
fonte,
18,
rgb(0, 0, 0.7)
);
// Linha separadora
pagina.drawLine({
start: { x: margem, y: yPos - 10 },
end: { x: pagina.getWidth() - margem, y: yPos - 10 },
thickness: 1,
color: rgb(0, 0, 0.5),
});
return yPos - 30; // Retorna a posição Y após o cabeçalho
}
/**
* Cria um rodapé para o documento
* @param pagina - Página do PDF
* @param texto - Texto do rodapé
* @param fonte - Fonte a ser usada
* @param margem - Margem
*/
criarRodape(pagina: any, texto: string, fonte: any, margem: number) {
const yPos = margem / 2;
this.desenharTexto(
pagina,
texto,
margem,
yPos,
fonte,
8,
rgb(0.5, 0.5, 0.5)
);
}
private async getConfiguracao() {
try {
// Buscar configuração ou usar valores padrão
const config = await prisma.configuracaoDocumento.findFirst({
orderBy: { criadoEm: 'desc' },
select: {
id: true,
timbradoUrl: true,
timbradoMarginTop: true,
timbradoMarginBottom: true,
timbradoMarginLeft: true,
timbradoMarginRight: true,
templatePadrao: true,
margensTemplate: true,
criadoEm: true
}
});
console.log('Configuração encontrada:', config); // Debug
// Retornar configuração padrão se não existir
return {
// Valores padrão
cabecalhoHtml: `
<div style="text-align: center; padding: 20px;">
<h2 style="margin:0;font-size:14pt">{{escritorio.nome}}</h2>
</div>
`,
rodapeHtml: `
<div style="text-align: center; font-size: 10pt;">
{{escritorio.endereco}}<br>
Tel: {{escritorio.telefone}} | Email: {{escritorio.email}}
</div>
`,
// Campos que existem no modelo
timbradoUrl: config?.timbradoUrl || '',
timbradoMarginTop: config?.timbradoMarginTop || 100,
timbradoMarginBottom: config?.timbradoMarginBottom || 50,
timbradoMarginLeft: config?.timbradoMarginLeft || 50,
timbradoMarginRight: config?.timbradoMarginRight || 50,
templatePadrao: config?.templatePadrao || null,
margensTemplate: config?.margensTemplate || null
};
} catch (error) {
console.error('Erro ao buscar configuração:', error);
// Retornar configuração padrão para não interromper o fluxo
return {
cabecalhoHtml: `<div style="text-align: center; padding: 20px;"><h2 style="margin:0;font-size:14pt">Documento</h2></div>`,
rodapeHtml: `<div style="text-align: center; font-size: 10pt;">Documento gerado pelo sistema</div>`,
timbradoUrl: '',
timbradoMarginTop: 100,
timbradoMarginBottom: 50,
timbradoMarginLeft: 50,
timbradoMarginRight: 50,
templatePadrao: null,
margensTemplate: null
};
}
}
/**
* Gera um PDF a partir do conteúdo HTML simples (apenas texto) e dados do escritório,
* encaixando o texto sobre o timbrado (PDF de fundo) em todas as páginas.
* Não usa Puppeteer, apenas PDF-LIB.
*/
async gerarPDF(conteudo: string, escritorio: any = {}): Promise<Buffer> {
try {
console.log('Buscando configurações do documento...');
const config = await this.getConfiguracao();
// Verificar se temos um timbrado para usar
const temTimbrado = !!config.timbradoUrl;
let timbradoPath = '';
let timbradoExists = false;
if (temTimbrado) {
if (config.timbradoUrl.startsWith('/uploads')) {
timbradoPath = path.join(process.cwd(), 'public', config.timbradoUrl);
} else {
timbradoPath = path.join(process.cwd(), 'public', 'uploads', path.basename(config.timbradoUrl));
}
try {
await fs.access(timbradoPath);
timbradoExists = true;
} catch (e) {
timbradoExists = false;
}
}
// Margens
const margens = config.margensTemplate || {
top: config.timbradoMarginTop || 100,
left: config.timbradoMarginLeft || 50,
right: config.timbradoMarginRight || 50,
bottom: config.timbradoMarginBottom || 50
};
// Parâmetros de página
const PAGE_WIDTH = 595.28; // A4
const PAGE_HEIGHT = 841.89; // A4
const FONT_SIZE = 12;
const LINE_HEIGHT = FONT_SIZE * 1.5;
const MAX_WIDTH = PAGE_WIDTH - margens.left - margens.right;
// Crie o PDFDocument ANTES de tentar usar pdfDoc para embedFont!
let pdfDoc: PDFDocument = await PDFDocument.create();
// Fonte padrão do pdf-lib: TimesRoman, TimesBold, TimesItalic
const font = await pdfDoc.embedFont('Times-Roman');
const fontBold = await pdfDoc.embedFont('Times-Bold');
const fontItalic = await pdfDoc.embedFont('Times-Italic');
const fontBoldItalic = fontBold;
// Função para decodificar entidades HTML comuns (acentuação, símbolos, º, etc)
function decodeHtmlEntities(str: string): string {
if (!str) return '';
return str
// Acentos minúsculos e maiúsculos
.replace(/&Aacute;/g, 'Á').replace(/&aacute;/g, 'á')
.replace(/&Eacute;/g, 'É').replace(/&eacute;/g, 'é')
.replace(/&Iacute;/g, 'Í').replace(/&iacute;/g, 'í')
.replace(/&Oacute;/g, 'Ó').replace(/&oacute;/g, 'ó')
.replace(/&Uacute;/g, 'Ú').replace(/&uacute;/g, 'ú')
.replace(/&Agrave;/g, 'À').replace(/&agrave;/g, 'à')
.replace(/&Egrave;/g, 'È').replace(/&egrave;/g, 'è')
.replace(/&Igrave;/g, 'Ì').replace(/&igrave;/g, 'ì')
.replace(/&Ograve;/g, 'Ò').replace(/&ograve;/g, 'ò')
.replace(/&Ugrave;/g, 'Ù').replace(/&ugrave;/g, 'ù')
.replace(/&Acirc;/g, 'Â').replace(/&acirc;/g, 'â')
.replace(/&Ecirc;/g, 'Ê').replace(/&ecirc;/g, 'ê')
.replace(/&Icirc;/g, 'Î').replace(/&icirc;/g, 'î')
.replace(/&Ocirc;/g, 'Ô').replace(/&ocirc;/g, 'ô')
.replace(/&Ucirc;/g, 'Û').replace(/&ucirc;/g, 'û')
.replace(/&Atilde;/g, 'Ã').replace(/&atilde;/g, 'ã')
.replace(/&Otilde;/g, 'Õ').replace(/&otilde;/g, 'õ')
.replace(/&Ccedil;/g, 'Ç').replace(/&ccedil;/g, 'ç')
.replace(/&Ntilde;/g, 'Ñ').replace(/&ntilde;/g, 'ñ')
.replace(/&Uuml;/g, 'Ü').replace(/&uuml;/g, 'ü')
// Símbolos comuns
.replace(/&ordm;/gi, 'º')
.replace(/&ordf;/gi, 'ª')
.replace(/&sect;/gi, '§')
.replace(/&deg;/gi, '°')
.replace(/&copy;/gi, '©')
.replace(/&reg;/gi, '®')
.replace(/&para;/gi, '¶')
.replace(/&bull;/gi, '•')
.replace(/&ndash;/gi, '–')
.replace(/&mdash;/gi, '—')
.replace(/&laquo;/gi, '«')
.replace(/&raquo;/gi, '»')
.replace(/&lsquo;/gi, '‘')
.replace(/&rsquo;/gi, '’')
.replace(/&ldquo;/gi, '“')
.replace(/&rdquo;/gi, '”')
.replace(/&euro;/gi, '€')
.replace(/&yen;/gi, '¥')
.replace(/&pound;/gi, '£')
.replace(/&cent;/gi, '¢')
.replace(/&nbsp;/gi, ' ')
.replace(/&amp;/gi, '&')
.replace(/&quot;/gi, '"')
.replace(/&#39;/g, "'")
.replace(/&lt;/gi, '<')
.replace(/&gt;/gi, '>')
// Numéricos
.replace(/&#(\d+);/g, (m, code) => String.fromCharCode(code));
}
// Função para remover todas as tags HTML, exceto as de formatação suportadas
function stripUnsupportedTags(html: string): string {
// Remove todas as tags, exceto <b>, <strong>, <i>, <em>, <u>, <br>, <p>, <span style="text-indent:2em;">, <span style="text-align:center;">
// Remove atributos de <span> exceto text-indent e text-align
return html
// Mantém apenas <span> com text-indent ou text-align:center
.replace(/<span\b(?:(?!text-indent|text-align)[^>])*?>/gi, '')
// Remove atributos de <b>, <strong>, <i>, <em>, <u>, <p>
.replace(/<(b|strong|i|em|u|p)[^>]*>/gi, '<$1>')
// Remove todas as outras tags e atributos
.replace(/<(?!\/?(b|strong|i|em|u|br|p|span)[ >])[^>]+>/gi, '')
// Remove spans sem text-indent ou text-align
.replace(/<span>(.*?)<\/span>/gi, '$1')
// Remove comentários HTML
.replace(/<!--[\s\S]*?-->/g, '');
}
// Função para renderizar texto com formatação inline (negrito, itálico, sublinhado) e controle de quebra de linha e recuo
function renderInlineFormattedParagraph(
page,
text: string,
x: number,
y: number,
font,
fontBold,
fontItalic,
fontBoldItalic,
fontSize: number,
color,
align: string,
maxWidth: number,
indent: boolean,
topMargin: number,
bottomMargin: number,
pageHeight: number
) {
let regex = /(<\/?(b|strong|i|em|u)>)/gi;
let tokens: { text: string, bold: boolean, italic: boolean, underline: boolean }[] = [];
let lastIndex = 0;
let match;
let currentStyle = { bold: false, italic: false, underline: false };
while ((match = regex.exec(text)) !== null) {
if (match.index > lastIndex) {
tokens.push({
text: text.substring(lastIndex, match.index),
bold: currentStyle.bold,
italic: currentStyle.italic,
underline: currentStyle.underline
});
}
if (/^<(b|strong)>$/i.test(match[0])) currentStyle.bold = true;
if (/^<\/(b|strong)>$/i.test(match[0])) currentStyle.bold = false;
if (/^<(i|em)>$/i.test(match[0])) currentStyle.italic = true;
if (/^<\/(i|em)>$/i.test(match[0])) currentStyle.italic = false;
if (/^<u>$/i.test(match[0])) currentStyle.underline = true;
if (/^<\/u>$/i.test(match[0])) currentStyle.underline = false;
lastIndex = regex.lastIndex;
}
if (lastIndex < text.length) {
tokens.push({
text: text.substring(lastIndex),
bold: currentStyle.bold,
italic: currentStyle.italic,
underline: currentStyle.underline
});
}
let words: { text: string, font: any, underline: boolean, bold: boolean, italic: boolean }[] = [];
for (const token of tokens) {
let usedFont = font;
if (token.bold && token.italic) usedFont = fontBoldItalic;
else if (token.bold) usedFont = fontBold;
else if (token.italic) usedFont = fontItalic;
// Corrige: split por espaço, mas preserva espaços como tokens separados
const split = token.text.split(/(\s+)/);
for (const part of split) {
words.push({ text: part, font: usedFont, underline: token.underline, bold: token.bold, italic: token.italic });
}
}
let lines: { tokens: { text: string, font: any, underline: boolean, bold: boolean, italic: boolean }[] }[] = [];
let currentTokens: { text: string, font: any, underline: boolean, bold: boolean, italic: boolean }[] = [];
let currentWidth = 0;
for (const [i, word] of words.entries()) {
const wordWidth = word.font.widthOfTextAtSize(word.text, fontSize);
if (currentWidth + wordWidth > maxWidth && currentTokens.length > 0) {
lines.push({ tokens: currentTokens });
currentTokens = [word];
currentWidth = wordWidth;
} else {
currentTokens.push(word);
currentWidth += wordWidth;
}
}
if (currentTokens.length > 0) {
lines.push({ tokens: currentTokens });
}
// Ajuste: Força alinhamento consistente para todas as linhas do parágrafo
// Se align === 'center', todas as linhas centralizadas
// Se align === 'justify', todas as linhas justificadas (exceto a última ou linhas curtas)
// Se align === 'left' ou outro, todas à esquerda
for (let i = 0; i < lines.length; i++) {
if (y < bottomMargin + fontSize * 1.5) {
return null;
}
let line = lines[i];
let drawX = x;
// Remove espaços no início e fim da linha para não justificar esses espaços
let trimmedTokens = [...line.tokens];
while (trimmedTokens.length && /^\s+$/.test(trimmedTokens[0].text)) trimmedTokens.shift();
while (trimmedTokens.length && /^\s+$/.test(trimmedTokens[trimmedTokens.length - 1].text)) trimmedTokens.pop();
let totalWidth = trimmedTokens.reduce((acc, t) => acc + t.font.widthOfTextAtSize(t.text, fontSize), 0);
// Corrige centralização: centraliza a linha inteira, inclusive se for a única linha do parágrafo
if (align === 'center') {
drawX = x + (maxWidth - totalWidth) / 2;
for (const t of trimmedTokens) {
page.drawText(t.text, {
x: drawX,
y,
size: fontSize,
font: t.font,
color
});
if (t.underline && t.text.trim() !== '') {
const underlineY = y - 1.5;
page.drawLine({
start: { x: drawX, y: underlineY },
end: { x: drawX + t.font.widthOfTextAtSize(t.text, fontSize), y: underlineY },
thickness: 0.75,
color
});
}
drawX += t.font.widthOfTextAtSize(t.text, fontSize);
}
} else if (align === 'justify' && i < lines.length - 1 && trimmedTokens.length > 2) {
// Justify: distribui espaço entre palavras, exceto na última linha ou linhas curtas
const spaces = trimmedTokens.filter(t => /^\s+$/.test(t.text));
const numSpaces = spaces.length;
const lineTextWidth = trimmedTokens.reduce((acc, t) => acc + t.font.widthOfTextAtSize(t.text, fontSize), 0);
const extraSpace = maxWidth - lineTextWidth;
let spaceWidth = 0;
// Só justifica se houver pelo menos 2 espaços e a linha não for muito curta
if (numSpaces > 0 && extraSpace > 0) {
spaceWidth = extraSpace / numSpaces;
}
let localDrawX = x;
for (const t of trimmedTokens) {
page.drawText(t.text, {
x: localDrawX,
y,
size: fontSize,
font: t.font,
color
});
if (t.underline && t.text.trim() !== '') {
const underlineY = y - 1.5;
page.drawLine({
start: { x: localDrawX, y: underlineY },
end: { x: localDrawX + t.font.widthOfTextAtSize(t.text, fontSize), y: underlineY },
thickness: 0.75,
color
});
}
if (/^\s+$/.test(t.text) && spaceWidth > 0) {
localDrawX += t.font.widthOfTextAtSize(t.text, fontSize) + spaceWidth;
} else {
localDrawX += t.font.widthOfTextAtSize(t.text, fontSize);
}
}
} else {
// Alinhamento à esquerda (padrão) ou última linha de parágrafo justificado
for (const t of trimmedTokens) {
page.drawText(t.text, {
x: drawX,
y,
size: fontSize,
font: t.font,
color
});
if (t.underline && t.text.trim() !== '') {
const underlineY = y - 1.5;
page.drawLine({
start: { x: drawX, y: underlineY },
end: { x: drawX + t.font.widthOfTextAtSize(t.text, fontSize), y: underlineY },
thickness: 0.75,
color
});
}
drawX += t.font.widthOfTextAtSize(t.text, fontSize);
}
}
y -= fontSize * 1.5;
}
return y;
}
const texto = decodeHtmlEntities(
stripUnsupportedTags(
this.processarTemplate(conteudo, escritorio)
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/p>/gi, '\n\n')
.replace(/<p[^>]*>/gi, '')
.replace(/<span[^>]*text-indent[^>]*>/gi, '§§INDENT§§')
.replace(/<span[^>]*text-align\s*:\s*center[^>]*>/gi, '§§CENTER§§')
.replace(/<\/span>/gi, '')
.replace(/\r\n/g, '\n')
.replace(/\r/g, '\n')
.replace(/\n{3,}/g, '\n\n')
.trim()
)
);
const paragrafos = texto.split(/\n{2,}/).map(p => p.trim()).filter(Boolean);
let timbradoPdf: PDFDocument | null = null;
let timbradoPageCount = 0;
let timbradoPages: any[] = [];
if (timbradoExists) {
const timbradoBytes = await fs.readFile(timbradoPath);
timbradoPdf = await PDFDocument.load(timbradoBytes);
timbradoPageCount = timbradoPdf.getPageCount();
timbradoPages = [];
for (let i = 0; i < timbradoPageCount; i++) {
const [embedded] = await pdfDoc.embedPages([timbradoPdf.getPage(i)]);
timbradoPages.push(embedded);
}
}
let currentPar = 0;
let pageIndex = 0;
while (currentPar < paragrafos.length) {
let page = pdfDoc.addPage([PAGE_WIDTH, PAGE_HEIGHT]);
if (timbradoPages.length > 0) {
const embedded = timbradoPages[pageIndex % timbradoPages.length];
page.drawPage(embedded, {
x: 0,
y: 0,
width: PAGE_WIDTH,
height: PAGE_HEIGHT
});
}
let y = PAGE_HEIGHT - margens.top;
while (currentPar < paragrafos.length) {
let indent = paragrafos[currentPar].startsWith('§§INDENT§§');
let center = paragrafos[currentPar].startsWith('§§CENTER§§');
let align: 'center' | 'justify' | 'left' = center ? 'center' : 'justify';
let text = paragrafos[currentPar].replace(/^§§INDENT§§/, '').replace(/^§§CENTER§§/, '').trim();
// Se o parágrafo for centralizado, força alinhamento center e ignora recuo
if (center) {
indent = false;
align = 'center';
}
text = decodeHtmlEntities(text);
let x = margens.left;
let parWidth = MAX_WIDTH;
let yAfter = renderInlineFormattedParagraph(
page,
text,
x,
y,
font,
fontBold,
fontItalic,
fontBoldItalic,
FONT_SIZE,
rgb(0, 0, 0),
align,
parWidth,
indent,
margens.top,
margens.bottom,
PAGE_HEIGHT
);
if (yAfter === null) {
pageIndex++;
break;
}
y = yAfter - FONT_SIZE * 0.5;
currentPar++;
if (y < margens.bottom + FONT_SIZE * 1.5) break;
}
pageIndex++;
}
const pdfBytes = await pdfDoc.save();
return Buffer.from(pdfBytes);
} catch (error) {
console.error('Erro geral ao gerar PDF:', error);
throw error;
}
}
private processarTemplate(template: string, dados: any): string {
return template.replace(/\{\{([^}]+)\}\}/g, (match, key) => {
const keyParts = key.trim().split('.');
let value = dados;
for (const part of keyParts) {
if (value && typeof value === 'object' && part in value) {
value = value[part];
} else {
value = undefined;
break;
}
}
return value !== undefined ? value : match;
});
}
}
+219
View File
@@ -0,0 +1,219 @@
import puppeteer from 'puppeteer';
import { PDFDocument } from 'pdf-lib';
import fs from 'fs/promises';
import path from 'path';
import { prisma } from '../prismaClient';
// Função utilitária para converter pixels em milímetros (1px ≈ 0.264583 mm)
function pxToMm(px: number | null | undefined): string {
if (!px) return '0mm';
return (px * 0.264583).toFixed(2) + 'mm';
}
export class PdfService {
// Busca configuração do documento, usando apenas campos válidos do schema
private async getConfiguracao() {
try {
const config = await prisma.configuracaoDocumento.findFirst({
orderBy: { criadoEm: 'desc' },
select: {
id: true,
timbradoUrl: true,
timbradoMarginTop: true,
timbradoMarginBottom: true,
timbradoMarginLeft: true,
timbradoMarginRight: true,
templatePadrao: true,
margensTemplate: true,
criadoEm: true
}
});
// Extrai recuo de primeira linha se existir em margensTemplate
let firstLineIndent = '0mm';
if (config?.margensTemplate) {
try {
const margens = typeof config.margensTemplate === 'string' ? JSON.parse(config.margensTemplate) : config.margensTemplate;
if (margens && margens.firstLineIndent) {
firstLineIndent = `${margens.firstLineIndent}mm`;
}
} catch (e) {
// Se der erro, ignora e usa padrão
}
}
return {
timbradoUrl: config?.timbradoUrl || '',
timbradoMarginTop: config?.timbradoMarginTop ?? 100,
timbradoMarginBottom: config?.timbradoMarginBottom ?? 50,
timbradoMarginLeft: config?.timbradoMarginLeft ?? 50,
timbradoMarginRight: config?.timbradoMarginRight ?? 50,
templatePadrao: config?.templatePadrao || '',
firstLineIndent
};
} catch (error) {
console.error('Erro ao buscar configuração:', error);
throw new Error('Falha ao buscar configuração');
}
}
// Gera HTML com timbrado e margens
private gerarHTML(content: string, config: any) {
// Limpa espaços, quebras de linha e tags vazias do final do conteúdo
let cleanContent = content
.replace(/(\s|<br\s*\/?>|<p>\s*<\/p>)+$/gi, '')
.replace(/(<p>\s*<\/p>)+/gi, '');
const timbradoUrl = config.timbradoUrl
? `${process.env.FRONTEND_URL || 'http://localhost:5000'}${config.timbradoUrl}`
: '';
// Adiciona log para debug
if (timbradoUrl) {
console.log('[PDF] Timbrado inserido no HTML:', timbradoUrl);
}
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;500;600&display=swap" rel="stylesheet">
<style>
@page {
margin-top: ${pxToMm(config.timbradoMarginTop)};
margin-bottom: ${pxToMm(config.timbradoMarginBottom)};
margin-left: ${pxToMm(config.timbradoMarginLeft)};
margin-right: ${pxToMm(config.timbradoMarginRight)};
size: A4;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
font-family: 'Fira Sans', Arial, sans-serif;
font-size: 11pt;
line-height: 1.5;
background: none;
}
body {
position: relative;
min-height: 100vh;
/* Remove background-image do body para evitar problemas no Puppeteer */
}
.timbrado-bg {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: 0;
${timbradoUrl ? `background-image: url('${timbradoUrl}'); background-size: cover; background-position: center; background-repeat: no-repeat;` : ''}
pointer-events: none;
}
.content {
position: relative;
z-index: 1;
box-sizing: border-box;
width: 100%;
/* Removido padding-top e padding-bottom para evitar recuo duplo com as margens do PDF */
padding-left: ${pxToMm(config.timbradoMarginLeft)};
padding-right: ${pxToMm(config.timbradoMarginRight)};
overflow-wrap: break-word;
word-break: break-word;
/* Permite múltiplas páginas e evita corte de conteúdo */
break-inside: auto;
page-break-inside: auto;
}
.content p {
text-indent: ${config.firstLineIndent || '0mm'};
}
/* Corrige recuo exagerado apenas na primeira linha do primeiro parágrafo da primeira página */
.content p:first-child {
text-indent: 0mm !important;
}
/* Corrige recuo exagerado apenas na última linha do último parágrafo da última página */
.content p:last-child {
margin-bottom: 0 !important;
padding-bottom: 0 !important;
}
</style>
</head>
<body>
${timbradoUrl ? '<div class="timbrado-bg"></div>' : ''}
<div class="content">
${cleanContent}
</div>
</body>
</html>
`;
}
// Gera PDF a partir do HTML, depois sobrepõe o timbrado em cada página
async gerarPDF(conteudo: string) {
try {
const config = await this.getConfiguracao();
// Usa templatePadrao se não houver conteúdo
const html = this.gerarHTML(conteudo || config.templatePadrao, config);
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] });
const page = await browser.newPage();
await page.setContent(html, {
waitUntil: ['networkidle0', 'load'],
timeout: 30000
});
const margin = {
top: pxToMm(config.timbradoMarginTop),
bottom: pxToMm(config.timbradoMarginBottom),
left: pxToMm(config.timbradoMarginLeft),
right: pxToMm(config.timbradoMarginRight)
};
const pdfBuffer = await page.pdf({
format: 'A4',
printBackground: true,
margin,
preferCSSPageSize: true
});
await browser.close();
// Se não houver timbrado, retorna direto
if (!config.timbradoUrl) {
return Buffer.from(pdfBuffer);
}
// Caminho absoluto do PDF de timbrado
const timbradoPath = config.timbradoUrl.startsWith('/uploads')
? path.join(process.cwd(), 'public', config.timbradoUrl)
: path.join(process.cwd(), 'public', 'uploads', path.basename(config.timbradoUrl));
let timbradoBytes: Buffer;
try {
timbradoBytes = await fs.readFile(timbradoPath);
} catch (e) {
console.error('Timbrado não encontrado:', timbradoPath);
return Buffer.from(pdfBuffer);
}
// Mescla cada página do PDF gerado com o timbrado
const pdfDoc = await PDFDocument.load(pdfBuffer);
const timbradoDoc = await PDFDocument.load(timbradoBytes);
const timbradoPage = timbradoDoc.getPage(0);
const [timbradoEmbed] = await pdfDoc.embedPages([timbradoPage]);
const pageCount = pdfDoc.getPageCount();
for (let i = 0; i < pageCount; i++) {
const page = pdfDoc.getPage(i);
page.drawPage(timbradoEmbed, { x: 0, y: 0, width: page.getWidth(), height: page.getHeight() });
}
// Remove última página se estiver vazia (sem conteúdo visível)
if (pdfDoc.getPageCount() > 1) {
const lastPage = pdfDoc.getPage(pdfDoc.getPageCount() - 1);
const textContent = lastPage.getTextContent ? await lastPage.getTextContent() : null;
// pdf-lib não tem getTextContent, então alternativa: verifica se altura do conteúdo é mínima
if (lastPage.getHeight && lastPage.getWidth && lastPage.getHeight() > 0 && lastPage.getWidth() > 0) {
// Heurística: verifica se a página tem apenas o timbrado (sem outros objetos)
if (lastPage.node.Contents().size() === 0) {
pdfDoc.removePage(pdfDoc.getPageCount() - 1);
}
}
}
const mergedPdf = await pdfDoc.save();
return Buffer.from(mergedPdf);
} catch (error) {
console.error('Erro ao gerar PDF:', error);
throw new Error('Falha ao gerar PDF');
}
}
}
+140 -283
View File
@@ -1,188 +1,53 @@
import puppeteer from 'puppeteer';
import { prisma } from '../prismaClient';
import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
import { PDFDocument } from 'pdf-lib';
import fs from 'fs/promises';
import path from 'path';
import { prisma } from '../prismaClient';
// Função utilitária para converter pixels em milímetros (1px ≈ 0.264583 mm)
function pxToMm(px: number | null | undefined): string {
if (!px) return '0mm';
return (px * 0.264583).toFixed(2) + 'mm';
}
/**
* Serviço para geração e manipulação de arquivos PDF
*/
export class PdfService {
/**
* Cria um documento PDF básico
* @returns Documento PDF
*/
async criarDocumento() {
return await PDFDocument.create();
}
/**
* Carrega um documento PDF existente
* @param pdfBytes - Bytes do PDF
* @returns Documento PDF
*/
async carregarDocumento(pdfBytes: Uint8Array) {
return await PDFDocument.load(pdfBytes);
}
/**
* Adiciona uma página ao documento
* @param doc - Documento PDF
* @param tamanho - Tamanho da página (padrão: A4)
* @returns Página adicionada
*/
adicionarPagina(doc: any, tamanho = [595.28, 841.89]) {
return doc.addPage(tamanho);
}
/**
* Salva o documento como buffer
* @param doc - Documento PDF
* @returns Buffer do PDF
*/
async salvarComoBuffer(doc: any): Promise<Buffer> {
const pdfBytes = await doc.save();
return Buffer.from(pdfBytes);
}
/**
* Carrega uma fonte padrão
* @param doc - Documento PDF
* @param fonte - Nome da fonte padrão
* @returns Fonte carregada
*/
async carregarFonte(doc: any, fonte: StandardFonts) {
return await doc.embedFont(fonte);
}
/**
* Desenha texto em uma página
* @param pagina - Página do PDF
* @param texto - Texto a ser desenhado
* @param x - Posição X
* @param y - Posição Y
* @param fonte - Fonte a ser usada
* @param tamanho - Tamanho da fonte
* @param cor - Cor do texto (padrão: preto)
*/
desenharTexto(
pagina: any,
texto: string,
x: number,
y: number,
fonte: any,
tamanho: number,
cor = rgb(0, 0, 0)
) {
pagina.drawText(texto, {
x,
y,
font: fonte,
size: tamanho,
color: cor,
});
}
/**
* Cria um cabeçalho para o documento
* @param pagina - Página do PDF
* @param titulo - Título do cabeçalho
* @param fonte - Fonte a ser usada
* @param margemSuperior - Margem superior
* @param margem - Margem lateral
* @returns Posição Y após o cabeçalho
*/
criarCabecalho(
pagina: any,
titulo: string,
fonte: any,
margemSuperior: number,
margem: number
): number {
const yPos = pagina.getHeight() - margemSuperior;
this.desenharTexto(
pagina,
titulo,
margem,
yPos,
fonte,
18,
rgb(0, 0, 0.7)
);
// Linha separadora
pagina.drawLine({
start: { x: margem, y: yPos - 10 },
end: { x: pagina.getWidth() - margem, y: yPos - 10 },
thickness: 1,
color: rgb(0, 0, 0.5),
});
return yPos - 30; // Retorna a posição Y após o cabeçalho
}
/**
* Cria um rodapé para o documento
* @param pagina - Página do PDF
* @param texto - Texto do rodapé
* @param fonte - Fonte a ser usada
* @param margem - Margem
*/
criarRodape(pagina: any, texto: string, fonte: any, margem: number) {
const yPos = margem / 2;
this.desenharTexto(
pagina,
texto,
margem,
yPos,
fonte,
8,
rgb(0.5, 0.5, 0.5)
);
}
// Busca configuração do documento, usando apenas campos válidos do schema
private async getConfiguracao() {
try {
// Buscar configuração ou usar valores padrão
const config = await prisma.configuracaoDocumento.findFirst({
orderBy: { criadoEm: 'desc' },
select: {
id: true,
headerImageUrl: true,
footerImageUrl: true,
logoUrl: true,
timbradoUrl: true,
timbradoMarginTop: true,
timbradoMarginBottom: true,
timbradoMarginLeft: true,
timbradoMarginRight: true,
templatePadrao: true,
margensTemplate: true,
criadoEm: true
}
});
console.log('Configuração encontrada:', config); // Debug
// Retornar configuração padrão se não existir
// Extrai recuo de primeira linha se existir em margensTemplate
let firstLineIndent = '0mm';
if (config?.margensTemplate) {
try {
const margens = typeof config.margensTemplate === 'string' ? JSON.parse(config.margensTemplate) : config.margensTemplate;
if (margens && margens.firstLineIndent) {
firstLineIndent = `${margens.firstLineIndent}mm`;
}
} catch (e) {
// Se der erro, ignora e usa padrão
}
}
return {
cabecalhoHtml: config?.cabecalhoHtml || `
<div style="text-align: center; padding: 20px;">
<h2 style="margin:0;font-size:14pt">{{escritorio.nome}}</h2>
</div>
`,
rodapeHtml: config?.rodapeHtml || `
<div style="text-align: center; font-size: 10pt;">
{{escritorio.endereco}}<br>
Tel: {{escritorio.telefone}} | Email: {{escritorio.email}}
</div>
`,
logoUrl: config?.logoUrl || '',
timbradoUrl: config?.timbradoUrl || '',
timbradoMarginTop: config?.timbradoMarginTop || 100,
timbradoMarginBottom: config?.timbradoMarginBottom || 50,
timbradoMarginLeft: config?.timbradoMarginLeft || 50,
timbradoMarginRight: config?.timbradoMarginRight || 50
timbradoMarginTop: config?.timbradoMarginTop ?? 100,
timbradoMarginBottom: config?.timbradoMarginBottom ?? 50,
timbradoMarginLeft: config?.timbradoMarginLeft ?? 50,
timbradoMarginRight: config?.timbradoMarginRight ?? 50,
templatePadrao: config?.templatePadrao || '',
firstLineIndent
};
} catch (error) {
console.error('Erro ao buscar configuração:', error);
@@ -190,13 +55,19 @@ export class PdfService {
}
}
// Gera HTML com timbrado e margens
private gerarHTML(content: string, config: any) {
const timbradoUrl = config.timbradoUrl
? `${process.env.BACKEND_URL || 'http://localhost:5000'}${config.timbradoUrl}`
// Limpa espaços, quebras de linha e tags vazias do final do conteúdo
let cleanContent = content
.replace(/(\s|<br\s*\/?>|<p>\s*<\/p>)+$/gi, '')
.replace(/(<p>\s*<\/p>)+/gi, '');
const timbradoUrl = config.timbradoUrl
? `${process.env.FRONTEND_URL || 'http://localhost:5000'}${config.timbradoUrl}`
: '';
console.log('Gerando PDF com timbrado:', timbradoUrl);
// Adiciona log para debug
if (timbradoUrl) {
console.log('[PDF] Timbrado inserido no HTML:', timbradoUrl);
}
return `
<!DOCTYPE html>
<html>
@@ -204,157 +75,143 @@ export class PdfService {
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;500;600&display=swap" rel="stylesheet">
<style>
@page {
margin: 0;
@page {
margin-top: ${pxToMm(config.timbradoMarginTop)};
margin-bottom: ${pxToMm(config.timbradoMarginBottom)};
margin-left: ${pxToMm(config.timbradoMarginLeft)};
margin-right: ${pxToMm(config.timbradoMarginRight)};
size: A4;
}
body {
html, body {
height: 100%;
margin: 0;
padding: 0;
font-family: 'Fira Sans', Arial, sans-serif;
font-size: 11pt;
line-height: 1.5;
background: none;
}
body {
position: relative;
min-height: 100vh;
/* Remove background-image do body para evitar problemas no Puppeteer */
}
.page {
position: relative;
width: 21cm;
min-height: 29.7cm;
padding: ${config.timbradoMarginTop || 100}px ${config.timbradoMarginRight || 50}px ${config.timbradoMarginBottom || 50}px ${config.timbradoMarginLeft || 50}px;
background: ${timbradoUrl ? `url('${timbradoUrl}')` : 'none'};
background-size: cover;
background-position: center;
background-repeat: no-repeat;
box-sizing: border-box;
.timbrado-bg {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: 0;
${timbradoUrl ? `background-image: url('${timbradoUrl}'); background-size: cover; background-position: center; background-repeat: no-repeat;` : ''}
pointer-events: none;
}
.content {
position: relative;
z-index: 1;
box-sizing: border-box;
width: 100%;
/* Removido padding-top e padding-bottom para evitar recuo duplo com as margens do PDF */
padding-left: ${pxToMm(config.timbradoMarginLeft)};
padding-right: ${pxToMm(config.timbradoMarginRight)};
overflow-wrap: break-word;
word-break: break-word;
/* Permite múltiplas páginas e evita corte de conteúdo */
break-inside: auto;
page-break-inside: auto;
}
.content p {
text-indent: ${config.firstLineIndent || '0mm'};
}
/* Corrige recuo exagerado apenas na primeira linha do primeiro parágrafo da primeira página */
.content p:first-child {
text-indent: 0mm !important;
}
/* Corrige recuo exagerado apenas na última linha do último parágrafo da última página */
.content p:last-child {
margin-bottom: 0 !important;
padding-bottom: 0 !important;
}
</style>
</head>
<body>
<div class="page">
<div class="content">
${content}
</div>
${timbradoUrl ? '<div class="timbrado-bg"></div>' : ''}
<div class="content">
${cleanContent}
</div>
</body>
</html>
`;
}
async gerarPDF(conteudo: string, escritorio: any) {
// Gera PDF a partir do HTML, depois sobrepõe o timbrado em cada página
async gerarPDF(conteudo: string) {
try {
// 1. Buscar configuração do template
const config = await prisma.configuracaoDocumento.findFirst({
orderBy: { criadoEm: 'desc' }
});
// 2. Gerar PDF do conteúdo
const browser = await puppeteer.launch({
headless: 'new',
args: ['--no-sandbox']
});
const config = await this.getConfiguracao();
// Usa templatePadrao se não houver conteúdo
const html = this.gerarHTML(conteudo || config.templatePadrao, config);
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] });
const page = await browser.newPage();
// Usar template padrão ou fallback para o template básico
const template = config?.templatePadrao || `
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;500;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Fira Sans', Arial, sans-serif;
font-size: 11pt;
line-height: 1.3;
margin: 0;
padding: 0;
}
.content {
margin: 0;
padding: 0;
min-height: calc(100vh - 58mm);
position: relative;
}
p { margin: 0.7em 0; }
h1, h2, h3 { margin: 0.8em 0; }
</style>
</head>
<body>
<div class="content">
${conteudo}
</div>
</body>
</html>
`;
// Processar o template substituindo variáveis
const templateProcessado = template.replace(/\{\{(.+?)\}\}/g, (match, key) => {
return escritorio[key.trim()] || match;
await page.setContent(html, {
waitUntil: ['networkidle0', 'load'],
timeout: 30000
});
await page.setContent(templateProcessado);
const margens = config?.margensTemplate || {
top: '35mm',
bottom: '29mm',
left: '25mm',
right: '25mm'
const margin = {
top: pxToMm(config.timbradoMarginTop),
bottom: pxToMm(config.timbradoMarginBottom),
left: pxToMm(config.timbradoMarginLeft),
right: pxToMm(config.timbradoMarginRight)
};
const contentPdfBuffer = await page.pdf({
const pdfBuffer = await page.pdf({
format: 'A4',
margin: margens,
displayHeaderFooter: false,
printBackground: true
printBackground: true,
margin,
preferCSSPageSize: true
});
await browser.close();
// 2. Carregar os PDFs
const templatePath = path.join(process.cwd(), 'public', 'uploads', 'Timbrado_2025.pdf');
const templateBytes = await fs.readFile(templatePath);
const templateDoc = await PDFDocument.load(templateBytes);
const contentDoc = await PDFDocument.load(contentPdfBuffer);
// 3. Criar documento final
const pdfDoc = await PDFDocument.create();
// 4. Copiar template e conteúdo
const [templatePage] = await templateDoc.copyPages(templateDoc, [0]);
const contentPages = await contentDoc.getPages();
// 5. Para cada página do conteúdo
for (let i = 0; i < contentPages.length; i++) {
// Primeiro: adicionar template
const page = await pdfDoc.embedPage(templatePage);
const contentPage = await pdfDoc.embedPage(contentPages[i]);
// Segundo: criar nova página
const newPage = pdfDoc.addPage([page.width, page.height]);
// Terceiro: desenhar template e conteúdo
newPage.drawPage(page);
newPage.drawPage(contentPage);
// Se não houver timbrado, retorna direto
if (!config.timbradoUrl) {
return Buffer.from(pdfBuffer);
}
// 6. Gerar PDF final
const pdfBytes = await pdfDoc.save();
return Buffer.from(pdfBytes);
// Caminho absoluto do PDF de timbrado
const timbradoPath = config.timbradoUrl.startsWith('/uploads')
? path.join(process.cwd(), 'public', config.timbradoUrl)
: path.join(process.cwd(), 'public', 'uploads', path.basename(config.timbradoUrl));
let timbradoBytes: Buffer;
try {
timbradoBytes = await fs.readFile(timbradoPath);
} catch (e) {
console.error('Timbrado não encontrado:', timbradoPath);
return Buffer.from(pdfBuffer);
}
// Mescla cada página do PDF gerado com o timbrado
const pdfDoc = await PDFDocument.load(pdfBuffer);
const timbradoDoc = await PDFDocument.load(timbradoBytes);
const timbradoPage = timbradoDoc.getPage(0);
const [timbradoEmbed] = await pdfDoc.embedPages([timbradoPage]);
const pageCount = pdfDoc.getPageCount();
for (let i = 0; i < pageCount; i++) {
const page = pdfDoc.getPage(i);
page.drawPage(timbradoEmbed, { x: 0, y: 0, width: page.getWidth(), height: page.getHeight() });
}
// Após mesclar o timbrado
const pageCountBefore = pdfDoc.getPageCount();
if (pageCountBefore > 1) {
// Heurística: remove a última página se ela estiver completamente em branco (sem texto)
const lastPage = pdfDoc.getPage(pageCountBefore - 1);
const text = await lastPage.getTextContent?.();
if (!text || (Array.isArray(text.items) && text.items.length === 0)) {
pdfDoc.removePage(pageCountBefore - 1);
}
}
const mergedPdf = await pdfDoc.save();
return Buffer.from(mergedPdf);
} catch (error) {
console.error('Erro ao gerar PDF:', error);
throw new Error('Falha ao gerar PDF');
}
}
}
}
+13 -3
View File
@@ -606,9 +606,19 @@ export class ReportGenerator {
y -= 15;
// RESTAURAR GEOLOCALIZAÇÃO - CORRIGIDA PARA EVITAR N/A
const latitude = typeof data.metadata?.latitude !== 'undefined' ? data.metadata.latitude : '-7.2035066';
const longitude = typeof data.metadata?.longitude !== 'undefined' ? data.metadata.longitude : '-48.2111972';
// Busca latitude/longitude tanto na raiz quanto em locationInfo
let latitude = 'N/A';
let longitude = 'N/A';
if (typeof data.metadata?.latitude !== 'undefined' && data.metadata?.latitude !== null) {
latitude = String(data.metadata.latitude);
} else if (typeof data.metadata?.locationInfo?.latitude !== 'undefined' && data.metadata?.locationInfo?.latitude !== null) {
latitude = String(data.metadata.locationInfo.latitude);
}
if (typeof data.metadata?.longitude !== 'undefined' && data.metadata?.longitude !== null) {
longitude = String(data.metadata.longitude);
} else if (typeof data.metadata?.locationInfo?.longitude !== 'undefined' && data.metadata?.locationInfo?.longitude !== null) {
longitude = String(data.metadata.locationInfo.longitude);
}
this.drawLabelValue(page, "Coordenadas:", `${latitude}, ${longitude}`, y, helvetica, helveticaBold);
y -= 15;
@@ -0,0 +1,6 @@
{
"hash": "5e87cdeee62ec3e659704f86b359862f4d6ab3764de6d2490ffbdf4560c6faa0",
"timestamp": "2025-04-22T22:32:04.863Z",
"ntpReference": "Acompanhando time.nist.gov [132.163.97.4:123].\nColetando 1 amostras.\nA hora atual � 22/04/2025 19:32:04.\n19:32:04, Erro: 0x800705B4\n",
"unixTimestamp": 1745361124
}
@@ -0,0 +1,71 @@
{
"timestamp": "2025-04-22T22:32:07.355Z",
"fileName": "solicitação.jpg",
"fileSize": 79952,
"mimeType": "image/jpeg",
"checksums": {
"sha256": "5e87cdeee62ec3e659704f86b359862f4d6ab3764de6d2490ffbdf4560c6faa0",
"sha512": "aac8920361b942a02a79c56503e36f98a0624f16e6e17023338358752ec5fdd35d2bbc3ef69bbd53723af2edac95c76ce40a897c6a59ac2cc8e0774c9b649cbb",
"md5": "53ef086077fa170f4154f555ccf9545f"
},
"metadata": {
"collectionId": "e73e9767-1ac7-493a-8247-d54aeb5e2379",
"collectionTimestamp": "2025-04-22T22:32:04.840Z",
"userInfo": {
"ipAddress": "::1:55009",
"userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36",
"language": "pt-BR",
"browser": {
"name": "Chrome",
"version": "135.0.0.0",
"major": "135"
},
"engine": {
"name": "Blink",
"version": "135.0.0.0"
},
"os": {
"name": "Windows",
"version": "10"
},
"device": {
"vendor": "desconhecido",
"model": "desconhecido",
"type": "desconhecido"
},
"cpu": {
"architecture": "amd64"
},
"viewportSize": "1150x695",
"referrer": "não informado"
},
"fileInfo": {
"name": "solicitação.jpg",
"size": 79952,
"sizeFormatted": "78.08 KB",
"modifiedDate": "2025-04-08T18:55:21.595Z"
},
"locationInfo": {
"latitude": -7.2045208,
"longitude": -48.2294113,
"city": "não disponível",
"region": "não disponível",
"country": "não disponível",
"timezone": "não disponível"
},
"timestamp": "2025-04-22T22:32:04.831Z",
"integrityHash": "2faf0e219dda1105b713b1e220cf4b89b5c26bb75e700d417f1f397c8685d8b4"
},
"processingInfo": {
"processingNode": "RODRIGO",
"processingUser": "rodri",
"processingTimestamp": "2025-04-22T22:32:07.360Z",
"systemInfo": {
"platform": "win32",
"release": "10.0.26100",
"cpus": 4,
"memory": "20GB",
"uptime": "11h"
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

@@ -0,0 +1,6 @@
{
"hash": "a97fe62052f746e17a48e6c3db29bcb3cd30d6457222d272ba1a83691024070f",
"timestamp": "2025-04-22T22:20:25.521Z",
"ntpReference": "Acompanhando time.nist.gov [129.6.15.26:123].\nColetando 1 amostras.\nA hora atual � 22/04/2025 19:20:25.\n19:20:25, Erro: 0x800705B4\n",
"unixTimestamp": 1745360425
}
@@ -0,0 +1,71 @@
{
"timestamp": "2025-04-22T22:20:27.452Z",
"fileName": "WhatsApp Image 2025-04-10 at 17.34.45.jpeg",
"fileSize": 199339,
"mimeType": "image/jpeg",
"checksums": {
"sha256": "a97fe62052f746e17a48e6c3db29bcb3cd30d6457222d272ba1a83691024070f",
"sha512": "fcafa2baf00a9a123e797d364d8010c5d45a58ca3dd5612cfa4032539762fdf0b014cfd11bc3655e18c6eade3a38d01149cce4cae6a6dffe486af407c6a0eea8",
"md5": "78581f0292ca27ea3066998009018e38"
},
"metadata": {
"collectionId": "7bbe3133-8616-478d-8fab-bc29deab2351",
"collectionTimestamp": "2025-04-22T22:20:25.506Z",
"userInfo": {
"ipAddress": "::1:54423",
"userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36",
"language": "pt-BR",
"browser": {
"name": "Chrome",
"version": "135.0.0.0",
"major": "135"
},
"engine": {
"name": "Blink",
"version": "135.0.0.0"
},
"os": {
"name": "Windows",
"version": "10"
},
"device": {
"vendor": "desconhecido",
"model": "desconhecido",
"type": "desconhecido"
},
"cpu": {
"architecture": "amd64"
},
"viewportSize": "1150x695",
"referrer": "não informado"
},
"fileInfo": {
"name": "WhatsApp Image 2025-04-10 at 17.34.45.jpeg",
"size": 199339,
"sizeFormatted": "194.67 KB",
"modifiedDate": "2025-04-11T00:02:14.553Z"
},
"locationInfo": {
"latitude": -7.2045208,
"longitude": -48.2294113,
"city": "não disponível",
"region": "não disponível",
"country": "não disponível",
"timezone": "não disponível"
},
"timestamp": "2025-04-22T22:20:25.494Z",
"integrityHash": "7ef6d0611c893f56912d613b5e0f60a603c3e2ddeb0e2c2ddafb9b49a49a4878"
},
"processingInfo": {
"processingNode": "RODRIGO",
"processingUser": "rodri",
"processingTimestamp": "2025-04-22T22:20:27.452Z",
"systemInfo": {
"platform": "win32",
"release": "10.0.26100",
"cpus": 4,
"memory": "20GB",
"uptime": "11h"
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 195 KiB

@@ -0,0 +1,6 @@
{
"hash": "daea8251005113c549873cb271c3cedd345f36a5289dafcf76ac4a9664291864",
"timestamp": "2025-04-22T22:33:58.785Z",
"ntpReference": "Acompanhando time.nist.gov [132.163.97.2:123].\nColetando 1 amostras.\nA hora atual � 22/04/2025 19:33:58.\n19:33:58, Erro: 0x800705B4\n",
"unixTimestamp": 1745361238
}
@@ -0,0 +1,71 @@
{
"timestamp": "2025-04-22T22:34:00.953Z",
"fileName": "WhatsApp Image 2025-04-10 at 17.33.40 (3).jpeg",
"fileSize": 165323,
"mimeType": "image/jpeg",
"checksums": {
"sha256": "daea8251005113c549873cb271c3cedd345f36a5289dafcf76ac4a9664291864",
"sha512": "d9eff17b23fa3e4b5314197838a7d6531b0940d96d184982283da1e01812cfa13417737a1760bb72fab2f10f0c6919885cb3738b3286263a2c1797efc2ce5365",
"md5": "4f0f85e5503e45cb7a7f3990991dc515"
},
"metadata": {
"collectionId": "4ba82667-b08d-46a6-9713-e0c664b3af6f",
"collectionTimestamp": "2025-04-22T22:33:58.755Z",
"userInfo": {
"ipAddress": "::1:55140",
"userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36",
"language": "pt-BR",
"browser": {
"name": "Chrome",
"version": "135.0.0.0",
"major": "135"
},
"engine": {
"name": "Blink",
"version": "135.0.0.0"
},
"os": {
"name": "Windows",
"version": "10"
},
"device": {
"vendor": "desconhecido",
"model": "desconhecido",
"type": "desconhecido"
},
"cpu": {
"architecture": "amd64"
},
"viewportSize": "1150x695",
"referrer": "não informado"
},
"fileInfo": {
"name": "WhatsApp Image 2025-04-10 at 17.33.40 (3).jpeg",
"size": 165323,
"sizeFormatted": "161.45 KB",
"modifiedDate": "2025-04-11T00:02:10.578Z"
},
"locationInfo": {
"latitude": -7.2045208,
"longitude": -48.2294113,
"city": "não disponível",
"region": "não disponível",
"country": "não disponível",
"timezone": "não disponível"
},
"timestamp": "2025-04-22T22:33:58.722Z",
"integrityHash": "ea7631b891db898d4b082e0f3b9ca839c074424cc39ac3d5963e8ac3b4e5b790"
},
"processingInfo": {
"processingNode": "RODRIGO",
"processingUser": "rodri",
"processingTimestamp": "2025-04-22T22:34:00.954Z",
"systemInfo": {
"platform": "win32",
"release": "10.0.26100",
"cpus": 4,
"memory": "20GB",
"uptime": "11h"
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 161 KiB

@@ -0,0 +1,6 @@
{
"hash": "e64cd45d0423541166f6cef318bbe8a6c34df8aafc03a10fb0390e72daa732c4",
"timestamp": "2025-04-22T22:22:48.274Z",
"ntpReference": "Acompanhando time.nist.gov [129.6.15.26:123].\nColetando 1 amostras.\nA hora atual � 22/04/2025 19:22:48.\n19:22:48, Erro: 0x800705B4\n",
"unixTimestamp": 1745360568
}
@@ -0,0 +1,71 @@
{
"timestamp": "2025-04-22T22:22:50.477Z",
"fileName": "Trabalhador_Rural_Idoso_Prestes_a_se_Aposentar.jpg",
"fileSize": 1721153,
"mimeType": "image/jpeg",
"checksums": {
"sha256": "e64cd45d0423541166f6cef318bbe8a6c34df8aafc03a10fb0390e72daa732c4",
"sha512": "8b4526086e7cf7f1ec3056aace8c03dd6c74dad91ba2b521910e5dcd65a15064bd9e1f5272b48de09ccf05383c0ce6bcf6bc34717e823a0c544eb725484b3646",
"md5": "e6c1c696bc8e6dc5cc67bdf42caa149d"
},
"metadata": {
"collectionId": "c26103a3-e80f-4902-a20f-e4f24a7053e8",
"collectionTimestamp": "2025-04-22T22:22:48.225Z",
"userInfo": {
"ipAddress": "::1:54550",
"userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36",
"language": "pt-BR",
"browser": {
"name": "Chrome",
"version": "135.0.0.0",
"major": "135"
},
"engine": {
"name": "Blink",
"version": "135.0.0.0"
},
"os": {
"name": "Windows",
"version": "10"
},
"device": {
"vendor": "desconhecido",
"model": "desconhecido",
"type": "desconhecido"
},
"cpu": {
"architecture": "amd64"
},
"viewportSize": "1150x695",
"referrer": "não informado"
},
"fileInfo": {
"name": "Trabalhador_Rural_Idoso_Prestes_a_se_Aposentar.jpg",
"size": 1721153,
"sizeFormatted": "1.64 MB",
"modifiedDate": "2025-04-11T01:08:13.364Z"
},
"locationInfo": {
"latitude": -7.2045208,
"longitude": -48.2294113,
"city": "não disponível",
"region": "não disponível",
"country": "não disponível",
"timezone": "não disponível"
},
"timestamp": "2025-04-22T22:22:48.213Z",
"integrityHash": "b99c926d06a10f7b4c0c6955073b145f5ca6494f0e356d8264dfcdbff1bca1b5"
},
"processingInfo": {
"processingNode": "RODRIGO",
"processingUser": "rodri",
"processingTimestamp": "2025-04-22T22:22:50.477Z",
"systemInfo": {
"platform": "win32",
"release": "10.0.26100",
"cpus": 4,
"memory": "20GB",
"uptime": "11h"
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB