@devly-cl/sii-client 0.6.0 → 0.7.9
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 +113 -251
- package/dist/application/document-status.d.ts +13 -0
- package/dist/application/document-status.js +50 -0
- package/dist/application/invoice-queries.d.ts +11 -5
- package/dist/application/invoice-queries.js +13 -9
- 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 +4 -0
- package/dist/domain/document.js +38 -3
- package/dist/domain/dte-reconciliation.d.ts +5 -0
- package/dist/domain/dte-reconciliation.js +351 -0
- package/dist/domain/invoice-xml.d.ts +133 -1
- package/dist/domain/invoicing.d.ts +78 -5
- package/dist/domain/invoicing.js +143 -26
- package/dist/domain/rcv-document.d.ts +17 -0
- package/dist/domain/rcv-document.js +2 -0
- package/dist/index.d.ts +9 -4
- package/dist/index.js +5 -1
- 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.js +148 -30
- package/dist/infrastructure/facturador-gateway.d.ts +4 -1
- package/dist/infrastructure/facturador-gateway.js +113 -15
- package/dist/infrastructure/facturador.d.ts +4 -1
- package/dist/infrastructure/facturador.js +22 -4
- package/dist/infrastructure/rcv-gateway.d.ts +3 -0
- package/dist/infrastructure/rcv-gateway.js +9 -5
- package/dist/infrastructure/rcv-normalization.d.ts +7 -0
- package/dist/infrastructure/rcv-normalization.js +9 -1
- package/dist/infrastructure/sii-client.d.ts +10 -1
- package/dist/infrastructure/sii-client.js +29 -3
- package/dist/infrastructure/sii-http-session.d.ts +5 -1
- package/dist/infrastructure/sii-http-session.js +75 -27
- package/dist/sii-error.d.ts +4 -3
- package/dist/sii-error.js +11 -4
- package/package.json +45 -45
- package/dist/domain/sii-error.d.ts +0 -27
- package/dist/domain/sii-error.js +0 -82
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
export interface DocumentQueryOptions {
|
|
2
|
+
signal?: AbortSignal;
|
|
3
|
+
}
|
|
4
|
+
export type DocumentDirection = 'ISSUED' | 'RECEIVED';
|
|
5
|
+
export interface DocumentIdentity {
|
|
6
|
+
issuerRut: string;
|
|
7
|
+
receiverRut: string;
|
|
8
|
+
documentType: 33 | 34 | 61;
|
|
9
|
+
folio: string;
|
|
10
|
+
}
|
|
11
|
+
export type DocumentStatusQuery = ({
|
|
12
|
+
direction: 'ISSUED';
|
|
13
|
+
documentType: 33 | 34 | 61;
|
|
14
|
+
folio: string;
|
|
15
|
+
receiverRut: string;
|
|
16
|
+
} | {
|
|
17
|
+
direction: 'RECEIVED';
|
|
18
|
+
documentType: 33 | 34;
|
|
19
|
+
folio: string;
|
|
20
|
+
issuerRut: string;
|
|
21
|
+
}) & {
|
|
22
|
+
issuedDate: string;
|
|
23
|
+
totalAmount: number;
|
|
24
|
+
};
|
|
25
|
+
export type RecipientEventsQuery = {
|
|
26
|
+
direction: 'ISSUED';
|
|
27
|
+
documentType: 33 | 34;
|
|
28
|
+
folio: string;
|
|
29
|
+
} | {
|
|
30
|
+
direction: 'RECEIVED';
|
|
31
|
+
documentType: 33 | 34;
|
|
32
|
+
folio: string;
|
|
33
|
+
issuerRut: string;
|
|
34
|
+
};
|
|
35
|
+
export type DocumentVerification = {
|
|
36
|
+
verification: 'RECEIVED_MATCH';
|
|
37
|
+
cancellation: 'REPORTED' | 'NOT_REPORTED';
|
|
38
|
+
} | {
|
|
39
|
+
verification: 'RECEIVED_MISMATCH' | 'DOCUMENT_NOT_AUTHORIZED';
|
|
40
|
+
cancellation: 'UNCONFIRMED';
|
|
41
|
+
};
|
|
42
|
+
export type DocumentStatusResult = DocumentVerification & {
|
|
43
|
+
document: DocumentIdentity;
|
|
44
|
+
fiscalVerdict: 'NOT_OBSERVED';
|
|
45
|
+
source: 'SII_CONTENT_QUERY';
|
|
46
|
+
observedAt: string;
|
|
47
|
+
};
|
|
48
|
+
export interface RecipientEvent {
|
|
49
|
+
code: string;
|
|
50
|
+
kind: 'CONTENT_ACCEPTANCE' | 'GOODS_RECEIPT' | 'CONTENT_CLAIM' | 'PARTIAL_DELIVERY_CLAIM' | 'TOTAL_DELIVERY_CLAIM' | 'CASH_PAYMENT' | 'CREDIT_NOTE_CANCELLATION' | 'UNKNOWN';
|
|
51
|
+
description: string;
|
|
52
|
+
occurredAtLocal: string | null;
|
|
53
|
+
responsibleRut: string | null;
|
|
54
|
+
}
|
|
55
|
+
export interface RecipientEventsResult {
|
|
56
|
+
document: DocumentIdentity & {
|
|
57
|
+
documentType: 33 | 34;
|
|
58
|
+
};
|
|
59
|
+
siiReceivedAtLocal: string | null;
|
|
60
|
+
timeZone: null;
|
|
61
|
+
indicators: {
|
|
62
|
+
paidInCashReported: boolean | null;
|
|
63
|
+
claimsReported: boolean | null;
|
|
64
|
+
acknowledgementsReported: boolean | null;
|
|
65
|
+
};
|
|
66
|
+
events: RecipientEvent[];
|
|
67
|
+
source: 'SII_RECIPIENT_REGISTRY';
|
|
68
|
+
observedAt: string;
|
|
69
|
+
}
|
|
70
|
+
export type BoundDocumentStatusQuery = DocumentIdentity & {
|
|
71
|
+
direction: DocumentDirection;
|
|
72
|
+
issuedDate: string;
|
|
73
|
+
totalAmount: number;
|
|
74
|
+
};
|
|
75
|
+
export interface BoundRecipientEventsQuery {
|
|
76
|
+
direction: DocumentDirection;
|
|
77
|
+
companyRut: string;
|
|
78
|
+
issuerRut: string;
|
|
79
|
+
documentType: 33 | 34;
|
|
80
|
+
folio: string;
|
|
81
|
+
}
|
|
82
|
+
export type RecipientEventsObservation = Omit<RecipientEventsResult, 'source' | 'observedAt'> & {
|
|
83
|
+
accessAsIssuer: boolean;
|
|
84
|
+
accessAsReceiver: boolean;
|
|
85
|
+
};
|
|
86
|
+
export declare class DocumentQueryError extends Error {
|
|
87
|
+
readonly code: 'SII_DOCUMENT_IDENTITY_MISMATCH' | 'SII_DOCUMENT_ACCESS_DENIED';
|
|
88
|
+
constructor(code: 'SII_DOCUMENT_IDENTITY_MISMATCH' | 'SII_DOCUMENT_ACCESS_DENIED');
|
|
89
|
+
}
|
|
90
|
+
export declare function bindDocumentStatusQuery(companyRut: string, query: DocumentStatusQuery): BoundDocumentStatusQuery;
|
|
91
|
+
export declare function bindRecipientEventsQuery(companyRut: string, query: RecipientEventsQuery): BoundRecipientEventsQuery;
|
|
92
|
+
export declare function assertDocumentQueryOptions(options?: DocumentQueryOptions): void;
|
|
93
|
+
export declare function assertRecipientEventsAccess(query: BoundRecipientEventsQuery, observation: RecipientEventsObservation): void;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DocumentQueryError = void 0;
|
|
4
|
+
exports.bindDocumentStatusQuery = bindDocumentStatusQuery;
|
|
5
|
+
exports.bindRecipientEventsQuery = bindRecipientEventsQuery;
|
|
6
|
+
exports.assertDocumentQueryOptions = assertDocumentQueryOptions;
|
|
7
|
+
exports.assertRecipientEventsAccess = assertRecipientEventsAccess;
|
|
8
|
+
const rut_1 = require("./rut");
|
|
9
|
+
class DocumentQueryError extends Error {
|
|
10
|
+
code;
|
|
11
|
+
constructor(code) {
|
|
12
|
+
super(code);
|
|
13
|
+
this.code = code;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
exports.DocumentQueryError = DocumentQueryError;
|
|
17
|
+
function assertFields(value, allowed, message) {
|
|
18
|
+
if (!value || typeof value !== 'object')
|
|
19
|
+
throw new TypeError(message);
|
|
20
|
+
const prototype = Object.getPrototypeOf(value);
|
|
21
|
+
if (prototype !== Object.prototype && prototype !== null || Reflect.ownKeys(value).some(key => typeof key !== 'string' || !allowed.includes(key) || !Object.hasOwn(Object.getOwnPropertyDescriptor(value, key) ?? {}, 'value')))
|
|
22
|
+
throw new TypeError(message);
|
|
23
|
+
}
|
|
24
|
+
function assertIdentity(direction, documentType, folio, creditNote) {
|
|
25
|
+
if (direction !== 'ISSUED' && direction !== 'RECEIVED' || documentType !== 33 && documentType !== 34 && !(creditNote && direction === 'ISSUED' && documentType === 61))
|
|
26
|
+
throw new TypeError('Dirección o tipo documental inválido');
|
|
27
|
+
if (typeof folio !== 'string' || !/^[1-9]\d{0,9}$/.test(folio))
|
|
28
|
+
throw new TypeError('Folio inválido');
|
|
29
|
+
}
|
|
30
|
+
function bindDocumentStatusQuery(companyRut, query) {
|
|
31
|
+
assertFields(query, ['direction', 'documentType', 'folio', Object.getOwnPropertyDescriptor(query ?? {}, 'direction')?.value === 'RECEIVED' ? 'issuerRut' : 'receiverRut', 'issuedDate', 'totalAmount'], 'Consulta de estado documental inválida');
|
|
32
|
+
assertIdentity(query.direction, query.documentType, query.folio, true);
|
|
33
|
+
const company = (0, rut_1.parseRut)(companyRut).formatted;
|
|
34
|
+
const issuerRut = query.direction === 'ISSUED' ? company : (0, rut_1.parseRut)(query.issuerRut).formatted;
|
|
35
|
+
const receiverRut = query.direction === 'RECEIVED' ? company : (0, rut_1.parseRut)(query.receiverRut).formatted;
|
|
36
|
+
if (typeof query.issuedDate !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(query.issuedDate) || !Number.isFinite(Date.parse(`${query.issuedDate}T00:00:00Z`)) || new Date(`${query.issuedDate}T00:00:00Z`).toISOString().slice(0, 10) !== query.issuedDate)
|
|
37
|
+
throw new TypeError('Fecha de emisión inválida: YYYY-MM-DD');
|
|
38
|
+
if (!Number.isSafeInteger(query.totalAmount) || query.totalAmount < 0)
|
|
39
|
+
throw new TypeError('Monto total inválido: entero CLP no negativo');
|
|
40
|
+
return { direction: query.direction, issuerRut, receiverRut, documentType: query.documentType, folio: query.folio, issuedDate: query.issuedDate, totalAmount: query.totalAmount };
|
|
41
|
+
}
|
|
42
|
+
function bindRecipientEventsQuery(companyRut, query) {
|
|
43
|
+
assertFields(query, Object.getOwnPropertyDescriptor(query ?? {}, 'direction')?.value === 'RECEIVED' ? ['direction', 'documentType', 'folio', 'issuerRut'] : ['direction', 'documentType', 'folio'], 'Consulta de eventos del receptor inválida');
|
|
44
|
+
assertIdentity(query.direction, query.documentType, query.folio, false);
|
|
45
|
+
const company = (0, rut_1.parseRut)(companyRut).formatted;
|
|
46
|
+
return { direction: query.direction, companyRut: company, issuerRut: query.direction === 'ISSUED' ? company : (0, rut_1.parseRut)(query.issuerRut).formatted, documentType: query.documentType, folio: query.folio };
|
|
47
|
+
}
|
|
48
|
+
function assertDocumentQueryOptions(options) {
|
|
49
|
+
if (options === undefined)
|
|
50
|
+
return;
|
|
51
|
+
assertFields(options, ['signal'], 'Opciones de consulta documental inválidas');
|
|
52
|
+
if (options.signal !== undefined && !(options.signal instanceof AbortSignal))
|
|
53
|
+
throw new TypeError('Señal de consulta documental inválida');
|
|
54
|
+
}
|
|
55
|
+
function assertRecipientEventsAccess(query, observation) {
|
|
56
|
+
const document = observation?.document;
|
|
57
|
+
let issuerRut, receiverRut;
|
|
58
|
+
try {
|
|
59
|
+
issuerRut = (0, rut_1.parseRut)(document.issuerRut).formatted;
|
|
60
|
+
receiverRut = (0, rut_1.parseRut)(document.receiverRut).formatted;
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
throw new DocumentQueryError('SII_DOCUMENT_IDENTITY_MISMATCH');
|
|
64
|
+
}
|
|
65
|
+
if (issuerRut !== query.issuerRut || document.documentType !== query.documentType || document.folio !== query.folio || (query.direction === 'ISSUED' ? issuerRut : receiverRut) !== query.companyRut)
|
|
66
|
+
throw new DocumentQueryError('SII_DOCUMENT_IDENTITY_MISMATCH');
|
|
67
|
+
if ((query.direction === 'ISSUED' ? observation.accessAsIssuer : observation.accessAsReceiver) !== true)
|
|
68
|
+
throw new DocumentQueryError('SII_DOCUMENT_ACCESS_DENIED');
|
|
69
|
+
}
|
|
@@ -15,6 +15,10 @@ export interface PreparedDocument {
|
|
|
15
15
|
readonly issuerLegalName?: string;
|
|
16
16
|
readonly issuerBusinessActivity?: string;
|
|
17
17
|
readonly issuerBranchCode?: string;
|
|
18
|
+
readonly issuerContact?: {
|
|
19
|
+
readonly email: string;
|
|
20
|
+
readonly phone: string;
|
|
21
|
+
};
|
|
18
22
|
readonly originalInvoice?: IssuedDocumentXmlResult['detail'];
|
|
19
23
|
readonly reference?: {
|
|
20
24
|
readonly documentType: 33;
|
package/dist/domain/document.js
CHANGED
|
@@ -9,8 +9,10 @@ class DocumentContentMismatchError extends Error {
|
|
|
9
9
|
exports.DocumentContentMismatchError = DocumentContentMismatchError;
|
|
10
10
|
function assertApprovedDocument(document, approved) {
|
|
11
11
|
const d = document.detail;
|
|
12
|
+
if (d.nonBillableAmount || d.previousBalance || (d.periodAmount != null && d.periodAmount !== 0 && d.periodAmount !== d.totalAmount) || (d.payableAmount != null && d.payableAmount !== 0 && d.payableAmount !== d.totalAmount))
|
|
13
|
+
throw new DocumentContentMismatchError();
|
|
12
14
|
const decimal = (value) => value == null ? null : value.replace(/^0+(?=\d)/, '').replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '');
|
|
13
|
-
if (d.issuedDate !== approved.issuedDate || d.netAmount !== approved.netAmount || d.vatAmount !== approved.vatAmount || d.totalAmount !== approved.totalAmount || Number(d.vatRate) !== 19 || d.
|
|
15
|
+
if (d.issuerRut !== approved.issuerRut || d.receiverRut !== approved.receiverRut || d.documentType !== approved.documentType || d.issuedDate !== approved.issuedDate || d.netAmount !== approved.netAmount || d.vatAmount !== approved.vatAmount || d.totalAmount !== approved.totalAmount || Number(d.vatRate) !== 19 || d.exemptAmount || d.fiscalHeader?.noDebitReduction != null || d.fiscalHeader?.unapprovedFiscalFields.length || d.issuanceOptions?.unapprovedFields.length)
|
|
14
16
|
throw new DocumentContentMismatchError();
|
|
15
17
|
if (approved.invoice) {
|
|
16
18
|
const items = approved.invoice.items;
|
|
@@ -21,7 +23,37 @@ function assertApprovedDocument(document, approved) {
|
|
|
21
23
|
throw new DocumentContentMismatchError();
|
|
22
24
|
if (!header || header.issuer.legalName !== approved.issuerLegalName || header.issuer.businessActivity !== approved.issuerBusinessActivity || header.issuer.address !== i.issuer.address || header.issuer.commune !== i.issuer.commune || header.issuer.city !== i.issuer.city || header.issuer.activityCode !== i.issuer.activityCode || header.receiver.legalName !== i.receiver.legalName || header.receiver.businessActivity !== i.receiver.businessActivity || header.receiver.address !== i.receiver.address || header.receiver.commune !== i.receiver.commune || header.receiver.city !== i.receiver.city || (header.receiver.contact ?? '') !== (i.receiver.contact ?? '') || header.paymentForm !== i.paymentForm || header.saleType !== i.saleType || header.purchaseType !== i.purchaseType)
|
|
23
25
|
throw new DocumentContentMismatchError();
|
|
24
|
-
|
|
26
|
+
const breakdown = (0, invoicing_1.invoiceBreakdown)(items, i.globalDiscount);
|
|
27
|
+
if (d.lines.length !== items.length || d.lines.some((line, index) => {
|
|
28
|
+
const item = items[index], expected = breakdown.lineAmounts[index];
|
|
29
|
+
return line.lineNumber !== index + 1 || (0, invoicing_1.hashContent)(line.codes) !== (0, invoicing_1.hashContent)(item.productCode ? [item.productCode] : []) || line.name !== item.name || (line.description ?? '') !== (item.description ?? '') || decimal(line.quantity) !== decimal(item.quantity) || decimal(line.unitPrice) !== decimal(item.unitNetPriceClp) || (line.unit ?? '') !== (item.unit ?? '') || line.amount !== expected.amount || decimal(line.discountPercent ?? '0') !== decimal(item.discountPercent ?? '0') || (line.discountAmount ?? 0) !== expected.discountAmount || line.surchargeAmount || line.surchargePercent && Number(line.surchargePercent) || line.exemptIndicator;
|
|
30
|
+
}))
|
|
31
|
+
throw new DocumentContentMismatchError();
|
|
32
|
+
const taxOrder = (taxes) => taxes.map(tax => ({ ...tax, rate: decimal(tax.rate) })).sort((a, b) => a.type - b.type);
|
|
33
|
+
if ((0, invoicing_1.hashContent)(taxOrder(d.taxes)) !== (0, invoicing_1.hashContent)(taxOrder(breakdown.taxes)))
|
|
34
|
+
throw new DocumentContentMismatchError();
|
|
35
|
+
const adjustment = d.adjustments[0];
|
|
36
|
+
const hasDiscount = breakdown.discountAmount > 0 || Number(breakdown.discountPercent) > 0;
|
|
37
|
+
if (hasDiscount) {
|
|
38
|
+
const matches = adjustment?.valueType === '%'
|
|
39
|
+
? decimal(adjustment.value) === decimal(breakdown.discountPercent) && breakdown.discountAmountFromPercent === breakdown.discountAmount
|
|
40
|
+
: adjustment?.valueType === '$' && breakdown.discountAmount > 0 && decimal(adjustment.value) === String(breakdown.discountAmount);
|
|
41
|
+
if (d.adjustments.length !== 1 || !adjustment || !matches || adjustment.lineNumber !== 1 || adjustment.movement !== 'D' || adjustment.exemptIndicator || adjustment.description !== null && adjustment.description.toLowerCase() !== 'descuento global')
|
|
42
|
+
throw new DocumentContentMismatchError();
|
|
43
|
+
}
|
|
44
|
+
else if (d.adjustments.length)
|
|
45
|
+
throw new DocumentContentMismatchError();
|
|
46
|
+
const references = i.references ?? [];
|
|
47
|
+
if (d.references.length !== references.length || d.references.some((ref, index) => { const expected = references[index]; return ref.lineNumber !== index + 1 || ref.documentType !== expected.documentType || ref.folio !== expected.folio || ref.date !== expected.date || (ref.reason ?? '') !== (expected.reason ?? '') || ref.code !== null; }))
|
|
48
|
+
throw new DocumentContentMismatchError();
|
|
49
|
+
const options = d.issuanceOptions;
|
|
50
|
+
const expectedPayments = (i.payments ?? []).map(payment => ({ date: payment.date, amount: payment.amountClp, description: payment.description ?? null }));
|
|
51
|
+
const expectedTaxCodes = items.flatMap((item, index) => item.additionalTaxCode === undefined ? [] : [{ lineNumber: index + 1, codes: [item.additionalTaxCode] }]);
|
|
52
|
+
const expectedGlobal = references.flatMap((ref, index) => ref.global ? [{ lineNumber: index + 1, indicator: 1 }] : []);
|
|
53
|
+
if (d.hasTransport !== !!i.transport || (0, invoicing_1.hashContent)(options?.transport ?? null) !== (0, invoicing_1.hashContent)(i.transport ?? null) || (options?.requesterRut ?? '') !== (i.requesterRut ?? '') || (0, invoicing_1.hashContent)(options?.payments ?? []) !== (0, invoicing_1.hashContent)(expectedPayments) || (0, invoicing_1.hashContent)(options?.lineTaxCodes ?? []) !== (0, invoicing_1.hashContent)(expectedTaxCodes) || (0, invoicing_1.hashContent)(options?.referenceGlobalIndicators ?? []) !== (0, invoicing_1.hashContent)(expectedGlobal))
|
|
54
|
+
throw new DocumentContentMismatchError();
|
|
55
|
+
const email = approved.issuerContact?.email ?? i.issuer.email ?? '', phone = approved.issuerContact?.phone ?? i.issuer.phone ?? '';
|
|
56
|
+
if ((i.issuer.email !== undefined || options?.issuerEmail != null) && (options?.issuerEmail ?? '') !== email || (i.issuer.phone !== undefined || options?.issuerPhones.length) && (0, invoicing_1.hashContent)(options?.issuerPhones ?? []) !== (0, invoicing_1.hashContent)(phone ? [phone] : []))
|
|
25
57
|
throw new DocumentContentMismatchError();
|
|
26
58
|
}
|
|
27
59
|
else {
|
|
@@ -32,7 +64,10 @@ function assertApprovedDocument(document, approved) {
|
|
|
32
64
|
const header = d.fiscalHeader;
|
|
33
65
|
const originalHeader = original?.fiscalHeader;
|
|
34
66
|
const lines = (values) => values.map(line => ({ ...line, quantity: decimal(line.quantity), unitPrice: decimal(line.unitPrice), discountPercent: decimal(line.discountPercent), surchargePercent: decimal(line.surchargePercent) }));
|
|
35
|
-
|
|
67
|
+
const fiscalOptions = (detail) => ({ issuerEmail: detail.issuanceOptions?.issuerEmail ?? null, issuerPhones: detail.issuanceOptions?.issuerPhones ?? [], requesterRut: detail.issuanceOptions?.requesterRut ?? null, transport: detail.issuanceOptions?.transport ?? null, payments: detail.issuanceOptions?.payments ?? [], lineTaxCodes: detail.issuanceOptions?.lineTaxCodes ?? [] });
|
|
68
|
+
const taxes = (detail) => detail.taxes.map(tax => ({ ...tax, rate: decimal(tax.rate) }));
|
|
69
|
+
const adjustments = (detail) => detail.adjustments.map(adjustment => ({ ...adjustment, value: decimal(adjustment.value) }));
|
|
70
|
+
if (!original || !header || !originalHeader || original.issuanceOptions?.unapprovedFields.length || (0, invoicing_1.hashContent)(lines(d.lines)) !== (0, invoicing_1.hashContent)(lines(original.lines)) || (0, invoicing_1.hashContent)(taxes(d)) !== (0, invoicing_1.hashContent)(taxes(original)) || (0, invoicing_1.hashContent)(adjustments(d)) !== (0, invoicing_1.hashContent)(adjustments(original)) || d.hasTransport !== original.hasTransport || (0, invoicing_1.hashContent)(fiscalOptions(d)) !== (0, invoicing_1.hashContent)(fiscalOptions(original)) || d.issuanceOptions?.referenceGlobalIndicators.length || (0, invoicing_1.hashContent)(header.issuer) !== (0, invoicing_1.hashContent)(originalHeader.issuer) || (0, invoicing_1.hashContent)(header.receiver) !== (0, invoicing_1.hashContent)(originalHeader.receiver) || ['paymentForm', 'saleType', 'purchaseType'].some(field => header[field] !== null && header[field] !== originalHeader[field]))
|
|
36
71
|
throw new DocumentContentMismatchError();
|
|
37
72
|
}
|
|
38
73
|
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { DteFiscalDetail, DteReconciliation } from './invoice-xml';
|
|
2
|
+
/** Positive numeric identity, independent of presentation and JavaScript integer precision. */
|
|
3
|
+
export declare function normalizeDteFolio(value: string): string;
|
|
4
|
+
/** Pure read normalization. Inconsistencies produce diagnostics, never amended declared totals. */
|
|
5
|
+
export declare function reconcileDteDetail(detail: DteFiscalDetail): DteReconciliation;
|
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.normalizeDteFolio = normalizeDteFolio;
|
|
4
|
+
exports.reconcileDteDetail = reconcileDteDetail;
|
|
5
|
+
class Review extends Error {
|
|
6
|
+
code;
|
|
7
|
+
amounts;
|
|
8
|
+
constructor(code, message, amounts) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.amounts = amounts;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function fail(code, message, amounts) { throw new Review(code, message, amounts); }
|
|
15
|
+
const gcd = (a, b) => { while (b)
|
|
16
|
+
[a, b] = [b, a % b]; return a < 0n ? -a : a; };
|
|
17
|
+
const fraction = (n, d = 1n) => { const divisor = gcd(n, d); return { n: n / divisor, d: d / divisor }; };
|
|
18
|
+
const add = (a, b) => fraction(a.n * b.d + b.n * a.d, a.d * b.d);
|
|
19
|
+
const multiply = (a, b) => fraction(a.n * b.n, a.d * b.d);
|
|
20
|
+
const round = (v) => v.n < 0n ? -round({ n: -v.n, d: v.d }) : (v.n * 2n + v.d) / (v.d * 2n);
|
|
21
|
+
function decimal(value) {
|
|
22
|
+
if (typeof value !== 'string' || value.length > 40 || !/^\d+(?:\.\d+)?$/.test(value))
|
|
23
|
+
fail('INVALID_DECIMAL', 'Valor decimal XML inválido o fuera de precisión.');
|
|
24
|
+
const [whole, part = ''] = value.split('.');
|
|
25
|
+
return fraction(BigInt(whole + part), 10n ** BigInt(part.length));
|
|
26
|
+
}
|
|
27
|
+
function money(value, signed = false) {
|
|
28
|
+
if (!Number.isSafeInteger(value) || (!signed && value < 0))
|
|
29
|
+
fail('INVALID_AMOUNT', 'Importe XML fuera del rango entero seguro.');
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
function moneySum(values, signed = false) {
|
|
33
|
+
return money(Number(values.reduce((sum, value) => sum + BigInt(money(value, true)), 0n)), signed);
|
|
34
|
+
}
|
|
35
|
+
function decimalText(value, places = 6) {
|
|
36
|
+
const scale = 10n ** BigInt(places), scaled = round(multiply(value, fraction(scale)));
|
|
37
|
+
return `${scaled / scale}.${String(scaled % scale).padStart(places, '0')}`.replace(/\.?0+$/, '');
|
|
38
|
+
}
|
|
39
|
+
/** Positive numeric identity, independent of presentation and JavaScript integer precision. */
|
|
40
|
+
function normalizeDteFolio(value) {
|
|
41
|
+
if (typeof value !== 'string' || !/^\d{1,20}$/.test(value) || BigInt(value) === 0n)
|
|
42
|
+
throw new Error('SII_FOLIO_INVALID');
|
|
43
|
+
return BigInt(value).toString();
|
|
44
|
+
}
|
|
45
|
+
function lineAdjustment(gross, price, quantity, percent, declared, kind, info) {
|
|
46
|
+
const amount = money(declared ?? 0), pct = decimal(percent ?? '0');
|
|
47
|
+
if (pct.n > pct.d * 100n)
|
|
48
|
+
fail('INVALID_PERCENT', 'Porcentaje de ajuste de línea fuera de rango.');
|
|
49
|
+
if (!pct.n)
|
|
50
|
+
return amount;
|
|
51
|
+
if (declared === null)
|
|
52
|
+
fail('MISSING_ADJUSTMENT_AMOUNT', 'El porcentaje de línea requiere su monto declarado.');
|
|
53
|
+
const rate = fraction(pct.n, pct.d * 100n), unit = multiply(price, rate);
|
|
54
|
+
const candidates = [
|
|
55
|
+
['PERCENT_OF_PRODUCT', round(multiply(gross, rate))],
|
|
56
|
+
['PERCENT_OF_ROUNDED_PRODUCT', round(multiply(fraction(round(gross)), rate))],
|
|
57
|
+
['PER_UNIT_ROUNDING', round(multiply(quantity, fraction(round(multiply(unit, fraction(100n))), 100n)))],
|
|
58
|
+
['PER_UNIT_TRUNCATION', round(multiply(quantity, fraction(unit.n * 100n / unit.d, 100n)))],
|
|
59
|
+
['NET_FIRST_ROUNDING', kind === 'DISCOUNT' ? round(gross) - round(multiply(gross, fraction(rate.d - rate.n, rate.d))) : round(multiply(gross, fraction(rate.d + rate.n, rate.d))) - round(gross)],
|
|
60
|
+
];
|
|
61
|
+
const matched = candidates.find(([, value]) => value === BigInt(amount));
|
|
62
|
+
if (!matched)
|
|
63
|
+
fail('LINE_ADJUSTMENT_MISMATCH', 'El monto del descuento o recargo de línea no coincide con el porcentaje informado.');
|
|
64
|
+
if (matched[0] !== 'PERCENT_OF_PRODUCT')
|
|
65
|
+
info(`${kind}_${matched[0]}`, 'El ajuste declarado concilia con un método de redondeo distinto al porcentaje del producto exacto.');
|
|
66
|
+
return amount;
|
|
67
|
+
}
|
|
68
|
+
/** Largest remainder allocation, with stable original order as the tie breaker. */
|
|
69
|
+
function allocate(weights, target) {
|
|
70
|
+
const total = weights.reduce((s, w) => s + BigInt(w), 0n);
|
|
71
|
+
if (!total) {
|
|
72
|
+
if (target)
|
|
73
|
+
fail('GROSS_ALLOCATION_MISMATCH', 'No hay base para distribuir el neto fiscal.');
|
|
74
|
+
return weights.map(() => 0);
|
|
75
|
+
}
|
|
76
|
+
const parts = weights.map((w, index) => { const product = BigInt(w) * BigInt(target); return { index, amount: Number(product / total), remainder: product % total }; });
|
|
77
|
+
const remaining = target - parts.reduce((s, p) => s + p.amount, 0);
|
|
78
|
+
const ranked = [...parts].sort((a, b) => a.remainder === b.remainder ? a.index - b.index : a.remainder > b.remainder ? -1 : 1);
|
|
79
|
+
for (let i = 0; i < remaining; i++)
|
|
80
|
+
ranked[i].amount++;
|
|
81
|
+
return parts.map(p => p.amount);
|
|
82
|
+
}
|
|
83
|
+
/** Pure read normalization. Inconsistencies produce diagnostics, never amended declared totals. */
|
|
84
|
+
function reconcileDteDetail(detail) {
|
|
85
|
+
const diagnostics = [];
|
|
86
|
+
const declared = {
|
|
87
|
+
netAmount: detail.netAmount, exemptAmount: detail.exemptAmount, vatAmount: detail.vatAmount, totalAmount: detail.totalAmount,
|
|
88
|
+
nonBillableAmount: detail.nonBillableAmount ?? null, periodAmount: detail.periodAmount ?? null, previousBalance: detail.previousBalance ?? null, payableAmount: detail.payableAmount ?? null,
|
|
89
|
+
grossAmounts: detail.grossAmounts ?? null,
|
|
90
|
+
};
|
|
91
|
+
try {
|
|
92
|
+
return { version: 1, status: 'RECONCILED', declared, derived: reconcile(detail, diagnostics), diagnostics };
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
if (!(error instanceof Review))
|
|
96
|
+
throw error;
|
|
97
|
+
if (!diagnostics.some(d => d.severity === 'ERROR' && d.code === error.code))
|
|
98
|
+
diagnostics.push({ code: error.code, severity: 'ERROR', message: error.message, ...error.amounts });
|
|
99
|
+
return { version: 1, status: 'REVIEW_REQUIRED', declared, derived: null, diagnostics };
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function reconcile(detail, diagnostics) {
|
|
103
|
+
const info = (code, message, lineNumber, amounts) => diagnostics.push({ code, severity: 'INFO', message, ...(lineNumber !== undefined ? { lineNumber } : {}), ...amounts });
|
|
104
|
+
if (![33, 34, 61].includes(detail.documentType))
|
|
105
|
+
fail('UNSUPPORTED_DOCUMENT', 'Tipo de documento fuera del alcance de conciliación.');
|
|
106
|
+
if (!detail.lines.length || detail.lines.length > 1000)
|
|
107
|
+
fail('INVALID_LINES', 'Documento sin líneas o con demasiadas líneas.');
|
|
108
|
+
if (detail.documentType === 61 && !detail.references.some(r => /^\d{1,3}$/.test(r.documentType) && Number(r.documentType) < 200 && Number(r.documentType) > 0 && /^[1-9]\d{0,19}$/.test(r.folio) && [1, 2, 3].includes(r.code ?? 0) && r.date <= detail.issuedDate))
|
|
109
|
+
fail('INVALID_FISCAL_REFERENCE', 'La nota de crédito requiere una referencia fiscal original válida.');
|
|
110
|
+
const netAmount = money(detail.netAmount ?? 0), exemptAmount = money(detail.exemptAmount ?? 0), vatAmount = money(detail.vatAmount ?? 0), totalAmount = money(detail.totalAmount);
|
|
111
|
+
if ((detail.documentType === 34 && (netAmount || vatAmount)) || (netAmount && exemptAmount))
|
|
112
|
+
fail('UNSUPPORTED_TAX_SPLIT', 'La combinación de importes afectos y exentos requiere revisión.');
|
|
113
|
+
const exempt = detail.documentType === 34 || (!netAmount && exemptAmount > 0);
|
|
114
|
+
const taxes = detail.taxes.map(tax => {
|
|
115
|
+
if (![18, 23, 24, 25, 26, 27, 271].includes(tax.type))
|
|
116
|
+
fail('UNSUPPORTED_TAX', 'Código de impuesto o retención fuera del alcance de conciliación.');
|
|
117
|
+
money(tax.amount);
|
|
118
|
+
if (tax.rate !== null)
|
|
119
|
+
decimal(tax.rate);
|
|
120
|
+
return { ...tax, kind: tax.type === 18 ? 'ANTICIPATED' : 'ADDITIONAL' };
|
|
121
|
+
});
|
|
122
|
+
if (new Set(taxes.map(t => t.type)).size !== taxes.length)
|
|
123
|
+
fail('DUPLICATE_TAX_TYPE', 'Un mismo impuesto de encabezado aparece más de una vez; requiere revisión de su base.');
|
|
124
|
+
const headerTotal = moneySum([netAmount, exemptAmount, vatAmount, ...taxes.map(t => t.amount)]);
|
|
125
|
+
if (headerTotal !== totalAmount)
|
|
126
|
+
diagnostics.push({ code: 'HEADER_TOTAL_MISMATCH', severity: 'ERROR', message: 'Subtotal, IVA e impuestos adicionales XML no cuadran con el total fiscal.', declaredAmount: totalAmount, derivedAmount: headerTotal });
|
|
127
|
+
const rate = decimal(detail.vatRate ?? (vatAmount ? '19' : '0'));
|
|
128
|
+
const expectedVat = round(multiply(fraction(BigInt(netAmount)), fraction(rate.n, rate.d * 100n)));
|
|
129
|
+
const precise = [];
|
|
130
|
+
let lines = detail.lines.map((source, index) => {
|
|
131
|
+
const lineNumber = source.lineNumber ?? index + 1, quantityText = source.quantity ?? '1', quantity = decimal(quantityText);
|
|
132
|
+
if (!quantity.n)
|
|
133
|
+
fail('INVALID_QUANTITY', 'La cantidad XML debe ser mayor a cero.');
|
|
134
|
+
const amount = money(source.amount), indicator = source.exemptIndicator ?? 0;
|
|
135
|
+
if (![0, 1, 2, 6].includes(indicator))
|
|
136
|
+
fail('UNSUPPORTED_EXEMPT_INDICATOR', 'Indicador de exención o no facturable fuera del alcance de conciliación.');
|
|
137
|
+
if (!exempt && indicator === 1)
|
|
138
|
+
fail('UNSUPPORTED_TAX_SPLIT', 'Las líneas exentas y afectas requieren conciliación separada.');
|
|
139
|
+
let priceText = source.unitPrice;
|
|
140
|
+
if (priceText === null) {
|
|
141
|
+
if (source.discountAmount || source.discountPercent && decimal(source.discountPercent).n || source.surchargeAmount || source.surchargePercent && decimal(source.surchargePercent).n)
|
|
142
|
+
fail('MISSING_UNIT_PRICE', 'Línea sin precio unitario verificable.');
|
|
143
|
+
priceText = decimalText(fraction(BigInt(amount) * quantity.d, quantity.n));
|
|
144
|
+
info('DERIVED_UNIT_PRICE', 'Precio unitario derivado del importe declarado y la cantidad.', lineNumber);
|
|
145
|
+
}
|
|
146
|
+
const price = decimal(priceText), gross = multiply(quantity, price);
|
|
147
|
+
const lineInfo = (code, message) => info(code, message, lineNumber);
|
|
148
|
+
const discount = lineAdjustment(gross, price, quantity, source.discountPercent, source.discountAmount, 'DISCOUNT', lineInfo);
|
|
149
|
+
const surcharge = lineAdjustment(gross, price, quantity, source.surchargePercent, source.surchargeAmount, 'SURCHARGE', lineInfo);
|
|
150
|
+
if (BigInt(discount) > round(gross))
|
|
151
|
+
fail('LINE_DISCOUNT_EXCEEDS_GROSS', 'El descuento supera el importe de la línea.');
|
|
152
|
+
if (round(gross) - BigInt(discount) + BigInt(surcharge) !== BigInt(amount))
|
|
153
|
+
fail('LINE_AMOUNT_MISMATCH', 'Cantidad, precio, descuento y recargo no cuadran con MontoItem.');
|
|
154
|
+
precise.push(add(gross, fraction(BigInt(surcharge - discount))));
|
|
155
|
+
return { lineNumber, quantity: quantityText, unitPrice: priceText, discountPercent: source.discountPercent ?? '0', discountAmount: discount, surchargeAmount: surcharge, netAmount: amount, declaredAmount: amount, category: indicator === 2 ? 'NON_BILLABLE' : indicator === 6 ? 'NON_BILLABLE_DEDUCTION' : exempt || indicator === 1 ? 'EXEMPT' : 'TAXABLE' };
|
|
156
|
+
});
|
|
157
|
+
const nonBillableLines = lines.filter(l => l.category === 'NON_BILLABLE' || l.category === 'NON_BILLABLE_DEDUCTION').map(l => ({ lineNumber: l.lineNumber, amount: l.netAmount, indicator: l.category === 'NON_BILLABLE' ? 2 : 6 }));
|
|
158
|
+
const nonBillableAmount = moneySum(nonBillableLines.map(l => l.amount * (l.indicator === 6 ? -1 : 1)), true);
|
|
159
|
+
if (nonBillableAmount !== money(detail.nonBillableAmount ?? 0, true) || (detail.nonBillableAmount && !nonBillableLines.length))
|
|
160
|
+
fail('NON_BILLABLE_MISMATCH', 'El monto no facturable no cuadra con las líneas XML.');
|
|
161
|
+
const periodAmount = moneySum([totalAmount, nonBillableAmount]);
|
|
162
|
+
const payableAmount = moneySum([periodAmount, detail.previousBalance ?? 0]);
|
|
163
|
+
if (detail.periodAmount && detail.periodAmount !== periodAmount || detail.payableAmount && detail.payableAmount !== payableAmount)
|
|
164
|
+
fail('PAYABLE_TOTAL_MISMATCH', 'El valor a pagar no cuadra con los totalizadores XML.');
|
|
165
|
+
for (const [field, expected] of [['periodAmount', periodAmount], ['payableAmount', payableAmount]]) {
|
|
166
|
+
if (detail[field] === 0 && expected !== 0)
|
|
167
|
+
info('ZERO_OPTIONAL_PAYMENT_TOTAL', `Totalizador opcional ${field} en cero conservado como declarado; el valor derivado no acredita pagos.`, undefined, { declaredAmount: 0, derivedAmount: expected });
|
|
168
|
+
}
|
|
169
|
+
const fiscalLines = lines.filter(l => l.category !== 'NON_BILLABLE' && l.category !== 'NON_BILLABLE_DEDUCTION');
|
|
170
|
+
const lineTotal = money(fiscalLines.reduce((s, l) => s + l.netAmount, 0));
|
|
171
|
+
let discount = 0, globalSurcharge = 0;
|
|
172
|
+
for (const adjustment of detail.adjustments) {
|
|
173
|
+
if (!['D', 'R'].includes(adjustment.movement) || adjustment.exemptIndicator != null && !(exempt && adjustment.exemptIndicator === 1) || !['$', '%'].includes(adjustment.valueType))
|
|
174
|
+
fail('UNSUPPORTED_GLOBAL_ADJUSTMENT', 'El ajuste global requiere conciliación de su alcance y tipo.');
|
|
175
|
+
const value = decimal(adjustment.value);
|
|
176
|
+
if (adjustment.valueType === '$' && value.n % value.d || adjustment.valueType === '%' && value.n > value.d * 100n)
|
|
177
|
+
fail('INVALID_GLOBAL_DISCOUNT', 'El ajuste global requiere un importe entero CLP o un porcentaje entre cero y cien.');
|
|
178
|
+
const amount = adjustment.valueType === '$' ? Number(value.n / value.d) : Number(round(multiply(fraction(BigInt(lineTotal - discount + globalSurcharge)), fraction(value.n, value.d * 100n))));
|
|
179
|
+
if (adjustment.movement === 'D')
|
|
180
|
+
discount = money(discount + amount);
|
|
181
|
+
else
|
|
182
|
+
globalSurcharge = money(globalSurcharge + amount);
|
|
183
|
+
money(lineTotal - discount + globalSurcharge);
|
|
184
|
+
}
|
|
185
|
+
if (discount && globalSurcharge)
|
|
186
|
+
fail('MIXED_GLOBAL_ADJUSTMENTS', 'La combinación de descuentos y recargos globales requiere revisión de su distribución.');
|
|
187
|
+
const subtotal = netAmount + exemptAmount;
|
|
188
|
+
const inferred = detail.grossAmounts === undefined && !exempt && !taxes.length && !nonBillableLines.length && netAmount > 0 && vatAmount > 0 && rate.n === 19n * rate.d && lineTotal - discount + globalSurcharge === totalAmount;
|
|
189
|
+
if (BigInt(vatAmount) !== expectedVat) {
|
|
190
|
+
// Gross historic documents may total independently rounded VAT per line.
|
|
191
|
+
const truncatedVat = BigInt(vatAmount) === BigInt(netAmount) * rate.n / (rate.d * 100n);
|
|
192
|
+
const preciseNet = precise.reduce((sum, value, index) => lines[index].category === 'TAXABLE' ? add(sum, value) : sum, fraction(0n));
|
|
193
|
+
const preciseVat = !truncatedVat && !discount && !globalSurcharge && !exempt && !detail.grossAmounts && !inferred && detail.vatRate != null
|
|
194
|
+
&& detail.lines.every((source, index) => lines[index].category !== 'TAXABLE' || source.quantity != null && source.unitPrice != null)
|
|
195
|
+
&& round(preciseNet) === BigInt(netAmount) && round(multiply(preciseNet, fraction(rate.n, rate.d * 100n))) === BigInt(vatAmount);
|
|
196
|
+
const perLineVat = !truncatedVat && !discount && !globalSurcharge && (detail.grossAmounts || inferred) && !taxes.length
|
|
197
|
+
? ['NEAREST', 'CEILING', 'FLOOR', 'PER_UNIT_NEAREST'].find(method => fiscalLines.reduce((sum, line) => {
|
|
198
|
+
const value = fraction(BigInt(line.declaredAmount) * rate.n, rate.d * 100n + rate.n);
|
|
199
|
+
if (method === 'PER_UNIT_NEAREST') {
|
|
200
|
+
if (line.discountAmount || line.surchargeAmount)
|
|
201
|
+
return -1n;
|
|
202
|
+
const unitTax = round(multiply(decimal(line.unitPrice), fraction(rate.n, rate.d * 100n + rate.n)));
|
|
203
|
+
return sum + round(multiply(fraction(unitTax), decimal(line.quantity)));
|
|
204
|
+
}
|
|
205
|
+
return sum + (method === 'NEAREST' ? round(value) : method === 'CEILING' ? (value.n + value.d - 1n) / value.d : value.n / value.d);
|
|
206
|
+
}, 0n) === BigInt(vatAmount)) : undefined;
|
|
207
|
+
if (!truncatedVat && !perLineVat && !preciseVat)
|
|
208
|
+
fail('VAT_MISMATCH', 'El IVA del XML no cuadra con el neto fiscal y la tasa declarada.');
|
|
209
|
+
if (preciseVat)
|
|
210
|
+
info('VAT_PRECISE_PRODUCTS', 'El IVA declarado concilia al aplicar la tasa a la suma exacta de cantidad por precio y ajustes de línea, antes de redondear el neto.');
|
|
211
|
+
else
|
|
212
|
+
info(truncatedVat ? 'VAT_TRUNCATED' : `VAT_PER_GROSS_LINE_${perLineVat}`, truncatedVat ? 'El IVA declarado concilia con truncamiento del impuesto sobre el neto fiscal.' : 'El IVA declarado concilia al totalizar el impuesto por cada línea bruta.');
|
|
213
|
+
}
|
|
214
|
+
let globalDiscount;
|
|
215
|
+
let surcharge;
|
|
216
|
+
let lineRounding;
|
|
217
|
+
if (detail.grossAmounts || inferred) {
|
|
218
|
+
if (taxes.length || exempt || lineTotal - discount + globalSurcharge !== totalAmount)
|
|
219
|
+
fail('GROSS_TOTAL_MISMATCH', 'Las líneas y ajustes globales no cuadran con el total bruto del XML.');
|
|
220
|
+
const netBeforeDiscount = discount || globalSurcharge ? Number(round(fraction(BigInt(lineTotal) * rate.d * 100n, rate.d * 100n + rate.n))) : subtotal;
|
|
221
|
+
if (discount && netBeforeDiscount < subtotal || globalSurcharge && netBeforeDiscount > subtotal)
|
|
222
|
+
fail('GROSS_DISCOUNT_MISMATCH', 'El ajuste global bruto no conserva el neto fiscal.');
|
|
223
|
+
const allocated = allocate(fiscalLines.map(l => l.netAmount), netBeforeDiscount);
|
|
224
|
+
let fiscalIndex = 0;
|
|
225
|
+
lines = lines.map(l => {
|
|
226
|
+
if (l.category === 'NON_BILLABLE' || l.category === 'NON_BILLABLE_DEDUCTION')
|
|
227
|
+
return l;
|
|
228
|
+
const net = allocated[fiscalIndex++], quantity = decimal(l.quantity);
|
|
229
|
+
const lineDiscount = Number(round(fraction(BigInt(l.discountAmount) * rate.d * 100n, rate.d * 100n + rate.n)));
|
|
230
|
+
const surcharge = Number(round(fraction(BigInt(l.surchargeAmount) * rate.d * 100n, rate.d * 100n + rate.n)));
|
|
231
|
+
const price = decimalText(fraction(BigInt(net + lineDiscount - surcharge) * quantity.d, quantity.n));
|
|
232
|
+
if (round(multiply(quantity, decimal(price))) - BigInt(lineDiscount) + BigInt(surcharge) !== BigInt(net))
|
|
233
|
+
fail('GROSS_PRICE_PRECISION', 'La conversión de precio bruto no conserva el importe neto de línea.');
|
|
234
|
+
return { ...l, unitPrice: price, discountAmount: lineDiscount, surchargeAmount: surcharge, netAmount: net };
|
|
235
|
+
});
|
|
236
|
+
if (discount)
|
|
237
|
+
globalDiscount = { netAmount: netBeforeDiscount - subtotal, grossAmount: discount };
|
|
238
|
+
if (globalSurcharge)
|
|
239
|
+
surcharge = { netAmount: subtotal - netBeforeDiscount, grossAmount: globalSurcharge };
|
|
240
|
+
info(inferred ? 'GROSS_AMOUNTS_INFERRED' : 'GROSS_AMOUNTS_CONVERTED', 'Líneas brutas convertidas contra los totales fiscales declarados, conservando cantidades y XML.');
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
if (discount)
|
|
244
|
+
globalDiscount = { netAmount: discount };
|
|
245
|
+
if (globalSurcharge)
|
|
246
|
+
surcharge = { netAmount: globalSurcharge };
|
|
247
|
+
if (lineTotal - discount + globalSurcharge !== subtotal) {
|
|
248
|
+
const preciseTotal = precise.reduce((s, v, index) => lines[index].category.startsWith('NON_BILLABLE') ? s : add(s, v), fraction(0n));
|
|
249
|
+
if (Number(round(preciseTotal)) - discount + globalSurcharge !== subtotal)
|
|
250
|
+
fail('LINE_SUBTOTAL_MISMATCH', 'Las líneas y ajustes XML no cuadran con el subtotal fiscal.');
|
|
251
|
+
lineRounding = subtotal - (lineTotal - discount + globalSurcharge);
|
|
252
|
+
info('PRECISE_SUBTOTAL_ROUNDING', 'El subtotal concilia al sumar los productos exactos antes de redondear, en lugar de sumar MontoItem redondeados.', undefined, { declaredAmount: subtotal, derivedAmount: lineTotal - discount + globalSurcharge });
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
for (const source of detail.lines) {
|
|
256
|
+
const codes = source.additionalTaxCodes ?? [];
|
|
257
|
+
if (codes.length > 2 || new Set(codes).size !== codes.length)
|
|
258
|
+
fail('INVALID_LINE_TAX_CODES', 'Códigos de impuesto de línea duplicados o fuera de alcance.');
|
|
259
|
+
for (const code of codes) {
|
|
260
|
+
if (![18, 23, 24, 25, 26, 27, 271].includes(code))
|
|
261
|
+
fail('UNSUPPORTED_LINE_TAX', 'Código de impuesto de línea fuera del alcance de conciliación.');
|
|
262
|
+
if (!taxes.some(t => t.type === code))
|
|
263
|
+
fail('MISSING_HEADER_TAX', 'Un impuesto de línea no tiene su monto declarado en el encabezado.');
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
const distinctCodes = new Set(detail.lines.flatMap(source => source.additionalTaxCodes ?? []));
|
|
267
|
+
const fixedMixedAdjustment = distinctCodes.size > 1 && detail.adjustments.some(adjustment => adjustment.valueType === '$' && decimal(adjustment.value).n !== 0n);
|
|
268
|
+
if (fixedMixedAdjustment) {
|
|
269
|
+
const code = 'GLOBAL_ADJUSTMENT_REQUIRES_PERCENT';
|
|
270
|
+
const message = 'El descuento o recargo global está expresado en un monto fijo para ítems con distintos impuestos. Se conservan los impuestos declarados; su reparto por línea no es verificable.';
|
|
271
|
+
diagnostics.unshift({ code, severity: 'INFO', message });
|
|
272
|
+
}
|
|
273
|
+
for (const tax of taxes) {
|
|
274
|
+
const scope = detail.lines.flatMap((source, index) => source.additionalTaxCodes?.includes(tax.type) ? [index] : []);
|
|
275
|
+
if (!scope.length || scope.some(i => lines[i].category !== 'TAXABLE'))
|
|
276
|
+
fail('MISSING_TAX_BASE', 'La base del impuesto adicional no puede identificarse en las líneas fiscales.');
|
|
277
|
+
if (tax.rate === null) {
|
|
278
|
+
if (tax.amount)
|
|
279
|
+
fail('MISSING_TAX_RATE', 'El impuesto adicional requiere su tasa declarada para conciliar la base.');
|
|
280
|
+
info('ZERO_TAX_WITHOUT_RATE', 'Impuesto declarado en cero sin tasa; no se deriva una tasa del documento.');
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
const percentage = decimal(tax.rate);
|
|
284
|
+
if (percentage.n > percentage.d * 100n)
|
|
285
|
+
fail('INVALID_TAX_RATE', 'Tasa de impuesto adicional fuera de alcance.');
|
|
286
|
+
if (!percentage.n && tax.amount)
|
|
287
|
+
fail('TAX_AMOUNT_MISMATCH', 'Un impuesto con tasa cero no puede tener un monto positivo.', { declaredAmount: tax.amount, derivedAmount: 0 });
|
|
288
|
+
if (!lineTotal && (discount || globalSurcharge))
|
|
289
|
+
fail('MISSING_TAX_BASE', 'No hay base de líneas para distribuir el ajuste global del impuesto.');
|
|
290
|
+
if (fixedMixedAdjustment)
|
|
291
|
+
continue;
|
|
292
|
+
const taxRate = fraction(percentage.n, percentage.d * 100n);
|
|
293
|
+
const prorate = (amount) => discount || globalSurcharge ? multiply(amount, fraction(BigInt(subtotal), BigInt(lineTotal))) : amount;
|
|
294
|
+
const base = prorate(fraction(scope.reduce((s, i) => s + BigInt(lines[i].netAmount), 0n)));
|
|
295
|
+
const computed = multiply(base, taxRate);
|
|
296
|
+
const exactBase = !detail.grossAmounts && !inferred ? prorate(scope.reduce((s, i) => add(s, precise[i]), fraction(0n))) : base;
|
|
297
|
+
const candidates = [
|
|
298
|
+
['GROUP_NEAREST', round(computed)],
|
|
299
|
+
['GROUP_TRUNCATED', computed.n / computed.d],
|
|
300
|
+
['GROUP_CEILING', (computed.n + computed.d - 1n) / computed.d],
|
|
301
|
+
['PRECISE_PRODUCTS', round(multiply(exactBase, taxRate))],
|
|
302
|
+
['PER_LINE_NEAREST', scope.reduce((s, i) => s + round(multiply(prorate(fraction(BigInt(lines[i].netAmount))), taxRate)), 0n)],
|
|
303
|
+
];
|
|
304
|
+
const method = candidates.find(([, value]) => value === BigInt(tax.amount));
|
|
305
|
+
if (!method)
|
|
306
|
+
fail(discount || globalSurcharge ? 'TAX_BASE_REVIEW_REQUIRED' : 'TAX_AMOUNT_MISMATCH', discount || globalSurcharge ? 'La distribución proporcional del ajuste global no explica el impuesto declarado; requiere verificar el alcance del ajuste sobre su base.' : 'El impuesto adicional no concilia con sus líneas y tasa declaradas.', { declaredAmount: tax.amount, derivedAmount: Number(round(computed)) });
|
|
307
|
+
if (method[0] !== 'GROUP_NEAREST')
|
|
308
|
+
info(`TAX_${method[0]}`, 'El impuesto adicional concilia con un método de redondeo distinto al del grupo de líneas.', undefined, { declaredAmount: tax.amount, derivedAmount: Number(round(computed)) });
|
|
309
|
+
}
|
|
310
|
+
let totalRounding;
|
|
311
|
+
if (headerTotal !== totalAmount) {
|
|
312
|
+
const difference = totalAmount - headerTotal;
|
|
313
|
+
// Global adjustments lack structured per-line allocation; never guess their scope to explain a total.
|
|
314
|
+
if ((difference === -1 || difference === 1) && !detail.adjustments.length && !detail.grossAmounts && !inferred && lineRounding === undefined && (!fiscalLines.some(line => line.category === 'TAXABLE') || detail.vatRate != null) && taxes.every(t => t.rate !== null)) {
|
|
315
|
+
const taxRates = new Map(taxes.map(t => { const percentage = decimal(t.rate); return [t.type, fraction(percentage.n, percentage.d * 100n)]; }));
|
|
316
|
+
const vatFactor = fraction(rate.d * 100n + rate.n, rate.d * 100n);
|
|
317
|
+
for (const basis of ['DECLARED_LINE_AMOUNTS', 'EXACT_PRODUCTS']) {
|
|
318
|
+
if (basis === 'EXACT_PRODUCTS' && detail.lines.some((source, i) => !lines[i].category.startsWith('NON_BILLABLE') && (source.unitPrice == null || source.quantity == null)))
|
|
319
|
+
continue;
|
|
320
|
+
let candidate = 0n;
|
|
321
|
+
for (let i = 0; i < lines.length; i++) {
|
|
322
|
+
const line = lines[i];
|
|
323
|
+
if (line.category.startsWith('NON_BILLABLE'))
|
|
324
|
+
continue;
|
|
325
|
+
const base = basis === 'DECLARED_LINE_AMOUNTS' ? fraction(BigInt(line.netAmount)) : precise[i];
|
|
326
|
+
candidate += round(line.category === 'EXEMPT' ? base : multiply(base, vatFactor));
|
|
327
|
+
for (const code of detail.lines[i].additionalTaxCodes ?? [])
|
|
328
|
+
candidate += round(multiply(base, taxRates.get(code)));
|
|
329
|
+
}
|
|
330
|
+
if (candidate === BigInt(totalAmount)) {
|
|
331
|
+
totalRounding = { difference, method: 'PER_LINE_VAT_AND_TAX', basis, componentTotal: headerTotal };
|
|
332
|
+
const diagnostic = diagnostics.find(d => d.code === 'HEADER_TOTAL_MISMATCH');
|
|
333
|
+
diagnostic.code = 'TOTAL_ROUNDING_EXPLAINED';
|
|
334
|
+
diagnostic.severity = 'INFO';
|
|
335
|
+
diagnostic.message = 'El total declarado concilia al sumar por línea el importe con IVA y sus impuestos adicionales redondeados. Se conservan todos los valores originales y la diferencia frente a sumar los totalizadores.';
|
|
336
|
+
break;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
if (!totalRounding) {
|
|
341
|
+
const originalLineValues = detail.lines.every((source, i) => lines[i].category.startsWith('NON_BILLABLE') || source.quantity != null && source.unitPrice != null);
|
|
342
|
+
if ((difference !== -1 && difference !== 1) || detail.grossAmounts || inferred || !originalLineValues || fiscalLines.some(line => line.category === 'TAXABLE') && detail.vatRate == null || taxes.some(t => t.rate === null))
|
|
343
|
+
fail('HEADER_TOTAL_MISMATCH', 'Subtotal, IVA e impuestos adicionales XML no cuadran con el total fiscal.', { declaredAmount: totalAmount, derivedAmount: headerTotal });
|
|
344
|
+
const diagnostic = diagnostics.find(d => d.code === 'HEADER_TOTAL_MISMATCH');
|
|
345
|
+
diagnostic.severity = 'INFO';
|
|
346
|
+
diagnostic.message = 'El total informado difiere en un peso de la suma del neto, exento, IVA e impuestos. Se conserva el total original del documento.';
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const observations = diagnostics.filter(d => d.code === 'GLOBAL_ADJUSTMENT_REQUIRES_PERCENT' || d.code === 'HEADER_TOTAL_MISMATCH').map(({ code, message, declaredAmount, derivedAmount }) => ({ code, message, ...(declaredAmount !== undefined ? { declaredAmount } : {}), ...(derivedAmount !== undefined ? { derivedAmount } : {}) }));
|
|
350
|
+
return { netAmount, exemptAmount, vatAmount, totalAmount, payableAmount, lines, taxes, ...(globalDiscount ? { globalDiscount } : {}), ...(surcharge ? { globalSurcharge: surcharge } : {}), ...(nonBillableLines.length ? { nonBillable: { amount: nonBillableAmount, lines: nonBillableLines } } : {}), ...(inferred ? { grossAmountsInferred: true } : {}), ...(lineRounding !== undefined ? { lineRounding } : {}), ...(totalRounding ? { totalRounding } : {}), ...(observations.length ? { observations } : {}) };
|
|
351
|
+
}
|