@devly-cl/sii-client 0.6.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.
Files changed (40) hide show
  1. package/README.md +96 -251
  2. package/dist/application/document-status.d.ts +13 -0
  3. package/dist/application/document-status.js +50 -0
  4. package/dist/application/invoice-queries.d.ts +11 -5
  5. package/dist/application/invoice-queries.js +13 -9
  6. package/dist/domain/company-info.d.ts +13 -0
  7. package/dist/domain/company-info.js +2 -0
  8. package/dist/domain/document-status.d.ts +93 -0
  9. package/dist/domain/document-status.js +69 -0
  10. package/dist/domain/document.d.ts +4 -0
  11. package/dist/domain/document.js +36 -3
  12. package/dist/domain/invoice-xml.d.ts +34 -1
  13. package/dist/domain/invoicing.d.ts +78 -5
  14. package/dist/domain/invoicing.js +143 -26
  15. package/dist/domain/rcv-document.d.ts +17 -0
  16. package/dist/domain/rcv-document.js +2 -0
  17. package/dist/index.d.ts +7 -4
  18. package/dist/index.js +2 -1
  19. package/dist/infrastructure/document-status-gateway.d.ts +13 -0
  20. package/dist/infrastructure/document-status-gateway.js +127 -0
  21. package/dist/infrastructure/document-status-parser.d.ts +12 -0
  22. package/dist/infrastructure/document-status-parser.js +258 -0
  23. package/dist/infrastructure/dte-xml.js +81 -6
  24. package/dist/infrastructure/facturador-gateway.d.ts +4 -1
  25. package/dist/infrastructure/facturador-gateway.js +113 -15
  26. package/dist/infrastructure/facturador.d.ts +3 -0
  27. package/dist/infrastructure/facturador.js +18 -1
  28. package/dist/infrastructure/rcv-gateway.d.ts +3 -0
  29. package/dist/infrastructure/rcv-gateway.js +9 -5
  30. package/dist/infrastructure/rcv-normalization.d.ts +7 -0
  31. package/dist/infrastructure/rcv-normalization.js +9 -1
  32. package/dist/infrastructure/sii-client.d.ts +10 -1
  33. package/dist/infrastructure/sii-client.js +29 -3
  34. package/dist/infrastructure/sii-http-session.d.ts +5 -1
  35. package/dist/infrastructure/sii-http-session.js +20 -5
  36. package/dist/sii-error.d.ts +3 -3
  37. package/dist/sii-error.js +10 -4
  38. package/package.json +45 -45
  39. package/dist/domain/sii-error.d.ts +0 -27
  40. 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;
@@ -10,7 +10,7 @@ exports.DocumentContentMismatchError = DocumentContentMismatchError;
10
10
  function assertApprovedDocument(document, approved) {
11
11
  const d = document.detail;
12
12
  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.taxes.length || d.adjustments.length || d.exemptAmount || d.fiscalHeader?.noDebitReduction != null || d.fiscalHeader?.unapprovedFiscalFields.length)
13
+ 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
14
  throw new DocumentContentMismatchError();
15
15
  if (approved.invoice) {
16
16
  const items = approved.invoice.items;
@@ -21,7 +21,37 @@ function assertApprovedDocument(document, approved) {
21
21
  throw new DocumentContentMismatchError();
22
22
  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
23
  throw new DocumentContentMismatchError();
24
- if (d.hasTransport || d.lines.length !== items.length || d.references.length || d.lines.some((line, i) => line.codes.length || line.name !== items[i]?.name || (line.description ?? '') !== (items[i]?.description ?? '') || decimal(line.quantity) !== decimal(items[i]?.quantity ?? null) || decimal(line.unitPrice) !== decimal(items[i]?.unitNetPriceClp ?? null) || (line.unit ?? '') !== (items[i]?.unit ?? '') || line.amount !== (0, invoicing_1.calculateInvoiceTotals)([items[i]]).netAmount || line.discountAmount || line.surchargeAmount || line.discountPercent && Number(line.discountPercent) || line.surchargePercent && Number(line.surchargePercent) || line.exemptIndicator))
24
+ const breakdown = (0, invoicing_1.invoiceBreakdown)(items, i.globalDiscount);
25
+ if (d.lines.length !== items.length || d.lines.some((line, index) => {
26
+ const item = items[index], expected = breakdown.lineAmounts[index];
27
+ 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;
28
+ }))
29
+ throw new DocumentContentMismatchError();
30
+ const taxOrder = (taxes) => taxes.map(tax => ({ ...tax, rate: decimal(tax.rate) })).sort((a, b) => a.type - b.type);
31
+ if ((0, invoicing_1.hashContent)(taxOrder(d.taxes)) !== (0, invoicing_1.hashContent)(taxOrder(breakdown.taxes)))
32
+ throw new DocumentContentMismatchError();
33
+ const adjustment = d.adjustments[0];
34
+ const hasDiscount = breakdown.discountAmount > 0 || Number(breakdown.discountPercent) > 0;
35
+ if (hasDiscount) {
36
+ const matches = adjustment?.valueType === '%'
37
+ ? decimal(adjustment.value) === decimal(breakdown.discountPercent) && breakdown.discountAmountFromPercent === breakdown.discountAmount
38
+ : adjustment?.valueType === '$' && breakdown.discountAmount > 0 && decimal(adjustment.value) === String(breakdown.discountAmount);
39
+ if (d.adjustments.length !== 1 || !adjustment || !matches || adjustment.lineNumber !== 1 || adjustment.movement !== 'D' || adjustment.exemptIndicator || adjustment.description !== null && adjustment.description.toLowerCase() !== 'descuento global')
40
+ throw new DocumentContentMismatchError();
41
+ }
42
+ else if (d.adjustments.length)
43
+ throw new DocumentContentMismatchError();
44
+ const references = i.references ?? [];
45
+ 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; }))
46
+ throw new DocumentContentMismatchError();
47
+ const options = d.issuanceOptions;
48
+ const expectedPayments = (i.payments ?? []).map(payment => ({ date: payment.date, amount: payment.amountClp, description: payment.description ?? null }));
49
+ const expectedTaxCodes = items.flatMap((item, index) => item.additionalTaxCode === undefined ? [] : [{ lineNumber: index + 1, codes: [item.additionalTaxCode] }]);
50
+ const expectedGlobal = references.flatMap((ref, index) => ref.global ? [{ lineNumber: index + 1, indicator: 1 }] : []);
51
+ 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))
52
+ throw new DocumentContentMismatchError();
53
+ const email = approved.issuerContact?.email ?? i.issuer.email ?? '', phone = approved.issuerContact?.phone ?? i.issuer.phone ?? '';
54
+ 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
55
  throw new DocumentContentMismatchError();
