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