@credithub/harlan-components 1.109.3 → 1.110.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.
@@ -3,7 +3,7 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook
3
3
  return cooked;
4
4
  };
5
5
  import styled from 'styled-components';
6
- var BtnWrapper = styled.div(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n width: 30px;\n height: 30px;\n background-color: ", ";\n border-radius: 50%;\n display: flex;\n justify-content: center;\n align-items: center;\n cursor: pointer;\n\n @media print {\n display: none;\n }\n"], ["\n width: 30px;\n height: 30px;\n background-color: ", ";\n border-radius: 50%;\n display: flex;\n justify-content: center;\n align-items: center;\n cursor: pointer;\n\n @media print {\n display: none;\n }\n"])), function (_a) {
6
+ var BtnWrapper = styled.div(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n width: 30px;\n height: 30px;\n background-color: ", ";\n border-radius: 50%;\n display: flex;\n justify-content: center;\n align-items: center;\n cursor: pointer;\n\n @media print {\n display: none !important;\n visibility: hidden !important;\n pointer-events: none !important;\n }\n"], ["\n width: 30px;\n height: 30px;\n background-color: ", ";\n border-radius: 50%;\n display: flex;\n justify-content: center;\n align-items: center;\n cursor: pointer;\n\n @media print {\n display: none !important;\n visibility: hidden !important;\n pointer-events: none !important;\n }\n"])), function (_a) {
7
7
  var theme = _a.theme;
8
8
  return theme.colors.cinza85;
9
9
  });
@@ -32,14 +32,21 @@ var SkipButton = styled.button(templateObject_8 || (templateObject_8 = __makeTem
32
32
  });
33
33
  var PrintButton = function (_a) {
34
34
  var onClick = _a.onClick, _b = _a.isLoading, isLoading = _b === void 0 ? false : _b, _c = _a.tooltipMessage, tooltipMessage = _c === void 0 ? 'Carregando dados das consultas...' : _c;
35
- var button = (React.createElement(BtnWrapper, { onClick: !isLoading ? onClick : undefined },
35
+ var requestImmediatePrint = function () {
36
+ var _a, _b;
37
+ if (typeof window !== 'undefined') {
38
+ (_b = (_a = window.__harlanPrintState) === null || _a === void 0 ? void 0 : _a.forceReady) === null || _b === void 0 ? void 0 : _b.call(_a);
39
+ }
40
+ onClick === null || onClick === void 0 ? void 0 : onClick();
41
+ };
42
+ var button = (React.createElement(BtnWrapper, { onClick: !isLoading ? requestImmediatePrint : undefined },
36
43
  React.createElement(IconContainer, null, isLoading ? React.createElement(Spinner, null) : React.createElement(PrintIcon, null))));
37
44
  if (isLoading) {
38
45
  return (React.createElement(TooltipWrapper, null,
39
46
  React.createElement(Tooltip, { placement: "left", content: React.createElement(TooltipContent, null,
40
47
  React.createElement(TooltipTitle, null, "\uD83D\uDCC4 Preparando impress\u00E3o"),
41
48
  React.createElement(TooltipMessage, null, tooltipMessage),
42
- onClick && (React.createElement(SkipButton, { onClick: onClick }, "Imprimir agora"))), icon: button })));
49
+ onClick && (React.createElement(SkipButton, { onClick: requestImmediatePrint }, "Imprimir agora"))), icon: button })));
43
50
  }
44
51
  return button;
45
52
  };
