@miguelmorales13/nestkit 0.11.0 → 0.18.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.
Files changed (126) hide show
  1. package/README.md +619 -35
  2. package/dist/audit/audit.module.d.ts +23 -0
  3. package/dist/audit/audit.options.d.ts +16 -0
  4. package/dist/audit/audit.port.d.ts +37 -0
  5. package/dist/audit/audit.service.d.ts +29 -0
  6. package/dist/audit/index.cjs +72 -0
  7. package/dist/audit/index.d.ts +7 -0
  8. package/dist/audit/index.js +72 -0
  9. package/dist/audit/sinks.d.ts +18 -0
  10. package/dist/auth/index.cjs +12 -10
  11. package/dist/auth/index.js +5 -3
  12. package/dist/auth/oauth/http.d.ts +10 -3
  13. package/dist/auth/oauth/index.cjs +189 -29
  14. package/dist/auth/oauth/index.d.ts +6 -4
  15. package/dist/auth/oauth/index.js +169 -9
  16. package/dist/auth/oauth/magic-link.dto.d.ts +6 -0
  17. package/dist/auth/oauth/memory-magic-link.store.d.ts +19 -0
  18. package/dist/auth/oauth/oauth-auth.service.d.ts +46 -5
  19. package/dist/auth/oauth/oauth.controller.d.ts +5 -1
  20. package/dist/auth/oauth/oauth.options.d.ts +34 -1
  21. package/dist/auth/oauth/oauth.ports.d.ts +38 -0
  22. package/dist/bootstrap/index.cjs +9 -6
  23. package/dist/bootstrap/index.js +8 -5
  24. package/dist/{chunk-TJHRABML.cjs → chunk-3AUOOEQO.cjs} +12 -7
  25. package/dist/{chunk-NVCI3CQI.cjs → chunk-4HHZFOVC.cjs} +10 -5
  26. package/dist/{chunk-EYURGACO.js → chunk-4PFAKLT3.js} +1 -1
  27. package/dist/chunk-52IOOHNX.cjs +205 -0
  28. package/dist/chunk-6RAPVLJM.js +212 -0
  29. package/dist/{chunk-7I2Y7V52.js → chunk-A2DGK4ZL.js} +26 -3
  30. package/dist/chunk-APUFKA4K.cjs +212 -0
  31. package/dist/chunk-AXMW5JF7.cjs +83 -0
  32. package/dist/{chunk-KDAA6GFF.js → chunk-DYHSOULW.js} +12 -7
  33. package/dist/chunk-ETRUVZTJ.js +43 -0
  34. package/dist/{chunk-54ZXIB5T.cjs → chunk-FNUZGYUF.cjs} +4 -4
  35. package/dist/{chunk-FDNGAYTZ.cjs → chunk-HDFPSA2V.cjs} +6 -6
  36. package/dist/{chunk-V2M75FN3.cjs → chunk-HVHYZXBB.cjs} +2 -2
  37. package/dist/chunk-IFNYRZP2.js +205 -0
  38. package/dist/{chunk-A3B2EY4V.js → chunk-IKXSVEJ7.js} +7 -2
  39. package/dist/{chunk-YFYHLYHN.js → chunk-M3GQDRWR.js} +7 -1
  40. package/dist/{chunk-J7TURDAL.cjs → chunk-MSTXS3MU.cjs} +28 -5
  41. package/dist/chunk-PNK5WMPP.cjs +30 -0
  42. package/dist/chunk-Q5Y33L7B.cjs +19 -0
  43. package/dist/{chunk-ZA56XBCK.cjs → chunk-SDWHKPXI.cjs} +23 -0
  44. package/dist/chunk-TCAMLNUZ.js +27 -0
  45. package/dist/{chunk-AOCF5QCZ.js → chunk-UNEVXCFW.js} +2 -2
  46. package/dist/chunk-VVMRZEIW.js +30 -0
  47. package/dist/chunk-W2T2VFLC.cjs +57 -0
  48. package/dist/chunk-X4PQJZ4G.js +83 -0
  49. package/dist/chunk-Y72D5L6I.cjs +27 -0
  50. package/dist/{chunk-ORWJ7LES.js → chunk-ZFIDAX7K.js} +1 -1
  51. package/dist/chunk-ZJMLEP5H.js +57 -0
  52. package/dist/crud/crud.controller.d.ts +3 -1
  53. package/dist/crud/crud.service.d.ts +63 -4
  54. package/dist/crud/index.cjs +7 -2
  55. package/dist/crud/index.d.ts +2 -1
  56. package/dist/crud/index.js +6 -1
  57. package/dist/crud/list-query.dto.d.ts +23 -0
  58. package/dist/crud/repository.port.d.ts +33 -1
  59. package/dist/errors/app.exception.d.ts +9 -1
  60. package/dist/errors/common.exceptions.d.ts +6 -5
  61. package/dist/errors/global-exception.filter.d.ts +9 -0
  62. package/dist/errors/index.cjs +8 -5
  63. package/dist/errors/index.js +9 -6
  64. package/dist/i18n/i18n.interceptor.d.ts +16 -0
  65. package/dist/i18n/i18n.module.d.ts +49 -3
  66. package/dist/i18n/index.cjs +26 -2
  67. package/dist/i18n/index.d.ts +8 -0
  68. package/dist/i18n/index.js +25 -1
  69. package/dist/i18n/locale.d.ts +53 -0
  70. package/dist/i18n/message.d.ts +36 -0
  71. package/dist/i18n/nestjs-i18n.translator.d.ts +9 -0
  72. package/dist/i18n/runtime.d.ts +55 -0
  73. package/dist/i18n/translator.port.d.ts +29 -0
  74. package/dist/idempotency/idempotency.interceptor.d.ts +35 -0
  75. package/dist/idempotency/idempotency.module.d.ts +27 -0
  76. package/dist/idempotency/idempotency.options.d.ts +29 -0
  77. package/dist/idempotency/idempotency.port.d.ts +43 -0
  78. package/dist/idempotency/index.cjs +207 -0
  79. package/dist/idempotency/index.d.ts +7 -0
  80. package/dist/idempotency/index.js +207 -0
  81. package/dist/idempotency/memory.store.d.ts +24 -0
  82. package/dist/index.cjs +48 -15
  83. package/dist/index.js +51 -18
  84. package/dist/invoicing/adapters/facturama.invoicing.d.ts +50 -0
  85. package/dist/invoicing/adapters/facturapi.invoicing.d.ts +35 -0
  86. package/dist/invoicing/amounts.d.ts +52 -0
  87. package/dist/invoicing/index.cjs +578 -0
  88. package/dist/invoicing/index.d.ts +11 -0
  89. package/dist/invoicing/index.js +578 -0
  90. package/dist/invoicing/invoicing.module.d.ts +42 -0
  91. package/dist/invoicing/invoicing.options.d.ts +51 -0
  92. package/dist/invoicing/invoicing.port.d.ts +156 -0
  93. package/dist/invoicing/lines.d.ts +21 -0
  94. package/dist/invoicing/provider-http.d.ts +21 -0
  95. package/dist/payments/adapters/clip.terminal.d.ts +101 -0
  96. package/dist/payments/adapters/mercadopago.terminal.d.ts +74 -0
  97. package/dist/payments/index.cjs +796 -0
  98. package/dist/payments/index.d.ts +12 -0
  99. package/dist/payments/index.js +796 -0
  100. package/dist/payments/money.d.ts +20 -0
  101. package/dist/payments/payments-webhook.controller.d.ts +30 -0
  102. package/dist/payments/payments.module.d.ts +45 -0
  103. package/dist/payments/payments.options.d.ts +84 -0
  104. package/dist/payments/payments.port.d.ts +174 -0
  105. package/dist/payments/provider-http.d.ts +26 -0
  106. package/dist/response/api-response.d.ts +7 -0
  107. package/dist/response/index.cjs +12 -4
  108. package/dist/response/index.d.ts +2 -0
  109. package/dist/response/index.js +12 -4
  110. package/dist/response/paginated.d.ts +25 -0
  111. package/dist/response/response.interceptor.d.ts +4 -0
  112. package/dist/stripe/index.cjs +4 -3
  113. package/dist/stripe/index.js +3 -2
  114. package/dist/tracking/index.cjs +3 -3
  115. package/dist/tracking/index.d.ts +1 -1
  116. package/dist/tracking/index.js +2 -2
  117. package/dist/tracking/request-context.d.ts +32 -0
  118. package/package.json +25 -3
  119. package/dist/chunk-3CLYZC3T.cjs +0 -104
  120. package/dist/chunk-EBO6UKHL.js +0 -20
  121. package/dist/chunk-IYUUYCP5.js +0 -36
  122. package/dist/chunk-JOVBJDJ2.js +0 -104
  123. package/dist/chunk-M3EL5O6T.cjs +0 -36
  124. package/dist/chunk-R7BVS6CI.cjs +0 -13
  125. /package/dist/{chunk-MR2IFCZE.cjs → chunk-H2EHN366.cjs} +0 -0
  126. /package/dist/{chunk-NAK4WDKS.js → chunk-ODPSIFOB.js} +0 -0
