@devly-cl/sii-client 0.7.9 → 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 +68 -2
- 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 +47 -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 +14 -4
- package/dist/domain/dte-reconciliation.js +211 -172
- package/dist/domain/dte-validation.d.ts +7 -0
- package/dist/domain/dte-validation.js +84 -0
- package/dist/domain/invoice-xml.d.ts +12 -151
- 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 +18 -10
- package/dist/index.js +18 -5
- 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 +116 -238
- package/dist/infrastructure/facturador-gateway.d.ts +10 -7
- package/dist/infrastructure/facturador-gateway.js +256 -56
- package/dist/infrastructure/facturador.js +14 -7
- 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 +83 -19
- package/dist/sii-error.d.ts +4 -0
- package/dist/sii-error.js +38 -13
- package/package.json +2 -2
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/** Derived explanations of declared amounts; never fiscal approval or import authorization. */
|
|
2
|
+
export interface DteProjectedTax {
|
|
3
|
+
type: number;
|
|
4
|
+
rate: string | null;
|
|
5
|
+
amount: number;
|
|
6
|
+
kind: 'ADDITIONAL' | 'ANTICIPATED' | 'SPECIFIC' | 'RETENTION' | 'MARGIN' | 'UNCLASSIFIED';
|
|
7
|
+
effect: 'ADD' | 'SUBTRACT' | 'UNKNOWN';
|
|
8
|
+
contribution: number | null;
|
|
9
|
+
}
|
|
10
|
+
export interface DteReconciliationDiagnostic {
|
|
11
|
+
code: string;
|
|
12
|
+
severity: 'INFO' | 'ERROR';
|
|
13
|
+
message: string;
|
|
14
|
+
lineNumber?: number;
|
|
15
|
+
declaredAmount?: number;
|
|
16
|
+
derivedAmount?: number;
|
|
17
|
+
}
|
|
18
|
+
/** Non-blocking documentary observations; declared fiscal amounts remain authoritative. */
|
|
19
|
+
export type DteFiscalObservation = Pick<DteReconciliationDiagnostic, 'code' | 'message' | 'declaredAmount' | 'derivedAmount'>;
|
|
20
|
+
export interface DteReconciledLine {
|
|
21
|
+
lineNumber: number;
|
|
22
|
+
quantity: string;
|
|
23
|
+
unitPrice: string;
|
|
24
|
+
discountPercent: string;
|
|
25
|
+
discountAmount: number;
|
|
26
|
+
surchargeAmount: number;
|
|
27
|
+
netAmount: number;
|
|
28
|
+
/** MontoItem exactly as declared, even when the derived line is converted from gross to net. */
|
|
29
|
+
declaredAmount: number;
|
|
30
|
+
category: 'TAXABLE' | 'EXEMPT' | 'DEPOSIT' | 'NON_BILLABLE' | 'NON_BILLABLE_DEDUCTION';
|
|
31
|
+
}
|
|
32
|
+
/** Derived explanation only; the original header and line amounts are never changed. */
|
|
33
|
+
export interface DteTotalRounding {
|
|
34
|
+
difference: -1 | 1;
|
|
35
|
+
method: 'PER_LINE_VAT_AND_TAX';
|
|
36
|
+
basis: 'DECLARED_LINE_AMOUNTS' | 'EXACT_PRODUCTS';
|
|
37
|
+
componentTotal: number;
|
|
38
|
+
}
|
|
39
|
+
export interface DteReconciledAmounts {
|
|
40
|
+
netAmount: number;
|
|
41
|
+
exemptAmount: number;
|
|
42
|
+
vatAmount: number;
|
|
43
|
+
totalAmount: number;
|
|
44
|
+
payableAmount: number;
|
|
45
|
+
lines: DteReconciledLine[];
|
|
46
|
+
taxes: DteProjectedTax[];
|
|
47
|
+
globalDiscount?: {
|
|
48
|
+
netAmount: number;
|
|
49
|
+
grossAmount?: number;
|
|
50
|
+
};
|
|
51
|
+
globalSurcharge?: {
|
|
52
|
+
netAmount: number;
|
|
53
|
+
grossAmount?: number;
|
|
54
|
+
};
|
|
55
|
+
nonBillable?: {
|
|
56
|
+
amount: number;
|
|
57
|
+
lines: {
|
|
58
|
+
lineNumber: number;
|
|
59
|
+
amount: number;
|
|
60
|
+
indicator: 2 | 6;
|
|
61
|
+
}[];
|
|
62
|
+
};
|
|
63
|
+
grossAmountsInferred?: true;
|
|
64
|
+
/** Difference explained by summing exact source products before rounding the subtotal. */
|
|
65
|
+
lineRounding?: number;
|
|
66
|
+
/** At most one peso per document, explained by an exact supported line calculation. */
|
|
67
|
+
totalRounding?: DteTotalRounding;
|
|
68
|
+
observations?: DteFiscalObservation[];
|
|
69
|
+
}
|
|
70
|
+
export interface DteReconciliation {
|
|
71
|
+
version: 1;
|
|
72
|
+
status: 'RECONCILED' | 'REVIEW_REQUIRED';
|
|
73
|
+
/** Header values are never overwritten by calculations. Null means absent in the XML. */
|
|
74
|
+
declared: {
|
|
75
|
+
netAmount: number | null;
|
|
76
|
+
exemptAmount: number | null;
|
|
77
|
+
vatAmount: number | null;
|
|
78
|
+
totalAmount: number;
|
|
79
|
+
nonBillableAmount: number | null;
|
|
80
|
+
periodAmount: number | null;
|
|
81
|
+
previousBalance: number | null;
|
|
82
|
+
payableAmount: number | null;
|
|
83
|
+
grossAmounts: boolean | null;
|
|
84
|
+
};
|
|
85
|
+
derived: DteReconciledAmounts | null;
|
|
86
|
+
diagnostics: DteReconciliationDiagnostic[];
|
|
87
|
+
}
|
|
@@ -1,5 +1,15 @@
|
|
|
1
|
-
import type { DteFiscalDetail
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
import type { DteFiscalDetail } from './invoice-xml';
|
|
2
|
+
import type { DteReconciliation } from './dte-reconciliation-model';
|
|
3
|
+
/**
|
|
4
|
+
* Explica los importes declarados mediante las reglas aritméticas soportadas para DTE 33, 34 y 61.
|
|
5
|
+
* No modifica el detalle, sus líneas ni los totales fiscales originales.
|
|
6
|
+
*
|
|
7
|
+
* @param detail Detalle declarado con importes enteros seguros; las cantidades y precios son strings decimales.
|
|
8
|
+
* @returns RECONCILED con importes derivados, o REVIEW_REQUIRED con derived=null y diagnósticos.
|
|
9
|
+
* Ambos estados describen la capacidad de interpretación del SDK, no la validez fiscal del documento.
|
|
10
|
+
* @remarks No consulta el SII, no verifica autorización y no decide la persistencia en un consumidor.
|
|
11
|
+
* @example
|
|
12
|
+
* const analysis = reconcileDteDetail(detail);
|
|
13
|
+
* if (analysis.status === 'REVIEW_REQUIRED') console.log(analysis.diagnostics);
|
|
14
|
+
*/
|
|
5
15
|
export declare function reconcileDteDetail(detail: DteFiscalDetail): DteReconciliation;
|