@credithub/harlan-components 1.115.0 → 1.115.2

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.
@@ -36,7 +36,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
36
36
  };
37
37
  export function sendInstrumentoManualEmail(client, payload) {
38
38
  return __awaiter(this, void 0, void 0, function () {
39
- var res;
39
+ var response, json;
40
40
  return __generator(this, function (_a) {
41
41
  switch (_a.label) {
42
42
  case 0: return [4 /*yield*/, client.request("INSERT INTO 'IEPTB'.'InstrumentoManualSendmail'", {
@@ -45,27 +45,37 @@ export function sendInstrumentoManualEmail(client, payload) {
45
45
  livro: payload.livro,
46
46
  folha: payload.folha
47
47
  })];
48
- case 1: return [4 /*yield*/, (_a.sent()).json()];
48
+ case 1:
49
+ response = _a.sent();
50
+ return [4 /*yield*/, response
51
+ .clone()
52
+ .json()
53
+ .catch(function () { return null; })];
49
54
  case 2:
50
- res = _a.sent();
51
- return [2 /*return*/, (res !== null && res !== void 0 ? res : {})];
55
+ json = _a.sent();
56
+ return [2 /*return*/, (json !== null && json !== void 0 ? json : {})];
52
57
  }
53
58
  });
54
59
  });
55
60
  }
56
61
  export function sendInstrumentoDiscoveryEmail(client, payload) {
57
62
  return __awaiter(this, void 0, void 0, function () {
58
- var res;
63
+ var response, json;
59
64
  return __generator(this, function (_a) {
60
65
  switch (_a.label) {
61
66
  case 0: return [4 /*yield*/, client.request("INSERT INTO 'IEPTB'.'InstrumentoDiscoverySendmail'", {
62
67
  documento: payload.documento,
63
68
  nm_chave: payload.nm_chave
64
69
  })];
65
- case 1: return [4 /*yield*/, (_a.sent()).json()];
70
+ case 1:
71
+ response = _a.sent();
72
+ return [4 /*yield*/, response
73
+ .clone()
74
+ .json()
75
+ .catch(function () { return null; })];
66
76
  case 2:
67
- res = _a.sent();
68
- return [2 /*return*/, (res !== null && res !== void 0 ? res : {})];
77
+ json = _a.sent();
78
+ return [2 /*return*/, (json !== null && json !== void 0 ? json : {})];
69
79
  }
70
80
  });
71
81
  });
@@ -49,7 +49,9 @@ var Falencia = function (_a) {
49
49
  var documento = _a.documento;
50
50
  var setData = useGlobalData().setData;
51
51
  var _b = useState(false), dataUpdated = _b[0], setDataUpdated = _b[1];
52
- var _c = useQuery("SELECT FROM 'ValorEconomico'.'Falencia'", { documento: documento }), response = _c.response, error = _c.error, isLoading = _c.isLoading, loadingProgress = _c.loadingProgress, refetch = _c.refetch;
52
+ // Desabilitado: endpoint legado `ValorEconomico.Falencia` está retornando 500.
53
+ // Reativar quando a rota estiver estável.
54
+ var _c = useQuery("SELECT FROM 'ValorEconomico'.'Falencia'", { documento: documento }, false), response = _c.response, error = _c.error, isLoading = _c.isLoading, loadingProgress = _c.loadingProgress, refetch = _c.refetch;
53
55
  // Transforma o retorno em array tipado ----------------------------------
54
56
  var records = useMemo(function () {
55
57
  if (!(response === null || response === void 0 ? void 0 : response.document))
@@ -5,12 +5,11 @@ interface LiminarProtestosDoPassadoProps {
5
5
  /**
6
6
  * Hook que identifica indícios de liminar de sustação de protesto.
7
7
  *
8
- * Regras (20250701)
9
- * Um instrumento é **oculto** se a consulta a `PDFPROTESTO.PDF` **não** retornar PDF.
10
- * Se todos ainda possuem PDF, não indício de liminar. (!?)
8
+ * Regra simplificada (20260119):
9
+ * - Considera "oculto" todo protesto que aparece no histórico e está ausente
10
+ * na lista atual (missingAt), sem consultar `PDFPROTESTO.PDF` (rota legado).
11
11
  *
12
- * Esta versão limita a concorrência (10 chamadas em paralelo) e aplica
13
- * timeout defensivo para cada requisição.
12
+ * Motivo: `PDFPROTESTO.PDF` está instável/legado e gera erros no console.
14
13
  */
15
14
  declare const useLiminarProtestosDoPassado: ({ documento }: LiminarProtestosDoPassadoProps) => {
16
15
  readonly fetchLiminarProtestosDoPassado: () => Promise<{
@@ -53,12 +53,11 @@ import { WebService } from '../webservice';
53
53
  /**
54
54
  * Hook que identifica indícios de liminar de sustação de protesto.
55
55
  *
56
- * Regras (20250701)
57
- * Um instrumento é **oculto** se a consulta a `PDFPROTESTO.PDF` **não** retornar PDF.
58
- * Se todos ainda possuem PDF, não indício de liminar. (!?)
56
+ * Regra simplificada (20260119):
57
+ * - Considera "oculto" todo protesto que aparece no histórico e está ausente
58
+ * na lista atual (missingAt), sem consultar `PDFPROTESTO.PDF` (rota legado).
59
59
  *
60
- * Esta versão limita a concorrência (10 chamadas em paralelo) e aplica
61
- * timeout defensivo para cada requisição.
60
+ * Motivo: `PDFPROTESTO.PDF` está instável/legado e gera erros no console.
62
61
  */
63
62
  var useLiminarProtestosDoPassado = function (_a) {
64
63
  var _b;
@@ -66,42 +65,8 @@ var useLiminarProtestosDoPassado = function (_a) {
66
65
  var client = useContext(WebService);
67
66
  var posthog = useContext(PostHogContext).posthog;
68
67
  var _c = useGlobalData(), globalData = _c.data, setData = _c.setData;
69
- /** Máximo de requisições simultâneas ao endpoint de PDF. */
70
- var MAX_CONCURRENT = 10;
71
- /** Timeout (ms) por requisição individual ao PDF. */
72
- var PDF_TIMEOUT = 80000;
73
- /**
74
- * Checa se um `nm_chave` ainda possui PDF no CENPROT.
75
- * Retorna `true` quando há PDF, `false` caso contrário ou erro.
76
- */
77
- var possuiPdf = function (nm_chave) { return __awaiter(void 0, void 0, void 0, function () {
78
- var ctrl, timer, response, error_1;
79
- return __generator(this, function (_a) {
80
- switch (_a.label) {
81
- case 0:
82
- ctrl = new AbortController();
83
- timer = setTimeout(function () { return ctrl.abort(); }, PDF_TIMEOUT);
84
- _a.label = 1;
85
- case 1:
86
- _a.trys.push([1, 4, 5, 6]);
87
- return [4 /*yield*/, client.request("SELECT FROM 'PDFPROTESTO'.'PDF'", { nm_chave: nm_chave, documento: documento }, undefined, ctrl.signal)];
88
- case 2:
89
- response = _a.sent();
90
- return [4 /*yield*/, response.json()];
91
- case 3: return [2 /*return*/, !!(_a.sent())];
92
- case 4:
93
- error_1 = _a.sent();
94
- console.error('Erro ao verificar PDF:', error_1);
95
- return [2 /*return*/, false]; // considera oculto se erro ou timeout
96
- case 5:
97
- clearTimeout(timer);
98
- return [7 /*endfinally*/];
99
- case 6: return [2 /*return*/];
100
- }
101
- });
102
- }); };
103
68
  var fetch = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () {
104
- var data, parsedData, _a, _b, numerosChave, ocultos, running, idx, launch, _loop_1, protestosDoPassado;
69
+ var data, parsedData, _a, _b, numerosChave, protestosDoPassado, ocultos;
105
70
  return __generator(this, function (_c) {
106
71
  switch (_c.label) {
107
72
  case 0: return [4 /*yield*/, client.request("SELECT FROM 'Protestos'.'History'", {
@@ -116,44 +81,8 @@ var useLiminarProtestosDoPassado = function (_a) {
116
81
  numerosChave = parsedData
117
82
  .filter(function (item) { return item.missingAt; })
118
83
  .map(function (item) { return item.chave; });
119
- ocultos = [];
120
- running = [];
121
- idx = 0;
122
- launch = function (chave) { return __awaiter(void 0, void 0, void 0, function () {
123
- return __generator(this, function (_a) {
124
- switch (_a.label) {
125
- case 0: return [4 /*yield*/, possuiPdf(chave)];
126
- case 1:
127
- if (_a.sent())
128
- ocultos.push(chave);
129
- return [2 /*return*/];
130
- }
131
- });
132
- }); };
133
- _c.label = 3;
134
- case 3:
135
- if (!(idx < numerosChave.length || running.length)) return [3 /*break*/, 6];
136
- _loop_1 = function () {
137
- var p = launch(numerosChave[idx++]).finally(function () {
138
- var i = running.indexOf(p);
139
- if (i >= 0)
140
- running.splice(i, 1);
141
- });
142
- running.push(p);
143
- };
144
- while (idx < numerosChave.length && running.length < MAX_CONCURRENT) {
145
- _loop_1();
146
- }
147
- if (!running.length) return [3 /*break*/, 5];
148
- return [4 /*yield*/, Promise.race(running)];
149
- case 4:
150
- _c.sent();
151
- _c.label = 5;
152
- case 5: return [3 /*break*/, 3];
153
- case 6:
154
- protestosDoPassado = parsedData
155
- .filter(function (item) { return item.missingAt; })
156
- .filter(function (item) { return !ocultos.includes(item.chave); });
84
+ protestosDoPassado = parsedData.filter(function (item) { return item.missingAt; });
85
+ ocultos = protestosDoPassado.map(function (item) { return item.chave; });
157
86
  setData(function (prev) { return (__assign(__assign({}, prev), { protestosPagosBaixados: {
158
87
  isLoaded: true,
159
88
  protestos: protestosDoPassado
@@ -10,6 +10,7 @@ interface UseInstrumentoReturn {
10
10
  isEmailModalOpen: boolean;
11
11
  emailMessage: ReactNode;
12
12
  emailTitle: string;
13
+ isSuccess: boolean;
13
14
  isEnviandoEmail: boolean;
14
15
  isProcessandoDescoberta: boolean;
15
16
  openModalSP: () => void;
@@ -49,8 +49,9 @@ export var useInstrumento = function (_a) {
49
49
  var _c = useState(false), isEmailModalOpen = _c[0], setIsEmailModalOpen = _c[1];
50
50
  var _d = useState(''), emailMessage = _d[0], setEmailMessage = _d[1];
51
51
  var _e = useState('Instrumento de Protesto'), emailTitle = _e[0], setEmailTitle = _e[1];
52
- var _f = useState(false), isEnviandoEmail = _f[0], setIsEnviandoEmail = _f[1];
53
- var _g = useState(false), isProcessandoDescoberta = _g[0], setIsProcessandoDescoberta = _g[1];
52
+ var _f = useState(false), isSuccess = _f[0], setIsSuccess = _f[1];
53
+ var _g = useState(false), isEnviandoEmail = _g[0], setIsEnviandoEmail = _g[1];
54
+ var _h = useState(false), isProcessandoDescoberta = _h[0], setIsProcessandoDescoberta = _h[1];
54
55
  var openModalSP = useCallback(function () {
55
56
  setIsModalSPOpen(true);
56
57
  }, []);
@@ -61,6 +62,7 @@ export var useInstrumento = function (_a) {
61
62
  setIsEmailModalOpen(false);
62
63
  setEmailMessage('');
63
64
  setEmailTitle('Instrumento de Protesto');
65
+ setIsSuccess(false);
64
66
  }, []);
65
67
  var handleEnviarEmail = useCallback(function (livro, folha) { return __awaiter(void 0, void 0, void 0, function () {
66
68
  var res, error_1;
@@ -82,6 +84,7 @@ export var useInstrumento = function (_a) {
82
84
  setEmailTitle('Instrumento solicitado por e-mail');
83
85
  setEmailMessage((res === null || res === void 0 ? void 0 : res.message) ||
84
86
  'Solicitação registrada. Vamos processar o instrumento e também agregar as informações do credor quando possível. Em alguns minutos, refaça a consulta de hoje para atualizar os dados.');
87
+ setIsSuccess(true);
85
88
  setIsEmailModalOpen(true);
86
89
  setIsModalSPOpen(false);
87
90
  return [3 /*break*/, 5];
@@ -89,6 +92,7 @@ export var useInstrumento = function (_a) {
89
92
  error_1 = _a.sent();
90
93
  setEmailTitle('Erro ao Enviar E-mail');
91
94
  setEmailMessage('Não foi possível solicitar o instrumento por e-mail agora. Tente novamente em instantes.');
95
+ setIsSuccess(false);
92
96
  setIsEmailModalOpen(true);
93
97
  return [3 /*break*/, 5];
94
98
  case 4:
@@ -116,12 +120,14 @@ export var useInstrumento = function (_a) {
116
120
  setEmailTitle('Solicitação enviada');
117
121
  setEmailMessage((res === null || res === void 0 ? void 0 : res.message) ||
118
122
  'Solicitação registrada. Vamos processar o instrumento e também agregar as informações do credor quando possível. Em alguns minutos, refaça a consulta de hoje para atualizar os dados.');
123
+ setIsSuccess(true);
119
124
  setIsEmailModalOpen(true);
120
125
  return [3 /*break*/, 5];
121
126
  case 3:
122
127
  error_2 = _a.sent();
123
128
  setEmailTitle('Erro na solicitação');
124
129
  setEmailMessage('Não foi possível iniciar a solicitação por e-mail agora. Tente novamente em instantes.');
130
+ setIsSuccess(false);
125
131
  setIsEmailModalOpen(true);
126
132
  return [3 /*break*/, 5];
127
133
  case 4:
@@ -136,6 +142,7 @@ export var useInstrumento = function (_a) {
136
142
  isEmailModalOpen: isEmailModalOpen,
137
143
  emailMessage: emailMessage,
138
144
  emailTitle: emailTitle,
145
+ isSuccess: isSuccess,
139
146
  isEnviandoEmail: isEnviandoEmail,
140
147
  isProcessandoDescoberta: isProcessandoDescoberta,
141
148
  openModalSP: openModalSP,
@@ -163,58 +163,10 @@ export var ProtestoItem = memo(function (_a) {
163
163
  return value === 'true' ? 'Sim' : 'Não';
164
164
  };
165
165
  var fetchQuemApresentou = function (nm_chave) { return __awaiter(void 0, void 0, void 0, function () {
166
- var normalizedKey, response, nomeDetectado_1, error_1;
167
166
  return __generator(this, function (_a) {
168
- switch (_a.label) {
169
- case 0:
170
- if (!isInstrumentKeyValid(nm_chave))
171
- return [2 /*return*/];
172
- normalizedKey = normalizeInstrumentKey(nm_chave);
173
- if (!normalizedKey)
174
- return [2 /*return*/];
175
- setLoading(true);
176
- _a.label = 1;
177
- case 1:
178
- _a.trys.push([1, 4, 5, 6]);
179
- return [4 /*yield*/, client.request("SELECT FROM 'PDFPROTESTO'.'AI'", {
180
- nm_chave: normalizedKey,
181
- documento: documento
182
- })];
183
- case 2: return [4 /*yield*/, (_a.sent()).json()];
184
- case 3:
185
- response = _a.sent();
186
- nomeDetectado_1 = null;
187
- if (response === null || response === void 0 ? void 0 : response['Quem Protestou']) {
188
- nomeDetectado_1 = response['Quem Protestou'];
189
- }
190
- else if (response === null || response === void 0 ? void 0 : response['Quem Apresentou']) {
191
- nomeDetectado_1 = response['Quem Apresentou'];
192
- }
193
- if (nomeDetectado_1) {
194
- setQuemApresentou(nomeDetectado_1);
195
- setIsAIData(true);
196
- // Salva IA override globalmente
197
- setData(function (prev) {
198
- var _a;
199
- var _b;
200
- // Garante que só string é atribuída
201
- if (!nomeDetectado_1)
202
- return prev;
203
- return __assign(__assign({}, prev), { protestosData: __assign(__assign({}, prev.protestosData), { iaOverrides: __assign(__assign({}, (((_b = prev.protestosData) === null || _b === void 0 ? void 0 : _b.iaOverrides) || {})), (_a = {}, _a[nm_chave] = nomeDetectado_1, _a)) }) });
204
- });
205
- }
206
- return [3 /*break*/, 6];
207
- case 4:
208
- error_1 = _a.sent();
209
- console.error('Erro ao buscar dados de protesto IA:', error_1);
210
- return [3 /*break*/, 6];
211
- case 5:
212
- setLoading(false);
213
- activeRequests--;
214
- processQueue();
215
- return [7 /*endfinally*/];
216
- case 6: return [2 /*return*/];
217
- }
167
+ // Desabilitado: endpoint PDFPROTESTO.AI está retornando erro 500 (serviço legado indisponível)
168
+ // TODO: Reativar quando novo endpoint de IA estiver disponível
169
+ return [2 /*return*/];
218
170
  });
219
171
  }); };
220
172
  var queueOrExecuteFetch = function (nm_chave) {
@@ -280,10 +232,6 @@ export var Instrumento = function (_a) {
280
232
  var ctxProtestos = useContext(Queries.Protestos);
281
233
  var _b = useGlobalData(), setData = _b.setData, globalData = _b.data;
282
234
  var protestosData = (globalData === null || globalData === void 0 ? void 0 : globalData.protestosData) || {};
283
- var failedInstruments = protestosData.failedInstruments || {};
284
- var failedInstrumentReasons = protestosData.failedInstrumentReasons || {};
285
- var checkedInstruments = protestosData.checkedInstruments || {};
286
- var instrumentCache = protestosData.instrumentCache || {};
287
235
  var normalizedKey = useMemo(function () { return normalizeInstrumentKey(nm_chave); }, [nm_chave]);
288
236
  // Hook para gerenciar fluxo de instrumento (fase mockada)
289
237
  var instrumentoHook = useInstrumento({
@@ -293,131 +241,31 @@ export var Instrumento = function (_a) {
293
241
  });
294
242
  if (!nm_chave)
295
243
  return null;
296
- var hasFailedBefore = failedInstruments[nm_chave] === true;
297
- var failureReason = failedInstrumentReasons[nm_chave];
298
- var alreadyChecked = checkedInstruments[nm_chave] === true;
299
- var cachedInstrument = instrumentCache[nm_chave];
300
244
  var hasCpfCnpj = Boolean(cpfCnpj && cpfCnpj.trim() !== '');
301
245
  var isValidKey = useMemo(function () { return isInstrumentKeyValid(nm_chave); }, [nm_chave]);
302
- var shouldPrefetch = isValidKey &&
303
- hasCpfCnpj &&
304
- normalizedKey &&
305
- !hasFailedBefore &&
306
- !alreadyChecked;
307
246
  var classifyInstrumentError = function (err) {
308
247
  var rawMessage = err instanceof Error ? err.message : String(err !== null && err !== void 0 ? err : '').toString();
309
248
  if (/chave.+inv[aá]lid/i.test(rawMessage) ||
310
249
  /invalid key/i.test(rawMessage)) {
311
250
  return 'invalid-key';
312
251
  }
313
- return 'not-found';
252
+ return 'missing-doc';
314
253
  };
315
254
  var deriveErrorKind = useCallback(function () {
316
255
  if (!hasCpfCnpj)
317
256
  return 'missing-doc';
318
257
  if (!isValidKey)
319
258
  return 'invalid-key';
320
- if (failureReason === 'invalid-key' || failureReason === 'not-found')
321
- return failureReason;
322
- if (hasFailedBefore)
323
- return 'not-found';
324
259
  return null;
325
- }, [failureReason, hasCpfCnpj, hasFailedBefore, isValidKey]);
260
+ }, [hasCpfCnpj, isValidKey]);
326
261
  var _c = useState(deriveErrorKind), errorKind = _c[0], setErrorKind = _c[1];
327
262
  var _d = useState(false), isLoading = _d[0], setIsLoading = _d[1];
328
- var _e = useState(shouldPrefetch), isPrefetching = _e[0], setIsPrefetching = _e[1];
329
- var _f = useState(false), isDiscoveryConfirmOpen = _f[0], setIsDiscoveryConfirmOpen = _f[1];
263
+ var _e = useState(false), isDiscoveryConfirmOpen = _e[0], setIsDiscoveryConfirmOpen = _e[1];
330
264
  useEffect(function () {
331
265
  setErrorKind(deriveErrorKind());
332
266
  }, [deriveErrorKind]);
333
- useEffect(function () {
334
- if (!shouldPrefetch) {
335
- return;
336
- }
337
- var cancelled = false;
338
- var runRequest = function () { return __awaiter(void 0, void 0, void 0, function () {
339
- var response_1, prefetchError_1, failure_1;
340
- return __generator(this, function (_a) {
341
- switch (_a.label) {
342
- case 0:
343
- if (cancelled) {
344
- instrumentActiveRequests--;
345
- processInstrumentQueue();
346
- return [2 /*return*/];
347
- }
348
- setIsPrefetching(function (prev) { return (prev ? prev : true); });
349
- _a.label = 1;
350
- case 1:
351
- _a.trys.push([1, 4, 5, 6]);
352
- return [4 /*yield*/, client.request("SELECT FROM 'IEPTB'.'PDF'", {
353
- nm_chave: normalizedKey,
354
- documento: cpfCnpj
355
- })];
356
- case 2: return [4 /*yield*/, (_a.sent()).json()];
357
- case 3:
358
- response_1 = _a.sent();
359
- if (cancelled)
360
- return [2 /*return*/];
361
- if (!(response_1 === null || response_1 === void 0 ? void 0 : response_1.instrumentoProtesto)) {
362
- throw new Error('Instrumento não retornado pela API');
363
- }
364
- setData(function (prev) {
365
- var _a, _b;
366
- var base = prev || {};
367
- var prevProtestosData = base.protestosData || {};
368
- var _c = prevProtestosData.failedInstruments || {}, _d = nm_chave, _removedFailed = _c[_d], restFailed = __rest(_c, [typeof _d === "symbol" ? _d : _d + ""]);
369
- var _e = prevProtestosData.failedInstrumentReasons || {}, _f = nm_chave, _removedReason = _e[_f], restReasons = __rest(_e, [typeof _f === "symbol" ? _f : _f + ""]);
370
- return __assign(__assign({}, base), { protestosData: __assign(__assign({}, prevProtestosData), { failedInstruments: restFailed, failedInstrumentReasons: restReasons, checkedInstruments: __assign(__assign({}, (prevProtestosData.checkedInstruments || {})), (_a = {}, _a[nm_chave] = true, _a)), instrumentCache: __assign(__assign({}, (prevProtestosData.instrumentCache || {})), (_b = {}, _b[nm_chave] = response_1.instrumentoProtesto, _b)) }) });
371
- });
372
- setErrorKind(null);
373
- return [3 /*break*/, 6];
374
- case 4:
375
- prefetchError_1 = _a.sent();
376
- if (cancelled)
377
- return [2 /*return*/];
378
- failure_1 = classifyInstrumentError(prefetchError_1);
379
- setErrorKind(failure_1);
380
- setData(function (prev) {
381
- var _a, _b, _c;
382
- var base = prev || {};
383
- var prevProtestosData = base.protestosData || {};
384
- var _d = prevProtestosData.instrumentCache || {}, _e = nm_chave, _cachedInstrument = _d[_e], restCache = __rest(_d, [typeof _e === "symbol" ? _e : _e + ""]);
385
- return __assign(__assign({}, base), { protestosData: __assign(__assign({}, prevProtestosData), { instrumentCache: restCache, checkedInstruments: __assign(__assign({}, (prevProtestosData.checkedInstruments || {})), (_a = {}, _a[nm_chave] = true, _a)), failedInstruments: __assign(__assign({}, (prevProtestosData.failedInstruments || {})), (_b = {}, _b[nm_chave] = true, _b)), failedInstrumentReasons: __assign(__assign({}, (prevProtestosData.failedInstrumentReasons || {})), (_c = {}, _c[nm_chave] = failure_1, _c)) }) });
386
- });
387
- return [3 /*break*/, 6];
388
- case 5:
389
- if (!cancelled) {
390
- setIsPrefetching(false);
391
- }
392
- instrumentActiveRequests--;
393
- processInstrumentQueue();
394
- return [7 /*endfinally*/];
395
- case 6: return [2 /*return*/];
396
- }
397
- });
398
- }); };
399
- if (instrumentActiveRequests < MAX_CONCURRENT_INSTRUMENT_REQUESTS) {
400
- instrumentActiveRequests++;
401
- runRequest();
402
- }
403
- else {
404
- instrumentRequestQueue.push(runRequest);
405
- }
406
- return function () {
407
- cancelled = true;
408
- };
409
- }, [
410
- client,
411
- cpfCnpj,
412
- hasCpfCnpj,
413
- nm_chave,
414
- normalizedKey,
415
- setData,
416
- shouldPrefetch
417
- ]);
418
- // Mantém o botão clicável em `not-found` para permitir solicitar por e-mail
267
+ // Mantém o botão clicável para "Solicitar instrumento" mesmo durante prefetch
419
268
  var isDisabled = isLoading ||
420
- isPrefetching ||
421
269
  errorKind === 'invalid-key' ||
422
270
  errorKind === 'missing-doc';
423
271
  var getTooltipMessage = function () {
@@ -425,26 +273,16 @@ export var Instrumento = function (_a) {
425
273
  return 'Documento não disponível para consulta';
426
274
  if (errorKind === 'invalid-key')
427
275
  return 'Chave de instrumento inválida';
428
- if (errorKind === 'not-found')
429
- return 'PDF indisponível. Você pode solicitar o instrumento.';
430
- if (isPrefetching)
431
- return 'Verificando disponibilidade do instrumento...';
432
276
  return '';
433
277
  };
434
278
  var getButtonLabel = function () {
435
- if (errorKind === 'not-found' && !isProtestoSPByNmChave(normalizedKey))
436
- return 'Solicitar instrumento';
437
279
  if (errorKind === 'invalid-key' || errorKind === 'missing-doc')
438
280
  return 'Instrumento Indisponível';
281
+ if (!isProtestoSPByNmChave(normalizedKey))
282
+ return 'Solicitar instrumento';
439
283
  return 'Instrumento';
440
284
  };
441
285
  var tooltipMessage = getTooltipMessage();
442
- var openInstrumentPdf = function (base64) {
443
- var pdfWindow = window.open('', '_blank');
444
- if (!pdfWindow)
445
- return;
446
- pdfWindow.document.write("<iframe width='100%' height='100%' src='data:application/pdf;base64,".concat(base64, "'></iframe>"));
447
- };
448
286
  var isSP = isProtestoSPByNmChave(normalizedKey);
449
287
  var resetInstrumentStateForKey = useCallback(function () {
450
288
  if (!nm_chave)
@@ -463,86 +301,29 @@ export var Instrumento = function (_a) {
463
301
  return (React.createElement(React.Fragment, null,
464
302
  React.createElement("span", { title: tooltipMessage, style: { display: 'inline-block' } },
465
303
  React.createElement(Button, { isLoading: isLoading || instrumentoHook.isProcessandoDescoberta, onClick: function () { return __awaiter(void 0, void 0, void 0, function () {
466
- var request_1, e_1, failure_2;
467
304
  return __generator(this, function (_a) {
468
- switch (_a.label) {
469
- case 0:
470
- if (isDisabled)
471
- return [2 /*return*/];
472
- // Fluxo SP: abre modal para Livro/Folha
473
- if (isSP) {
474
- instrumentoHook.openModalSP();
475
- return [2 /*return*/];
476
- }
477
- // Se já sabemos que o PDF está indisponível, oferecemos o fluxo por e-mail
478
- if (errorKind === 'not-found') {
479
- setIsDiscoveryConfirmOpen(true);
480
- return [2 /*return*/];
481
- }
482
- // Fluxo não-SP: tenta abrir PDF se disponível
483
- if (cachedInstrument) {
484
- openInstrumentPdf(cachedInstrument);
485
- return [2 /*return*/];
486
- }
487
- // Tenta buscar PDF do backend
488
- setIsLoading(true);
489
- _a.label = 1;
490
- case 1:
491
- _a.trys.push([1, 4, 5, 6]);
492
- return [4 /*yield*/, client.request("SELECT FROM 'IEPTB'.'PDF'", {
493
- nm_chave: normalizedKey,
494
- documento: cpfCnpj
495
- })];
496
- case 2: return [4 /*yield*/, (_a.sent()).json()];
497
- case 3:
498
- request_1 = _a.sent();
499
- if (!(request_1 === null || request_1 === void 0 ? void 0 : request_1.instrumentoProtesto)) {
500
- throw new Error('Instrumento não retornado pela API');
501
- }
502
- openInstrumentPdf(request_1.instrumentoProtesto);
503
- setData(function (prev) {
504
- var _a, _b;
505
- var base = prev || {};
506
- var prevProtestosData = base.protestosData || {};
507
- var _c = prevProtestosData.failedInstruments || {}, _d = nm_chave, _removedFailed = _c[_d], restFailed = __rest(_c, [typeof _d === "symbol" ? _d : _d + ""]);
508
- var _e = prevProtestosData.failedInstrumentReasons || {}, _f = nm_chave, _removedReason = _e[_f], restReasons = __rest(_e, [typeof _f === "symbol" ? _f : _f + ""]);
509
- return __assign(__assign({}, base), { protestosData: __assign(__assign({}, prevProtestosData), { failedInstruments: restFailed, failedInstrumentReasons: restReasons, instrumentCache: __assign(__assign({}, (prevProtestosData.instrumentCache || {})), (_a = {}, _a[nm_chave] = request_1.instrumentoProtesto, _a)), checkedInstruments: __assign(__assign({}, (prevProtestosData.checkedInstruments || {})), (_b = {}, _b[nm_chave] = true, _b)) }) });
510
- });
511
- setErrorKind(null);
512
- return [3 /*break*/, 6];
513
- case 4:
514
- e_1 = _a.sent();
515
- console.error(e_1);
516
- failure_2 = classifyInstrumentError(e_1);
517
- setErrorKind(failure_2);
518
- // Quando PDF não está disponível, oferece descoberta automática com confirmação (UX)
519
- if (failure_2 === 'not-found' && hasCpfCnpj && isValidKey) {
520
- setIsDiscoveryConfirmOpen(true);
521
- }
522
- // Persistimos falha/cache para evitar loops de prefetch
523
- setData(function (prev) {
524
- var _a, _b, _c;
525
- var base = prev || {};
526
- var prevProtestosData = base.protestosData || {};
527
- var _d = prevProtestosData.instrumentCache || {}, _e = nm_chave, _cachedInstrument = _d[_e], restCache = __rest(_d, [typeof _e === "symbol" ? _e : _e + ""]);
528
- return __assign(__assign({}, base), { protestosData: __assign(__assign({}, prevProtestosData), { instrumentCache: restCache, failedInstruments: __assign(__assign({}, (prevProtestosData.failedInstruments || {})), (_a = {}, _a[nm_chave] = true, _a)), checkedInstruments: __assign(__assign({}, (prevProtestosData.checkedInstruments || {})), (_b = {}, _b[nm_chave] = true, _b)), failedInstrumentReasons: __assign(__assign({}, (prevProtestosData.failedInstrumentReasons || {})), (_c = {}, _c[nm_chave] = failure_2, _c)) }) });
529
- });
530
- return [3 /*break*/, 6];
531
- case 5:
532
- setIsLoading(false);
533
- return [7 /*endfinally*/];
534
- case 6: return [2 /*return*/];
305
+ if (isDisabled)
306
+ return [2 /*return*/];
307
+ // Fluxo SP: abre modal para Livro/Folha
308
+ if (isSP) {
309
+ instrumentoHook.openModalSP();
310
+ return [2 /*return*/];
535
311
  }
312
+ // Fluxo não-SP: IEPTB.PDF foi depreciado. Vai direto para solicitação.
313
+ setIsDiscoveryConfirmOpen(true);
314
+ return [2 /*return*/];
536
315
  });
537
316
  }); }, disabled: isDisabled }, getButtonLabel())),
538
317
  React.createElement(ModalInstrumentoProtestoSP, { isOpen: instrumentoHook.isModalSPOpen, onClose: instrumentoHook.closeModalSP, onEnviarEmail: instrumentoHook.handleEnviarEmail, isEnviandoEmail: instrumentoHook.isEnviandoEmail }),
539
- React.createElement(InstrumentoEmailStatusModal, { isOpen: instrumentoHook.isEmailModalOpen, onClose: instrumentoHook.closeEmailModal, message: instrumentoHook.emailMessage, title: instrumentoHook.emailTitle, secondaryActionLabel: "Atualizar consulta (hoje)", secondaryActionDisabled: isPrefetching || isLoading, onSecondaryAction: function () {
540
- var _a;
541
- // Permite reconsultar no mesmo dia para tentar “desocultar” instrumento/nome
542
- resetInstrumentStateForKey();
543
- (_a = ctxProtestos === null || ctxProtestos === void 0 ? void 0 : ctxProtestos.refetch) === null || _a === void 0 ? void 0 : _a.call(ctxProtestos);
544
- instrumentoHook.closeEmailModal();
545
- } }),
318
+ React.createElement(InstrumentoEmailStatusModal, { isOpen: instrumentoHook.isEmailModalOpen, onClose: instrumentoHook.closeEmailModal, message: instrumentoHook.emailMessage, title: instrumentoHook.emailTitle, secondaryActionLabel: instrumentoHook.isSuccess ? 'Atualizar consulta (hoje)' : undefined, secondaryActionDisabled: false, onSecondaryAction: instrumentoHook.isSuccess
319
+ ? function () {
320
+ var _a;
321
+ // Permite reconsultar no mesmo dia para tentar “desocultar” instrumento/nome
322
+ resetInstrumentStateForKey();
323
+ (_a = ctxProtestos === null || ctxProtestos === void 0 ? void 0 : ctxProtestos.refetch) === null || _a === void 0 ? void 0 : _a.call(ctxProtestos);
324
+ instrumentoHook.closeEmailModal();
325
+ }
326
+ : undefined }),
546
327
  React.createElement(InstrumentoDiscoveryConfirmModal, { isOpen: isDiscoveryConfirmOpen, onClose: function () { return setIsDiscoveryConfirmOpen(false); }, isLoading: instrumentoHook.isProcessandoDescoberta, onConfirm: function () { return __awaiter(void 0, void 0, void 0, function () {
547
328
  return __generator(this, function (_a) {
548
329
  switch (_a.label) {
@@ -167,15 +167,6 @@ export declare const Queries: {
167
167
  urlData?: Client.Form;
168
168
  }>>;
169
169
  };
170
- Falencia: React.Context<RequestContext<Document>> & {
171
- Request: React.FC<React.PropsWithChildren<{
172
- data?: {
173
- documento: string;
174
- } | undefined;
175
- depends?: RequestContext<unknown>[];
176
- urlData?: Client.Form;
177
- }>>;
178
- };
179
170
  Edital: React.Context<RequestContext<EditalResponse>> & {
180
171
  Request: React.FC<React.PropsWithChildren<{
181
172
  data?: {
@@ -509,6 +509,8 @@ export var Queries = {
509
509
  ReclameAqui: query("SELECT FROM 'RECLAMEAQUI'.'CONSULTA'"),
510
510
  Dominios: query("SELECT FROM 'DOMINIOS'.'CONSULTA'"),
511
511
  GraficosAnaliticos: query("SELECT FROM 'DOCUMENTHISTORY'.'BASICHISTORY'"),
512
- Falencia: query("SELECT FROM 'ValorEconomico'.'Falencia'"),
512
+ // Falencia: query<{ documento: string }, Document>(
513
+ // "SELECT FROM 'ValorEconomico'.'Falencia'"
514
+ // ),
513
515
  Edital: query("SELECT FROM 'APICENPROT'.'EDITAL'")
514
516
  };