26
56
  }
27
57
  else {
@@ -32,7 +62,10 @@ function assertApprovedDocument(document, approved) {
32
62
  const header = d.fiscalHeader;
33
63
  const originalHeader = original?.fiscalHeader;
34
64
  const lines = (values) => values.map(line => ({ ...line, quantity: decimal(line.quantity), unitPrice: decimal(line.unitPrice), discountPercent: decimal(line.discountPercent), surchargePercent: decimal(line.surchargePercent) }));
35
- if (!original || !header || !originalHeader || (0, invoicing_1.hashContent)(lines(d.lines)) !== (0, invoicing_1.hashContent)(lines(original.lines)) || (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]))
65
+ 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 ?? [] });
66
+ const taxes = (detail) => detail.taxes.map(tax => ({ ...tax, rate: decimal(tax.rate) }));
67
+ const adjustments = (detail) => detail.adjustments.map(adjustment => ({ ...adjustment, value: decimal(adjustment.value) }));
68
+ 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
69
  throw new DocumentContentMismatchError();
37
70
  }
38
71
  }
@@ -5,6 +5,9 @@ export interface IssuedDocumentXmlQuery {
5
5
  documentType: IssuedDocumentType;
6
6
  folio: string;
7
7
  }
8
+ export interface ReceivedDocumentXmlQuery extends IssuedDocumentXmlQuery {
9
+ issuerRut: string;
10
+ }
8
11
  export interface IssuedInvoiceXmlQuery {
9
12
  documentType: InvoiceDocumentType;
10
13
  folio: string;
@@ -31,6 +34,8 @@ export interface DteInvoiceLine {
31
34
  amount: number;
32
35
  }
33
36
  export interface DteInvoiceDetail {
37
+ /** Present only for MntBruto=1: line amounts/prices include VAT. Original fiscal totals are unchanged. */
38
+ grossAmounts?: boolean;
34
39
  issuerRut: string;
35
40
  documentType: InvoiceDocumentType;
36
41
  folio: string;
@@ -76,6 +81,8 @@ export interface DteDocumentDetail extends Omit<DteInvoiceDetail, 'documentType'
76
81
  hasSignature: boolean;
77
82
  /** Transport data is present; an observed empty Transporte container does not count. */
78
83
  hasTransport: boolean;
84
+ /** Present only when optional issuance data exists. Legacy parseDteXml keeps its shape. */
85
+ issuanceOptions?: DteIssuanceOptions;
79
86
  fiscalHeader?: {
80
87
  issuer: {
81
88
  legalName: string | null;
@@ -98,10 +105,36 @@ export interface DteDocumentDetail extends Omit<DteInvoiceDetail, 'documentType'
98
105
  saleType: number | null;
99
106
  purchaseType: number | null;
100
107
  noDebitReduction: number | null;
101
- /** IdDoc fields outside the supported invoice/annulment issuance command. Reads preserve them. */
108
+ /** Fiscal fields outside the supported invoice/annulment issuance command. Reads preserve them. */
102
109
  unapprovedFiscalFields: string[];
103
110
  };
104
111
  }
112
+ export interface DteIssuanceOptions {
113
+ issuerEmail: string | null;
114
+ issuerPhones: string[];
115
+ requesterRut: string | null;
116
+ transport: {
117
+ carrierRut: string | null;
118
+ licensePlate: string | null;
119
+ driverRut: string | null;
120
+ driverName: string | null;
121
+ } | null;
122
+ payments: {
123
+ date: string;
124
+ amount: number;
125
+ description: string | null;
126
+ }[];
127
+ lineTaxCodes: {
128
+ lineNumber: number;
129
+ codes: number[];
130
+ }[];
131
+ referenceGlobalIndicators: {
132
+ lineNumber: number;
133
+ indicator: number;
134
+ }[];
135
+ /** Optional structures outside the supported form are readable but cannot be issued. */
136
+ unapprovedFields: string[];
137
+ }
105
138
  export interface IssuedDocumentXmlResult extends Omit<InvoiceXmlResult, 'detail'> {
106
139
  detail: DteDocumentDetail;
107
140
  }
@@ -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
- /** Tipo 33, IVA 19%, sin descuentos ni opciones fiscales implícitas. */
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 cada línea a CLP y después el IVA; sin aritmética decimal binaria. */
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. */