@@ -0,0 +1,578 @@
1
+ import {
2
+ ValidationAppException
3
+ } from "../chunk-ZFIDAX7K.js";
4
+ import {
5
+ AppException
6
+ } from "../chunk-M3GQDRWR.js";
7
+ import "../chunk-VVMRZEIW.js";
8
+ import {
9
+ __decorateClass
10
+ } from "../chunk-4MGIQFAJ.js";
11
+
12
+ // src/invoicing/invoicing.port.ts
13
+ var INVOICING = /* @__PURE__ */ Symbol("INVOICING");
14
+
15
+ // src/invoicing/invoicing.options.ts
16
+ var INVOICING_OPTIONS = /* @__PURE__ */ Symbol("INVOICING_OPTIONS");
17
+
18
+ // src/invoicing/invoicing.module.ts
19
+ import { Global, Module } from "@nestjs/common";
20
+
21
+ // src/invoicing/amounts.ts
22
+ function roundHalfUp(value) {
23
+ return value < 0 ? -Math.round(-value) : Math.round(value);
24
+ }
25
+ function assertCents(cents, field) {
26
+ if (!Number.isInteger(cents)) {
27
+ throw new ValidationAppException(`${field} must be an integer number of cents, got ${cents}`, {
28
+ [field]: cents
29
+ });
30
+ }
31
+ if (cents < 0) {
32
+ throw new ValidationAppException(`${field} must not be negative, got ${cents}`, { [field]: cents });
33
+ }
34
+ }
35
+ function centsToDecimal(cents) {
36
+ const sign = cents < 0 ? "-" : "";
37
+ const abs = Math.abs(cents);
38
+ return `${sign}${Math.floor(abs / 100)}.${String(abs % 100).padStart(2, "0")}`;
39
+ }
40
+ function decimalToCents(value) {
41
+ const text = typeof value === "number" ? value.toFixed(2) : value.trim();
42
+ const match = /^(-?)(\d+)(?:\.(\d+))?$/.exec(text);
43
+ if (!match) {
44
+ throw new ValidationAppException(`Cannot read "${text}" as a decimal amount`, { value });
45
+ }
46
+ const [, sign, whole, fraction = ""] = match;
47
+ const cents = Number(whole) * 100 + roundHalfUp(Number(`0.${fraction || "0"}`) * 100);
48
+ return sign === "-" ? -cents : cents;
49
+ }
50
+ function assertDecimalString(value, field) {
51
+ if (!/^\d+(\.\d{1,6})?$/.test(value.trim())) {
52
+ throw new ValidationAppException(
53
+ `${field} must be a decimal with at most 6 places, written as a string, got "${value}"`,
54
+ { [field]: value }
55
+ );
56
+ }
57
+ }
58
+ function unitPriceToDecimal(price) {
59
+ return "cents" in price ? centsToDecimal(price.cents) : price.decimal.trim();
60
+ }
61
+ function lineAmountCents(price, quantity) {
62
+ if (!(quantity > 0) || !Number.isFinite(quantity)) {
63
+ throw new ValidationAppException(`quantity must be a positive number, got ${quantity}`, { quantity });
64
+ }
65
+ const micros = "cents" in price ? price.cents * 1e4 : roundHalfUp(Number(price.decimal) * 1e6);
66
+ return roundHalfUp(micros * quantity / 1e4);
67
+ }
68
+ function taxAmountCents(baseCents, rate) {
69
+ return roundHalfUp(baseCents * rate);
70
+ }
71
+
72
+ // src/invoicing/lines.ts
73
+ var DEFAULT_TAXES = [{ type: "IVA", rate: 0.16 }];
74
+ function unitPriceOf(item) {
75
+ const hasCents = item.unitPriceCents !== void 0;
76
+ const hasDecimal = item.unitPrice !== void 0;
77
+ if (hasCents === hasDecimal) {
78
+ throw new ValidationAppException(
79
+ "each item needs exactly one of unitPriceCents (the usual) or unitPrice (an exact decimal string)",
80
+ { description: item.description }
81
+ );
82
+ }
83
+ if (hasCents) {
84
+ assertCents(item.unitPriceCents, "unitPriceCents");
85
+ return { cents: item.unitPriceCents };
86
+ }
87
+ assertDecimalString(item.unitPrice, "unitPrice");
88
+ return { decimal: item.unitPrice };
89
+ }
90
+ function computeLine(item) {
91
+ if (!item.description?.trim()) {
92
+ throw new ValidationAppException("each item needs a description", { item });
93
+ }
94
+ if (!item.productKey?.trim()) {
95
+ throw new ValidationAppException(
96
+ `item "${item.description}" needs a productKey (ClaveProdServ from the SAT catalogue)`,
97
+ { item }
98
+ );
99
+ }
100
+ const price = unitPriceOf(item);
101
+ const quantity = item.quantity ?? 1;
102
+ const amountCents = lineAmountCents(price, quantity);
103
+ const taxes = (item.taxes ?? DEFAULT_TAXES).map((tax) => ({
104
+ tax,
105
+ baseCents: amountCents,
106
+ amountCents: taxAmountCents(amountCents, tax.rate)
107
+ }));
108
+ const totalCents = taxes.reduce(
109
+ (total, t) => total + (t.tax.withholding ? -t.amountCents : t.amountCents),
110
+ amountCents
111
+ );
112
+ return { item, quantity, unitPriceDecimal: unitPriceToDecimal(price), amountCents, taxes, totalCents };
113
+ }
114
+ function computeLines(items) {
115
+ if (items.length === 0) {
116
+ throw new ValidationAppException("an invoice needs at least one item", { items });
117
+ }
118
+ return items.map(computeLine);
119
+ }
120
+ function sumCents(lines, field) {
121
+ return lines.reduce((total, line) => total + line[field], 0);
122
+ }
123
+ var decimal = centsToDecimal;
124
+
125
+ // src/invoicing/provider-http.ts
126
+ import { HttpStatus } from "@nestjs/common";
127
+ var InvoicingProviderException = class extends AppException {
128
+ constructor(provider, status, body, message) {
129
+ super(
130
+ "INVOICING_PROVIDER_ERROR",
131
+ message ?? `${provider} rejected the request (HTTP ${status})`,
132
+ HttpStatus.BAD_GATEWAY,
133
+ { provider, status, body }
134
+ );
135
+ }
136
+ };
137
+ var UnsupportedByProviderException = class extends AppException {
138
+ constructor(provider, message) {
139
+ super("INVOICING_UNSUPPORTED", message, HttpStatus.BAD_REQUEST, { provider });
140
+ }
141
+ };
142
+ async function send(provider, fetchImpl, url, init) {
143
+ try {
144
+ return await fetchImpl(url, init);
145
+ } catch (cause) {
146
+ throw new InvoicingProviderException(
147
+ provider,
148
+ 0,
149
+ { error: cause instanceof Error ? cause.message : String(cause) },
150
+ `${provider} is unreachable`
151
+ );
152
+ }
153
+ }
154
+ async function requestJson(provider, fetchImpl, url, init) {
155
+ const response = await send(provider, fetchImpl, url, init);
156
+ const text = await response.text();
157
+ let body = void 0;
158
+ if (text) {
159
+ try {
160
+ body = JSON.parse(text);
161
+ } catch {
162
+ body = text;
163
+ }
164
+ }
165
+ if (!response.ok) throw new InvoicingProviderException(provider, response.status, body);
166
+ return body;
167
+ }
168
+ async function requestBytes(provider, fetchImpl, url, init) {
169
+ const response = await send(provider, fetchImpl, url, init);
170
+ if (!response.ok) {
171
+ throw new InvoicingProviderException(provider, response.status, await response.text());
172
+ }
173
+ return new Uint8Array(await response.arrayBuffer());
174
+ }
175
+
176
+ // src/invoicing/adapters/facturapi.invoicing.ts
177
+ var PROVIDER = "facturapi";
178
+ var DEFAULT_BASE_URL = "https://www.facturapi.io/v2";
179
+ function toStatus(status) {
180
+ switch (status) {
181
+ case "valid":
182
+ return "stamped";
183
+ case "canceled":
184
+ case "cancelled":
185
+ return "cancelled";
186
+ case "draft":
187
+ return "draft";
188
+ case "pending_cancellation":
189
+ return "pending";
190
+ default:
191
+ return "unknown";
192
+ }
193
+ }
194
+ var FacturapiInvoicing = class {
195
+ constructor(options) {
196
+ this.options = options;
197
+ this.provider = PROVIDER;
198
+ if (!options.apiKey) {
199
+ throw new Error("FacturapiInvoicing: apiKey is required (FACTURAPI_API_KEY).");
200
+ }
201
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
202
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
203
+ }
204
+ /** True when the configured key cannot produce a document with fiscal effects. */
205
+ get isTestKey() {
206
+ return this.options.apiKey.startsWith("sk_test_");
207
+ }
208
+ headers() {
209
+ return {
210
+ authorization: `Bearer ${this.options.apiKey}`,
211
+ "content-type": "application/json"
212
+ };
213
+ }
214
+ async issue(draft) {
215
+ const lines = computeLines(draft.items);
216
+ const invoice = await requestJson(PROVIDER, this.fetchImpl, `${this.baseUrl}/invoices`, {
217
+ method: "POST",
218
+ headers: this.headers(),
219
+ body: JSON.stringify({
220
+ customer: typeof draft.customer === "string" ? draft.customer : {
221
+ legal_name: draft.customer.legalName,
222
+ tax_id: draft.customer.taxId,
223
+ tax_system: draft.customer.taxSystem,
224
+ address: { zip: draft.customer.zip },
225
+ email: draft.customer.email
226
+ },
227
+ items: lines.map((line) => ({
228
+ quantity: line.quantity,
229
+ product: {
230
+ description: line.item.description,
231
+ product_key: line.item.productKey,
232
+ unit_key: line.item.unitKey ?? "H87",
233
+ unit_name: line.item.unitName,
234
+ sku: line.item.sku,
235
+ // Sent as a decimal, from cents: Facturapi's `price` is a JSON
236
+ // number and building it by division is how 19.99 becomes 19.989999.
237
+ price: Number(line.unitPriceDecimal),
238
+ tax_included: false,
239
+ taxes: line.taxes.map(({ tax }) => ({
240
+ type: tax.type,
241
+ rate: tax.rate,
242
+ withholding: tax.withholding ?? false
243
+ }))
244
+ }
245
+ })),
246
+ payment_form: draft.paymentForm,
247
+ payment_method: draft.paymentMethod ?? "PUE",
248
+ use: draft.use ?? (typeof draft.customer === "string" ? void 0 : draft.customer.use) ?? "G03",
249
+ type: draft.type ?? "I",
250
+ currency: draft.currency ?? "MXN",
251
+ exchange: draft.exchangeRate,
252
+ series: draft.series,
253
+ folio_number: draft.folioNumber,
254
+ external_id: draft.externalId
255
+ })
256
+ });
257
+ return this.toInvoice(invoice);
258
+ }
259
+ async get(id) {
260
+ return this.toInvoice(
261
+ await requestJson(PROVIDER, this.fetchImpl, `${this.baseUrl}/invoices/${encodeURIComponent(id)}`, {
262
+ method: "GET",
263
+ headers: this.headers()
264
+ })
265
+ );
266
+ }
267
+ async cancel(id, options) {
268
+ if (options.motive === "01" && !options.substitutionId) {
269
+ throw new InvoicingProviderException(
270
+ PROVIDER,
271
+ 0,
272
+ options,
273
+ "Cancelling with motive 01 requires the id of the invoice that replaces this one."
274
+ );
275
+ }
276
+ const query = new URLSearchParams({ motive: options.motive });
277
+ if (options.substitutionId) query.set("substitution", options.substitutionId);
278
+ return this.toInvoice(
279
+ await requestJson(
280
+ PROVIDER,
281
+ this.fetchImpl,
282
+ `${this.baseUrl}/invoices/${encodeURIComponent(id)}?${query.toString()}`,
283
+ { method: "DELETE", headers: this.headers() }
284
+ )
285
+ );
286
+ }
287
+ async pdf(id) {
288
+ return requestBytes(PROVIDER, this.fetchImpl, `${this.baseUrl}/invoices/${encodeURIComponent(id)}/pdf`, {
289
+ method: "GET",
290
+ headers: { authorization: `Bearer ${this.options.apiKey}` }
291
+ });
292
+ }
293
+ async xml(id) {
294
+ const bytes = await requestBytes(PROVIDER, this.fetchImpl, `${this.baseUrl}/invoices/${encodeURIComponent(id)}/xml`, {
295
+ method: "GET",
296
+ headers: { authorization: `Bearer ${this.options.apiKey}` }
297
+ });
298
+ return new TextDecoder().decode(bytes);
299
+ }
300
+ async sendByEmail(id, to) {
301
+ await requestJson(PROVIDER, this.fetchImpl, `${this.baseUrl}/invoices/${encodeURIComponent(id)}/email`, {
302
+ method: "POST",
303
+ headers: this.headers(),
304
+ body: JSON.stringify(to ? { email: to } : {})
305
+ });
306
+ }
307
+ toInvoice(invoice) {
308
+ if (!invoice?.id) {
309
+ throw new InvoicingProviderException(PROVIDER, 200, invoice, "Facturapi returned an invoice with no id");
310
+ }
311
+ const issuedAt = invoice.date ?? invoice.created_at;
312
+ return {
313
+ id: invoice.id,
314
+ provider: PROVIDER,
315
+ status: toStatus(invoice.status),
316
+ uuid: invoice.uuid,
317
+ series: invoice.series,
318
+ folioNumber: invoice.folio_number,
319
+ subtotalCents: invoice.subtotal === void 0 ? void 0 : decimalToCents(invoice.subtotal),
320
+ totalCents: invoice.total === void 0 ? 0 : decimalToCents(invoice.total),
321
+ currency: invoice.currency ?? "MXN",
322
+ customerTaxId: invoice.customer?.tax_id,
323
+ issuedAt: issuedAt ? new Date(issuedAt) : void 0,
324
+ raw: invoice
325
+ };
326
+ }
327
+ };
328
+
329
+ // src/invoicing/adapters/facturama.invoicing.ts
330
+ var PROVIDER2 = "facturama";
331
+ var DEFAULT_BASE_URL2 = "https://apisandbox.facturama.mx";
332
+ function toStatus2(cfdi) {
333
+ const status = cfdi.Status?.toLowerCase();
334
+ if (status === "canceled" || status === "cancelled") return "cancelled";
335
+ if (status === "active") return "stamped";
336
+ return cfdi.Complement?.TaxStamp?.Uuid ? "stamped" : "unknown";
337
+ }
338
+ var FacturamaInvoicing = class {
339
+ constructor(options) {
340
+ this.options = options;
341
+ this.provider = PROVIDER2;
342
+ if (!options.user || !options.password) {
343
+ throw new Error("FacturamaInvoicing: user and password are required (FACTURAMA_USER / FACTURAMA_PASSWORD).");
344
+ }
345
+ if (!options.expeditionPlace) {
346
+ throw new Error("FacturamaInvoicing: expeditionPlace (the issuer postal code) is required on every CFDI.");
347
+ }
348
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL2).replace(/\/$/, "");
349
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
350
+ this.token = Buffer.from(`${options.user}:${options.password}`).toString("base64");
351
+ this.documentType = options.documentType ?? "issued";
352
+ }
353
+ /** True while this adapter points at the sandbox host. */
354
+ get isSandbox() {
355
+ return this.baseUrl.includes("apisandbox.");
356
+ }
357
+ headers() {
358
+ return { authorization: `Basic ${this.token}`, "content-type": "application/json" };
359
+ }
360
+ async issue(draft) {
361
+ if (typeof draft.customer === "string") {
362
+ throw new UnsupportedByProviderException(
363
+ PROVIDER2,
364
+ "Facturama's API Web takes the receiver inline on each CFDI, not by id. Pass the customer object."
365
+ );
366
+ }
367
+ const lines = computeLines(draft.items);
368
+ const cfdi = await requestJson(PROVIDER2, this.fetchImpl, `${this.baseUrl}/api/3/cfdis`, {
369
+ method: "POST",
370
+ headers: this.headers(),
371
+ body: JSON.stringify({
372
+ NameId: this.options.templateId,
373
+ CfdiType: draft.type ?? "I",
374
+ PaymentForm: draft.paymentForm,
375
+ PaymentMethod: draft.paymentMethod ?? "PUE",
376
+ ExpeditionPlace: this.options.expeditionPlace,
377
+ Currency: draft.currency ?? "MXN",
378
+ ExchangeRate: draft.exchangeRate,
379
+ Serie: draft.series,
380
+ Folio: draft.folioNumber === void 0 ? void 0 : String(draft.folioNumber),
381
+ OrderNumber: draft.externalId,
382
+ // `01` = no export operation, which is what a domestic invoice carries.
383
+ Exportation: "01",
384
+ Receiver: {
385
+ Rfc: draft.customer.taxId,
386
+ Name: draft.customer.legalName,
387
+ CfdiUse: draft.use ?? draft.customer.use ?? "G03",
388
+ FiscalRegime: draft.customer.taxSystem,
389
+ TaxZipCode: draft.customer.zip
390
+ },
391
+ Items: lines.map((line) => ({
392
+ Quantity: String(line.quantity),
393
+ ProductCode: line.item.productKey,
394
+ UnitCode: line.item.unitKey ?? "H87",
395
+ Unit: line.item.unitName,
396
+ Description: line.item.description,
397
+ IdentificationNumber: line.item.sku,
398
+ UnitPrice: line.unitPriceDecimal,
399
+ Subtotal: decimal(line.amountCents),
400
+ TaxObject: line.item.taxObject ?? (line.taxes.length === 0 ? "01" : "02"),
401
+ Taxes: line.taxes.map(({ tax, baseCents, amountCents }) => ({
402
+ Name: tax.type,
403
+ Rate: String(tax.rate),
404
+ Base: decimal(baseCents),
405
+ Total: decimal(amountCents),
406
+ IsRetention: String(tax.withholding ?? false),
407
+ IsFederalTax: "true"
408
+ })),
409
+ Total: decimal(line.totalCents)
410
+ }))
411
+ })
412
+ });
413
+ return this.toInvoice(cfdi, sumCents(lines, "totalCents"));
414
+ }
415
+ async get(id) {
416
+ return this.toInvoice(
417
+ await requestJson(
418
+ PROVIDER2,
419
+ this.fetchImpl,
420
+ `${this.baseUrl}/Cfdi/${encodeURIComponent(id)}/${this.documentType}`,
421
+ { method: "GET", headers: this.headers() }
422
+ )
423
+ );
424
+ }
425
+ /**
426
+ * Cancels with a motive.
427
+ *
428
+ * Facturama documents this route twice — once with the parameters in the path
429
+ * and once, in its how-to guide, with them in the query string. The guide's
430
+ * form is the one with a working example next to it, so it is the one used
431
+ * here.
432
+ */
433
+ async cancel(id, options) {
434
+ if (options.motive === "01" && !options.substitutionId) {
435
+ throw new InvoicingProviderException(
436
+ PROVIDER2,
437
+ 0,
438
+ options,
439
+ "Cancelling with motive 01 requires the UUID of the invoice that replaces this one."
440
+ );
441
+ }
442
+ const query = new URLSearchParams({ type: this.documentType, motive: options.motive });
443
+ if (options.substitutionId) query.set("uuidReplacement", options.substitutionId);
444
+ await requestJson(
445
+ PROVIDER2,
446
+ this.fetchImpl,
447
+ `${this.baseUrl}/cfdi/${encodeURIComponent(id)}?${query.toString()}`,
448
+ { method: "DELETE", headers: this.headers() }
449
+ );
450
+ return this.get(id);
451
+ }
452
+ async pdf(id) {
453
+ return this.download("pdf", id);
454
+ }
455
+ async xml(id) {
456
+ return new TextDecoder().decode(await this.download("xml", id));
457
+ }
458
+ /**
459
+ * Facturama hands files back as base64 inside a JSON envelope rather than as
460
+ * bytes, so this decodes rather than streams.
461
+ */
462
+ async download(format, id) {
463
+ const file = await requestJson(
464
+ PROVIDER2,
465
+ this.fetchImpl,
466
+ `${this.baseUrl}/Cfdi/${format}/${this.documentType}/${encodeURIComponent(id)}`,
467
+ { method: "GET", headers: this.headers() }
468
+ );
469
+ if (!file?.Content) {
470
+ throw new InvoicingProviderException(PROVIDER2, 200, file, `Facturama returned no ${format} content`);
471
+ }
472
+ return new Uint8Array(Buffer.from(file.Content, "base64"));
473
+ }
474
+ async sendByEmail(_id, _to) {
475
+ throw new UnsupportedByProviderException(
476
+ PROVIDER2,
477
+ "Facturama's email route carries subject, comments, issuer address and a pay-button flag as path segments, and sends to the receiver on file rather than to an address you choose \u2014 it does not fit this method. Call it directly if you need it, or send the PDF/XML with the email module."
478
+ );
479
+ }
480
+ toInvoice(cfdi, fallbackTotalCents = 0) {
481
+ if (!cfdi?.Id) {
482
+ throw new InvoicingProviderException(PROVIDER2, 200, cfdi, "Facturama returned a CFDI with no Id");
483
+ }
484
+ const stampedAt = cfdi.Complement?.TaxStamp?.Date ?? cfdi.Date;
485
+ return {
486
+ id: cfdi.Id,
487
+ provider: PROVIDER2,
488
+ status: toStatus2(cfdi),
489
+ uuid: cfdi.Complement?.TaxStamp?.Uuid,
490
+ series: cfdi.Serie,
491
+ folioNumber: cfdi.Folio === void 0 ? void 0 : Number(cfdi.Folio) || void 0,
492
+ subtotalCents: cfdi.Subtotal === void 0 ? void 0 : decimalToCents(cfdi.Subtotal),
493
+ totalCents: cfdi.Total === void 0 ? fallbackTotalCents : decimalToCents(cfdi.Total),
494
+ currency: cfdi.Currency ?? "MXN",
495
+ customerTaxId: cfdi.Receiver?.Rfc,
496
+ issuedAt: stampedAt ? new Date(stampedAt) : void 0,
497
+ raw: cfdi
498
+ };
499
+ }
500
+ };
501
+
502
+ // src/invoicing/invoicing.module.ts
503
+ var env = (key) => process.env[key] || void 0;
504
+ function resolveInvoicingOptions(options = {}) {
505
+ return {
506
+ provider: options.provider ?? env("INVOICING_PROVIDER"),
507
+ facturapi: options.facturapi ?? (env("FACTURAPI_API_KEY") ? { apiKey: env("FACTURAPI_API_KEY") } : void 0),
508
+ facturama: options.facturama ?? (env("FACTURAMA_USER") ? {
509
+ user: env("FACTURAMA_USER"),
510
+ password: env("FACTURAMA_PASSWORD") ?? "",
511
+ expeditionPlace: env("FACTURAMA_EXPEDITION_PLACE") ?? "",
512
+ templateId: env("FACTURAMA_TEMPLATE_ID"),
513
+ baseUrl: env("FACTURAMA_BASE_URL")
514
+ } : void 0)
515
+ };
516
+ }
517
+ function createInvoicingAdapter(options) {
518
+ const resolved = resolveInvoicingOptions(options);
519
+ switch (resolved.provider) {
520
+ case "facturapi":
521
+ if (!resolved.facturapi)
522
+ throw new Error('InvoicingModule: provider "facturapi" selected but no facturapi options / FACTURAPI_API_KEY set.');
523
+ return new FacturapiInvoicing(resolved.facturapi);
524
+ case "facturama":
525
+ if (!resolved.facturama)
526
+ throw new Error('InvoicingModule: provider "facturama" selected but no facturama options / FACTURAMA_* env set.');
527
+ return new FacturamaInvoicing(resolved.facturama);
528
+ case void 0:
529
+ throw new Error("InvoicingModule: no provider selected \u2014 pass `provider` or set INVOICING_PROVIDER.");
530
+ default:
531
+ throw new Error(`InvoicingModule: unknown provider "${resolved.provider}".`);
532
+ }
533
+ }
534
+ var InvoicingModule = class {
535
+ static forRoot(options = {}) {
536
+ const providers = [
537
+ { provide: INVOICING_OPTIONS, useValue: options },
538
+ { provide: INVOICING, useFactory: () => createInvoicingAdapter(options) }
539
+ ];
540
+ return { module: InvoicingModule, providers, exports: [INVOICING, INVOICING_OPTIONS] };
541
+ }
542
+ static forRootAsync(config) {
543
+ const providers = [
544
+ { provide: INVOICING_OPTIONS, useFactory: config.useFactory, inject: config.inject ?? [] },
545
+ {
546
+ provide: INVOICING,
547
+ useFactory: (options) => createInvoicingAdapter(options),
548
+ inject: [INVOICING_OPTIONS]
549
+ }
550
+ ];
551
+ return {
552
+ module: InvoicingModule,
553
+ imports: config.imports ?? [],
554
+ providers,
555
+ exports: [INVOICING, INVOICING_OPTIONS]
556
+ };
557
+ }
558
+ };
559
+ InvoicingModule = __decorateClass([
560
+ Global(),
561
+ Module({})
562
+ ], InvoicingModule);
563
+ export {
564
+ FacturamaInvoicing,
565
+ FacturapiInvoicing,
566
+ INVOICING,
567
+ INVOICING_OPTIONS,
568
+ InvoicingModule,
569
+ InvoicingProviderException,
570
+ UnsupportedByProviderException,
571
+ centsToDecimal,
572
+ computeLine,
573
+ computeLines,
574
+ createInvoicingAdapter,
575
+ decimalToCents,
576
+ resolveInvoicingOptions,
577
+ sumCents
578
+ };
@@ -0,0 +1,42 @@
1
+ import { type DynamicModule } from '@nestjs/common';
2
+ import { type InvoicingOptions } from './invoicing.options.js';
3
+ import { type InvoicingPort } from './invoicing.port.js';
4
+ /**
5
+ * Merge explicit options with the environment, so `InvoicingModule.forRoot()`
6
+ * with no arguments works when the environment is configured.
7
+ *
8
+ * Recognized vars: `INVOICING_PROVIDER`; Facturapi `FACTURAPI_API_KEY`;
9
+ * Facturama `FACTURAMA_USER`, `FACTURAMA_PASSWORD`, `FACTURAMA_EXPEDITION_PLACE`,
10
+ * `FACTURAMA_TEMPLATE_ID`, `FACTURAMA_BASE_URL`.
11
+ */
12
+ export declare function resolveInvoicingOptions(options?: InvoicingOptions): InvoicingOptions;
13
+ /**
14
+ * Build the adapter the options select, failing loudly on missing config.
15
+ *
16
+ * Exported on its own for the same reason as the payments one: a business can
17
+ * legitimately need two, and a second PAC as a fallback for when the first is
18
+ * down is a real pattern in Mexico.
19
+ */
20
+ export declare function createInvoicingAdapter(options: InvoicingOptions): InvoicingPort;
21
+ /**
22
+ * CFDI 4.0 invoicing for NestJS. Register once in the root module and inject
23
+ * the port anywhere with `@Inject(INVOICING) invoicing: InvoicingPort`.
24
+ *
25
+ * ```ts
26
+ * InvoicingModule.forRoot({ provider: 'facturapi' }) // reads FACTURAPI_API_KEY
27
+ * InvoicingModule.forRoot({ provider: 'facturama' }) // reads FACTURAMA_* (sandbox by default)
28
+ * InvoicingModule.forRootAsync({ inject: [Config], useFactory: (c) => ({ provider: c.pac }) })
29
+ * ```
30
+ *
31
+ * Changing PAC is this one line — which matters more here than elsewhere,
32
+ * because PACs go down, raise prices and get their authorisation revoked, and
33
+ * none of that should reach the code that sells things.
34
+ */
35
+ export declare class InvoicingModule {
36
+ static forRoot(options?: InvoicingOptions): DynamicModule;
37
+ static forRootAsync(config: {
38
+ imports?: any[];
39
+ inject?: any[];
40
+ useFactory: (...args: any[]) => InvoicingOptions | Promise<InvoicingOptions>;
41
+ }): DynamicModule;
42
+ }
@@ -0,0 +1,51 @@
1
+ /** DI token carrying the {@link InvoicingOptions} the module was registered with. */
2
+ export declare const INVOICING_OPTIONS: unique symbol;
3
+ /** Which PAC backs the {@link InvoicingPort}. */
4
+ export type InvoicingProvider = 'facturapi' | 'facturama';
5
+ /**
6
+ * Facturapi. Keys are environment-shaped the way Stripe's are —
7
+ * `sk_test_…` validates and builds the CFDI without sending it to the SAT,
8
+ * `sk_live_…` stamps for real. There is no separate host, so **the key is the
9
+ * only thing standing between a test and a real invoice with fiscal effects**:
10
+ * keep them in different environments and never default to live.
11
+ */
12
+ export interface FacturapiOptions {
13
+ /** `sk_test_…` or `sk_live_…`. */
14
+ apiKey: string;
15
+ /** Override for tests. Defaults to `https://www.facturapi.io/v2`. */
16
+ baseUrl?: string;
17
+ /** Override for tests. Defaults to the global `fetch`. */
18
+ fetchImpl?: typeof fetch;
19
+ }
20
+ /**
21
+ * Facturama. Unlike Facturapi, the environment is the **host**: the sandbox
22
+ * lives at `https://apisandbox.facturama.mx` with its own credentials, and
23
+ * production at `https://api.facturama.mx`. Same code, different base URL.
24
+ */
25
+ export interface FacturamaOptions {
26
+ /** Dashboard user. Combined with {@link password} into the Basic token. */
27
+ user: string;
28
+ password: string;
29
+ /**
30
+ * Issuer's `ExpeditionPlace` — the postal code the invoice is issued from.
31
+ * Required on every CFDI, so it is configured once here instead of on each
32
+ * draft.
33
+ */
34
+ expeditionPlace: string;
35
+ /** `NameId` of the PDF template configured in the Facturama account. */
36
+ templateId?: string;
37
+ /**
38
+ * Which set of documents the id refers to. `issued` covers income, egress and
39
+ * complements, and is what an API Web account uses.
40
+ */
41
+ documentType?: 'issued' | 'received' | 'payroll';
42
+ /** Defaults to the sandbox host. Point it at `https://api.facturama.mx` to stamp for real. */
43
+ baseUrl?: string;
44
+ /** Override for tests. Defaults to the global `fetch`. */
45
+ fetchImpl?: typeof fetch;
46
+ }
47
+ export interface InvoicingOptions {
48
+ provider?: InvoicingProvider;
49
+ facturapi?: FacturapiOptions;
50
+ facturama?: FacturamaOptions;
51
+ }