@devly-cl/sii-client 0.7.1 → 0.7.11
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 +84 -1
- package/dist/application/document-status.d.ts +5 -5
- package/dist/application/document-status.js +14 -9
- package/dist/application/dte-import-mapper.d.ts +8 -0
- package/dist/application/dte-import-mapper.js +25 -0
- package/dist/application/dte-import-model.d.ts +28 -0
- package/dist/application/dte-import-model.js +2 -0
- package/dist/application/dte-import.d.ts +37 -0
- package/dist/application/dte-import.js +352 -0
- package/dist/application/invoice-queries.d.ts +12 -6
- package/dist/application/invoice-queries.js +9 -5
- package/dist/application/issuance.d.ts +2 -2
- package/dist/application/issuance.js +26 -10
- package/dist/contracts.d.ts +32 -0
- package/dist/contracts.js +17 -0
- package/dist/domain/civil-date.d.ts +2 -0
- package/dist/domain/civil-date.js +10 -0
- package/dist/domain/document-status.d.ts +0 -4
- package/dist/domain/document-status.js +18 -11
- package/dist/domain/document.js +49 -9
- package/dist/domain/dte-arithmetic.d.ts +35 -0
- package/dist/domain/dte-arithmetic.js +78 -0
- package/dist/domain/dte-components.d.ts +9 -0
- package/dist/domain/dte-components.js +37 -0
- package/dist/domain/dte-detail.d.ts +111 -0
- package/dist/domain/dte-detail.js +2 -0
- package/dist/domain/dte-identity.d.ts +19 -0
- package/dist/domain/dte-identity.js +52 -0
- package/dist/domain/dte-money.d.ts +41 -0
- package/dist/domain/dte-money.js +81 -0
- package/dist/domain/dte-reconciliation-model.d.ts +87 -0
- package/dist/domain/dte-reconciliation-model.js +2 -0
- package/dist/domain/dte-reconciliation.d.ts +15 -0
- package/dist/domain/dte-reconciliation.js +390 -0
- package/dist/domain/dte-validation.d.ts +7 -0
- package/dist/domain/dte-validation.js +84 -0
- package/dist/domain/invoice-xml.d.ts +17 -57
- package/dist/domain/invoice-xml.js +0 -10
- package/dist/domain/invoicing.d.ts +30 -4
- package/dist/domain/invoicing.js +75 -21
- package/dist/domain/issued-invoice.d.ts +0 -6
- package/dist/domain/rcv-document.d.ts +0 -4
- package/dist/domain/received-invoice.d.ts +1 -4
- package/dist/index.d.ts +19 -9
- package/dist/index.js +20 -4
- package/dist/infrastructure/document-status-gateway.d.ts +6 -4
- package/dist/infrastructure/document-status-gateway.js +34 -13
- package/dist/infrastructure/document-status-parser.js +38 -12
- package/dist/infrastructure/dte-xml-mapper.d.ts +16 -0
- package/dist/infrastructure/dte-xml-mapper.js +381 -0
- package/dist/infrastructure/dte-xml.d.ts +40 -4
- package/dist/infrastructure/dte-xml.js +117 -196
- package/dist/infrastructure/facturador-gateway.d.ts +10 -7
- package/dist/infrastructure/facturador-gateway.js +256 -56
- package/dist/infrastructure/facturador.d.ts +1 -1
- package/dist/infrastructure/facturador.js +18 -10
- package/dist/infrastructure/invoice-pdf.js +10 -3
- package/dist/infrastructure/rcv-gateway.d.ts +7 -4
- package/dist/infrastructure/rcv-gateway.js +53 -12
- package/dist/infrastructure/rcv-normalization.d.ts +8 -1
- package/dist/infrastructure/rcv-normalization.js +54 -12
- package/dist/infrastructure/read-options.d.ts +3 -0
- package/dist/infrastructure/read-options.js +25 -0
- package/dist/infrastructure/sii-client.d.ts +98 -13
- package/dist/infrastructure/sii-client.js +182 -31
- package/dist/infrastructure/sii-http-session.d.ts +2 -2
- package/dist/infrastructure/sii-http-session.js +134 -37
- package/dist/sii-error.d.ts +5 -0
- package/dist/sii-error.js +39 -13
- package/package.json +2 -2
package/dist/domain/document.js
CHANGED
|
@@ -4,11 +4,19 @@ exports.DocumentContentMismatchError = void 0;
|
|
|
4
4
|
exports.assertApprovedDocument = assertApprovedDocument;
|
|
5
5
|
const invoicing_1 = require("./invoicing");
|
|
6
6
|
class DocumentContentMismatchError extends Error {
|
|
7
|
-
constructor() {
|
|
7
|
+
constructor() {
|
|
8
|
+
super('SII_DOCUMENT_CONTENT_MISMATCH');
|
|
9
|
+
}
|
|
8
10
|
}
|
|
9
11
|
exports.DocumentContentMismatchError = DocumentContentMismatchError;
|
|
10
12
|
function assertApprovedDocument(document, approved) {
|
|
11
13
|
const d = document.detail;
|
|
14
|
+
if (d.references.some(reference => Object.hasOwn(reference, 'issuerRut')))
|
|
15
|
+
throw new DocumentContentMismatchError();
|
|
16
|
+
if (d.fiscalComponents || d.commissions?.length || d.lines.some(line => line.retention) || d.fiscalConditions?.noDebitReduction != null)
|
|
17
|
+
throw new DocumentContentMismatchError();
|
|
18
|
+
if (d.nonBillableAmount || d.previousBalance || (d.periodAmount != null && d.periodAmount !== 0 && d.periodAmount !== d.totalAmount) || (d.payableAmount != null && d.payableAmount !== 0 && d.payableAmount !== d.totalAmount))
|
|
19
|
+
throw new DocumentContentMismatchError();
|
|
12
20
|
const decimal = (value) => value == null ? null : value.replace(/^0+(?=\d)/, '').replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '');
|
|
13
21
|
if (d.issuerRut !== approved.issuerRut || d.receiverRut !== approved.receiverRut || d.documentType !== approved.documentType || d.issuedDate !== approved.issuedDate || d.netAmount !== approved.netAmount || d.vatAmount !== approved.vatAmount || d.totalAmount !== approved.totalAmount || Number(d.vatRate) !== 19 || d.exemptAmount || d.fiscalHeader?.noDebitReduction != null || d.fiscalHeader?.unapprovedFiscalFields.length || d.issuanceOptions?.unapprovedFields.length)
|
|
14
22
|
throw new DocumentContentMismatchError();
|
|
@@ -27,7 +35,10 @@ function assertApprovedDocument(document, approved) {
|
|
|
27
35
|
return line.lineNumber !== index + 1 || (0, invoicing_1.hashContent)(line.codes) !== (0, invoicing_1.hashContent)(item.productCode ? [item.productCode] : []) || line.name !== item.name || (line.description ?? '') !== (item.description ?? '') || decimal(line.quantity) !== decimal(item.quantity) || decimal(line.unitPrice) !== decimal(item.unitNetPriceClp) || (line.unit ?? '') !== (item.unit ?? '') || line.amount !== expected.amount || decimal(line.discountPercent ?? '0') !== decimal(item.discountPercent ?? '0') || (line.discountAmount ?? 0) !== expected.discountAmount || line.surchargeAmount || line.surchargePercent && Number(line.surchargePercent) || line.exemptIndicator;
|
|
28
36
|
}))
|
|
29
37
|
throw new DocumentContentMismatchError();
|
|
30
|
-
const taxOrder = (taxes) => taxes.map(tax => ({
|
|
38
|
+
const taxOrder = (taxes) => taxes.map(tax => ({
|
|
39
|
+
...tax,
|
|
40
|
+
rate: decimal(tax.rate)
|
|
41
|
+
})).sort((a, b) => a.type - b.type);
|
|
31
42
|
if ((0, invoicing_1.hashContent)(taxOrder(d.taxes)) !== (0, invoicing_1.hashContent)(taxOrder(breakdown.taxes)))
|
|
32
43
|
throw new DocumentContentMismatchError();
|
|
33
44
|
const adjustment = d.adjustments[0];
|
|
@@ -42,12 +53,25 @@ function assertApprovedDocument(document, approved) {
|
|
|
42
53
|
else if (d.adjustments.length)
|
|
43
54
|
throw new DocumentContentMismatchError();
|
|
44
55
|
const references = i.references ?? [];
|
|
45
|
-
if (d.references.length !== references.length || d.references.some((ref, index) => {
|
|
56
|
+
if (d.references.length !== references.length || d.references.some((ref, index) => {
|
|
57
|
+
const expected = references[index];
|
|
58
|
+
return ref.lineNumber !== index + 1 || ref.documentType !== expected.documentType || ref.folio !== expected.folio || ref.date !== expected.date || (ref.reason ?? '') !== (expected.reason ?? '') || ref.code !== null;
|
|
59
|
+
}))
|
|
46
60
|
throw new DocumentContentMismatchError();
|
|
47
61
|
const options = d.issuanceOptions;
|
|
48
|
-
const expectedPayments = (i.payments ?? []).map(payment => ({
|
|
49
|
-
|
|
50
|
-
|
|
62
|
+
const expectedPayments = (i.payments ?? []).map(payment => ({
|
|
63
|
+
date: payment.date,
|
|
64
|
+
amount: payment.amountClp,
|
|
65
|
+
description: payment.description ?? null
|
|
66
|
+
}));
|
|
67
|
+
const expectedTaxCodes = items.flatMap((item, index) => item.additionalTaxCode === undefined ? [] : [{
|
|
68
|
+
lineNumber: index + 1,
|
|
69
|
+
codes: [item.additionalTaxCode]
|
|
70
|
+
}]);
|
|
71
|
+
const expectedGlobal = references.flatMap((ref, index) => ref.global ? [{
|
|
72
|
+
lineNumber: index + 1,
|
|
73
|
+
indicator: 1
|
|
74
|
+
}] : []);
|
|
51
75
|
if (d.hasTransport !== !!i.transport || (0, invoicing_1.hashContent)(options?.transport ?? null) !== (0, invoicing_1.hashContent)(i.transport ?? null) || (options?.requesterRut ?? '') !== (i.requesterRut ?? '') || (0, invoicing_1.hashContent)(options?.payments ?? []) !== (0, invoicing_1.hashContent)(expectedPayments) || (0, invoicing_1.hashContent)(options?.lineTaxCodes ?? []) !== (0, invoicing_1.hashContent)(expectedTaxCodes) || (0, invoicing_1.hashContent)(options?.referenceGlobalIndicators ?? []) !== (0, invoicing_1.hashContent)(expectedGlobal))
|
|
52
76
|
throw new DocumentContentMismatchError();
|
|
53
77
|
const email = approved.issuerContact?.email ?? i.issuer.email ?? '', phone = approved.issuerContact?.phone ?? i.issuer.phone ?? '';
|
|
@@ -61,10 +85,26 @@ function assertApprovedDocument(document, approved) {
|
|
|
61
85
|
const original = approved.originalInvoice;
|
|
62
86
|
const header = d.fiscalHeader;
|
|
63
87
|
const originalHeader = original?.fiscalHeader;
|
|
64
|
-
const lines = (values) => values.map(line => ({
|
|
65
|
-
|
|
88
|
+
const lines = (values) => values.map(line => ({
|
|
89
|
+
...line,
|
|
90
|
+
quantity: decimal(line.quantity),
|
|
91
|
+
unitPrice: decimal(line.unitPrice),
|
|
92
|
+
discountPercent: decimal(line.discountPercent),
|
|
93
|
+
surchargePercent: decimal(line.surchargePercent)
|
|
94
|
+
}));
|
|
95
|
+
const fiscalOptions = (detail) => ({
|
|
96
|
+
issuerEmail: detail.issuanceOptions?.issuerEmail ?? null,
|
|
97
|
+
issuerPhones: detail.issuanceOptions?.issuerPhones ?? [],
|
|
98
|
+
requesterRut: detail.issuanceOptions?.requesterRut ?? null,
|
|
99
|
+
transport: detail.issuanceOptions?.transport ?? null,
|
|
100
|
+
payments: detail.issuanceOptions?.payments ?? [],
|
|
101
|
+
lineTaxCodes: detail.issuanceOptions?.lineTaxCodes ?? []
|
|
102
|
+
});
|
|
66
103
|
const taxes = (detail) => detail.taxes.map(tax => ({ ...tax, rate: decimal(tax.rate) }));
|
|
67
|
-
const adjustments = (detail) => detail.adjustments.map(adjustment => ({
|
|
104
|
+
const adjustments = (detail) => detail.adjustments.map(adjustment => ({
|
|
105
|
+
...adjustment,
|
|
106
|
+
value: decimal(adjustment.value)
|
|
107
|
+
}));
|
|
68
108
|
if (!original || !header || !originalHeader || original.issuanceOptions?.unapprovedFields.length || (0, invoicing_1.hashContent)(lines(d.lines)) !== (0, invoicing_1.hashContent)(lines(original.lines)) || (0, invoicing_1.hashContent)(taxes(d)) !== (0, invoicing_1.hashContent)(taxes(original)) || (0, invoicing_1.hashContent)(adjustments(d)) !== (0, invoicing_1.hashContent)(adjustments(original)) || d.hasTransport !== original.hasTransport || (0, invoicing_1.hashContent)(fiscalOptions(d)) !== (0, invoicing_1.hashContent)(fiscalOptions(original)) || d.issuanceOptions?.referenceGlobalIndicators.length || (0, invoicing_1.hashContent)(header.issuer) !== (0, invoicing_1.hashContent)(originalHeader.issuer) || (0, invoicing_1.hashContent)(header.receiver) !== (0, invoicing_1.hashContent)(originalHeader.receiver) || ['paymentForm', 'saleType', 'purchaseType'].some(field => header[field] !== null && header[field] !== originalHeader[field]))
|
|
69
109
|
throw new DocumentContentMismatchError();
|
|
70
110
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** Exact rational arithmetic and safe CLP amounts shared by read interpretation and import preparation. */
|
|
2
|
+
/** n is the numerator; d is the positive denominator. Both remain exact BigInts. */
|
|
3
|
+
export interface Rational {
|
|
4
|
+
readonly n: bigint;
|
|
5
|
+
readonly d: bigint;
|
|
6
|
+
}
|
|
7
|
+
/** A supported interpretation could not explain the source; callers turn this into a diagnostic. */
|
|
8
|
+
export declare class DteInterpretationError extends Error {
|
|
9
|
+
readonly code: string;
|
|
10
|
+
readonly amounts?: {
|
|
11
|
+
declaredAmount: number;
|
|
12
|
+
derivedAmount: number;
|
|
13
|
+
} | undefined;
|
|
14
|
+
constructor(code: string, message: string, amounts?: {
|
|
15
|
+
declaredAmount: number;
|
|
16
|
+
derivedAmount: number;
|
|
17
|
+
} | undefined);
|
|
18
|
+
}
|
|
19
|
+
export declare function fail(code: string, message: string, amounts?: {
|
|
20
|
+
declaredAmount: number;
|
|
21
|
+
derivedAmount: number;
|
|
22
|
+
}): never;
|
|
23
|
+
export declare function fraction(n: bigint, d?: bigint): Rational;
|
|
24
|
+
export declare const add: (a: Rational, b: Rational) => Rational;
|
|
25
|
+
export declare const multiply: (a: Rational, b: Rational) => Rational;
|
|
26
|
+
/** Nearest integer; ties go away from zero. Never applies a monetary tolerance. */
|
|
27
|
+
export declare const round: (v: Rational) => bigint;
|
|
28
|
+
/** Parses a nonnegative XML decimal without binary floating-point conversion. */
|
|
29
|
+
export declare function decimal(value: string): Rational;
|
|
30
|
+
/** Requires an integer CLP amount that Number can represent exactly; no coercion or rounding. */
|
|
31
|
+
export declare function money(value: number, signed?: boolean): number;
|
|
32
|
+
export declare function moneySum(values: readonly number[], signed?: boolean): number;
|
|
33
|
+
export declare function decimalText(value: Rational, places?: number): string;
|
|
34
|
+
/** Largest remainder allocation, with stable original order as the tie breaker. */
|
|
35
|
+
export declare function allocate(weights: readonly number[], target: number): number[];
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.round = exports.multiply = exports.add = exports.DteInterpretationError = void 0;
|
|
4
|
+
exports.fail = fail;
|
|
5
|
+
exports.fraction = fraction;
|
|
6
|
+
exports.decimal = decimal;
|
|
7
|
+
exports.money = money;
|
|
8
|
+
exports.moneySum = moneySum;
|
|
9
|
+
exports.decimalText = decimalText;
|
|
10
|
+
exports.allocate = allocate;
|
|
11
|
+
/** A supported interpretation could not explain the source; callers turn this into a diagnostic. */
|
|
12
|
+
class DteInterpretationError extends Error {
|
|
13
|
+
code;
|
|
14
|
+
amounts;
|
|
15
|
+
constructor(code, message, amounts) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.code = code;
|
|
18
|
+
this.amounts = amounts;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
exports.DteInterpretationError = DteInterpretationError;
|
|
22
|
+
function fail(code, message, amounts) {
|
|
23
|
+
throw new DteInterpretationError(code, message, amounts);
|
|
24
|
+
}
|
|
25
|
+
function gcd(a, b) {
|
|
26
|
+
while (b)
|
|
27
|
+
[a, b] = [b, a % b];
|
|
28
|
+
return a < 0n ? -a : a;
|
|
29
|
+
}
|
|
30
|
+
function fraction(n, d = 1n) {
|
|
31
|
+
const divisor = gcd(n, d);
|
|
32
|
+
return { n: n / divisor, d: d / divisor };
|
|
33
|
+
}
|
|
34
|
+
const add = (a, b) => fraction(a.n * b.d + b.n * a.d, a.d * b.d);
|
|
35
|
+
exports.add = add;
|
|
36
|
+
const multiply = (a, b) => fraction(a.n * b.n, a.d * b.d);
|
|
37
|
+
exports.multiply = multiply;
|
|
38
|
+
/** Nearest integer; ties go away from zero. Never applies a monetary tolerance. */
|
|
39
|
+
const round = (v) => v.n < 0n ? -(0, exports.round)({ n: -v.n, d: v.d }) : (v.n * 2n + v.d) / (v.d * 2n);
|
|
40
|
+
exports.round = round;
|
|
41
|
+
/** Parses a nonnegative XML decimal without binary floating-point conversion. */
|
|
42
|
+
function decimal(value) {
|
|
43
|
+
if (typeof value !== 'string' || value.length > 40 || !/^\d+(?:\.\d+)?$/.test(value))
|
|
44
|
+
fail('INVALID_DECIMAL', 'Valor decimal XML inválido o fuera de precisión.');
|
|
45
|
+
const [whole, part = ''] = value.split('.');
|
|
46
|
+
return fraction(BigInt(whole + part), 10n ** BigInt(part.length));
|
|
47
|
+
}
|
|
48
|
+
/** Requires an integer CLP amount that Number can represent exactly; no coercion or rounding. */
|
|
49
|
+
function money(value, signed = false) {
|
|
50
|
+
if (!Number.isSafeInteger(value) || (!signed && value < 0))
|
|
51
|
+
fail('INVALID_AMOUNT', 'Importe XML fuera del rango entero seguro.');
|
|
52
|
+
return value;
|
|
53
|
+
}
|
|
54
|
+
function moneySum(values, signed = false) {
|
|
55
|
+
return money(Number(values.reduce((sum, value) => sum + BigInt(money(value, true)), 0n)), signed);
|
|
56
|
+
}
|
|
57
|
+
function decimalText(value, places = 6) {
|
|
58
|
+
const scale = 10n ** BigInt(places), scaled = (0, exports.round)((0, exports.multiply)(value, fraction(scale)));
|
|
59
|
+
return `${scaled / scale}.${String(scaled % scale).padStart(places, '0')}`.replace(/\.?0+$/, '');
|
|
60
|
+
}
|
|
61
|
+
/** Largest remainder allocation, with stable original order as the tie breaker. */
|
|
62
|
+
function allocate(weights, target) {
|
|
63
|
+
const total = weights.reduce((s, w) => s + BigInt(w), 0n);
|
|
64
|
+
if (!total) {
|
|
65
|
+
if (target)
|
|
66
|
+
fail('GROSS_ALLOCATION_MISMATCH', 'No hay base para distribuir el neto fiscal.');
|
|
67
|
+
return weights.map(() => 0);
|
|
68
|
+
}
|
|
69
|
+
const parts = weights.map((w, index) => {
|
|
70
|
+
const product = BigInt(w) * BigInt(target);
|
|
71
|
+
return { index, amount: Number(product / total), remainder: product % total };
|
|
72
|
+
});
|
|
73
|
+
const remaining = target - parts.reduce((s, p) => s + p.amount, 0);
|
|
74
|
+
const ranked = [...parts].sort((a, b) => a.remainder === b.remainder ? a.index - b.index : a.remainder > b.remainder ? -1 : 1);
|
|
75
|
+
for (let i = 0; i < remaining; i++)
|
|
76
|
+
ranked[i].amount++;
|
|
77
|
+
return parts.map(p => p.amount);
|
|
78
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { DteFiscalDetail, DteProjectedTax, ExactDteFiscalDetail } from './invoice-xml';
|
|
2
|
+
import type { ExactDte } from './dte-money';
|
|
3
|
+
type TaxContext = Pick<DteFiscalDetail, 'documentType' | 'references'>;
|
|
4
|
+
/** DTE 2.5 catalog, February 2026. Purchase-invoice retentions require their fiscal reference context. */
|
|
5
|
+
export declare function projectDteTax(detail: TaxContext, tax: DteFiscalDetail['taxes'][number]): DteProjectedTax;
|
|
6
|
+
export declare function projectDteTax(detail: TaxContext, tax: ExactDteFiscalDetail['taxes'][number]): ExactDte<DteProjectedTax>;
|
|
7
|
+
/** Informational bases and IVA breakdowns are not added again to the fiscal total. */
|
|
8
|
+
export declare function dteHeaderTotal(detail: DteFiscalDetail | ExactDteFiscalDetail, taxes: readonly (DteProjectedTax | ExactDte<DteProjectedTax>)[]): bigint | null;
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.projectDteTax = projectDteTax;
|
|
4
|
+
exports.dteHeaderTotal = dteHeaderTotal;
|
|
5
|
+
function purchaseReference(detail) {
|
|
6
|
+
const references = detail.references.filter(r => /^\d+$/.test(r.documentType) && Number(r.documentType) > 0 && Number(r.documentType) < 200);
|
|
7
|
+
return detail.documentType === 61 && references.length > 0 && references.every(r => ['45', '46'].includes(r.documentType));
|
|
8
|
+
}
|
|
9
|
+
function projectDteTax(detail, tax) {
|
|
10
|
+
const retention = [15, 30, 301, 31, 32, 321, 33, 331, 34, 341, 36, 361, 37, 371, 38, 39, 41, 47, 48, 481, 49].includes(tax.type);
|
|
11
|
+
const kind = retention || tax.type === 46 ? 'RETENTION' : [14, 50].includes(tax.type) ? 'MARGIN' : [17, 18, 19].includes(tax.type) ? 'ANTICIPATED' : [28, 35, 51, 52].includes(tax.type) ? 'SPECIFIC' : [23, 24, 25, 26, 27, 271, 44, 45].includes(tax.type) ? 'ADDITIONAL' : 'UNCLASSIFIED';
|
|
12
|
+
const zeroRetentionConflict = tax.type === 49 && (BigInt(tax.amount) !== 0n || tax.rate != null && Number(tax.rate) !== 0);
|
|
13
|
+
const known = !zeroRetentionConflict && detail.documentType !== 34 && kind !== 'UNCLASSIFIED' && (!retention || purchaseReference(detail));
|
|
14
|
+
const effect = !known ? 'UNKNOWN' : kind === 'RETENTION' ? 'SUBTRACT' : 'ADD';
|
|
15
|
+
const contribution = effect === 'UNKNOWN' ? null : BigInt(tax.amount) * (effect === 'SUBTRACT' ? -1n : 1n);
|
|
16
|
+
return {
|
|
17
|
+
...tax,
|
|
18
|
+
kind,
|
|
19
|
+
effect,
|
|
20
|
+
contribution: contribution === null ? null : typeof tax.amount === 'string' ? String(contribution) : Number(contribution)
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/** Informational bases and IVA breakdowns are not added again to the fiscal total. */
|
|
24
|
+
function dteHeaderTotal(detail, taxes) {
|
|
25
|
+
if (taxes.some(tax => tax.contribution === null))
|
|
26
|
+
return null;
|
|
27
|
+
const c = detail.fiscalComponents;
|
|
28
|
+
if (BigInt(c?.constructionCredit ?? 0) !== 0n && detail.documentType === 34)
|
|
29
|
+
return null;
|
|
30
|
+
const commissions = [c?.commissionNet, c?.commissionExempt, c?.commissionVat].some(value => BigInt(value ?? 0) !== 0n);
|
|
31
|
+
if (commissions && !purchaseReference(detail))
|
|
32
|
+
return null;
|
|
33
|
+
return BigInt(detail.netAmount ?? 0) + BigInt(detail.exemptAmount ?? 0) + BigInt(detail.vatAmount ?? 0)
|
|
34
|
+
+ taxes.reduce((sum, tax) => sum + BigInt(tax.contribution), 0n)
|
|
35
|
+
+ BigInt(c?.containerDeposit ?? 0) - BigInt(c?.constructionCredit ?? 0)
|
|
36
|
+
- BigInt(c?.commissionNet ?? 0) - BigInt(c?.commissionExempt ?? 0) - BigInt(c?.commissionVat ?? 0);
|
|
37
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/** Declared fiscal facts. Calculations and import policies live in separate models. */
|
|
2
|
+
export interface DteFiscalReference {
|
|
3
|
+
lineNumber: number;
|
|
4
|
+
documentType: string;
|
|
5
|
+
folio: string;
|
|
6
|
+
declaredFolio?: string;
|
|
7
|
+
date: string;
|
|
8
|
+
code: number | null;
|
|
9
|
+
reason: string | null;
|
|
10
|
+
/** Explicit RUTOtr, including an unresolved empty value; absence means the current issuer. */
|
|
11
|
+
issuerRut?: string | null;
|
|
12
|
+
globalIndicator?: number;
|
|
13
|
+
}
|
|
14
|
+
export interface DteReferenceIdentity {
|
|
15
|
+
issuerRut: string;
|
|
16
|
+
documentType: number;
|
|
17
|
+
folio: string;
|
|
18
|
+
date: string;
|
|
19
|
+
}
|
|
20
|
+
export interface DteFiscalComponents {
|
|
21
|
+
containerDeposit?: number;
|
|
22
|
+
constructionCredit?: number;
|
|
23
|
+
unretainedVat?: number;
|
|
24
|
+
meatProcessingBase?: number;
|
|
25
|
+
marginBase?: number;
|
|
26
|
+
ownVat?: number;
|
|
27
|
+
thirdPartyVat?: number;
|
|
28
|
+
commissionNet?: number;
|
|
29
|
+
commissionExempt?: number;
|
|
30
|
+
commissionVat?: number;
|
|
31
|
+
}
|
|
32
|
+
export interface DteFiscalConditions {
|
|
33
|
+
noDebitReduction?: number;
|
|
34
|
+
paymentForm?: number;
|
|
35
|
+
saleType?: number;
|
|
36
|
+
purchaseType?: number;
|
|
37
|
+
}
|
|
38
|
+
export interface DteCommission {
|
|
39
|
+
lineNumber: number;
|
|
40
|
+
movement: 'C' | 'O';
|
|
41
|
+
description: string;
|
|
42
|
+
rate: string | null;
|
|
43
|
+
netAmount: number;
|
|
44
|
+
exemptAmount: number;
|
|
45
|
+
vatAmount: number | null;
|
|
46
|
+
}
|
|
47
|
+
export interface DteInvoiceLine {
|
|
48
|
+
lineNumber: number;
|
|
49
|
+
name: string;
|
|
50
|
+
description: string | null;
|
|
51
|
+
codes: {
|
|
52
|
+
type: string;
|
|
53
|
+
value: string;
|
|
54
|
+
}[];
|
|
55
|
+
quantity: string | null;
|
|
56
|
+
unit: string | null;
|
|
57
|
+
unitPrice: string | null;
|
|
58
|
+
discountPercent: string | null;
|
|
59
|
+
discountAmount: number | null;
|
|
60
|
+
surchargePercent: string | null;
|
|
61
|
+
surchargeAmount: number | null;
|
|
62
|
+
exemptIndicator: number | null;
|
|
63
|
+
amount: number;
|
|
64
|
+
/** Original per-line tax codes, when present. They do not replace the declared header taxes. */
|
|
65
|
+
additionalTaxCodes?: number[];
|
|
66
|
+
retention?: {
|
|
67
|
+
agentIndicator: string | null;
|
|
68
|
+
meatProcessingBase: number | null;
|
|
69
|
+
marginBase: number | null;
|
|
70
|
+
consumerUnitPrice: string | null;
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
export interface DteDeclaredDetail {
|
|
74
|
+
fiscalComponents?: DteFiscalComponents;
|
|
75
|
+
fiscalConditions?: DteFiscalConditions;
|
|
76
|
+
commissions?: DteCommission[];
|
|
77
|
+
/** Present only for MntBruto=1: line amounts/prices include VAT. Original fiscal totals are unchanged. */
|
|
78
|
+
grossAmounts?: boolean;
|
|
79
|
+
issuerRut: string;
|
|
80
|
+
documentType: number;
|
|
81
|
+
folio: string;
|
|
82
|
+
/** Original spelling when numeric normalization removes leading zeroes. XML bytes are unchanged. */
|
|
83
|
+
declaredFolio?: string;
|
|
84
|
+
issuedDate: string;
|
|
85
|
+
receiverRut: string;
|
|
86
|
+
netAmount: number | null;
|
|
87
|
+
exemptAmount: number | null;
|
|
88
|
+
vatRate: string | null;
|
|
89
|
+
vatAmount: number | null;
|
|
90
|
+
totalAmount: number;
|
|
91
|
+
/** Optional original totalizers; do not change the fiscal total or infer cash rounding. */
|
|
92
|
+
nonBillableAmount?: number;
|
|
93
|
+
periodAmount?: number;
|
|
94
|
+
previousBalance?: number;
|
|
95
|
+
payableAmount?: number;
|
|
96
|
+
lines: DteInvoiceLine[];
|
|
97
|
+
taxes: {
|
|
98
|
+
type: number;
|
|
99
|
+
rate: string | null;
|
|
100
|
+
amount: number;
|
|
101
|
+
}[];
|
|
102
|
+
adjustments: {
|
|
103
|
+
lineNumber: number;
|
|
104
|
+
movement: 'D' | 'R';
|
|
105
|
+
description: string | null;
|
|
106
|
+
valueType: '%' | '$';
|
|
107
|
+
value: string;
|
|
108
|
+
exemptIndicator: number | null;
|
|
109
|
+
}[];
|
|
110
|
+
references: DteFiscalReference[];
|
|
111
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { DteFiscalReference, DteReferenceIdentity } from './dte-detail';
|
|
2
|
+
/**
|
|
3
|
+
* Normaliza un folio positivo de 1 a 20 dígitos, eliminando ceros iniciales sin usar Number.
|
|
4
|
+
* @param value Folio decimal original; no admite cero, signo, espacios ni notación exponencial.
|
|
5
|
+
* @returns Identidad numérica canónica como string.
|
|
6
|
+
* @throws Error con mensaje SII_FOLIO_INVALID si no es representable como folio positivo.
|
|
7
|
+
* @example normalizeDteFolio('000123'); // '123'
|
|
8
|
+
*/
|
|
9
|
+
export declare function normalizeDteFolio(value: string): string;
|
|
10
|
+
export declare function validDteCreditReference(reference: DteFiscalReference): boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Resuelve una referencia fiscal concreta con RUT emisor, tipo, folio canónico y fecha.
|
|
13
|
+
* Usa currentIssuerRut sólo cuando issuerRut está ausente. Un emisor explícito vacío o inválido no se sustituye.
|
|
14
|
+
* @param reference Referencia declarada; las referencias globales no identifican un documento individual.
|
|
15
|
+
* @param currentIssuerRut Emisor del documento actual para referencias sin RUTOtr explícito.
|
|
16
|
+
* @returns Identidad concreta o null cuando la referencia es global, informativa o no resoluble.
|
|
17
|
+
* @remarks Resolver una identidad no verifica autorización, existencia ni estado del documento referido.
|
|
18
|
+
*/
|
|
19
|
+
export declare function resolveDteReferenceIdentity(reference: DteFiscalReference, currentIssuerRut: string): DteReferenceIdentity | null;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.normalizeDteFolio = normalizeDteFolio;
|
|
4
|
+
exports.validDteCreditReference = validDteCreditReference;
|
|
5
|
+
exports.resolveDteReferenceIdentity = resolveDteReferenceIdentity;
|
|
6
|
+
const civil_date_1 = require("./civil-date");
|
|
7
|
+
const rut_1 = require("./rut");
|
|
8
|
+
/**
|
|
9
|
+
* Normaliza un folio positivo de 1 a 20 dígitos, eliminando ceros iniciales sin usar Number.
|
|
10
|
+
* @param value Folio decimal original; no admite cero, signo, espacios ni notación exponencial.
|
|
11
|
+
* @returns Identidad numérica canónica como string.
|
|
12
|
+
* @throws Error con mensaje SII_FOLIO_INVALID si no es representable como folio positivo.
|
|
13
|
+
* @example normalizeDteFolio('000123'); // '123'
|
|
14
|
+
*/
|
|
15
|
+
function normalizeDteFolio(value) {
|
|
16
|
+
if (typeof value !== 'string' || !/^\d{1,20}$/.test(value) || BigInt(value) === 0n)
|
|
17
|
+
throw new Error('SII_FOLIO_INVALID');
|
|
18
|
+
return BigInt(value).toString();
|
|
19
|
+
}
|
|
20
|
+
function validDteCreditReference(reference) {
|
|
21
|
+
if (!reference || !/^\d{1,3}$/.test(reference.documentType) || Number(reference.documentType) < 1 || Number(reference.documentType) >= 200 || ![1, 2, 3].includes(reference.code ?? 0) || !(0, civil_date_1.isCivilDate)(reference.date))
|
|
22
|
+
return false;
|
|
23
|
+
return reference.globalIndicator === 1 ? reference.folio === '0' && reference.code === 3 : !reference.globalIndicator && /^[1-9]\d{0,19}$/.test(reference.folio);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Resuelve una referencia fiscal concreta con RUT emisor, tipo, folio canónico y fecha.
|
|
27
|
+
* Usa currentIssuerRut sólo cuando issuerRut está ausente. Un emisor explícito vacío o inválido no se sustituye.
|
|
28
|
+
* @param reference Referencia declarada; las referencias globales no identifican un documento individual.
|
|
29
|
+
* @param currentIssuerRut Emisor del documento actual para referencias sin RUTOtr explícito.
|
|
30
|
+
* @returns Identidad concreta o null cuando la referencia es global, informativa o no resoluble.
|
|
31
|
+
* @remarks Resolver una identidad no verifica autorización, existencia ni estado del documento referido.
|
|
32
|
+
*/
|
|
33
|
+
function resolveDteReferenceIdentity(reference, currentIssuerRut) {
|
|
34
|
+
if (!reference || reference.globalIndicator || !/^\d{1,3}$/.test(reference.documentType) || Number(reference.documentType) < 1 || Number(reference.documentType) >= 200)
|
|
35
|
+
return null;
|
|
36
|
+
try {
|
|
37
|
+
if (!(0, civil_date_1.isCivilDate)(reference.date))
|
|
38
|
+
return null;
|
|
39
|
+
const explicitIssuer = Object.hasOwn(reference, 'issuerRut') ? reference.issuerRut : currentIssuerRut;
|
|
40
|
+
if (typeof explicitIssuer !== 'string')
|
|
41
|
+
return null;
|
|
42
|
+
return {
|
|
43
|
+
issuerRut: (0, rut_1.parseRut)(explicitIssuer).formatted,
|
|
44
|
+
documentType: Number(reference.documentType),
|
|
45
|
+
folio: normalizeDteFolio(reference.folio),
|
|
46
|
+
date: reference.date
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** Monetary fields only; identifiers, indicators, quantities and original decimal strings retain their types. */
|
|
2
|
+
declare const monetaryFields: readonly ["amount", "netAmount", "exemptAmount", "vatAmount", "totalAmount", "nonBillableAmount", "periodAmount", "previousBalance", "payableAmount", "statementPayableAmount", "discountAmount", "surchargeAmount", "subtotalAmount", "declaredAmount", "derivedAmount", "grossAmount", "lineRounding", "difference", "componentTotal", "contribution", "containerDeposit", "constructionCredit", "unretainedVat", "meatProcessingBase", "marginBase", "ownVat", "thirdPartyVat", "commissionNet", "commissionExempt", "commissionVat"];
|
|
3
|
+
export type DteMoneyField = typeof monetaryFields[number];
|
|
4
|
+
export type ExactDte<T> = T extends readonly (infer Item)[] ? ExactDte<Item>[] : T extends object ? {
|
|
5
|
+
[Key in keyof T]: Key extends DteMoneyField ? T[Key] extends number | null | undefined ? Exclude<T[Key], number> | string : ExactDte<T[Key]> : ExactDte<T[Key]>;
|
|
6
|
+
} : T;
|
|
7
|
+
/**
|
|
8
|
+
* La conversión a Number perdería precisión, o el valor numérico de entrada ya es inseguro.
|
|
9
|
+
* Su mensaje estable es DTE_AMOUNT_OUT_OF_NUMBER_RANGE.
|
|
10
|
+
*/
|
|
11
|
+
export declare class DteMoneyRangeError extends RangeError {
|
|
12
|
+
constructor();
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Normaliza un importe fuente de hasta 18 dígitos como entero canónico, sin redondear.
|
|
16
|
+
* @param value String entero o number seguro. Un number inseguro se rechaza aunque ya haya perdido precisión.
|
|
17
|
+
* @param signed Permite importes negativos; por defecto sólo admite cero y positivos.
|
|
18
|
+
* @returns String decimal canónico, sin ceros iniciales ni notación exponencial.
|
|
19
|
+
* @throws TypeError por sintaxis o longitud inválida; DteMoneyRangeError por numbers inseguros.
|
|
20
|
+
* @example exactDteMoney('0001190'); // '1190'
|
|
21
|
+
*/
|
|
22
|
+
export declare function exactDteMoney(value: unknown, signed?: boolean): string;
|
|
23
|
+
/**
|
|
24
|
+
* Copia un DTO DTE y convierte sus campos monetarios conocidos a strings enteros exactos.
|
|
25
|
+
* Recorre objetos y arrays del modelo; no altera RUT, folio, indicadores, precios, cantidades ni porcentajes.
|
|
26
|
+
* @param value DTO plano del SDK, sin ciclos ni objetos de plataforma. El catálogo de campos monetarios define la conversión.
|
|
27
|
+
* @returns Una copia; null y campos ausentes se conservan. No reconstruye precisión ya perdida.
|
|
28
|
+
* @throws DteMoneyRangeError por numbers inseguros; TypeError por textos monetarios no enteros.
|
|
29
|
+
* @example withExactDteAmounts({ totalAmount: 1190, folio: '101' }); // { totalAmount: '1190', folio: '101' }
|
|
30
|
+
*/
|
|
31
|
+
export declare function withExactDteAmounts<T>(value: T): ExactDte<T>;
|
|
32
|
+
/**
|
|
33
|
+
* Copia un DTO DTE y convierte sus campos monetarios conocidos a enteros seguros de Number.
|
|
34
|
+
* Es una frontera explícita de compatibilidad; nunca redondea un importe exacto para hacerlo caber.
|
|
35
|
+
* @param value DTO plano numérico o exacto del SDK; use el tipo numérico de destino como argumento genérico.
|
|
36
|
+
* @returns Una copia numérica; no cambia precios, cantidades, porcentajes, identidad ni bytes del XML.
|
|
37
|
+
* @throws DteMoneyRangeError si cualquier importe excede el rango entero seguro; TypeError por sintaxis monetaria inválida.
|
|
38
|
+
* @example withNumberDteAmounts<DteDocumentDetail>(exactDetail);
|
|
39
|
+
*/
|
|
40
|
+
export declare function withNumberDteAmounts<T>(value: T | ExactDte<T>): T;
|
|
41
|
+
export {};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DteMoneyRangeError = void 0;
|
|
4
|
+
exports.exactDteMoney = exactDteMoney;
|
|
5
|
+
exports.withExactDteAmounts = withExactDteAmounts;
|
|
6
|
+
exports.withNumberDteAmounts = withNumberDteAmounts;
|
|
7
|
+
/** Monetary fields only; identifiers, indicators, quantities and original decimal strings retain their types. */
|
|
8
|
+
const monetaryFields = ['amount', 'netAmount', 'exemptAmount', 'vatAmount', 'totalAmount', 'nonBillableAmount', 'periodAmount', 'previousBalance', 'payableAmount', 'statementPayableAmount', 'discountAmount', 'surchargeAmount', 'subtotalAmount', 'declaredAmount', 'derivedAmount', 'grossAmount', 'lineRounding', 'difference', 'componentTotal', 'contribution', 'containerDeposit', 'constructionCredit', 'unretainedVat', 'meatProcessingBase', 'marginBase', 'ownVat', 'thirdPartyVat', 'commissionNet', 'commissionExempt', 'commissionVat'];
|
|
9
|
+
const fields = new Set(monetaryFields);
|
|
10
|
+
/**
|
|
11
|
+
* La conversión a Number perdería precisión, o el valor numérico de entrada ya es inseguro.
|
|
12
|
+
* Su mensaje estable es DTE_AMOUNT_OUT_OF_NUMBER_RANGE.
|
|
13
|
+
*/
|
|
14
|
+
class DteMoneyRangeError extends RangeError {
|
|
15
|
+
constructor() {
|
|
16
|
+
super('DTE_AMOUNT_OUT_OF_NUMBER_RANGE');
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
exports.DteMoneyRangeError = DteMoneyRangeError;
|
|
20
|
+
/**
|
|
21
|
+
* Normaliza un importe fuente de hasta 18 dígitos como entero canónico, sin redondear.
|
|
22
|
+
* @param value String entero o number seguro. Un number inseguro se rechaza aunque ya haya perdido precisión.
|
|
23
|
+
* @param signed Permite importes negativos; por defecto sólo admite cero y positivos.
|
|
24
|
+
* @returns String decimal canónico, sin ceros iniciales ni notación exponencial.
|
|
25
|
+
* @throws TypeError por sintaxis o longitud inválida; DteMoneyRangeError por numbers inseguros.
|
|
26
|
+
* @example exactDteMoney('0001190'); // '1190'
|
|
27
|
+
*/
|
|
28
|
+
function exactDteMoney(value, signed = false) {
|
|
29
|
+
if (typeof value === 'number') {
|
|
30
|
+
if (!Number.isSafeInteger(value))
|
|
31
|
+
throw new DteMoneyRangeError();
|
|
32
|
+
value = String(value);
|
|
33
|
+
}
|
|
34
|
+
if (typeof value !== 'string' || !(signed ? /^-?\d{1,18}$/ : /^\d{1,18}$/).test(value))
|
|
35
|
+
throw new TypeError('INVALID_DTE_AMOUNT');
|
|
36
|
+
return BigInt(value).toString();
|
|
37
|
+
}
|
|
38
|
+
function convert(value, mode, key = '') {
|
|
39
|
+
if (value == null)
|
|
40
|
+
return value;
|
|
41
|
+
if (fields.has(key) && (typeof value === 'string' || typeof value === 'number')) {
|
|
42
|
+
if (typeof value === 'number' && !Number.isSafeInteger(value))
|
|
43
|
+
throw new DteMoneyRangeError();
|
|
44
|
+
const text = String(value);
|
|
45
|
+
if (!/^-?\d{1,38}$/.test(text))
|
|
46
|
+
throw new TypeError('INVALID_DTE_AMOUNT');
|
|
47
|
+
const exact = BigInt(text);
|
|
48
|
+
if (mode === 'exact')
|
|
49
|
+
return exact.toString();
|
|
50
|
+
if (exact < -BigInt(Number.MAX_SAFE_INTEGER) || exact > BigInt(Number.MAX_SAFE_INTEGER))
|
|
51
|
+
throw new DteMoneyRangeError();
|
|
52
|
+
return Number(exact);
|
|
53
|
+
}
|
|
54
|
+
if (Array.isArray(value))
|
|
55
|
+
return value.map(item => convert(item, mode));
|
|
56
|
+
if (typeof value === 'object')
|
|
57
|
+
return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, convert(item, mode, name)]));
|
|
58
|
+
return value;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Copia un DTO DTE y convierte sus campos monetarios conocidos a strings enteros exactos.
|
|
62
|
+
* Recorre objetos y arrays del modelo; no altera RUT, folio, indicadores, precios, cantidades ni porcentajes.
|
|
63
|
+
* @param value DTO plano del SDK, sin ciclos ni objetos de plataforma. El catálogo de campos monetarios define la conversión.
|
|
64
|
+
* @returns Una copia; null y campos ausentes se conservan. No reconstruye precisión ya perdida.
|
|
65
|
+
* @throws DteMoneyRangeError por numbers inseguros; TypeError por textos monetarios no enteros.
|
|
66
|
+
* @example withExactDteAmounts({ totalAmount: 1190, folio: '101' }); // { totalAmount: '1190', folio: '101' }
|
|
67
|
+
*/
|
|
68
|
+
function withExactDteAmounts(value) {
|
|
69
|
+
return convert(value, 'exact');
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Copia un DTO DTE y convierte sus campos monetarios conocidos a enteros seguros de Number.
|
|
73
|
+
* Es una frontera explícita de compatibilidad; nunca redondea un importe exacto para hacerlo caber.
|
|
74
|
+
* @param value DTO plano numérico o exacto del SDK; use el tipo numérico de destino como argumento genérico.
|
|
75
|
+
* @returns Una copia numérica; no cambia precios, cantidades, porcentajes, identidad ni bytes del XML.
|
|
76
|
+
* @throws DteMoneyRangeError si cualquier importe excede el rango entero seguro; TypeError por sintaxis monetaria inválida.
|
|
77
|
+
* @example withNumberDteAmounts<DteDocumentDetail>(exactDetail);
|
|
78
|
+
*/
|
|
79
|
+
function withNumberDteAmounts(value) {
|
|
80
|
+
return convert(value, 'number');
|
|
81
|
+
}
|