@@ -15,7 +15,7 @@ export var ContainerSummary = styled.div(templateObject_2 || (templateObject_2 =
15
15
  export var ContentSummary = styled.div(templateObject_3 || (templateObject_3 = __makeTemplateObject(["\n display: grid;\n grid-row: 1 / 8;\n grid-template-columns: repeat(4, 1fr);\n gap: 0 16px;\n\n @media (max-width: 1280px) {\n grid-template-columns: repeat(3, 1fr);\n justify-content: center;\n align-items: center;\n }\n\n @media (max-width: 768px) {\n display: grid;\n grid-template-columns: repeat(2, 1fr);\n flex-direction: row;\n width: 100%;\n }\n"], ["\n display: grid;\n grid-row: 1 / 8;\n grid-template-columns: repeat(4, 1fr);\n gap: 0 16px;\n\n @media (max-width: 1280px) {\n grid-template-columns: repeat(3, 1fr);\n justify-content: center;\n align-items: center;\n }\n\n @media (max-width: 768px) {\n display: grid;\n grid-template-columns: repeat(2, 1fr);\n flex-direction: row;\n width: 100%;\n }\n"])));
16
16
  export var FieldSummary = styled.div(templateObject_4 || (templateObject_4 = __makeTemplateObject(["\n align-items: center;\n margin-bottom: 16px;\n grid-column: ", ";\n"], ["\n align-items: center;\n margin-bottom: 16px;\n grid-column: ", ";\n"])), function (props) { return (props.fullRow ? '1 / 3' : 'auto'); });
17
17
  export var ButtonsSummary = styled.div(templateObject_5 || (templateObject_5 = __makeTemplateObject(["\n @media (max-width: 768px) {\n align-items: center;\n max-width: 100%;\n }\n"], ["\n @media (max-width: 768px) {\n align-items: center;\n max-width: 100%;\n }\n"])));
18
- export var ButtonsWrapper = styled.div(templateObject_6 || (templateObject_6 = __makeTemplateObject(["\n display: flex;\n gap: 10px;\n min-width: fit-content;\n flex-direction: column;\n\n @media print {\n display: none;\n }\n"], ["\n display: flex;\n gap: 10px;\n min-width: fit-content;\n flex-direction: column;\n\n @media print {\n display: none;\n }\n"])));
18
+ export var ButtonsWrapper = styled.div(templateObject_6 || (templateObject_6 = __makeTemplateObject(["\n display: flex;\n gap: 10px;\n min-width: fit-content;\n flex-direction: column;\n\n @media print {\n display: none !important;\n visibility: hidden !important;\n }\n"], ["\n display: flex;\n gap: 10px;\n min-width: fit-content;\n flex-direction: column;\n\n @media print {\n display: none !important;\n visibility: hidden !important;\n }\n"])));
19
19
  export var SummaryButton = styled(Button)(templateObject_7 || (templateObject_7 = __makeTemplateObject(["\n height: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n\n background: ", ";\n color: ", ";\n cursor: ", ";\n opacity: ", ";\n pointer-events: ", ";\n\n &:hover {\n background: ", ";\n }\n"], ["\n height: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n\n background: ", ";\n color: ", ";\n cursor: ", ";\n opacity: ", ";\n pointer-events: ", ";\n\n &:hover {\n background: ", ";\n }\n"])), function (_a) {
20
20
  var theme = _a.theme, disabled = _a.disabled;
21
21
  return disabled ? theme.colors.cinzaClaro : theme.colors.azulCredithub;
@@ -78,7 +78,7 @@ var HeaderUI = styled(function (_a) {
78
78
  return (React.createElement("header", __assign({}, props), children));
79
79
  })(templateObject_4 || (templateObject_4 = __makeTemplateObject(["\n @media screen {\n background: #ffffff !important;\n box-shadow: 0px 4px 5px rgba(0, 0, 0, 0.15);\n border-radius: 30px;\n }\n\n @media print {\n page-break-before: avoid;\n page-break-after: avoid;\n page-break-inside: avoid;\n padding: 18px;\n print-color-adjust: exact;\n background: #eae9e9;\n border-radius: 18px;\n }\n\n padding: 30px 20px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n\n ", " {\n color: ", ";\n }\n"], ["\n @media screen {\n background: #ffffff !important;\n box-shadow: 0px 4px 5px rgba(0, 0, 0, 0.15);\n border-radius: 30px;\n }\n\n @media print {\n page-break-before: avoid;\n page-break-after: avoid;\n page-break-inside: avoid;\n padding: 18px;\n print-color-adjust: exact;\n background: #eae9e9;\n border-radius: 18px;\n }\n\n padding: 30px 20px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n\n ", " {\n color: ", ";\n }\n"])), Title, function (props) { return props.color; });
80
80
  var HeaderContainer = styled.div(templateObject_5 || (templateObject_5 = __makeTemplateObject(["\n display: flex;\n gap: 20px;\n\n @media print {\n width: 100%;\n }\n"], ["\n display: flex;\n gap: 20px;\n\n @media print {\n width: 100%;\n }\n"])));
81
- var ActionsList = styled.div(templateObject_6 || (templateObject_6 = __makeTemplateObject(["\n display: flex;\n flex-direction: row;\n gap: 10px;\n"], ["\n display: flex;\n flex-direction: row;\n gap: 10px;\n"])));
81
+ var ActionsList = styled.div(templateObject_6 || (templateObject_6 = __makeTemplateObject(["\n display: flex;\n flex-direction: row;\n gap: 10px;\n\n @media print {\n display: none !important;\n visibility: hidden !important;\n }\n"], ["\n display: flex;\n flex-direction: row;\n gap: 10px;\n\n @media print {\n display: none !important;\n visibility: hidden !important;\n }\n"])));
82
82
  var IconWrapper = styled.div(templateObject_7 || (templateObject_7 = __makeTemplateObject(["\n display: flex;\n align-items: flex-start;\n padding-top: 5px;\n width: 30px;\n"], ["\n display: flex;\n align-items: flex-start;\n padding-top: 5px;\n width: 30px;\n"])));
83
83
  var TextWrapper = styled.div(templateObject_8 || (templateObject_8 = __makeTemplateObject(["\n display: flex;\n flex-direction: column;\n gap: 10px;\n\n .text-wrapper-subtitle-description {\n display: flex;\n flex-direction: row;\n flex-wrap: wrap;\n gap: 20px;\n align-items: center;\n\n @media (max-width: 768px) {\n align-items: flex-start;\n }\n\n @media print {\n flex-direction: row;\n }\n }\n"], ["\n display: flex;\n flex-direction: column;\n gap: 10px;\n\n .text-wrapper-subtitle-description {\n display: flex;\n flex-direction: row;\n flex-wrap: wrap;\n gap: 20px;\n align-items: center;\n\n @media (max-width: 768px) {\n align-items: flex-start;\n }\n\n @media print {\n flex-direction: row;\n }\n }\n"])));
84
84
  var LoadingBarWrapper = styled.div(templateObject_9 || (templateObject_9 = __makeTemplateObject(["\n width: 100%;\n max-width: 300px;\n height: 10px;\n opacity: ", ";\n transition: opacity 0.3s ease;\n"], ["\n width: 100%;\n max-width: 300px;\n height: 10px;\n opacity: ", ";\n transition: opacity 0.3s ease;\n"])), function (_a) {
@@ -44,42 +44,57 @@ var BtnWrapper = styled.div(templateObject_2 || (templateObject_2 = __makeTempla
44
44
  // Função utilitária para extrair as chaves dos protestos
45
45
  var getChaves = function (arr) { return arr.map(function (p) { return p.nm_chave; }); };
46
46
  var PROTESTOS_ERROR_SUMMARY = 'Falha ao consultar protestos, tente novamente mais tarde.';
47
+ var clearProtestosCollections = function (state) { return (__assign(__assign({}, (state || {})), { protestosDeCredito: undefined, protestosDeImposto: undefined, protestosGerais: undefined, totalProtestos: undefined, valorTotalProtestos: undefined, nmChaves: undefined })); };
47
48
  var Protestos = function () {
48
- var _a;
49
+ var _a, _b;
49
50
  var ctx = useContext(Queries.Protestos);
50
51
  var ctxLiminar = useContext(Queries.Liminar);
51
- var _b = useGlobalData(), globalData = _b.data, setData = _b.setData;
52
- var _c = useState(false), dataUpdated = _c[0], setDataUpdated = _c[1];
52
+ var _c = useGlobalData(), globalData = _c.data, setData = _c.setData;
53
+ var _d = useState(false), dataUpdated = _d[0], setDataUpdated = _d[1];
53
54
  var protestosAll = useMemo(function () {
54
55
  if (!ctx.document)
55
56
  return [];
56
57
  return XPathUtils.selectArray('//body//protesto', ctx.document).map(parseProtesto);
57
58
  }, [ctx.document]);
58
59
  var iaOverrides = (_a = globalData.protestosData) === null || _a === void 0 ? void 0 : _a.iaOverrides;
59
- var _d = useProtestosClassification(protestosAll, iaOverrides), protestosDeCredito = _d.protestosDeCredito, protestosDeImposto = _d.protestosDeImposto, protestosGerais = _d.protestosGerais;
60
+ var _e = useProtestosClassification(protestosAll, iaOverrides), protestosDeCredito = _e.protestosDeCredito, protestosDeImposto = _e.protestosDeImposto, protestosGerais = _e.protestosGerais;
60
61
  useEffect(function () {
62
+ var _a;
63
+ var prevProtestos = globalData.protestosData;
61
64
  if ((ctx === null || ctx === void 0 ? void 0 : ctx.type) === RequestStatus.Error) {
62
- setData(function (prevState) { return (__assign(__assign({}, prevState), { protestosData: {
63
- isLoaded: true,
64
- error: { summary: PROTESTOS_ERROR_SUMMARY }
65
- } })); });
65
+ var alreadyErrored = (prevProtestos === null || prevProtestos === void 0 ? void 0 : prevProtestos.isLoaded) === true &&
66
+ (prevProtestos === null || prevProtestos === void 0 ? void 0 : prevProtestos.isLoading) === false &&
67
+ ((_a = prevProtestos === null || prevProtestos === void 0 ? void 0 : prevProtestos.error) === null || _a === void 0 ? void 0 : _a.summary) === PROTESTOS_ERROR_SUMMARY;
68
+ if (alreadyErrored)
69
+ return;
70
+ setData(function (prevState) {
71
+ var current = prevState.protestosData;
72
+ return __assign(__assign({}, prevState), { protestosData: __assign(__assign({}, clearProtestosCollections(current)), { isLoaded: true, isLoading: false, error: { summary: PROTESTOS_ERROR_SUMMARY } }) });
73
+ });
66
74
  return;
67
75
  }
68
76
  if ((ctx === null || ctx === void 0 ? void 0 : ctx.type) === RequestStatus.Empty) {
69
- setData(function (prevState) { return (__assign(__assign({}, prevState), { protestosData: { isLoaded: true } })); });
70
- return;
77
+ var alreadyPending = (prevProtestos === null || prevProtestos === void 0 ? void 0 : prevProtestos.isLoaded) === false &&
78
+ (prevProtestos === null || prevProtestos === void 0 ? void 0 : prevProtestos.isLoading) === true &&
79
+ !(prevProtestos === null || prevProtestos === void 0 ? void 0 : prevProtestos.error);
80
+ if (alreadyPending)
81
+ return;
82
+ setData(function (prevState) {
83
+ var current = prevState.protestosData;
84
+ return __assign(__assign({}, prevState), { protestosData: __assign(__assign({}, clearProtestosCollections(current)), { isLoaded: false, isLoading: true, error: undefined }) });
85
+ });
71
86
  }
72
- }, [ctx.type, setData]);
87
+ }, [ctx === null || ctx === void 0 ? void 0 : ctx.type, globalData === null || globalData === void 0 ? void 0 : globalData.protestosData, setData]);
73
88
  useEffect(function () {
74
89
  if (dataUpdated || !ctx.document)
75
90
  return;
76
91
  var registros = protestosAll.length;
77
92
  var haveException = /Falha na integra/gi.test(XPathUtils.select('string(//raw)', ctx.document));
78
93
  if (haveException) {
79
- setData(function (prevState) { return (__assign(__assign({}, prevState), { protestosData: {
80
- isLoaded: true,
81
- error: { summary: PROTESTOS_ERROR_SUMMARY }
82
- } })); });
94
+ setData(function (prevState) {
95
+ var prevProtestos = prevState.protestosData;
96
+ return __assign(__assign({}, prevState), { protestosData: __assign(__assign({}, clearProtestosCollections(prevProtestos)), { isLoaded: true, isLoading: false, error: { summary: PROTESTOS_ERROR_SUMMARY } }) });
97
+ });
83
98
  setDataUpdated(true);
84
99
  return;
85
100
  }
@@ -91,17 +106,8 @@ var Protestos = function () {
91
106
  return total + valorNumero;
92
107
  }, 0);
93
108
  setData(function (prevState) {
94
- var _a;
95
- return (__assign(__assign({}, prevState), { protestos: registros, protestosData: {
96
- protestosDeCredito: protestosDeCredito,
97
- protestosDeImposto: protestosDeImposto,
98
- protestosGerais: protestosGerais,
99
- totalProtestos: registros,
100
- valorTotalProtestos: valorTotalProtestos,
101
- isLoaded: true,
102
- iaOverrides: (_a = prevState.protestosData) === null || _a === void 0 ? void 0 : _a.iaOverrides,
103
- nmChaves: nmChave
104
- } }));
109
+ var prevProtestos = prevState.protestosData;
110
+ return __assign(__assign({}, prevState), { protestos: registros, protestosData: __assign(__assign({}, clearProtestosCollections(prevProtestos)), { protestosDeCredito: protestosDeCredito, protestosDeImposto: protestosDeImposto, protestosGerais: protestosGerais, totalProtestos: registros, valorTotalProtestos: valorTotalProtestos, isLoaded: true, isLoading: false, error: undefined, iaOverrides: prevProtestos === null || prevProtestos === void 0 ? void 0 : prevProtestos.iaOverrides, nmChaves: nmChave, failedInstruments: prevProtestos === null || prevProtestos === void 0 ? void 0 : prevProtestos.failedInstruments, failedInstrumentReasons: prevProtestos === null || prevProtestos === void 0 ? void 0 : prevProtestos.failedInstrumentReasons, instrumentCache: prevProtestos === null || prevProtestos === void 0 ? void 0 : prevProtestos.instrumentCache, checkedInstruments: prevProtestos === null || prevProtestos === void 0 ? void 0 : prevProtestos.checkedInstruments }) });
105
111
  });
106
112
  setDataUpdated(true);
107
113
  }, [
@@ -113,10 +119,20 @@ var Protestos = function () {
113
119
  protestosGerais
114
120
  ]);
115
121
  useEffect(function () {
116
- if ((ctx === null || ctx === void 0 ? void 0 : ctx.type) === RequestStatus.Loading) {
117
- setData(function (prevState) { return (__assign(__assign({}, prevState), { protestosData: __assign(__assign({}, (prevState.protestosData || {})), { isLoaded: false }) })); });
118
- }
119
- }, [ctx.type]);
122
+ if ((ctx === null || ctx === void 0 ? void 0 : ctx.type) !== RequestStatus.Loading)
123
+ return;
124
+ var prevProtestos = globalData.protestosData;
125
+ var alreadyLoading = (prevProtestos === null || prevProtestos === void 0 ? void 0 : prevProtestos.isLoaded) === false &&
126
+ (prevProtestos === null || prevProtestos === void 0 ? void 0 : prevProtestos.isLoading) === true &&
127
+ !(prevProtestos === null || prevProtestos === void 0 ? void 0 : prevProtestos.error);
128
+ if (alreadyLoading)
129
+ return;
130
+ setDataUpdated(false);
131
+ setData(function (prevState) {
132
+ var current = prevState.protestosData;
133
+ return __assign(__assign({}, prevState), { protestosData: __assign(__assign({}, clearProtestosCollections(current)), { isLoaded: false, isLoading: true, error: undefined, iaOverrides: current === null || current === void 0 ? void 0 : current.iaOverrides, failedInstruments: current === null || current === void 0 ? void 0 : current.failedInstruments, failedInstrumentReasons: current === null || current === void 0 ? void 0 : current.failedInstrumentReasons, instrumentCache: current === null || current === void 0 ? void 0 : current.instrumentCache, checkedInstruments: current === null || current === void 0 ? void 0 : current.checkedInstruments }) });
134
+ });
135
+ }, [ctx === null || ctx === void 0 ? void 0 : ctx.type, globalData === null || globalData === void 0 ? void 0 : globalData.protestosData, setData]);
120
136
  var handleSuccess = useCallback(function (data) {
121
137
  var parsed = XPathUtils.selectArray('//body//protesto', data).map(parseProtesto);
122
138
  var registros = parsed.length;
@@ -150,7 +166,18 @@ var Protestos = function () {
150
166
  : 'Não há ocorrência de protesto'))
151
167
  };
152
168
  }, [iaOverrides]);
153
- return (React.createElement(Section, { ctx: ctx, title: "Apontamentos na Central de Protestos (CENPROT)", subtitle: "Consulta de protestos de cr\u00E9dito, imposto e gerais.", icon: ProtestosIcon, onSuccess: handleSuccess, actions: typeof harlan !== 'undefined' ? (React.createElement(BtnWrapper, null,
169
+ var effectiveCtx = useMemo(function () {
170
+ var _a, _b;
171
+ if (!ctx)
172
+ return ctx;
173
+ var shouldForceLoading = ((_b = (_a = globalData === null || globalData === void 0 ? void 0 : globalData.protestosData) === null || _a === void 0 ? void 0 : _a.isLoading) !== null && _b !== void 0 ? _b : false) &&
174
+ ctx.type !== RequestStatus.Error;
175
+ if (shouldForceLoading && ctx.type !== RequestStatus.Loading) {
176
+ return __assign(__assign({}, ctx), { type: RequestStatus.Loading });
177
+ }
178
+ return ctx;
179
+ }, [ctx, (_b = globalData === null || globalData === void 0 ? void 0 : globalData.protestosData) === null || _b === void 0 ? void 0 : _b.isLoading]);
180
+ return (React.createElement(Section, { ctx: effectiveCtx, title: "Apontamentos na Central de Protestos (CENPROT)", subtitle: "Consulta de protestos de cr\u00E9dito, imposto e gerais.", icon: ProtestosIcon, onSuccess: handleSuccess, actions: typeof harlan !== 'undefined' ? (React.createElement(BtnWrapper, null,
154
181
  React.createElement(Button, { onClick: function () {
155
182
  var _a;
156
183
  // Obtém o documento do contexto e formata adequadamente
@@ -45,11 +45,22 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
45
45
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
46
46
  }
47
47
  };
48
+ var __rest = (this && this.__rest) || function (s, e) {
49
+ var t = {};
50
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
51
+ t[p] = s[p];
52
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
53
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
54
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
55
+ t[p[i]] = s[p[i]];
56
+ }
57
+ return t;
58
+ };
48
59
  import { useGlobalData } from '../../contexts/globalDataContext';
49
60
  import { formatMoney } from '../../utils/number';
50
61
  import { openFormThenRedirect } from '../../utils/protestosp';
51
62
  import { formatDocument } from '../../utils/string';
52
- import React, { memo, useContext, useEffect, useState } from 'react';
63
+ import React, { memo, useCallback, useContext, useEffect, useMemo, useState } from 'react';
53
64
  import AddItemField from '../common/addItem';
54
65
  import Button from '../common/button';
55
66
  import { ResultContent } from '../interface/result';
@@ -68,6 +79,34 @@ var processQueue = function () {
68
79
  nextRequest();
69
80
  }
70
81
  };
82
+ var instrumentActiveRequests = 0;
83
+ var MAX_CONCURRENT_INSTRUMENT_REQUESTS = 2;
84
+ var instrumentRequestQueue = [];
85
+ var processInstrumentQueue = function () {
86
+ if (instrumentRequestQueue.length === 0 ||
87
+ instrumentActiveRequests >= MAX_CONCURRENT_INSTRUMENT_REQUESTS)
88
+ return;
89
+ var nextRequest = instrumentRequestQueue.shift();
90
+ if (nextRequest) {
91
+ instrumentActiveRequests++;
92
+ nextRequest();
93
+ }
94
+ };
95
+ var normalizeInstrumentKey = function (key) {
96
+ return key ? key.replace(/\D+/g, '') : '';
97
+ };
98
+ var isInstrumentKeyValid = function (key) {
99
+ if (!key)
100
+ return false;
101
+ var normalized = normalizeInstrumentKey(key);
102
+ if (!normalized)
103
+ return false;
104
+ if (normalized.length < 5)
105
+ return false;
106
+ if (!/^[0-9]+$/.test(normalized))
107
+ return false;
108
+ return true;
109
+ };
71
110
  // Elegant three-dot loader component
72
111
  var ThreeDotsLoader = function () {
73
112
  // CSS for the loader container
@@ -119,18 +158,21 @@ export var ProtestoItem = memo(function (_a) {
119
158
  return value === 'true' ? 'Sim' : 'Não';
120
159
  };
121
160
  var fetchQuemApresentou = function (nm_chave) { return __awaiter(void 0, void 0, void 0, function () {
122
- var response, nomeDetectado_1, error_1;
161
+ var normalizedKey, response, nomeDetectado_1, error_1;
123
162
  return __generator(this, function (_a) {
124
163
  switch (_a.label) {
125
164
  case 0:
126
- if (!nm_chave)
165
+ if (!isInstrumentKeyValid(nm_chave))
166
+ return [2 /*return*/];
167
+ normalizedKey = normalizeInstrumentKey(nm_chave);
168
+ if (!normalizedKey)
127
169
  return [2 /*return*/];
128
170
  setLoading(true);
129
171
  _a.label = 1;
130
172
  case 1:
131
173
  _a.trys.push([1, 4, 5, 6]);
132
174
  return [4 /*yield*/, client.request("SELECT FROM 'PDFPROTESTO'.'AI'", {
133
- nm_chave: nm_chave,
175
+ nm_chave: normalizedKey,
134
176
  documento: documento
135
177
  })];
136
178
  case 2: return [4 /*yield*/, (_a.sent()).json()];
@@ -188,7 +230,7 @@ export var ProtestoItem = memo(function (_a) {
188
230
  var nomeCedente = protesto.nomeCedente;
189
231
  if (nomeCedente && nomeCedente.trim() !== '')
190
232
  return;
191
- if (nm_chave) {
233
+ if (isInstrumentKeyValid(nm_chave)) {
192
234
  queueOrExecuteFetch(nm_chave);
193
235
  }
194
236
  return function () {
@@ -230,48 +272,229 @@ export var ProtestoItem = memo(function (_a) {
230
272
  export var Instrumento = function (_a) {
231
273
  var nm_chave = _a.nm_chave, cpfCnpj = _a.cpfCnpj;
232
274
  var client = useContext(WebService);
233
- var _b = useState(), error = _b[0], setError = _b[1];
234
- var _c = useState(false), isLoading = _c[0], setIsLoading = _c[1];
275
+ var _b = useGlobalData(), setData = _b.setData, globalData = _b.data;
276
+ var protestosData = (globalData === null || globalData === void 0 ? void 0 : globalData.protestosData) || {};
277
+ var failedInstruments = protestosData.failedInstruments || {};
278
+ var failedInstrumentReasons = protestosData.failedInstrumentReasons || {};
279
+ var checkedInstruments = protestosData.checkedInstruments || {};
280
+ var instrumentCache = protestosData.instrumentCache || {};
281
+ var normalizedKey = useMemo(function () { return normalizeInstrumentKey(nm_chave); }, [nm_chave]);
235
282
  if (!nm_chave)
236
283
  return null;
237
- return (React.createElement(Button, { onClick: function () { return __awaiter(void 0, void 0, void 0, function () {
238
- var request, pdfWindow, e_1;
284
+ var hasFailedBefore = failedInstruments[nm_chave] === true;
285
+ var failureReason = failedInstrumentReasons[nm_chave];
286
+ var alreadyChecked = checkedInstruments[nm_chave] === true;
287
+ var cachedInstrument = instrumentCache[nm_chave];
288
+ var hasCpfCnpj = Boolean(cpfCnpj && cpfCnpj.trim() !== '');
289
+ var isValidKey = useMemo(function () { return isInstrumentKeyValid(nm_chave); }, [nm_chave]);
290
+ var shouldPrefetch = isValidKey &&
291
+ hasCpfCnpj &&
292
+ normalizedKey &&
293
+ !hasFailedBefore &&
294
+ !alreadyChecked;
295
+ var classifyInstrumentError = function (err) {
296
+ var rawMessage = err instanceof Error ? err.message : String(err !== null && err !== void 0 ? err : '').toString();
297
+ if (/chave.+inv[aá]lid/i.test(rawMessage) ||
298
+ /invalid key/i.test(rawMessage)) {
299
+ return 'invalid-key';
300
+ }
301
+ return 'not-found';
302
+ };
303
+ var deriveErrorKind = useCallback(function () {
304
+ if (!hasCpfCnpj)
305
+ return 'missing-doc';
306
+ if (!isValidKey)
307
+ return 'invalid-key';
308
+ if (failureReason === 'invalid-key' || failureReason === 'not-found')
309
+ return failureReason;
310
+ if (hasFailedBefore)
311
+ return 'not-found';
312
+ return null;
313
+ }, [failureReason, hasCpfCnpj, hasFailedBefore, isValidKey]);
314
+ var _c = useState(deriveErrorKind), errorKind = _c[0], setErrorKind = _c[1];
315
+ var _d = useState(false), isLoading = _d[0], setIsLoading = _d[1];
316
+ var _e = useState(shouldPrefetch), isPrefetching = _e[0], setIsPrefetching = _e[1];
317
+ useEffect(function () {
318
+ setErrorKind(deriveErrorKind());
319
+ }, [deriveErrorKind]);
320
+ useEffect(function () {
321
+ if (!shouldPrefetch) {
322
+ return;
323
+ }
324
+ var cancelled = false;
325
+ var runRequest = function () { return __awaiter(void 0, void 0, void 0, function () {
326
+ var response_1, prefetchError_1, failure_1;
239
327
  return __generator(this, function (_a) {
240
328
  switch (_a.label) {
241
329
  case 0:
242
- setIsLoading(true);
243
- if (/^35/.test(nm_chave)) {
244
- openFormThenRedirect(nm_chave, cpfCnpj);
245
- setIsLoading(false);
330
+ if (cancelled) {
331
+ instrumentActiveRequests--;
332
+ processInstrumentQueue();
246
333
  return [2 /*return*/];
247
334
  }
335
+ setIsPrefetching(function (prev) { return (prev ? prev : true); });
248
336
  _a.label = 1;
249
337
  case 1:
250
338
  _a.trys.push([1, 4, 5, 6]);
251
339
  return [4 /*yield*/, client.request("SELECT FROM 'IEPTB'.'PDF'", {
252
- nm_chave: nm_chave,
340
+ nm_chave: normalizedKey,
253
341
  documento: cpfCnpj
254
342
  })];
255
343
  case 2: return [4 /*yield*/, (_a.sent()).json()];
256
344
  case 3:
257
- request = _a.sent();
258
- pdfWindow = window.open('', '_blank');
259
- if (!pdfWindow)
345
+ response_1 = _a.sent();
346
+ if (cancelled)
260
347
  return [2 /*return*/];
261
- pdfWindow.document.write("<iframe width='100%' height='100%' src='data:application/pdf;base64,".concat(request === null || request === void 0 ? void 0 : request.instrumentoProtesto, "'></iframe>"));
348
+ if (!(response_1 === null || response_1 === void 0 ? void 0 : response_1.instrumentoProtesto)) {
349
+ throw new Error('Instrumento não retornado pela API');
350
+ }
351
+ setData(function (prev) {
352
+ var _a, _b;
353
+ var base = prev || {};
354
+ var prevProtestosData = base.protestosData || {};
355
+ var _c = prevProtestosData.failedInstruments || {}, _d = nm_chave, _removedFailed = _c[_d], restFailed = __rest(_c, [typeof _d === "symbol" ? _d : _d + ""]);
356
+ var _e = prevProtestosData.failedInstrumentReasons || {}, _f = nm_chave, _removedReason = _e[_f], restReasons = __rest(_e, [typeof _f === "symbol" ? _f : _f + ""]);
357
+ 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)) }) });
358
+ });
359
+ setErrorKind(null);
262
360
  return [3 /*break*/, 6];
263
361
  case 4:
264
- e_1 = _a.sent();
265
- console.error(e_1);
266
- setError(true);
362
+ prefetchError_1 = _a.sent();
363
+ if (cancelled)
364
+ return [2 /*return*/];
365
+ failure_1 = classifyInstrumentError(prefetchError_1);
366
+ setErrorKind(failure_1);
367
+ setData(function (prev) {
368
+ var _a, _b, _c;
369
+ var base = prev || {};
370
+ var prevProtestosData = base.protestosData || {};
371
+ var _d = prevProtestosData.instrumentCache || {}, _e = nm_chave, _cachedInstrument = _d[_e], restCache = __rest(_d, [typeof _e === "symbol" ? _e : _e + ""]);
372
+ 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)) }) });
373
+ });
267
374
  return [3 /*break*/, 6];
268
375
  case 5:
269
- setIsLoading(false);
376
+ if (!cancelled) {
377
+ setIsPrefetching(false);
378
+ }
379
+ instrumentActiveRequests--;
380
+ processInstrumentQueue();
270
381
  return [7 /*endfinally*/];
271
382
  case 6: return [2 /*return*/];
272
383
  }
273
384
  });
274
- }); }, disabled: isLoading }, error ? 'Instrumento não Localizado' : 'Instrumento'));
385
+ }); };
386
+ if (instrumentActiveRequests < MAX_CONCURRENT_INSTRUMENT_REQUESTS) {
387
+ instrumentActiveRequests++;
388
+ runRequest();
389
+ }
390
+ else {
391
+ instrumentRequestQueue.push(runRequest);
392
+ }
393
+ return function () {
394
+ cancelled = true;
395
+ };
396
+ }, [
397
+ client,
398
+ cpfCnpj,
399
+ hasCpfCnpj,
400
+ nm_chave,
401
+ normalizedKey,
402
+ setData,
403
+ shouldPrefetch
404
+ ]);
405
+ var isDisabled = isLoading || isPrefetching || errorKind !== null;
406
+ var getTooltipMessage = function () {
407
+ if (errorKind === 'missing-doc')
408
+ return 'Documento não disponível para consulta';
409
+ if (errorKind === 'invalid-key')
410
+ return 'Chave de instrumento inválida';
411
+ if (errorKind === 'not-found')
412
+ return 'Instrumento não localizado no sistema';
413
+ if (isPrefetching)
414
+ return 'Verificando disponibilidade do instrumento...';
415
+ return '';
416
+ };
417
+ var getButtonLabel = function () {
418
+ if (errorKind === 'not-found')
419
+ return 'Instrumento não Localizado';
420
+ if (errorKind === 'invalid-key' || errorKind === 'missing-doc')
421
+ return 'Instrumento Indisponível';
422
+ return 'Instrumento';
423
+ };
424
+ var tooltipMessage = getTooltipMessage();
425
+ var openInstrumentPdf = function (base64) {
426
+ var pdfWindow = window.open('', '_blank');
427
+ if (!pdfWindow)
428
+ return;
429
+ pdfWindow.document.write("<iframe width='100%' height='100%' src='data:application/pdf;base64,".concat(base64, "'></iframe>"));
430
+ };
431
+ return (React.createElement("span", { title: tooltipMessage, style: { display: 'inline-block' } },
432
+ React.createElement(Button, { isLoading: isLoading, onClick: function () { return __awaiter(void 0, void 0, void 0, function () {
433
+ var request_1, e_1, failure_2;
434
+ return __generator(this, function (_a) {
435
+ switch (_a.label) {
436
+ case 0:
437
+ if (isDisabled)
438
+ return [2 /*return*/];
439
+ if (/^35/.test(normalizedKey)) {
440
+ setIsLoading(true);
441
+ try {
442
+ openFormThenRedirect(normalizedKey, cpfCnpj);
443
+ }
444
+ finally {
445
+ setIsLoading(false);
446
+ }
447
+ return [2 /*return*/];
448
+ }
449
+ if (cachedInstrument) {
450
+ openInstrumentPdf(cachedInstrument);
451
+ return [2 /*return*/];
452
+ }
453
+ setIsLoading(true);
454
+ _a.label = 1;
455
+ case 1:
456
+ _a.trys.push([1, 4, 5, 6]);
457
+ return [4 /*yield*/, client.request("SELECT FROM 'IEPTB'.'PDF'", {
458
+ nm_chave: normalizedKey,
459
+ documento: cpfCnpj
460
+ })];
461
+ case 2: return [4 /*yield*/, (_a.sent()).json()];
462
+ case 3:
463
+ request_1 = _a.sent();
464
+ if (!(request_1 === null || request_1 === void 0 ? void 0 : request_1.instrumentoProtesto)) {
465
+ throw new Error('Instrumento não retornado pela API');
466
+ }
467
+ openInstrumentPdf(request_1.instrumentoProtesto);
468
+ setData(function (prev) {
469
+ var _a, _b;
470
+ var base = prev || {};
471
+ var prevProtestosData = base.protestosData || {};
472
+ var _c = prevProtestosData.failedInstruments || {}, _d = nm_chave, _removedFailed = _c[_d], restFailed = __rest(_c, [typeof _d === "symbol" ? _d : _d + ""]);
473
+ var _e = prevProtestosData.failedInstrumentReasons || {}, _f = nm_chave, _removedReason = _e[_f], restReasons = __rest(_e, [typeof _f === "symbol" ? _f : _f + ""]);
474
+ 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)) }) });
475
+ });
476
+ setErrorKind(null);
477
+ return [3 /*break*/, 6];
478
+ case 4:
479
+ e_1 = _a.sent();
480
+ console.error(e_1);
481
+ failure_2 = classifyInstrumentError(e_1);
482
+ setErrorKind(failure_2);
483
+ setData(function (prev) {
484
+ var _a, _b, _c;
485
+ var base = prev || {};
486
+ var prevProtestosData = base.protestosData || {};
487
+ var _d = prevProtestosData.instrumentCache || {}, _e = nm_chave, _cachedInstrument = _d[_e], restCache = __rest(_d, [typeof _e === "symbol" ? _e : _e + ""]);
488
+ 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)) }) });
489
+ });
490
+ return [3 /*break*/, 6];
491
+ case 5:
492
+ setIsLoading(false);
493
+ return [7 /*endfinally*/];
494
+ case 6: return [2 /*return*/];
495
+ }
496
+ });
497
+ }); }, disabled: isDisabled }, getButtonLabel())));
275
498
  };
276
499
  export var ProtestosList = function (_a) {
277
500
  var protestos = _a.protestos;
@@ -29,9 +29,10 @@ import BtnWrapper from '../assets/btn/btnWrapper';
29
29
  import ChevronDown from '../assets/btn/chevronDown';
30
30
  import ChevronUp from '../assets/btn/chevronUp';
31
31
  import { usePrintMode } from '../contexts/printModeContext';
32
+ import { usePrintReadiness } from '../contexts/printReadinessContext';
32
33
  import useToggle from '../hooks/useToggle';
33
34
  import cn from 'classnames';
34
- import React, { forwardRef, useCallback, useMemo } from 'react';
35
+ import React, { forwardRef, useCallback, useEffect, useMemo, useRef } from 'react';
35
36
  import styled from 'styled-components';
36
37
  import Button from './common/button';
37
38
  import { PrintSectionWrapper } from './common/printSectionWrapper';
@@ -39,6 +40,40 @@ import Header from './interface/header';
39
40
  import StatusMessage from './interface/statusMessage';
40
41
  import { RequestStatus } from './webservice';
41
42
  var ButtonWrapper = styled.div(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n justify-content: center;\n width: 100%;\n height: 40%;\n max-height: 52px;\n max-width: 300px;\n margin: 0 auto;\n"], ["\n justify-content: center;\n width: 100%;\n height: 40%;\n max-height: 52px;\n max-width: 300px;\n margin: 0 auto;\n"])));
43
+ var sectionIdCounter = 0;
44
+ var nextSectionId = function () {
45
+ sectionIdCounter += 1;
46
+ return "section-".concat(sectionIdCounter);
47
+ };
48
+ var stringifyTitle = function (title) {
49
+ if (typeof title === 'string')
50
+ return title;
51
+ return undefined;
52
+ };
53
+ var useSectionPrintBlocker = function (ctx, title, enabled, registerBlocker, resolveBlocker) {
54
+ var blockerIdRef = useRef(nextSectionId());
55
+ useEffect(function () {
56
+ if (!enabled)
57
+ return;
58
+ return function () {
59
+ resolveBlocker(blockerIdRef.current);
60
+ };
61
+ }, [enabled, resolveBlocker]);
62
+ useEffect(function () {
63
+ var _a;
64
+ if (!enabled || !ctx)
65
+ return;
66
+ var shouldBlock = ctx.type === RequestStatus.Loading ||
67
+ ctx.type === RequestStatus.Empty ||
68
+ ((_a = ctx.activeRequests) !== null && _a !== void 0 ? _a : 0) > 0;
69
+ if (shouldBlock) {
70
+ registerBlocker(blockerIdRef.current, stringifyTitle(title));
71
+ }
72
+ else {
73
+ resolveBlocker(blockerIdRef.current);
74
+ }
75
+ }, [ctx, enabled, registerBlocker, resolveBlocker, title]);
76
+ };
42
77
  var Section = forwardRef(function (_a, ref) {
43
78
  var onSuccess = _a.onSuccess, _b = _a.isError, isError = _b === void 0 ? function (err, ctx) {
44
79
  var shouldPush = (err === null || err === void 0 ? void 0 : err.push) === true;
@@ -55,6 +90,9 @@ var Section = forwardRef(function (_a, ref) {
55
90
  } : _b, _c = _a.onLoading, onLoading = _c === void 0 ? function () { return React.createElement(React.Fragment, null); } : _c, ctx = _a.ctx, className = _a.className, _d = _a.hideHeader, hideHeader = _d === void 0 ? false : _d, _e = _a.minimized, minimized = _e === void 0 ? false : _e, headerProps = __rest(_a, ["onSuccess", "isError", "onLoading", "ctx", "className", "hideHeader", "minimized"]);
56
91
  var _f = useToggle(!minimized), isOpen = _f[0], toggleOpen = _f[1];
57
92
  var printMode = usePrintMode().printMode;
93
+ var printReadiness = usePrintReadiness();
94
+ var readinessEnabled = Boolean(printMode && printReadiness.enabled);
95
+ useSectionPrintBlocker(ctx, headerProps === null || headerProps === void 0 ? void 0 : headerProps.title, readinessEnabled, printReadiness.registerBlocker, printReadiness.resolveBlocker);
58
96
  if (!ctx)
59
97
  return null;
60
98
  var type = ctx.type, progress = ctx.progress, warningMessage = ctx.warningMessage;
@@ -436,7 +436,7 @@ export function query(query) {
436
436
  }
437
437
  export var Queries = {
438
438
  Finder: query("SELECT FROM 'FINDER'.'BILLING'"),
439
- Protestos: query("SELECT FROM 'IEPTB'.'IEPTBHARLAN'"),
439
+ Protestos: query("SELECT FROM 'APICENPROTTESTE'.'CONSULTA'"),
440
440
  CCF: query("SELECT FROM 'SEEKLOC'.'CCF'"),
441
441
  ProcessosJuridicos: query("SELECT FROM 'PROCESSOSJURIDICOS'.'PROCESSOS'"),
442
442
  Liminar: query("SELECT FROM 'LIMINAR'.'CONSULTA'"),