@credithub/harlan-components 1.81.6 → 1.82.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -211,7 +211,6 @@ var ChartSystem = function (_a) {
211
211
  ? ultimaOcorrenciaSerasa
212
212
  : undefined
213
213
  };
214
- console.log('documentHistory', docHistory);
215
214
  return __assign(__assign({}, prev), { documentHistory: docHistory });
216
215
  });
217
216
  setDataUpdated(true);
@@ -1,14 +1,3 @@
1
- var __assign = (this && this.__assign) || function () {
2
- __assign = Object.assign || function(t) {
3
- for (var s, i = 1, n = arguments.length; i < n; i++) {
4
- s = arguments[i];
5
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6
- t[p] = s[p];
7
- }
8
- return t;
9
- };
10
- return __assign.apply(this, arguments);
11
- };
12
1
  var __rest = (this && this.__rest) || function (s, e) {
13
2
  var t = {};
14
3
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
@@ -32,14 +21,14 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
32
21
  /* eslint-disable @typescript-eslint/no-explicit-any */
33
22
  import { normalizeName, similarNames } from '../../../utils/similarNames';
34
23
  import { safeStringify } from './responseUtils';
24
+ // -----------------------------------------------------------------------------
25
+ // Helpers externos -------------------------------------------------------------
26
+ // -----------------------------------------------------------------------------
35
27
  export function flattenData(data) {
36
28
  var flattened = {};
37
29
  for (var key in data) {
38
30
  if (typeof data[key] === 'object' && !Array.isArray(data[key])) {
39
- var innerData = data[key];
40
- for (var innerKey in innerData) {
41
- flattened[innerKey] = innerData[innerKey];
42
- }
31
+ Object.assign(flattened, data[key]);
43
32
  }
44
33
  else {
45
34
  flattened[key] = data[key];
@@ -52,12 +41,7 @@ export function limitDataSize(items, maxItems) {
52
41
  return [];
53
42
  return items.slice(0, maxItems).map(function (item) {
54
43
  if (typeof item === 'object') {
55
- return Object.keys(item).reduce(function (limitedItem, key, index) {
56
- if (index < maxItems) {
57
- limitedItem[key] = item[key];
58
- }
59
- return limitedItem;
60
- }, {});
44
+ return Object.fromEntries(Object.entries(item).slice(0, maxItems));
61
45
  }
62
46
  return item;
63
47
  });
@@ -65,78 +49,145 @@ export function limitDataSize(items, maxItems) {
65
49
  function isEmptyObject(obj) {
66
50
  if (typeof obj !== 'object' || obj === null)
67
51
  return false;
68
- return Object.values(obj).every(function (value) { return isEmptyObject(value); });
52
+ // Remove a chave isLoaded antes de decidir se o objeto está “vazio”
53
+ var keys = Object.keys(obj).filter(function (k) { return k !== 'isLoaded'; });
54
+ if (!keys.length)
55
+ return true;
56
+ return keys.every(function (k) { return isEmptyObject(obj[k]); });
69
57
  }
70
58
  function deepCleanData(data) {
71
59
  if (typeof data !== 'object' || data === null)
72
60
  return data;
61
+ // Se o objeto contém apenas isLoaded, descarta-o de imediato
62
+ if (!Array.isArray(data) &&
63
+ Object.keys(data).length === 1 &&
64
+ 'isLoaded' in data) {
65
+ return null;
66
+ }
73
67
  if (Array.isArray(data)) {
74
- var cleanedArray = data
75
- .map(function (item) { return deepCleanData(item); })
76
- .filter(function (item) {
77
- return item !== null &&
78
- item !== undefined &&
79
- item !== '' &&
80
- !(Array.isArray(item) && item.length === 0);
68
+ var arr = data
69
+ .map(deepCleanData)
70
+ .filter(function (i) {
71
+ return i !== null &&
72
+ i !== undefined &&
73
+ i !== '' &&
74
+ !(Array.isArray(i) && i.length === 0);
81
75
  });
82
- return cleanedArray.length > 0 ? cleanedArray : null;
76
+ return arr.length ? arr : null;
83
77
  }
84
- var cleanedObject = Object.entries(data).reduce(function (acc, _a) {
85
- var key = _a[0], value = _a[1];
86
- if (key === 'props')
87
- return acc;
88
- var cleanedValue = deepCleanData(value);
89
- if (cleanedValue !== null &&
90
- cleanedValue !== undefined &&
91
- cleanedValue !== '' &&
92
- !(typeof cleanedValue === 'object' && isEmptyObject(cleanedValue))) {
93
- acc[key] = cleanedValue;
78
+ var obj = {};
79
+ for (var _i = 0, _a = Object.entries(data); _i < _a.length; _i++) {
80
+ var _b = _a[_i], k = _b[0], v = _b[1];
81
+ // ignora props e isLoaded
82
+ if (k === 'props' || k === 'isLoaded')
83
+ continue;
84
+ var cleaned = deepCleanData(v);
85
+ if (cleaned !== null &&
86
+ cleaned !== undefined &&
87
+ cleaned !== '' &&
88
+ !(typeof cleaned === 'object' && isEmptyObject(cleaned))) {
89
+ obj[k] = cleaned;
94
90
  }
95
- return acc;
96
- }, {});
97
- return Object.keys(cleanedObject).length > 0 ? cleanedObject : null;
91
+ }
92
+ return Object.keys(obj).length ? obj : null;
98
93
  }
94
+ // -----------------------------------------------------------------------------
95
+ // Main normaliser --------------------------------------------------------------
96
+ // -----------------------------------------------------------------------------
99
97
  export var selectRelevantData = function (data) {
100
- var _a, _b, _c, _d, _e, _f;
101
- var _g = data || {}, protestosDeCredito = _g.protestos, chequesSemFundo = _g.ccf, dividasPublicas = _g.dividasPublicas, contasBancarias = _g.bankAccounts, dadosDeChequesSemFundo = _g.ccfData, dividas = _g.divida, _h = _g.dossie, dossie = _h === void 0 ? {} : _h, liminar = _g.liminar, socios = _g.partners, dadosPessoasExpostasPoliticamente = _g.pepData, detalhesProcessosJuridicos = _g.processosJuridicosData, dadosReclameAqui = _g.reclameAqui, relatoriosRefinBoaVista = _g.refinBoaVista, relatoriosRefinSerasa = _g.refinSerasa, dadosScore = _g.scoreData, relatoriosSCR = _g.scr, registrosDeVeiculos = _g.veiculos, ResumoDosDados = _g.documentHistory;
102
- var _j = ResumoDosDados !== null && ResumoDosDados !== void 0 ? ResumoDosDados : {}, _omit = _j.protestoLiminar, ResumoDosDadosSafe = __rest(_j, ["protestoLiminar"]);
103
- if ((ResumoDosDadosSafe === null || ResumoDosDadosSafe === void 0 ? void 0 : ResumoDosDadosSafe.protestoHistory) &&
104
- Array.isArray(ResumoDosDadosSafe.protestoHistory) &&
105
- ResumoDosDadosSafe.protestoHistory.length) {
106
- var latest = __spreadArray([], ResumoDosDadosSafe.protestoHistory, true).sort(function (a, b) { return new Date(b.data).getTime() - new Date(a.data).getTime(); })[0];
107
- ResumoDosDadosSafe.protestoHistory = [latest];
98
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
99
+ var _l = data || {}, protestosNumero = _l.protestos, ccfNumero = _l.ccf, dividasPublicas = _l.dividasPublicas, contasBancarias = _l.bankAccounts, ccfData = _l.ccfData, dividas = _l.divida, _m = _l.dossie, dossie = _m === void 0 ? {} : _m, liminar = _l.liminar, socios = _l.partners, dadosPessoasExpostasPoliticamente = _l.pepData, detalhesProcessosJuridicos = _l.processosJuridicosData, dadosReclameAqui = _l.reclameAqui, refinBoaVista = _l.refinBoaVista, refinSerasa = _l.refinSerasa, dadosScore = _l.scoreData, _o = _l.scr, scr = _o === void 0 ? { isLoaded: false } : _o, _p = _l.veiculos, veiculos = _p === void 0 ? [] : _p, ResumoDosDados = _l.documentHistory;
100
+ // ────────────────────────────────────────────────
101
+ // 1. Protestos somente a entrada mais recente
102
+ // ────────────────────────────────────────────────
103
+ var _q = ResumoDosDados !== null && ResumoDosDados !== void 0 ? ResumoDosDados : {}, _omit = _q.protestoLiminar, ResumoSafe = __rest(_q, ["protestoLiminar"]);
104
+ var protestosData = [];
105
+ if (Array.isArray(ResumoSafe === null || ResumoSafe === void 0 ? void 0 : ResumoSafe.protestoHistory) &&
106
+ ResumoSafe.protestoHistory.length) {
107
+ var latest = __spreadArray([], ResumoSafe.protestoHistory, true).sort(function (a, b) { return new Date(b.data).getTime() - new Date(a.data).getTime(); })[0];
108
+ protestosData = [latest];
109
+ // 💡 mantém histórico enxuto também em ResumoSafe
110
+ ResumoSafe.protestoHistory = [latest];
111
+ }
112
+ if (!protestosData.length &&
113
+ typeof protestosNumero === 'number' &&
114
+ protestosNumero > 0) {
115
+ protestosData = [{ quantidade: protestosNumero }];
108
116
  }
109
- var tipoPessoa = ((_b = (_a = dossie === null || dossie === void 0 ? void 0 : dossie.carousel) === null || _a === void 0 ? void 0 : _a.document) === null || _b === void 0 ? void 0 : _b.replace(/\D/g, '').length) === 11
117
+ // ────────────────────────────────────────────────
118
+ // 2. Processos jurídicos – ativos + passivos
119
+ // ────────────────────────────────────────────────
120
+ var empresaNomeNorm = normalizeName((_a = dossie.carousel) === null || _a === void 0 ? void 0 : _a.name);
121
+ var processar = function (tipo) {
122
+ var _a, _b;
123
+ return (_b = (_a = detalhesProcessosJuridicos === null || detalhesProcessosJuridicos === void 0 ? void 0 : detalhesProcessosJuridicos.empresa) === null || _a === void 0 ? void 0 : _a.filter(function (p) {
124
+ var _a;
125
+ return (_a = p.envolvidos_ultima_movimentacao) === null || _a === void 0 ? void 0 : _a.some(function (e) {
126
+ return e.envolvido_tipo === tipo &&
127
+ similarNames(normalizeName(e.nome_sem_filtro), empresaNomeNorm);
128
+ });
129
+ })) === null || _b === void 0 ? void 0 : _b.map(function (p) { return ({
130
+ assuntos: p.assuntos,
131
+ classe_processual: p.classe_processual,
132
+ diario_sigla: p.diario_sigla,
133
+ updated_at: p.updated_at
134
+ }); });
135
+ };
136
+ var processosAtivos = (_b = processar('Ativo')) !== null && _b !== void 0 ? _b : [];
137
+ var processosPassivos = (_c = processar('Passivo')) !== null && _c !== void 0 ? _c : [];
138
+ var ProcessosJuridicos = __spreadArray(__spreadArray([], processosAtivos, true), processosPassivos, true);
139
+ var quantidadeProcessosJuridicos = ProcessosJuridicos.length;
140
+ // ────────────────────────────────────────────────
141
+ // 3. Liminar
142
+ // ────────────────────────────────────────────────
143
+ var liminarInfo = (liminar === null || liminar === void 0 ? void 0 : liminar.descricaoLiminar) || ((_e = (_d = liminar === null || liminar === void 0 ? void 0 : liminar.origensLiminar) === null || _d === void 0 ? void 0 : _d.length) !== null && _e !== void 0 ? _e : 0)
144
+ ? { descricao: liminar.descricaoLiminar, origens: liminar.origensLiminar }
145
+ : undefined;
146
+ // ────────────────────────────────────────────────
147
+ // 4. Tipo de pessoa
148
+ // ────────────────────────────────────────────────
149
+ var tipoPessoa = ((_g = (_f = dossie === null || dossie === void 0 ? void 0 : dossie.carousel) === null || _f === void 0 ? void 0 : _f.document) === null || _g === void 0 ? void 0 : _g.replace(/\D/g, '').length) === 11
110
150
  ? 'Pessoa Física'
111
151
  : 'Pessoa Jurídica';
112
- var sociosAnonimizados = (_c = socios === null || socios === void 0 ? void 0 : socios.partners) === null || _c === void 0 ? void 0 : _c.map(function (socio, index) { return ({
113
- nome: "S\u00F3cio ".concat(index + 1),
114
- cargo: socio.cargo,
115
- receitaStatus: socio.receitaStatus || {},
116
- dividasPublicas: socio.dividasPublicas || {},
117
- protestos: socio.protestos || {}
118
- }); });
119
- var empresaNomeNormalizado = normalizeName((_d = dossie.carousel) === null || _d === void 0 ? void 0 : _d.name);
120
- var processosPassivos = (_f = (_e = detalhesProcessosJuridicos === null || detalhesProcessosJuridicos === void 0 ? void 0 : detalhesProcessosJuridicos.empresa) === null || _e === void 0 ? void 0 : _e.filter(function (processo) {
121
- var _a;
122
- return (_a = processo.envolvidos_ultima_movimentacao) === null || _a === void 0 ? void 0 : _a.some(function (envolvido) {
123
- var nomeNormalizado = normalizeName(envolvido.nome_sem_filtro);
124
- return (similarNames(nomeNormalizado, empresaNomeNormalizado) &&
125
- envolvido.envolvido_tipo === 'Passivo');
152
+ // ────────────────────────────────────────────────
153
+ // 5. Sócios anonimizados
154
+ // ────────────────────────────────────────────────
155
+ var sociosAnonimizados = (_h = socios === null || socios === void 0 ? void 0 : socios.partners) === null || _h === void 0 ? void 0 : _h.map(function (s, i) {
156
+ var _a, _b, _c;
157
+ return ({
158
+ nome: "S\u00F3cio ".concat(i + 1),
159
+ cargo: s.cargo,
160
+ receitaStatus: (_a = s.receitaStatus) !== null && _a !== void 0 ? _a : {},
161
+ dividasPublicas: (_b = s.dividasPublicas) !== null && _b !== void 0 ? _b : {},
162
+ protestos: (_c = s.protestos) !== null && _c !== void 0 ? _c : {}
126
163
  });
127
- })) === null || _f === void 0 ? void 0 : _f.map(function (processo) { return ({
128
- assuntos: processo.assuntos,
129
- classe_processual: processo.classe_processual,
130
- diario_sigla: processo.diario_sigla,
131
- updated_at: processo.updated_at
132
- }); });
133
- var resumoDaEmpresa = dossie.summary;
134
- var statusLiminar = (liminar === null || liminar === void 0 ? void 0 : liminar.indiciosDeLiminar)
135
- ? 'Indício de Liminar para Ocultar Protestos'
136
- : undefined;
137
- var dadosOrganizados = __assign(__assign({ protestosDeCredito: protestosDeCredito, processosJuridicosPassivos: processosPassivos, chequesSemFundo: chequesSemFundo, dividasPublicas: dividasPublicas, contasBancarias: contasBancarias, dadosDeChequesSemFundo: dadosDeChequesSemFundo, dividas: dividas, resumoDaEmpresa: resumoDaEmpresa }, (statusLiminar && { liminar: statusLiminar })), { socios: sociosAnonimizados, dadosPessoasExpostasPoliticamente: dadosPessoasExpostasPoliticamente, dadosReclameAqui: dadosReclameAqui, relatoriosRefinBoaVista: relatoriosRefinBoaVista, relatoriosRefinSerasa: relatoriosRefinSerasa, dadosScore: dadosScore, relatoriosSCR: relatoriosSCR, registrosDeVeiculos: registrosDeVeiculos, ResumoDosDados: ResumoDosDadosSafe, tipoPessoa: tipoPessoa });
138
- var dadosFiltrados = deepCleanData(dadosOrganizados);
139
- return {
140
- dadosFiltrados: dadosFiltrados
164
+ });
165
+ // ────────────────────────────────────────────────
166
+ // 6. Construção final
167
+ // ────────────────────────────────────────────────
168
+ var dadosOrganizados = {
169
+ protestosData: protestosData,
170
+ quantidadeProtestos: (_j = ResumoSafe === null || ResumoSafe === void 0 ? void 0 : ResumoSafe.quantidadeProtestos) !== null && _j !== void 0 ? _j : protestosData.length,
171
+ ccf: (_k = ccfNumero !== null && ccfNumero !== void 0 ? ccfNumero : ResumoSafe === null || ResumoSafe === void 0 ? void 0 : ResumoSafe.quantidadeChequesSemFundos) !== null && _k !== void 0 ? _k : 0,
172
+ ccfData: ccfData !== null && ccfData !== void 0 ? ccfData : {},
173
+ dividasPublicas: dividasPublicas,
174
+ liminar: liminarInfo,
175
+ ProcessosJuridicos: ProcessosJuridicos,
176
+ quantidadeProcessosJuridicos: quantidadeProcessosJuridicos,
177
+ refinBoaVista: refinBoaVista !== null && refinBoaVista !== void 0 ? refinBoaVista : [],
178
+ refinSerasa: refinSerasa !== null && refinSerasa !== void 0 ? refinSerasa : [],
179
+ scr: scr,
180
+ veiculos: veiculos,
181
+ bankAccounts: contasBancarias,
182
+ dividas: dividas,
183
+ resumoDaEmpresa: dossie.summary,
184
+ socios: sociosAnonimizados,
185
+ dadosPessoasExpostasPoliticamente: dadosPessoasExpostasPoliticamente,
186
+ dadosReclameAqui: dadosReclameAqui,
187
+ dadosScore: dadosScore,
188
+ ResumoDosDados: ResumoSafe,
189
+ tipoPessoa: tipoPessoa
141
190
  };
191
+ var dadosFiltrados = deepCleanData(dadosOrganizados);
192
+ return { dadosFiltrados: dadosFiltrados };
142
193
  };
@@ -65,6 +65,7 @@ import StatusMessage from '../../../components/interface/statusMessage';
65
65
  import { useStreamQuery } from '../../../components/streamQuery';
66
66
  import { useGlobalData } from '../../../contexts/globalDataContext';
67
67
  import useToggle from '../../../hooks/useToggle';
68
+ import { isGlobalReady } from '../../../utils/isGlobalReady';
68
69
  import React, { useEffect, useMemo, useRef, useState } from 'react';
69
70
  import ReactMarkdown from 'react-markdown';
70
71
  import remarkGfm from 'remark-gfm';
@@ -89,29 +90,23 @@ var GenerativeAI = function (_a) {
89
90
  var lastQueryRef = useRef(null);
90
91
  var lastUserMessageRef = useRef(null);
91
92
  var messageHistoryRef = useRef(null);
92
- // Verifica se os dados globais estão carregados
93
- var isGlobalDataLoaded = useMemo(function () {
94
- return (globalData.documentHistory !== undefined &&
95
- globalData.documentHistory !== null);
96
- }, [globalData]);
93
+ var isGlobalDataReady = useMemo(function () { return isGlobalReady(globalData); }, [globalData]);
97
94
  // Atualiza o payload serializado sempre que os dados globais mudarem
98
95
  useEffect(function () {
99
- if (globalData && documento && isGlobalDataLoaded) {
96
+ if (globalData && documento && isGlobalDataReady) {
100
97
  try {
101
98
  var relevantData = selectRelevantData(globalData);
102
99
  var serialized = flattenData(relevantData);
103
- if (serialized !== serializedData) {
100
+ if (serialized !== serializedData)
104
101
  setSerializedData(serialized);
105
- }
106
102
  }
107
- catch (error) {
108
- console.error('Erro ao preparar os dados para a API:', error);
109
- if (serializedData !== '{}') {
103
+ catch (err) {
104
+ console.error('Erro ao preparar dados para IA:', err);
105
+ if (serializedData !== '{}')
110
106
  setSerializedData('{}');
111
- }
112
107
  }
113
108
  }
114
- }, [documento, globalData, isGlobalDataLoaded, serializedData]);
109
+ }, [documento, globalData, isGlobalDataReady, serializedData]);
115
110
  // Deriva o payload para a consulta summary a partir do serializedData.
116
111
  // Incluímos o refreshKey para forçar a atualização da query.
117
112
  var summaryQueryData = useMemo(function () {
@@ -49,19 +49,19 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
49
49
  import ProtestosIcon from '../../assets/icones/protestos';
50
50
  import { useGlobalData } from '../../contexts/globalDataContext';
51
51
  import theme from '../../styles/theme';
52
+ import { formatMoney } from '../../utils/number';
52
53
  import { normalizeName, similarNames } from '../../utils/similarNames';
54
+ import { hasOneOfTags } from '../../utils/tags';
53
55
  import { WarningCircle } from 'phosphor-react';
54
56
  import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
55
57
  import Button from '../common/button';
56
58
  import Modal from '../common/modal';
59
+ import { SummaryButton } from '../dossie/summary/styles';
57
60
  import StatusMessage from '../interface/statusMessage';
58
61
  import Section from '../section';
59
62
  import { Queries, RequestStatus, useFetch } from '../webservice';
60
63
  import { TitleWithTooltip, TooltipContainer, TooltipText } from './liminarStyles';
61
64
  import useLiminarProtestosDoPassado from './useLiminarProtestosDoPassado';
62
- import { hasOneOfTags } from '../../utils/tags';
63
- import { SummaryButton } from '../dossie/summary/styles';
64
- import { formatMoney } from '../../utils/number';
65
65
  /* ----------------------------------
66
66
  * Constantes
67
67
  * ---------------------------------*/
@@ -184,7 +184,7 @@ var Liminar = function (_a) {
184
184
  ]), origensDetectadas = _w.origensDetectadas, foundBusinessEntity = _w.foundBusinessEntity;
185
185
  useEffect(function () {
186
186
  var fetch = function () { return __awaiter(void 0, void 0, void 0, function () {
187
- var dossie, processosJuridicos, depsLoaded, newIds, hash, indiciosApi, indiciosDeLiminarProtestosDoPassado, protestosDoPassadoIds, _a, possuiIndiciosDeLiminarProtestosDoPassado, protestosIds, finalStatus;
187
+ var dossie, processosJuridicos, depsLoaded, newIds, hash, indiciosApi, indiciosDeLiminarProtestosDoPassado, protestosDoPassadoIds, _a, possuiIndiciosDeLiminarProtestosDoPassado, protestosIds, finalStatus, descricaoLiminar;
188
188
  var _b, _c, _d;
189
189
  return __generator(this, function (_e) {
190
190
  switch (_e.label) {
@@ -231,6 +231,11 @@ var Liminar = function (_a) {
231
231
  ? 'Encontrado'
232
232
  : 'Não encontrado';
233
233
  invertedIdsRef.current = newIds;
234
+ descricaoLiminar = origensDetectadas.length
235
+ ? "Liminar encontrada ".concat(origensDetectadas
236
+ .map(function (o) { return o.replace(/^Liminar (no|na) /, 'no '); })
237
+ .join(', '))
238
+ : 'Não encontrado';
234
239
  setData(function (prev) { return (__assign(__assign({}, prev), { liminar: {
235
240
  indiciosDeLiminar: indiciosApi || indiciosDeLiminarProtestosDoPassado,
236
241
  message: finalStatus,
@@ -238,7 +243,9 @@ var Liminar = function (_a) {
238
243
  processosComLiminarIds: processosComAssuntoValido.map(function (p) { return p.id; }),
239
244
  indiciosDeLiminarProtestosDoPassado: indiciosDeLiminarProtestosDoPassado,
240
245
  protestosDoPassadoIds: protestosDoPassadoIds,
241
- invertedProcessos: newIds
246
+ invertedProcessos: newIds,
247
+ origensLiminar: origensDetectadas,
248
+ descricaoLiminar: descricaoLiminar
242
249
  } })); });
243
250
  processedRef.current = true;
244
251
  return [2 /*return*/];
@@ -343,7 +350,7 @@ var Liminar = function (_a) {
343
350
  color: '#007aff'
344
351
  } }, p.id)); }))))))), subtitle: "Ind\u00EDcios de liminares para oculta\u00E7\u00E3o de registros.", icon: ProtestosIcon, ctx: ready ? ctx : ctxLoading, onSuccess: ready
345
352
  ? function (_data, _context) {
346
- var _a, _b, _c, _d;
353
+ var _a, _b, _c, _d, _e, _f;
347
354
  var msg = (_b = (_a = globalData === null || globalData === void 0 ? void 0 : globalData.liminar) === null || _a === void 0 ? void 0 : _a.message) !== null && _b !== void 0 ? _b : 'Não encontrado';
348
355
  var variant = msg === 'Encontrado' ? 'error' : 'default';
349
356
  return {
@@ -354,7 +361,10 @@ var Liminar = function (_a) {
354
361
  origensDetectadas.map(function (o) { return (React.createElement(StatusMessage, { key: o, type: variant }, o)); }))),
355
362
  actions: (React.createElement("div", { style: { textAlign: 'center' }, onClick: function (e) { return e.stopPropagation(); } }, isFinancial &&
356
363
  ((_c = globalData === null || globalData === void 0 ? void 0 : globalData.liminar) === null || _c === void 0 ? void 0 : _c.indiciosDeLiminarProtestosDoPassado) &&
357
- ((_d = globalData === null || globalData === void 0 ? void 0 : globalData.liminar) === null || _d === void 0 ? void 0 : _d.protestosDoPassadoIds) && (React.createElement(SummaryButton, { onClick: handleSendEmailIndicios, disabled: isEmailSending, smallContent: liminarMailPrice && !isEmailSending ? formatMoney(liminarMailPrice / 1000) : '' }, "Baixar Protestos Ocultos"))))
364
+ /** mostra o botão apenas se existir ao menos 1 chave oculta */
365
+ ((_f = (_e = (_d = globalData === null || globalData === void 0 ? void 0 : globalData.liminar) === null || _d === void 0 ? void 0 : _d.protestosDoPassadoIds) === null || _e === void 0 ? void 0 : _e.length) !== null && _f !== void 0 ? _f : 0) > 0 && (React.createElement(SummaryButton, { onClick: handleSendEmailIndicios, disabled: isEmailSending, smallContent: liminarMailPrice && !isEmailSending
366
+ ? formatMoney(liminarMailPrice / 1000)
367
+ : '' }, "Baixar Protestos Ocultos"))))
358
368
  };
359
369
  }
360
370
  : undefined }),
@@ -1,10 +1,21 @@
1
1
  interface LiminarProtestosDoPassadoProps {
2
+ /** CNPJ/CPF analisado para detectar instrumentos de protesto que sumiram do CENPROT */
2
3
  documento: string;
3
4
  }
5
+ /**
6
+ * Hook que identifica indícios de liminar de sustação de protesto.
7
+ *
8
+ * Regras (2025‑07‑01)
9
+ * • Um instrumento é **oculto** se a consulta a `PDFPROTESTO.PDF` **não** retornar PDF.
10
+ * • Se todos ainda possuem PDF, não há indício de liminar.
11
+ *
12
+ * Esta versão limita a concorrência (10 chamadas em paralelo) e aplica
13
+ * timeout defensivo para cada requisição.
14
+ */
4
15
  declare const useLiminarProtestosDoPassado: ({ documento }: LiminarProtestosDoPassadoProps) => {
5
- fetchLiminarProtestosDoPassado: () => Promise<{
6
- possuiIndiciosDeLiminarProtestosDoPassado: boolean;
7
- protestosDoPassadoIds: string[];
16
+ readonly fetchLiminarProtestosDoPassado: () => Promise<{
17
+ readonly possuiIndiciosDeLiminarProtestosDoPassado: boolean;
18
+ readonly protestosDoPassadoIds: string[];
8
19
  }>;
9
20
  };
10
21
  export default useLiminarProtestosDoPassado;
@@ -38,55 +38,54 @@ import XPathUtils from '../../utils/xpath';
38
38
  import { Client } from '@credithub/webservice';
39
39
  import { useCallback, useContext } from 'react';
40
40
  import { WebService } from '../webservice';
41
+ /**
42
+ * Hook que identifica indícios de liminar de sustação de protesto.
43
+ *
44
+ * Regras (2025‑07‑01)
45
+ * • Um instrumento é **oculto** se a consulta a `PDFPROTESTO.PDF` **não** retornar PDF.
46
+ * • Se todos ainda possuem PDF, não há indício de liminar.
47
+ *
48
+ * Esta versão limita a concorrência (10 chamadas em paralelo) e aplica
49
+ * timeout defensivo para cada requisição.
50
+ */
41
51
  var useLiminarProtestosDoPassado = function (_a) {
42
52
  var documento = _a.documento;
43
53
  var client = useContext(WebService);
44
- var getAlgumInstrumentoPossuiPDF = function (numerosChave) { return __awaiter(void 0, void 0, void 0, function () {
45
- var getNumeroChave, i, chunk, results;
46
- return __generator(this, function (_a) {
47
- switch (_a.label) {
54
+ /** Máximo de requisições simultâneas ao endpoint de PDF. */
55
+ var MAX_CONCURRENT = 10;
56
+ /** Timeout (ms) por requisição individual ao PDF. */
57
+ var PDF_TIMEOUT = 8000;
58
+ /**
59
+ * Checa se um `nm_chave` ainda possui PDF no CENPROT.
60
+ * Retorna `true` quando há PDF, `false` caso contrário ou erro.
61
+ */
62
+ var possuiPdf = function (nm_chave) { return __awaiter(void 0, void 0, void 0, function () {
63
+ var ctrl, timer, response, _a;
64
+ return __generator(this, function (_b) {
65
+ switch (_b.label) {
48
66
  case 0:
49
- getNumeroChave = function (numeroChave) { return __awaiter(void 0, void 0, void 0, function () {
50
- var response, _a;
51
- return __generator(this, function (_b) {
52
- switch (_b.label) {
53
- case 0:
54
- _b.trys.push([0, 3, , 4]);
55
- return [4 /*yield*/, client.request("SELECT FROM 'PDFPROTESTO'.'PDF'", {
56
- nm_chave: numeroChave,
57
- documento: documento
58
- })];
59
- case 1:
60
- response = _b.sent();
61
- return [4 /*yield*/, response.json()];
62
- case 2: return [2 /*return*/, !!(_b.sent())];
63
- case 3:
64
- _a = _b.sent();
65
- return [2 /*return*/, false];
66
- case 4: return [2 /*return*/];
67
- }
68
- });
69
- }); };
70
- i = 0;
71
- _a.label = 1;
67
+ ctrl = new AbortController();
68
+ timer = setTimeout(function () { return ctrl.abort(); }, PDF_TIMEOUT);
69
+ _b.label = 1;
72
70
  case 1:
73
- if (!(i < numerosChave.length)) return [3 /*break*/, 4];
74
- chunk = numerosChave.slice(i, i + 5);
75
- return [4 /*yield*/, Promise.all(chunk.map(getNumeroChave))];
71
+ _b.trys.push([1, 4, 5, 6]);
72
+ return [4 /*yield*/, client.request("SELECT FROM 'PDFPROTESTO'.'PDF'", { nm_chave: nm_chave, documento: documento }, undefined, ctrl.signal)];
76
73
  case 2:
77
- results = _a.sent();
78
- if (results.includes(true))
79
- return [2 /*return*/, true];
80
- _a.label = 3;
81
- case 3:
82
- i += 5;
83
- return [3 /*break*/, 1];
84
- case 4: return [2 /*return*/, false];
74
+ response = _b.sent();
75
+ return [4 /*yield*/, response.json()];
76
+ case 3: return [2 /*return*/, !!(_b.sent())];
77
+ case 4:
78
+ _a = _b.sent();
79
+ return [2 /*return*/, false]; // considera oculto se erro ou timeout
80
+ case 5:
81
+ clearTimeout(timer);
82
+ return [7 /*endfinally*/];
83
+ case 6: return [2 /*return*/];
85
84
  }
86
85
  });
87
86
  }); };
88
87
  var fetch = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () {
89
- var data, parsed, nodes, numerosChave, possuiIndiciosDeLiminarProtestosDoPassado;
88
+ var data, parsed, nodes, numerosChave, ocultos, idx, running, launch, _loop_1;
90
89
  return __generator(this, function (_a) {
91
90
  switch (_a.label) {
92
91
  case 0: return [4 /*yield*/, client.request("SELECT FROM 'IEPTB'.'PASTQUERIES'", {
@@ -98,17 +97,48 @@ var useLiminarProtestosDoPassado = function (_a) {
98
97
  case 2:
99
98
  parsed = (_a.sent());
100
99
  nodes = XPathUtils.selectArray('//protesto/nm_chave', parsed);
101
- numerosChave = Array.from(new Set(nodes.map(function (node) { return node.textContent || ''; })));
102
- return [4 /*yield*/, getAlgumInstrumentoPossuiPDF(numerosChave)];
100
+ numerosChave = Array.from(new Set(nodes.map(function (n) { return n.textContent || ''; })));
101
+ ocultos = [];
102
+ idx = 0;
103
+ running = [];
104
+ launch = function (chave) { return __awaiter(void 0, void 0, void 0, function () {
105
+ return __generator(this, function (_a) {
106
+ switch (_a.label) {
107
+ case 0: return [4 /*yield*/, possuiPdf(chave)];
108
+ case 1:
109
+ if (!(_a.sent()))
110
+ ocultos.push(chave);
111
+ return [2 /*return*/];
112
+ }
113
+ });
114
+ }); };
115
+ _a.label = 3;
103
116
  case 3:
104
- possuiIndiciosDeLiminarProtestosDoPassado = _a.sent();
105
- return [2 /*return*/, {
106
- possuiIndiciosDeLiminarProtestosDoPassado: possuiIndiciosDeLiminarProtestosDoPassado,
107
- protestosDoPassadoIds: numerosChave
108
- }];
117
+ if (!(idx < numerosChave.length || running.length)) return [3 /*break*/, 6];
118
+ _loop_1 = function () {
119
+ var p = launch(numerosChave[idx++]).finally(function () {
120
+ var i = running.indexOf(p);
121
+ if (i >= 0)
122
+ running.splice(i, 1);
123
+ });
124
+ running.push(p);
125
+ };
126
+ while (idx < numerosChave.length && running.length < MAX_CONCURRENT) {
127
+ _loop_1();
128
+ }
129
+ if (!running.length) return [3 /*break*/, 5];
130
+ return [4 /*yield*/, Promise.race(running)];
131
+ case 4:
132
+ _a.sent();
133
+ _a.label = 5;
134
+ case 5: return [3 /*break*/, 3];
135
+ case 6: return [2 /*return*/, {
136
+ possuiIndiciosDeLiminarProtestosDoPassado: ocultos.length > 0,
137
+ protestosDoPassadoIds: ocultos
138
+ }];
109
139
  }
110
140
  });
111
- }); }, [documento]);
141
+ }); }, [client, documento]);
112
142
  return { fetchLiminarProtestosDoPassado: fetch };
113
143
  };
114
144
  export default useLiminarProtestosDoPassado;
@@ -0,0 +1,2 @@
1
+ import { GlobalState } from '@/types/globalState.d';
2
+ export declare const isGlobalReady: (g: GlobalState) => boolean | undefined;
@@ -0,0 +1,9 @@
1
+ export var isGlobalReady = function (g) {
2
+ var _a, _b, _c, _d, _e;
3
+ return !!g.documentHistory && // veio do dossiê
4
+ ((_a = g.liminar) === null || _a === void 0 ? void 0 : _a.isLoaded) &&
5
+ ((_b = g.processosJuridicosData) === null || _b === void 0 ? void 0 : _b.isLoaded) &&
6
+ ((_c = g.protestosData) === null || _c === void 0 ? void 0 : _c.isLoaded) &&
7
+ ((_d = g.ccfData) === null || _d === void 0 ? void 0 : _d.isLoaded) &&
8
+ ((_e = g.divida) === null || _e === void 0 ? void 0 : _e.isLoaded);
9
+ };