-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument-generator-workbench.js
More file actions
3668 lines (3269 loc) · 153 KB
/
document-generator-workbench.js
File metadata and controls
3668 lines (3269 loc) · 153 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ══════════════════════════════════════════════════════════════
DOCUMENT GENERATOR WORKBENCH · JS Engine v3
Módulos: Importação PDF · Extração · Mapeamento Heurístico ·
Revisão · Templates por Tipo · Geração · Exportação
══════════════════════════════════════════════════════════════ */
/* ── Versão para diagnóstico de cache ───────────────────────────
Confirme no console: window.DOC_WORKBENCH_VERSION
Se retornar undefined ou valor antigo → browser está servindo
uma versão cacheada do arquivo. Force Ctrl+Shift+R ou adicione
?v= diferente na tag <script src="document-generator-workbench.js?v=...">
────────────────────────────────────────────────────────────── */
window.DOC_WORKBENCH_VERSION = '2026-03-13.02';
/* ══════════════════════════════════════════════════════════════
MÓDULO: CARREGAMENTO DO PDF.JS — robusto, com fallback de CDN
══════════════════════════════════════════════════════════════
Estratégia:
1. Tenta CDN primário (cdnjs)
2. Se falhar em 8s, tenta CDN secundário (jsdelivr)
3. Se ambos falharem, sinaliza claramente: import fica bloqueado
com mensagem específica, sem crash silencioso.
Por que dinâmico em vez de <script> estático:
- <script integrity="hash"> descarta o arquivo inteiro se o hash
não bater, sem erro visível → pdfjsLib fica undefined silenciosamente.
- Carregamento dinâmico detecta o erro e tenta fallback.
- Permite configurar workerSrc do mesmo CDN que carregou.
══════════════════════════════════════════════════════════════ */
const PDFJS_VERSION = '3.11.174';
const PDFJS_CDNS = [
{
lib: `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${PDFJS_VERSION}/pdf.min.js`,
worker: `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${PDFJS_VERSION}/pdf.worker.min.js`,
name: 'cdnjs',
},
{
lib: `https://cdn.jsdelivr.net/npm/pdfjs-dist@${PDFJS_VERSION}/build/pdf.min.js`,
worker: `https://cdn.jsdelivr.net/npm/pdfjs-dist@${PDFJS_VERSION}/build/pdf.worker.min.js`,
name: 'jsdelivr',
},
];
// Estado global do carregamento — consultado por handlePdfFile
window._gudiPdfJs = {
status: 'loading', // 'loading' | 'ready' | 'failed'
workerSrc: null,
error: null,
};
function _loadScriptWithTimeout(src, timeoutMs) {
return new Promise((resolve, reject) => {
const el = document.createElement('script');
el.src = src;
el.crossOrigin = 'anonymous';
const timer = setTimeout(() => {
el.remove();
reject(new Error(`timeout após ${timeoutMs}ms`));
}, timeoutMs);
el.onload = () => { clearTimeout(timer); resolve(); };
el.onerror = (e) => { clearTimeout(timer); el.remove(); reject(e); };
document.head.appendChild(el);
});
}
async function _initPdfJs() {
for (const cdn of PDFJS_CDNS) {
try {
console.info(`[DOCS] Tentando carregar pdf.js via ${cdn.name}…`);
await _loadScriptWithTimeout(cdn.lib, 8000);
if (typeof window.pdfjsLib === 'undefined') {
throw new Error('script carregado mas pdfjsLib não definido');
}
pdfjsLib.GlobalWorkerOptions.workerSrc = cdn.worker;
window._gudiPdfJs.status = 'ready';
window._gudiPdfJs.workerSrc = cdn.worker;
console.info(`[DOCS] pdf.js carregado via ${cdn.name} (v${pdfjsLib.version})`);
return;
} catch (err) {
console.warn(`[DOCS] pdf.js falhou via ${cdn.name}:`, err.message || err);
}
}
// Todos os CDNs falharam
window._gudiPdfJs.status = 'failed';
window._gudiPdfJs.error = 'Nenhum CDN disponível';
console.error('[DOCS] pdf.js não carregou em nenhum CDN. Import de PDF indisponível.');
}
// Iniciar carregamento imediatamente (não bloqueia o resto do JS)
const _pdfJsReady = _initPdfJs();
/* ──────────────────────────────────────────────────────────────
MÓDULO: STATE
────────────────────────────────────────────────────────────── */
const state = {
docType: 'relatorio',
theme: 'grafite',
sections: [],
highlights: [],
documentModel: [],
structureMode: 'editorial',
sectionIdCounter: 0,
highlightIdCounter: 0,
reviewBlocks: [],
reviewBlockCounter: 0,
};
/* ──────────────────────────────────────────────────────────────
MÓDULO: METADADOS DE TIPO DOCUMENTAL
────────────────────────────────────────────────────────────── */
const DOC_TYPE_LABELS = {
relatorio: 'RELATÓRIO EXECUTIVO',
parecer: 'PARECER INSTITUCIONAL',
diagnostico: 'DIAGNÓSTICO ESTRATÉGICO',
proposta: 'PROPOSTA',
sintese: 'SÍNTESE ESTRATÉGICA',
impacto: 'RELATÓRIO DE IMPACTO',
crm: 'RELATÓRIO DE CRM — INTELIGÊNCIA PÓS-EVENTO',
};
/* Estrutura editorial sugerida por tipo documental */
const DOC_TYPE_SCHEMA = {
relatorio: {
summaryLabel: 'Resumo Executivo',
nextLabel: 'Próximos Passos',
defaultSections: ['Contexto e Objetivos', 'Análise de Resultados', 'Conclusões'],
highlightsLabel: 'Indicadores-Chave',
intro: null,
signature: false,
},
parecer: {
summaryLabel: 'Fundamentação',
nextLabel: 'Recomendações',
defaultSections: ['Objeto do Parecer', 'Análise', 'Conclusão e Parecer Final'],
highlightsLabel: 'Pontos Avaliados',
intro: 'Este parecer foi elaborado com base nas informações disponibilizadas e tem caráter institucional. As conclusões aqui apresentadas são de responsabilidade da equipe signatária.',
signature: true,
},
diagnostico: {
summaryLabel: 'Síntese Diagnóstica',
nextLabel: 'Recomendações',
defaultSections: ['Contexto e Metodologia', 'Achados Principais', 'Análise Crítica', 'Leitura Estratégica'],
highlightsLabel: 'Indicadores Diagnósticos',
intro: null,
signature: false,
},
proposta: {
summaryLabel: 'Visão Geral da Proposta',
nextLabel: 'Próximos Passos para Aprovação',
defaultSections: ['Objetivo e Escopo', 'Entregáveis', 'Cronograma', 'Investimento'],
highlightsLabel: 'Resumo da Proposta',
intro: null,
signature: false,
},
sintese: {
summaryLabel: 'Síntese Executiva',
nextLabel: 'Ações Prioritárias',
defaultSections: ['Situação Atual', 'Análise Estratégica', 'Decisões Recomendadas'],
highlightsLabel: 'Fatores Críticos',
intro: null,
signature: false,
},
impacto: {
summaryLabel: 'Sumário de Impacto',
nextLabel: 'Próximos Ciclos',
defaultSections: ['Contexto do Projeto', 'Resultados Alcançados', 'Repercussão Institucional', 'Lições Aprendidas'],
highlightsLabel: 'Indicadores de Impacto',
intro: null,
signature: false,
},
crm: {
summaryLabel: 'Panorama Geral — Inteligência CRM',
nextLabel: 'Ações de Reengajamento',
defaultSections: [
'Ausentes Totais — 6 Temperaturas',
'Segmentos de Maior Valor Estratégico',
'Hipóteses sobre Comparecimento',
'Públicos Prioritários — Próxima Edição',
'Proposta de Segmentação CRM',
'Recomendações de Próximos Movimentos',
],
highlightsLabel: 'KPIs Analíticos',
intro: null,
signature: false,
},
};
const THEME_DESCS = {
grafite: '<strong>Grafite</strong> — fundo grafite escuro, contraste máximo, lateral colorida. Para relatórios executivos e materiais de impacto interno.',
editorial:'<strong>Editorial</strong> — fundo branco, tipografia refinada, linha laranja de acento. Para documentos formais de circulação externa.',
navy: '<strong>Navy</strong> — azul institucional profundo, identidade corporativa e governamental. Para pareceres e documentos sérios.',
pdf: '<strong>Modo PDF</strong> — language inspired by polished presentation decks: bold type, gradient bar and decorative accents.',
};
const BULLET_COLORS = ['#E16E1A','#2ED9C3','#81C458','#E5B92B','#2D4F76'];
const RE_TABULAR_SEP = / {2,}|\t|[|;]/;
const RE_TABULAR_SPLIT = / {2,}|\t|\s+\|\s+|;/;
const MAX_X_GAP_FOR_LINE = 8; // Reduzido para evitar merge de colunas distintas
const MAX_Y_GAP_FOR_LINE = 2; // Reduzido para evitar merge de linhas separadas
const MIN_FONT_SIZE_RATIO_FOR_HEADING = 1.3; // Aumentado para evitar falsos headings
const MAX_FONT_SIZE_VARIATION_IN_LINE = 1.15; // Reduzido para evitar merge de tamanhos diferentes
const RE_SLASH_SEP = /\s+\/\s+/;
const RE_DASH_SEP = /\s+[—–]{1,2}\s+/;
/* ──────────────────────────────────────────────────────────────
MÓDULO: LOGO INLINE (resolve bug de imagem quebrada no print)
Em vez de <img src="...">, usamos um logotipo tipográfico SVG
inline que sempre renderiza corretamente em qualquer contexto.
────────────────────────────────────────────────────────────── */
function buildLogoSVG(variant = 'light', size = 'header') {
// variant: 'light' = texto branco (fundos escuros)
// 'dark' = texto laranja (fundos claros)
// size: 'header' | 'footer'
const h = size === 'footer' ? '17' : '26';
const colors = variant === 'light'
? ['#81C458','#2ED9C3','#2D4F76','#E16E1A']
: ['#E16E1A','#E5B92B','#2D4F76','#2ED9C3'];
return `<svg height="${h}" viewBox="0 0 72 ${h === '17' ? '17' : '26'}" xmlns="http://www.w3.org/2000/svg" class="doc-header__logo-svg" aria-label="DOCS">
<text y="${h === '17' ? '13' : '20'}" font-family="'Nunito',sans-serif" font-weight="900" font-size="${h === '17' ? '14' : '22'}" letter-spacing="2" fill="url(#lgrd-${variant}-${size})">DOCS</text>
<defs>
<linearGradient id="lgrd-${variant}-${size}" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stop-color="${colors[0]}"/>
<stop offset="33%" stop-color="${colors[1]}"/>
<stop offset="66%" stop-color="${colors[2]}"/>
<stop offset="100%" stop-color="${colors[3]}"/>
</linearGradient>
</defs>
</svg>`;
}
function logoVariant(theme) {
return (theme === 'editorial' || theme === 'pdf') ? 'dark' : 'light';
}
/* ──────────────────────────────────────────────────────────────
MÓDULO: ASSETS EXTERNOS (ornamentos)
────────────────────────────────────────────────────────────── */
const ASSETS = {
degrade06: 'degradês-06.svg',
degrade07: 'degradês-07.svg',
};
/* Ornamento SVG inline (fallback caso asset não carregue) */
const SVG_STAR_ORNAMENT = `<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" class="doc-ornament doc-ornament--star" aria-hidden="true">
<polygon points="50,0 58,35 95,38 68,60 78,95 50,73 22,95 32,60 5,38 42,35" fill="url(#grd-orn-s)"/>
<defs><linearGradient id="grd-orn-s" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#81C458"/><stop offset="50%" stop-color="#2ED9C3"/><stop offset="100%" stop-color="#2D4F76"/>
</linearGradient></defs>
</svg>`;
const SVG_SWIRL_ORNAMENT = `<svg viewBox="0 0 200 120" xmlns="http://www.w3.org/2000/svg" class="doc-ornament doc-ornament--swirl" aria-hidden="true">
<path d="M10,80 C10,20 70,5 100,40 C130,75 170,20 190,50" fill="none" stroke="url(#grd-orn-sw)" stroke-width="16" stroke-linecap="round"/>
<defs><linearGradient id="grd-orn-sw" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stop-color="#E16E1A"/><stop offset="50%" stop-color="#81C458"/><stop offset="100%" stop-color="#2ED9C3"/>
</linearGradient></defs>
</svg>`;
/* ──────────────────────────────────────────────────────────────
DOM REFS
────────────────────────────────────────────────────────────── */
const $ = id => document.getElementById(id);
const els = {
docTypes: $('docTypes'),
themeOpts: $('themeOpts'),
themeDesc: $('themeDesc'),
fldTitle: $('fldTitle'),
fldSubtitle: $('fldSubtitle'),
fldDate: $('fldDate'),
fldVersion: $('fldVersion'),
fldAuthor: $('fldAuthor'),
fldDept: $('fldDept'),
fldSummary: $('fldSummary'),
fldNextSteps: $('fldNextSteps'),
sectionsList: $('sectionsList'),
highlightsList: $('highlightsList'),
addSectionBtn: $('addSectionBtn'),
addHighlightBtn: $('addHighlightBtn'),
generateBtn: $('generateBtn'),
exampleBtn: $('exampleBtn'),
printBtn: $('printBtn'),
stageHint: $('stageHint'),
docWrap: $('docWrap'),
// Import
importPdfBtn: $('importPdfBtn'),
pdfFileInput: $('pdfFileInput'),
importZone: $('importZone'),
dropZoneGlobal: $('dropZoneGlobal'),
loadingOverlay: $('loadingOverlay'),
loadingLabel: $('loadingLabel'),
// Review modal
reviewOverlay: $('reviewOverlay'),
reviewClose: $('reviewClose'),
reviewCancel: $('reviewCancel'),
reviewApply: $('reviewApply'),
reviewAddSec: $('reviewAddSec'),
reviewSectionsList: $('reviewSectionsList'),
reviewSubtitle: $('reviewSubtitle'),
reviewWarning: $('reviewWarning'),
reviewWarningText: $('reviewWarningText'),
reviewPageInfo: $('reviewPageInfo'),
rv_docType: $('rv_docType'),
rv_structureMode: $('rv_structureMode'),
rv_title: $('rv_title'),
rv_subtitle: $('rv_subtitle'),
rv_date: $('rv_date'),
rv_version: $('rv_version'),
rv_author: $('rv_author'),
rv_dept: $('rv_dept'),
rv_summary: $('rv_summary'),
rv_nextSteps:$('rv_nextSteps'),
rv_raw: $('rv_raw'),
};
/* ══════════════════════════════════════════════════════════════
MÓDULO: INIT — liga todos os eventos
══════════════════════════════════════════════════════════════ */
function init() {
/* ── Diagnóstico de ambiente — visível no console do browser ── */
console.info(
`%c[DOCS] JS carregado · versão ${window.DOC_WORKBENCH_VERSION}`,
'color:#2ED9C3;font-weight:700'
);
// pdf.js pode ainda estar carregando de forma assíncrona —
// o status real é consultado em handlePdfFile via _pdfJsReady
console.info(`[DOCS] pdf.js status inicial: ${window._gudiPdfJs?.status}`);
console.info(`[DOCS] setupDragDropZone: ${typeof setupDragDropZone}`);
if (typeof setupDragDropZone === 'undefined') {
console.error('[DOCS] CRÍTICO: setupDragDropZone não definida — versão errada do JS em execução!');
}
/* pdf.js worker já configurado por _initPdfJs() — não reconfigurar aqui */
/* ── Tipo de documento ──────────────────────────────────────── */
els.docTypes.addEventListener('click', e => {
const btn = e.target.closest('.doc-type');
if (!btn) return;
document.querySelectorAll('.doc-type').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
state.docType = btn.dataset.type;
if (els.docWrap.style.display !== 'none') generateDocument();
});
/* ── Tema visual ──────────────────────────────────────────── */
els.themeOpts.addEventListener('click', e => {
const btn = e.target.closest('.theme-card');
if (!btn) return;
document.querySelectorAll('.theme-card').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
state.theme = btn.dataset.theme;
if (els.themeDesc) els.themeDesc.innerHTML = THEME_DESCS[state.theme] || '';
// Aplica instantaneamente sem regenerar
const docEl = els.docWrap.querySelector('.gudi-doc');
if (docEl) {
docEl.dataset.theme = state.theme;
// Atualiza logos inline (eles são SVG, só troca a variante)
docEl.querySelectorAll('[data-logo-variant]').forEach(el => {
const sz = el.dataset.logoSize || 'header';
el.outerHTML = buildLogoSVG(logoVariant(state.theme), sz);
});
}
});
/* ── Seções e indicadores ──────────────────────────────────── */
els.addSectionBtn.addEventListener('click', () => addSection());
els.addHighlightBtn.addEventListener('click', () => addHighlight());
/* ── Gerar ─────────────────────────────────────────────────── */
els.generateBtn.addEventListener('click', generateDocument);
/* ── Exemplo ───────────────────────────────────────────────── */
els.exampleBtn.addEventListener('click', loadExample);
/* ── Exportar PDF — versão robusta (preserva cores no print) ── */
els.printBtn.addEventListener('click', async () => {
const btn = els.printBtn;
const orig = btn.innerHTML;
btn.innerHTML = 'Preparando…';
btn.disabled = true;
preparePrintMode();
try {
if (document.fonts?.ready) await document.fonts.ready;
await waitForAssetsReady(els.docWrap);
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
window.print();
} finally {
setTimeout(() => {
btn.innerHTML = orig;
btn.disabled = false;
cleanupPrintMode();
}, 300);
}
});
/* ── Import PDF: botão no header ──────────────────────────── */
els.importPdfBtn.addEventListener('click', () => els.pdfFileInput.click());
/* ── Import PDF: zona no painel ─────────────────────────────── */
els.importZone.addEventListener('click', () => els.pdfFileInput.click());
/* ── Input de arquivo ──────────────────────────────────────── */
els.pdfFileInput.addEventListener('change', e => {
const file = e.target.files[0];
if (file) handlePdfFile(file);
e.target.value = ''; // reset para permitir re-upload do mesmo arquivo
});
/* ── Drag and drop: zona do painel ─────────────────────────── */
setupDragDropZone(els.importZone);
runAutotestFromQuery();
/* ── Drag and drop: global (body) ──────────────────────────── */
let dragCount = 0;
document.addEventListener('dragenter', e => {
if (e.dataTransfer.types.includes('Files')) {
dragCount++;
els.dropZoneGlobal.style.display = 'flex';
}
});
document.addEventListener('dragleave', () => {
dragCount--;
if (dragCount <= 0) { dragCount = 0; els.dropZoneGlobal.style.display = 'none'; }
});
document.addEventListener('dragover', e => e.preventDefault());
document.addEventListener('drop', e => {
e.preventDefault();
dragCount = 0;
els.dropZoneGlobal.style.display = 'none';
const file = e.dataTransfer.files[0];
if (file && file.type === 'application/pdf') {
handlePdfFile(file);
} else if (file) {
showWarning('Apenas arquivos PDF são suportados para importação.');
}
});
/* ── Review modal ────────────────────────────────────────── */
els.reviewClose.addEventListener('click', closeReview);
els.reviewCancel.addEventListener('click', closeReview);
els.reviewApply.addEventListener('click', applyReviewToTemplate);
els.reviewOverlay.addEventListener('click', e => {
if (e.target === els.reviewOverlay) closeReview();
});
els.reviewAddSec.addEventListener('click', () => addReviewBlock({ type: 'generic', confidence: 'low', title: '', text: '', enabled: true }));
window.addEventListener('beforeprint', preparePrintMode);
window.addEventListener('afterprint', cleanupPrintMode);
const params = new URLSearchParams(window.location.search);
if (params.get('example') === '1') {
loadExample();
}
}
function setupDragDropZone(zone) {
zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('import-zone--active'); });
zone.addEventListener('dragleave', () => zone.classList.remove('import-zone--active'));
zone.addEventListener('drop', e => {
e.preventDefault(); zone.classList.remove('import-zone--active');
const file = e.dataTransfer.files[0];
if (file && file.type === 'application/pdf') handlePdfFile(file);
});
}
/* ══════════════════════════════════════════════════════════════
MÓDULO: IMPORTAÇÃO E EXTRAÇÃO DE PDF
Usa pdf.js para extração real de texto página por página
══════════════════════════════════════════════════════════════ */
async function handlePdfFile(file) {
if (!file || file.type !== 'application/pdf') {
showWarning('O arquivo selecionado não é um PDF válido.');
return;
}
showLoading('Carregando leitor de PDF…');
// ── Aguardar o carregamento dinâmico do pdf.js ─────────────────────────
// _pdfJsReady é a promise de _initPdfJs() lançada no topo do arquivo.
// Se o usuário clicou em importar logo após a página carregar,
// o CDN pode ainda não ter respondido — aguardamos aqui sem travar a UI.
try { await _pdfJsReady; } catch (_) { /* _initPdfJs nunca rejeita */ }
// ── Verificar resultado ────────────────────────────────────────────────
if (window._gudiPdfJs?.status !== 'ready' || !window.pdfjsLib) {
hideLoading();
const gudiStatus = window._gudiPdfJs?.status || 'desconhecido';
console.error(`[DOCS] pdf.js indisponível. Status: ${gudiStatus}`);
const isEdge = /Edg\//.test(navigator.userAgent);
const isFF = /Firefox\//.test(navigator.userAgent);
let msg;
if (gudiStatus === 'failed') {
msg = 'O leitor de PDF não carregou em nenhum servidor. '
+ 'Verifique sua conexão e recarregue (Ctrl+Shift+R). '
+ 'Redes corporativas podem bloquear CDNs externos.';
} else if (isEdge) {
msg = 'O leitor de PDF não carregou. O Edge pode estar bloqueando CDNs '
+ '(Tracking Prevention). Tente: Configurações → Privacidade → '
+ 'Prevenção de rastreamento → Básico. Ou abra em aba normal.';
} else if (isFF) {
msg = 'O leitor de PDF não carregou. O Firefox pode bloquear CDNs em modo Privativo. '
+ 'Abra em aba normal ou desative o bloqueio para este site.';
} else {
msg = 'O leitor de PDF não carregou. Recarregue a página e tente novamente. '
+ 'Se persistir, tente em outro navegador.';
}
showWarning(msg);
return;
}
setLoading('Lendo o arquivo PDF…');
try {
const arrayBuffer = await file.arrayBuffer();
setLoading('Extraindo texto do PDF…');
const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise;
const totalPages = pdf.numPages;
setLoading(`Processando ${totalPages} página(s)…`);
let fullText = '';
const pageTexts = [];
const pageStructures = [];
for (let i = 1; i <= totalPages; i++) {
setLoading(`Extraindo página ${i} de ${totalPages}…`);
const page = await pdf.getPage(i);
const content = await page.getTextContent();
const pageStructure = reconstructPageStructure(content.items, i);
const pageText = pageStructure.blocks.map(block => block.text).join('\n\n');
pageStructures.push(pageStructure);
pageTexts.push(pageText);
fullText += pageText + '\n\n';
}
hideLoading();
// ── Qualidade da extração ──────────────────────────────────────────
const charCount = fullText.trim().length;
let warning = null;
if (charCount === 0) {
warning = 'Nenhum texto extraído. O PDF provavelmente é uma imagem escaneada '
+ 'ou está protegido. Preencha os campos manualmente.';
} else if (charCount < 50) {
warning = 'Texto muito escasso. O PDF pode ser escaneado ou protegido. '
+ 'Revise e complete os campos antes de aplicar.';
} else if (charCount < 300) {
warning = 'Texto curto extraído. Pode haver conteúdo predominantemente visual. '
+ 'Revise o mapeamento antes de aplicar.';
}
const mapped = heuristicMap({
text: fullText,
pageTexts,
pageStructures,
filename: file.name,
selectedDocType: state.docType,
});
openReview(mapped, fullText, warning, totalPages);
} catch (err) {
hideLoading();
console.error('[DOCS] Erro durante extração de PDF:', err);
let userMsg;
const errMsg = (err.message || '').toLowerCase();
if (/password|encrypted/.test(errMsg)) {
userMsg = 'O PDF está protegido por senha. Remova a proteção antes de importar.';
} else if (err.name === 'UnknownErrorException' || /worker.*crash|worker.*terminat/.test(errMsg)) {
userMsg = 'O processador de PDF travou. Recarregue a página e tente novamente.';
} else if (/invalid pdf|missing pdf|not a pdf|unexpected end/.test(errMsg)) {
userMsg = 'O arquivo não é um PDF válido ou está corrompido.';
} else if (/network|fetch|failed to fetch|load failed/.test(errMsg)) {
userMsg = 'Falha de rede durante o processamento. Verifique sua conexão.';
} else if (/not defined|referenceerror/.test(errMsg)) {
userMsg = 'Erro interno: função não reconhecida. Force a recarga com Ctrl+Shift+R.';
} else {
userMsg = `Erro ao processar o PDF: ${err.message || 'erro desconhecido'}. `
+ 'Tente outro arquivo ou preencha os campos manualmente.';
}
openReviewWithError(userMsg, file.name);
}
}
function reconstructPageStructure(items, pageNumber) {
const lines = reconstructPdfLines(items);
const blocks = buildEditorialPipeline(lines, pageNumber);
return { pageNumber, lines, blocks };
}
function reconstructPdfLines(items) {
if (!items || items.length === 0) return [];
const filtered = items
.map(item => ({
text: cleanPdfToken(item.str || ''),
x: Number(item.transform?.[4] || 0),
y: Number(item.transform?.[5] || 0),
width: Number(item.width || 0),
height: Math.abs(Number(item.height || item.transform?.[0] || 0)) || 0,
fontName: item.fontName || '',
raw: item,
}))
.filter(item => item.text);
const sorted = filtered.sort((a, b) => {
const dy = Math.abs(b.y - a.y);
if (dy > 3) return b.y - a.y;
return a.x - b.x;
});
const lines = [];
for (const token of sorted) {
const target = lines.find(line => Math.abs(line.y - token.y) <= Math.max(2.5, Math.min(token.height || 0, 6)));
if (target) {
target.tokens.push(token);
target.y = (target.y + token.y) / 2;
target.maxHeight = Math.max(target.maxHeight, token.height || 0);
} else {
lines.push({
y: token.y,
maxHeight: token.height || 0,
tokens: [token],
});
}
}
return lines
.sort((a, b) => b.y - a.y)
.map((line, index, arr) => {
const tokens = line.tokens.sort((a, b) => a.x - b.x);
const text = joinPdfLineTokens(tokens);
const next = arr[index + 1];
return {
text,
y: line.y,
x: tokens[0]?.x || 0,
width: Math.max(0, (tokens[tokens.length - 1]?.x || 0) - (tokens[0]?.x || 0)),
fontSize: median(tokens.map(t => t.height).filter(Boolean)) || 0,
gapAfter: next ? Math.abs(line.y - next.y) : 0,
tokens,
};
})
.filter(line => line.text);
}
function cleanPdfToken(text) {
return String(text || '')
.replace(/\u00A0/g, ' ')
.replace(/[ \t]+/g, ' ')
.trim();
}
function joinPdfLineTokens(tokens) {
let out = '';
let prev = null;
for (const token of tokens) {
if (!token.text) continue;
if (!prev) {
out = token.text;
prev = token;
continue;
}
const gap = token.x - (prev.x + prev.width);
const noSpaceBefore = /^[,.;:!?%)\]}]/.test(token.text);
const noSpaceAfterPrev = /[(\[{\/-]$/.test(prev.text);
const needsSpace = gap > Math.max(1.5, (prev.height || 0) * 0.14) && !noSpaceBefore && !noSpaceAfterPrev;
out += `${needsSpace ? ' ' : ''}${token.text}`;
prev = token;
}
return normalizeImportedLine(out);
}
function normalizeImportedLine(text) {
return String(text || '')
.replace(/\s+([,.;:!?])/g, '$1')
.replace(/([(\[{])\s+/g, '$1')
.replace(/\s+/g, ' ')
.replace(/-\s+$/g, '-')
.trim();
}
function sanitizeEditorialLine(text) {
return normalizeImportedLine(String(text || '')
.replace(/\b(?:id|uuid|guid|field|label|name|value|type)\s*[:=]\s*[A-Za-z0-9_\-./]+/gi, ' ')
.replace(/\b(?:id|uuid|guid)\b$/i, ' ')
.replace(/\s+/g, ' '));
}
function buildEditorialPipeline(lines, pageNumber) {
const normalized = normalizeEditorialLines(lines);
const grouped = segmentRawEditorialBlocks(normalized, pageNumber);
const recomposed = grouped
.map((block, index) => finalizeEditorialBlock(recomposeHeadingLines(block.lines), index, pageNumber))
.filter(Boolean);
const fused = fuseOrphanEditorialBlocks(recomposed);
return dedupeEditorialBlocks(fused);
}
function normalizeEditorialLines(lines) {
const output = [];
for (const line of lines || []) {
const text = sanitizeEditorialLine(line?.text || '');
if (!text || isLikelyNoiseLine(text) || isTechnicalLeakLine(text)) continue;
output.push({
...line,
text,
lexicalDensity: estimateLexicalDensity(text),
uppercaseRatio: computeUppercaseRatio(text),
sentenceLike: isSentenceLike(text),
tableCandidate: isLikelyTabularLine(text),
headingCandidate: false,
});
}
const medianFont = median(output.map(item => item.fontSize).filter(Boolean)) || 10;
return output.map((line, index, arr) => ({
...line,
headingCandidate: isEditorialHeadingLine(line, arr[index + 1], arr[index - 1], medianFont),
}));
}
function segmentRawEditorialBlocks(lines, pageNumber) {
if (!lines.length) return [];
const blocks = [];
let current = null;
const bodyFont = median(lines.map(line => line.fontSize).filter(Boolean)) || 10;
const largeGap = Math.max(18, bodyFont * 1.7);
lines.forEach((line, index) => {
const next = lines[index + 1];
const prevLine = current?.lines?.[current.lines.length - 1] || null;
const blockBreak = !current
|| current.lastGap >= largeGap
|| shouldStartEditorialBlock(prevLine, line, next, bodyFont);
if (blockBreak) {
current = { page: pageNumber, lines: [], lastGap: 0 };
blocks.push(current);
}
current.lines.push(line);
current.lastGap = line.gapAfter;
});
return blocks.filter(block => block.lines.length);
}
function shouldStartEditorialBlock(prevLine, line, nextLine, bodyFont = 10) {
if (!prevLine || !line) return true;
const prevText = sanitizeEditorialLine(prevLine.text || '');
const text = sanitizeEditorialLine(line.text || '');
if (!prevText || !text) return true;
if (looksLikeBullet(text) || looksLikeStepLine(text)) return true;
// Tabular lines stay together with each other
const currentTabular = isLikelyTabularLine(text) || isLikelyTableHeaderLine(text);
const prevTabular = isLikelyTabularLine(prevText) || isLikelyTableHeaderLine(prevText);
if (currentTabular && prevTabular) return false;
// Mergeable heading continuations stay together
if (shouldMergeHeadingLines(prevLine, line, bodyFont)) return false;
// Strong heading (numbered or clearly uppercase non-tabular) starts a new block
const isHeading = isEditorialHeadingLine(line, nextLine, prevLine, bodyFont);
if (isHeading && (looksLikeNumberedHeading(text) || (computeUppercaseRatio(text) >= 0.6 && !currentTabular))) return true;
// Large gap starts new block (except between tabular lines already handled above)
const gap = Number(prevLine.gapAfter) || 0;
const largeGapThreshold = Math.max(18, Number(prevLine.fontSize || line.fontSize || bodyFont) * 1.5);
if (gap >= largeGapThreshold && !(currentTabular && (prevTabular || lineHasHeadingTraits(prevLine, bodyFont, line)))) return true;
return false;
}
function createFallbackStructure(pageLines, pageIndex, issues) {
// Fallback mais simples: agrupar linhas por proximidade sem tentar ser inteligente
const blocks = [];
const allText = pageLines.map(line => sanitizeEditorialLine(line.text || '')).filter(Boolean);
if (allText.length === 0) return [];
// Criar um único bloco genérico com todo o conteúdo
const combinedText = allText.join('\n');
// Se o texto for muito longo, tentar dividir em parágrafos
if (combinedText.length > 500) {
const paragraphs = splitTextIntoParagraphs(combinedText);
paragraphs.forEach((paragraph, index) => {
if (paragraph.trim()) {
blocks.push({
heading: '',
text: paragraph,
lines: [],
pageNumber: pageIndex + 1,
extractionQuality: 'poor',
fallbackMode: true,
fallbackReason: issues.join(',')
});
}
});
} else {
// Texto curto: um único bloco
blocks.push({
heading: '',
text: combinedText,
lines: pageLines,
pageNumber: pageIndex + 1,
extractionQuality: 'poor',
fallbackMode: true,
fallbackReason: issues.join(',')
});
}
return blocks;
}
function assessPageExtractionQuality(pageText, pageBlocks) {
if (!pageText || !pageText.trim()) return { quality: 'empty', confidence: 0, issues: ['empty_page'] };
const issues = [];
let confidence = 1.0;
// Verificar conteúdo muito curto (pode ser ruído)
if (pageText.length < 50) {
issues.push('very_short_content');
confidence -= 0.4;
}
// Verificar conteúdo fragmentado (muitas linhas curtas)
const lines = pageText.split('\n').filter(line => line.trim().length > 0);
const avgLineLength = lines.reduce((sum, line) => sum + line.length, 0) / lines.length;
if (avgLineLength < 20 && lines.length > 10) {
issues.push('fragmented_content');
confidence -= 0.3;
}
// Verificar proporção de ruído
const noiseLines = lines.filter(line => isLikelyNoiseLine(line)).length;
const noiseRatio = noiseLines / lines.length;
if (noiseRatio > 0.4) {
issues.push('high_noise_ratio');
confidence -= 0.3;
}
// Verificar se há blocos estruturais
const structuredBlocks = pageBlocks.filter(block =>
block.type === 'table' || block.type === 'matrix' || block.type === 'comparison'
).length;
if (structuredBlocks === 0 && pageText.length > 500) {
issues.push('no_structured_blocks');
confidence -= 0.2;
}
// Verificar se há headings detectados
const headingBlocks = pageBlocks.filter(block =>
block.heading || block.type === 'section'
).length;
if (headingBlocks === 0 && pageText.length > 300) {
issues.push('no_headings_detected');
confidence -= 0.1;
}
// Verificar se o conteúdo parece ser apenas metadata/ruído
if (looksLikeFooterCluster(pageText) || looksLikeMostlyHeaderFooter(pageBlocks)) {
issues.push('mostly_metadata');
confidence -= 0.5;
}
// Determinar qualidade final
let quality = 'good';
if (confidence < 0.3) quality = 'poor';
else if (confidence < 0.6) quality = 'moderate';
return { quality, confidence: Math.max(0, confidence), issues };
}
function heuristicMap({ text, pageTexts, pageStructures, filename, selectedDocType }) {
const lines = text.split('\n').map(l => l.trim()).filter(l => l.length > 0);
const blocks = (pageStructures || []).flatMap(page => page.blocks || []);
const extraction = assessExtractionQuality(text, blocks, pageTexts);
const result = {
title: '', subtitle: '', date: '', version: '', author: '', dept: '',
summary: '', nextSteps: '', docType: selectedDocType || 'relatorio', sections: [],
highlights: [],
blocks: [],
confidence: extraction.confidence,
extractionNotes: extraction.notes,
};
if (lines.length === 0) return result;
const titleCandidate = findTitleCandidate(blocks, lines, filename);
const subtitleCandidate = findSubtitleCandidate(blocks, titleCandidate?.text || '');
result.title = titleCandidate?.confidence === 'high' ? titleCandidate.text : filenameToTitle(filename);
result.subtitle = subtitleCandidate?.confidence !== 'low' ? subtitleCandidate.text : '';
result.date = findDate(text);
result.version = findVersion(text);
result.author = findAuthor(text);
result.dept = findDept(text);
const inferredDocType = inferDocType(text, result.title, blocks);
result.docType = selectedDocType || inferredDocType;
const classifiedBlocks = classifyBlocks(blocks, {
title: result.title,
subtitle: result.subtitle,
docType: result.docType,
text,
});
result.blocks = classifiedBlocks;
result.sections = classifiedBlocks
.filter(block => block.type === 'section' && block.enabled)
.slice(0, 12)
.map(block => ({
title: block.title || fallbackSectionTitle(block, result.docType),
body: block.text,
}));
result.summary = deriveSummaryFromBlocks(classifiedBlocks).slice(0, 900);
result.nextSteps = deriveNextStepsFromBlocks(classifiedBlocks).slice(0, 900);
result.highlights = classifiedBlocks
.filter(block => block.type === 'highlight' && block.enabled)
.slice(0, 4)
.map(block => extractHighlightFromBlock(block))
.filter(Boolean);
return result;
}
function classifyBlocks(blocks, context) {
return (blocks || []).map((block, index) => classifySingleBlock(block, index, context));
}
function classifySingleBlock(block, index, context) {
const text = (block.text || '').trim();
const firstLine = block.heading || block.firstLine || text.split('\n')[0] || '';
const normalizedFirstLine = normalizeHeadingText(firstLine).toLowerCase();
const lowered = text.toLowerCase();
let type = 'generic';
let confidence = 'medium';
let title = normalizeContentText(block.title || block.heading || '');
const enabled = block.enabled !== false;
// Classificação mais conservadora para evitar falsos positivos
// Summary - critérios mais restritos
if (normalizedFirstLine.includes('resumo') || normalizedFirstLine.includes('sumário') ||
normalizedFirstLine.includes('executivo') || normalizedFirstLine.includes('síntese')) {
if (text.length <= 800 && text.split('\n').length <= 6) {
type = 'summary';
confidence = text.length > 100 ? 'high' : 'medium';
}
}
// Next Steps - critérios mais restritos
else if (normalizedFirstLine.includes('próximos passos') || normalizedFirstLine.includes('próximo') ||
normalizedFirstLine.includes('ações') || normalizedFirstLine.includes('recomendações')) {
if (looksLikeExplicitStepBlock(text)) {
type = 'nextSteps';
confidence = 'high';
}
}
// Highlights - apenas se for claramente métrica
else if (looksLikeMetricBlock(text) && text.length <= 200) {
type = 'highlight';
confidence = 'high';
} else if (looksLikeComparisonBlock(text)) {
type = 'comparison';
confidence = 'medium';
} else if (looksLikeKeyValueBlock(text)) {
type = 'matrix';
confidence = 'medium';
} else if (/^(nota\b|observa[çc][aã]o|metodologia|nota metodol[oó]gica|crit[eé]rio de an[aá]lise|ressalva|limita[çc][oõ]es)/i.test(normalizedFirstLine)) {
type = 'note';
confidence = 'medium';
} else if (block.metricsLike && supportsHighlights(context.docType, lowered) && !looksLikeSummarySentence(text) && hasStrongHighlightEvidence(text)) {
type = 'highlight';
confidence = 'medium';
} else if ((block.strongHeading || /^(\d+[\.\)]|[IVXLC]+[\.\)])\s+/i.test(firstLine)) && !isEditorialMetadataBlock(firstLine)) {
type = 'section';
confidence = 'high';
title = firstLine;
} else if (index <= 1 && text.length >= 220 && text.length <= 1200 && !looksLikeFooterCluster(text) && supportsSummary(context.docType) && !looksLikeHeading(text)) {
type = 'summary';
confidence = 'low';
}
if (type === 'highlight' && !extractHighlightFromBlock({ text })) {
type = 'generic';
confidence = 'low';
}