@credithub/harlan-components 1.59.6 → 1.59.7

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.
@@ -1,3 +1,3 @@
1
1
  import React from 'react';
2
- declare const CCF: () => React.JSX.Element;
3
- export default CCF;
2
+ declare const _default: React.MemoExoticComponent<() => React.JSX.Element>;
3
+ export default _default;
@@ -12,16 +12,17 @@ var __assign = (this && this.__assign) || function () {
12
12
  import ChequesSemFundoIcon from '../../assets/icones/chequesSemFundo';
13
13
  import { useGlobalData } from '../../contexts/globalDataContext';
14
14
  import XPathUtils from '../../utils/xpath';
15
- import React, { useCallback, useContext, useState } from 'react';
15
+ import React, { useCallback, useContext, useState, useEffect, useMemo } from 'react';
16
16
  import { Result } from '../interface/result';
17
17
  import StatusMessage from '../interface/statusMessage';
18
18
  import Section from '../section';
19
- import { Queries } from '../webservice';
19
+ import { Queries, RequestStatus } from '../webservice';
20
20
  import CCFList from './ccfList';
21
21
  var CCF = function () {
22
22
  var ctx = useContext(Queries.CCF);
23
23
  var setData = useGlobalData().setData;
24
24
  var _a = useState(false), dataUpdated = _a[0], setDataUpdated = _a[1];
25
+ // Memoize mapper function to prevent unnecessary recreation
25
26
  var mapNodeToCCFData = useCallback(function (node) { return ({
26
27
  banco: XPathUtils.select('string(./banco)', node),
27
28
  agencia: XPathUtils.select('string(./agencia)', node),
@@ -29,23 +30,37 @@ var CCF = function () {
29
30
  ultimaOcorrencia: XPathUtils.select('string(./ultimo)', node),
30
31
  motivo: XPathUtils.select('string(./motivo)', node)
31
32
  }); }, []);
32
- return (React.createElement(Section, { ctx: ctx, title: "Cheques sem Fundos em Institui\u00E7\u00E3o Banc\u00E1ria", subtitle: "Detalhes acerca de cheques sem fundos emitidos.", icon: ChequesSemFundoIcon, onSuccess: function (data) {
33
- var allItems = XPathUtils.selectArray('//list/*', data);
34
- var filteredItems = allItems.filter(function (node) {
35
- return node.nodeName.startsWith('item');
36
- });
37
- var ccfData = filteredItems.map(mapNodeToCCFData);
38
- var totalOcorrencias = XPathUtils.select('number(//sumQteOcorrencias)', data);
39
- var ultimoRegistro = XPathUtils.select('string(//ultimo)', data);
40
- if (!dataUpdated &&
41
- (totalOcorrencias !== 0 ||
42
- ultimoRegistro.length > 0 ||
43
- ccfData.length > 0)) {
44
- var ccfState_1 = { ccfData: ccfData };
45
- setData(function (prevState) { return (__assign(__assign({}, prevState), { ccfData: ccfState_1, ccf: totalOcorrencias || 0, ultimoRegistroCCF: ultimoRegistro || '' })); });
46
- setDataUpdated(true);
47
- }
48
- var children = (ccfData === null || ccfData === void 0 ? void 0 : ccfData.length) ? (React.createElement(Result, null, ccfData.map(function (ccf, key) { return (React.createElement(CCFList, { key: key, data: [ccf] })); }))) : null;
33
+ // Extract data processing logic to a reusable function
34
+ var processData = useCallback(function (data) {
35
+ var allItems = XPathUtils.selectArray('//list/*', data);
36
+ var filteredItems = allItems.filter(function (node) {
37
+ return node.nodeName.startsWith('item');
38
+ });
39
+ var ccfData = filteredItems.map(mapNodeToCCFData);
40
+ // Ensure totalOcorrencias is always a number
41
+ var totalOcorrencias = XPathUtils.select('number(//sumQteOcorrencias)', data) || 0;
42
+ var ultimoRegistro = XPathUtils.select('string(//ultimo)', data) || '';
43
+ return { ccfData: ccfData, totalOcorrencias: totalOcorrencias, ultimoRegistro: ultimoRegistro };
44
+ }, [mapNodeToCCFData]);
45
+ // Update global state when data changes
46
+ useEffect(function () {
47
+ if (ctx.type !== RequestStatus.Success || dataUpdated || !ctx.document) {
48
+ return;
49
+ }
50
+ var data = ctx.document;
51
+ var _a = processData(data), ccfData = _a.ccfData, totalOcorrencias = _a.totalOcorrencias, ultimoRegistro = _a.ultimoRegistro;
52
+ if (totalOcorrencias !== 0 ||
53
+ ultimoRegistro.length > 0 ||
54
+ ccfData.length > 0) {
55
+ var ccfState_1 = { ccfData: ccfData };
56
+ setData(function (prevState) { return (__assign(__assign({}, prevState), { ccfData: ccfState_1, ccf: totalOcorrencias, ultimoRegistroCCF: ultimoRegistro })); });
57
+ setDataUpdated(true);
58
+ }
59
+ }, [ctx, dataUpdated, processData, setData]);
60
+ // Memoize the component rendering for better performance
61
+ var sectionComponent = useMemo(function () { return (React.createElement(Section, { ctx: ctx, title: "Cheques sem Fundos em Institui\u00E7\u00E3o Banc\u00E1ria", subtitle: "Detalhes acerca de cheques sem fundos emitidos.", icon: ChequesSemFundoIcon, onSuccess: function (data) {
62
+ var _a = processData(data), ccfData = _a.ccfData, totalOcorrencias = _a.totalOcorrencias, ultimoRegistro = _a.ultimoRegistro;
63
+ var children = (ccfData === null || ccfData === void 0 ? void 0 : ccfData.length) ? (React.createElement(Result, null, ccfData.map(function (ccf, key) { return (React.createElement(CCFList, { key: "ccf-".concat(key), data: [ccf] })); }))) : null;
49
64
  return {
50
65
  children: children,
51
66
  variant: totalOcorrencias ? 'error' : 'default',
@@ -55,6 +70,7 @@ var CCF = function () {
55
70
  : "Encontrados ".concat(totalOcorrencias, " Cheques sem fundos")
56
71
  : 'Não há ocorrência de cheques sem fundo'))
57
72
  };
58
- } }));
73
+ } })); }, [ctx, processData]);
74
+ return sectionComponent;
59
75
  };
60
- export default CCF;
76
+ export default React.memo(CCF);
@@ -5,5 +5,5 @@ interface DossieProps {
5
5
  onOpenNewTransactionModal?: () => void;
6
6
  printMode?: boolean;
7
7
  }
8
- declare const Dossie: React.FC<DossieProps>;
9
- export default Dossie;
8
+ declare const _default: React.NamedExoticComponent<DossieProps>;
9
+ export default _default;
@@ -17,12 +17,11 @@ import { useGlobalData } from '../../contexts/globalDataContext';
17
17
  import { useConsultaRfb } from '../../hooks/useConsultaRfb';
18
18
  import { formatCnpj, formatCpf } from '../../utils/string';
19
19
  import XPathUtils from '../../utils/xpath';
20
- import React, { useContext, useEffect, useState } from 'react';
20
+ import React, { useContext, useEffect, useState, useCallback, useMemo } from 'react';
21
21
  import styled from 'styled-components';
22
22
  import { ReclameAquiCarousel } from '../reclameAqui/reclameAquiCarousel';
23
23
  import Section from '../section';
24
- import { Queries, RequestStatus } from '../webservice';
25
- import { Carrousel } from './carrousel/carrousel';
24
+ import { Queries, RequestStatus, useQuery } from '../webservice';
26
25
  import { createDossieData } from './dossieData';
27
26
  import { Summary } from './summary/summary';
28
27
  import { TransactionsTable } from './transactionTable/transactionTable';
@@ -39,42 +38,70 @@ var Dossie = function (_a) {
39
38
  var rfbResponse = useConsultaRfb().rfbResponse;
40
39
  var setData = useGlobalData().setData;
41
40
  var _b = useState(false), dataUpdated = _b[0], setDataUpdated = _b[1];
42
- useEffect(function () {
41
+ // Fetch ReclameAqui data here instead of in the carousel component
42
+ var _c = useQuery("SELECT FROM 'RECLAMEAQUI'.'CONSULTA'", { documento: documento }), reclameAquiResponse = _c.response, reclameAquiLoading = _c.isLoading, reclameAquiError = _c.error;
43
+ // Parse ReclameAqui data
44
+ var reclameAquiCompanies = useMemo(function () {
45
+ var _a;
46
+ if (!reclameAquiLoading && !reclameAquiError && ((_a = reclameAquiResponse === null || reclameAquiResponse === void 0 ? void 0 : reclameAquiResponse.document) === null || _a === void 0 ? void 0 : _a.length)) {
47
+ var isPF = (documento === null || documento === void 0 ? void 0 : documento.length) === 11;
48
+ if (isPF)
49
+ return undefined;
50
+ // Get the name from the Finder document
51
+ var name_1 = ctx.document && XPathUtils.select('string(//cadastro/razaoSocial)', ctx.document) || '';
52
+ return reclameAquiResponse.document.map(function (item) { return ({
53
+ nome: name_1, // Use the name from Finder instead of from ReclameAqui response
54
+ cnpj: documento,
55
+ score: item.infos.finalScore,
56
+ status: item.infos.status,
57
+ shortname: item.infos.shortname,
58
+ imageUrl: item.infos.logo,
59
+ quantidadeProblemasResolvidos: item.infos.count.toString(),
60
+ percentualProblemasResolvidos: item.infos.solvedPercentual
61
+ }); });
62
+ }
63
+ return undefined;
64
+ }, [reclameAquiResponse, reclameAquiLoading, reclameAquiError, documento, ctx.document]);
65
+ // Move the data processing to a useCallback to avoid recreating it on every render
66
+ var processDossieData = useCallback(function () {
43
67
  if (ctx.type === RequestStatus.Success && !dataUpdated && ctx.document) {
44
68
  var data = ctx.document;
45
69
  var isPF = (documento === null || documento === void 0 ? void 0 : documento.length) === 11;
46
- var name_1 = (isPF
70
+ var name_2 = (isPF
47
71
  ? XPathUtils.select('string(//cadastro/nome)', data)
48
72
  : XPathUtils.select('string(//cadastro/razaoSocial)', data) ||
49
73
  (rfbResponse &&
50
74
  XPathUtils.select('string(//RFB/nome)', rfbResponse)));
51
75
  var document_1 = isPF ? formatCpf(documento) : formatCnpj(documento);
52
- var dossieData_1 = createDossieData(data, rfbResponse, name_1, document_1);
76
+ var dossieData_1 = createDossieData(data, rfbResponse, name_2, document_1);
53
77
  setData(function (prevState) { return (__assign(__assign({}, prevState), { dossie: dossieData_1 })); });
54
78
  setDataUpdated(true);
55
79
  }
56
- }, [ctx, rfbResponse, documento, setData, dataUpdated]);
57
- var response = function (_data) {
58
- var data = _data instanceof Error ? undefined : _data;
59
- var isPF = (documento === null || documento === void 0 ? void 0 : documento.length) === 11;
60
- var name = (isPF
61
- ? XPathUtils.select('string(//cadastro/nome)', data)
62
- : XPathUtils.select('string(//cadastro/razaoSocial)', data) ||
63
- (rfbResponse && XPathUtils.select('string(//RFB/nome)', rfbResponse)));
64
- var document = isPF ? formatCpf(documento) : formatCnpj(documento);
65
- var DossieCarrousel = function () {
66
- return !isPF ? (React.createElement(ReclameAquiCarousel, { documento: document, nome: name })) : (React.createElement(Carrousel, { name: name, document: document }));
80
+ }, [ctx.type, ctx.document, dataUpdated, documento, rfbResponse, setData]);
81
+ // Only update global state once when data is available
82
+ useEffect(function () {
83
+ processDossieData();
84
+ }, [processDossieData]);
85
+ var response = useMemo(function () {
86
+ return function (_data) {
87
+ var data = _data instanceof Error ? undefined : _data;
88
+ var isPF = (documento === null || documento === void 0 ? void 0 : documento.length) === 11;
89
+ var name = (isPF
90
+ ? XPathUtils.select('string(//cadastro/nome)', data)
91
+ : XPathUtils.select('string(//cadastro/razaoSocial)', data) ||
92
+ (rfbResponse && XPathUtils.select('string(//RFB/nome)', rfbResponse)));
93
+ var document = isPF ? formatCpf(documento) : formatCnpj(documento);
94
+ return (React.createElement(React.Fragment, null,
95
+ React.createElement(DossieContainer, null,
96
+ React.createElement(DossieContent, null,
97
+ React.createElement(ReclameAquiCarousel, { documento: document, nome: name, companies: reclameAquiCompanies }),
98
+ React.createElement(Summary, { finderResponse: data, document: document })),
99
+ React.createElement(TransactionsTable, { events: XPathUtils.select('//historico/consulta', data) || [] })),
100
+ !printMode && (React.createElement(GenerativeAIContainer, null,
101
+ React.createElement(GenerativeAI, { documento: document })))));
67
102
  };
68
- return (React.createElement(React.Fragment, null,
69
- React.createElement(DossieContainer, null,
70
- React.createElement(DossieContent, null,
71
- React.createElement(DossieCarrousel, null),
72
- React.createElement(Summary, { finderResponse: data, document: document })),
73
- React.createElement(TransactionsTable, { events: XPathUtils.select('//historico/consulta', data) || [] })),
74
- !printMode && (React.createElement(GenerativeAIContainer, null,
75
- React.createElement(GenerativeAI, { documento: document })))));
76
- };
103
+ }, [documento, rfbResponse, printMode, reclameAquiCompanies]);
77
104
  return (React.createElement(Section, { ctx: ctx, hideHeader: true, minimized: false, isError: function (e) { return response(e); }, onSuccess: response }));
78
105
  };
79
- export default Dossie;
106
+ export default React.memo(Dossie);
80
107
  var templateObject_1, templateObject_2, templateObject_3;
@@ -81,30 +81,48 @@ var GenerativeAI = function (_a) {
81
81
  globalData.documentHistory !== null);
82
82
  }, [globalData]);
83
83
  useEffect(function () {
84
+ // Only update serializedData if globalData has actually changed and is loaded
84
85
  if (globalData && documento && isGlobalDataLoaded) {
85
86
  try {
86
87
  var relevantData = selectRelevantData(globalData);
87
88
  var serialized = flattenData(relevantData);
88
- setSerializedData(serialized);
89
+ // Only update state if the data has actually changed
90
+ if (serialized !== serializedData) {
91
+ setSerializedData(serialized);
92
+ }
89
93
  }
90
94
  catch (error) {
91
95
  console.error('Erro ao preparar os dados para a API:', error);
92
- setSerializedData('{}');
96
+ if (serializedData !== '{}') {
97
+ setSerializedData('{}');
98
+ }
93
99
  }
94
100
  }
95
- }, [documento, globalData, isGlobalDataLoaded]);
101
+ }, [documento, globalData, isGlobalDataLoaded, serializedData]);
102
+ // Only set summary query data once when serializedData is available
96
103
  useEffect(function () {
97
104
  if (serializedData &&
98
105
  serializedData !== '{}' &&
99
106
  streamMode === 'summary' &&
100
107
  !summaryQueryData) {
101
- setSummaryQueryData(createQueryAndMessages(serializedData, []));
108
+ var queryData = createQueryAndMessages(serializedData, []);
109
+ setSummaryQueryData(queryData);
102
110
  }
103
111
  }, [serializedData, streamMode, summaryQueryData]);
