@devly-cl/sii-client 0.4.4 → 0.6.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 +118 -26
- package/dist/application/invoice-queries.d.ts +17 -0
- package/dist/application/invoice-queries.js +51 -0
- package/dist/application/issuance.d.ts +40 -0
- package/dist/application/issuance.js +79 -0
- package/dist/contracts.d.ts +66 -0
- package/dist/contracts.js +2 -0
- package/dist/domain/document.d.ts +47 -0
- package/dist/domain/document.js +38 -0
- package/dist/domain/invoice-xml.d.ts +58 -11
- package/dist/domain/invoice-xml.js +0 -138
- package/dist/domain/invoicing.d.ts +52 -0
- package/dist/domain/invoicing.js +157 -0
- package/dist/domain/issued-invoice.d.ts +16 -9
- package/dist/domain/issued-invoice.js +4 -43
- package/dist/domain/received-invoice.d.ts +11 -7
- package/dist/domain/received-invoice.js +0 -10
- package/dist/domain/sii-error.d.ts +3 -3
- package/dist/domain/sii-error.js +10 -4
- package/dist/index.d.ts +13 -3
- package/dist/index.js +12 -3
- package/dist/infrastructure/dte-xml.d.ts +11 -0
- package/dist/infrastructure/dte-xml.js +173 -0
- package/dist/infrastructure/facturador-gateway.d.ts +28 -0
- package/dist/infrastructure/facturador-gateway.js +411 -0
- package/dist/infrastructure/facturador.d.ts +18 -0
- package/dist/infrastructure/facturador.js +231 -0
- package/dist/infrastructure/invoice-pdf.d.ts +9 -0
- package/dist/infrastructure/invoice-pdf.js +171 -0
- package/dist/infrastructure/rcv-gateway.d.ts +17 -0
- package/dist/infrastructure/rcv-gateway.js +105 -0
- package/dist/infrastructure/rcv-normalization.d.ts +6 -0
- package/dist/infrastructure/rcv-normalization.js +55 -0
- package/dist/infrastructure/sii-client.d.ts +52 -54
- package/dist/infrastructure/sii-client.js +66 -487
- package/dist/infrastructure/sii-http-session.d.ts +25 -0
- package/dist/infrastructure/sii-http-session.js +344 -0
- package/dist/sii-error.d.ts +27 -0
- package/dist/sii-error.js +86 -0
- package/package.json +4 -4
|
@@ -1,10 +1,15 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { InvoiceDocumentType } from './issued-invoice';
|
|
2
2
|
export declare const MAX_DTE_XML_BYTES = 1048576;
|
|
3
|
-
export
|
|
4
|
-
|
|
3
|
+
export type IssuedDocumentType = InvoiceDocumentType | 61;
|
|
4
|
+
export interface IssuedDocumentXmlQuery {
|
|
5
|
+
documentType: IssuedDocumentType;
|
|
5
6
|
folio: string;
|
|
6
7
|
}
|
|
7
|
-
export interface
|
|
8
|
+
export interface IssuedInvoiceXmlQuery {
|
|
9
|
+
documentType: InvoiceDocumentType;
|
|
10
|
+
folio: string;
|
|
11
|
+
}
|
|
12
|
+
export interface ReceivedInvoiceXmlQuery extends IssuedInvoiceXmlQuery {
|
|
8
13
|
issuerRut: string;
|
|
9
14
|
}
|
|
10
15
|
export interface DteInvoiceLine {
|
|
@@ -27,7 +32,7 @@ export interface DteInvoiceLine {
|
|
|
27
32
|
}
|
|
28
33
|
export interface DteInvoiceDetail {
|
|
29
34
|
issuerRut: string;
|
|
30
|
-
documentType:
|
|
35
|
+
documentType: InvoiceDocumentType;
|
|
31
36
|
folio: string;
|
|
32
37
|
issuedDate: string;
|
|
33
38
|
receiverRut: string;
|
|
@@ -59,18 +64,60 @@ export interface DteInvoiceDetail {
|
|
|
59
64
|
reason: string | null;
|
|
60
65
|
}[];
|
|
61
66
|
}
|
|
62
|
-
export interface
|
|
67
|
+
export interface InvoiceXmlResult {
|
|
63
68
|
/** Original bytes, including the original encoding and signatures. */
|
|
64
69
|
xml: Uint8Array;
|
|
65
70
|
encoding: 'UTF-8' | 'ISO-8859-1';
|
|
66
71
|
detail: DteInvoiceDetail;
|
|
67
72
|
}
|
|
73
|
+
export interface DteDocumentDetail extends Omit<DteInvoiceDetail, 'documentType'> {
|
|
74
|
+
documentType: IssuedDocumentType;
|
|
75
|
+
/** Presence of one XMLDSig child of DTE; does not verify cryptographic validity. */
|
|
76
|
+
hasSignature: boolean;
|
|
77
|
+
/** Transport data is present; an observed empty Transporte container does not count. */
|
|
78
|
+
hasTransport: boolean;
|
|
79
|
+
fiscalHeader?: {
|
|
80
|
+
issuer: {
|
|
81
|
+
legalName: string | null;
|
|
82
|
+
businessActivity: string | null;
|
|
83
|
+
activityCode: string | null;
|
|
84
|
+
branchCode: string | null;
|
|
85
|
+
address: string | null;
|
|
86
|
+
commune: string | null;
|
|
87
|
+
city: string | null;
|
|
88
|
+
};
|
|
89
|
+
receiver: {
|
|
90
|
+
legalName: string | null;
|
|
91
|
+
address: string | null;
|
|
92
|
+
commune: string | null;
|
|
93
|
+
city: string | null;
|
|
94
|
+
businessActivity: string | null;
|
|
95
|
+
contact: string | null;
|
|
96
|
+
};
|
|
97
|
+
paymentForm: number | null;
|
|
98
|
+
saleType: number | null;
|
|
99
|
+
purchaseType: number | null;
|
|
100
|
+
noDebitReduction: number | null;
|
|
101
|
+
/** IdDoc fields outside the supported invoice/annulment issuance command. Reads preserve them. */
|
|
102
|
+
unapprovedFiscalFields: string[];
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
export interface IssuedDocumentXmlResult extends Omit<InvoiceXmlResult, 'detail'> {
|
|
106
|
+
detail: DteDocumentDetail;
|
|
107
|
+
}
|
|
108
|
+
/** @deprecated Use IssuedDocumentType. */
|
|
109
|
+
export type TipoDocumentoEmitido = IssuedDocumentType;
|
|
110
|
+
/** @deprecated Use IssuedDocumentXmlQuery. */
|
|
111
|
+
export type ConsultaXmlDocumentoEmitido = IssuedDocumentXmlQuery;
|
|
112
|
+
/** @deprecated Use IssuedInvoiceXmlQuery. */
|
|
113
|
+
export type ConsultaXmlFacturaEmitida = IssuedInvoiceXmlQuery;
|
|
114
|
+
/** @deprecated Use ReceivedInvoiceXmlQuery. */
|
|
115
|
+
export type ConsultaXmlFacturaRecibida = ReceivedInvoiceXmlQuery;
|
|
116
|
+
/** @deprecated Use InvoiceXmlResult. */
|
|
117
|
+
export type ResultadoXmlFacturaEmitida = InvoiceXmlResult;
|
|
118
|
+
/** @deprecated Use IssuedDocumentXmlResult. */
|
|
119
|
+
export type ResultadoXmlDocumentoEmitido = IssuedDocumentXmlResult;
|
|
68
120
|
export declare class DteXmlError extends Error {
|
|
69
121
|
readonly code: 'SII_XML_INVALID' | 'SII_XML_IDENTITY_MISMATCH';
|
|
70
122
|
constructor(code: 'SII_XML_INVALID' | 'SII_XML_IDENTITY_MISMATCH');
|
|
71
123
|
}
|
|
72
|
-
/** Bounded, namespace-aware parsing; no DTD, external entities or network I/O. */
|
|
73
|
-
export declare function parseDteXml(xml: Uint8Array, expected: ConsultaXmlFacturaEmitida & {
|
|
74
|
-
issuerRut: string;
|
|
75
|
-
receiverRut?: string;
|
|
76
|
-
}): ResultadoXmlFacturaEmitida;
|
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.DteXmlError = exports.MAX_DTE_XML_BYTES = void 0;
|
|
4
|
-
exports.parseDteXml = parseDteXml;
|
|
5
|
-
const saxes_1 = require("saxes");
|
|
6
|
-
const rut_1 = require("./rut");
|
|
7
4
|
exports.MAX_DTE_XML_BYTES = 1_048_576;
|
|
8
5
|
class DteXmlError extends Error {
|
|
9
6
|
code;
|
|
@@ -13,138 +10,3 @@ class DteXmlError extends Error {
|
|
|
13
10
|
}
|
|
14
11
|
}
|
|
15
12
|
exports.DteXmlError = DteXmlError;
|
|
16
|
-
function invalid() { throw new DteXmlError('SII_XML_INVALID'); }
|
|
17
|
-
const children = (node, name) => node.children.filter(n => n.name === name && n.uri === node.uri);
|
|
18
|
-
function one(node, name) {
|
|
19
|
-
const values = children(node, name);
|
|
20
|
-
return values.length === 1 ? values[0] : invalid();
|
|
21
|
-
}
|
|
22
|
-
function text(node, name, required = false, limit = 1000) {
|
|
23
|
-
const values = children(node, name);
|
|
24
|
-
if (values.length > 1 || (required && values.length !== 1))
|
|
25
|
-
invalid();
|
|
26
|
-
if (!values.length)
|
|
27
|
-
return null;
|
|
28
|
-
const value = values[0];
|
|
29
|
-
if (value.children.length || value.text.length > limit || (required && !value.text.trim()))
|
|
30
|
-
invalid();
|
|
31
|
-
return value.text.trim() || null;
|
|
32
|
-
}
|
|
33
|
-
function integer(node, name, required = false) {
|
|
34
|
-
const value = text(node, name, required, 20);
|
|
35
|
-
if (value === null)
|
|
36
|
-
return null;
|
|
37
|
-
const number = Number(value);
|
|
38
|
-
if (!/^\d+$/.test(value) || !Number.isSafeInteger(number))
|
|
39
|
-
invalid();
|
|
40
|
-
return number;
|
|
41
|
-
}
|
|
42
|
-
function decimal(node, name, required = false) {
|
|
43
|
-
const value = text(node, name, required, 40);
|
|
44
|
-
if (value !== null && !/^\d+(?:\.\d+)?$/.test(value))
|
|
45
|
-
invalid();
|
|
46
|
-
return value;
|
|
47
|
-
}
|
|
48
|
-
function date(node, name) {
|
|
49
|
-
const value = text(node, name, true, 10);
|
|
50
|
-
const parsed = new Date(`${value}T00:00:00Z`);
|
|
51
|
-
if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || !Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== value)
|
|
52
|
-
invalid();
|
|
53
|
-
return value;
|
|
54
|
-
}
|
|
55
|
-
function lineNumber(node, name) {
|
|
56
|
-
const value = integer(node, name, true);
|
|
57
|
-
return value > 0 ? value : invalid();
|
|
58
|
-
}
|
|
59
|
-
function uniqueLines(items) {
|
|
60
|
-
if (new Set(items.map(item => item.lineNumber)).size !== items.length)
|
|
61
|
-
invalid();
|
|
62
|
-
}
|
|
63
|
-
/** Bounded, namespace-aware parsing; no DTD, external entities or network I/O. */
|
|
64
|
-
function parseDteXml(xml, expected) {
|
|
65
|
-
if (!(xml instanceof Uint8Array) || !xml.byteLength || xml.byteLength > exports.MAX_DTE_XML_BYTES)
|
|
66
|
-
invalid();
|
|
67
|
-
let root;
|
|
68
|
-
const stack = [];
|
|
69
|
-
let nodes = 0;
|
|
70
|
-
const header = Buffer.from(xml.subarray(0, 200)).toString('latin1');
|
|
71
|
-
const declared = /<\?xml\b[^?]*\bencoding\s*=\s*['"]([^'"]+)['"]/i.exec(header)?.[1]?.toUpperCase() ?? 'UTF-8';
|
|
72
|
-
const encoding = declared === 'UTF-8' || declared === 'UTF8' ? 'UTF-8' : declared === 'ISO-8859-1' ? 'ISO-8859-1' : invalid();
|
|
73
|
-
try {
|
|
74
|
-
const source = encoding === 'ISO-8859-1' ? Buffer.from(xml).toString('latin1') : new TextDecoder('utf-8', { fatal: true }).decode(xml);
|
|
75
|
-
const parser = new saxes_1.SaxesParser({ xmlns: true });
|
|
76
|
-
parser.on('error', invalid);
|
|
77
|
-
parser.on('doctype', invalid);
|
|
78
|
-
parser.on('processinginstruction', invalid);
|
|
79
|
-
parser.on('opentag', tag => {
|
|
80
|
-
if (++nodes > 10000 || stack.length >= 32)
|
|
81
|
-
invalid();
|
|
82
|
-
const node = { name: tag.local, uri: tag.uri, text: '', children: [] };
|
|
83
|
-
if (stack.length)
|
|
84
|
-
stack[stack.length - 1].children.push(node);
|
|
85
|
-
else if (root)
|
|
86
|
-
invalid();
|
|
87
|
-
else
|
|
88
|
-
root = node;
|
|
89
|
-
stack.push(node);
|
|
90
|
-
});
|
|
91
|
-
const append = (value) => { if (stack.length)
|
|
92
|
-
stack[stack.length - 1].text += value; };
|
|
93
|
-
parser.on('text', append);
|
|
94
|
-
parser.on('cdata', append);
|
|
95
|
-
parser.on('closetag', () => { stack.pop(); });
|
|
96
|
-
parser.write(source).close();
|
|
97
|
-
}
|
|
98
|
-
catch {
|
|
99
|
-
invalid();
|
|
100
|
-
}
|
|
101
|
-
if (!root || !['', 'http://www.sii.cl/SiiDte'].includes(root.uri))
|
|
102
|
-
invalid();
|
|
103
|
-
const dtes = root.name === 'DTE' ? [root] : root.name === 'SetDTE' ? children(root, 'DTE') : root.name === 'EnvioDTE' ? children(one(root, 'SetDTE'), 'DTE') : [];
|
|
104
|
-
if (dtes.length !== 1)
|
|
105
|
-
invalid();
|
|
106
|
-
const document = one(dtes[0], 'Documento');
|
|
107
|
-
const headerNode = one(document, 'Encabezado');
|
|
108
|
-
const identity = one(headerNode, 'IdDoc');
|
|
109
|
-
const totals = one(headerNode, 'Totales');
|
|
110
|
-
const documentType = integer(identity, 'TipoDTE', true);
|
|
111
|
-
const folio = text(identity, 'Folio', true, 20);
|
|
112
|
-
let issuerRut, receiverRut;
|
|
113
|
-
try {
|
|
114
|
-
issuerRut = (0, rut_1.parseRut)(text(one(headerNode, 'Emisor'), 'RUTEmisor', true, 12)).formatted;
|
|
115
|
-
receiverRut = (0, rut_1.parseRut)(text(one(headerNode, 'Receptor'), 'RUTRecep', true, 12)).formatted;
|
|
116
|
-
}
|
|
117
|
-
catch {
|
|
118
|
-
return invalid();
|
|
119
|
-
}
|
|
120
|
-
if ((documentType !== 33 && documentType !== 34) || !/^[1-9]\d{0,19}$/.test(folio))
|
|
121
|
-
invalid();
|
|
122
|
-
if (issuerRut !== (0, rut_1.parseRut)(expected.issuerRut).formatted || documentType !== expected.documentType || folio !== expected.folio || (expected.receiverRut !== undefined && receiverRut !== (0, rut_1.parseRut)(expected.receiverRut).formatted))
|
|
123
|
-
throw new DteXmlError('SII_XML_IDENTITY_MISMATCH');
|
|
124
|
-
const lines = children(document, 'Detalle').map(line => ({
|
|
125
|
-
lineNumber: lineNumber(line, 'NroLinDet'), name: text(line, 'NmbItem', true, 80), description: text(line, 'DscItem'),
|
|
126
|
-
codes: children(line, 'CdgItem').map(code => ({ type: text(code, 'TpoCodigo', true, 10), value: text(code, 'VlrCodigo', true, 35) })),
|
|
127
|
-
quantity: decimal(line, 'QtyItem'), unit: text(line, 'UnmdItem', false, 4), unitPrice: decimal(line, 'PrcItem'),
|
|
128
|
-
discountPercent: decimal(line, 'DescuentoPct'), discountAmount: integer(line, 'DescuentoMonto'),
|
|
129
|
-
surchargePercent: decimal(line, 'RecargoPct'), surchargeAmount: integer(line, 'RecargoMonto'), exemptIndicator: integer(line, 'IndExe'), amount: integer(line, 'MontoItem', true),
|
|
130
|
-
}));
|
|
131
|
-
if (!lines.length || lines.length > 1000)
|
|
132
|
-
invalid();
|
|
133
|
-
const adjustments = children(document, 'DscRcgGlobal').map(node => {
|
|
134
|
-
const movement = text(node, 'TpoMov', true), valueType = text(node, 'TpoValor', true);
|
|
135
|
-
if ((movement !== 'D' && movement !== 'R') || (valueType !== '%' && valueType !== '$'))
|
|
136
|
-
invalid();
|
|
137
|
-
return { lineNumber: lineNumber(node, 'NroLinDR'), movement: movement, description: text(node, 'GlosaDR'), valueType: valueType, value: decimal(node, 'ValorDR', true), exemptIndicator: integer(node, 'IndExeDR') };
|
|
138
|
-
});
|
|
139
|
-
const references = children(document, 'Referencia').map(node => ({
|
|
140
|
-
lineNumber: lineNumber(node, 'NroLinRef'), documentType: text(node, 'TpoDocRef', true, 3), folio: text(node, 'FolioRef', true, 18), date: date(node, 'FchRef'), code: integer(node, 'CodRef'), reason: text(node, 'RazonRef', false, 90),
|
|
141
|
-
}));
|
|
142
|
-
uniqueLines(lines);
|
|
143
|
-
uniqueLines(adjustments);
|
|
144
|
-
uniqueLines(references);
|
|
145
|
-
return { xml: new Uint8Array(xml), encoding, detail: {
|
|
146
|
-
issuerRut, documentType: documentType, folio, issuedDate: date(identity, 'FchEmis'), receiverRut,
|
|
147
|
-
netAmount: integer(totals, 'MntNeto'), exemptAmount: integer(totals, 'MntExe'), vatRate: decimal(totals, 'TasaIVA'), vatAmount: integer(totals, 'IVA'), totalAmount: integer(totals, 'MntTotal', true), lines,
|
|
148
|
-
taxes: children(totals, 'ImptoReten').map(node => ({ type: integer(node, 'TipoImp', true), rate: decimal(node, 'TasaImp'), amount: integer(node, 'MontoImp', true) })), adjustments, references,
|
|
149
|
-
} };
|
|
150
|
-
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
export interface InvoiceLineInput {
|
|
2
|
+
name: string;
|
|
3
|
+
description?: string;
|
|
4
|
+
quantity: string;
|
|
5
|
+
unitNetPriceClp: string;
|
|
6
|
+
unit?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface InvoiceInput {
|
|
9
|
+
issuedDate: string;
|
|
10
|
+
issuer: {
|
|
11
|
+
address: string;
|
|
12
|
+
commune: string;
|
|
13
|
+
city: string;
|
|
14
|
+
activityCode: string;
|
|
15
|
+
};
|
|
16
|
+
receiver: {
|
|
17
|
+
rut: string;
|
|
18
|
+
legalName: string;
|
|
19
|
+
address: string;
|
|
20
|
+
commune: string;
|
|
21
|
+
city: string;
|
|
22
|
+
businessActivity: string;
|
|
23
|
+
contact?: string;
|
|
24
|
+
};
|
|
25
|
+
paymentForm: 1 | 2;
|
|
26
|
+
saleType: 1 | 2;
|
|
27
|
+
purchaseType: 1 | 2 | 3 | 4 | 5 | 6 | 7;
|
|
28
|
+
items: InvoiceLineInput[];
|
|
29
|
+
}
|
|
30
|
+
export interface InvoiceTotals {
|
|
31
|
+
netAmount: number;
|
|
32
|
+
vatAmount: number;
|
|
33
|
+
totalAmount: number;
|
|
34
|
+
}
|
|
35
|
+
/** @deprecated Use InvoiceLineInput. */
|
|
36
|
+
export type LineaFactura = InvoiceLineInput;
|
|
37
|
+
/** @deprecated Use InvoiceInput. */
|
|
38
|
+
export type EntradaFactura = InvoiceInput;
|
|
39
|
+
/** @deprecated Use InvoiceTotals. */
|
|
40
|
+
export type TotalesFactura = InvoiceTotals;
|
|
41
|
+
/** Tipo 33, IVA 19%, sin descuentos ni opciones fiscales implícitas. */
|
|
42
|
+
export declare function validateInvoice(input: unknown): InvoiceInput;
|
|
43
|
+
/** Redondea cada línea a CLP y después el IVA; sin aritmética decimal binaria. */
|
|
44
|
+
export declare function calculateInvoiceTotals(input: unknown): InvoiceTotals;
|
|
45
|
+
/** Huella determinista del contenido fiscal; el llamador excluye claves y tokens. */
|
|
46
|
+
export declare function hashContent(value: unknown): string;
|
|
47
|
+
/** @deprecated Use validateInvoice. */
|
|
48
|
+
export declare const validarFactura: typeof validateInvoice;
|
|
49
|
+
/** @deprecated Use calculateInvoiceTotals. */
|
|
50
|
+
export declare const calcularTotalesFactura: typeof calculateInvoiceTotals;
|
|
51
|
+
/** @deprecated Use hashContent. */
|
|
52
|
+
export declare const hashContenido: typeof hashContent;
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.hashContenido = exports.calcularTotalesFactura = exports.validarFactura = void 0;
|
|
4
|
+
exports.validateInvoice = validateInvoice;
|
|
5
|
+
exports.calculateInvoiceTotals = calculateInvoiceTotals;
|
|
6
|
+
exports.hashContent = hashContent;
|
|
7
|
+
const node_crypto_1 = require("node:crypto");
|
|
8
|
+
const rut_1 = require("./rut");
|
|
9
|
+
const controls = /[\u0000-\u001f\u007f-\u009f]/u;
|
|
10
|
+
function invalid(field) { throw new TypeError(`Factura inválida: ${field}`); }
|
|
11
|
+
function isRecord(value) {
|
|
12
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
13
|
+
&& (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
|
14
|
+
}
|
|
15
|
+
function record(value, allowed, field) {
|
|
16
|
+
if (!isRecord(value) || Reflect.ownKeys(value).some(key => typeof key !== 'string' || !allowed.includes(key)))
|
|
17
|
+
invalid(field);
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
function text(value, limit, field, optional = false) {
|
|
21
|
+
if (optional && value === undefined)
|
|
22
|
+
return undefined;
|
|
23
|
+
if (typeof value !== 'string' || controls.test(value))
|
|
24
|
+
invalid(field);
|
|
25
|
+
const result = value.trim();
|
|
26
|
+
if (result.length > limit || (!optional && !result))
|
|
27
|
+
invalid(field);
|
|
28
|
+
return result || undefined;
|
|
29
|
+
}
|
|
30
|
+
function requiredText(value, limit, field) {
|
|
31
|
+
return text(value, limit, field) ?? invalid(field);
|
|
32
|
+
}
|
|
33
|
+
function decimal(value, field) {
|
|
34
|
+
const result = requiredText(value, 12, field);
|
|
35
|
+
const match = /^(\d{1,10})(?:\.(\d{1,2}))?$/.exec(result);
|
|
36
|
+
if (!match)
|
|
37
|
+
invalid(field);
|
|
38
|
+
const integer = match[1].replace(/^0+(?=\d)/u, '');
|
|
39
|
+
const fraction = (match[2] ?? '').replace(/0+$/u, '');
|
|
40
|
+
if (integer === '0' && !fraction)
|
|
41
|
+
invalid(field);
|
|
42
|
+
return fraction ? `${integer}.${fraction}` : integer;
|
|
43
|
+
}
|
|
44
|
+
function hundredths(value) {
|
|
45
|
+
const [integer, fraction = ''] = value.split('.');
|
|
46
|
+
return BigInt(integer) * 100n + BigInt(fraction.padEnd(2, '0'));
|
|
47
|
+
}
|
|
48
|
+
function items(value) {
|
|
49
|
+
if (!Array.isArray(value) || !value.length || value.length > 10)
|
|
50
|
+
invalid('items');
|
|
51
|
+
return Array.from(value, entry => {
|
|
52
|
+
const source = record(entry, ['name', 'description', 'quantity', 'unitNetPriceClp', 'unit'], 'items');
|
|
53
|
+
const description = text(source.description, 999, 'description', true);
|
|
54
|
+
const unit = text(source.unit, 4, 'unit', true);
|
|
55
|
+
return Object.freeze({
|
|
56
|
+
name: requiredText(source.name, 25, 'name'),
|
|
57
|
+
...(description === undefined ? {} : { description }),
|
|
58
|
+
quantity: decimal(source.quantity, 'quantity'),
|
|
59
|
+
unitNetPriceClp: decimal(source.unitNetPriceClp, 'unitNetPriceClp'),
|
|
60
|
+
...(unit === undefined ? {} : { unit }),
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
function totals(lines) {
|
|
65
|
+
const net = lines.reduce((sum, line) => {
|
|
66
|
+
const amount = (hundredths(line.quantity) * hundredths(line.unitNetPriceClp) + 5000n) / 10000n;
|
|
67
|
+
if (amount < 1n)
|
|
68
|
+
invalid('lineAmount');
|
|
69
|
+
return sum + amount;
|
|
70
|
+
}, 0n);
|
|
71
|
+
const vat = (net * 19n + 50n) / 100n;
|
|
72
|
+
const total = net + vat;
|
|
73
|
+
if (net < 1n || total > 9999999999n)
|
|
74
|
+
invalid('totalAmount');
|
|
75
|
+
return Object.freeze({ netAmount: Number(net), vatAmount: Number(vat), totalAmount: Number(total) });
|
|
76
|
+
}
|
|
77
|
+
function issuedDate(value) {
|
|
78
|
+
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/u.test(value))
|
|
79
|
+
invalid('issuedDate');
|
|
80
|
+
const year = Number(value.slice(0, 4)), month = Number(value.slice(5, 7)), day = Number(value.slice(8, 10));
|
|
81
|
+
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
82
|
+
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
83
|
+
if (year < 2017 || month < 1 || month > 12 || day < 1 || day > days[month - 1])
|
|
84
|
+
invalid('issuedDate');
|
|
85
|
+
return value;
|
|
86
|
+
}
|
|
87
|
+
/** Tipo 33, IVA 19%, sin descuentos ni opciones fiscales implícitas. */
|
|
88
|
+
function validateInvoice(input) {
|
|
89
|
+
const source = record(input, ['issuedDate', 'issuer', 'receiver', 'paymentForm', 'saleType', 'purchaseType', 'items'], 'input');
|
|
90
|
+
const issuer = record(source.issuer, ['address', 'commune', 'city', 'activityCode'], 'issuer');
|
|
91
|
+
const receiver = record(source.receiver, ['rut', 'legalName', 'address', 'commune', 'city', 'businessActivity', 'contact'], 'receiver');
|
|
92
|
+
const activityCode = requiredText(issuer.activityCode, 6, 'activityCode');
|
|
93
|
+
if (!/^\d{6}$/u.test(activityCode))
|
|
94
|
+
invalid('activityCode');
|
|
95
|
+
const paymentForm = source.paymentForm, saleType = source.saleType, purchaseType = source.purchaseType;
|
|
96
|
+
if (paymentForm !== 1 && paymentForm !== 2)
|
|
97
|
+
invalid('paymentForm');
|
|
98
|
+
if (saleType !== 1 && saleType !== 2)
|
|
99
|
+
invalid('saleType');
|
|
100
|
+
if (purchaseType !== 1 && purchaseType !== 2 && purchaseType !== 3 && purchaseType !== 4 && purchaseType !== 5 && purchaseType !== 6 && purchaseType !== 7)
|
|
101
|
+
invalid('purchaseType');
|
|
102
|
+
const lines = items(source.items);
|
|
103
|
+
totals(lines);
|
|
104
|
+
const contact = text(receiver.contact, 80, 'contact', true);
|
|
105
|
+
const result = {
|
|
106
|
+
issuedDate: issuedDate(source.issuedDate),
|
|
107
|
+
issuer: Object.freeze({
|
|
108
|
+
address: requiredText(issuer.address, 70, 'issuer.address'),
|
|
109
|
+
commune: requiredText(issuer.commune, 20, 'issuer.commune'),
|
|
110
|
+
city: requiredText(issuer.city, 15, 'issuer.city'), activityCode,
|
|
111
|
+
}),
|
|
112
|
+
receiver: Object.freeze({
|
|
113
|
+
rut: (0, rut_1.parseRut)(requiredText(receiver.rut, 15, 'receiver.rut')).formatted,
|
|
114
|
+
legalName: requiredText(receiver.legalName, 100, 'receiver.legalName'),
|
|
115
|
+
address: requiredText(receiver.address, 70, 'receiver.address'),
|
|
116
|
+
commune: requiredText(receiver.commune, 20, 'receiver.commune'),
|
|
117
|
+
city: requiredText(receiver.city, 15, 'receiver.city'),
|
|
118
|
+
businessActivity: requiredText(receiver.businessActivity, 40, 'receiver.businessActivity'),
|
|
119
|
+
...(contact === undefined ? {} : { contact }),
|
|
120
|
+
}),
|
|
121
|
+
paymentForm, saleType, purchaseType, items: lines,
|
|
122
|
+
};
|
|
123
|
+
Object.freeze(result.items);
|
|
124
|
+
return Object.freeze(result);
|
|
125
|
+
}
|
|
126
|
+
/** Redondea cada línea a CLP y después el IVA; sin aritmética decimal binaria. */
|
|
127
|
+
function calculateInvoiceTotals(input) { return totals(items(input)); }
|
|
128
|
+
/** Huella determinista del contenido fiscal; el llamador excluye claves y tokens. */
|
|
129
|
+
function hashContent(value) {
|
|
130
|
+
const ancestors = new Set();
|
|
131
|
+
function canonical(input) {
|
|
132
|
+
if (input === null || typeof input === 'string' || typeof input === 'boolean')
|
|
133
|
+
return input;
|
|
134
|
+
if (typeof input === 'number' && Number.isFinite(input))
|
|
135
|
+
return input;
|
|
136
|
+
if (typeof input !== 'object' || ancestors.has(input))
|
|
137
|
+
invalid('contenido');
|
|
138
|
+
ancestors.add(input);
|
|
139
|
+
let result;
|
|
140
|
+
if (Array.isArray(input))
|
|
141
|
+
result = Array.from(input, canonical);
|
|
142
|
+
else if (isRecord(input) && Reflect.ownKeys(input).every(key => typeof key === 'string')) {
|
|
143
|
+
result = Object.fromEntries(Object.keys(input).sort().map(key => [key, canonical(input[key])]));
|
|
144
|
+
}
|
|
145
|
+
else
|
|
146
|
+
invalid('contenido');
|
|
147
|
+
ancestors.delete(input);
|
|
148
|
+
return result;
|
|
149
|
+
}
|
|
150
|
+
return (0, node_crypto_1.createHash)('sha256').update(JSON.stringify(canonical(value))).digest('hex');
|
|
151
|
+
}
|
|
152
|
+
/** @deprecated Use validateInvoice. */
|
|
153
|
+
exports.validarFactura = validateInvoice;
|
|
154
|
+
/** @deprecated Use calculateInvoiceTotals. */
|
|
155
|
+
exports.calcularTotalesFactura = calculateInvoiceTotals;
|
|
156
|
+
/** @deprecated Use hashContent. */
|
|
157
|
+
exports.hashContenido = hashContent;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
export type
|
|
2
|
-
export interface
|
|
1
|
+
export type InvoiceDocumentType = 33 | 34;
|
|
2
|
+
export interface IssuedInvoicesQuery {
|
|
3
3
|
periodo: string;
|
|
4
4
|
tokenRecaptcha?: string;
|
|
5
5
|
}
|
|
6
|
-
export interface
|
|
6
|
+
export interface IssuedInvoice {
|
|
7
7
|
issuerRut: string;
|
|
8
|
-
documentType:
|
|
8
|
+
documentType: InvoiceDocumentType;
|
|
9
9
|
folio: string;
|
|
10
10
|
issuedDate: string;
|
|
11
11
|
receiverRut: string;
|
|
@@ -17,12 +17,19 @@ export interface FacturaEmitida {
|
|
|
17
17
|
siiBranchCode: string | null;
|
|
18
18
|
rcvPeriod: string;
|
|
19
19
|
}
|
|
20
|
-
export interface
|
|
21
|
-
data:
|
|
20
|
+
export interface IssuedInvoicesResult {
|
|
21
|
+
data: IssuedInvoice[];
|
|
22
22
|
complete: boolean;
|
|
23
23
|
expectedCount: number;
|
|
24
24
|
observedAt: string;
|
|
25
|
-
incompleteDocumentTypes:
|
|
25
|
+
incompleteDocumentTypes: InvoiceDocumentType[];
|
|
26
26
|
}
|
|
27
|
-
/**
|
|
28
|
-
export
|
|
27
|
+
/** @deprecated Use InvoiceDocumentType. */
|
|
28
|
+
export type TipoFacturaEmitida = InvoiceDocumentType;
|
|
29
|
+
/** @deprecated Use IssuedInvoicesQuery. */
|
|
30
|
+
export type ConsultaFacturasEmitidas = IssuedInvoicesQuery;
|
|
31
|
+
/** @deprecated Use IssuedInvoice. */
|
|
32
|
+
export type FacturaEmitida = IssuedInvoice;
|
|
33
|
+
/** @deprecated Use IssuedInvoicesResult. */
|
|
34
|
+
export type ResultadoFacturasEmitidas = IssuedInvoicesResult;
|
|
35
|
+
export declare function assertPeriod(periodo: string): void;
|
|
@@ -1,46 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
throw new TypeError('SII_INVALID_RESPONSE');
|
|
8
|
-
return value;
|
|
9
|
-
}
|
|
10
|
-
function nullableAmount(value) { return value == null ? null : integer(value); }
|
|
11
|
-
function date(value) {
|
|
12
|
-
if (typeof value !== 'string')
|
|
13
|
-
throw new TypeError('SII_INVALID_RESPONSE');
|
|
14
|
-
const iso = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
|
15
|
-
const local = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec(value);
|
|
16
|
-
const [year, month, day] = iso ? [iso[1], iso[2], iso[3]] : local ? [local[3], local[2], local[1]] : [];
|
|
17
|
-
if (!year || !month || !day)
|
|
18
|
-
throw new TypeError('SII_INVALID_RESPONSE');
|
|
19
|
-
const y = Number(year), m = Number(month), d = Number(day);
|
|
20
|
-
const days = [31, y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
21
|
-
if (y < 1 || m < 1 || m > 12 || d < 1 || d > days[m - 1])
|
|
22
|
-
throw new TypeError('SII_INVALID_RESPONSE');
|
|
23
|
-
return `${year}-${month}-${day}`;
|
|
24
|
-
}
|
|
25
|
-
/** Campos del proveedor validados; emisor y periodo vienen de la consulta autorizada. */
|
|
26
|
-
function normalizeIssuedInvoice(row, issuerRut, period, type) {
|
|
27
|
-
if (row.detTipoDoc !== type || integer(row.detNroDoc) === 0 || integer(row.detRutDoc) === 0 || typeof row.detDvDoc !== 'string' || !/^[\dKk]$/.test(row.detDvDoc)) {
|
|
28
|
-
throw new TypeError('SII_INVALID_RESPONSE');
|
|
29
|
-
}
|
|
30
|
-
if (row.detRznSoc != null && typeof row.detRznSoc !== 'string')
|
|
31
|
-
throw new TypeError('SII_INVALID_RESPONSE');
|
|
32
|
-
let receiverRut;
|
|
33
|
-
try {
|
|
34
|
-
receiverRut = (0, rut_1.parseRut)(`${row.detRutDoc}-${row.detDvDoc}`).formatted;
|
|
35
|
-
}
|
|
36
|
-
catch {
|
|
37
|
-
throw new TypeError('SII_INVALID_RESPONSE');
|
|
38
|
-
}
|
|
39
|
-
return {
|
|
40
|
-
issuerRut, documentType: type, folio: String(row.detNroDoc), issuedDate: date(row.detFchDoc),
|
|
41
|
-
receiverRut, receiverName: typeof row.detRznSoc === 'string' ? row.detRznSoc.trim() || null : null,
|
|
42
|
-
netAmount: nullableAmount(row.detMntNeto), exemptAmount: nullableAmount(row.detMntExe),
|
|
43
|
-
vatAmount: nullableAmount(row.detMntIVA), totalAmount: integer(row.detMntTotal),
|
|
44
|
-
siiBranchCode: row.detCdgSIISucur == null ? null : String(integer(row.detCdgSIISucur)), rcvPeriod: period,
|
|
45
|
-
};
|
|
3
|
+
exports.assertPeriod = assertPeriod;
|
|
4
|
+
function assertPeriod(periodo) {
|
|
5
|
+
if (typeof periodo !== 'string' || !/^\d{4}(0[1-9]|1[0-2])$/.test(periodo) || Number(periodo.slice(0, 4)) < 2017)
|
|
6
|
+
throw new TypeError('Periodo inválido: YYYYMM');
|
|
46
7
|
}
|
|
@@ -1,10 +1,14 @@
|
|
|
1
|
-
import { type
|
|
2
|
-
export type
|
|
3
|
-
export interface
|
|
1
|
+
import { type IssuedInvoicesQuery, type IssuedInvoice, type IssuedInvoicesResult } from './issued-invoice';
|
|
2
|
+
export type ReceivedInvoicesQuery = IssuedInvoicesQuery;
|
|
3
|
+
export interface ReceivedInvoice extends IssuedInvoice {
|
|
4
4
|
issuerName: string | null;
|
|
5
5
|
}
|
|
6
|
-
export interface
|
|
7
|
-
data:
|
|
6
|
+
export interface ReceivedInvoicesResult extends Omit<IssuedInvoicesResult, 'data'> {
|
|
7
|
+
data: ReceivedInvoice[];
|
|
8
8
|
}
|
|
9
|
-
/**
|
|
10
|
-
export
|
|
9
|
+
/** @deprecated Use ReceivedInvoicesQuery. */
|
|
10
|
+
export type ConsultaFacturasRecibidas = ReceivedInvoicesQuery;
|
|
11
|
+
/** @deprecated Use ReceivedInvoice. */
|
|
12
|
+
export type FacturaRecibida = ReceivedInvoice;
|
|
13
|
+
/** @deprecated Use ReceivedInvoicesResult. */
|
|
14
|
+
export type ResultadoFacturasRecibidas = ReceivedInvoicesResult;
|
|
@@ -1,12 +1,2 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.normalizeReceivedInvoice = normalizeReceivedInvoice;
|
|
4
|
-
const issued_invoice_1 = require("./issued-invoice");
|
|
5
|
-
/** In purchases detRutDoc identifies the supplier; the authorized company is the receiver. */
|
|
6
|
-
function normalizeReceivedInvoice(row, receiverRut, period, type) {
|
|
7
|
-
// getDetalleCompra returns detTipoDoc:null for the requested type (observed in RCV).
|
|
8
|
-
if (row.detTipoDoc != null && row.detTipoDoc !== type)
|
|
9
|
-
throw new TypeError('SII_INVALID_RESPONSE');
|
|
10
|
-
const invoice = (0, issued_invoice_1.normalizeIssuedInvoice)({ ...row, detTipoDoc: type }, receiverRut, period, type);
|
|
11
|
-
return { ...invoice, issuerRut: invoice.receiverRut, issuerName: invoice.receiverName, receiverRut, receiverName: null };
|
|
12
|
-
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
declare const STAGES: readonly ["AUTHENTICATION", "SESSION_CHECK", "COMPANY_AUTHORIZATION", "RCV_INITIALIZATION", "RCV_SUMMARY", "RCV_DETAIL", "XML_COMPANY_SELECTION", "XML_DOWNLOAD", "XML_PARSE", "LOGOUT"];
|
|
2
|
-
declare const ENDPOINTS: readonly ["CAutInicio.cgi", "aaSessionService/load", "getDcvEmpresasAutorizadas", "getDatosInicio", "getResumen", "getDetalleCompra", "getDetalleVenta", "mipeSelEmpresa.cgi", "mipeLaunchPage.cgi", "mipeDownLoad.cgi", "autTermino.cgi"];
|
|
3
|
-
declare const REASONS: readonly ["DOCUMENT_LIMIT_EXCEEDED", "DOCUMENT_NOT_FOUND", "EMPTY_RESPONSE", "HTML_RESPONSE", "PROVIDER_ERROR_PAGE", "UNEXPECTED_PDF", "UNEXPECTED_ARCHIVE", "UNEXPECTED_FORMAT", "INVALID_XML", "XML_IDENTITY_MISMATCH", "RESPONSE_TOO_LARGE", "HTTP_ERROR", "TIMEOUT", "TRANSPORT_ERROR", "RETRY_LATER", "CAPTCHA_REQUIRED", "SESSION_REQUIRED", "LOGIN_NOT_CONFIRMED", "PERSONAL_SESSION_REQUIRED", "SESSION_IDENTITY_MISMATCH", "COMPANY_NOT_AUTHORIZED", "COMPANY_SELECTION_REQUIRED", "PROVIDER_REJECTED", "INVALID_RESPONSE"];
|
|
1
|
+
declare const STAGES: readonly ["AUTHENTICATION", "SESSION_CHECK", "COMPANY_AUTHORIZATION", "RCV_INITIALIZATION", "RCV_SUMMARY", "RCV_DETAIL", "XML_COMPANY_SELECTION", "XML_DOWNLOAD", "XML_PARSE", "LOGOUT", "DOCUMENT_PREPARATION", "DOCUMENT_REVIEW", "DOCUMENT_SIGNING", "DOCUMENT_SEND", "DOCUMENT_RECOVERY"];
|
|
2
|
+
declare const ENDPOINTS: readonly ["CAutInicio.cgi", "aaSessionService/load", "getDcvEmpresasAutorizadas", "getDatosInicio", "getResumen", "getDetalleCompra", "getDetalleVenta", "mipeSelEmpresa.cgi", "mipeLaunchPage.cgi", "mipeDownLoad.cgi", "autTermino.cgi", "mipeGenFacEx.cgi", "mipeDisplayPreView.cgi", "mipeGenXMLFirma.cgi", "getCertDigital.cgi", "postFirmaDigital.cgi", "mipeSendXML.cgi", "mipeAdminDocsEmi.cgi", "mipeGesDocEmi.cgi", "mipeDisplayPDF.cgi"];
|
|
3
|
+
declare const REASONS: readonly ["DOCUMENT_LIMIT_EXCEEDED", "DOCUMENT_NOT_FOUND", "EMPTY_RESPONSE", "HTML_RESPONSE", "PROVIDER_ERROR_PAGE", "UNEXPECTED_PDF", "UNEXPECTED_ARCHIVE", "UNEXPECTED_FORMAT", "INVALID_XML", "XML_IDENTITY_MISMATCH", "RESPONSE_TOO_LARGE", "HTTP_ERROR", "TIMEOUT", "TRANSPORT_ERROR", "RETRY_LATER", "CAPTCHA_REQUIRED", "SESSION_REQUIRED", "LOGIN_NOT_CONFIRMED", "PERSONAL_SESSION_REQUIRED", "SESSION_IDENTITY_MISMATCH", "COMPANY_NOT_AUTHORIZED", "COMPANY_SELECTION_REQUIRED", "PROVIDER_REJECTED", "INVALID_RESPONSE", "DOCUMENT_CONTENT_MISMATCH", "CERTIFICATE_UNAVAILABLE", "CERTIFICATE_PASSWORD_INVALID", "CERTIFICATE_EXPIRED", "CERTIFICATE_REVOKED", "SIGNATURE_INVALID", "ISSUANCE_OUTCOME_UNKNOWN"];
|
|
4
4
|
declare const RESPONSE_TYPES: readonly ["XML", "HTML", "PDF", "ZIP", "JSON", "EMPTY", "UNKNOWN"];
|
|
5
5
|
declare const CONTENT_TYPES: readonly ["application/xml", "text/xml", "application/octet-stream", "text/html", "application/pdf", "application/zip", "application/json", "text/plain"];
|
|
6
6
|
export interface SiiDiagnostics {
|
package/dist/domain/sii-error.js
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.SiiError = void 0;
|
|
4
4
|
exports.sanitizeSiiDiagnostics = sanitizeSiiDiagnostics;
|
|
5
|
-
const STAGES = ['AUTHENTICATION', 'SESSION_CHECK', 'COMPANY_AUTHORIZATION', 'RCV_INITIALIZATION', 'RCV_SUMMARY', 'RCV_DETAIL', 'XML_COMPANY_SELECTION', 'XML_DOWNLOAD', 'XML_PARSE', 'LOGOUT'];
|
|
6
|
-
const ENDPOINTS = ['CAutInicio.cgi', 'aaSessionService/load', 'getDcvEmpresasAutorizadas', 'getDatosInicio', 'getResumen', 'getDetalleCompra', 'getDetalleVenta', 'mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi', 'mipeDownLoad.cgi', 'autTermino.cgi'];
|
|
7
|
-
const REASONS = ['DOCUMENT_LIMIT_EXCEEDED', 'DOCUMENT_NOT_FOUND', 'EMPTY_RESPONSE', 'HTML_RESPONSE', 'PROVIDER_ERROR_PAGE', 'UNEXPECTED_PDF', 'UNEXPECTED_ARCHIVE', 'UNEXPECTED_FORMAT', 'INVALID_XML', 'XML_IDENTITY_MISMATCH', 'RESPONSE_TOO_LARGE', 'HTTP_ERROR', 'TIMEOUT', 'TRANSPORT_ERROR', 'RETRY_LATER', 'CAPTCHA_REQUIRED', 'SESSION_REQUIRED', 'LOGIN_NOT_CONFIRMED', 'PERSONAL_SESSION_REQUIRED', 'SESSION_IDENTITY_MISMATCH', 'COMPANY_NOT_AUTHORIZED', 'COMPANY_SELECTION_REQUIRED', 'PROVIDER_REJECTED', 'INVALID_RESPONSE'];
|
|
5
|
+
const STAGES = ['AUTHENTICATION', 'SESSION_CHECK', 'COMPANY_AUTHORIZATION', 'RCV_INITIALIZATION', 'RCV_SUMMARY', 'RCV_DETAIL', 'XML_COMPANY_SELECTION', 'XML_DOWNLOAD', 'XML_PARSE', 'LOGOUT', 'DOCUMENT_PREPARATION', 'DOCUMENT_REVIEW', 'DOCUMENT_SIGNING', 'DOCUMENT_SEND', 'DOCUMENT_RECOVERY'];
|
|
6
|
+
const ENDPOINTS = ['CAutInicio.cgi', 'aaSessionService/load', 'getDcvEmpresasAutorizadas', 'getDatosInicio', 'getResumen', 'getDetalleCompra', 'getDetalleVenta', 'mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi', 'mipeDownLoad.cgi', 'autTermino.cgi', 'mipeGenFacEx.cgi', 'mipeDisplayPreView.cgi', 'mipeGenXMLFirma.cgi', 'getCertDigital.cgi', 'postFirmaDigital.cgi', 'mipeSendXML.cgi', 'mipeAdminDocsEmi.cgi', 'mipeGesDocEmi.cgi', 'mipeDisplayPDF.cgi'];
|
|
7
|
+
const REASONS = ['DOCUMENT_LIMIT_EXCEEDED', 'DOCUMENT_NOT_FOUND', 'EMPTY_RESPONSE', 'HTML_RESPONSE', 'PROVIDER_ERROR_PAGE', 'UNEXPECTED_PDF', 'UNEXPECTED_ARCHIVE', 'UNEXPECTED_FORMAT', 'INVALID_XML', 'XML_IDENTITY_MISMATCH', 'RESPONSE_TOO_LARGE', 'HTTP_ERROR', 'TIMEOUT', 'TRANSPORT_ERROR', 'RETRY_LATER', 'CAPTCHA_REQUIRED', 'SESSION_REQUIRED', 'LOGIN_NOT_CONFIRMED', 'PERSONAL_SESSION_REQUIRED', 'SESSION_IDENTITY_MISMATCH', 'COMPANY_NOT_AUTHORIZED', 'COMPANY_SELECTION_REQUIRED', 'PROVIDER_REJECTED', 'INVALID_RESPONSE', 'DOCUMENT_CONTENT_MISMATCH', 'CERTIFICATE_UNAVAILABLE', 'CERTIFICATE_PASSWORD_INVALID', 'CERTIFICATE_EXPIRED', 'CERTIFICATE_REVOKED', 'SIGNATURE_INVALID', 'ISSUANCE_OUTCOME_UNKNOWN'];
|
|
8
8
|
const RESPONSE_TYPES = ['XML', 'HTML', 'PDF', 'ZIP', 'JSON', 'EMPTY', 'UNKNOWN'];
|
|
9
9
|
const CONTENT_TYPES = ['application/xml', 'text/xml', 'application/octet-stream', 'text/html', 'application/pdf', 'application/zip', 'application/json', 'text/plain'];
|
|
10
10
|
function member(values, value) {
|
|
@@ -32,6 +32,7 @@ const STAGE_LABELS = {
|
|
|
32
32
|
AUTHENTICATION: 'inicio de sesión', SESSION_CHECK: 'validación de sesión', COMPANY_AUTHORIZATION: 'autorización de empresa',
|
|
33
33
|
RCV_INITIALIZATION: 'inicio del RCV', RCV_SUMMARY: 'resumen del RCV', RCV_DETAIL: 'detalle del RCV',
|
|
34
34
|
XML_COMPANY_SELECTION: 'selección de empresa en el facturador', XML_DOWNLOAD: 'descarga del XML', XML_PARSE: 'validación del XML', LOGOUT: 'cierre de sesión',
|
|
35
|
+
DOCUMENT_PREPARATION: 'preparación del documento', DOCUMENT_REVIEW: 'revisión del documento', DOCUMENT_SIGNING: 'firma del documento', DOCUMENT_SEND: 'envío del documento', DOCUMENT_RECOVERY: 'recuperación del documento emitido',
|
|
35
36
|
};
|
|
36
37
|
const REASON_LABELS = {
|
|
37
38
|
DOCUMENT_LIMIT_EXCEEDED: 'SII rechazó la consulta porque devuelve demasiados documentos. No confirmó si el XML individual está disponible.',
|
|
@@ -51,7 +52,12 @@ const REASON_LABELS = {
|
|
|
51
52
|
LOGIN_NOT_CONFIRMED: 'SII no confirmó el inicio de sesión.', PERSONAL_SESSION_REQUIRED: 'SII no confirmó una sesión personal.',
|
|
52
53
|
SESSION_IDENTITY_MISMATCH: 'La sesión de SII no corresponde al usuario solicitado.', COMPANY_NOT_AUTHORIZED: 'SII no autorizó el acceso a la empresa solicitada.',
|
|
53
54
|
COMPANY_SELECTION_REQUIRED: 'SII no confirmó la selección de empresa en el facturador.',
|
|
54
|
-
PROVIDER_REJECTED: 'SII rechazó la
|
|
55
|
+
PROVIDER_REJECTED: 'SII rechazó la solicitud.', INVALID_RESPONSE: 'SII devolvió una respuesta que no cumple el contrato esperado.',
|
|
56
|
+
DOCUMENT_CONTENT_MISMATCH: 'El contenido fiscal recibido difiere del contenido aprobado. No se envió el documento.',
|
|
57
|
+
CERTIFICATE_UNAVAILABLE: 'SII no devolvió un certificado centralizado utilizable para esta identidad.',
|
|
58
|
+
CERTIFICATE_PASSWORD_INVALID: 'SII rechazó la clave del certificado centralizado.', CERTIFICATE_EXPIRED: 'El certificado centralizado está expirado.', CERTIFICATE_REVOKED: 'El certificado centralizado está revocado.',
|
|
59
|
+
SIGNATURE_INVALID: 'SII no devolvió un XML firmado válido para el documento aprobado. No se envió.',
|
|
60
|
+
ISSUANCE_OUTCOME_UNKNOWN: 'El envío comenzó pero no se confirmó su resultado. Conserve el XML y consulte el historial antes de volver a emitir; repetir puede duplicar el documento.',
|
|
55
61
|
};
|
|
56
62
|
class SiiError extends Error {
|
|
57
63
|
code;
|