@ripwords/myinvois-client 0.2.6 → 0.2.7

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 (38) hide show
  1. package/dist/api/documentManagement.d.ts +2 -2
  2. package/dist/api/documentSubmission.d.ts +3 -3
  3. package/dist/api/documentSubmission.js +2 -2
  4. package/dist/api/documentTypeManagement.d.ts +2 -2
  5. package/dist/api/notificationManagement.d.ts +2 -2
  6. package/dist/api/platformLogin.d.ts +2 -2
  7. package/dist/api/taxpayerValidation.d.ts +2 -2
  8. package/dist/{document-djvnrrZo.cjs → document-BgPF4b8T.cjs} +20 -3
  9. package/dist/document-BgPF4b8T.cjs.map +1 -0
  10. package/dist/{document-BvyYSCPx.js → document-CX2DalTX.js} +19 -2
  11. package/dist/{documentSubmission-695VhFA8.js → documentSubmission-BszHhgyA.js} +1 -1
  12. package/dist/{documentSubmission-CK1zOsSV.cjs → documentSubmission-DTnOLqdW.cjs} +2 -2
  13. package/dist/documentSubmission-DTnOLqdW.cjs.map +1 -0
  14. package/dist/{documents-BuU5vKSi.d.cts → documents-BXxJLeMe.d.cts} +221 -24
  15. package/dist/{documents-Bw8tPK9r.d.ts → documents-BrbgAg2U.d.ts} +220 -23
  16. package/dist/index.cjs +2 -2
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.ts +4 -4
  19. package/dist/index.js +2 -2
  20. package/dist/index25.cjs +1 -1
  21. package/dist/index27.cjs +1 -1
  22. package/dist/index3.cjs +2 -2
  23. package/dist/index62.cts.map +1 -1
  24. package/dist/index67.cts.map +1 -1
  25. package/dist/index70.cts.map +1 -1
  26. package/dist/{taxpayer-Rnw1l38P.d.ts → taxpayer-B5jvXdII.d.ts} +1 -1
  27. package/dist/{taxpayer-C2ZUMCP6.d.cts → taxpayer-ONpnw0na.d.cts} +2 -2
  28. package/dist/types/documents.d.ts +2 -2
  29. package/dist/types/index.d.ts +3 -3
  30. package/dist/types/taxpayer.d.ts +2 -2
  31. package/dist/utils/document.d.ts +20 -20
  32. package/dist/utils/document.js +1 -1
  33. package/dist/utils/signature-diagnostics.d.ts +2 -2
  34. package/dist/utils/signature-diagnostics.js +1 -1
  35. package/dist/utils/validation.d.ts +2 -2
  36. package/package.json +1 -1
  37. package/dist/document-djvnrrZo.cjs.map +0 -1
  38. package/dist/documentSubmission-CK1zOsSV.cjs.map +0 -1
@@ -51,11 +51,11 @@ import "../YX-CzIG0m1_.js";
51
51
  import "../ZX-BoEUGCYa.js";
52
52
  import "../XX-DhTx4dT8.js";
53
53
  import "../unit-types-COhKgwRx.js";
54
- import { DocumentStatus, DocumentSummary, DocumentValidationResult, DocumentValidationStepResult } from "../documents-Bw8tPK9r.js";
54
+ import { DocumentStatus, DocumentSummary, DocumentValidationResult, DocumentValidationStepResult } from "../documents-BrbgAg2U.js";
55
55
  import "../payment-modes-tbWpu_Qh.js";
56
56
  import "../signatures-C-nCPDqt.js";
57
57
  import "../notifications-B4l_qRj7.js";
58
- import "../taxpayer-Rnw1l38P.js";
58
+ import "../taxpayer-B5jvXdII.js";
59
59
  import { Fetch } from "../utils-B3mo51Zp.js";
60
60
  import "../index-FTgB2nM6.js";
61
61
 
@@ -51,11 +51,11 @@ import "../YX-CzIG0m1_.js";
51
51
  import "../ZX-BoEUGCYa.js";
52
52
  import "../XX-DhTx4dT8.js";
53
53
  import "../unit-types-COhKgwRx.js";
54
- import { DocumentSummary, InvoiceV1_1, SigningCredentials, StandardError, SubmissionResponse, SubmissionStatus } from "../documents-Bw8tPK9r.js";
54
+ import { AllDocumentsV1_1, DocumentSummary, SigningCredentials, StandardError, SubmissionResponse, SubmissionStatus } from "../documents-BrbgAg2U.js";
55
55
  import "../payment-modes-tbWpu_Qh.js";
56
56
  import "../signatures-C-nCPDqt.js";
57
57
  import "../notifications-B4l_qRj7.js";
58
- import "../taxpayer-Rnw1l38P.js";
58
+ import "../taxpayer-B5jvXdII.js";
59
59
  import { Fetch } from "../utils-B3mo51Zp.js";
60
60
  import "../index-FTgB2nM6.js";
61
61
 
@@ -65,7 +65,7 @@ interface SubmissionContext {
65
65
  debug: boolean;
66
66
  signingCredentials: SigningCredentials;
67
67
  }