104
- var _o = useStreamQuery("SELECT FROM 'LlamaApi'.'Consulta'", summaryQueryData, streamMode === 'summary' && !!summaryQueryData), summaryIterator = _o.responseIterator, summaryError = _o.error, summaryLoading = _o.isLoading, refetchSummary = _o.refetch, abortSummary = _o.abort;
105
- var _p = useStreamQuery("SELECT FROM 'LlamaApi'.'Consulta'", chatQueryData, streamMode === 'chat' && !!chatQueryData), chatIterator = _p.responseIterator, chatError = _p.error, chatLoading = _p.isLoading, refetchChat = _p.refetch, abortChat = _p.abort;
112
+ // Memoize the useStreamQuery parameters to prevent unnecessary API calls
113
+ var summaryQueryEnabled = useMemo(function () {
114
+ return streamMode === 'summary' && !!summaryQueryData;
115
+ }, [streamMode, summaryQueryData]);
116
+ var chatQueryEnabled = useMemo(function () {
117
+ return streamMode === 'chat' && !!chatQueryData;
118
+ }, [streamMode, chatQueryData]);
119
+ var _o = useStreamQuery("SELECT FROM 'LlamaApi'.'Consulta'", summaryQueryData, summaryQueryEnabled), summaryIterator = _o.responseIterator, summaryError = _o.error, summaryLoading = _o.isLoading, refetchSummary = _o.refetch, abortSummary = _o.abort;
120
+ var _p = useStreamQuery("SELECT FROM 'LlamaApi'.'Consulta'", chatQueryData, chatQueryEnabled), chatIterator = _p.responseIterator, chatError = _p.error, chatLoading = _p.isLoading, refetchChat = _p.refetch, abortChat = _p.abort;
121
+ // Use a ref to track if we've already processed this iterator
122
+ var processedSummaryRef = useRef(false);
106
123
  useEffect(function () {
107
- if (summaryIterator) {
124
+ if (summaryIterator && !processedSummaryRef.current) {
125
+ processedSummaryRef.current = true;
108
126
  (function () { return __awaiter(void 0, void 0, void 0, function () {
109
127
  return __generator(this, function (_a) {
110
128
  switch (_a.label) {
@@ -122,8 +140,11 @@ var GenerativeAI = function (_a) {
122
140
  }); })();
123
141
  }
124
142
  }, [summaryIterator]);
143
+ // Use a ref to track each chat iterator
144
+ var processedChatRef = useRef(new Map());
125
145
  useEffect(function () {
126
- if (chatIterator) {
146
+ if (chatIterator && !processedChatRef.current.get(chatIterator)) {
147
+ processedChatRef.current.set(chatIterator, true);
127
148
  processStream({
128
149
  iterator: chatIterator,
129
150
  mode: 'chat',
@@ -131,14 +152,6 @@ var GenerativeAI = function (_a) {
131
152
  });
132
153
  }
133
154
  }, [chatIterator]);
134
- var handleSendMessage = function () {
135
- if (userInput.trim()) {
136
- setMessageHistory(function (prev) { return __spreadArray(__spreadArray([], prev, true), [
137
- { role: 'user', content: userInput }
138
- ], false); });
139
- setUserInput('');
140
- }
141
- };
142
155
  useEffect(function () {
143
156
  if (streamMode !== 'chat' || chatLoading || messageHistory.length === 0)
144
157
  return;
@@ -173,6 +186,14 @@ var GenerativeAI = function (_a) {
173
186
  handleSendMessage();
174
187
  }
175
188
  };
189
+ var handleSendMessage = function () {
190
+ if (userInput.trim()) {
191
+ setMessageHistory(function (prev) { return __spreadArray(__spreadArray([], prev, true), [
192
+ { role: 'user', content: userInput }
193
+ ], false); });
194
+ setUserInput('');
195
+ }
196
+ };
176
197
  return (React.createElement(GenerativeAi, null,
177
198
  React.createElement(Header, null,
178
199
  React.createElement(HeaderContent, null,
@@ -12,7 +12,7 @@ var __assign = (this && this.__assign) || function () {
12
12
  import ProtestosIcon from '../../assets/icones/protestos';
13
13
  import { useGlobalData } from '../../contexts/globalDataContext';
14
14
  import { normalizeName, similarNames } from '../../utils/similarNames';
15
- import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
15
+ import React, { useContext, useEffect, useMemo, useRef } from 'react';
16
16
  import StatusMessage from '../interface/statusMessage';
17
17
  import Section from '../section';
18
18
  import { Queries, RequestStatus } from '../webservice';
@@ -20,19 +20,59 @@ var Liminar = function () {
20
20
  var _a, _b, _c;
21
21
  var ctx = useContext(Queries.LiminarCenprot);
22
22
  var _d = useGlobalData(), globalData = _d.data, setData = _d.setData;
23
- var _e = useState(undefined), liminarResult = _e[0], setLiminarResult = _e[1];
24
- var didRunRef = useRef(false);
25
- var carousel = (_a = globalData === null || globalData === void 0 ? void 0 : globalData.dossie) === null || _a === void 0 ? void 0 : _a.carousel;
26
- var isPJDataLoaded = (_b = globalData === null || globalData === void 0 ? void 0 : globalData.processosJuridicosData) === null || _b === void 0 ? void 0 : _b.isLoaded;
27
- var empresas = (_c = globalData === null || globalData === void 0 ? void 0 : globalData.processosJuridicosData) === null || _c === void 0 ? void 0 : _c.empresa;
23
+ // Use refs instead of state to avoid rendering cycles
24
+ var processedRef = useRef(false);
25
+ var processingRef = useRef(true);
26
+ var resultRef = useRef(undefined);
27
+ var dataHashRef = useRef('');
28
+ // Determine if process was not found using API exception
29
+ var isProcessoNaoEncontrado = useMemo(function () {
30
+ return ctx.type === RequestStatus.Error && ctx.error;
31
+ }, [ctx.type, ctx.error]);
32
+ // Create derived context to handle not found exceptions
33
+ var derivedCtx = useMemo(function () {
34
+ return __assign(__assign({}, ctx), { type: isProcessoNaoEncontrado ? RequestStatus.Success : ctx.type, document: isProcessoNaoEncontrado
35
+ ? { indiciosDeLiminar: false }
36
+ : ctx.document });
37
+ }, [ctx, isProcessoNaoEncontrado]);
38
+ // Reset processing state when loading new data
39
+ useEffect(function () {
40
+ if (ctx.type === RequestStatus.Loading) {
41
+ processingRef.current = true;
42
+ processedRef.current = false;
43
+ }
44
+ }, [ctx.type]);
45
+ // Process data once when context and global data are available
28
46
  useEffect(function () {
29
- var _a;
30
- if (didRunRef.current)
47
+ var _a, _b, _c;
48
+ // Skip processing if we don't have the necessary data
49
+ if (!((_a = globalData === null || globalData === void 0 ? void 0 : globalData.dossie) === null || _a === void 0 ? void 0 : _a.carousel) || !((_b = globalData === null || globalData === void 0 ? void 0 : globalData.processosJuridicosData) === null || _b === void 0 ? void 0 : _b.isLoaded)) {
31
50
  return;
32
- if (!carousel || !isPJDataLoaded)
51
+ }
52
+ // Skip if we're still loading
53
+ if (ctx.type === RequestStatus.Loading) {
54
+ return;
55
+ }
56
+ // Create a hash of the current data state
57
+ var currentDataHash = JSON.stringify({
58
+ carousel: globalData.dossie.carousel,
59
+ empresa: globalData.processosJuridicosData.empresa,
60
+ ctx: {
61
+ type: ctx.type,
62
+ document: ctx.document ? true : false,
63
+ error: ctx.error ? String(ctx.error) : null
64
+ }
65
+ });
66
+ // If data hasn't changed and we've already processed, skip reprocessing
67
+ if (currentDataHash === dataHashRef.current && processedRef.current) {
33
68
  return;
34
- var empresaNome = carousel.name || '';
35
- var empresaNomeNormalizado = normalizeName(empresaNome);
69
+ }
70
+ // Update data hash reference
71
+ dataHashRef.current = currentDataHash;
72
+ var carousel = globalData.dossie.carousel;
73
+ var empresas = globalData.processosJuridicosData.empresa;
74
+ // Begin the actual data processing
75
+ var empresaNomeNormalizado = normalizeName((carousel === null || carousel === void 0 ? void 0 : carousel.name) || '');
36
76
  var validAssuntos = [
37
77
  'protesto indevido de títulos',
38
78
  'inclusão indevida em cadastro de inadimplentes',
@@ -42,57 +82,70 @@ var Liminar = function () {
42
82
  'Adimplemento e Extinção',
43
83
  'Inexequibilidade do Título / Inexequibilidade da Obrigação | Tutela de Urgência | Protesto Indevido de Título'
44
84
  ].map(normalizeName);
85
+ // Look for valid processes
45
86
  var processosAtivo = empresas === null || empresas === void 0 ? void 0 : empresas.filter(function (processo) {
46
87
  var _a;
47
88
  var hasAtivoEnvolvido = (_a = processo.envolvidos_ultima_movimentacao) === null || _a === void 0 ? void 0 : _a.some(function (envolvido) {
48
- var nomeEnvolvidoNormalizado = normalizeName(envolvido.nome_sem_filtro);
49
- return (envolvido.envolvido_tipo === 'Ativo' &&
50
- similarNames(nomeEnvolvidoNormalizado, empresaNomeNormalizado));
89
+ return envolvido.envolvido_tipo === 'Ativo' &&
90
+ similarNames(normalizeName(envolvido.nome_sem_filtro), empresaNomeNormalizado);
51
91
  });
52
92
  var assuntos = Array.isArray(processo.assuntos)
53
93
  ? processo.assuntos
54
94
  : [processo.assuntos];
55
95
  var hasValidAssunto = assuntos.some(function (assunto) {
56
- var assuntoNormalizado = normalizeName(assunto);
57
96
  return validAssuntos.some(function (valid) {
58
- return similarNames(assuntoNormalizado, valid);
97
+ return similarNames(normalizeName(assunto), valid);
59
98
  });
60
99
  });
61
100
  return hasAtivoEnvolvido && hasValidAssunto;
62
101
  });
63
- var indiciosDeLiminar = false;
64
- if (ctx.type === RequestStatus.Error) {
102
+ // Only log actual errors
103
+ if (ctx.type === RequestStatus.Error && !isProcessoNaoEncontrado) {
65
104
  console.error('Erro na requisição de liminares:', ctx.error || 'Erro desconhecido');
66
105
  }
67
- else if (ctx.type === RequestStatus.Success) {
68
- indiciosDeLiminar = ((_a = ctx.document) === null || _a === void 0 ? void 0 : _a.indiciosDeLiminar) === true;
69
- }
106
+ // Determine final status
107
+ var isSuccess = ctx.type === RequestStatus.Success || isProcessoNaoEncontrado;
108
+ var indiciosDeLiminar = isSuccess ? ((_c = ctx.document) === null || _c === void 0 ? void 0 : _c.indiciosDeLiminar) === true : false;
70
109
  var finalStatus = indiciosDeLiminar || (processosAtivo && processosAtivo.length > 0)
71
110
  ? 'Encontrado'
72
111
  : 'Não encontrado';
73
- setData(function (prev) { return (__assign(__assign({}, prev), { liminar: { indiciosDeLiminar: indiciosDeLiminar, message: finalStatus } })); });
74
- setLiminarResult(finalStatus);
75
- didRunRef.current = true;
76
- }, [carousel, isPJDataLoaded, empresas, ctx.type, setData]);
77
- var derivedCtx = useMemo(function () {
78
- if (liminarResult === undefined) {
79
- return __assign(__assign({}, ctx), { type: RequestStatus.Loading });
80
- }
81
- return __assign(__assign({}, ctx), { type: ctx.type === RequestStatus.Error ? RequestStatus.Success : ctx.type, document: ctx.type === RequestStatus.Error
82
- ? { indiciosDeLiminar: false }
83
- : ctx.document });
84
- }, [liminarResult, ctx]);
85
- if (liminarResult === 'Não encontrado') {
112
+ // Only update global state if the value has changed
113
+ setData(function (prev) {
114
+ var _a, _b;
115
+ if (((_a = prev.liminar) === null || _a === void 0 ? void 0 : _a.message) === finalStatus &&
116
+ ((_b = prev.liminar) === null || _b === void 0 ? void 0 : _b.indiciosDeLiminar) === indiciosDeLiminar) {
117
+ return prev;
118
+ }
119
+ return __assign(__assign({}, prev), { liminar: { indiciosDeLiminar: indiciosDeLiminar, message: finalStatus } });
120
+ });
121
+ // Store the result in our ref
122
+ resultRef.current = finalStatus;
123
+ processingRef.current = false;
124
+ processedRef.current = true;
125
+ }, [
126
+ ctx,
127
+ (_a = globalData === null || globalData === void 0 ? void 0 : globalData.dossie) === null || _a === void 0 ? void 0 : _a.carousel,
128
+ (_b = globalData === null || globalData === void 0 ? void 0 : globalData.processosJuridicosData) === null || _b === void 0 ? void 0 : _b.isLoaded,
129
+ (_c = globalData === null || globalData === void 0 ? void 0 : globalData.processosJuridicosData) === null || _c === void 0 ? void 0 : _c.empresa,
130
+ isProcessoNaoEncontrado,
131
+ setData
132
+ ]);
133
+ // Don't render if no indications were found
134
+ if (processedRef.current && resultRef.current === 'Não encontrado')
86
135
  return null;
87
- }
88
- return (React.createElement(Section, { title: "Liminares para Remo\u00E7\u00E3o de Protesto", subtitle: "Ind\u00EDcios de liminares para oculta\u00E7\u00E3o de registros.", icon: ProtestosIcon, ctx: derivedCtx, onSuccess: function (doc) {
89
- var _a;
90
- var globalMessage = ((_a = globalData === null || globalData === void 0 ? void 0 : globalData.liminar) === null || _a === void 0 ? void 0 : _a.message) || 'Não encontrado';
91
- return {
92
- children: React.createElement(React.Fragment, null),
93
- variant: globalMessage === 'Encontrado' ? 'error' : 'default',
94
- description: (React.createElement(StatusMessage, { type: globalMessage === 'Encontrado' ? 'error' : 'default' }, globalMessage))
95
- };
96
- } }));
136
+ return (React.createElement(Section, { title: "Liminares para Remo\u00E7\u00E3o de Protesto", subtitle: processingRef.current
137
+ ? 'Carregando liminar...'
138
+ : 'Indícios de liminares para ocultação de registros.', icon: ProtestosIcon, ctx: processingRef.current ? __assign(__assign({}, ctx), { type: RequestStatus.Loading }) : derivedCtx, onSuccess: processingRef.current
139
+ ? undefined
140
+ : function (data, context) {
141
+ var _a;
142
+ var globalMessage = ((_a = globalData === null || globalData === void 0 ? void 0 : globalData.liminar) === null || _a === void 0 ? void 0 : _a.message) || 'Não encontrado';
143
+ var variant = globalMessage === 'Encontrado' ? 'error' : 'default';
144
+ return {
145
+ children: React.createElement(React.Fragment, null),
146
+ variant: variant,
147
+ description: (React.createElement(StatusMessage, { type: variant }, globalMessage))
148
+ };
149
+ } }));
97
150
  };
98
151
  export default Liminar;
@@ -1,5 +1,17 @@
1
1
  import React from 'react';
2
+ import { StatusMapType } from '@/@types/domain/reclameAquiTypes';
3
+ export interface ReclameAquiCompany {
4
+ nome: string;
5
+ cnpj: string;
6
+ score: string;
7
+ status: string | StatusMapType;
8
+ shortname: string;
9
+ imageUrl: string;
10
+ quantidadeProblemasResolvidos: string;
11
+ percentualProblemasResolvidos: string;
12
+ }
2
13
  export declare const ReclameAquiCarousel: React.FC<{
3
14
  documento: string;
4
15
  nome: string;
16
+ companies?: ReclameAquiCompany[];
5
17
  }>;
@@ -10,14 +10,12 @@ var __assign = (this && this.__assign) || function () {
10
10
  return __assign.apply(this, arguments);
11
11
  };
12
12
  /* eslint-disable @typescript-eslint/no-unused-vars */
13
- import React, { memo, useState } from 'react';
13
+ import React, { memo } from 'react';
14
14
  import Carousel from '../common/carousel';
15
- import { useQuery } from '../webservice';
16
15
  import ChevronLeft from '../../assets/btn/chevronLeft';
17
16
  import ChevronRight from '../../assets/btn/chevronRight';
18
17
  import { formatValue } from '../../utils/number';
19
18
  import { statusMap } from '../../constants/reclameAqui';
20
- import { useGlobalData } from '../../contexts/globalDataContext';
21
19
  import Carrousel from '../dossie/carrousel/carrousel';
22
20
  import { CarrouselBtn, CompanyName, ContainerSummary, DocumentContainer, DocumentPrefix, LogoContainer, ProblemsSolved, ReclameAquiStatsContainer, StatsImage, StyledImage } from './styles';
23
21
  var translateStatus = function (status) {
@@ -51,30 +49,16 @@ var ReclameAquiStats = function (_a) {
51
49
  "/10")),
52
50
  React.createElement(ProblemasResolvidos, { value: percentualProblemasResolvidos + '%' }))));
53
51
  };
52
+ // Convert this to a pure presentational component
54
53
  export var ReclameAquiCarousel = memo(function (_a) {
55
- var _b;
56
- var nome = _a.nome, documento = _a.documento;
57
- var _c = useQuery("SELECT FROM 'RECLAMEAQUI'.'CONSULTA'", { documento: documento }), response = _c.response, isLoading = _c.isLoading, error = _c.error;
58
- var setData = useGlobalData().setData;
59
- var _d = useState(false), dataUpdated = _d[0], setDataUpdated = _d[1];
60
- if (isLoading ||
61
- error ||
62
- ((response === null || response === void 0 ? void 0 : response.document) && !((_b = response === null || response === void 0 ? void 0 : response.document) === null || _b === void 0 ? void 0 : _b.length))) {
54
+ var nome = _a.nome, documento = _a.documento, companies = _a.companies;
55
+ // If no companies data is provided, fallback to regular carousel
56
+ if (!companies || companies.length === 0) {
63
57
  return React.createElement(Carrousel, { name: nome, document: documento });
64
58
  }
65
- var companies = response === null || response === void 0 ? void 0 : response.document.map(function (item) { return ({
66
- nome: nome,
67
- cnpj: documento,
68
- score: item.infos.finalScore,
69
- status: item.infos.status,
70
- shortname: item.infos.shortname,
71
- imageUrl: item.infos.logo,
72
- quantidadeProblemasResolvidos: item.infos.count.toString(),
73
- percentualProblemasResolvidos: item.infos.solvedPercentual
74
- }); });
75
59
  return (React.createElement(ContainerSummary, null,
76
- React.createElement(Carousel, { pagination: false, isRTL: false, showArrows: companies && companies.length > 1, renderArrow: function (_a) {
60
+ React.createElement(Carousel, { pagination: false, isRTL: false, showArrows: companies.length > 1, renderArrow: function (_a) {
77
61
  var type = _a.type, onClick = _a.onClick;
78
62
  return (React.createElement(CarrouselBtn, null, type === 'PREV' ? (React.createElement(ChevronLeft, { onClick: onClick })) : (React.createElement(ChevronRight, { onClick: onClick }))));
79
- } }, companies === null || companies === void 0 ? void 0 : companies.map(function (empresa, index) { return (React.createElement(ReclameAquiStats, __assign({ key: index }, empresa))); }))));
63
+ } }, companies.map(function (empresa, index) { return (React.createElement(ReclameAquiStats, __assign({ key: "reclameaqui-".concat(index) }, empresa))); }))));
80
64
  });
@@ -208,6 +208,7 @@ export function useQuery(query, data, enabled) {
208
208
  var _c = useState(false), isLoading = _c[0], setIsLoading = _c[1];
209
209
  var _d = useState(false), shouldFetch = _d[0], setShouldFetch = _d[1];
210
210
  var loadingProgressRef = useRef(0);
211
+ var memoizedData = useMemo(function () { return data; }, [JSON.stringify(data)]);
211
212
  var simulateProgress = useCallback(function () {
212
213
  loadingProgressRef.current = 0;
213
214
  var progress = 0;
@@ -227,7 +228,7 @@ export function useQuery(query, data, enabled) {
227
228
  simulateProgress();
228
229
  var abortController = new AbortController();
229
230
  client
230
- .request(query, data, undefined, abortController.signal)
231
+ .request(query, memoizedData, undefined, abortController.signal)
231
232
  .then(function (response) {
232
233
  return Client.WebService.parse(response).then(function (document) { return ({
233
234
  response: response,
@@ -252,20 +253,20 @@ export function useQuery(query, data, enabled) {
252
253
  setShouldFetch(false);
253
254
  });
254
255
  return function () { return abortController.abort(); };
255
- }, [shouldFetch, isLoading, client, query, data, simulateProgress]);
256
+ }, [shouldFetch, isLoading, client, query, memoizedData, simulateProgress]);
257
+ useEffect(function () {
258
+ if (enabled && !response && !error && !isLoading && !shouldFetch) {
259
+ setShouldFetch(true);
260
+ }
261
+ }, []);
256
262
  useEffect(function () {
257
263
  if (enabled && shouldFetch) {
258
264
  fetch();
259
265
  }
260
266
  }, [fetch, shouldFetch, enabled]);
261
- useEffect(function () {
262
- if (enabled && !isLoading && !shouldFetch && !response && !error) {
263
- setShouldFetch(true);
264
- }
265
- }, [enabled, isLoading, shouldFetch, response, error]);
266
267
  var refetch = useCallback(function () {
267
268
  setShouldFetch(true);
268
- }, [query]);
269
+ }, []);
269
270
  return {
270
271
  response: response,
271
272
  error: error,