brisa-sdk 0.0.0-stage → 0.2.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/CHANGELOG.md +24 -0
- package/LICENSE +21 -0
- package/README.md +90 -2
- package/dist/index.cjs +621 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +928 -0
- package/dist/index.d.ts +928 -0
- package/dist/index.js +590 -0
- package/dist/index.js.map +1 -0
- package/docs/01-primeiros-passos.md +106 -0
- package/docs/02-autenticacao.md +55 -0
- package/docs/03-documentos.md +80 -0
- package/docs/04-pagamentos.md +69 -0
- package/docs/05-impressao.md +44 -0
- package/docs/06-dados-bancarios.md +42 -0
- package/docs/07-clientes-e-extrato.md +61 -0
- package/docs/08-artigos-e-stock.md +38 -0
- package/docs/09-saft.md +23 -0
- package/docs/10-webhooks.md +42 -0
- package/docs/11-erros.md +52 -0
- package/docs/12-idempotencia-e-limites.md +29 -0
- package/docs/13-sandbox-e-producao.md +25 -0
- package/docs/README.md +35 -0
- package/docs/openapi.json +16772 -0
- package/docs/upgrade.md +23 -0
- package/package.json +67 -4
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,928 @@
|
|
|
1
|
+
declare const DEFAULT_BASE_URL = "https://api.brisa.ao";
|
|
2
|
+
interface BrisaOptions {
|
|
3
|
+
/** A chave de API (`brk_...` em produção, `brk_sbx...` na sandbox). Por omissão, `process.env.BRISA_API_KEY`. */
|
|
4
|
+
apiKey?: string;
|
|
5
|
+
/** Por omissão `https://api.brisa.ao` (ou `process.env.BRISA_API_URL`). A chave escolhe o ambiente, não o endereço. */
|
|
6
|
+
baseUrl?: string;
|
|
7
|
+
/** Tempo máximo de cada tentativa, em milissegundos (por omissão 30 000). */
|
|
8
|
+
timeoutMs?: number;
|
|
9
|
+
/** Repetições em `429`, `502`, `503` e falhas de rede (por omissão 2). */
|
|
10
|
+
maxRetries?: number;
|
|
11
|
+
/** Espera máxima aceite de um `Retry-After`, em milissegundos (por omissão 60 000): acima disso o erro sobe logo. */
|
|
12
|
+
maxRetryDelayMs?: number;
|
|
13
|
+
/** Uma implementação de `fetch` (por omissão a global). */
|
|
14
|
+
fetch?: typeof fetch;
|
|
15
|
+
/** Cabeçalhos acrescentados a todos os pedidos. */
|
|
16
|
+
headers?: Record<string, string>;
|
|
17
|
+
}
|
|
18
|
+
interface RequestOptions {
|
|
19
|
+
/** `Idempotency-Key` (8 a 128 caracteres `A-Z a-z 0-9 _ . : -`). Nas criações, o SDK gera um se não o indicar. */
|
|
20
|
+
idempotencyKey?: string;
|
|
21
|
+
signal?: AbortSignal;
|
|
22
|
+
timeoutMs?: number;
|
|
23
|
+
maxRetries?: number;
|
|
24
|
+
headers?: Record<string, string>;
|
|
25
|
+
}
|
|
26
|
+
interface RateLimit {
|
|
27
|
+
/** Pedidos permitidos por minuto. */
|
|
28
|
+
limit: number;
|
|
29
|
+
/** Pedidos que ainda pode fazer. */
|
|
30
|
+
remaining: number;
|
|
31
|
+
/** Segundos até o contador repor. */
|
|
32
|
+
reset: number;
|
|
33
|
+
}
|
|
34
|
+
interface ApiResponse<T> {
|
|
35
|
+
data: T;
|
|
36
|
+
status: number;
|
|
37
|
+
headers: Headers;
|
|
38
|
+
/** `true` quando a resposta é a de uma tentativa anterior com o mesmo `Idempotency-Key`. */
|
|
39
|
+
replayed: boolean;
|
|
40
|
+
rateLimit?: RateLimit;
|
|
41
|
+
}
|
|
42
|
+
type ResponseKind = 'json' | 'text' | 'bytes';
|
|
43
|
+
interface Request {
|
|
44
|
+
method: 'GET' | 'POST' | 'PUT' | 'DELETE';
|
|
45
|
+
path: string;
|
|
46
|
+
query?: object;
|
|
47
|
+
body?: unknown;
|
|
48
|
+
/** Como ler a resposta (por omissão JSON). */
|
|
49
|
+
as?: ResponseKind;
|
|
50
|
+
accept?: string;
|
|
51
|
+
}
|
|
52
|
+
/** Gera um `Idempotency-Key` aleatório (`brisa-js-<uuid>`). */
|
|
53
|
+
declare function idempotencyKey(): string;
|
|
54
|
+
/** Segundos de um `Retry-After` (número ou data HTTP). */
|
|
55
|
+
declare function parseRetryAfter(value: string | null, now?: number): number | undefined;
|
|
56
|
+
declare class HttpClient {
|
|
57
|
+
readonly baseUrl: string;
|
|
58
|
+
private readonly apiKey;
|
|
59
|
+
private readonly timeoutMs;
|
|
60
|
+
private readonly maxRetries;
|
|
61
|
+
private readonly maxRetryDelayMs;
|
|
62
|
+
private readonly fetchImpl;
|
|
63
|
+
private readonly headers;
|
|
64
|
+
/** Os limites de pedidos da última resposta. */
|
|
65
|
+
lastRateLimit?: RateLimit;
|
|
66
|
+
constructor(options?: BrisaOptions);
|
|
67
|
+
url(path: string, query?: object): string;
|
|
68
|
+
request<T>(req: Request, options?: RequestOptions): Promise<ApiResponse<T>>;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Modelos da API Brisa (REST v1), alinhados com `docs/openapi.json` e com as respostas reais da API.
|
|
73
|
+
* Os campos opcionais (`?`) podem não vir na resposta quando não têm valor.
|
|
74
|
+
*/
|
|
75
|
+
/** Uma página de uma lista: `page` começa em 0, `size` é no máximo 200. */
|
|
76
|
+
interface Page<T> {
|
|
77
|
+
items: T[];
|
|
78
|
+
page: number;
|
|
79
|
+
size: number;
|
|
80
|
+
total: number;
|
|
81
|
+
}
|
|
82
|
+
interface PageParams {
|
|
83
|
+
/** Página, a partir de 0. */
|
|
84
|
+
page?: number;
|
|
85
|
+
/** Itens por página, de 1 a 200 (por omissão 50). */
|
|
86
|
+
size?: number;
|
|
87
|
+
}
|
|
88
|
+
/** Valores livres (string) são aceites para não partir com valores novos da API. */
|
|
89
|
+
type Open<T extends string> = T | (string & {});
|
|
90
|
+
/** Tipos que se emitem com `documents.issue`. */
|
|
91
|
+
type IssuableDocumentType = 'FT' | 'FR' | 'TV' | 'PF';
|
|
92
|
+
/** Todos os tipos: os recibos (`RC`, `RG`) e as notas de crédito (`NC`) nascem dos pagamentos e das anulações. */
|
|
93
|
+
type DocumentType = Open<IssuableDocumentType | 'RC' | 'RG' | 'NC'>;
|
|
94
|
+
type DocumentState = Open<'issued' | 'paid' | 'cancelled' | 'rectified'>;
|
|
95
|
+
type PaymentMethod = Open<'cash' | 'credit_card' | 'debit_card' | 'transfer' | 'check' | 'multicaixa' | 'other'>;
|
|
96
|
+
/** Um imposto de uma linha: tem de coincidir com um imposto da empresa (ver `catalog.taxes()`). */
|
|
97
|
+
interface LineTax {
|
|
98
|
+
/** Ex.: `IVA 14%`. */
|
|
99
|
+
name: string;
|
|
100
|
+
/** Ex.: `14`. */
|
|
101
|
+
percentage: number;
|
|
102
|
+
/** Ex.: `IVA`. */
|
|
103
|
+
taxType: string;
|
|
104
|
+
/** Ex.: `NOR`, `ISE`. */
|
|
105
|
+
taxCode: string;
|
|
106
|
+
/** De 1 a 10, sem repetir na linha. */
|
|
107
|
+
calculationOrder: number;
|
|
108
|
+
withholding?: boolean;
|
|
109
|
+
/** `AO` ou `AO-CAB`. */
|
|
110
|
+
countryRegion?: string;
|
|
111
|
+
reasonCode?: string;
|
|
112
|
+
}
|
|
113
|
+
/** O cliente escrito no próprio documento (em alternativa a `clientId`). */
|
|
114
|
+
interface DocumentCustomer {
|
|
115
|
+
name: string;
|
|
116
|
+
/** NIF (9 ou 10 dígitos) ou BI; consumidor final `999999999`. */
|
|
117
|
+
taxId?: string;
|
|
118
|
+
address?: string;
|
|
119
|
+
email?: string;
|
|
120
|
+
phone?: string;
|
|
121
|
+
/** ISO 3166-1 alfa-2, ex.: `AO`. */
|
|
122
|
+
country?: string;
|
|
123
|
+
}
|
|
124
|
+
interface DocumentLineInput {
|
|
125
|
+
quantity: number;
|
|
126
|
+
/** Código de um produto do catálogo: traz descrição, preço e impostos. */
|
|
127
|
+
productCode?: string;
|
|
128
|
+
/** Obrigatória sem `productCode`. */
|
|
129
|
+
description?: string;
|
|
130
|
+
/** Obrigatório sem `productCode`. */
|
|
131
|
+
unitPrice?: number;
|
|
132
|
+
/** Obrigatório sem `productCode` (no máximo 5). */
|
|
133
|
+
taxes?: LineTax[];
|
|
134
|
+
discountPercent?: number;
|
|
135
|
+
discountAmount?: number;
|
|
136
|
+
/** Motivo de isenção `M00`…`M94`, obrigatório em linhas isentas ou não sujeitas. */
|
|
137
|
+
exemptionCode?: string;
|
|
138
|
+
exemptionReason?: string;
|
|
139
|
+
}
|
|
140
|
+
/** Um meio de pagamento e o que se pagou com ele. */
|
|
141
|
+
interface PaymentPart {
|
|
142
|
+
method: PaymentMethod;
|
|
143
|
+
/** Maior que zero, com no máximo 2 casas decimais. */
|
|
144
|
+
amount: number;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Como uma venda direta (`FR`, `TV`) foi paga: **um meio** e o valor entregue (`amountReceived`, por omissão exatamente o total), **ou vários meios ao mesmo tempo**
|
|
148
|
+
* (`payments`, até 6: parte em numerário, parte no TPA, parte em transferência), nunca os dois. O que se paga cobre o total; o troco (o que se pagou a mais) sai do
|
|
149
|
+
* numerário, por isso os meios que não são numerário não podem somar mais do que o total (`422`). Uma lista de um só meio vale como um só meio.
|
|
150
|
+
*/
|
|
151
|
+
type PaymentAtIssue = {
|
|
152
|
+
method: PaymentMethod;
|
|
153
|
+
amountReceived?: number;
|
|
154
|
+
payments?: undefined;
|
|
155
|
+
} | {
|
|
156
|
+
payments: PaymentPart[];
|
|
157
|
+
method?: undefined;
|
|
158
|
+
amountReceived?: undefined;
|
|
159
|
+
};
|
|
160
|
+
/** Como pagar uma fatura: o banco, o titular, o IBAN, o n.º de conta, a chave Kwik e o número do Multicaixa Express (todos opcionais, uma linha cada). */
|
|
161
|
+
interface BankDetails {
|
|
162
|
+
bankName: string;
|
|
163
|
+
holder: string;
|
|
164
|
+
/** O IBAN como se escreve (não é verificado); imprime-se tal e qual. */
|
|
165
|
+
iban: string;
|
|
166
|
+
accountNumber: string;
|
|
167
|
+
kwikKey: string;
|
|
168
|
+
expressNumber: string;
|
|
169
|
+
notes: string;
|
|
170
|
+
}
|
|
171
|
+
interface IssueDocumentRequest {
|
|
172
|
+
type: IssuableDocumentType;
|
|
173
|
+
lines: DocumentLineInput[];
|
|
174
|
+
/** Use este ou `customer`. */
|
|
175
|
+
clientId?: number;
|
|
176
|
+
customer?: DocumentCustomer;
|
|
177
|
+
/** Omita: é sempre o dia da emissão (em Luanda). */
|
|
178
|
+
issueDate?: string;
|
|
179
|
+
/** Data do facto tributável (AAAA-MM-DD). */
|
|
180
|
+
eventDate?: string;
|
|
181
|
+
/** Confirma a emissão fora do prazo do `eventDate`. */
|
|
182
|
+
lateIssue?: boolean;
|
|
183
|
+
/** Só `AOA`, por agora. */
|
|
184
|
+
currency?: string;
|
|
185
|
+
/** Obrigatório em `FR` e `TV`. */
|
|
186
|
+
payment?: PaymentAtIssue;
|
|
187
|
+
settlementAmount?: number;
|
|
188
|
+
retentionType?: string;
|
|
189
|
+
/** AAAA-MM-DD, no máximo 365 dias depois da emissão. */
|
|
190
|
+
dueDate?: string;
|
|
191
|
+
paymentTermsDays?: number;
|
|
192
|
+
notes?: string;
|
|
193
|
+
contingency?: boolean;
|
|
194
|
+
/**
|
|
195
|
+
* Só em `FT` e `PF` (faturas a pagar mais tarde): os dados bancários **desta** fatura. Sem isto, leva os da empresa (`company.bank()`). Cada campo é opcional;
|
|
196
|
+
* a fatura imprime-os enquanto estiver por pagar.
|
|
197
|
+
*/
|
|
198
|
+
bankDetails?: Partial<BankDetails>;
|
|
199
|
+
/** `false`: esta fatura não leva dados bancários. */
|
|
200
|
+
printBankDetails?: boolean;
|
|
201
|
+
}
|
|
202
|
+
/** Resposta de uma emissão (documento, recibo ou nota de crédito). */
|
|
203
|
+
interface IssuedDocument {
|
|
204
|
+
id: number;
|
|
205
|
+
/** Ex.: `FT FT2026/1`. */
|
|
206
|
+
number: string;
|
|
207
|
+
sequence: number;
|
|
208
|
+
hash: string;
|
|
209
|
+
/** Os caracteres 1, 11, 21 e 31 do hash, como impressos (vazio nos recibos). */
|
|
210
|
+
hashControl: string;
|
|
211
|
+
grossTotal: number;
|
|
212
|
+
}
|
|
213
|
+
interface ListDocumentsParams extends PageParams {
|
|
214
|
+
type?: DocumentType;
|
|
215
|
+
state?: DocumentState;
|
|
216
|
+
/** Emitidos a partir de (AAAA-MM-DD). */
|
|
217
|
+
from?: string;
|
|
218
|
+
/** Emitidos até (AAAA-MM-DD). */
|
|
219
|
+
to?: string;
|
|
220
|
+
customerTaxId?: string;
|
|
221
|
+
/** Texto livre. */
|
|
222
|
+
q?: string;
|
|
223
|
+
sort?: Open<'id' | 'number' | 'issueDate' | 'systemEntry' | 'gross' | 'net' | 'customerName' | 'type' | 'amountDue' | 'state'>;
|
|
224
|
+
dir?: 'asc' | 'desc';
|
|
225
|
+
}
|
|
226
|
+
/** Um documento numa lista. */
|
|
227
|
+
interface DocumentSummary {
|
|
228
|
+
id: number;
|
|
229
|
+
number: string;
|
|
230
|
+
type: DocumentType;
|
|
231
|
+
state: DocumentState;
|
|
232
|
+
issueDate: string;
|
|
233
|
+
systemEntry: string;
|
|
234
|
+
customerTaxId: string;
|
|
235
|
+
customerName: string;
|
|
236
|
+
grossTotal: number;
|
|
237
|
+
netTotal: number;
|
|
238
|
+
taxPayable: number;
|
|
239
|
+
payable: number;
|
|
240
|
+
amountDue: number;
|
|
241
|
+
currency: string;
|
|
242
|
+
/** `VALID`, `INVALID`... (ausente na sandbox e antes da resposta da AGT). */
|
|
243
|
+
agtStatus?: string;
|
|
244
|
+
issuedBy?: string;
|
|
245
|
+
/** Ex.: `API: Integração principal`. */
|
|
246
|
+
issuedByName?: string;
|
|
247
|
+
offline: boolean;
|
|
248
|
+
synced: boolean;
|
|
249
|
+
dueDate?: string;
|
|
250
|
+
overdue?: boolean;
|
|
251
|
+
}
|
|
252
|
+
interface DocumentLine {
|
|
253
|
+
number: number;
|
|
254
|
+
productCode?: string | null;
|
|
255
|
+
description: string;
|
|
256
|
+
quantity: number;
|
|
257
|
+
unitPrice: number;
|
|
258
|
+
netTotal: number;
|
|
259
|
+
taxTotal: number;
|
|
260
|
+
grossTotal: number;
|
|
261
|
+
}
|
|
262
|
+
/** Um documento, com linhas, totais, valor em dívida e estado na AGT. */
|
|
263
|
+
interface DocumentDetail {
|
|
264
|
+
id: number;
|
|
265
|
+
number: string;
|
|
266
|
+
type: DocumentType;
|
|
267
|
+
state: DocumentState;
|
|
268
|
+
issueDate: string;
|
|
269
|
+
systemEntry: string;
|
|
270
|
+
dueDate?: string;
|
|
271
|
+
customerTaxId: string;
|
|
272
|
+
customerName: string;
|
|
273
|
+
customerAddress?: string;
|
|
274
|
+
customerEmail?: string;
|
|
275
|
+
customerPhone?: string;
|
|
276
|
+
customerCountry?: string;
|
|
277
|
+
netTotal: number;
|
|
278
|
+
taxPayable: number;
|
|
279
|
+
grossTotal: number;
|
|
280
|
+
retention: number;
|
|
281
|
+
payable: number;
|
|
282
|
+
amountDue: number;
|
|
283
|
+
hash: string;
|
|
284
|
+
hashControl: string;
|
|
285
|
+
offline: boolean;
|
|
286
|
+
syncedWithAgt: boolean;
|
|
287
|
+
agtStatus?: string;
|
|
288
|
+
agtRequestId?: string;
|
|
289
|
+
/** `REFUSED` quando a AGT recusou a anulação. */
|
|
290
|
+
agtCancelStatus?: string | null;
|
|
291
|
+
/** O meio de pagamento (`mixed` quando foram vários: ver `payments`). */
|
|
292
|
+
paymentMethod?: PaymentMethod | 'mixed' | null;
|
|
293
|
+
/** O que se entregou (numa venda direta); o troco é isto menos `payable`. */
|
|
294
|
+
amountReceived?: number | null;
|
|
295
|
+
/** Os meios, quando foram vários; vazio quando foi um só. */
|
|
296
|
+
payments?: PaymentPart[];
|
|
297
|
+
/** Como pagar, tal como a fatura dizia ao ser emitida; `null` quando não dizia nada. */
|
|
298
|
+
bankDetails?: BankDetails | null;
|
|
299
|
+
lines: DocumentLine[];
|
|
300
|
+
[extra: string]: unknown;
|
|
301
|
+
}
|
|
302
|
+
interface PdfOptions {
|
|
303
|
+
/**
|
|
304
|
+
* `a4` (por omissão), `a5` (o A4 reduzido a meia folha), `thermal80` (talão para rolo de 80 mm; `thermal` é o mesmo) ou `thermal58` (rolo de 58 mm).
|
|
305
|
+
* Os talões só existem para FR, TV, RC e RG.
|
|
306
|
+
*/
|
|
307
|
+
format?: 'a4' | 'a5' | 'thermal' | 'thermal80' | 'thermal58';
|
|
308
|
+
/** `original` (por omissão) ou `second` (2.ª via). */
|
|
309
|
+
copy?: 'original' | 'second';
|
|
310
|
+
}
|
|
311
|
+
/** O documento exportado como dados (`documents.export`). */
|
|
312
|
+
interface DocumentExport {
|
|
313
|
+
documentNo: string;
|
|
314
|
+
type: DocumentType;
|
|
315
|
+
sequence: number;
|
|
316
|
+
issueDate: string;
|
|
317
|
+
dueDate?: string;
|
|
318
|
+
systemEntry: string;
|
|
319
|
+
state: DocumentState;
|
|
320
|
+
status: string;
|
|
321
|
+
hash: string;
|
|
322
|
+
currency: string;
|
|
323
|
+
supplier: Record<string, string>;
|
|
324
|
+
customer: Record<string, string>;
|
|
325
|
+
totals: {
|
|
326
|
+
net: number;
|
|
327
|
+
tax: number;
|
|
328
|
+
gross: number;
|
|
329
|
+
retention: number;
|
|
330
|
+
payable: number;
|
|
331
|
+
settlement: number;
|
|
332
|
+
};
|
|
333
|
+
paymentMethod?: string;
|
|
334
|
+
agt?: {
|
|
335
|
+
status?: string;
|
|
336
|
+
synced: boolean;
|
|
337
|
+
offline: boolean;
|
|
338
|
+
};
|
|
339
|
+
issuedBy?: string;
|
|
340
|
+
series?: string;
|
|
341
|
+
items: Array<{
|
|
342
|
+
line: number;
|
|
343
|
+
description: string;
|
|
344
|
+
quantity: number;
|
|
345
|
+
unitPrice: number;
|
|
346
|
+
discount: number;
|
|
347
|
+
taxes: Array<{
|
|
348
|
+
type: string;
|
|
349
|
+
code: string;
|
|
350
|
+
percentage: number;
|
|
351
|
+
base: number;
|
|
352
|
+
amount: number;
|
|
353
|
+
withholding: boolean;
|
|
354
|
+
}>;
|
|
355
|
+
net: number;
|
|
356
|
+
tax: number;
|
|
357
|
+
gross: number;
|
|
358
|
+
}>;
|
|
359
|
+
payments?: Array<{
|
|
360
|
+
receipt: string;
|
|
361
|
+
amount: number;
|
|
362
|
+
method: string;
|
|
363
|
+
date: string;
|
|
364
|
+
reversed: boolean;
|
|
365
|
+
}>;
|
|
366
|
+
creditNotes?: Array<{
|
|
367
|
+
issueDate: string;
|
|
368
|
+
documentNo: string;
|
|
369
|
+
gross: number;
|
|
370
|
+
}>;
|
|
371
|
+
[extra: string]: unknown;
|
|
372
|
+
}
|
|
373
|
+
interface PayDocumentRequest {
|
|
374
|
+
method: PaymentMethod;
|
|
375
|
+
/** Sem ele, paga tudo o que falta. Até 2 casas decimais. */
|
|
376
|
+
amount?: number;
|
|
377
|
+
}
|
|
378
|
+
interface PaymentResult {
|
|
379
|
+
/** O recibo (`RC`); `null` quando não havia nada a pagar. */
|
|
380
|
+
receipt: IssuedDocument | null;
|
|
381
|
+
}
|
|
382
|
+
interface GlobalPaymentRequest {
|
|
383
|
+
/** De 1 a 100 faturas (`FT`) do mesmo cliente, sem repetir. */
|
|
384
|
+
documentIds: number[];
|
|
385
|
+
method: PaymentMethod;
|
|
386
|
+
}
|
|
387
|
+
interface CancelDocumentRequest {
|
|
388
|
+
/** Até 500 caracteres. */
|
|
389
|
+
reason: string;
|
|
390
|
+
/** Obrigatório numa fatura já emitida (Art. 8.º n.º 8). */
|
|
391
|
+
basis?: 'emitter_identification' | 'not_sent_to_acquirer';
|
|
392
|
+
}
|
|
393
|
+
interface RectifyDocumentRequest {
|
|
394
|
+
reason: string;
|
|
395
|
+
/** Obrigatório num talão de venda (`TV`): quem devolve. */
|
|
396
|
+
customerName?: string;
|
|
397
|
+
/** Obrigatório num talão de venda (`TV`): NIF de quem devolve (não `999999999`). */
|
|
398
|
+
customerNif?: string;
|
|
399
|
+
}
|
|
400
|
+
interface CreditNoteRequest extends RectifyDocumentRequest {
|
|
401
|
+
/** Linhas a creditar; sem `lines` credita tudo. */
|
|
402
|
+
lines?: Array<{
|
|
403
|
+
line: number;
|
|
404
|
+
quantity: number;
|
|
405
|
+
}>;
|
|
406
|
+
}
|
|
407
|
+
interface CreditedLine {
|
|
408
|
+
line: number;
|
|
409
|
+
description: string;
|
|
410
|
+
quantity: number;
|
|
411
|
+
credited: number;
|
|
412
|
+
remaining: number;
|
|
413
|
+
}
|
|
414
|
+
interface SendDocumentRequest {
|
|
415
|
+
/** Com uma chave de API, só o e-mail do cliente que consta do documento (por omissão). */
|
|
416
|
+
to?: string[];
|
|
417
|
+
copy?: 'original' | 'second';
|
|
418
|
+
}
|
|
419
|
+
interface SendResult {
|
|
420
|
+
queued: number;
|
|
421
|
+
recipients: string[];
|
|
422
|
+
}
|
|
423
|
+
interface DocumentHistory {
|
|
424
|
+
document: string;
|
|
425
|
+
state: DocumentState;
|
|
426
|
+
events: Array<{
|
|
427
|
+
id: number;
|
|
428
|
+
at: string;
|
|
429
|
+
subject: string;
|
|
430
|
+
action: string;
|
|
431
|
+
target: string;
|
|
432
|
+
detail?: unknown;
|
|
433
|
+
}>;
|
|
434
|
+
sends: unknown[];
|
|
435
|
+
}
|
|
436
|
+
interface ClientInput {
|
|
437
|
+
name: string;
|
|
438
|
+
/** Obrigatório ao atualizar (o PUT substitui tudo). */
|
|
439
|
+
taxId?: string;
|
|
440
|
+
clientType?: 'individual' | 'company';
|
|
441
|
+
email?: string;
|
|
442
|
+
phone?: string;
|
|
443
|
+
address?: string;
|
|
444
|
+
city?: string;
|
|
445
|
+
postalCode?: string;
|
|
446
|
+
country?: string;
|
|
447
|
+
paymentTermsDays?: number;
|
|
448
|
+
comments?: string;
|
|
449
|
+
}
|
|
450
|
+
interface Client {
|
|
451
|
+
id: number;
|
|
452
|
+
name: string;
|
|
453
|
+
taxId: string;
|
|
454
|
+
clientType: string;
|
|
455
|
+
email: string;
|
|
456
|
+
phone: string;
|
|
457
|
+
address: string;
|
|
458
|
+
city: string;
|
|
459
|
+
postalCode: string;
|
|
460
|
+
country: string;
|
|
461
|
+
paymentTermsDays: number;
|
|
462
|
+
comments: string;
|
|
463
|
+
active: boolean;
|
|
464
|
+
createdAt: string;
|
|
465
|
+
/** Só numa lista pedida com `totals: true` (e nunca para o consumidor final): o que se faturou ao cliente (faturas, vendas diretas e notas de débito, menos notas de crédito). */
|
|
466
|
+
invoiced?: number;
|
|
467
|
+
/** Idem: o que o cliente ainda deve. */
|
|
468
|
+
amountDue?: number;
|
|
469
|
+
/** Idem: a data da última fatura (AAAA-MM-DD). */
|
|
470
|
+
lastInvoiceDate?: string;
|
|
471
|
+
/** Idem: quantos documentos de venda. */
|
|
472
|
+
documents?: number;
|
|
473
|
+
}
|
|
474
|
+
interface ListClientsParams extends PageParams {
|
|
475
|
+
/** Texto a procurar no nome ou NIF. */
|
|
476
|
+
q?: string;
|
|
477
|
+
/** Só ativos (por omissão `true`). */
|
|
478
|
+
activeOnly?: boolean;
|
|
479
|
+
/**
|
|
480
|
+
* A ordem: `campo[:asc|:desc][,campo...]` entre `name` (por omissão), `taxId`, `city`, `createdAt` e, que pedem os totais, `invoiced`, `due`, `lastInvoice`, `documents`.
|
|
481
|
+
*/
|
|
482
|
+
sort?: string;
|
|
483
|
+
/** `true` inverte um campo que não diga a direção. */
|
|
484
|
+
desc?: boolean;
|
|
485
|
+
/** Acrescenta a cada cliente `invoiced`, `amountDue`, `lastInvoiceDate` e `documents`. */
|
|
486
|
+
totals?: boolean;
|
|
487
|
+
}
|
|
488
|
+
/** Um movimento da conta corrente: débito (o que o cliente passou a dever) ou crédito (o que pagou ou lhe foi creditado), com o saldo a seguir. */
|
|
489
|
+
interface StatementEntry {
|
|
490
|
+
date: string;
|
|
491
|
+
reference: string;
|
|
492
|
+
type: string;
|
|
493
|
+
description: string;
|
|
494
|
+
debit: number;
|
|
495
|
+
credit: number;
|
|
496
|
+
balance: number;
|
|
497
|
+
}
|
|
498
|
+
/** A conta corrente de um cliente: faturas, notas de crédito e recibos dia a dia; um saldo positivo é o que o cliente deve. */
|
|
499
|
+
interface ClientStatement {
|
|
500
|
+
clientId: number;
|
|
501
|
+
taxId: string;
|
|
502
|
+
name: string;
|
|
503
|
+
from: string;
|
|
504
|
+
to: string;
|
|
505
|
+
opening: number;
|
|
506
|
+
entries: StatementEntry[];
|
|
507
|
+
debits: number;
|
|
508
|
+
credits: number;
|
|
509
|
+
closing: number;
|
|
510
|
+
}
|
|
511
|
+
interface ProductTaxRef {
|
|
512
|
+
/** O `id` de `catalog.taxes()`. */
|
|
513
|
+
taxId: number;
|
|
514
|
+
order: number;
|
|
515
|
+
}
|
|
516
|
+
interface ProductInput {
|
|
517
|
+
name: string;
|
|
518
|
+
/** `product` ou `service` (obrigatório). */
|
|
519
|
+
type: 'product' | 'service';
|
|
520
|
+
price?: number;
|
|
521
|
+
unit?: string;
|
|
522
|
+
description?: string;
|
|
523
|
+
categoryId?: number;
|
|
524
|
+
/** Omitido: o produto fica com os impostos que tinha. `[]` tira-os. */
|
|
525
|
+
taxes?: ProductTaxRef[];
|
|
526
|
+
exemptionCode?: string;
|
|
527
|
+
retentionType?: string;
|
|
528
|
+
trackStock?: boolean;
|
|
529
|
+
minStockLevel?: number;
|
|
530
|
+
active?: boolean;
|
|
531
|
+
}
|
|
532
|
+
interface Product {
|
|
533
|
+
code: string;
|
|
534
|
+
name: string;
|
|
535
|
+
type: string;
|
|
536
|
+
price: number;
|
|
537
|
+
unit: string;
|
|
538
|
+
description: string;
|
|
539
|
+
categoryId?: number;
|
|
540
|
+
taxes: ProductTaxRef[];
|
|
541
|
+
exemptionCode?: string;
|
|
542
|
+
retentionType?: string;
|
|
543
|
+
trackStock: boolean;
|
|
544
|
+
minStockLevel: number;
|
|
545
|
+
active: boolean;
|
|
546
|
+
quantity: number;
|
|
547
|
+
lowStock: boolean;
|
|
548
|
+
createdAt: string;
|
|
549
|
+
}
|
|
550
|
+
interface ListProductsParams extends PageParams {
|
|
551
|
+
q?: string;
|
|
552
|
+
categoryId?: number;
|
|
553
|
+
activeOnly?: boolean;
|
|
554
|
+
}
|
|
555
|
+
interface StockMovementRequest {
|
|
556
|
+
type: 'in' | 'out' | 'adjustment';
|
|
557
|
+
quantity: number;
|
|
558
|
+
reason: string;
|
|
559
|
+
}
|
|
560
|
+
/** O stock de um produto depois de um movimento. */
|
|
561
|
+
interface StockLevel {
|
|
562
|
+
code: string;
|
|
563
|
+
name: string;
|
|
564
|
+
type: string;
|
|
565
|
+
trackStock: boolean;
|
|
566
|
+
unit: string;
|
|
567
|
+
quantity: number;
|
|
568
|
+
}
|
|
569
|
+
interface CompanyTax {
|
|
570
|
+
/** O `taxId` que os produtos usam. */
|
|
571
|
+
id: number;
|
|
572
|
+
name: string;
|
|
573
|
+
code: string;
|
|
574
|
+
type: string;
|
|
575
|
+
countryRegion: string;
|
|
576
|
+
percentage: number;
|
|
577
|
+
withholding: boolean;
|
|
578
|
+
description: string;
|
|
579
|
+
system: boolean;
|
|
580
|
+
active: boolean;
|
|
581
|
+
}
|
|
582
|
+
interface ExemptionReason {
|
|
583
|
+
code: string;
|
|
584
|
+
name: string;
|
|
585
|
+
legalBasis: string;
|
|
586
|
+
}
|
|
587
|
+
interface Category {
|
|
588
|
+
id: number;
|
|
589
|
+
code: string;
|
|
590
|
+
description: string;
|
|
591
|
+
}
|
|
592
|
+
type SaftExportStatus = Open<'REQUESTED' | 'RUNNING' | 'READY' | 'FAILED'>;
|
|
593
|
+
interface SaftExport {
|
|
594
|
+
id: number;
|
|
595
|
+
from: string;
|
|
596
|
+
to: string;
|
|
597
|
+
status: SaftExportStatus;
|
|
598
|
+
documents?: number;
|
|
599
|
+
sizeBytes?: number;
|
|
600
|
+
sha256?: string;
|
|
601
|
+
error?: string;
|
|
602
|
+
requestedBy: string;
|
|
603
|
+
createdAt: string;
|
|
604
|
+
finishedAt?: string;
|
|
605
|
+
}
|
|
606
|
+
/** `GET /api/v1/me`: com uma chave, `subject` é `apikey:<id>` e `grants` as permissões da chave. */
|
|
607
|
+
interface Me {
|
|
608
|
+
subject: string;
|
|
609
|
+
grants: Record<string, unknown>;
|
|
610
|
+
user?: Record<string, unknown>;
|
|
611
|
+
}
|
|
612
|
+
interface Company {
|
|
613
|
+
name: string;
|
|
614
|
+
nif: string;
|
|
615
|
+
address: string;
|
|
616
|
+
city: string;
|
|
617
|
+
phone: string;
|
|
618
|
+
email: string;
|
|
619
|
+
eInvoicing: boolean;
|
|
620
|
+
ivaRegime: string;
|
|
621
|
+
establishmentNumber: string;
|
|
622
|
+
defaultPaymentTermsDays: number;
|
|
623
|
+
exemptActivity: boolean;
|
|
624
|
+
[extra: string]: unknown;
|
|
625
|
+
}
|
|
626
|
+
type WebhookEventType = Open<'document.issued' | 'document.cancelled' | 'document.credited' | 'document.rectified' | 'document.agt.validated' | 'document.agt.rejected' | 'document.agt.cancel_rejected' | 'ping'>;
|
|
627
|
+
interface WebhookEvent<D = Record<string, unknown>> {
|
|
628
|
+
/** `evt_...`: igual em todas as repetições (use-o para ignorar duplicados). */
|
|
629
|
+
id: string;
|
|
630
|
+
type: WebhookEventType;
|
|
631
|
+
createdAt: string;
|
|
632
|
+
/** A empresa (na sandbox, o identificador da sandbox). */
|
|
633
|
+
tenant: string;
|
|
634
|
+
data: D;
|
|
635
|
+
}
|
|
636
|
+
/** O `data` de `document.issued`. */
|
|
637
|
+
interface DocumentIssuedData {
|
|
638
|
+
documentId: number;
|
|
639
|
+
documentNo: string;
|
|
640
|
+
documentType: DocumentType;
|
|
641
|
+
customerTaxId: string;
|
|
642
|
+
grossTotal: string;
|
|
643
|
+
}
|
|
644
|
+
/** Documento de erro RFC 9457. */
|
|
645
|
+
interface Problem {
|
|
646
|
+
type: string;
|
|
647
|
+
title: string;
|
|
648
|
+
status: number;
|
|
649
|
+
detail?: string;
|
|
650
|
+
instance?: string;
|
|
651
|
+
field?: string;
|
|
652
|
+
errors?: Record<string, string>;
|
|
653
|
+
metric?: string;
|
|
654
|
+
limit?: number;
|
|
655
|
+
[extra: string]: unknown;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
/** Documentos fiscais: emitir, consultar, PDF, pagamentos, anulações e notas de crédito. */
|
|
659
|
+
declare class Documents {
|
|
660
|
+
private readonly http;
|
|
661
|
+
constructor(http: HttpClient);
|
|
662
|
+
/** Emite `FT`, `FR`, `TV` ou `PF` (`POST /api/v1/documents`). Permissão `invoices.issue`. */
|
|
663
|
+
issue(body: IssueDocumentRequest, options?: RequestOptions): Promise<IssuedDocument>;
|
|
664
|
+
/** Uma página de documentos, do mais recente para o mais antigo. Permissão `invoices.view`. */
|
|
665
|
+
list(params?: ListDocumentsParams, options?: RequestOptions): Promise<Page<DocumentSummary>>;
|
|
666
|
+
/** Todos os documentos que correspondem aos filtros, página a página. */
|
|
667
|
+
listAll(params?: ListDocumentsParams, options?: RequestOptions): AsyncGenerator<DocumentSummary, void, undefined>;
|
|
668
|
+
/** Um documento, com linhas, totais, valor em dívida e estado na AGT. */
|
|
669
|
+
get(documentId: number, options?: RequestOptions): Promise<DocumentDetail>;
|
|
670
|
+
/** O PDF do documento (bytes). Conta como mais de um pedido no limite da chave: guarde-o em vez de o pedir de cada vez. */
|
|
671
|
+
pdf(documentId: number, params?: PdfOptions, options?: RequestOptions): Promise<Uint8Array>;
|
|
672
|
+
/** O documento como dados: JSON (por omissão) ou XML (texto). Permissão `invoices.export`. */
|
|
673
|
+
export(documentId: number, format?: 'json', options?: RequestOptions): Promise<DocumentExport>;
|
|
674
|
+
export(documentId: number, format: 'xml', options?: RequestOptions): Promise<string>;
|
|
675
|
+
/** Paga o documento, no todo (sem `amount`) ou em parte, e emite o recibo (`RC`). Permissão `invoices.payments`. */
|
|
676
|
+
pay(documentId: number, body: PayDocumentRequest, options?: RequestOptions): Promise<PaymentResult>;
|
|
677
|
+
/** Liquida várias faturas de um mesmo cliente num recibo global (`RG`). */
|
|
678
|
+
payGlobal(body: GlobalPaymentRequest, options?: RequestOptions): Promise<IssuedDocument>;
|
|
679
|
+
/** Anula o documento (numa fatura emitida, só com `basis`). Repetido, dá o mesmo resultado. Permissão `invoices.cancel`. */
|
|
680
|
+
cancel(documentId: number, body: CancelDocumentRequest, options?: RequestOptions): Promise<void>;
|
|
681
|
+
/** Retifica: emite uma nota de crédito (`NC`) que espelha o original. */
|
|
682
|
+
rectify(documentId: number, body: RectifyDocumentRequest, options?: RequestOptions): Promise<IssuedDocument>;
|
|
683
|
+
/** Nota de crédito parcial (ou total, sem `lines`). */
|
|
684
|
+
creditNote(documentId: number, body: CreditNoteRequest, options?: RequestOptions): Promise<IssuedDocument>;
|
|
685
|
+
/** Quanto de cada linha já foi creditado e quanto ainda se pode creditar. */
|
|
686
|
+
credits(documentId: number, options?: RequestOptions): Promise<CreditedLine[]>;
|
|
687
|
+
/** O histórico do documento (auditoria e envios). */
|
|
688
|
+
history(documentId: number, options?: RequestOptions): Promise<DocumentHistory>;
|
|
689
|
+
/** Muda a data de vencimento (AAAA-MM-DD, até 365 dias depois da emissão). */
|
|
690
|
+
setDueDate(documentId: number, dueDate: string, options?: RequestOptions): Promise<void>;
|
|
691
|
+
/** Envia o documento por e-mail. Com uma chave de API, só ao e-mail do cliente que consta do documento. Permissão `invoices.send`. */
|
|
692
|
+
send(documentId: number, body?: SendDocumentRequest, options?: RequestOptions): Promise<SendResult>;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/** Clientes da empresa. */
|
|
696
|
+
declare class Clients {
|
|
697
|
+
private readonly http;
|
|
698
|
+
constructor(http: HttpClient);
|
|
699
|
+
/** Regista um cliente e devolve o seu `id`. Permissão `clients.manage`. */
|
|
700
|
+
create(body: ClientInput, options?: RequestOptions): Promise<{
|
|
701
|
+
id: number;
|
|
702
|
+
}>;
|
|
703
|
+
/** Substitui os dados do cliente: envie o corpo completo (com `taxId`). */
|
|
704
|
+
update(clientId: number, body: ClientInput & {
|
|
705
|
+
taxId: string;
|
|
706
|
+
}, options?: RequestOptions): Promise<void>;
|
|
707
|
+
get(clientId: number, options?: RequestOptions): Promise<Client>;
|
|
708
|
+
list(params?: ListClientsParams, options?: RequestOptions): Promise<Page<Client>>;
|
|
709
|
+
listAll(params?: ListClientsParams, options?: RequestOptions): AsyncGenerator<Client, void, undefined>;
|
|
710
|
+
/** Ativa ou desativa o cliente. Permissão `clients.delete`. */
|
|
711
|
+
setActive(clientId: number, active: boolean, options?: RequestOptions): Promise<void>;
|
|
712
|
+
/** A conta corrente do cliente (faturas, notas de crédito e recibos dia a dia, com o saldo). Permissões `clients.view` e `invoices.view`. */
|
|
713
|
+
statement(clientId: number, period?: {
|
|
714
|
+
from?: string;
|
|
715
|
+
to?: string;
|
|
716
|
+
}, options?: RequestOptions): Promise<ClientStatement>;
|
|
717
|
+
/** O extrato para imprimir (PDF, bytes). Pede também a permissão `reports.export`. */
|
|
718
|
+
statementPdf(clientId: number, period?: {
|
|
719
|
+
from?: string;
|
|
720
|
+
to?: string;
|
|
721
|
+
}, options?: RequestOptions): Promise<Uint8Array>;
|
|
722
|
+
/** O extrato em CSV (texto). Pede também a permissão `reports.export`. */
|
|
723
|
+
statementCsv(clientId: number, period?: {
|
|
724
|
+
from?: string;
|
|
725
|
+
to?: string;
|
|
726
|
+
}, options?: RequestOptions): Promise<string>;
|
|
727
|
+
}
|
|
728
|
+
/** Produtos do catálogo e stock. */
|
|
729
|
+
declare class Products {
|
|
730
|
+
private readonly http;
|
|
731
|
+
constructor(http: HttpClient);
|
|
732
|
+
/** Cria o produto se o código não existir; senão atualiza-o. Permissão `products.manage`. */
|
|
733
|
+
upsert(code: string, body: ProductInput, options?: RequestOptions): Promise<Product>;
|
|
734
|
+
/** Um produto, com o stock atual. */
|
|
735
|
+
get(code: string, options?: RequestOptions): Promise<Product>;
|
|
736
|
+
list(params?: ListProductsParams, options?: RequestOptions): Promise<Page<Product>>;
|
|
737
|
+
listAll(params?: ListProductsParams, options?: RequestOptions): AsyncGenerator<Product, void, undefined>;
|
|
738
|
+
/** Entrada, saída ou acerto de stock. Permissão `stock.adjust`. */
|
|
739
|
+
moveStock(code: string, body: StockMovementRequest, options?: RequestOptions): Promise<StockLevel>;
|
|
740
|
+
}
|
|
741
|
+
/** Impostos, motivos de isenção e categorias. */
|
|
742
|
+
declare class Catalog {
|
|
743
|
+
private readonly http;
|
|
744
|
+
constructor(http: HttpClient);
|
|
745
|
+
/** Os impostos da empresa: o `id` é o `taxId` dos produtos; uma linha só aceita impostos daqui. */
|
|
746
|
+
taxes(params?: {
|
|
747
|
+
activeOnly?: boolean;
|
|
748
|
+
}, options?: RequestOptions): Promise<CompanyTax[]>;
|
|
749
|
+
/** Os motivos de isenção `M00`…`M94` aceites pela AGT. */
|
|
750
|
+
exemptionReasons(options?: RequestOptions): Promise<ExemptionReason[]>;
|
|
751
|
+
categories(options?: RequestOptions): Promise<Category[]>;
|
|
752
|
+
}
|
|
753
|
+
/** Ficheiros SAF-T (AO). Permissão `saft.export`. */
|
|
754
|
+
declare class Saft {
|
|
755
|
+
private readonly http;
|
|
756
|
+
constructor(http: HttpClient);
|
|
757
|
+
/** Pede a exportação de um período (o fim não pode ser no futuro). Gera-se em segundo plano: veja `get` ou `waitUntilReady`. */
|
|
758
|
+
request(period: {
|
|
759
|
+
from: string;
|
|
760
|
+
to: string;
|
|
761
|
+
}, options?: RequestOptions): Promise<SaftExport>;
|
|
762
|
+
list(params?: {
|
|
763
|
+
limit?: number;
|
|
764
|
+
}, options?: RequestOptions): Promise<SaftExport[]>;
|
|
765
|
+
get(exportId: number, options?: RequestOptions): Promise<SaftExport>;
|
|
766
|
+
/** O XML de uma exportação `READY` (`409` antes disso). Conta como vários pedidos no limite da chave. */
|
|
767
|
+
file(exportId: number, options?: RequestOptions): Promise<string>;
|
|
768
|
+
/** Espera até a exportação ficar `READY` (ou falha com `FAILED`). */
|
|
769
|
+
waitUntilReady(exportId: number, { intervalMs, timeoutMs }?: {
|
|
770
|
+
intervalMs?: number | undefined;
|
|
771
|
+
timeoutMs?: number | undefined;
|
|
772
|
+
}, options?: RequestOptions): Promise<SaftExport>;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
interface VerifyWebhookOptions {
|
|
776
|
+
/** Diferença máxima, em segundos, entre o `t` da assinatura e o relógio local (por omissão 300). */
|
|
777
|
+
toleranceSeconds?: number;
|
|
778
|
+
/** O instante atual em segundos (para testes). */
|
|
779
|
+
now?: number;
|
|
780
|
+
}
|
|
781
|
+
/** `t=<segundos>,v1=<hex>[,v1=<hex>]` → `{ timestamp, signatures }`. */
|
|
782
|
+
declare function parseSignatureHeader(header: string): {
|
|
783
|
+
timestamp: number;
|
|
784
|
+
signatures: string[];
|
|
785
|
+
};
|
|
786
|
+
/**
|
|
787
|
+
* Verifica a assinatura de um webhook (`Brisa-Signature`) e devolve o evento.
|
|
788
|
+
*
|
|
789
|
+
* Use o corpo **bruto**, tal como chegou (antes de o interpretar como JSON). Durante a troca do segredo vêm dois `v1`: basta um coincidir.
|
|
790
|
+
* Lança `BrisaWebhookSignatureError` se a assinatura não coincidir ou se `t` estiver fora da tolerância.
|
|
791
|
+
*
|
|
792
|
+
* ```ts
|
|
793
|
+
* app.post('/webhooks/brisa', express.raw({ type: 'application/json' }), async (req, res) => {
|
|
794
|
+
* const event = await verifyWebhook(req.body, req.get('Brisa-Signature'), process.env.BRISA_WEBHOOK_SECRET)
|
|
795
|
+
* res.sendStatus(200)
|
|
796
|
+
* })
|
|
797
|
+
* ```
|
|
798
|
+
*/
|
|
799
|
+
declare function verifyWebhook<D = Record<string, unknown>>(payload: string | Uint8Array | ArrayBuffer, signatureHeader: string | null | undefined, secret: string | string[], options?: VerifyWebhookOptions): Promise<WebhookEvent<D>>;
|
|
800
|
+
/** Calcula o cabeçalho `Brisa-Signature` de um corpo: útil para testar o seu endpoint. */
|
|
801
|
+
declare function signWebhookPayload(payload: string, secret: string, timestamp?: number): Promise<string>;
|
|
802
|
+
|
|
803
|
+
/**
|
|
804
|
+
* Cliente da API Brisa.
|
|
805
|
+
*
|
|
806
|
+
* ```ts
|
|
807
|
+
* import { Brisa } from 'brisa-sdk'
|
|
808
|
+
* const brisa = new Brisa({ apiKey: process.env.BRISA_API_KEY })
|
|
809
|
+
* const doc = await brisa.documents.issue({ type: 'FT', clientId: 42, lines: [{ productCode: 'PAR-M8', quantity: 4 }] })
|
|
810
|
+
* ```
|
|
811
|
+
*/
|
|
812
|
+
declare class Brisa {
|
|
813
|
+
readonly documents: Documents;
|
|
814
|
+
readonly clients: Clients;
|
|
815
|
+
readonly products: Products;
|
|
816
|
+
readonly catalog: Catalog;
|
|
817
|
+
readonly saft: Saft;
|
|
818
|
+
/** Verificação de webhooks (também exportada como `verifyWebhook`). */
|
|
819
|
+
static readonly webhooks: {
|
|
820
|
+
verify: typeof verifyWebhook;
|
|
821
|
+
};
|
|
822
|
+
private readonly http;
|
|
823
|
+
constructor(options?: BrisaOptions);
|
|
824
|
+
get baseUrl(): string;
|
|
825
|
+
/** Os limites de pedidos indicados na última resposta (`X-RateLimit-*`). */
|
|
826
|
+
get rateLimit(): RateLimit | undefined;
|
|
827
|
+
/** Quem é a chave e que permissões tem (`GET /api/v1/me`). */
|
|
828
|
+
me(options?: RequestOptions): Promise<Me>;
|
|
829
|
+
/** Os dados da empresa da chave (`GET /api/v1/company`). */
|
|
830
|
+
company(options?: RequestOptions): Promise<Company>;
|
|
831
|
+
/** Os dados bancários da empresa (`GET /api/v1/company/bank`): o que as suas faturas por pagar dizem sobre como pagar. */
|
|
832
|
+
bank(options?: RequestOptions): Promise<BankDetails>;
|
|
833
|
+
/**
|
|
834
|
+
* Substitui os dados bancários da empresa (o IBAN é verificado: um angolano tem 25 caracteres e dígitos de controlo certos; tudo vazio limpa-os).
|
|
835
|
+
* Permissão `settings.manage`. Devolve o que ficou guardado.
|
|
836
|
+
*/
|
|
837
|
+
setBank(details: Partial<BankDetails>, options?: RequestOptions): Promise<BankDetails>;
|
|
838
|
+
/** Um pedido qualquer à API, com autenticação, repetições e erros do SDK; devolve também o estado e os cabeçalhos. */
|
|
839
|
+
request<T = unknown>(req: Request, options?: RequestOptions): Promise<ApiResponse<T>>;
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
/** Base de todos os erros do SDK. */
|
|
843
|
+
declare class BrisaError extends Error {
|
|
844
|
+
constructor(message: string, options?: {
|
|
845
|
+
cause?: unknown;
|
|
846
|
+
});
|
|
847
|
+
}
|
|
848
|
+
/**
|
|
849
|
+
* A API respondeu com um erro (RFC 9457, `application/problem+json`).
|
|
850
|
+
* Programe contra `status`, `type` e `field`, não contra o texto de `detail` (em português, pode variar).
|
|
851
|
+
*/
|
|
852
|
+
declare class BrisaApiError extends BrisaError {
|
|
853
|
+
/** O estado HTTP. */
|
|
854
|
+
readonly status: number;
|
|
855
|
+
/** `urn:brisa:...`: identificador estável do tipo de problema. */
|
|
856
|
+
readonly type: string;
|
|
857
|
+
readonly title: string;
|
|
858
|
+
readonly detail?: string;
|
|
859
|
+
readonly instance?: string;
|
|
860
|
+
/** O campo que causou o erro (regras fiscais, `422`). */
|
|
861
|
+
readonly field?: string;
|
|
862
|
+
/** Erros de validação (`400`): `campo: mensagem`. */
|
|
863
|
+
readonly errors?: Record<string, string>;
|
|
864
|
+
/** O documento de erro completo, incluindo membros que o SDK não conhece. */
|
|
865
|
+
readonly problem: Problem;
|
|
866
|
+
/** Segundos a esperar (`Retry-After`), quando a API os indicou. */
|
|
867
|
+
readonly retryAfter?: number;
|
|
868
|
+
readonly headers: Headers;
|
|
869
|
+
constructor(problem: Problem, headers: Headers, retryAfter?: number);
|
|
870
|
+
/** `true` para `429`, `502` e `503`: repetir mais tarde (com o mesmo `Idempotency-Key`). */
|
|
871
|
+
get retryable(): boolean;
|
|
872
|
+
}
|
|
873
|
+
/** `400`: o corpo não é válido; `errors` diz quais campos. */
|
|
874
|
+
declare class BrisaValidationError extends BrisaApiError {
|
|
875
|
+
}
|
|
876
|
+
/** `401`: chave inválida, expirada, revogada, de outro ambiente ou de um endereço não autorizado. */
|
|
877
|
+
declare class BrisaAuthenticationError extends BrisaApiError {
|
|
878
|
+
}
|
|
879
|
+
/** `402`: o plano não permite (`limite-do-plano`, `plano-sem-api`) ou a subscrição está inativa. */
|
|
880
|
+
declare class BrisaPlanError extends BrisaApiError {
|
|
881
|
+
/** O que se esgotou (`invoices`, `clients`, `products`, `users`), nos erros de limite do plano. */
|
|
882
|
+
get metric(): string | undefined;
|
|
883
|
+
/** O máximo do plano. */
|
|
884
|
+
get limit(): number | undefined;
|
|
885
|
+
}
|
|
886
|
+
/** `403`: a chave não tem a permissão necessária. */
|
|
887
|
+
declare class BrisaPermissionError extends BrisaApiError {
|
|
888
|
+
}
|
|
889
|
+
/** `404`: não existe nesta empresa (ou está no outro ambiente). */
|
|
890
|
+
declare class BrisaNotFoundError extends BrisaApiError {
|
|
891
|
+
}
|
|
892
|
+
/** `409`: o recurso ainda não está pronto (ex.: SAF-T ainda a gerar). */
|
|
893
|
+
declare class BrisaConflictError extends BrisaApiError {
|
|
894
|
+
}
|
|
895
|
+
/** `422`: uma regra fiscal recusou a operação (ou um `Idempotency-Key` foi reutilizado com outro corpo). */
|
|
896
|
+
declare class BrisaRuleError extends BrisaApiError {
|
|
897
|
+
}
|
|
898
|
+
/** `429`: demasiados pedidos; espere `retryAfter` segundos. */
|
|
899
|
+
declare class BrisaRateLimitError extends BrisaApiError {
|
|
900
|
+
}
|
|
901
|
+
/** `5xx`: a AGT ou o serviço estão temporariamente indisponíveis. */
|
|
902
|
+
declare class BrisaServerError extends BrisaApiError {
|
|
903
|
+
}
|
|
904
|
+
/** Não foi possível falar com a API (rede, DNS, TLS). */
|
|
905
|
+
declare class BrisaConnectionError extends BrisaError {
|
|
906
|
+
}
|
|
907
|
+
/** A API não respondeu dentro do tempo (`timeoutMs`). */
|
|
908
|
+
declare class BrisaTimeoutError extends BrisaConnectionError {
|
|
909
|
+
}
|
|
910
|
+
/** A assinatura de um webhook não é válida (ou está fora da tolerância de tempo). */
|
|
911
|
+
declare class BrisaWebhookSignatureError extends BrisaError {
|
|
912
|
+
}
|
|
913
|
+
declare function errorFor(problem: Problem, headers: Headers, retryAfter?: number): BrisaApiError;
|
|
914
|
+
|
|
915
|
+
/**
|
|
916
|
+
* Percorre todas as páginas de uma lista, pedindo a seguinte só quando é precisa.
|
|
917
|
+
*
|
|
918
|
+
* ```ts
|
|
919
|
+
* for await (const doc of brisa.documents.listAll({ type: 'FT' })) console.log(doc.number)
|
|
920
|
+
* ```
|
|
921
|
+
*/
|
|
922
|
+
declare function paginate<T, P extends PageParams>(fetchPage: (params: P) => Promise<Page<T>>, params: P): AsyncGenerator<T, void, undefined>;
|
|
923
|
+
/** Junta numa lista todos os itens de um iterador assíncrono (cuidado com listas muito grandes). */
|
|
924
|
+
declare function collect<T>(it: AsyncIterable<T>, max?: number): Promise<T[]>;
|
|
925
|
+
|
|
926
|
+
declare const VERSION = "0.2.0";
|
|
927
|
+
|
|
928
|
+
export { type ApiResponse, type BankDetails, Brisa, BrisaApiError, BrisaAuthenticationError, BrisaConflictError, BrisaConnectionError, BrisaError, BrisaNotFoundError, type BrisaOptions, BrisaPermissionError, BrisaPlanError, BrisaRateLimitError, BrisaRuleError, BrisaServerError, BrisaTimeoutError, BrisaValidationError, BrisaWebhookSignatureError, type CancelDocumentRequest, Catalog, type Category, type Client, type ClientInput, type ClientStatement, Clients, type Company, type CompanyTax, type CreditNoteRequest, type CreditedLine, DEFAULT_BASE_URL, type DocumentCustomer, type DocumentDetail, type DocumentExport, type DocumentHistory, type DocumentIssuedData, type DocumentLine, type DocumentLineInput, type DocumentState, type DocumentSummary, type DocumentType, Documents, type ExemptionReason, type GlobalPaymentRequest, type IssuableDocumentType, type IssueDocumentRequest, type IssuedDocument, type LineTax, type ListClientsParams, type ListDocumentsParams, type ListProductsParams, type Me, type Page, type PageParams, type PayDocumentRequest, type PaymentAtIssue, type PaymentMethod, type PaymentPart, type PaymentResult, type PdfOptions, type Problem, type Product, type ProductInput, type ProductTaxRef, Products, type RateLimit, type RectifyDocumentRequest, type Request, type RequestOptions, Saft, type SaftExport, type SaftExportStatus, type SendDocumentRequest, type SendResult, type StatementEntry, type StockLevel, type StockMovementRequest, VERSION, type VerifyWebhookOptions, type WebhookEvent, type WebhookEventType, collect, errorFor, idempotencyKey, paginate, parseRetryAfter, parseSignatureHeader, signWebhookPayload, verifyWebhook };
|