@tunnelhub/connector-closecare 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,166 @@
1
+ # PolyForm Shield License 1.0.0
2
+
3
+ <https://polyformproject.org/licenses/shield/1.0.0>
4
+
5
+ ## Acceptance
6
+
7
+ In order to get any license under these terms, you must agree
8
+ to them as both strict obligations and conditions to all
9
+ your licenses.
10
+
11
+ ## Copyright License
12
+
13
+ The licensor grants you a copyright license for the
14
+ software to do everything you might do with the software
15
+ that would otherwise infringe the licensor's copyright
16
+ in it for any permitted purpose. However, you may
17
+ only distribute the software according to [Distribution
18
+ License](#distribution-license) and make changes or new works
19
+ based on the software according to [Changes and New Works
20
+ License](#changes-and-new-works-license).
21
+
22
+ ## Distribution License
23
+
24
+ The licensor grants you an additional copyright license
25
+ to distribute copies of the software. Your license
26
+ to distribute covers distributing the software with
27
+ changes and new works permitted by [Changes and New Works
28
+ License](#changes-and-new-works-license).
29
+
30
+ ## Notices
31
+
32
+ You must ensure that anyone who gets a copy of any part of
33
+ the software from you also gets a copy of these terms or the
34
+ URL for them above, as well as copies of any plain-text lines
35
+ beginning with `Required Notice:` that the licensor provided
36
+ with the software. For example:
37
+
38
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
39
+
40
+ ## Changes and New Works License
41
+
42
+ The licensor grants you an additional copyright license to
43
+ make changes and new works based on the software for any
44
+ permitted purpose.
45
+
46
+ ## Patent License
47
+
48
+ The licensor grants you a patent license for the software that
49
+ covers patent claims the licensor can license, or becomes able
50
+ to license, that you would infringe by using the software.
51
+
52
+ ## Noncompete
53
+
54
+ Any purpose is a permitted purpose, except for providing any
55
+ product that competes with the software or any product the
56
+ licensor or any of its affiliates provides using the software.
57
+
58
+ ## Competition
59
+
60
+ Goods and services compete even when they provide functionality
61
+ through different kinds of interfaces or for different technical
62
+ platforms. Applications can compete with services, libraries
63
+ with plugins, frameworks with development tools, and so on,
64
+ even if they're written in different programming languages
65
+ or for different computer architectures. Goods and services
66
+ compete even when provided free of charge. If you market a
67
+ product as a practical substitute for the software or another
68
+ product, it definitely competes.
69
+
70
+ ## New Products
71
+
72
+ If you are using the software to provide a product that does
73
+ not compete, but the licensor or any of its affiliates brings
74
+ your product into competition by providing a new version of
75
+ the software or another product using the software, you may
76
+ continue using versions of the software available under these
77
+ terms beforehand to provide your competing product, but not
78
+ any later versions.
79
+
80
+ ## Discontinued Products
81
+
82
+ You may begin using the software to compete with a product
83
+ or service that the licensor or any of its affiliates has
84
+ stopped providing, unless the licensor includes a plain-text
85
+ line beginning with `Licensor Line of Business:` with the
86
+ software that mentions that line of business. For example:
87
+
88
+ > Licensor Line of Business: YoyodyneCMS Content Management
89
+ System (http://example.com/cms)
90
+
91
+ ## Sales of Business
92
+
93
+ If the licensor or any of its affiliates sells a line of
94
+ business developing the software or using the software
95
+ to provide a product, the buyer can also enforce
96
+ [Noncompete](#noncompete) for that product.
97
+
98
+ ## Fair Use
99
+
100
+ You may have "fair use" rights for the software under the
101
+ law. These terms do not limit them.
102
+
103
+ ## No Other Rights
104
+
105
+ These terms do not allow you to sublicense or transfer any of
106
+ your licenses to anyone else, or prevent the licensor from
107
+ granting licenses to anyone else. These terms do not imply
108
+ any other licenses.
109
+
110
+ ## Patent Defense
111
+
112
+ If you make any written claim that the software infringes or
113
+ contributes to infringement of any patent, your patent license
114
+ for the software granted under these terms ends immediately. If
115
+ your company makes such a claim, your patent license ends
116
+ immediately for work on behalf of your company.
117
+
118
+ ## Violations
119
+
120
+ The first time you are notified in writing that you have
121
+ violated any of these terms, or done anything with the software
122
+ not covered by your licenses, your licenses can nonetheless
123
+ continue if you come into full compliance with these terms,
124
+ and take practical steps to correct past violations, within
125
+ 32 days of receiving notice. Otherwise, all your licenses
126
+ end immediately.
127
+
128
+ ## No Liability
129
+
130
+ ***As far as the law allows, the software comes as is, without
131
+ any warranty or condition, and the licensor will not be liable
132
+ to you for any damages arising out of these terms or the use
133
+ or nature of the software, under any kind of legal claim.***
134
+
135
+ ## Definitions
136
+
137
+ The **licensor** is the individual or entity offering these
138
+ terms, and the **software** is the software the licensor makes
139
+ available under these terms.
140
+
141
+ A **product** can be a good or service, or a combination
142
+ of them.
143
+
144
+ **You** refers to the individual or entity agreeing to these
145
+ terms.
146
+
147
+ **Your company** is any legal entity, sole proprietorship,
148
+ or other kind of organization that you work for, plus all
149
+ its affiliates.
150
+
151
+ **Affiliates** means the other organizations than an
152
+ organization has control over, is under the control of, or is
153
+ under common control with.
154
+
155
+ **Control** means ownership of substantially all the assets of
156
+ an entity, or the power to direct its management and policies
157
+ by vote, contract, or otherwise. Control can be direct or
158
+ indirect.
159
+
160
+ **Your licenses** are all the licenses granted to you for the
161
+ software under these terms.
162
+
163
+ **Use** means anything you do with the software requiring one
164
+ of your licenses.
165
+
166
+ Required Notice: Copyright 4success/TunnelHub (https://tunnelhub.io)
package/README.md CHANGED
@@ -1,3 +1,76 @@
1
- # Temporary Holding Version
1
+ # @tunnelhub/connector-closecare
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Cliente CloseCare REST com configuração explícita, Node 24/26 e saídas ESM/CJS. Sem dependência de runtime do SDK TunnelHub. Os mesmos pacotes são usados em Lambda e ECS.
4
+
5
+ ```ts
6
+ import {CloseCareConnector, closeCareInterceptorIgnoreUrls} from '@tunnelhub/connector-closecare';
7
+
8
+ const config = {
9
+ companyId: 'empresa',
10
+ clientId: process.env.CLOSECARE_CLIENT_ID!,
11
+ clientSecret: process.env.CLOSECARE_CLIENT_SECRET!,
12
+ };
13
+ const closecare = new CloseCareConnector(config);
14
+ const response = await closecare.atestados.list({fornecedor: 'soc', sync: ['not_sync', 'error']});
15
+ await closecare.sync.sickNotes({items: [{sick_note_id: 'id', success: true, vendor: 'soc'}]});
16
+ ```
17
+
18
+ `baseUrl` é opcional, com padrão `https://api.closecare.com.br`. `oauthTokenUrl` permite sobrescrever o endpoint padrão `{baseUrl}/v3/oauth/token`. `timeout` é em milissegundos (padrão 60.000); `logger.info` recebe apenas metadados da chamada. Credenciais, tokens, URLs completas e corpos não são registrados. O pacote não carrega sistemas TunnelHub nem decide mapeamentos da integração.
19
+
20
+ ## Operações
21
+
22
+ | Método | Endpoint | Política | Validação |
23
+ | --- | --- | --- | --- |
24
+ | `pessoas.importar` | POST v4/import/people | write | exposed |
25
+ | `pessoas.cadastrar` | POST v4/people | write | exposed |
26
+ | `atestados.list` | GET v5/documents/leave | read | exposed |
27
+ | `atestados.sendLeaveJson` | POST v5/documents/leave_json | write | exposed |
28
+ | `documentos.sendOccupationalJson` | POST v5/documents/occupational_json | write | exposed |
29
+ | `sync.sickNotes` | POST v4/sync/sick_notes | write | exposed |
30
+
31
+ Todos os caminhos incluem `/companies/{companyId}`. `exposed` significa contrato tipado e testes de transporte com respostas sintéticas; não representa execução no sandbox CloseCare nem migração de clientes. As operações diretas preservam os payloads do fornecedor. A importação de pessoas recebe `{items: [...]}` e retorna `batch_id`; esse identificador confirma o recebimento do lote, não o processamento de cada pessoa.
32
+
33
+ A listagem aceita os filtros do OpenAPI (nomes originais), `dataAtualizacaoMin` como alias de `data_atualizacao_min` e uma lista de `sync`. A ausência de `sync` mantém o comportamento padrão da API. Consultas por vários `sync` são sequenciais; duplicatas idênticas são removidas, mas versões conflitantes provocam erro para não escolher silenciosamente dados clínicos.
34
+
35
+ **Paginação de atestados pendente de contrato:** o OpenAPI consultado não define page/offset/cursor para `documents/leave`. O conector não inventa parâmetros; se a resposta trouxer `total` diferente de `items.length`, lança `InvalidResponseError` antes de entregar dados parciais. O `total` do retorno agregado é o número de itens únicos confirmados. Usuários e reembolsos têm paginação distinta na especificação, mas não integram esta entrega. Não existe helper genérico de paginação sem consumidor validado.
36
+
37
+ ## OAuth e falhas
38
+
39
+ O token é adquirido com `client_id` e `client_secret` em formulário, conforme contrato CloseCare; cache e uma aquisição compartilhada por instância evitam autenticação redundante. Após HTTP 401, o token é invalidado e há somente uma nova tentativa autenticada, inclusive para a escrita explicitamente recusada. Redirects não são seguidos.
40
+
41
+ | Falha | Resultado |
42
+ | --- | --- |
43
+ | 401 persistente / credenciais recusadas | `AuthError` |
44
+ | 403 na API | `PermissionError` |
45
+ | 400/422 | `ValidationError` |
46
+ | 409 | `CloseCareDuplicateError`, com `existingId` quando informado pela API |
47
+ | 429/5xx ou falha de transporte | leitura: até três tentativas; escrita: sem retry, `uncertain=true` |
48
+ | JSON inválido / confirmação de escrita sem identificador | `InvalidResponseError`; escrita com `uncertain=true` |
49
+
50
+ Mensagens livres do fornecedor nunca entram no texto do erro, no `cause` ou no logger. Não reenvie automaticamente uma escrita incerta: reconcilie no destino. As respostas `sync.sickNotes` podem ter corpo vazio, conforme OpenAPI.
51
+
52
+ ## Interceptor TunnelHub
53
+
54
+ Se a automação usar `log_http_requests`, configure todas as exclusões na **primeira** chamada ao interceptor. O pacote não ativa nem modifica o interceptor.
55
+
56
+ ```ts
57
+ import {setupInterceptor} from '@tunnelhub/sdk';
58
+ import {socInterceptorIgnoreUrls} from '@tunnelhub/connector-soc';
59
+
60
+ setupInterceptor({ignoreUrls: [
61
+ ...socInterceptorIgnoreUrls(socConfig),
62
+ ...closeCareInterceptorIgnoreUrls(config),
63
+ ]});
64
+ ```
65
+
66
+ O helper cobre a API efetiva e o OAuth, inclusive URLs sobrescritas. O teste com interceptor ativo verifica a composição SOC + CloseCare e ausência de credenciais, Bearer e dados pessoais no console.
67
+
68
+ ## Contrato e tipos
69
+
70
+ Fonte versionada: `openapi/closecare.yaml`, cópia da especificação pública CloseCare v4.2 já mantida em `th-closecare-casas-bahia-funcionarios/docs/openapi-closecare.yaml`, consultada em 17/11/2026. Não foi localizada uma URL pública atualizada da especificação; a homologação no sandbox e confirmação da paginação permanecem pendentes.
71
+
72
+ `pnpm closecare:generate` extrai os schemas dos seis endpoints e gera `src/generated/types.ts` com `json-schema-to-typescript`. O script normaliza `nullable` e propriedades com `required: true`; itens de `required` inexistentes naquele objeto são descartados (o schema de sync declara campos de item no objeto externo). Não se adicionam campos obrigatórios nem regras de negócio inferidas. O conteúdo do OpenAPI original é preservado, com remoção apenas de espaços finais de linha. Tipos não substituem validação no fornecedor.
73
+
74
+ ## Licença
75
+
76
+ PolyForm Shield 1.0.0. Preserve os avisos da licença no bundle; não configure `legalComments: 'none'`.
package/dist/index.cjs ADDED
@@ -0,0 +1,225 @@
1
+ /*! @license PolyForm-Shield-1.0.0 https://polyformproject.org/licenses/shield/1.0.0 Required Notice: Copyright 4success/TunnelHub (https://tunnelhub.io) */
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ CloseCareConnector: () => CloseCareConnector,
25
+ CloseCareDuplicateError: () => CloseCareDuplicateError,
26
+ closeCareInterceptorIgnoreUrls: () => closeCareInterceptorIgnoreUrls,
27
+ manifest: () => manifest
28
+ });
29
+ module.exports = __toCommonJS(index_exports);
30
+ var import_node_util = require("util");
31
+ var import_connector_core3 = require("@tunnelhub/connector-core");
32
+
33
+ // src/config.ts
34
+ var import_connector_core = require("@tunnelhub/connector-core");
35
+ var DEFAULT_BASE_URL = "https://api.closecare.com.br";
36
+ function closeCareInterceptorIgnoreUrls(config) {
37
+ const base = (0, import_connector_core.validateHttpUrl)(config.baseUrl ?? DEFAULT_BASE_URL).toString().replace(/\/$/, "");
38
+ const oauth = config.oauthTokenUrl ?? `${base}/v3/oauth/token`;
39
+ (0, import_connector_core.validateHttpUrl)(oauth);
40
+ return [.../* @__PURE__ */ new Set([base, oauth])];
41
+ }
42
+ function validateConfig(config) {
43
+ for (const key of ["companyId", "clientId", "clientSecret"]) {
44
+ if (typeof config[key] !== "string" || !config[key].trim())
45
+ throw new import_connector_core.ConfigError(`Configura\xE7\xE3o obrigat\xF3ria: ${key}.`);
46
+ }
47
+ if (config.companyId === "." || config.companyId === "..")
48
+ throw new import_connector_core.ConfigError(
49
+ "companyId n\xE3o pode ser um segmento relativo de URL."
50
+ );
51
+ const baseUrl = (0, import_connector_core.validateHttpUrl)(config.baseUrl ?? DEFAULT_BASE_URL).toString().replace(/\/$/, "");
52
+ const oauthTokenUrl = config.oauthTokenUrl ?? `${baseUrl}/v3/oauth/token`;
53
+ (0, import_connector_core.validateHttpUrl)(oauthTokenUrl);
54
+ return { ...config, baseUrl, oauthTokenUrl };
55
+ }
56
+
57
+ // src/errors.ts
58
+ var import_connector_core2 = require("@tunnelhub/connector-core");
59
+ var CloseCareDuplicateError = class extends import_connector_core2.BusinessError {
60
+ constructor(existingId) {
61
+ super("O registro j\xE1 existe na CloseCare.", { code: "HTTP-409" });
62
+ this.existingId = existingId;
63
+ }
64
+ existingId;
65
+ name = "CloseCareDuplicateError";
66
+ };
67
+
68
+ // src/index.ts
69
+ var manifest = {
70
+ pessoas: {
71
+ importar: { kind: "write", stability: "exposed" },
72
+ cadastrar: { kind: "write", stability: "exposed" }
73
+ },
74
+ atestados: {
75
+ list: { kind: "read", stability: "exposed" },
76
+ sendLeaveJson: { kind: "write", stability: "exposed" }
77
+ },
78
+ documentos: { sendOccupationalJson: { kind: "write", stability: "exposed" } },
79
+ sync: { sickNotes: { kind: "write", stability: "exposed" } }
80
+ };
81
+ function record(value) {
82
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
83
+ }
84
+ function resultWithId(value, field) {
85
+ if (typeof record(value)?.[field] !== "string" || !String(record(value)?.[field]).trim())
86
+ throw new import_connector_core3.InvalidResponseError(
87
+ "Resposta CloseCare sem identificador de confirma\xE7\xE3o.",
88
+ { uncertain: true }
89
+ );
90
+ return value;
91
+ }
92
+ var CloseCareConnector = class {
93
+ pessoas;
94
+ atestados;
95
+ documentos;
96
+ sync;
97
+ constructor(input) {
98
+ const config = validateConfig(input);
99
+ const oauth = new import_connector_core3.OAuthClientCredentials({
100
+ tokenUrl: config.oauthTokenUrl,
101
+ clientId: config.clientId,
102
+ clientSecret: config.clientSecret,
103
+ timeout: config.timeout,
104
+ logger: config.logger
105
+ });
106
+ const http = new import_connector_core3.HttpClient({
107
+ baseUrl: config.baseUrl,
108
+ service: "CloseCare",
109
+ oauth,
110
+ timeout: config.timeout,
111
+ logger: config.logger,
112
+ classifyError: (status, body) => {
113
+ if (status !== 409) return void 0;
114
+ const id = record(body)?.id;
115
+ return new CloseCareDuplicateError(
116
+ typeof id === "string" ? id : void 0
117
+ );
118
+ }
119
+ });
120
+ const company = encodeURIComponent(config.companyId);
121
+ const v4 = `v4/companies/${company}`;
122
+ const documents = `v5/companies/${company}/documents`;
123
+ this.pessoas = {
124
+ importar: (body) => http.request(
125
+ "pessoas.importar",
126
+ manifest.pessoas.importar.kind,
127
+ `${v4}/import/people`,
128
+ { method: "POST", body },
129
+ (value) => resultWithId(value, "batch_id")
130
+ ),
131
+ cadastrar: (body) => http.request(
132
+ "pessoas.cadastrar",
133
+ manifest.pessoas.cadastrar.kind,
134
+ `${v4}/people`,
135
+ { method: "POST", body },
136
+ (value) => resultWithId(value, "id")
137
+ )
138
+ };
139
+ this.atestados = {
140
+ list: (params = {}) => listLeaves(http, documents, params),
141
+ sendLeaveJson: (body) => http.request(
142
+ "atestados.sendLeaveJson",
143
+ manifest.atestados.sendLeaveJson.kind,
144
+ `${documents}/leave_json`,
145
+ { method: "POST", body },
146
+ (value) => resultWithId(value, "protocolo")
147
+ )
148
+ };
149
+ this.documentos = {
150
+ sendOccupationalJson: (body) => http.request(
151
+ "documentos.sendOccupationalJson",
152
+ manifest.documentos.sendOccupationalJson.kind,
153
+ `${documents}/occupational_json`,
154
+ { method: "POST", body },
155
+ (value) => resultWithId(value, "protocolo")
156
+ )
157
+ };
158
+ this.sync = {
159
+ sickNotes: (body) => http.request(
160
+ "sync.sickNotes",
161
+ manifest.sync.sickNotes.kind,
162
+ `${v4}/sync/sick_notes`,
163
+ { method: "POST", body },
164
+ () => void 0
165
+ )
166
+ };
167
+ }
168
+ };
169
+ async function listLeaves(http, documents, params) {
170
+ if (params.dataAtualizacaoMin && params.data_atualizacao_min && params.dataAtualizacaoMin !== params.data_atualizacao_min)
171
+ throw new import_connector_core3.ValidationError(
172
+ "Informe apenas uma data inicial de atualiza\xE7\xE3o."
173
+ );
174
+ const { sync, dataAtualizacaoMin, ...filters } = params;
175
+ if (dataAtualizacaoMin) filters.data_atualizacao_min = dataAtualizacaoMin;
176
+ const selections = sync === void 0 ? [void 0] : typeof sync === "string" ? [sync] : [...new Set(sync)];
177
+ if (!selections.length)
178
+ throw new import_connector_core3.ValidationError("sync n\xE3o pode ser uma lista vazia.");
179
+ const combined = /* @__PURE__ */ new Map();
180
+ for (const selected of selections) {
181
+ const query = new URLSearchParams();
182
+ for (const [key, value] of Object.entries({ ...filters, sync: selected })) {
183
+ if (value === void 0) continue;
184
+ for (const item of Array.isArray(value) ? value : [value])
185
+ query.append(key, String(item));
186
+ }
187
+ const page = await http.request(
188
+ "atestados.list",
189
+ manifest.atestados.list.kind,
190
+ `${documents}/leave`,
191
+ { method: "GET", query },
192
+ (value) => {
193
+ const data = record(value);
194
+ if (!data || !Array.isArray(data.items))
195
+ throw new import_connector_core3.InvalidResponseError("Listagem CloseCare sem items.");
196
+ if (data.total !== void 0 && (!Number.isInteger(data.total) || data.total !== data.items.length))
197
+ throw new import_connector_core3.InvalidResponseError(
198
+ "Listagem CloseCare incompleta ou total inconsistente. O contrato de pagina\xE7\xE3o de atestados precisa ser confirmado."
199
+ );
200
+ for (const item of data.items)
201
+ if (typeof record(item)?.id_atestado !== "string" || !String(record(item)?.id_atestado).trim())
202
+ throw new import_connector_core3.InvalidResponseError(
203
+ "Atestado CloseCare sem identificador."
204
+ );
205
+ return data.items;
206
+ }
207
+ );
208
+ for (const item of page) {
209
+ const id = item.id_atestado;
210
+ if (combined.has(id) && !(0, import_node_util.isDeepStrictEqual)(combined.get(id), item))
211
+ throw new import_connector_core3.InvalidResponseError(
212
+ "Vers\xF5es conflitantes do mesmo atestado. Refa\xE7a a leitura antes de processar."
213
+ );
214
+ combined.set(id, item);
215
+ }
216
+ }
217
+ return { items: [...combined.values()], total: combined.size };
218
+ }
219
+ // Annotate the CommonJS export names for ESM import in node:
220
+ 0 && (module.exports = {
221
+ CloseCareConnector,
222
+ CloseCareDuplicateError,
223
+ closeCareInterceptorIgnoreUrls,
224
+ manifest
225
+ });