@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.
- package/README.md +619 -35
- 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 +12 -10
- package/dist/auth/index.js +5 -3
- package/dist/auth/oauth/http.d.ts +10 -3
- package/dist/auth/oauth/index.cjs +189 -29
- package/dist/auth/oauth/index.d.ts +6 -4
- package/dist/auth/oauth/index.js +169 -9
- package/dist/auth/oauth/magic-link.dto.d.ts +6 -0
- package/dist/auth/oauth/memory-magic-link.store.d.ts +19 -0
- package/dist/auth/oauth/oauth-auth.service.d.ts +46 -5
- package/dist/auth/oauth/oauth.controller.d.ts +5 -1
- package/dist/auth/oauth/oauth.options.d.ts +34 -1
- package/dist/auth/oauth/oauth.ports.d.ts +38 -0
- package/dist/bootstrap/index.cjs +9 -6
- package/dist/bootstrap/index.js +8 -5
- package/dist/{chunk-TJHRABML.cjs → chunk-3AUOOEQO.cjs} +12 -7
- package/dist/{chunk-NVCI3CQI.cjs → chunk-4HHZFOVC.cjs} +10 -5
- package/dist/{chunk-EYURGACO.js → chunk-4PFAKLT3.js} +1 -1
- package/dist/chunk-52IOOHNX.cjs +205 -0
- package/dist/chunk-6RAPVLJM.js +212 -0
- package/dist/{chunk-7I2Y7V52.js → chunk-A2DGK4ZL.js} +26 -3
- package/dist/chunk-APUFKA4K.cjs +212 -0
- package/dist/chunk-AXMW5JF7.cjs +83 -0
- package/dist/{chunk-KDAA6GFF.js → chunk-DYHSOULW.js} +12 -7
- package/dist/chunk-ETRUVZTJ.js +43 -0
- package/dist/{chunk-54ZXIB5T.cjs → chunk-FNUZGYUF.cjs} +4 -4
- package/dist/{chunk-FDNGAYTZ.cjs → chunk-HDFPSA2V.cjs} +6 -6
- package/dist/{chunk-V2M75FN3.cjs → chunk-HVHYZXBB.cjs} +2 -2
- package/dist/chunk-IFNYRZP2.js +205 -0
- package/dist/{chunk-A3B2EY4V.js → chunk-IKXSVEJ7.js} +7 -2
- package/dist/{chunk-YFYHLYHN.js → chunk-M3GQDRWR.js} +7 -1
- package/dist/{chunk-J7TURDAL.cjs → chunk-MSTXS3MU.cjs} +28 -5
- package/dist/chunk-PNK5WMPP.cjs +30 -0
- package/dist/chunk-Q5Y33L7B.cjs +19 -0
- package/dist/{chunk-ZA56XBCK.cjs → chunk-SDWHKPXI.cjs} +23 -0
- package/dist/chunk-TCAMLNUZ.js +27 -0
- package/dist/{chunk-AOCF5QCZ.js → chunk-UNEVXCFW.js} +2 -2
- package/dist/chunk-VVMRZEIW.js +30 -0
- package/dist/chunk-W2T2VFLC.cjs +57 -0
- package/dist/chunk-X4PQJZ4G.js +83 -0
- package/dist/chunk-Y72D5L6I.cjs +27 -0
- package/dist/{chunk-ORWJ7LES.js → chunk-ZFIDAX7K.js} +1 -1
- package/dist/chunk-ZJMLEP5H.js +57 -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/app.exception.d.ts +9 -1
- package/dist/errors/common.exceptions.d.ts +6 -5
- package/dist/errors/global-exception.filter.d.ts +9 -0
- package/dist/errors/index.cjs +8 -5
- package/dist/errors/index.js +9 -6
- package/dist/i18n/i18n.interceptor.d.ts +16 -0
- package/dist/i18n/i18n.module.d.ts +49 -3
- package/dist/i18n/index.cjs +26 -2
- package/dist/i18n/index.d.ts +8 -0
- package/dist/i18n/index.js +25 -1
- package/dist/i18n/locale.d.ts +53 -0
- package/dist/i18n/message.d.ts +36 -0
- package/dist/i18n/nestjs-i18n.translator.d.ts +9 -0
- package/dist/i18n/runtime.d.ts +55 -0
- package/dist/i18n/translator.port.d.ts +29 -0
- 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 +207 -0
- package/dist/idempotency/index.d.ts +7 -0
- package/dist/idempotency/index.js +207 -0
- package/dist/idempotency/memory.store.d.ts +24 -0
- package/dist/index.cjs +48 -15
- package/dist/index.js +51 -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 +578 -0
- package/dist/invoicing/index.d.ts +11 -0
- package/dist/invoicing/index.js +578 -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/payments/adapters/clip.terminal.d.ts +101 -0
- package/dist/payments/adapters/mercadopago.terminal.d.ts +74 -0
- package/dist/payments/index.cjs +796 -0
- package/dist/payments/index.d.ts +12 -0
- package/dist/payments/index.js +796 -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/stripe/index.cjs +4 -3
- package/dist/stripe/index.js +3 -2
- 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 +32 -0
- package/package.json +25 -3
- package/dist/chunk-3CLYZC3T.cjs +0 -104
- package/dist/chunk-EBO6UKHL.js +0 -20
- package/dist/chunk-IYUUYCP5.js +0 -36
- package/dist/chunk-JOVBJDJ2.js +0 -104
- package/dist/chunk-M3EL5O6T.cjs +0 -36
- package/dist/chunk-R7BVS6CI.cjs +0 -13
- /package/dist/{chunk-MR2IFCZE.cjs → chunk-H2EHN366.cjs} +0 -0
- /package/dist/{chunk-NAK4WDKS.js → chunk-ODPSIFOB.js} +0 -0
|
@@ -0,0 +1,578 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
2
|
+
|
|
3
|
+
var _chunkHDFPSA2Vcjs = require('../chunk-HDFPSA2V.cjs');
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
var _chunkQ5Y33L7Bcjs = require('../chunk-Q5Y33L7B.cjs');
|
|
7
|
+
require('../chunk-PNK5WMPP.cjs');
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
var _chunk2REOCMUDcjs = require('../chunk-2REOCMUD.cjs');
|
|
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
|
+
var _common = require('@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 (0, _chunkHDFPSA2Vcjs.ValidationAppException)(`${field} must be an integer number of cents, got ${cents}`, {
|
|
28
|
+
[field]: cents
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
if (cents < 0) {
|
|
32
|
+
throw new (0, _chunkHDFPSA2Vcjs.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 (0, _chunkHDFPSA2Vcjs.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 (0, _chunkHDFPSA2Vcjs.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 (0, _chunkHDFPSA2Vcjs.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 (0, _chunkHDFPSA2Vcjs.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 (!_optionalChain([item, 'access', _ => _.description, 'optionalAccess', _2 => _2.trim, 'call', _3 => _3()])) {
|
|
92
|
+
throw new (0, _chunkHDFPSA2Vcjs.ValidationAppException)("each item needs a description", { item });
|
|
93
|
+
}
|
|
94
|
+
if (!_optionalChain([item, 'access', _4 => _4.productKey, 'optionalAccess', _5 => _5.trim, 'call', _6 => _6()])) {
|
|
95
|
+
throw new (0, _chunkHDFPSA2Vcjs.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 = _nullishCoalesce(item.quantity, () => ( 1));
|
|
102
|
+
const amountCents = lineAmountCents(price, quantity);
|
|
103
|
+
const taxes = (_nullishCoalesce(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 (0, _chunkHDFPSA2Vcjs.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
|
+
|
|
127
|
+
var InvoicingProviderException = class extends _chunkQ5Y33L7Bcjs.AppException {
|
|
128
|
+
constructor(provider, status, body, message) {
|
|
129
|
+
super(
|
|
130
|
+
"INVOICING_PROVIDER_ERROR",
|
|
131
|
+
_nullishCoalesce(message, () => ( `${provider} rejected the request (HTTP ${status})`)),
|
|
132
|
+
_common.HttpStatus.BAD_GATEWAY,
|
|
133
|
+
{ provider, status, body }
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
var UnsupportedByProviderException = class extends _chunkQ5Y33L7Bcjs.AppException {
|
|
138
|
+
constructor(provider, message) {
|
|
139
|
+
super("INVOICING_UNSUPPORTED", message, _common.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 (e) {
|
|
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 = (_nullishCoalesce(options.baseUrl, () => ( DEFAULT_BASE_URL))).replace(/\/$/, "");
|
|
202
|
+
this.fetchImpl = _nullishCoalesce(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: _nullishCoalesce(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: _nullishCoalesce(tax.withholding, () => ( false))
|
|
243
|
+
}))
|
|
244
|
+
}
|
|
245
|
+
})),
|
|
246
|
+
payment_form: draft.paymentForm,
|
|
247
|
+
payment_method: _nullishCoalesce(draft.paymentMethod, () => ( "PUE")),
|
|
248
|
+
use: _nullishCoalesce(_nullishCoalesce(draft.use, () => ( (typeof draft.customer === "string" ? void 0 : draft.customer.use))), () => ( "G03")),
|
|
249
|
+
type: _nullishCoalesce(draft.type, () => ( "I")),
|
|
250
|
+
currency: _nullishCoalesce(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 (!_optionalChain([invoice, 'optionalAccess', _7 => _7.id])) {
|
|
309
|
+
throw new InvoicingProviderException(PROVIDER, 200, invoice, "Facturapi returned an invoice with no id");
|
|
310
|
+
}
|
|
311
|
+
const issuedAt = _nullishCoalesce(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: _nullishCoalesce(invoice.currency, () => ( "MXN")),
|
|
322
|
+
customerTaxId: _optionalChain([invoice, 'access', _8 => _8.customer, 'optionalAccess', _9 => _9.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 = _optionalChain([cfdi, 'access', _10 => _10.Status, 'optionalAccess', _11 => _11.toLowerCase, 'call', _12 => _12()]);
|
|
334
|
+
if (status === "canceled" || status === "cancelled") return "cancelled";
|
|
335
|
+
if (status === "active") return "stamped";
|
|
336
|
+
return _optionalChain([cfdi, 'access', _13 => _13.Complement, 'optionalAccess', _14 => _14.TaxStamp, 'optionalAccess', _15 => _15.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 = (_nullishCoalesce(options.baseUrl, () => ( DEFAULT_BASE_URL2))).replace(/\/$/, "");
|
|
349
|
+
this.fetchImpl = _nullishCoalesce(options.fetchImpl, () => ( globalThis.fetch));
|
|
350
|
+
this.token = Buffer.from(`${options.user}:${options.password}`).toString("base64");
|
|
351
|
+
this.documentType = _nullishCoalesce(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: _nullishCoalesce(draft.type, () => ( "I")),
|
|
374
|
+
PaymentForm: draft.paymentForm,
|
|
375
|
+
PaymentMethod: _nullishCoalesce(draft.paymentMethod, () => ( "PUE")),
|
|
376
|
+
ExpeditionPlace: this.options.expeditionPlace,
|
|
377
|
+
Currency: _nullishCoalesce(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: _nullishCoalesce(_nullishCoalesce(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: _nullishCoalesce(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: _nullishCoalesce(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(_nullishCoalesce(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 (!_optionalChain([file, 'optionalAccess', _16 => _16.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 (!_optionalChain([cfdi, 'optionalAccess', _17 => _17.Id])) {
|
|
482
|
+
throw new InvoicingProviderException(PROVIDER2, 200, cfdi, "Facturama returned a CFDI with no Id");
|
|
483
|
+
}
|
|
484
|
+
const stampedAt = _nullishCoalesce(_optionalChain([cfdi, 'access', _18 => _18.Complement, 'optionalAccess', _19 => _19.TaxStamp, 'optionalAccess', _20 => _20.Date]), () => ( cfdi.Date));
|
|
485
|
+
return {
|
|
486
|
+
id: cfdi.Id,
|
|
487
|
+
provider: PROVIDER2,
|
|
488
|
+
status: toStatus2(cfdi),
|
|
489
|
+
uuid: _optionalChain([cfdi, 'access', _21 => _21.Complement, 'optionalAccess', _22 => _22.TaxStamp, 'optionalAccess', _23 => _23.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: _nullishCoalesce(cfdi.Currency, () => ( "MXN")),
|
|
495
|
+
customerTaxId: _optionalChain([cfdi, 'access', _24 => _24.Receiver, 'optionalAccess', _25 => _25.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: _nullishCoalesce(options.provider, () => ( env("INVOICING_PROVIDER"))),
|
|
507
|
+
facturapi: _nullishCoalesce(options.facturapi, () => ( (env("FACTURAPI_API_KEY") ? { apiKey: env("FACTURAPI_API_KEY") } : void 0))),
|
|
508
|
+
facturama: _nullishCoalesce(options.facturama, () => ( (env("FACTURAMA_USER") ? {
|
|
509
|
+
user: env("FACTURAMA_USER"),
|
|
510
|
+
password: _nullishCoalesce(env("FACTURAMA_PASSWORD"), () => ( "")),
|
|
511
|
+
expeditionPlace: _nullishCoalesce(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: _nullishCoalesce(config.inject, () => ( [])) },
|
|
545
|
+
{
|
|
546
|
+
provide: INVOICING,
|
|
547
|
+
useFactory: (options) => createInvoicingAdapter(options),
|
|
548
|
+
inject: [INVOICING_OPTIONS]
|
|
549
|
+
}
|
|
550
|
+
];
|
|
551
|
+
return {
|
|
552
|
+
module: InvoicingModule,
|
|
553
|
+
imports: _nullishCoalesce(config.imports, () => ( [])),
|
|
554
|
+
providers,
|
|
555
|
+
exports: [INVOICING, INVOICING_OPTIONS]
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
};
|
|
559
|
+
InvoicingModule = exports.InvoicingModule = _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
|
|
560
|
+
_common.Global.call(void 0, ),
|
|
561
|
+
_common.Module.call(void 0, {})
|
|
562
|
+
], InvoicingModule);
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
exports.FacturamaInvoicing = FacturamaInvoicing; exports.FacturapiInvoicing = FacturapiInvoicing; exports.INVOICING = INVOICING; exports.INVOICING_OPTIONS = INVOICING_OPTIONS; exports.InvoicingModule = InvoicingModule; exports.InvoicingProviderException = InvoicingProviderException; exports.UnsupportedByProviderException = UnsupportedByProviderException; exports.centsToDecimal = centsToDecimal; exports.computeLine = computeLine; exports.computeLines = computeLines; exports.createInvoicingAdapter = createInvoicingAdapter; exports.decimalToCents = decimalToCents; exports.resolveInvoicingOptions = resolveInvoicingOptions; exports.sumCents = sumCents;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { INVOICING } from './invoicing.port.js';
|
|
2
|
+
export type { InvoicingPort, Invoice, InvoiceDraft, InvoiceCustomer, InvoiceItem, InvoiceTax, InvoiceStatus, CfdiType, PaymentMethod, CancelMotive, } from './invoicing.port.js';
|
|
3
|
+
export { INVOICING_OPTIONS } from './invoicing.options.js';
|
|
4
|
+
export type { InvoicingOptions, InvoicingProvider, FacturapiOptions, FacturamaOptions, } from './invoicing.options.js';
|
|
5
|
+
export { InvoicingModule, createInvoicingAdapter, resolveInvoicingOptions } from './invoicing.module.js';
|
|
6
|
+
export { FacturapiInvoicing } from './adapters/facturapi.invoicing.js';
|
|
7
|
+
export { FacturamaInvoicing } from './adapters/facturama.invoicing.js';
|
|
8
|
+
export { InvoicingProviderException, UnsupportedByProviderException } from './provider-http.js';
|
|
9
|
+
export { computeLine, computeLines, sumCents } from './lines.js';
|
|
10
|
+
export type { ComputedLine } from './lines.js';
|
|
11
|
+
export { centsToDecimal, decimalToCents } from './amounts.js';
|