@devly-cl/sii-client 0.5.0 → 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 +36 -4
- 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 +0 -10
- package/dist/domain/invoice-xml.js +0 -170
- package/dist/domain/issued-invoice.d.ts +1 -2
- package/dist/domain/issued-invoice.js +4 -43
- package/dist/domain/received-invoice.d.ts +1 -3
- package/dist/domain/received-invoice.js +0 -10
- package/dist/index.d.ts +5 -3
- package/dist/index.js +4 -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 +10 -3
- package/dist/infrastructure/facturador.js +16 -2
- 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 +22 -121
- package/dist/infrastructure/sii-client.js +45 -774
- 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
|
@@ -32,5 +32,4 @@ export type ConsultaFacturasEmitidas = IssuedInvoicesQuery;
|
|
|
32
32
|
export type FacturaEmitida = IssuedInvoice;
|
|
33
33
|
/** @deprecated Use IssuedInvoicesResult. */
|
|
34
34
|
export type ResultadoFacturasEmitidas = IssuedInvoicesResult;
|
|
35
|
-
|
|
36
|
-
export declare function normalizeIssuedInvoice(row: Record<string, unknown>, issuerRut: string, period: string, type: InvoiceDocumentType): IssuedInvoice;
|
|
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,4 +1,4 @@
|
|
|
1
|
-
import { type IssuedInvoicesQuery, type IssuedInvoice, type IssuedInvoicesResult
|
|
1
|
+
import { type IssuedInvoicesQuery, type IssuedInvoice, type IssuedInvoicesResult } from './issued-invoice';
|
|
2
2
|
export type ReceivedInvoicesQuery = IssuedInvoicesQuery;
|
|
3
3
|
export interface ReceivedInvoice extends IssuedInvoice {
|
|
4
4
|
issuerName: string | null;
|
|
@@ -12,5 +12,3 @@ export type ConsultaFacturasRecibidas = ReceivedInvoicesQuery;
|
|
|
12
12
|
export type FacturaRecibida = ReceivedInvoice;
|
|
13
13
|
/** @deprecated Use ReceivedInvoicesResult. */
|
|
14
14
|
export type ResultadoFacturasRecibidas = ReceivedInvoicesResult;
|
|
15
|
-
/** In purchases detRutDoc identifies the supplier; the authorized company is the receiver. */
|
|
16
|
-
export declare function normalizeReceivedInvoice(row: Record<string, unknown>, receiverRut: string, period: string, type: InvoiceDocumentType): ReceivedInvoice;
|
|
@@ -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
|
-
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
export { SiiClient, SiiError } from './infrastructure/sii-client';
|
|
2
|
-
export { sanitizeSiiDiagnostics } from './
|
|
3
|
-
export type { SiiDiagnostics } from './
|
|
2
|
+
export { sanitizeSiiDiagnostics } from './sii-error';
|
|
3
|
+
export type { SiiDiagnostics } from './sii-error';
|
|
4
|
+
export type { IssuedInvoicePdfQuery, ReceivedInvoicePdfQuery, PdfDownloadOptions, InvoicePdfResult } from './contracts';
|
|
4
5
|
export { parseRut } from './domain/rut';
|
|
5
6
|
export { validateInvoice, calculateInvoiceTotals, hashContent, validarFactura, calcularTotalesFactura, hashContenido } from './domain/invoicing';
|
|
6
7
|
export type { InvoiceInput, InvoiceLineInput, InvoiceTotals, EntradaFactura, LineaFactura, TotalesFactura } from './domain/invoicing';
|
|
7
8
|
export type { DocumentoPreparado, DocumentoFirmado, DocumentoEnviado, FirmaDocumento } from './infrastructure/sii-client';
|
|
8
|
-
export { parseDteXml, parseDteDocumentXml
|
|
9
|
+
export { parseDteXml, parseDteDocumentXml } from './infrastructure/dte-xml';
|
|
10
|
+
export { DteXmlError, MAX_DTE_XML_BYTES } from './domain/invoice-xml';
|
|
9
11
|
export type { ConsultaXmlFacturaEmitida, ConsultaXmlFacturaRecibida, DteInvoiceLine, DteInvoiceDetail, ResultadoXmlFacturaEmitida } from './domain/invoice-xml';
|
|
10
12
|
export type { TipoDocumentoEmitido, ConsultaXmlDocumentoEmitido, DteDocumentDetail, ResultadoXmlDocumentoEmitido } from './domain/invoice-xml';
|
|
11
13
|
export type { ConsultaFacturasEmitidas, FacturaEmitida, ResultadoFacturasEmitidas, TipoFacturaEmitida } from './domain/issued-invoice';
|
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ exports.MAX_DTE_XML_BYTES = exports.DteXmlError = exports.parseDteDocumentXml =
|
|
|
4
4
|
var sii_client_1 = require("./infrastructure/sii-client");
|
|
5
5
|
Object.defineProperty(exports, "SiiClient", { enumerable: true, get: function () { return sii_client_1.SiiClient; } });
|
|
6
6
|
Object.defineProperty(exports, "SiiError", { enumerable: true, get: function () { return sii_client_1.SiiError; } });
|
|
7
|
-
var sii_error_1 = require("./
|
|
7
|
+
var sii_error_1 = require("./sii-error");
|
|
8
8
|
Object.defineProperty(exports, "sanitizeSiiDiagnostics", { enumerable: true, get: function () { return sii_error_1.sanitizeSiiDiagnostics; } });
|
|
9
9
|
var rut_1 = require("./domain/rut");
|
|
10
10
|
Object.defineProperty(exports, "parseRut", { enumerable: true, get: function () { return rut_1.parseRut; } });
|
|
@@ -15,8 +15,9 @@ Object.defineProperty(exports, "hashContent", { enumerable: true, get: function
|
|
|
15
15
|
Object.defineProperty(exports, "validarFactura", { enumerable: true, get: function () { return invoicing_1.validarFactura; } });
|
|
16
16
|
Object.defineProperty(exports, "calcularTotalesFactura", { enumerable: true, get: function () { return invoicing_1.calcularTotalesFactura; } });
|
|
17
17
|
Object.defineProperty(exports, "hashContenido", { enumerable: true, get: function () { return invoicing_1.hashContenido; } });
|
|
18
|
+
var dte_xml_1 = require("./infrastructure/dte-xml");
|
|
19
|
+
Object.defineProperty(exports, "parseDteXml", { enumerable: true, get: function () { return dte_xml_1.parseDteXml; } });
|
|
20
|
+
Object.defineProperty(exports, "parseDteDocumentXml", { enumerable: true, get: function () { return dte_xml_1.parseDteDocumentXml; } });
|
|
18
21
|
var invoice_xml_1 = require("./domain/invoice-xml");
|
|
19
|
-
Object.defineProperty(exports, "parseDteXml", { enumerable: true, get: function () { return invoice_xml_1.parseDteXml; } });
|
|
20
|
-
Object.defineProperty(exports, "parseDteDocumentXml", { enumerable: true, get: function () { return invoice_xml_1.parseDteDocumentXml; } });
|
|
21
22
|
Object.defineProperty(exports, "DteXmlError", { enumerable: true, get: function () { return invoice_xml_1.DteXmlError; } });
|
|
22
23
|
Object.defineProperty(exports, "MAX_DTE_XML_BYTES", { enumerable: true, get: function () { return invoice_xml_1.MAX_DTE_XML_BYTES; } });
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type IssuedInvoiceXmlQuery, type InvoiceXmlResult, type IssuedDocumentXmlQuery, type IssuedDocumentXmlResult } from '../domain/invoice-xml';
|
|
2
|
+
/** Bounded, namespace-aware parsing; no DTD, external entities or network I/O. */
|
|
3
|
+
export declare function parseDteXml(xml: Uint8Array, expected: IssuedInvoiceXmlQuery & {
|
|
4
|
+
issuerRut: string;
|
|
5
|
+
receiverRut?: string;
|
|
6
|
+
}): InvoiceXmlResult;
|
|
7
|
+
/** Issued invoices and credit notes; preserves original bytes and validates fiscal references. */
|
|
8
|
+
export declare function parseDteDocumentXml(xml: Uint8Array, expected: IssuedDocumentXmlQuery & {
|
|
9
|
+
issuerRut: string;
|
|
10
|
+
receiverRut?: string;
|
|
11
|
+
}): IssuedDocumentXmlResult;
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseDteXml = parseDteXml;
|
|
4
|
+
exports.parseDteDocumentXml = parseDteDocumentXml;
|
|
5
|
+
const saxes_1 = require("saxes");
|
|
6
|
+
const rut_1 = require("../domain/rut");
|
|
7
|
+
const invoice_xml_1 = require("../domain/invoice-xml");
|
|
8
|
+
function invalid() { throw new invoice_xml_1.DteXmlError('SII_XML_INVALID'); }
|
|
9
|
+
const children = (node, name) => node.children.filter(n => n.name === name && n.uri === node.uri);
|
|
10
|
+
function one(node, name) {
|
|
11
|
+
const values = children(node, name);
|
|
12
|
+
return values.length === 1 ? values[0] : invalid();
|
|
13
|
+
}
|
|
14
|
+
function text(node, name, required = false, limit = 1000) {
|
|
15
|
+
const values = children(node, name);
|
|
16
|
+
if (values.length > 1 || (required && values.length !== 1))
|
|
17
|
+
invalid();
|
|
18
|
+
if (!values.length)
|
|
19
|
+
return null;
|
|
20
|
+
const value = values[0];
|
|
21
|
+
if (value.children.length || value.text.length > limit || (required && !value.text.trim()))
|
|
22
|
+
invalid();
|
|
23
|
+
return value.text.trim() || null;
|
|
24
|
+
}
|
|
25
|
+
function integer(node, name, required = false) {
|
|
26
|
+
const value = text(node, name, required, 20);
|
|
27
|
+
if (value === null)
|
|
28
|
+
return null;
|
|
29
|
+
const number = Number(value);
|
|
30
|
+
if (!/^\d+$/.test(value) || !Number.isSafeInteger(number))
|
|
31
|
+
invalid();
|
|
32
|
+
return number;
|
|
33
|
+
}
|
|
34
|
+
function decimal(node, name, required = false) {
|
|
35
|
+
const value = text(node, name, required, 40);
|
|
36
|
+
if (value !== null && !/^\d+(?:\.\d+)?$/.test(value))
|
|
37
|
+
invalid();
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
40
|
+
function date(node, name) {
|
|
41
|
+
const value = text(node, name, true, 10);
|
|
42
|
+
const parsed = new Date(`${value}T00:00:00Z`);
|
|
43
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || !Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== value)
|
|
44
|
+
invalid();
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
function lineNumber(node, name) {
|
|
48
|
+
const value = integer(node, name, true);
|
|
49
|
+
return value > 0 ? value : invalid();
|
|
50
|
+
}
|
|
51
|
+
function uniqueLines(items) {
|
|
52
|
+
if (new Set(items.map(item => item.lineNumber)).size !== items.length)
|
|
53
|
+
invalid();
|
|
54
|
+
}
|
|
55
|
+
/** Bounded, namespace-aware parsing; no DTD, external entities or network I/O. */
|
|
56
|
+
function parseDteXml(xml, expected) {
|
|
57
|
+
const parsed = parseDocumentXml(xml, expected, false);
|
|
58
|
+
const documentType = parsed.detail.documentType;
|
|
59
|
+
if (documentType !== 33 && documentType !== 34)
|
|
60
|
+
invalid();
|
|
61
|
+
const { fiscalHeader: _header, hasSignature: _signature, hasTransport: _transport, ...detail } = parsed.detail;
|
|
62
|
+
return { ...parsed, detail: { ...detail, documentType } };
|
|
63
|
+
}
|
|
64
|
+
/** Issued invoices and credit notes; preserves original bytes and validates fiscal references. */
|
|
65
|
+
function parseDteDocumentXml(xml, expected) {
|
|
66
|
+
if (!expected || ![33, 34, 61].includes(expected.documentType))
|
|
67
|
+
invalid();
|
|
68
|
+
return parseDocumentXml(xml, expected, true);
|
|
69
|
+
}
|
|
70
|
+
function parseDocumentXml(xml, expected, allowCreditNotes) {
|
|
71
|
+
if (!(xml instanceof Uint8Array) || !xml.byteLength || xml.byteLength > invoice_xml_1.MAX_DTE_XML_BYTES)
|
|
72
|
+
invalid();
|
|
73
|
+
let root;
|
|
74
|
+
const stack = [];
|
|
75
|
+
let nodes = 0;
|
|
76
|
+
const header = Buffer.from(xml.subarray(0, 200)).toString('latin1');
|
|
77
|
+
const declared = /<\?xml\b[^?]*\bencoding\s*=\s*['"]([^'"]+)['"]/i.exec(header)?.[1]?.toUpperCase() ?? 'UTF-8';
|
|
78
|
+
const encoding = declared === 'UTF-8' || declared === 'UTF8' ? 'UTF-8' : declared === 'ISO-8859-1' ? 'ISO-8859-1' : invalid();
|
|
79
|
+
try {
|
|
80
|
+
const source = encoding === 'ISO-8859-1' ? Buffer.from(xml).toString('latin1') : new TextDecoder('utf-8', { fatal: true }).decode(xml);
|
|
81
|
+
const parser = new saxes_1.SaxesParser({ xmlns: true });
|
|
82
|
+
parser.on('error', invalid);
|
|
83
|
+
parser.on('doctype', invalid);
|
|
84
|
+
parser.on('processinginstruction', invalid);
|
|
85
|
+
parser.on('opentag', tag => {
|
|
86
|
+
if (++nodes > 10000 || stack.length >= 32)
|
|
87
|
+
invalid();
|
|
88
|
+
const node = { name: tag.local, uri: tag.uri, text: '', attributeCount: Object.values(tag.attributes).filter(attribute => attribute.uri !== 'http://www.w3.org/2000/xmlns/').length, children: [] };
|
|
89
|
+
if (stack.length)
|
|
90
|
+
stack[stack.length - 1].children.push(node);
|
|
91
|
+
else if (root)
|
|
92
|
+
invalid();
|
|
93
|
+
else
|
|
94
|
+
root = node;
|
|
95
|
+
stack.push(node);
|
|
96
|
+
});
|
|
97
|
+
const append = (value) => { if (stack.length)
|
|
98
|
+
stack[stack.length - 1].text += value; };
|
|
99
|
+
parser.on('text', append);
|
|
100
|
+
parser.on('cdata', append);
|
|
101
|
+
parser.on('closetag', () => { stack.pop(); });
|
|
102
|
+
parser.write(source).close();
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
invalid();
|
|
106
|
+
}
|
|
107
|
+
if (!root || !['', 'http://www.sii.cl/SiiDte'].includes(root.uri))
|
|
108
|
+
invalid();
|
|
109
|
+
const dtes = root.name === 'DTE' ? [root] : root.name === 'SetDTE' ? children(root, 'DTE') : root.name === 'EnvioDTE' ? children(one(root, 'SetDTE'), 'DTE') : [];
|
|
110
|
+
if (dtes.length !== 1)
|
|
111
|
+
invalid();
|
|
112
|
+
const document = one(dtes[0], 'Documento');
|
|
113
|
+
const headerNode = one(document, 'Encabezado');
|
|
114
|
+
const identity = one(headerNode, 'IdDoc');
|
|
115
|
+
const totals = one(headerNode, 'Totales');
|
|
116
|
+
const issuer = one(headerNode, 'Emisor'), receiver = one(headerNode, 'Receptor');
|
|
117
|
+
const documentType = integer(identity, 'TipoDTE', true);
|
|
118
|
+
const folio = text(identity, 'Folio', true, 20);
|
|
119
|
+
let issuerRut, receiverRut;
|
|
120
|
+
try {
|
|
121
|
+
issuerRut = (0, rut_1.parseRut)(text(issuer, 'RUTEmisor', true, 12)).formatted;
|
|
122
|
+
receiverRut = (0, rut_1.parseRut)(text(receiver, 'RUTRecep', true, 12)).formatted;
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return invalid();
|
|
126
|
+
}
|
|
127
|
+
if ((documentType !== 33 && documentType !== 34 && (!allowCreditNotes || documentType !== 61)) || !/^[1-9]\d{0,19}$/.test(folio))
|
|
128
|
+
invalid();
|
|
129
|
+
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))
|
|
130
|
+
throw new invoice_xml_1.DteXmlError('SII_XML_IDENTITY_MISMATCH');
|
|
131
|
+
const lines = children(document, 'Detalle').map(line => ({
|
|
132
|
+
lineNumber: lineNumber(line, 'NroLinDet'), name: text(line, 'NmbItem', true, 80), description: text(line, 'DscItem'),
|
|
133
|
+
codes: children(line, 'CdgItem').map(code => ({ type: text(code, 'TpoCodigo', true, 10), value: text(code, 'VlrCodigo', true, 35) })),
|
|
134
|
+
quantity: decimal(line, 'QtyItem'), unit: text(line, 'UnmdItem', false, 4), unitPrice: decimal(line, 'PrcItem'),
|
|
135
|
+
discountPercent: decimal(line, 'DescuentoPct'), discountAmount: integer(line, 'DescuentoMonto'),
|
|
136
|
+
surchargePercent: decimal(line, 'RecargoPct'), surchargeAmount: integer(line, 'RecargoMonto'), exemptIndicator: integer(line, 'IndExe'), amount: integer(line, 'MontoItem', true),
|
|
137
|
+
}));
|
|
138
|
+
if (!lines.length || lines.length > 1000)
|
|
139
|
+
invalid();
|
|
140
|
+
const adjustments = children(document, 'DscRcgGlobal').map(node => {
|
|
141
|
+
const movement = text(node, 'TpoMov', true), valueType = text(node, 'TpoValor', true);
|
|
142
|
+
if ((movement !== 'D' && movement !== 'R') || (valueType !== '%' && valueType !== '$'))
|
|
143
|
+
invalid();
|
|
144
|
+
return { lineNumber: lineNumber(node, 'NroLinDR'), movement: movement, description: text(node, 'GlosaDR'), valueType: valueType, value: decimal(node, 'ValorDR', true), exemptIndicator: integer(node, 'IndExeDR') };
|
|
145
|
+
});
|
|
146
|
+
const references = children(document, 'Referencia').map(node => ({
|
|
147
|
+
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),
|
|
148
|
+
}));
|
|
149
|
+
uniqueLines(lines);
|
|
150
|
+
uniqueLines(adjustments);
|
|
151
|
+
uniqueLines(references);
|
|
152
|
+
if (documentType === 61 && (!references.length
|
|
153
|
+
|| references.some(reference => reference.code === null || ![1, 2, 3].includes(reference.code))
|
|
154
|
+
|| (references.some(reference => reference.code === 1 || reference.code === 2) && references.length !== 1)))
|
|
155
|
+
invalid();
|
|
156
|
+
const signatures = dtes[0].children.filter(node => node.name === 'Signature' && node.uri === 'http://www.w3.org/2000/09/xmldsig#');
|
|
157
|
+
if (allowCreditNotes && signatures.length > 1)
|
|
158
|
+
invalid();
|
|
159
|
+
return { xml: new Uint8Array(xml), encoding, detail: {
|
|
160
|
+
issuerRut, documentType: expected.documentType, folio, issuedDate: date(identity, 'FchEmis'), receiverRut,
|
|
161
|
+
hasSignature: signatures.length === 1,
|
|
162
|
+
hasTransport: children(headerNode, 'Transporte').some(node => node.children.length > 0 || node.text.trim().length > 0 || node.attributeCount > 0),
|
|
163
|
+
...(allowCreditNotes ? { fiscalHeader: {
|
|
164
|
+
issuer: { legalName: text(issuer, 'RznSoc'), businessActivity: text(issuer, 'GiroEmis'), activityCode: text(issuer, 'Acteco'), branchCode: text(issuer, 'CdgSIISucur', false, 9), address: text(issuer, 'DirOrigen'), commune: text(issuer, 'CmnaOrigen'), city: text(issuer, 'CiudadOrigen') },
|
|
165
|
+
receiver: { legalName: text(receiver, 'RznSocRecep'), address: text(receiver, 'DirRecep'), commune: text(receiver, 'CmnaRecep'), city: text(receiver, 'CiudadRecep'), businessActivity: text(receiver, 'GiroRecep'), contact: text(receiver, 'Contacto') },
|
|
166
|
+
paymentForm: integer(identity, 'FmaPago'), saleType: integer(identity, 'TpoTranVenta'), purchaseType: integer(identity, 'TpoTranCompra'),
|
|
167
|
+
noDebitReduction: integer(identity, 'IndNoRebaja', children(identity, 'IndNoRebaja').length > 0),
|
|
168
|
+
unapprovedFiscalFields: identity.children.filter(node => node.uri === identity.uri && !['TipoDTE', 'Folio', 'FchEmis', 'FmaPago', 'TpoTranVenta', 'TpoTranCompra', 'IndNoRebaja'].includes(node.name)).map(node => node.name),
|
|
169
|
+
} } : {}),
|
|
170
|
+
netAmount: integer(totals, 'MntNeto'), exemptAmount: integer(totals, 'MntExe'), vatRate: decimal(totals, 'TasaIVA'), vatAmount: integer(totals, 'IVA'), totalAmount: integer(totals, 'MntTotal', true), lines,
|
|
171
|
+
taxes: children(totals, 'ImptoReten').map(node => ({ type: integer(node, 'TipoImp', true), rate: decimal(node, 'TasaImp'), amount: integer(node, 'MontoImp', true) })), adjustments, references,
|
|
172
|
+
} };
|
|
173
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type InvoiceInput } from '../domain/invoicing';
|
|
2
|
+
import { type PreparedDocument, type DocumentContent, type SignedDocument } from '../domain/document';
|
|
3
|
+
import { type IssuedInvoiceXmlQuery, type ReceivedInvoiceXmlQuery, type InvoiceXmlResult, type IssuedDocumentXmlQuery, type IssuedDocumentXmlResult } from '../domain/invoice-xml';
|
|
4
|
+
import type { InvoicingPort } from '../application/issuance';
|
|
5
|
+
import type { IssuedInvoicePdfQuery, ReceivedInvoicePdfQuery, PdfDownloadOptions, InvoicePdfResult } from '../contracts';
|
|
6
|
+
import { SiiHttpSession } from './sii-http-session';
|
|
7
|
+
export declare class FacturadorGateway implements InvoicingPort {
|
|
8
|
+
#private;
|
|
9
|
+
private readonly session;
|
|
10
|
+
private readonly closeSession;
|
|
11
|
+
constructor(session: SiiHttpSession, closeSession: () => Promise<void>);
|
|
12
|
+
assertReady(): void;
|
|
13
|
+
close(): Promise<void>;
|
|
14
|
+
clearPreparation(): void;
|
|
15
|
+
prepareInvoice(input: InvoiceInput): Promise<DocumentContent>;
|
|
16
|
+
prepareCancellationCreditNote({ factura, issuedDate }: {
|
|
17
|
+
factura: IssuedInvoiceXmlQuery;
|
|
18
|
+
issuedDate: string;
|
|
19
|
+
}): Promise<DocumentContent>;
|
|
20
|
+
unsignedDocument(approved: PreparedDocument): Promise<IssuedDocumentXmlResult>;
|
|
21
|
+
signDocument(approved: PreparedDocument, password: string): Promise<SignedDocument>;
|
|
22
|
+
sendDocument(document: SignedDocument, password: string): Promise<void>;
|
|
23
|
+
issuedInvoiceXml(input: IssuedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
|
|
24
|
+
receivedInvoiceXml(input: ReceivedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
|
|
25
|
+
issuedDocumentXml(input: IssuedDocumentXmlQuery): Promise<IssuedDocumentXmlResult>;
|
|
26
|
+
issuedInvoicePdf(input: IssuedInvoicePdfQuery, options?: PdfDownloadOptions): Promise<InvoicePdfResult>;
|
|
27
|
+
receivedInvoicePdf(input: ReceivedInvoicePdfQuery, options?: PdfDownloadOptions): Promise<InvoicePdfResult>;
|
|
28
|
+
}
|