68
- declare function submitDocument(context: SubmissionContext, documents: InvoiceV1_1[]): Promise<{
68
+ declare function submitDocument(context: SubmissionContext, documents: AllDocumentsV1_1[]): Promise<{
69
69
  data: SubmissionResponse;
70
70
  status: number;
71
71
  }>;
@@ -1,4 +1,4 @@
1
- import "../document-BvyYSCPx.js";
2
- import { getSubmissionStatus, performDocumentAction, submitDocument } from "../documentSubmission-695VhFA8.js";
1
+ import "../document-CX2DalTX.js";
2
+ import { getSubmissionStatus, performDocumentAction, submitDocument } from "../documentSubmission-BszHhgyA.js";
3
3
 
4
4
  export { getSubmissionStatus, performDocumentAction, submitDocument };
@@ -51,11 +51,11 @@ import "../YX-CzIG0m1_.js";
51
51
  import "../ZX-BoEUGCYa.js";
52
52
  import "../XX-DhTx4dT8.js";
53
53
  import "../unit-types-COhKgwRx.js";
54
- import { DocumentTypeResponse, DocumentTypeVersionResponse, DocumentTypesResponse } from "../documents-Bw8tPK9r.js";
54
+ import { DocumentTypeResponse, DocumentTypeVersionResponse, DocumentTypesResponse } from "../documents-BrbgAg2U.js";
55
55
  import "../payment-modes-tbWpu_Qh.js";
56
56
  import "../signatures-C-nCPDqt.js";
57
57
  import "../notifications-B4l_qRj7.js";
58
- import "../taxpayer-Rnw1l38P.js";
58
+ import "../taxpayer-B5jvXdII.js";
59
59
  import { Fetch } from "../utils-B3mo51Zp.js";
60
60
  import "../index-FTgB2nM6.js";
61
61
 
@@ -51,11 +51,11 @@ import "../YX-CzIG0m1_.js";
51
51
  import "../ZX-BoEUGCYa.js";
52
52
  import "../XX-DhTx4dT8.js";
53
53
  import "../unit-types-COhKgwRx.js";
54
- import "../documents-Bw8tPK9r.js";
54
+ import "../documents-BrbgAg2U.js";
55
55
  import "../payment-modes-tbWpu_Qh.js";
56
56
  import "../signatures-C-nCPDqt.js";
57
57
  import { NotificationResponse, NotificationSearchParams } from "../notifications-B4l_qRj7.js";
58
- import "../taxpayer-Rnw1l38P.js";
58
+ import "../taxpayer-B5jvXdII.js";
59
59
  import { Fetch } from "../utils-B3mo51Zp.js";
60
60
  import "../index-FTgB2nM6.js";
61
61
 
@@ -51,11 +51,11 @@ import "../YX-CzIG0m1_.js";
51
51
  import "../ZX-BoEUGCYa.js";
52
52
  import "../XX-DhTx4dT8.js";
53
53
  import "../unit-types-COhKgwRx.js";
54
- import "../documents-Bw8tPK9r.js";
54
+ import "../documents-BrbgAg2U.js";
55
55
  import "../payment-modes-tbWpu_Qh.js";
56
56
  import "../signatures-C-nCPDqt.js";
57
57
  import "../notifications-B4l_qRj7.js";
58
- import "../taxpayer-Rnw1l38P.js";
58
+ import "../taxpayer-B5jvXdII.js";
59
59
  import "../utils-B3mo51Zp.js";
60
60
  import { ClientCredentials } from "../index-FTgB2nM6.js";
61
61
 
@@ -51,11 +51,11 @@ import "../YX-CzIG0m1_.js";
51
51
  import "../ZX-BoEUGCYa.js";
52
52
  import "../XX-DhTx4dT8.js";
53
53
  import "../unit-types-COhKgwRx.js";
54
- import { RegistrationType } from "../documents-Bw8tPK9r.js";
54
+ import { RegistrationType } from "../documents-BrbgAg2U.js";
55
55
  import "../payment-modes-tbWpu_Qh.js";
56
56
  import "../signatures-C-nCPDqt.js";
57
57
  import "../notifications-B4l_qRj7.js";
58
- import { TaxpayerQRCodeResponse, TinSearchParams, TinSearchResponse } from "../taxpayer-Rnw1l38P.js";
58
+ import { TaxpayerQRCodeResponse, TinSearchParams, TinSearchResponse } from "../taxpayer-B5jvXdII.js";
59
59
  import { Fetch } from "../utils-B3mo51Zp.js";
60
60
  import "../index-FTgB2nM6.js";
61
61
 
@@ -28,6 +28,18 @@ const calculateExpectedTaxAmount = (item) => {
28
28
  return 0;
29
29
  };
30
30
  /**
31
+ * Extracts the line-item array from any document variant
32
+ */
33
+ const getLineItems = (doc) => {
34
+ if ("invoiceLineItems" in doc) return doc.invoiceLineItems;
35
+ if ("creditNoteLineItems" in doc) return doc.creditNoteLineItems;
36
+ if ("debitNoteLineItems" in doc) return doc.debitNoteLineItems;
37
+ if ("refundNoteLineItems" in doc) return doc.refundNoteLineItems;
38
+ if ("selfBilledCreditNoteLineItems" in doc) return doc.selfBilledCreditNoteLineItems;
39
+ if ("selfBilledRefundNoteLineItems" in doc) return doc.selfBilledRefundNoteLineItems;
40
+ return [];
41
+ };
42
+ /**
31
43
  * Helper function to recursively sort object keys for JSON canonicalization
32
44
  */
33
45
  function sortObjectKeys(obj) {
@@ -57,6 +69,7 @@ const canonicalizeJSON = (obj) => {
57
69
  * - Correct listID values (e.g., "3166-1" not "ISO3166-1")
58
70
  */
59
71
  const generateCleanInvoiceObject = (invoice) => {
72
+ const lineItems = getLineItems(invoice);
60
73
  return {
61
74
  ID: [{ _: invoice.eInvoiceCodeOrNumber }],
62
75
  IssueDate: [{ _: invoice.eInvoiceDate }],
@@ -66,6 +79,10 @@ const generateCleanInvoiceObject = (invoice) => {
66
79
  listVersionID: invoice.eInvoiceVersion || "1.1"
67
80
  }],
68
81
  DocumentCurrencyCode: [{ _: invoice.invoiceCurrencyCode }],
82
+ ..."originalEInvoiceReferenceNumber" in invoice && invoice.originalEInvoiceReferenceNumber ? { BillingReference: [{ InvoiceDocumentReference: [{
83
+ UUID: [{ _: invoice.originalEInvoiceReferenceNumber }],
84
+ ID: [{ _: invoice.eInvoiceCodeOrNumber }]
85
+ }] }] } : {},
69
86
  AccountingSupplierParty: [{ Party: [{
70
87
  IndustryClassificationCode: [{
71
88
  _: invoice.supplier.industryClassificationCode,
@@ -134,7 +151,7 @@ const generateCleanInvoiceObject = (invoice) => {
134
151
  currencyID: invoice.invoiceCurrencyCode
135
152
  }],
136
153
  TaxCategory: [{
137
- ID: [{ _: invoice.invoiceLineItems[0]?.taxType || "01" }],
154
+ ID: [{ _: lineItems[0]?.taxType || "01" }],
138
155
  TaxScheme: [{ ID: [{
139
156
  _: "OTH",
140
157
  schemeAgencyID: "6",
@@ -161,7 +178,7 @@ const generateCleanInvoiceObject = (invoice) => {
161
178
  currencyID: invoice.invoiceCurrencyCode
162
179
  }]
163
180
  }],
164
- InvoiceLine: invoice.invoiceLineItems.map((item, index) => ({
181
+ InvoiceLine: lineItems.map((item, index) => ({
165
182
  ID: [{ _: (index + 1).toString() }],
166
183
  Item: [{
167
184
  CommodityClassification: [{ ItemClassificationCode: [{
@@ -589,4 +606,4 @@ Object.defineProperty(exports, 'sortObjectKeys', {
589
606
  return sortObjectKeys;
590
607
  }
591
608
  });
592
- //# sourceMappingURL=document-djvnrrZo.cjs.map
609
+ //# sourceMappingURL=document-BgPF4b8T.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"document-BgPF4b8T.cjs","names":["item: InvoiceLineItem","doc: AllDocumentsV1_1","obj: unknown","sortedObj: Record<string, unknown>","invoice: AllDocumentsV1_1","invoices: AllDocumentsV1_1[]","invoice: any","certificatePem: string","X509Certificate","dn: string","serialHex: string","error: unknown","certificateDigest: string","signingTime: string","issuerName: string","serialNumber: string","signedProperties: SignedPropertiesObject","docDigest: string","propsDigest: string","privateKeyPem: string","signingCredentials: SigningCredentials","params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxRate: number\n totalTaxableAmountPerLine?: number\n}","params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxPerUnitAmount: number\n baseUnitMeasure: number\n baseUnitMeasureCode: UnitTypeCode\n totalTaxableAmountPerLine?: number\n}","lineItems: InvoiceLineItem[]"],"sources":["../src/utils/document.ts"],"sourcesContent":["import crypto, { X509Certificate } from 'crypto'\nimport {\n InvoiceSubmission,\n AllDocumentsV1_1,\n SigningCredentials,\n SignedPropertiesObject,\n UBLDocument,\n CompleteInvoice,\n SignedInfoObject,\n UnitTypeCode,\n InvoiceLineItem,\n} from '../types'\nimport type { ClassificationCode } from '../types'\nimport type { TaxTypeCode } from '../types'\n\n/**\n * MyInvois v1.1 Document Generation and Signing Utilities\n * Strictly follows: https://sdk.myinvois.hasil.gov.my/documents/invoice-v1-1\n * JSON Signature Guide: https://sdk.myinvois.hasil.gov.my/signature-creation-json/\n */\n\n/**\n * Determines if a line item uses fixed rate taxation\n */\nexport const isFixedRateTax = (item: InvoiceLineItem): boolean => {\n return (\n item.taxPerUnitAmount !== undefined && item.baseUnitMeasure !== undefined\n )\n}\n\n/**\n * Determines if a line item uses percentage taxation\n */\nexport const isPercentageTax = (item: InvoiceLineItem): boolean => {\n return item.taxRate !== undefined && !isFixedRateTax(item)\n}\n\n/**\n * Calculates expected tax amount for a line item based on its tax type\n */\nexport const calculateExpectedTaxAmount = (item: InvoiceLineItem): number => {\n if (isFixedRateTax(item)) {\n return item.taxPerUnitAmount! * item.baseUnitMeasure!\n } else if (isPercentageTax(item)) {\n return (item.totalTaxableAmountPerLine * item.taxRate!) / 100\n }\n return 0\n}\n\n/**\n * Extracts the line-item array from any document variant\n */\nconst getLineItems = (doc: AllDocumentsV1_1): InvoiceLineItem[] => {\n if ('invoiceLineItems' in doc) return doc.invoiceLineItems\n if ('creditNoteLineItems' in doc) return doc.creditNoteLineItems\n if ('debitNoteLineItems' in doc) return doc.debitNoteLineItems\n if ('refundNoteLineItems' in doc) return doc.refundNoteLineItems\n if ('selfBilledCreditNoteLineItems' in doc)\n return doc.selfBilledCreditNoteLineItems\n if ('selfBilledRefundNoteLineItems' in doc)\n return doc.selfBilledRefundNoteLineItems\n // Fallback (should never happen with exhaustive types)\n return []\n}\n\n/**\n * Helper function to recursively sort object keys for JSON canonicalization\n */\nexport function sortObjectKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj\n }\n\n if (Array.isArray(obj)) {\n return obj.map(sortObjectKeys)\n }\n\n const sortedObj: Record<string, unknown> = {}\n const keys = Object.keys(obj as Record<string, unknown>).sort()\n\n for (const key of keys) {\n sortedObj[key] = sortObjectKeys((obj as Record<string, unknown>)[key])\n }\n\n return sortedObj\n}\n\n/**\n * Enhanced canonicalization following MyInvois specification exactly\n * Key changes: ensure consistent ordering and formatting\n */\nexport const canonicalizeJSON = (obj: unknown): string => {\n const sortedObj = sortObjectKeys(obj)\n // Use compact JSON with no extra whitespace\n return JSON.stringify(sortedObj, null, 0)\n}\n\n/**\n * Generates a clean invoice object following MyInvois v1.1 specification exactly\n * This is the base invoice structure WITHOUT signature elements (for hash calculation)\n *\n * Key requirements from working documents:\n * - All mandatory fields must be present\n * - Many optional fields must be present even if empty\n * - Specific field ordering and structure\n * - Correct listID values (e.g., \"3166-1\" not \"ISO3166-1\")\n */\nexport const generateCleanInvoiceObject = (\n invoice: AllDocumentsV1_1,\n): InvoiceSubmission => {\n const lineItems = getLineItems(invoice)\n return {\n // === MANDATORY CORE FIELDS ===\n ID: [{ _: invoice.eInvoiceCodeOrNumber }],\n IssueDate: [{ _: invoice.eInvoiceDate }],\n IssueTime: [{ _: invoice.eInvoiceTime }],\n InvoiceTypeCode: [\n {\n _: invoice.eInvoiceTypeCode,\n listVersionID: invoice.eInvoiceVersion || '1.1',\n },\n ],\n DocumentCurrencyCode: [{ _: invoice.invoiceCurrencyCode }],\n\n // === BILLING REFERENCE (only for credit/debit/refund notes) ===\n ...('originalEInvoiceReferenceNumber' in invoice &&\n invoice.originalEInvoiceReferenceNumber\n ? {\n BillingReference: [\n {\n InvoiceDocumentReference: [\n {\n UUID: [\n {\n _: invoice.originalEInvoiceReferenceNumber,\n },\n ],\n ID: [\n {\n _: invoice.eInvoiceCodeOrNumber,\n },\n ],\n },\n ],\n },\n ],\n }\n : {}),\n\n // === SUPPLIER PARTY (AccountingSupplierParty) ===\n AccountingSupplierParty: [\n {\n Party: [\n {\n // Industry Classification - required field\n IndustryClassificationCode: [\n {\n _: invoice.supplier.industryClassificationCode,\n name: invoice.supplier.industryClassificationDescription,\n },\n ],\n\n // Party Identifications\n PartyIdentification: [\n {\n ID: [\n {\n _: invoice.supplier.tin,\n schemeID: 'TIN',\n },\n ],\n },\n {\n ID: [\n {\n _: invoice.supplier.registrationNumber,\n schemeID: invoice.supplier.registrationType || 'NRIC',\n },\n ],\n },\n ],\n\n // Postal Address - FIXED listID format\n PostalAddress: [\n {\n CityName: [{ _: invoice.supplier.address.cityName }],\n CountrySubentityCode: [{ _: invoice.supplier.address.state }],\n AddressLine: [\n {\n Line: [{ _: invoice.supplier.address.addressLine0 }],\n },\n ],\n Country: [\n {\n IdentificationCode: [\n {\n _: invoice.supplier.address.country || 'MYS',\n listID: '3166-1', // FIXED: was \"ISO3166-1\"\n listAgencyID: 'ISO',\n },\n ],\n },\n ],\n },\n ],\n\n // Party Legal Entity\n PartyLegalEntity: [\n {\n RegistrationName: [{ _: invoice.supplier.name }],\n },\n ],\n\n // Contact Information\n Contact: [\n {\n Telephone: [{ _: invoice.supplier.contactNumber || '' }],\n },\n ],\n },\n ],\n },\n ],\n\n // === BUYER PARTY (AccountingCustomerParty) ===\n AccountingCustomerParty: [\n {\n Party: [\n {\n // Party Identifications\n PartyIdentification: [\n {\n ID: [\n {\n _: invoice.buyer.tin,\n schemeID: 'TIN',\n },\n ],\n },\n {\n ID: [\n {\n _: invoice.buyer.registrationNumber,\n schemeID: invoice.buyer.registrationType || 'NRIC',\n },\n ],\n },\n {\n ID: [\n {\n _: invoice.buyer.sstRegistrationNumber || 'NA',\n schemeID: 'SST',\n },\n ],\n },\n ],\n\n // Postal Address - FIXED listID format\n PostalAddress: [\n {\n CityName: [{ _: invoice.buyer.address.cityName }],\n CountrySubentityCode: [{ _: invoice.buyer.address.state }],\n AddressLine: [\n {\n Line: [{ _: invoice.buyer.address.addressLine0 }],\n },\n ],\n Country: [\n {\n IdentificationCode: [\n {\n _: invoice.buyer.address.country || 'MYS',\n listID: '3166-1', // FIXED: was \"ISO3166-1\"\n listAgencyID: 'ISO',\n },\n ],\n },\n ],\n },\n ],\n\n // Party Legal Entity\n PartyLegalEntity: [\n {\n RegistrationName: [{ _: invoice.buyer.name }],\n },\n ],\n\n // Contact Information\n Contact: [\n {\n Telephone: [{ _: invoice.buyer.contactNumber || '' }],\n },\n ],\n },\n ],\n },\n ],\n\n // === TAX TOTAL ===\n TaxTotal: [\n {\n TaxAmount: [\n {\n _: invoice.taxTotal.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxSubtotal: [\n // Generate basic tax subtotal from invoice line items\n {\n TaxableAmount: [\n {\n _: invoice.legalMonetaryTotal.taxExclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxAmount: [\n {\n _: invoice.taxTotal.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxCategory: [\n {\n ID: [{ _: lineItems[0]?.taxType || '01' }],\n TaxScheme: [\n {\n ID: [\n {\n _: 'OTH',\n schemeAgencyID: '6',\n schemeID: 'UN/ECE 5153',\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n\n // === LEGAL MONETARY TOTAL ===\n LegalMonetaryTotal: [\n {\n LineExtensionAmount: [\n {\n _: invoice.legalMonetaryTotal.taxExclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxExclusiveAmount: [\n {\n _: invoice.legalMonetaryTotal.taxExclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxInclusiveAmount: [\n {\n _: invoice.legalMonetaryTotal.taxInclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n PayableAmount: [\n {\n _: invoice.legalMonetaryTotal.payableAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n },\n ],\n\n // === INVOICE LINES ===\n InvoiceLine: lineItems.map((item, index) => ({\n ID: [{ _: (index + 1).toString() }],\n\n // Item Information\n Item: [\n {\n CommodityClassification: [\n {\n ItemClassificationCode: [\n {\n _: item.itemClassificationCode,\n listID: 'CLASS',\n },\n ],\n },\n ],\n Description: [{ _: item.itemDescription }],\n },\n ],\n\n ItemPriceExtension: [\n {\n Amount: [\n {\n _: item.totalTaxableAmountPerLine,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n },\n ],\n\n LineExtensionAmount: [\n {\n _: item.totalTaxableAmountPerLine,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n\n // Price Information\n Price: [\n {\n PriceAmount: [\n {\n _: item.unitPrice,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n },\n ],\n\n // Tax Information for line\n TaxTotal: [\n {\n TaxAmount: [\n {\n _: item.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxSubtotal: [\n {\n TaxableAmount: [\n {\n _: item.totalTaxableAmountPerLine,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxAmount: [\n {\n _: item.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n // Conditional tax fields based on taxation type\n ...(item.taxPerUnitAmount !== undefined &&\n item.baseUnitMeasure !== undefined\n ? {\n // Fixed Rate Taxation\n PerUnitAmount: [\n {\n _: item.taxPerUnitAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n BaseUnitMeasure: [\n {\n _: item.baseUnitMeasure,\n unitCode: item.baseUnitMeasureCode || 'C62',\n },\n ],\n }\n : item.taxRate !== undefined\n ? {\n // Percentage Taxation\n Percent: [{ _: item.taxRate }],\n }\n : {}),\n TaxCategory: [\n {\n ID: [{ _: item.taxType }],\n TaxScheme: [\n {\n ID: [\n {\n _: 'OTH',\n schemeAgencyID: '6',\n schemeID: 'UN/ECE 5153',\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n })),\n\n // === TAX EXCHANGE RATE (mandatory where applicable) ===\n TaxExchangeRate: invoice.currencyExchangeRate\n ? [\n {\n SourceCurrencyCode: [\n {\n _: invoice.invoiceCurrencyCode,\n },\n ],\n TargetCurrencyCode: [\n {\n _: 'MYR',\n },\n ],\n CalculationRate: [\n {\n _: invoice.currencyExchangeRate,\n },\n ],\n },\n ]\n : undefined,\n }\n}\n\n/**\n * Generates the complete UBL document structure with namespace declarations\n */\nexport const generateCleanUBLDocument = (\n invoices: AllDocumentsV1_1[],\n): UBLDocument => {\n return {\n _D: 'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2',\n _A: 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2',\n _B: 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2',\n Invoice: invoices.map(generateCleanInvoiceObject),\n }\n}\n\n/**\n * Step 2: Calculate Document Digest\n * FIXED: Remove UBLExtensions and Signature before hashing (DS322)\n * Based on working implementation pattern\n */\nexport const calculateDocumentDigest = (\n invoices: AllDocumentsV1_1[],\n): string => {\n // Generate clean UBL document structure\n const cleanDocument = generateCleanUBLDocument(invoices)\n\n // CRITICAL FIX: Remove UBLExtensions and Signature from each invoice before hashing\n const documentForHashing = JSON.parse(JSON.stringify(cleanDocument))\n if (documentForHashing.Invoice && Array.isArray(documentForHashing.Invoice)) {\n documentForHashing.Invoice.forEach((invoice: any) => {\n delete invoice.UBLExtensions\n delete invoice.Signature\n })\n }\n\n // Convert to string for hashing (no canonicalization - use direct JSON.stringify)\n const documentString = JSON.stringify(documentForHashing)\n\n // Calculate SHA-256 hash\n const hash = crypto.createHash('sha256')\n hash.update(documentString, 'utf8')\n\n // Return as Base64 (DocDigest)\n return hash.digest('base64')\n}\n\n/**\n * Step 4: Calculate Certificate Digest\n * Enhanced to handle certificate content properly\n */\nexport const calculateCertificateDigest = (certificatePem: string): string => {\n // Extract certificate content (Base64 without PEM headers/footers)\n const certificateContent = certificatePem\n .replace(/-----BEGIN CERTIFICATE-----/g, '')\n .replace(/-----END CERTIFICATE-----/g, '')\n .replace(/\\s+/g, '') // Remove all whitespace\n\n // Convert Base64 to binary\n const certificateBinary = Buffer.from(certificateContent, 'base64')\n\n // Calculate SHA-256 hash of binary content\n const hash = crypto.createHash('sha256')\n hash.update(certificateBinary)\n\n // Return as Base64\n return hash.digest('base64')\n}\n\n/**\n * Enhanced certificate info extraction with better error handling\n * FIXED: Normalize issuer name format to match MyInvois expectations (DS326)\n */\nexport const extractCertificateInfo = (\n certificatePem: string,\n): {\n issuerName: string\n serialNumber: string\n subjectName: string\n} => {\n try {\n const cert = new X509Certificate(certificatePem)\n\n // Extract serial number and convert to decimal string\n const serialNumberHex = cert.serialNumber\n\n // ENHANCED: Normalize distinguished name format (DS326)\n // Ensures MyInvois portal compatibility for X509IssuerName matching\n const normalizeDistinguishedName = (dn: string): string => {\n // Convert multi-line format to comma-separated RFC2253 format\n const normalized = dn\n .split('\\n')\n .map(line => line.trim())\n .filter(line => line.length > 0)\n .join(', ')\n\n // MyInvois-specific normalization to prevent DS326 errors\n return normalized\n .replace(/\\s*=\\s*/g, '=') // Remove spaces around equals (CRITICAL for portal)\n .replace(/,\\s+/g, ', ') // Ensure single space after commas\n .replace(/\\r/g, '') // Remove any carriage returns\n .replace(/\\s{2,}/g, ' ') // Replace multiple spaces with single space\n .trim() // Remove leading/trailing whitespace\n }\n\n // Enhanced serial number formatting\n const formatSerialNumber = (serialHex: string): string => {\n // Convert hex to decimal and ensure it's a string\n const decimal = BigInt('0x' + serialHex).toString()\n return decimal\n }\n\n return {\n issuerName: normalizeDistinguishedName(cert.issuer),\n serialNumber: formatSerialNumber(serialNumberHex),\n subjectName: normalizeDistinguishedName(cert.subject),\n }\n } catch (error: unknown) {\n throw new Error(\n `Failed to extract certificate info: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n\n/**\n * Step 5: Create SignedProperties with enhanced structure\n * FIXED: Simplified structure to match MyInvois expectations (DS320)\n * Following MyInvois JSON signature specification exactly\n */\nexport const createSignedProperties = (\n certificateDigest: string,\n signingTime: string,\n issuerName: string,\n serialNumber: string,\n): SignedPropertiesObject => {\n return {\n SignedProperties: [\n {\n Id: 'id-xades-signed-props',\n SignedSignatureProperties: [\n {\n SigningTime: [{ _: signingTime }],\n SigningCertificate: [\n {\n Cert: [\n {\n CertDigest: [\n {\n DigestMethod: [\n {\n Algorithm:\n 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: certificateDigest }],\n },\n ],\n IssuerSerial: [\n {\n X509IssuerName: [{ _: issuerName }],\n X509SerialNumber: [{ _: serialNumber }],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n }\n}\n\n/**\n * Step 6: Calculate SignedProperties Digest\n * FIXED: Add Target wrapper and use direct JSON stringify (DS320)\n * Based on working implementation pattern\n */\nexport const calculateSignedPropertiesDigest = (\n signedProperties: SignedPropertiesObject,\n): string => {\n // CRITICAL FIX: Wrap with Target as per working implementation\n const signedPropertiesWithTarget = {\n Target: 'signature',\n SignedProperties: signedProperties.SignedProperties,\n }\n\n // Convert to string for hashing (no canonicalization - use direct JSON.stringify)\n const signedPropertiesString = JSON.stringify(signedPropertiesWithTarget)\n\n // Calculate SHA-256 hash\n const hash = crypto.createHash('sha256')\n hash.update(signedPropertiesString, 'utf8')\n\n // Return as Base64 (PropsDigest)\n return hash.digest('base64')\n}\n\n/**\n * Step 3: Create SignedInfo and calculate signature\n * Enhanced with better structure and signature generation\n */\nexport const createSignedInfoAndSign = (\n docDigest: string,\n propsDigest: string,\n privateKeyPem: string,\n): { signedInfo: SignedInfoObject; signatureValue: string } => {\n // Create SignedInfo structure following specification exactly\n const signedInfo = {\n CanonicalizationMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2006/12/xml-c14n11',\n },\n ],\n SignatureMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256',\n },\n ],\n Reference: [\n {\n Id: 'id-doc-signed-data',\n Type: '',\n URI: '',\n DigestMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: docDigest }],\n },\n {\n Id: 'id-xades-signed-props',\n Type: 'http://uri.etsi.org/01903/v1.3.2#SignedProperties',\n URI: '#id-xades-signed-props',\n DigestMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: propsDigest }],\n },\n ],\n }\n\n // FIXED: Use direct JSON.stringify instead of canonicalization (DS333)\n // Based on working implementation pattern\n const signedInfoString = JSON.stringify(signedInfo)\n\n // Sign with RSA-SHA256 directly (RSA-SHA256 handles hashing internally)\n // FIXED: Removed double-hashing bug that was causing DS333 errors\n try {\n const signer = crypto.createSign('RSA-SHA256')\n signer.update(signedInfoString, 'utf8')\n const signatureValue = signer.sign(privateKeyPem, 'base64')\n\n return { signedInfo, signatureValue }\n } catch (error) {\n throw new Error(\n `Signature generation failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n\n/**\n * Complete document generation with signatures\n * Follows the complete MyInvois JSON signature creation process (Steps 1-7)\n */\nexport const generateCompleteDocument = (\n invoices: AllDocumentsV1_1[],\n signingCredentials: SigningCredentials,\n): CompleteInvoice => {\n try {\n // Step 1: Generate clean document (done in calculateDocumentDigest)\n // Step 2: Calculate document digest\n const docDigest = calculateDocumentDigest(invoices)\n\n // Generate signing time in proper ISO format\n const signingTime = new Date().toISOString()\n\n // Extract certificate information (enhanced)\n const certInfo = extractCertificateInfo(signingCredentials.certificatePem)\n\n // Step 4: Calculate certificate digest\n const certificateDigest = calculateCertificateDigest(\n signingCredentials.certificatePem,\n )\n\n // Step 5: Create SignedProperties using extracted cert info\n const signedProperties = createSignedProperties(\n certificateDigest,\n signingTime,\n certInfo.issuerName,\n certInfo.serialNumber,\n )\n\n // Step 6: Calculate SignedProperties digest\n const propsDigest = calculateSignedPropertiesDigest(signedProperties)\n\n // Step 3: Create SignedInfo and generate signature\n const { signedInfo, signatureValue } = createSignedInfoAndSign(\n docDigest,\n propsDigest,\n signingCredentials.privateKeyPem,\n )\n\n // Extract certificate content (Base64 without PEM headers)\n const certificate = signingCredentials.certificatePem\n .replace(/-----BEGIN CERTIFICATE-----/g, '')\n .replace(/-----END CERTIFICATE-----/g, '')\n .replace(/\\s+/g, '')\n\n // Step 7: Create final signed document\n const signedInvoices = invoices.map(invoice => {\n const cleanInvoice = generateCleanInvoiceObject(invoice)\n\n return {\n ...cleanInvoice,\n\n // Add UBLExtensions with complete signature structure\n UBLExtensions: [\n {\n UBLExtension: [\n {\n ExtensionURI: [\n {\n _: 'urn:oasis:names:specification:ubl:dsig:enveloped:xades',\n },\n ],\n ExtensionContent: [\n {\n UBLDocumentSignatures: [\n {\n SignatureInformation: [\n {\n ID: [\n {\n _: 'urn:oasis:names:specification:ubl:signature:1',\n },\n ],\n ReferencedSignatureID: [\n {\n _: 'urn:oasis:names:specification:ubl:signature:Invoice',\n },\n ],\n Signature: [\n {\n Id: 'signature',\n Object: [\n {\n QualifyingProperties: [\n {\n Target: 'signature',\n SignedProperties:\n signedProperties.SignedProperties,\n },\n ],\n },\n ],\n KeyInfo: [\n {\n X509Data: [\n {\n X509Certificate: [{ _: certificate }],\n X509SubjectName: [\n { _: certInfo.subjectName },\n ],\n X509IssuerSerial: [\n {\n X509IssuerName: [\n {\n _: certInfo.issuerName,\n },\n ],\n X509SerialNumber: [\n {\n _: certInfo.serialNumber,\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n SignatureValue: [{ _: signatureValue }],\n SignedInfo: [signedInfo],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n\n // Add simple Signature reference\n Signature: [\n {\n ID: [\n {\n _: 'urn:oasis:names:specification:ubl:signature:Invoice',\n },\n ],\n SignatureMethod: [\n {\n _: 'urn:oasis:names:specification:ubl:dsig:enveloped:xades',\n },\n ],\n },\n ],\n }\n })\n\n return {\n _D: 'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2',\n _A: 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2',\n _B: 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2',\n Invoice: signedInvoices,\n }\n } catch (error) {\n throw new Error(\n `Document generation failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n\n/**\n * Creates a line item with percentage-based taxation (e.g., SST, GST)\n */\nexport const createPercentageTaxLineItem = (params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxRate: number\n totalTaxableAmountPerLine?: number\n}): InvoiceLineItem => {\n const quantity = params.quantity || 1\n const totalTaxableAmount =\n params.totalTaxableAmountPerLine || params.unitPrice * quantity\n const taxAmount = (totalTaxableAmount * params.taxRate) / 100\n\n return {\n itemClassificationCode: params.itemClassificationCode,\n itemDescription: params.itemDescription,\n unitPrice: params.unitPrice,\n taxType: params.taxType,\n taxRate: params.taxRate,\n taxAmount: Math.round(taxAmount * 100) / 100, // Round to 2 decimal places\n totalTaxableAmountPerLine: totalTaxableAmount,\n totalAmountPerLine: totalTaxableAmount + taxAmount,\n }\n}\n\n/**\n * Creates a line item with fixed rate taxation (e.g., Tourism Tax)\n */\nexport const createFixedRateTaxLineItem = (params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxPerUnitAmount: number\n baseUnitMeasure: number\n baseUnitMeasureCode: UnitTypeCode\n totalTaxableAmountPerLine?: number\n}): InvoiceLineItem => {\n const quantity = params.quantity || 1\n const totalTaxableAmount =\n params.totalTaxableAmountPerLine || params.unitPrice * quantity\n const taxAmount = params.taxPerUnitAmount * params.baseUnitMeasure\n\n return {\n itemClassificationCode: params.itemClassificationCode,\n itemDescription: params.itemDescription,\n unitPrice: params.unitPrice,\n taxType: params.taxType,\n taxPerUnitAmount: params.taxPerUnitAmount,\n baseUnitMeasure: params.baseUnitMeasure,\n baseUnitMeasureCode: params.baseUnitMeasureCode,\n taxAmount: Math.round(taxAmount * 100) / 100, // Round to 2 decimal places\n totalTaxableAmountPerLine: totalTaxableAmount,\n totalAmountPerLine: totalTaxableAmount + taxAmount,\n }\n}\n\n/**\n * Calculates invoice totals from line items\n */\nexport const calculateInvoiceTotals = (\n lineItems: InvoiceLineItem[],\n): {\n legalMonetaryTotal: {\n taxExclusiveAmount: number\n taxInclusiveAmount: number\n payableAmount: number\n }\n taxTotal: {\n taxAmount: number\n }\n} => {\n const taxExclusiveAmount = lineItems.reduce(\n (sum, item) => sum + item.totalTaxableAmountPerLine,\n 0,\n )\n const totalTaxAmount = lineItems.reduce(\n (sum, item) => sum + item.taxAmount,\n 0,\n )\n const taxInclusiveAmount = taxExclusiveAmount + totalTaxAmount\n\n return {\n legalMonetaryTotal: {\n taxExclusiveAmount: Math.round(taxExclusiveAmount * 100) / 100,\n taxInclusiveAmount: Math.round(taxInclusiveAmount * 100) / 100,\n payableAmount: Math.round(taxInclusiveAmount * 100) / 100,\n },\n taxTotal: {\n taxAmount: Math.round(totalTaxAmount * 100) / 100,\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;AAwBA,MAAa,iBAAiB,CAACA,SAAmC;AAChE,QACE,KAAK,+BAAkC,KAAK;AAE/C;;;;AAKD,MAAa,kBAAkB,CAACA,SAAmC;AACjE,QAAO,KAAK,uBAA0B,eAAe,KAAK;AAC3D;;;;AAKD,MAAa,6BAA6B,CAACA,SAAkC;AAC3E,KAAI,eAAe,KAAK,CACtB,QAAO,KAAK,mBAAoB,KAAK;UAC5B,gBAAgB,KAAK,CAC9B,QAAQ,KAAK,4BAA4B,KAAK,UAAY;AAE5D,QAAO;AACR;;;;AAKD,MAAM,eAAe,CAACC,QAA6C;AACjE,KAAI,sBAAsB,IAAK,QAAO,IAAI;AAC1C,KAAI,yBAAyB,IAAK,QAAO,IAAI;AAC7C,KAAI,wBAAwB,IAAK,QAAO,IAAI;AAC5C,KAAI,yBAAyB,IAAK,QAAO,IAAI;AAC7C,KAAI,mCAAmC,IACrC,QAAO,IAAI;AACb,KAAI,mCAAmC,IACrC,QAAO,IAAI;AAEb,QAAO,CAAE;AACV;;;;AAKD,SAAgB,eAAeC,KAAuB;AACpD,KAAI,QAAQ,eAAe,QAAQ,SACjC,QAAO;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,OAAO,YAAY;CACpC,MAAM,qBACJ,OAAO,6BAA6B,OAAO,YAAY;CACzD,MAAM,YAAY,OAAO,mBAAmB,OAAO;AAEnD,QAAO;EACL,wBAAwB,OAAO;EAC/B,iBAAiB,OAAO;EACxB,WAAW,OAAO;EAClB,SAAS,OAAO;EAChB,kBAAkB,OAAO;EACzB,iBAAiB,OAAO;EACxB,qBAAqB,OAAO;EAC5B,WAAW,KAAK,MAAM,YAAY,IAAI,GAAG;EACzC,2BAA2B;EAC3B,oBAAoB,qBAAqB;CAC1C;AACF;;;;AAKD,MAAa,yBAAyB,CACpCC,cAUG;CACH,MAAM,qBAAqB,UAAU,OACnC,CAAC,KAAK,SAAS,MAAM,KAAK,2BAC1B,EACD;CACD,MAAM,iBAAiB,UAAU,OAC/B,CAAC,KAAK,SAAS,MAAM,KAAK,WAC1B,EACD;CACD,MAAM,qBAAqB,qBAAqB;AAEhD,QAAO;EACL,oBAAoB;GAClB,oBAAoB,KAAK,MAAM,qBAAqB,IAAI,GAAG;GAC3D,oBAAoB,KAAK,MAAM,qBAAqB,IAAI,GAAG;GAC3D,eAAe,KAAK,MAAM,qBAAqB,IAAI,GAAG;EACvD;EACD,UAAU,EACR,WAAW,KAAK,MAAM,iBAAiB,IAAI,GAAG,IAC/C;CACF;AACF"}
@@ -27,6 +27,18 @@ const calculateExpectedTaxAmount = (item) => {
27
27
  return 0;
28
28
  };
29
29
  /**
30
+ * Extracts the line-item array from any document variant
31
+ */
32
+ const getLineItems = (doc) => {
33
+ if ("invoiceLineItems" in doc) return doc.invoiceLineItems;
34
+ if ("creditNoteLineItems" in doc) return doc.creditNoteLineItems;
35
+ if ("debitNoteLineItems" in doc) return doc.debitNoteLineItems;
36
+ if ("refundNoteLineItems" in doc) return doc.refundNoteLineItems;
37
+ if ("selfBilledCreditNoteLineItems" in doc) return doc.selfBilledCreditNoteLineItems;
38
+ if ("selfBilledRefundNoteLineItems" in doc) return doc.selfBilledRefundNoteLineItems;
39
+ return [];
40
+ };
41
+ /**
30
42
  * Helper function to recursively sort object keys for JSON canonicalization
31
43
  */
32
44
  function sortObjectKeys(obj) {
@@ -56,6 +68,7 @@ const canonicalizeJSON = (obj) => {
56
68
  * - Correct listID values (e.g., "3166-1" not "ISO3166-1")
57
69
  */
58
70
  const generateCleanInvoiceObject = (invoice) => {
71
+ const lineItems = getLineItems(invoice);
59
72
  return {
60
73
  ID: [{ _: invoice.eInvoiceCodeOrNumber }],
61
74
  IssueDate: [{ _: invoice.eInvoiceDate }],
@@ -65,6 +78,10 @@ const generateCleanInvoiceObject = (invoice) => {
65
78
  listVersionID: invoice.eInvoiceVersion || "1.1"
66
79
  }],
67
80
  DocumentCurrencyCode: [{ _: invoice.invoiceCurrencyCode }],
81
+ ..."originalEInvoiceReferenceNumber" in invoice && invoice.originalEInvoiceReferenceNumber ? { BillingReference: [{ InvoiceDocumentReference: [{
82
+ UUID: [{ _: invoice.originalEInvoiceReferenceNumber }],
83
+ ID: [{ _: invoice.eInvoiceCodeOrNumber }]
84
+ }] }] } : {},
68
85
  AccountingSupplierParty: [{ Party: [{
69
86
  IndustryClassificationCode: [{
70
87
  _: invoice.supplier.industryClassificationCode,
@@ -133,7 +150,7 @@ const generateCleanInvoiceObject = (invoice) => {
133
150
  currencyID: invoice.invoiceCurrencyCode
134
151
  }],
135
152
  TaxCategory: [{
136
- ID: [{ _: invoice.invoiceLineItems[0]?.taxType || "01" }],
153
+ ID: [{ _: lineItems[0]?.taxType || "01" }],
137
154
  TaxScheme: [{ ID: [{
138
155
  _: "OTH",
139
156
  schemeAgencyID: "6",
@@ -160,7 +177,7 @@ const generateCleanInvoiceObject = (invoice) => {
160
177
  currencyID: invoice.invoiceCurrencyCode
161
178
  }]
162
179
  }],
163
- InvoiceLine: invoice.invoiceLineItems.map((item, index) => ({
180
+ InvoiceLine: lineItems.map((item, index) => ({
164
181
  ID: [{ _: (index + 1).toString() }],
165
182
  Item: [{
166
183
  CommodityClassification: [{ ItemClassificationCode: [{
@@ -1,4 +1,4 @@
1
- import { generateCompleteDocument } from "./document-BvyYSCPx.js";
1
+ import { generateCompleteDocument } from "./document-CX2DalTX.js";
2
2
 
3
3
  //#region src/api/documentSubmission.ts
4
4
  async function submitDocument(context, documents) {
@@ -1,4 +1,4 @@
1
- const require_document = require('./document-djvnrrZo.cjs');
1
+ const require_document = require('./document-BgPF4b8T.cjs');
2
2
 
3
3
  //#region src/api/documentSubmission.ts
4
4
  async function submitDocument(context, documents) {
@@ -134,4 +134,4 @@ Object.defineProperty(exports, 'submitDocument', {
134
134
  return submitDocument;
135
135
  }
136
136
  });
137
- //# sourceMappingURL=documentSubmission-CK1zOsSV.cjs.map
137
+ //# sourceMappingURL=documentSubmission-DTnOLqdW.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"documentSubmission-DTnOLqdW.cjs","names":["context: SubmissionContext","documents: AllDocumentsV1_1[]","context: Pick<SubmissionContext, 'fetch' | 'debug'>","submissionUid: string","pollInterval: number","maxRetries: number","documentUid: string","status: 'rejected' | 'cancelled'","reason: string"],"sources":["../src/api/documentSubmission.ts"],"sourcesContent":["import type {\n AllDocumentsV1_1,\n SubmissionResponse,\n SigningCredentials,\n SubmissionStatus,\n DocumentSummary,\n Fetch,\n StandardError,\n} from '../types'\nimport { generateCompleteDocument } from '../utils/document'\n\ninterface SubmissionContext {\n fetch: Fetch\n debug: boolean\n signingCredentials: SigningCredentials\n}\n\nexport async function submitDocument(\n context: SubmissionContext,\n documents: AllDocumentsV1_1[],\n): Promise<{\n data: SubmissionResponse\n status: number\n}> {\n const { fetch, debug, signingCredentials } = context\n\n if (debug) {\n console.log(`📦 Preparing to submit ${documents.length} document(s)...`)\n }\n\n // Generate the complete signed document structure first\n const completeDocument = generateCompleteDocument(\n documents,\n signingCredentials,\n )\n\n if (debug) {\n console.log('✅ Documents signed successfully')\n console.log('📄 Document structure keys:', Object.keys(completeDocument))\n console.log('📊 Number of invoices:', completeDocument.Invoice.length)\n }\n\n // Convert the complete document to JSON string\n const documentJson = JSON.stringify(completeDocument)\n\n if (debug) {\n console.log(`📏 Document JSON size: ${documentJson.length} bytes`)\n }\n\n // Generate SHA256 hash of the JSON document\n const crypto = await import('crypto')\n const documentHash = crypto\n .createHash('sha256')\n .update(documentJson, 'utf8')\n .digest('hex')\n\n // Base64 encode the JSON document\n const documentBase64 = Buffer.from(documentJson, 'utf8').toString('base64')\n\n if (debug) {\n console.log(`🔒 Document hash: ${documentHash.substring(0, 16)}...`)\n console.log(`📦 Base64 size: ${documentBase64.length} bytes`)\n }\n\n // Build the submission payload according to MyInvois API format\n const submissionPayload = {\n documents: documents.map(doc => ({\n format: 'JSON', // We're submitting JSON format\n document: documentBase64, // Base64 encoded complete document\n documentHash: documentHash, // SHA256 hash of the JSON\n codeNumber: doc.eInvoiceCodeOrNumber, // Document reference number\n })),\n }\n\n if (debug) {\n console.log('🚀 Submission payload structure:')\n console.log('- Format: JSON')\n console.log('- Documents count:', submissionPayload.documents.length)\n console.log(\n '- Total payload size:',\n JSON.stringify(submissionPayload).length,\n 'bytes',\n )\n\n // Validate submission constraints\n const payloadSize = JSON.stringify(submissionPayload).length\n if (payloadSize > 5 * 1024 * 1024) {\n // 5MB\n console.warn('⚠️ WARNING: Payload size exceeds 5MB limit')\n }\n\n if (documents.length > 100) {\n console.warn('⚠️ WARNING: Document count exceeds 100 document limit')\n }\n\n if (documentJson.length > 300 * 1024) {\n // 300KB per document\n console.warn('⚠️ WARNING: Document size exceeds 300KB limit')\n }\n }\n\n // Submit to MyInvois API with proper headers\n const response = await fetch('/api/v1.0/documentsubmissions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(submissionPayload),\n })\n\n if (debug) {\n console.log(`📡 API Response status: ${response.status}`)\n }\n\n const data = (await response.json()) as SubmissionResponse\n\n if (debug) {\n if (response.status !== 202) {\n console.error('❌ Submission failed with status:', response.status)\n console.error('❌ Response data:', data)\n } else {\n console.log('✅ Submission successful!')\n console.log(`📋 Submission UID: ${data.submissionUid}`)\n console.log(\n `✅ Accepted documents: ${data.acceptedDocuments?.length || 0}`,\n )\n console.log(\n `❌ Rejected documents: ${data.rejectedDocuments?.length || 0}`,\n )\n }\n }\n\n return {\n data,\n status: response.status,\n }\n}\n\nexport async function getSubmissionStatus(\n context: Pick<SubmissionContext, 'fetch' | 'debug'>,\n submissionUid: string,\n pollInterval: number = 1000,\n maxRetries: number = 10,\n): Promise<{\n status: SubmissionStatus\n documentSummary?: DocumentSummary[]\n error?: {\n code: string\n message: string | null\n target: string\n details: {\n code: string\n message: string\n target: string\n }[]\n }\n}> {\n const { fetch, debug } = context\n\n try {\n const response = await fetch(\n `/api/v1.0/documentsubmissions/${submissionUid}`,\n )\n\n const data = await response.json()\n\n if (debug) {\n console.log('Submission:', data)\n if (data.error) {\n console.log('Submission error details:', data.error.details)\n }\n }\n\n // If we have a successful response and status is completed, return success\n if (data.overallStatus === 'Valid') {\n return {\n status: data.overallStatus,\n documentSummary: data.documentSummary,\n }\n }\n if (data.overallStatus === 'Invalid') {\n return {\n status: 'Invalid',\n documentSummary: data.documentSummary,\n }\n }\n\n // If we have retries left, continue polling for any non-completed status or errors\n if (maxRetries > 0) {\n await new Promise(resolve => setTimeout(resolve, pollInterval))\n return await getSubmissionStatus(\n context,\n submissionUid,\n pollInterval,\n maxRetries - 1,\n )\n }\n\n // No retries left - return timeout\n return {\n status: 'Invalid',\n error: {\n code: 'Timeout',\n message: 'Submission timed out',\n target: 'submission',\n details: [],\n },\n }\n } catch (error) {\n // Handle any request errors by retrying if we have retries left\n if (maxRetries > 0) {\n if (debug) {\n console.log('Request error, retrying...', error)\n }\n await new Promise(resolve => setTimeout(resolve, pollInterval))\n return await getSubmissionStatus(\n context,\n submissionUid,\n pollInterval,\n maxRetries - 1,\n )\n }\n\n // No retries left - return timeout\n return {\n status: 'Invalid',\n error: {\n code: 'Timeout',\n message: 'Submission timed out after request errors',\n target: 'submission',\n details: [],\n },\n }\n }\n}\n\nexport async function performDocumentAction(\n documentUid: string,\n status: 'rejected' | 'cancelled',\n reason: string,\n): Promise<{\n uuid: string\n status: string\n error: StandardError\n}> {\n const response = await fetch(\n `/api/v1.0/documents/state/${documentUid}/state`,\n {\n method: 'POST',\n body: JSON.stringify({\n status,\n reason,\n }),\n },\n )\n\n const data = (await response.json()) as {\n uuid: string\n status: string\n error: StandardError\n }\n\n return data\n}\n"],"mappings":";;;AAiBA,eAAsB,eACpBA,SACAC,WAIC;CACD,MAAM,EAAE,gBAAO,OAAO,oBAAoB,GAAG;AAE7C,KAAI,MACF,SAAQ,KAAK,yBAAyB,UAAU,OAAO,iBAAiB;CAI1E,MAAM,mBAAmB,0CACvB,WACA,mBACD;AAED,KAAI,OAAO;AACT,UAAQ,IAAI,kCAAkC;AAC9C,UAAQ,IAAI,+BAA+B,OAAO,KAAK,iBAAiB,CAAC;AACzE,UAAQ,IAAI,0BAA0B,iBAAiB,QAAQ,OAAO;CACvE;CAGD,MAAM,eAAe,KAAK,UAAU,iBAAiB;AAErD,KAAI,MACF,SAAQ,KAAK,yBAAyB,aAAa,OAAO,QAAQ;CAIpE,MAAM,SAAS,MAAM,OAAO;CAC5B,MAAM,eAAe,OAClB,WAAW,SAAS,CACpB,OAAO,cAAc,OAAO,CAC5B,OAAO,MAAM;CAGhB,MAAM,iBAAiB,OAAO,KAAK,cAAc,OAAO,CAAC,SAAS,SAAS;AAE3E,KAAI,OAAO;AACT,UAAQ,KAAK,oBAAoB,aAAa,UAAU,GAAG,GAAG,CAAC,KAAK;AACpE,UAAQ,KAAK,kBAAkB,eAAe,OAAO,QAAQ;CAC9D;CAGD,MAAM,oBAAoB,EACxB,WAAW,UAAU,IAAI,UAAQ;EAC/B,QAAQ;EACR,UAAU;EACI;EACd,YAAY,IAAI;CACjB,GAAE,CACJ;AAED,KAAI,OAAO;AACT,UAAQ,IAAI,mCAAmC;AAC/C,UAAQ,IAAI,iBAAiB;AAC7B,UAAQ,IAAI,sBAAsB,kBAAkB,UAAU,OAAO;AACrE,UAA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,KAAK;GACb,iBAAiB,KAAK;EACvB;AAEH,MAAI,KAAK,kBAAkB,UACzB,QAAO;GACL,QAAQ;GACR,iBAAiB,KAAK;EACvB;AAIH,MAAI,aAAa,GAAG;AAClB,SAAM,IAAI,QAAQ,aAAW,WAAW,SAAS,aAAa;AAC9D,UAAO,MAAM,oBACX,SACA,eACA,cACA,aAAa,EACd;EACF;AAGD,SAAO;GACL,QAAQ;GACR,OAAO;IACL,MAAM;IACN,SAAS;IACT,QAAQ;IACR,SAAS,CAAE;GACZ;EACF;CACF,SAAQ,OAAO;AAEd,MAAI,aAAa,GAAG;AAClB,OAAI,MACF,SAAQ,IAAI,8BAA8B,MAAM;AAElD,SAAM,IAAI,QAAQ,aAAW,WAAW,SAAS,aAAa;AAC9D,UAAO,MAAM,oBACX,SACA,eACA,cACA,aAAa,EACd;EACF;AAGD,SAAO;GACL,QAAQ;GACR,OAAO;IACL,MAAM;IACN,SAAS;IACT,QAAQ;IACR,SAAS,CAAE;GACZ;EACF;CACF;AACF;AAED,eAAsB,sBACpBC,aACAC,QACAC,QAKC;CACD,MAAM,WAAW,MAAM,OACpB,4BAA4B,YAAY,SACzC;EACE,QAAQ;EACR,MAAM,KAAK,UAAU;GACnB;GACA;EACD,EAAC;CACH,EACF;CAED,MAAM,OAAQ,MAAM,SAAS,MAAM;AAMnC,QAAO;AACR"}
@@ -259,6 +259,210 @@ interface InvoiceV1_1 {
259
259
  /** Total tax amounts and subtotals. */
260
260
  taxTotal: TaxTotal;
261
261
  }
262
+ interface CreditNoteV1_1 {
263
+ /** Supplier information (AccountingSupplierParty). */
264
+ supplier: Supplier;
265
+ /** Buyer information (AccountingCustomerParty). */
266
+ buyer: Buyer;
267
+
268
+ /** e-Invoice version. Fixed value '1.1'. */
269
+ eInvoiceVersion: '1.1';
270
+ /** e-Invoice type code for Credit Note. Fixed value '02'. */
271
+ eInvoiceTypeCode: EInvoiceTypeCode;
272
+ /** Document reference number used by Supplier for internal tracking purpose. Max 50 chars. */
273
+ eInvoiceCodeOrNumber: string;
274
+ /** LHDNM Unique Identifier Number of the original invoice / document that is being adjusted. 26 chars. */
275
+ originalEInvoiceReferenceNumber: string;
276
+ /** Date of issuance (YYYY-MM-DD) in UTC. Must be the current date. */
277
+ eInvoiceDate: string;
278
+ /** Time of issuance (HH:mm:ssZ) in UTC. Must be the current time. */
279
+ eInvoiceTime: string;
280
+
281
+ /** Specific currency that is used to represent the monetary value stated in the e-Invoice. */
282
+ invoiceCurrencyCode: CurrencyCode;
283
+ /** Rate at which non-Malaysian currency will be converted into Malaysian Ringgit.
284
+ * Mandatory when invoiceCurrencyCode is not 'MYR'.
285
+ */
286
+ currencyExchangeRate?: number;
287
+
288
+ /** Credit note line items. */
289
+ creditNoteLineItems: InvoiceLineItem[];
290
+
291
+ /** Overall monetary totals for the credit note. */
292
+ legalMonetaryTotal: LegalMonetaryTotal;
293
+ /** Total tax amounts and subtotals. */
294
+ taxTotal: TaxTotal;
295
+ }
296
+ interface DebitNoteV1_1 {
297
+ /** Supplier information (AccountingSupplierParty). */
298
+ supplier: Supplier;
299
+ /** Buyer information (AccountingCustomerParty). */
300
+ buyer: Buyer;
301
+
302
+ /** e-Invoice version. Fixed value '1.1'. */
303
+ eInvoiceVersion: '1.1';
304
+ /** e-Invoice type code for Debit Note. Fixed value '03'. */
305
+ eInvoiceTypeCode: EInvoiceTypeCode;
306
+ /** Document reference number used by Supplier for internal tracking purpose. Max 50 chars. */
307
+ eInvoiceCodeOrNumber: string;
308
+ /** LHDNM Unique Identifier Number of the original invoice / document that is being adjusted. Mandatory where applicable (Debit/Credit/Refund notes). */
309
+ originalEInvoiceReferenceNumber: string;
310
+ /** Date of issuance (YYYY-MM-DD) in UTC. Must be the current date. */
311
+ eInvoiceDate: string;
312
+ /** Time of issuance (HH:mm:ssZ) in UTC. Must be the current time. */
313
+ eInvoiceTime: string;
314
+
315
+ /** Specific currency that is used to represent the monetary value stated in the e-Invoice. */
316
+ invoiceCurrencyCode: CurrencyCode;
317
+ /** Rate at which non-Malaysian currency will be converted into Malaysian Ringgit.
318
+ * Mandatory when invoiceCurrencyCode is not 'MYR'.
319
+ */
320
+ currencyExchangeRate?: number;
321
+
322
+ /** Debit note line items (InvoiceLine section with required fields). */
323
+ debitNoteLineItems: InvoiceLineItem[];
324
+
325
+ /** Overall monetary totals for the debit note. */
326
+ legalMonetaryTotal: LegalMonetaryTotal;
327
+ /** Total tax amounts and subtotals. */
328
+ taxTotal: TaxTotal;
329
+ }
330
+ interface RefundNoteV1_1 {
331
+ /** Supplier information (AccountingSupplierParty). */
332
+ supplier: Supplier;
333
+ /** Buyer information (AccountingCustomerParty). */
334
+ buyer: Buyer;
335
+
336
+ /** e-Invoice version. Fixed value '1.1'. */
337
+ eInvoiceVersion: '1.1';
338
+ /** e-Invoice type code for Refund Note. Fixed value '04'. */
339
+ eInvoiceTypeCode: EInvoiceTypeCode;
340
+ /** Document reference number used by Supplier for internal tracking purpose. Max 50 chars. */
341
+ eInvoiceCodeOrNumber: string;
342
+ /** LHDNM Unique Identifier Number of the original invoice / document that is being adjusted. Mandatory where applicable (Debit/Credit/Refund notes). */
343
+ originalEInvoiceReferenceNumber: string;
344
+ /** Date of issuance (YYYY-MM-DD) in UTC. Must be the current date. */
345
+ eInvoiceDate: string;
346
+ /** Time of issuance (HH:mm:ssZ) in UTC. Must be the current time. */
347
+ eInvoiceTime: string;
348
+
349
+ /** Specific currency that is used to represent the monetary value stated in the e-Invoice. */
350
+ invoiceCurrencyCode: CurrencyCode;
351
+ /** Rate at which non-Malaysian currency will be converted into Malaysian Ringgit.
352
+ * Mandatory when invoiceCurrencyCode is not 'MYR'.
353
+ */
354
+ currencyExchangeRate?: number;
355
+
356
+ /** Refund note line items. */
357
+ refundNoteLineItems: InvoiceLineItem[];
358
+
359
+ /** Overall monetary totals for the refund note. */
360
+ legalMonetaryTotal: LegalMonetaryTotal;
361
+ /** Total tax amounts and subtotals. */
362
+ taxTotal: TaxTotal;
363
+ }
364
+ interface SelfBilledInvoiceV1_1 {
365
+ /** Supplier information (AccountingSupplierParty). */
366
+ supplier: Supplier;
367
+ /** Buyer information (AccountingCustomerParty). */
368
+ buyer: Buyer;
369
+
370
+ /** e-Invoice version. Fixed value '1.1'. */
371
+ eInvoiceVersion: '1.1';
372
+ /** e-Invoice type code for Self-Billed Invoice. Fixed value '11'. */
373
+ eInvoiceTypeCode: EInvoiceTypeCode;
374
+ /** Document reference number used by Buyer (acting as issuer) for internal tracking purpose. Max 50 chars. */
375
+ eInvoiceCodeOrNumber: string;
376
+ /** Date of issuance (YYYY-MM-DD) in UTC. Must be the current date. */
377
+ eInvoiceDate: string;
378
+ /** Time of issuance (HH:mm:ssZ) in UTC. Must be the current time. */
379
+ eInvoiceTime: string;
380
+
381
+ /** Specific currency used to represent the monetary values stated in the e-Invoice. */
382
+ invoiceCurrencyCode: CurrencyCode;
383
+ /** Currency exchange rate to MYR when invoiceCurrencyCode is not 'MYR'. Mandatory where applicable. */
384
+ currencyExchangeRate?: number;
385
+
386
+ /** Frequency of billing (e.g., Daily, Monthly). Optional. */
387
+ frequencyOfBilling?: string;
388
+ /** Billing period start date (YYYY-MM-DD). Optional but allowed; include to match spec for optional elements. */
389
+ billingPeriodStartDate?: string;
390
+ /** Billing period end date (YYYY-MM-DD). Optional. */
391
+ billingPeriodEndDate?: string;
392
+
393
+ /** Invoice line items. */
394
+ invoiceLineItems: InvoiceLineItem[];
395
+
396
+ /** Overall monetary totals for the invoice. */
397
+ legalMonetaryTotal: LegalMonetaryTotal;
398
+ /** Total tax amounts and subtotals. */
399
+ taxTotal: TaxTotal;
400
+ }
401
+ interface SelfBilledCreditNoteV1_1 {
402
+ /** Supplier information. */
403
+ supplier: Supplier;
404
+ /** Buyer information. */
405
+ buyer: Buyer;
406
+
407
+ /** Fixed e-Invoice version '1.1'. */
408
+ eInvoiceVersion: '1.1';
409
+ /** e-Invoice type code for Self-Billed Credit Note (code '12'). */
410
+ eInvoiceTypeCode: EInvoiceTypeCode;
411
+ /** Internal document reference number issued by Buyer. Max 50 chars. */
412
+ eInvoiceCodeOrNumber: string;
413
+ /** LHDNM unique identifier of the original self-billed invoice being adjusted. */
414
+ originalEInvoiceReferenceNumber: string;
415
+ /** Date of issuance (YYYY-MM-DD, UTC). */
416
+ eInvoiceDate: string;
417
+ /** Time of issuance (HH:mm:ssZ, UTC). */
418
+ eInvoiceTime: string;
419
+
420
+ /** Currency code for monetary values. */
421
+ invoiceCurrencyCode: CurrencyCode;
422
+ /** Exchange rate to MYR – required when invoiceCurrencyCode ≠ 'MYR'. */
423
+ currencyExchangeRate?: number;
424
+
425
+ /** Line items for the credit note. */
426
+ selfBilledCreditNoteLineItems: InvoiceLineItem[];
427
+
428
+ /** Monetary totals. */
429
+ legalMonetaryTotal: LegalMonetaryTotal;
430
+ /** Tax totals. */
431
+ taxTotal: TaxTotal;
432
+ }
433
+ interface SelfBilledRefundNoteV1_1 {
434
+ /** Supplier information issued in the self-billed refund note. */
435
+ supplier: Supplier;
436
+ /** Buyer information (issuer of the self-billed document). */
437
+ buyer: Buyer;
438
+
439
+ /** Fixed e-Invoice version. */
440
+ eInvoiceVersion: '1.1';
441
+ /** e-Invoice type code for Self-Billed Refund Note (code '14'). */
442
+ eInvoiceTypeCode: EInvoiceTypeCode;
443
+ /** Internal tracking reference number. Max 50 chars. */
444
+ eInvoiceCodeOrNumber: string;
445
+ /** Original self-billed invoice UUID being adjusted (mandatory for refund/credit/debit). */
446
+ originalEInvoiceReferenceNumber: string;
447
+ /** Issue date (YYYY-MM-DD, UTC). */
448
+ eInvoiceDate: string;
449
+ /** Issue time (HH:mm:ssZ, UTC). */
450
+ eInvoiceTime: string;
451
+
452
+ /** Document currency code. */
453
+ invoiceCurrencyCode: CurrencyCode;
454
+ /** Exchange rate to MYR when currency ≠ 'MYR'. */
455
+ currencyExchangeRate?: number;
456
+
457
+ /** Line items contained in the refund note. */
458
+ selfBilledRefundNoteLineItems: InvoiceLineItem[];
459
+
460
+ /** Monetary totals for the document. */
461
+ legalMonetaryTotal: LegalMonetaryTotal;
462
+ /** Tax totals for the document. */
463
+ taxTotal: TaxTotal;
464
+ }
465
+ type AllDocumentsV1_1 = InvoiceV1_1 | CreditNoteV1_1 | DebitNoteV1_1 | RefundNoteV1_1 | SelfBilledInvoiceV1_1 | SelfBilledCreditNoteV1_1 | SelfBilledRefundNoteV1_1;
262
466
  type SubmissionStatus = 'InProgress' | 'Valid' | 'PartiallyValid' | 'Invalid';
263
467
  type DocumentStatus = 'Valid' | 'Invalid' | 'Cancelled' | 'Submitted';
264
468
  type StandardError = {
@@ -665,28 +869,7 @@ interface InvoiceSubmission {
665
869
  SignatureValue: {
666
870
  _: string;
667
871
  }[];
668
- SignedInfo: {
669
- CanonicalizationMethod: {
670
- _: string;
671
- Algorithm: string;
672
- }[];
673
- SignatureMethod: {
674
- _: string;
675
- Algorithm: string;
676
- }[];
677
- Reference: {
678
- Id: string;
679
- Type: string;
680
- URI: string;
681
- DigestMethod: {
682
- _: string;
683
- Algorithm: string;
684
- }[];
685
- DigestValue: {
686
- _: string;
687
- }[];
688
- }[];
689
- }[];
872
+ SignedInfo: SignedInfoObject[];
690
873
  }[];
691
874
  }[];
692
875
  }[];
@@ -703,6 +886,20 @@ interface InvoiceSubmission {
703
886
  _: string;
704
887
  }[];
705
888
  }[];
889
+
890
+ /** Billing reference linking to original invoice (used for credit/debit/refund). Optional. */
891
+ BillingReference?: {
892
+ InvoiceDocumentReference: {
893
+ /** LHDNM Unique Identifier Number */
894
+ UUID: {
895
+ _: string;
896
+ }[];
897
+ /** Internal ID (e-Invoice Code/Number) */
898
+ ID: {
899
+ _: string;
900
+ }[];
901
+ }[];
902
+ }[];
706
903
  }
707
904
 
708
905
  /** Represents the complete UBL document structure with namespace declarations */
@@ -926,5 +1123,5 @@ interface DocumentTypeVersionResponse {
926
1123
  activeTo: string;
927
1124
  }
928
1125
  //#endregion
929
- export { Address, Buyer, CompleteInvoice, DocumentStatus, DocumentSummary, DocumentTypeResponse, DocumentTypeVersion, DocumentTypeVersionResponse, DocumentTypesResponse, DocumentValidationResult, DocumentValidationStepResult, FinalDocumentData, GetSubmissionResponse, InvoiceLineItem, InvoiceSubmission, InvoiceV1_1, LegalMonetaryTotal, RegistrationType, ResponseDocument, SignedInfoObject, SignedInvoiceSubmission, SignedPropertiesData, SignedPropertiesObject, SigningCredentials, StandardError, SubmissionResponse, SubmissionStatus, Supplier, TaxCategory, TaxSubtotal, TaxTotal, UBLDocument, WorkflowParameter };
930
- //# sourceMappingURL=documents-BuU5vKSi.d.cts.map
1126
+ export { Address, AllDocumentsV1_1, Buyer, CompleteInvoice, CreditNoteV1_1, DebitNoteV1_1, DocumentStatus, DocumentSummary, DocumentTypeResponse, DocumentTypeVersion, DocumentTypeVersionResponse, DocumentTypesResponse, DocumentValidationResult, DocumentValidationStepResult, FinalDocumentData, GetSubmissionResponse, InvoiceLineItem, InvoiceSubmission, InvoiceV1_1, LegalMonetaryTotal, RefundNoteV1_1, RegistrationType, ResponseDocument, SelfBilledCreditNoteV1_1, SelfBilledInvoiceV1_1, SelfBilledRefundNoteV1_1, SignedInfoObject, SignedInvoiceSubmission, SignedPropertiesData, SignedPropertiesObject, SigningCredentials, StandardError, SubmissionResponse, SubmissionStatus, Supplier, TaxCategory, TaxSubtotal, TaxTotal, UBLDocument, WorkflowParameter };
1127
+ //# sourceMappingURL=documents-BXxJLeMe.d.cts.map