@devly-cl/sii-client 0.5.0 → 0.7.1
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 +96 -219
- package/dist/application/document-status.d.ts +13 -0
- package/dist/application/document-status.js +50 -0
- package/dist/application/invoice-queries.d.ts +23 -0
- package/dist/application/invoice-queries.js +55 -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/company-info.d.ts +13 -0
- package/dist/domain/company-info.js +2 -0
- package/dist/domain/document-status.d.ts +93 -0
- package/dist/domain/document-status.js +69 -0
- package/dist/domain/document.d.ts +51 -0
- package/dist/domain/document.js +71 -0
- package/dist/domain/invoice-xml.d.ts +34 -11
- package/dist/domain/invoice-xml.js +0 -170
- package/dist/domain/invoicing.d.ts +78 -5
- package/dist/domain/invoicing.js +143 -26
- package/dist/domain/issued-invoice.d.ts +1 -2
- package/dist/domain/issued-invoice.js +4 -43
- package/dist/domain/rcv-document.d.ts +17 -0
- package/dist/domain/rcv-document.js +2 -0
- package/dist/domain/received-invoice.d.ts +1 -3
- package/dist/domain/received-invoice.js +0 -10
- package/dist/index.d.ts +12 -7
- package/dist/index.js +6 -4
- package/dist/infrastructure/document-status-gateway.d.ts +13 -0
- package/dist/infrastructure/document-status-gateway.js +127 -0
- package/dist/infrastructure/document-status-parser.d.ts +12 -0
- package/dist/infrastructure/document-status-parser.js +258 -0
- package/dist/infrastructure/dte-xml.d.ts +11 -0
- package/dist/infrastructure/dte-xml.js +248 -0
- package/dist/infrastructure/facturador-gateway.d.ts +31 -0
- package/dist/infrastructure/facturador-gateway.js +509 -0
- package/dist/infrastructure/facturador.d.ts +13 -3
- package/dist/infrastructure/facturador.js +34 -3
- package/dist/infrastructure/invoice-pdf.d.ts +9 -0
- package/dist/infrastructure/invoice-pdf.js +171 -0
- package/dist/infrastructure/rcv-gateway.d.ts +20 -0
- package/dist/infrastructure/rcv-gateway.js +109 -0
- package/dist/infrastructure/rcv-normalization.d.ts +13 -0
- package/dist/infrastructure/rcv-normalization.js +63 -0
- package/dist/infrastructure/sii-client.d.ts +31 -121
- package/dist/infrastructure/sii-client.js +69 -772
- package/dist/infrastructure/sii-http-session.d.ts +29 -0
- package/dist/infrastructure/sii-http-session.js +359 -0
- package/dist/{domain/sii-error.d.ts → sii-error.d.ts} +3 -3
- package/dist/{domain/sii-error.js → sii-error.js} +14 -4
- package/package.json +45 -45
|
@@ -4,6 +4,48 @@ export interface InvoiceLineInput {
|
|
|
4
4
|
quantity: string;
|
|
5
5
|
unitNetPriceClp: string;
|
|
6
6
|
unit?: string;
|
|
7
|
+
productCode?: {
|
|
8
|
+
type: string;
|
|
9
|
+
value: string;
|
|
10
|
+
};
|
|
11
|
+
additionalTaxCode?: InvoiceAdditionalTaxCode;
|
|
12
|
+
discountPercent?: string;
|
|
13
|
+
}
|
|
14
|
+
export type InvoiceAdditionalTaxCode = 23 | 44 | 24 | 25 | 26 | 27 | 271;
|
|
15
|
+
export declare const INVOICE_ADDITIONAL_TAX_RATES: Readonly<{
|
|
16
|
+
23: "15";
|
|
17
|
+
44: "15";
|
|
18
|
+
24: "31.5";
|
|
19
|
+
25: "20.5";
|
|
20
|
+
26: "20.5";
|
|
21
|
+
27: "10";
|
|
22
|
+
271: "18";
|
|
23
|
+
}>;
|
|
24
|
+
export type InvoiceGlobalDiscount = {
|
|
25
|
+
percent: string;
|
|
26
|
+
amountClp?: never;
|
|
27
|
+
} | {
|
|
28
|
+
amountClp: number;
|
|
29
|
+
percent?: never;
|
|
30
|
+
};
|
|
31
|
+
export type InvoiceReferenceDocumentType = '30' | '32' | '33' | '34' | '35' | '38' | '39' | '40' | '41' | '43' | '45' | '46' | '48' | '50' | '52' | '55' | '56' | '60' | '61' | '103' | '801' | '802' | '803' | '804' | '805' | '806' | '813' | '820' | '821' | '822' | '823' | 'HES';
|
|
32
|
+
export interface InvoiceReferenceInput {
|
|
33
|
+
documentType: InvoiceReferenceDocumentType;
|
|
34
|
+
folio: string;
|
|
35
|
+
date: string;
|
|
36
|
+
reason?: string;
|
|
37
|
+
global?: boolean;
|
|
38
|
+
}
|
|
39
|
+
export interface InvoicePaymentInput {
|
|
40
|
+
date: string;
|
|
41
|
+
amountClp: number;
|
|
42
|
+
description?: string;
|
|
43
|
+
}
|
|
44
|
+
export interface InvoiceTransportInput {
|
|
45
|
+
carrierRut: string;
|
|
46
|
+
licensePlate: string;
|
|
47
|
+
driverRut: string;
|
|
48
|
+
driverName: string;
|
|
7
49
|
}
|
|
8
50
|
export interface InvoiceInput {
|
|
9
51
|
issuedDate: string;
|
|
@@ -12,6 +54,8 @@ export interface InvoiceInput {
|
|
|
12
54
|
commune: string;
|
|
13
55
|
city: string;
|
|
14
56
|
activityCode: string;
|
|
57
|
+
email?: string;
|
|
58
|
+
phone?: string;
|
|
15
59
|
};
|
|
16
60
|
receiver: {
|
|
17
61
|
rut: string;
|
|
@@ -22,10 +66,17 @@ export interface InvoiceInput {
|
|
|
22
66
|
businessActivity: string;
|
|
23
67
|
contact?: string;
|
|
24
68
|
};
|
|
25
|
-
paymentForm: 1 | 2;
|
|
26
|
-
saleType: 1 | 2;
|
|
69
|
+
paymentForm: 1 | 2 | 3;
|
|
70
|
+
saleType: 1 | 2 | 3;
|
|
27
71
|
purchaseType: 1 | 2 | 3 | 4 | 5 | 6 | 7;
|
|
28
72
|
items: InvoiceLineInput[];
|
|
73
|
+
globalDiscount?: InvoiceGlobalDiscount;
|
|
74
|
+
references?: InvoiceReferenceInput[];
|
|
75
|
+
payments?: InvoicePaymentInput[];
|
|
76
|
+
requesterRut?: string;
|
|
77
|
+
transport?: InvoiceTransportInput;
|
|
78
|
+
/** Presentation flag in the SII form; not a tax calculation or an XML identifier. */
|
|
79
|
+
smallBusiness?: boolean;
|
|
29
80
|
}
|
|
30
81
|
export interface InvoiceTotals {
|
|
31
82
|
netAmount: number;
|
|
@@ -38,10 +89,32 @@ export type LineaFactura = InvoiceLineInput;
|
|
|
38
89
|
export type EntradaFactura = InvoiceInput;
|
|
39
90
|
/** @deprecated Use InvoiceTotals. */
|
|
40
91
|
export type TotalesFactura = InvoiceTotals;
|
|
41
|
-
/**
|
|
92
|
+
/** Shared exact arithmetic for the portal and the unsigned/signed XML guard. */
|
|
93
|
+
export declare function invoiceBreakdown(lines: readonly InvoiceLineInput[], discount?: InvoiceGlobalDiscount): {
|
|
94
|
+
totals: Readonly<{
|
|
95
|
+
netAmount: number;
|
|
96
|
+
vatAmount: number;
|
|
97
|
+
totalAmount: number;
|
|
98
|
+
}>;
|
|
99
|
+
subtotal: number;
|
|
100
|
+
discountAmount: number;
|
|
101
|
+
discountPercent: string;
|
|
102
|
+
discountAmountFromPercent: number;
|
|
103
|
+
additionalTaxAmount: number;
|
|
104
|
+
lineAmounts: {
|
|
105
|
+
amount: number;
|
|
106
|
+
discountAmount: number;
|
|
107
|
+
}[];
|
|
108
|
+
taxes: {
|
|
109
|
+
type: InvoiceAdditionalTaxCode;
|
|
110
|
+
rate: "15" | "31.5" | "20.5" | "10" | "18";
|
|
111
|
+
amount: number;
|
|
112
|
+
}[];
|
|
113
|
+
};
|
|
114
|
+
/** Tipo 33, IVA 19%, con opcionales explícitos del facturador gratuito. */
|
|
42
115
|
export declare function validateInvoice(input: unknown): InvoiceInput;
|
|
43
|
-
/** Redondea
|
|
44
|
-
export declare function calculateInvoiceTotals(input: unknown): InvoiceTotals;
|
|
116
|
+
/** Redondea líneas, descuento global, IVA e impuestos adicionales sin decimales binarios. */
|
|
117
|
+
export declare function calculateInvoiceTotals(input: unknown, discount?: InvoiceGlobalDiscount): InvoiceTotals;
|
|
45
118
|
/** Huella determinista del contenido fiscal; el llamador excluye claves y tokens. */
|
|
46
119
|
export declare function hashContent(value: unknown): string;
|
|
47
120
|
/** @deprecated Use validateInvoice. */
|
package/dist/domain/invoicing.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.hashContenido = exports.calcularTotalesFactura = exports.validarFactura = void 0;
|
|
3
|
+
exports.hashContenido = exports.calcularTotalesFactura = exports.validarFactura = exports.INVOICE_ADDITIONAL_TAX_RATES = void 0;
|
|
4
|
+
exports.invoiceBreakdown = invoiceBreakdown;
|
|
4
5
|
exports.validateInvoice = validateInvoice;
|
|
5
6
|
exports.calculateInvoiceTotals = calculateInvoiceTotals;
|
|
6
7
|
exports.hashContent = hashContent;
|
|
7
8
|
const node_crypto_1 = require("node:crypto");
|
|
8
9
|
const rut_1 = require("./rut");
|
|
10
|
+
exports.INVOICE_ADDITIONAL_TAX_RATES = Object.freeze({ 23: '15', 44: '15', 24: '31.5', 25: '20.5', 26: '20.5', 27: '10', 271: '18' });
|
|
9
11
|
const controls = /[\u0000-\u001f\u007f-\u009f]/u;
|
|
10
12
|
function invalid(field) { throw new TypeError(`Factura inválida: ${field}`); }
|
|
11
13
|
function isRecord(value) {
|
|
@@ -30,17 +32,36 @@ function text(value, limit, field, optional = false) {
|
|
|
30
32
|
function requiredText(value, limit, field) {
|
|
31
33
|
return text(value, limit, field) ?? invalid(field);
|
|
32
34
|
}
|
|
33
|
-
function decimal(value, field) {
|
|
35
|
+
function decimal(value, field, allowZero = false) {
|
|
34
36
|
const result = requiredText(value, 12, field);
|
|
35
37
|
const match = /^(\d{1,10})(?:\.(\d{1,2}))?$/.exec(result);
|
|
36
38
|
if (!match)
|
|
37
39
|
invalid(field);
|
|
38
40
|
const integer = match[1].replace(/^0+(?=\d)/u, '');
|
|
39
41
|
const fraction = (match[2] ?? '').replace(/0+$/u, '');
|
|
40
|
-
if (integer === '0' && !fraction)
|
|
42
|
+
if (!allowZero && integer === '0' && !fraction)
|
|
41
43
|
invalid(field);
|
|
42
44
|
return fraction ? `${integer}.${fraction}` : integer;
|
|
43
45
|
}
|
|
46
|
+
function percentage(value, field, allowZero = false) {
|
|
47
|
+
const result = decimal(value, field, allowZero);
|
|
48
|
+
return hundredths(result) <= 10000n ? result : invalid(field);
|
|
49
|
+
}
|
|
50
|
+
function amount(value, field, allowZero = false) {
|
|
51
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < (allowZero ? 0 : 1) || value > 9999999999)
|
|
52
|
+
invalid(field);
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
function globalDiscount(value) {
|
|
56
|
+
if (value === undefined)
|
|
57
|
+
return undefined;
|
|
58
|
+
const source = record(value, ['percent', 'amountClp'], 'globalDiscount');
|
|
59
|
+
if (Object.keys(source).length !== 1)
|
|
60
|
+
invalid('globalDiscount');
|
|
61
|
+
return Object.freeze(source.percent !== undefined
|
|
62
|
+
? { percent: percentage(source.percent, 'globalDiscount.percent', true) }
|
|
63
|
+
: { amountClp: amount(source.amountClp, 'globalDiscount.amountClp', true) });
|
|
64
|
+
}
|
|
44
65
|
function hundredths(value) {
|
|
45
66
|
const [integer, fraction = ''] = value.split('.');
|
|
46
67
|
return BigInt(integer) * 100n + BigInt(fraction.padEnd(2, '0'));
|
|
@@ -49,65 +70,155 @@ function items(value) {
|
|
|
49
70
|
if (!Array.isArray(value) || !value.length || value.length > 10)
|
|
50
71
|
invalid('items');
|
|
51
72
|
return Array.from(value, entry => {
|
|
52
|
-
const source = record(entry, ['name', 'description', 'quantity', 'unitNetPriceClp', 'unit'], 'items');
|
|
73
|
+
const source = record(entry, ['name', 'description', 'quantity', 'unitNetPriceClp', 'unit', 'productCode', 'additionalTaxCode', 'discountPercent'], 'items');
|
|
53
74
|
const description = text(source.description, 999, 'description', true);
|
|
54
75
|
const unit = text(source.unit, 4, 'unit', true);
|
|
76
|
+
const code = source.productCode === undefined ? undefined : record(source.productCode, ['type', 'value'], 'productCode');
|
|
77
|
+
const additionalTaxCode = source.additionalTaxCode;
|
|
78
|
+
if (additionalTaxCode !== undefined && (typeof additionalTaxCode !== 'number' || !Object.hasOwn(exports.INVOICE_ADDITIONAL_TAX_RATES, additionalTaxCode)))
|
|
79
|
+
invalid('additionalTaxCode');
|
|
55
80
|
return Object.freeze({
|
|
56
81
|
name: requiredText(source.name, 25, 'name'),
|
|
57
82
|
...(description === undefined ? {} : { description }),
|
|
58
83
|
quantity: decimal(source.quantity, 'quantity'),
|
|
59
84
|
unitNetPriceClp: decimal(source.unitNetPriceClp, 'unitNetPriceClp'),
|
|
60
85
|
...(unit === undefined ? {} : { unit }),
|
|
86
|
+
...(code === undefined ? {} : { productCode: Object.freeze({ type: requiredText(code.type, 10, 'productCode.type'), value: requiredText(code.value, 15, 'productCode.value') }) }),
|
|
87
|
+
...(additionalTaxCode === undefined ? {} : { additionalTaxCode: additionalTaxCode }),
|
|
88
|
+
...(source.discountPercent === undefined ? {} : { discountPercent: percentage(source.discountPercent, 'discountPercent') }),
|
|
61
89
|
});
|
|
62
90
|
});
|
|
63
91
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
92
|
+
const round = (numerator, denominator) => (numerator + denominator / 2n) / denominator;
|
|
93
|
+
const fromHundredths = (value) => `${value / 100n}.${String(value % 100n).padStart(2, '0')}`.replace(/\.?0+$/, '');
|
|
94
|
+
/** Shared exact arithmetic for the portal and the unsigned/signed XML guard. */
|
|
95
|
+
function invoiceBreakdown(lines, discount) {
|
|
96
|
+
const lineAmounts = lines.map(line => {
|
|
97
|
+
const product = hundredths(line.quantity) * hundredths(line.unitNetPriceClp);
|
|
98
|
+
const pct = hundredths(line.discountPercent ?? '0');
|
|
99
|
+
const result = round(product * (10000n - pct), 100000000n);
|
|
100
|
+
if (result < 1n && pct !== 10000n || result > 9999999999n)
|
|
68
101
|
invalid('lineAmount');
|
|
69
|
-
|
|
70
|
-
|
|
102
|
+
if (line.additionalTaxCode !== undefined && pct > 0n && (pct === 10000n || hundredths(line.unitNetPriceClp) * pct < 1000000n))
|
|
103
|
+
invalid('discountPercent.additionalTax');
|
|
104
|
+
return { amount: Number(result), discountAmount: Number(round(product * pct, 100000000n)) };
|
|
105
|
+
});
|
|
106
|
+
const subtotal = lineAmounts.reduce((sum, line) => sum + BigInt(line.amount), 0n);
|
|
107
|
+
if (subtotal > 9999999999n)
|
|
108
|
+
invalid('subtotal');
|
|
109
|
+
const discountAmount = discount?.amountClp !== undefined ? BigInt(discount.amountClp) : round(subtotal * hundredths(discount?.percent ?? '0'), 10000n);
|
|
110
|
+
if (discountAmount > subtotal)
|
|
111
|
+
invalid('globalDiscount');
|
|
112
|
+
const discountPercent = discount?.percent !== undefined ? hundredths(discount.percent) : subtotal ? round(discountAmount * 10000n, subtotal) : 0n;
|
|
113
|
+
const net = subtotal - discountAmount;
|
|
71
114
|
const vat = (net * 19n + 50n) / 100n;
|
|
72
|
-
const
|
|
73
|
-
|
|
115
|
+
const taxBases = new Map();
|
|
116
|
+
lines.forEach((line, index) => { if (line.additionalTaxCode !== undefined)
|
|
117
|
+
taxBases.set(line.additionalTaxCode, (taxBases.get(line.additionalTaxCode) ?? 0n) + BigInt(lineAmounts[index].amount)); });
|
|
118
|
+
let taxNumerator = 0n;
|
|
119
|
+
const taxes = [...taxBases].map(([type, base]) => {
|
|
120
|
+
const rate = exports.INVOICE_ADDITIONAL_TAX_RATES[type];
|
|
121
|
+
const numerator = base * hundredths(rate) * (10000n - discountPercent);
|
|
122
|
+
taxNumerator += numerator;
|
|
123
|
+
return { type, rate, amount: Number(round(numerator, 100000000n)) };
|
|
124
|
+
});
|
|
125
|
+
const additionalTaxAmount = round(taxNumerator, 100000000n);
|
|
126
|
+
if (taxes.length && additionalTaxAmount < 1n)
|
|
127
|
+
invalid('additionalTaxAmount');
|
|
128
|
+
const total = net + vat + additionalTaxAmount;
|
|
129
|
+
if ((!subtotal && !lines.every(line => line.discountPercent === '100')) || total > 9999999999n)
|
|
74
130
|
invalid('totalAmount');
|
|
75
|
-
return
|
|
131
|
+
return {
|
|
132
|
+
totals: Object.freeze({ netAmount: Number(net), vatAmount: Number(vat), totalAmount: Number(total) }),
|
|
133
|
+
subtotal: Number(subtotal), discountAmount: Number(discountAmount), discountPercent: fromHundredths(discountPercent), discountAmountFromPercent: Number(round(subtotal * discountPercent, 10000n)),
|
|
134
|
+
additionalTaxAmount: Number(additionalTaxAmount), lineAmounts, taxes,
|
|
135
|
+
};
|
|
76
136
|
}
|
|
77
|
-
function
|
|
137
|
+
function civilDate(value, field, minimum, maximum = '9999-12-31') {
|
|
78
138
|
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/u.test(value))
|
|
79
|
-
invalid(
|
|
139
|
+
invalid(field);
|
|
80
140
|
const year = Number(value.slice(0, 4)), month = Number(value.slice(5, 7)), day = Number(value.slice(8, 10));
|
|
81
141
|
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
82
142
|
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
83
|
-
if (
|
|
84
|
-
invalid(
|
|
143
|
+
if (value < minimum || value > maximum || month < 1 || month > 12 || day < 1 || day > days[month - 1])
|
|
144
|
+
invalid(field);
|
|
85
145
|
return value;
|
|
86
146
|
}
|
|
87
|
-
|
|
147
|
+
function smallArray(value, field) {
|
|
148
|
+
if (!Array.isArray(value) || !value.length || value.length > 3)
|
|
149
|
+
invalid(field);
|
|
150
|
+
return Array.from(value);
|
|
151
|
+
}
|
|
152
|
+
const referenceTypes = ['30', '32', '33', '34', '35', '38', '39', '40', '41', '43', '45', '46', '48', '50', '52', '55', '56', '60', '61', '103', '801', '802', '803', '804', '805', '806', '813', '820', '821', '822', '823', 'HES'];
|
|
153
|
+
function references(value) {
|
|
154
|
+
return Object.freeze(smallArray(value, 'references').map(entry => {
|
|
155
|
+
const source = record(entry, ['documentType', 'folio', 'date', 'reason', 'global'], 'reference');
|
|
156
|
+
if (typeof source.documentType !== 'string' || !referenceTypes.includes(source.documentType))
|
|
157
|
+
invalid('reference.documentType');
|
|
158
|
+
if (source.global !== undefined && typeof source.global !== 'boolean')
|
|
159
|
+
invalid('reference.global');
|
|
160
|
+
const folio = requiredText(source.folio, 18, 'reference.folio');
|
|
161
|
+
if (source.global ? folio !== '0' : ['30', '32', '38', '40', '45', '50', '55', '60', '33', '34', '39', '46', '56', '61', '52', '103'].includes(source.documentType) && !/^[1-9]\d*$/.test(folio))
|
|
162
|
+
invalid('reference.folio');
|
|
163
|
+
const reason = text(source.reason, 90, 'reference.reason', true);
|
|
164
|
+
return Object.freeze({ documentType: source.documentType, folio, date: civilDate(source.date, 'reference.date', '2002-08-01', '2050-12-31'), ...(reason === undefined ? {} : { reason }), ...(source.global ? { global: true } : {}) });
|
|
165
|
+
}));
|
|
166
|
+
}
|
|
167
|
+
function payments(value, issued, total) {
|
|
168
|
+
let previous = issued, sum = 0;
|
|
169
|
+
const result = smallArray(value, 'payments').map((entry, index) => {
|
|
170
|
+
const source = record(entry, ['date', 'amountClp', 'description'], 'payment');
|
|
171
|
+
const date = civilDate(source.date, 'payment.date', issued);
|
|
172
|
+
if (index && date <= previous)
|
|
173
|
+
invalid('payment.date');
|
|
174
|
+
previous = date;
|
|
175
|
+
const amountClp = amount(source.amountClp, 'payment.amountClp');
|
|
176
|
+
sum += amountClp;
|
|
177
|
+
const description = text(source.description, 40, 'payment.description', true);
|
|
178
|
+
return Object.freeze({ date, amountClp, ...(description === undefined ? {} : { description }) });
|
|
179
|
+
});
|
|
180
|
+
if (sum !== total)
|
|
181
|
+
invalid('payments.total');
|
|
182
|
+
return Object.freeze(result);
|
|
183
|
+
}
|
|
184
|
+
function transport(value) {
|
|
185
|
+
const source = record(value, ['carrierRut', 'licensePlate', 'driverRut', 'driverName'], 'transport');
|
|
186
|
+
return Object.freeze({ carrierRut: (0, rut_1.parseRut)(requiredText(source.carrierRut, 15, 'transport.carrierRut')).formatted, licensePlate: requiredText(source.licensePlate, 8, 'transport.licensePlate'), driverRut: (0, rut_1.parseRut)(requiredText(source.driverRut, 15, 'transport.driverRut')).formatted, driverName: requiredText(source.driverName, 30, 'transport.driverName') });
|
|
187
|
+
}
|
|
188
|
+
/** Tipo 33, IVA 19%, con opcionales explícitos del facturador gratuito. */
|
|
88
189
|
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');
|
|
190
|
+
const source = record(input, ['issuedDate', 'issuer', 'receiver', 'paymentForm', 'saleType', 'purchaseType', 'items', 'globalDiscount', 'references', 'payments', 'requesterRut', 'transport', 'smallBusiness'], 'input');
|
|
191
|
+
const issuer = record(source.issuer, ['address', 'commune', 'city', 'activityCode', 'email', 'phone'], 'issuer');
|
|
91
192
|
const receiver = record(source.receiver, ['rut', 'legalName', 'address', 'commune', 'city', 'businessActivity', 'contact'], 'receiver');
|
|
92
193
|
const activityCode = requiredText(issuer.activityCode, 6, 'activityCode');
|
|
93
194
|
if (!/^\d{6}$/u.test(activityCode))
|
|
94
195
|
invalid('activityCode');
|
|
95
196
|
const paymentForm = source.paymentForm, saleType = source.saleType, purchaseType = source.purchaseType;
|
|
96
|
-
if (paymentForm !== 1 && paymentForm !== 2)
|
|
197
|
+
if (paymentForm !== 1 && paymentForm !== 2 && paymentForm !== 3)
|
|
97
198
|
invalid('paymentForm');
|
|
98
|
-
if (saleType !== 1 && saleType !== 2)
|
|
199
|
+
if (saleType !== 1 && saleType !== 2 && saleType !== 3)
|
|
99
200
|
invalid('saleType');
|
|
100
201
|
if (purchaseType !== 1 && purchaseType !== 2 && purchaseType !== 3 && purchaseType !== 4 && purchaseType !== 5 && purchaseType !== 6 && purchaseType !== 7)
|
|
101
202
|
invalid('purchaseType');
|
|
102
203
|
const lines = items(source.items);
|
|
103
|
-
|
|
204
|
+
const discount = globalDiscount(source.globalDiscount);
|
|
205
|
+
const totals = invoiceBreakdown(lines, discount).totals;
|
|
206
|
+
const issued = civilDate(source.issuedDate, 'issuedDate', '2017-01-01');
|
|
207
|
+
const email = text(issuer.email, 30, 'issuer.email', true), phone = text(issuer.phone, 14, 'issuer.phone', true);
|
|
208
|
+
if (email !== undefined && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(email))
|
|
209
|
+
invalid('issuer.email');
|
|
210
|
+
if (phone !== undefined && !/^\d[\d ]*$/u.test(phone))
|
|
211
|
+
invalid('issuer.phone');
|
|
212
|
+
if (source.smallBusiness !== undefined && typeof source.smallBusiness !== 'boolean')
|
|
213
|
+
invalid('smallBusiness');
|
|
104
214
|
const contact = text(receiver.contact, 80, 'contact', true);
|
|
105
215
|
const result = {
|
|
106
|
-
issuedDate:
|
|
216
|
+
issuedDate: issued,
|
|
107
217
|
issuer: Object.freeze({
|
|
108
218
|
address: requiredText(issuer.address, 70, 'issuer.address'),
|
|
109
219
|
commune: requiredText(issuer.commune, 20, 'issuer.commune'),
|
|
110
220
|
city: requiredText(issuer.city, 15, 'issuer.city'), activityCode,
|
|
221
|
+
...(email === undefined ? {} : { email }), ...(phone === undefined ? {} : { phone }),
|
|
111
222
|
}),
|
|
112
223
|
receiver: Object.freeze({
|
|
113
224
|
rut: (0, rut_1.parseRut)(requiredText(receiver.rut, 15, 'receiver.rut')).formatted,
|
|
@@ -119,12 +230,18 @@ function validateInvoice(input) {
|
|
|
119
230
|
...(contact === undefined ? {} : { contact }),
|
|
120
231
|
}),
|
|
121
232
|
paymentForm, saleType, purchaseType, items: lines,
|
|
233
|
+
...(discount === undefined ? {} : { globalDiscount: discount }),
|
|
234
|
+
...(source.references === undefined ? {} : { references: references(source.references) }),
|
|
235
|
+
...(source.payments === undefined ? {} : { payments: payments(source.payments, issued, totals.totalAmount) }),
|
|
236
|
+
...(source.transport === undefined ? {} : { transport: transport(source.transport) }),
|
|
237
|
+
...(source.requesterRut === undefined ? {} : { requesterRut: (0, rut_1.parseRut)(requiredText(source.requesterRut, 15, 'requesterRut')).formatted }),
|
|
238
|
+
...(source.smallBusiness === undefined ? {} : { smallBusiness: source.smallBusiness }),
|
|
122
239
|
};
|
|
123
240
|
Object.freeze(result.items);
|
|
124
241
|
return Object.freeze(result);
|
|
125
242
|
}
|
|
126
|
-
/** Redondea
|
|
127
|
-
function calculateInvoiceTotals(input) { return
|
|
243
|
+
/** Redondea líneas, descuento global, IVA e impuestos adicionales sin decimales binarios. */
|
|
244
|
+
function calculateInvoiceTotals(input, discount) { return invoiceBreakdown(items(input), globalDiscount(discount)).totals; }
|
|
128
245
|
/** Huella determinista del contenido fiscal; el llamador excluye claves y tokens. */
|
|
129
246
|
function hashContent(value) {
|
|
130
247
|
const ancestors = new Set();
|
|
@@ -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
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { IssuedInvoice } from './issued-invoice';
|
|
2
|
+
export type RcvDocumentType = 33 | 34 | 61;
|
|
3
|
+
export interface RcvDocumentsQuery {
|
|
4
|
+
periodo: string;
|
|
5
|
+
tokenRecaptcha?: string;
|
|
6
|
+
}
|
|
7
|
+
export interface RcvDocument extends Omit<IssuedInvoice, 'documentType'> {
|
|
8
|
+
documentType: RcvDocumentType;
|
|
9
|
+
issuerName?: string | null;
|
|
10
|
+
}
|
|
11
|
+
export interface RcvDocumentsResult {
|
|
12
|
+
data: RcvDocument[];
|
|
13
|
+
complete: boolean;
|
|
14
|
+
expectedCount: number;
|
|
15
|
+
observedAt: string;
|
|
16
|
+
incompleteDocumentTypes: RcvDocumentType[];
|
|
17
|
+
}
|
|
@@ -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,17 +1,22 @@
|
|
|
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 { CompanyInfo } from './domain/company-info';
|
|
5
|
+
export type { RcvDocumentType, RcvDocument, RcvDocumentsQuery, RcvDocumentsResult } from './domain/rcv-document';
|
|
6
|
+
export type { DocumentQueryOptions, DocumentDirection, DocumentIdentity, DocumentStatusQuery, DocumentVerification, DocumentStatusResult, RecipientEventsQuery, RecipientEvent, RecipientEventsResult, } from './domain/document-status';
|
|
7
|
+
export type { IssuedInvoicePdfQuery, ReceivedInvoicePdfQuery, PdfDownloadOptions, InvoicePdfResult } from './contracts';
|
|
4
8
|
export { parseRut } from './domain/rut';
|
|
5
|
-
export { validateInvoice, calculateInvoiceTotals, hashContent, validarFactura, calcularTotalesFactura, hashContenido } from './domain/invoicing';
|
|
6
|
-
export type { InvoiceInput, InvoiceLineInput, InvoiceTotals, EntradaFactura, LineaFactura, TotalesFactura } from './domain/invoicing';
|
|
9
|
+
export { validateInvoice, calculateInvoiceTotals, hashContent, INVOICE_ADDITIONAL_TAX_RATES, validarFactura, calcularTotalesFactura, hashContenido } from './domain/invoicing';
|
|
10
|
+
export type { InvoiceInput, InvoiceLineInput, InvoiceTotals, InvoiceAdditionalTaxCode, InvoiceGlobalDiscount, InvoiceReferenceDocumentType, InvoiceReferenceInput, InvoicePaymentInput, InvoiceTransportInput, EntradaFactura, LineaFactura, TotalesFactura } from './domain/invoicing';
|
|
7
11
|
export type { DocumentoPreparado, DocumentoFirmado, DocumentoEnviado, FirmaDocumento } from './infrastructure/sii-client';
|
|
8
|
-
export { parseDteXml, parseDteDocumentXml
|
|
12
|
+
export { parseDteXml, parseDteDocumentXml } from './infrastructure/dte-xml';
|
|
13
|
+
export { DteXmlError, MAX_DTE_XML_BYTES } from './domain/invoice-xml';
|
|
9
14
|
export type { ConsultaXmlFacturaEmitida, ConsultaXmlFacturaRecibida, DteInvoiceLine, DteInvoiceDetail, ResultadoXmlFacturaEmitida } from './domain/invoice-xml';
|
|
10
|
-
export type { TipoDocumentoEmitido, ConsultaXmlDocumentoEmitido, DteDocumentDetail, ResultadoXmlDocumentoEmitido } from './domain/invoice-xml';
|
|
15
|
+
export type { TipoDocumentoEmitido, ConsultaXmlDocumentoEmitido, DteDocumentDetail, DteIssuanceOptions, ResultadoXmlDocumentoEmitido } from './domain/invoice-xml';
|
|
11
16
|
export type { ConsultaFacturasEmitidas, FacturaEmitida, ResultadoFacturasEmitidas, TipoFacturaEmitida } from './domain/issued-invoice';
|
|
12
17
|
export type { ConsultaFacturasRecibidas, FacturaRecibida, ResultadoFacturasRecibidas } from './domain/received-invoice';
|
|
13
18
|
export type { ConsultaResumen, CredencialesSii, EmpresaAutorizada, EstadoCompra, Operacion, RegistroSii, RespuestaSii, SesionSii, SiiClientOptions, } from './infrastructure/sii-client';
|
|
14
19
|
export type { SummaryQuery, SiiCredentials, SiiSession, Operation, PurchaseStatus, SiiRecord, SiiResponse, AuthorizedCompany, PreparedDocument, SignedDocument, SentDocument, SignDocumentInput, } from './infrastructure/sii-client';
|
|
15
20
|
export type { IssuedInvoicesQuery, IssuedInvoice, IssuedInvoicesResult, InvoiceDocumentType, } from './domain/issued-invoice';
|
|
16
21
|
export type { ReceivedInvoicesQuery, ReceivedInvoice, ReceivedInvoicesResult, } from './domain/received-invoice';
|
|
17
|
-
export type { IssuedInvoiceXmlQuery, ReceivedInvoiceXmlQuery, InvoiceXmlResult, IssuedDocumentType, IssuedDocumentXmlQuery, IssuedDocumentXmlResult, } from './domain/invoice-xml';
|
|
22
|
+
export type { IssuedInvoiceXmlQuery, ReceivedInvoiceXmlQuery, InvoiceXmlResult, IssuedDocumentType, IssuedDocumentXmlQuery, ReceivedDocumentXmlQuery, IssuedDocumentXmlResult, } from './domain/invoice-xml';
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.MAX_DTE_XML_BYTES = exports.DteXmlError = exports.parseDteDocumentXml = exports.parseDteXml = exports.hashContenido = exports.calcularTotalesFactura = exports.validarFactura = exports.hashContent = exports.calculateInvoiceTotals = exports.validateInvoice = exports.parseRut = exports.sanitizeSiiDiagnostics = exports.SiiError = exports.SiiClient = void 0;
|
|
3
|
+
exports.MAX_DTE_XML_BYTES = exports.DteXmlError = exports.parseDteDocumentXml = exports.parseDteXml = exports.hashContenido = exports.calcularTotalesFactura = exports.validarFactura = exports.INVOICE_ADDITIONAL_TAX_RATES = exports.hashContent = exports.calculateInvoiceTotals = exports.validateInvoice = exports.parseRut = exports.sanitizeSiiDiagnostics = exports.SiiError = exports.SiiClient = void 0;
|
|
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; } });
|
|
@@ -12,11 +12,13 @@ var invoicing_1 = require("./domain/invoicing");
|
|
|
12
12
|
Object.defineProperty(exports, "validateInvoice", { enumerable: true, get: function () { return invoicing_1.validateInvoice; } });
|
|
13
13
|
Object.defineProperty(exports, "calculateInvoiceTotals", { enumerable: true, get: function () { return invoicing_1.calculateInvoiceTotals; } });
|
|
14
14
|
Object.defineProperty(exports, "hashContent", { enumerable: true, get: function () { return invoicing_1.hashContent; } });
|
|
15
|
+
Object.defineProperty(exports, "INVOICE_ADDITIONAL_TAX_RATES", { enumerable: true, get: function () { return invoicing_1.INVOICE_ADDITIONAL_TAX_RATES; } });
|
|
15
16
|
Object.defineProperty(exports, "validarFactura", { enumerable: true, get: function () { return invoicing_1.validarFactura; } });
|
|
16
17
|
Object.defineProperty(exports, "calcularTotalesFactura", { enumerable: true, get: function () { return invoicing_1.calcularTotalesFactura; } });
|
|
17
18
|
Object.defineProperty(exports, "hashContenido", { enumerable: true, get: function () { return invoicing_1.hashContenido; } });
|
|
19
|
+
var dte_xml_1 = require("./infrastructure/dte-xml");
|
|
20
|
+
Object.defineProperty(exports, "parseDteXml", { enumerable: true, get: function () { return dte_xml_1.parseDteXml; } });
|
|
21
|
+
Object.defineProperty(exports, "parseDteDocumentXml", { enumerable: true, get: function () { return dte_xml_1.parseDteDocumentXml; } });
|
|
18
22
|
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
23
|
Object.defineProperty(exports, "DteXmlError", { enumerable: true, get: function () { return invoice_xml_1.DteXmlError; } });
|
|
22
24
|
Object.defineProperty(exports, "MAX_DTE_XML_BYTES", { enumerable: true, get: function () { return invoice_xml_1.MAX_DTE_XML_BYTES; } });
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { DocumentReadPort } from '../application/document-status';
|
|
2
|
+
import type { BoundDocumentStatusQuery, BoundRecipientEventsQuery, DocumentQueryOptions } from '../domain/document-status';
|
|
3
|
+
import { SiiHttpSession } from './sii-http-session';
|
|
4
|
+
/** Read-only personal queries; authentication and company authorization belong to the session. */
|
|
5
|
+
export declare class DocumentStatusGateway implements DocumentReadPort {
|
|
6
|
+
#private;
|
|
7
|
+
private readonly session;
|
|
8
|
+
constructor(session: SiiHttpSession);
|
|
9
|
+
get companyRut(): string;
|
|
10
|
+
assertReady(): void;
|
|
11
|
+
status(query: BoundDocumentStatusQuery, options?: DocumentQueryOptions): Promise<import("../domain/document-status").DocumentVerification>;
|
|
12
|
+
recipientEvents(query: BoundRecipientEventsQuery, options?: DocumentQueryOptions): Promise<import("../domain/document-status").RecipientEventsObservation>;
|
|
13
|
+
}
|