@ripwords/myinvois-client 0.2.3 → 0.2.5
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/dist/api/documentManagement.d.ts +2 -2
- package/dist/api/documentSubmission.d.ts +2 -2
- package/dist/api/documentSubmission.js +2 -2
- package/dist/api/documentTypeManagement.d.ts +4 -4
- package/dist/api/notificationManagement.d.ts +3 -3
- package/dist/api/platformLogin.d.ts +2 -2
- package/dist/api/taxpayerValidation.d.ts +4 -4
- package/dist/api/taxpayerValidation.js +1 -1
- package/dist/{document-BSuYbfXR.js → document-BvyYSCPx.js} +85 -1
- package/dist/{document-vDphtJTv.cjs → document-djvnrrZo.cjs} +121 -1
- package/dist/document-djvnrrZo.cjs.map +1 -0
- package/dist/{documentSubmission-BdJxIB_I.js → documentSubmission-695VhFA8.js} +1 -1
- package/dist/{documentSubmission-D5TC0MPC.cjs → documentSubmission-CK1zOsSV.cjs} +2 -2
- package/dist/{documentSubmission-D5TC0MPC.cjs.map → documentSubmission-CK1zOsSV.cjs.map} +1 -1
- package/dist/documentTypeManagement-DXRLfTsW.cjs.map +1 -1
- package/dist/{documents-zzL50wnG.d.ts → documents-Br8I8SvT.d.ts} +37 -2
- package/dist/{documents-DCOYxz61.d.cts → documents-BuH9ULyn.d.cts} +38 -3
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +8 -8
- package/dist/index.js +3 -3
- package/dist/index10.cjs +16 -187
- package/dist/index10.cjs.map +1 -1
- package/dist/index12.cjs +25 -16
- package/dist/index12.cjs.map +1 -1
- package/dist/index13.cjs +24 -0
- package/dist/{index19.cjs.map → index13.cjs.map} +1 -1
- package/dist/index15.cjs +0 -29
- package/dist/index16.cjs +0 -25
- package/dist/index17.cjs +5 -0
- package/dist/index18.cjs +5 -33
- package/dist/index19.cjs +4 -23
- package/dist/index2.cjs +61 -4
- package/dist/{index8.cjs.map → index2.cjs.map} +1 -1
- package/dist/index20.cjs +3 -0
- package/dist/index21.cjs +3 -0
- package/dist/index22.cjs +5 -0
- package/dist/index25.cjs +7 -1
- package/dist/index27.cjs +1 -1
- package/dist/index28.cjs +53 -0
- package/dist/index28.cjs.map +1 -1
- package/dist/index3.cjs +531 -5
- package/dist/index3.cjs.map +1 -0
- package/dist/index4.cjs +195 -4
- package/dist/index4.cjs.map +1 -0
- package/dist/index5.cjs +0 -3
- package/dist/index6.cjs +24 -2
- package/dist/index6.cjs.map +1 -0
- package/dist/index63.cts.map +1 -1
- package/dist/index64.cts.map +1 -1
- package/dist/index66.cts.map +1 -1
- package/dist/index67.cts.map +1 -1
- package/dist/index7.cjs +0 -5
- package/dist/index70.cts.map +1 -1
- package/dist/index73.cts.map +1 -1
- package/dist/index8.cjs +0 -62
- package/dist/index9.cjs +23 -526
- package/dist/index9.cjs.map +1 -1
- package/dist/notificationManagement-C_qrFwWL.cjs.map +1 -1
- package/dist/{taxpayer-CxAVm7lJ.d.ts → taxpayer-5MlboTnW.d.ts} +1 -1
- package/dist/{taxpayer-aaXyVf7B.d.cts → taxpayer-DVjaFzJw.d.cts} +2 -2
- package/dist/{taxpayerValidation-DdeXCvPT.cjs → taxpayerValidation-CSuifcY1.cjs} +2 -15
- package/dist/taxpayerValidation-CSuifcY1.cjs.map +1 -0
- package/dist/{taxpayerValidation-DI4B6kWx.js → taxpayerValidation-DiLGJg1l.js} +1 -14
- package/dist/types/documents.d.ts +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/taxpayer.d.ts +2 -2
- package/dist/utils/document.d.ts +54 -3
- package/dist/utils/document.js +2 -2
- package/dist/utils/signature-diagnostics.d.ts +2 -2
- package/dist/utils/signature-diagnostics.js +1 -1
- package/dist/utils/validation.d.ts +65 -3
- package/dist/utils/validation.js +53 -1
- package/package.json +1 -1
- package/dist/document-vDphtJTv.cjs.map +0 -1
- package/dist/index15.cjs.map +0 -1
- package/dist/index16.cjs.map +0 -1
- package/dist/index18.cjs.map +0 -1
- package/dist/taxpayerValidation-DdeXCvPT.cjs.map +0 -1
|
@@ -15,7 +15,7 @@ import "../9X-_XRgT2-_.js";
|
|
|
15
15
|
import "../msic-codes-CiPeemFK.js";
|
|
16
16
|
import "../tax-types-BskcyNBv.js";
|
|
17
17
|
import "../state-codes-BaGjZcA8.js";
|
|
18
|
-
import { DocumentStatus, DocumentSummary, DocumentValidationResult, DocumentValidationStepResult } from "../documents-
|
|
18
|
+
import { DocumentStatus, DocumentSummary, DocumentValidationResult, DocumentValidationStepResult } from "../documents-Br8I8SvT.js";
|
|
19
19
|
import "../payment-modes-NpE3OcCV.js";
|
|
20
20
|
import "../1X-C72Wa4pk.js";
|
|
21
21
|
import "../2X-CH89y3Af.js";
|
|
@@ -55,7 +55,7 @@ import "../XX-DOA-10JW.js";
|
|
|
55
55
|
import "../unit-types-VgYXIwTT.js";
|
|
56
56
|
import "../signatures-C-nCPDqt.js";
|
|
57
57
|
import "../notifications-B4l_qRj7.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-5MlboTnW.js";
|
|
59
59
|
import { Fetch } from "../utils-B3mo51Zp.js";
|
|
60
60
|
import "../index-FTgB2nM6.js";
|
|
61
61
|
|
|
@@ -15,7 +15,7 @@ import "../9X-_XRgT2-_.js";
|
|
|
15
15
|
import "../msic-codes-CiPeemFK.js";
|
|
16
16
|
import "../tax-types-BskcyNBv.js";
|
|
17
17
|
import "../state-codes-BaGjZcA8.js";
|
|
18
|
-
import { DocumentSummary, InvoiceV1_1, SigningCredentials, StandardError, SubmissionResponse, SubmissionStatus } from "../documents-
|
|
18
|
+
import { DocumentSummary, InvoiceV1_1, SigningCredentials, StandardError, SubmissionResponse, SubmissionStatus } from "../documents-Br8I8SvT.js";
|
|
19
19
|
import "../payment-modes-NpE3OcCV.js";
|
|
20
20
|
import "../1X-C72Wa4pk.js";
|
|
21
21
|
import "../2X-CH89y3Af.js";
|
|
@@ -55,7 +55,7 @@ import "../XX-DOA-10JW.js";
|
|
|
55
55
|
import "../unit-types-VgYXIwTT.js";
|
|
56
56
|
import "../signatures-C-nCPDqt.js";
|
|
57
57
|
import "../notifications-B4l_qRj7.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-5MlboTnW.js";
|
|
59
59
|
import { Fetch } from "../utils-B3mo51Zp.js";
|
|
60
60
|
import "../index-FTgB2nM6.js";
|
|
61
61
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "../document-
|
|
2
|
-
import { getSubmissionStatus, performDocumentAction, submitDocument } from "../documentSubmission-
|
|
1
|
+
import "../document-BvyYSCPx.js";
|
|
2
|
+
import { getSubmissionStatus, performDocumentAction, submitDocument } from "../documentSubmission-695VhFA8.js";
|
|
3
3
|
|
|
4
4
|
export { getSubmissionStatus, performDocumentAction, submitDocument };
|
|
@@ -15,7 +15,7 @@ import "../9X-_XRgT2-_.js";
|
|
|
15
15
|
import "../msic-codes-CiPeemFK.js";
|
|
16
16
|
import "../tax-types-BskcyNBv.js";
|
|
17
17
|
import "../state-codes-BaGjZcA8.js";
|
|
18
|
-
import { DocumentTypeResponse, DocumentTypeVersionResponse, DocumentTypesResponse
|
|
18
|
+
import { DocumentTypeResponse, DocumentTypeVersionResponse, DocumentTypesResponse } from "../documents-Br8I8SvT.js";
|
|
19
19
|
import "../payment-modes-NpE3OcCV.js";
|
|
20
20
|
import "../1X-C72Wa4pk.js";
|
|
21
21
|
import "../2X-CH89y3Af.js";
|
|
@@ -55,7 +55,7 @@ import "../XX-DOA-10JW.js";
|
|
|
55
55
|
import "../unit-types-VgYXIwTT.js";
|
|
56
56
|
import "../signatures-C-nCPDqt.js";
|
|
57
57
|
import "../notifications-B4l_qRj7.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-5MlboTnW.js";
|
|
59
59
|
import { Fetch } from "../utils-B3mo51Zp.js";
|
|
60
60
|
import "../index-FTgB2nM6.js";
|
|
61
61
|
|
|
@@ -64,7 +64,7 @@ interface DocumentTypeContext {
|
|
|
64
64
|
fetch: Fetch;
|
|
65
65
|
}
|
|
66
66
|
declare function getDocumentTypes(context: DocumentTypeContext): Promise<DocumentTypesResponse>;
|
|
67
|
-
declare function getDocumentType(context: DocumentTypeContext, id: number): Promise<DocumentTypeResponse
|
|
68
|
-
declare function getDocumentTypeVersion(context: DocumentTypeContext, id: number, versionId: number): Promise<DocumentTypeVersionResponse
|
|
67
|
+
declare function getDocumentType(context: DocumentTypeContext, id: number): Promise<DocumentTypeResponse>;
|
|
68
|
+
declare function getDocumentTypeVersion(context: DocumentTypeContext, id: number, versionId: number): Promise<DocumentTypeVersionResponse>;
|
|
69
69
|
//#endregion
|
|
70
70
|
export { getDocumentType, getDocumentTypeVersion, getDocumentTypes };
|
|
@@ -15,7 +15,7 @@ import "../9X-_XRgT2-_.js";
|
|
|
15
15
|
import "../msic-codes-CiPeemFK.js";
|
|
16
16
|
import "../tax-types-BskcyNBv.js";
|
|
17
17
|
import "../state-codes-BaGjZcA8.js";
|
|
18
|
-
import
|
|
18
|
+
import "../documents-Br8I8SvT.js";
|
|
19
19
|
import "../payment-modes-NpE3OcCV.js";
|
|
20
20
|
import "../1X-C72Wa4pk.js";
|
|
21
21
|
import "../2X-CH89y3Af.js";
|
|
@@ -55,7 +55,7 @@ import "../XX-DOA-10JW.js";
|
|
|
55
55
|
import "../unit-types-VgYXIwTT.js";
|
|
56
56
|
import "../signatures-C-nCPDqt.js";
|
|
57
57
|
import { NotificationResponse, NotificationSearchParams } from "../notifications-B4l_qRj7.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-5MlboTnW.js";
|
|
59
59
|
import { Fetch } from "../utils-B3mo51Zp.js";
|
|
60
60
|
import "../index-FTgB2nM6.js";
|
|
61
61
|
|
|
@@ -63,6 +63,6 @@ import "../index-FTgB2nM6.js";
|
|
|
63
63
|
interface NotificationContext {
|
|
64
64
|
fetch: Fetch;
|
|
65
65
|
}
|
|
66
|
-
declare function getNotifications(context: NotificationContext, params: NotificationSearchParams): Promise<NotificationResponse
|
|
66
|
+
declare function getNotifications(context: NotificationContext, params: NotificationSearchParams): Promise<NotificationResponse>;
|
|
67
67
|
//#endregion
|
|
68
68
|
export { getNotifications };
|
|
@@ -15,7 +15,7 @@ import "../9X-_XRgT2-_.js";
|
|
|
15
15
|
import "../msic-codes-CiPeemFK.js";
|
|
16
16
|
import "../tax-types-BskcyNBv.js";
|
|
17
17
|
import "../state-codes-BaGjZcA8.js";
|
|
18
|
-
import "../documents-
|
|
18
|
+
import "../documents-Br8I8SvT.js";
|
|
19
19
|
import "../payment-modes-NpE3OcCV.js";
|
|
20
20
|
import "../1X-C72Wa4pk.js";
|
|
21
21
|
import "../2X-CH89y3Af.js";
|
|
@@ -55,7 +55,7 @@ import "../XX-DOA-10JW.js";
|
|
|
55
55
|
import "../unit-types-VgYXIwTT.js";
|
|
56
56
|
import "../signatures-C-nCPDqt.js";
|
|
57
57
|
import "../notifications-B4l_qRj7.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-5MlboTnW.js";
|
|
59
59
|
import "../utils-B3mo51Zp.js";
|
|
60
60
|
import { ClientCredentials } from "../index-FTgB2nM6.js";
|
|
61
61
|
|
|
@@ -15,7 +15,7 @@ import "../9X-_XRgT2-_.js";
|
|
|
15
15
|
import "../msic-codes-CiPeemFK.js";
|
|
16
16
|
import "../tax-types-BskcyNBv.js";
|
|
17
17
|
import "../state-codes-BaGjZcA8.js";
|
|
18
|
-
import { RegistrationType
|
|
18
|
+
import { RegistrationType } from "../documents-Br8I8SvT.js";
|
|
19
19
|
import "../payment-modes-NpE3OcCV.js";
|
|
20
20
|
import "../1X-C72Wa4pk.js";
|
|
21
21
|
import "../2X-CH89y3Af.js";
|
|
@@ -55,7 +55,7 @@ import "../XX-DOA-10JW.js";
|
|
|
55
55
|
import "../unit-types-VgYXIwTT.js";
|
|
56
56
|
import "../signatures-C-nCPDqt.js";
|
|
57
57
|
import "../notifications-B4l_qRj7.js";
|
|
58
|
-
import { TaxpayerQRCodeResponse, TinSearchParams, TinSearchResponse } from "../taxpayer-
|
|
58
|
+
import { TaxpayerQRCodeResponse, TinSearchParams, TinSearchResponse } from "../taxpayer-5MlboTnW.js";
|
|
59
59
|
import { Fetch } from "../utils-B3mo51Zp.js";
|
|
60
60
|
import "../index-FTgB2nM6.js";
|
|
61
61
|
|
|
@@ -64,8 +64,8 @@ interface TaxpayerContext {
|
|
|
64
64
|
fetch: Fetch;
|
|
65
65
|
debug: boolean;
|
|
66
66
|
}
|
|
67
|
-
declare function tinSearch(context: TaxpayerContext, params: TinSearchParams): Promise<TinSearchResponse
|
|
67
|
+
declare function tinSearch(context: TaxpayerContext, params: TinSearchParams): Promise<TinSearchResponse>;
|
|
68
68
|
declare function verifyTin(context: TaxpayerContext, tin: string, idType: RegistrationType, idValue: string): Promise<boolean>;
|
|
69
|
-
declare function taxpayerQRCode(context: TaxpayerContext, qrCodeText: string): Promise<TaxpayerQRCodeResponse
|
|
69
|
+
declare function taxpayerQRCode(context: TaxpayerContext, qrCodeText: string): Promise<TaxpayerQRCodeResponse>;
|
|
70
70
|
//#endregion
|
|
71
71
|
export { taxpayerQRCode, tinSearch, verifyTin };
|
|
@@ -7,6 +7,26 @@ import crypto, { X509Certificate } from "crypto";
|
|
|
7
7
|
* JSON Signature Guide: https://sdk.myinvois.hasil.gov.my/signature-creation-json/
|
|
8
8
|
*/
|
|
9
9
|
/**
|
|
10
|
+
* Determines if a line item uses fixed rate taxation
|
|
11
|
+
*/
|
|
12
|
+
const isFixedRateTax = (item) => {
|
|
13
|
+
return item.taxPerUnitAmount !== void 0 && item.baseUnitMeasure !== void 0;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Determines if a line item uses percentage taxation
|
|
17
|
+
*/
|
|
18
|
+
const isPercentageTax = (item) => {
|
|
19
|
+
return item.taxRate !== void 0 && !isFixedRateTax(item);
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Calculates expected tax amount for a line item based on its tax type
|
|
23
|
+
*/
|
|
24
|
+
const calculateExpectedTaxAmount = (item) => {
|
|
25
|
+
if (isFixedRateTax(item)) return item.taxPerUnitAmount * item.baseUnitMeasure;
|
|
26
|
+
else if (isPercentageTax(item)) return item.totalTaxableAmountPerLine * item.taxRate / 100;
|
|
27
|
+
return 0;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
10
30
|
* Helper function to recursively sort object keys for JSON canonicalization
|
|
11
31
|
*/
|
|
12
32
|
function sortObjectKeys(obj) {
|
|
@@ -175,6 +195,16 @@ const generateCleanInvoiceObject = (invoice) => {
|
|
|
175
195
|
_: item.taxAmount,
|
|
176
196
|
currencyID: invoice.invoiceCurrencyCode
|
|
177
197
|
}],
|
|
198
|
+
...item.taxPerUnitAmount !== void 0 && item.baseUnitMeasure !== void 0 ? {
|
|
199
|
+
PerUnitAmount: [{
|
|
200
|
+
_: item.taxPerUnitAmount,
|
|
201
|
+
currencyID: invoice.invoiceCurrencyCode
|
|
202
|
+
}],
|
|
203
|
+
BaseUnitMeasure: [{
|
|
204
|
+
_: item.baseUnitMeasure,
|
|
205
|
+
unitCode: item.baseUnitMeasureCode || "C62"
|
|
206
|
+
}]
|
|
207
|
+
} : item.taxRate !== void 0 ? { Percent: [{ _: item.taxRate }] } : {},
|
|
178
208
|
TaxCategory: [{
|
|
179
209
|
ID: [{ _: item.taxType }],
|
|
180
210
|
TaxScheme: [{ ID: [{
|
|
@@ -400,6 +430,60 @@ const generateCompleteDocument = (invoices, signingCredentials) => {
|
|
|
400
430
|
throw new Error(`Document generation failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
401
431
|
}
|
|
402
432
|
};
|
|
433
|
+
/**
|
|
434
|
+
* Creates a line item with percentage-based taxation (e.g., SST, GST)
|
|
435
|
+
*/
|
|
436
|
+
const createPercentageTaxLineItem = (params) => {
|
|
437
|
+
const quantity = params.quantity || 1;
|
|
438
|
+
const totalTaxableAmount = params.totalTaxableAmountPerLine || params.unitPrice * quantity;
|
|
439
|
+
const taxAmount = totalTaxableAmount * params.taxRate / 100;
|
|
440
|
+
return {
|
|
441
|
+
itemClassificationCode: params.itemClassificationCode,
|
|
442
|
+
itemDescription: params.itemDescription,
|
|
443
|
+
unitPrice: params.unitPrice,
|
|
444
|
+
taxType: params.taxType,
|
|
445
|
+
taxRate: params.taxRate,
|
|
446
|
+
taxAmount: Math.round(taxAmount * 100) / 100,
|
|
447
|
+
totalTaxableAmountPerLine: totalTaxableAmount,
|
|
448
|
+
totalAmountPerLine: totalTaxableAmount + taxAmount
|
|
449
|
+
};
|
|
450
|
+
};
|
|
451
|
+
/**
|
|
452
|
+
* Creates a line item with fixed rate taxation (e.g., Tourism Tax)
|
|
453
|
+
*/
|
|
454
|
+
const createFixedRateTaxLineItem = (params) => {
|
|
455
|
+
const quantity = params.quantity || 1;
|
|
456
|
+
const totalTaxableAmount = params.totalTaxableAmountPerLine || params.unitPrice * quantity;
|
|
457
|
+
const taxAmount = params.taxPerUnitAmount * params.baseUnitMeasure;
|
|
458
|
+
return {
|
|
459
|
+
itemClassificationCode: params.itemClassificationCode,
|
|
460
|
+
itemDescription: params.itemDescription,
|
|
461
|
+
unitPrice: params.unitPrice,
|
|
462
|
+
taxType: params.taxType,
|
|
463
|
+
taxPerUnitAmount: params.taxPerUnitAmount,
|
|
464
|
+
baseUnitMeasure: params.baseUnitMeasure,
|
|
465
|
+
baseUnitMeasureCode: params.baseUnitMeasureCode,
|
|
466
|
+
taxAmount: Math.round(taxAmount * 100) / 100,
|
|
467
|
+
totalTaxableAmountPerLine: totalTaxableAmount,
|
|
468
|
+
totalAmountPerLine: totalTaxableAmount + taxAmount
|
|
469
|
+
};
|
|
470
|
+
};
|
|
471
|
+
/**
|
|
472
|
+
* Calculates invoice totals from line items
|
|
473
|
+
*/
|
|
474
|
+
const calculateInvoiceTotals = (lineItems) => {
|
|
475
|
+
const taxExclusiveAmount = lineItems.reduce((sum, item) => sum + item.totalTaxableAmountPerLine, 0);
|
|
476
|
+
const totalTaxAmount = lineItems.reduce((sum, item) => sum + item.taxAmount, 0);
|
|
477
|
+
const taxInclusiveAmount = taxExclusiveAmount + totalTaxAmount;
|
|
478
|
+
return {
|
|
479
|
+
legalMonetaryTotal: {
|
|
480
|
+
taxExclusiveAmount: Math.round(taxExclusiveAmount * 100) / 100,
|
|
481
|
+
taxInclusiveAmount: Math.round(taxInclusiveAmount * 100) / 100,
|
|
482
|
+
payableAmount: Math.round(taxInclusiveAmount * 100) / 100
|
|
483
|
+
},
|
|
484
|
+
taxTotal: { taxAmount: Math.round(totalTaxAmount * 100) / 100 }
|
|
485
|
+
};
|
|
486
|
+
};
|
|
403
487
|
|
|
404
488
|
//#endregion
|
|
405
|
-
export { calculateCertificateDigest, calculateDocumentDigest, calculateSignedPropertiesDigest, canonicalizeJSON, createSignedInfoAndSign, createSignedProperties, extractCertificateInfo, generateCleanInvoiceObject, generateCleanUBLDocument, generateCompleteDocument, sortObjectKeys };
|
|
489
|
+
export { calculateCertificateDigest, calculateDocumentDigest, calculateExpectedTaxAmount, calculateInvoiceTotals, calculateSignedPropertiesDigest, canonicalizeJSON, createFixedRateTaxLineItem, createPercentageTaxLineItem, createSignedInfoAndSign, createSignedProperties, extractCertificateInfo, generateCleanInvoiceObject, generateCleanUBLDocument, generateCompleteDocument, isFixedRateTax, isPercentageTax, sortObjectKeys };
|
|
@@ -8,6 +8,26 @@ const crypto = require_chunk.__toESM(require("crypto"));
|
|
|
8
8
|
* JSON Signature Guide: https://sdk.myinvois.hasil.gov.my/signature-creation-json/
|
|
9
9
|
*/
|
|
10
10
|
/**
|
|
11
|
+
* Determines if a line item uses fixed rate taxation
|
|
12
|
+
*/
|
|
13
|
+
const isFixedRateTax = (item) => {
|
|
14
|
+
return item.taxPerUnitAmount !== void 0 && item.baseUnitMeasure !== void 0;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Determines if a line item uses percentage taxation
|
|
18
|
+
*/
|
|
19
|
+
const isPercentageTax = (item) => {
|
|
20
|
+
return item.taxRate !== void 0 && !isFixedRateTax(item);
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Calculates expected tax amount for a line item based on its tax type
|
|
24
|
+
*/
|
|
25
|
+
const calculateExpectedTaxAmount = (item) => {
|
|
26
|
+
if (isFixedRateTax(item)) return item.taxPerUnitAmount * item.baseUnitMeasure;
|
|
27
|
+
else if (isPercentageTax(item)) return item.totalTaxableAmountPerLine * item.taxRate / 100;
|
|
28
|
+
return 0;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
11
31
|
* Helper function to recursively sort object keys for JSON canonicalization
|
|
12
32
|
*/
|
|
13
33
|
function sortObjectKeys(obj) {
|
|
@@ -176,6 +196,16 @@ const generateCleanInvoiceObject = (invoice) => {
|
|
|
176
196
|
_: item.taxAmount,
|
|
177
197
|
currencyID: invoice.invoiceCurrencyCode
|
|
178
198
|
}],
|
|
199
|
+
...item.taxPerUnitAmount !== void 0 && item.baseUnitMeasure !== void 0 ? {
|
|
200
|
+
PerUnitAmount: [{
|
|
201
|
+
_: item.taxPerUnitAmount,
|
|
202
|
+
currencyID: invoice.invoiceCurrencyCode
|
|
203
|
+
}],
|
|
204
|
+
BaseUnitMeasure: [{
|
|
205
|
+
_: item.baseUnitMeasure,
|
|
206
|
+
unitCode: item.baseUnitMeasureCode || "C62"
|
|
207
|
+
}]
|
|
208
|
+
} : item.taxRate !== void 0 ? { Percent: [{ _: item.taxRate }] } : {},
|
|
179
209
|
TaxCategory: [{
|
|
180
210
|
ID: [{ _: item.taxType }],
|
|
181
211
|
TaxScheme: [{ ID: [{
|
|
@@ -401,6 +431,60 @@ const generateCompleteDocument = (invoices, signingCredentials) => {
|
|
|
401
431
|
throw new Error(`Document generation failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
402
432
|
}
|
|
403
433
|
};
|
|
434
|
+
/**
|
|
435
|
+
* Creates a line item with percentage-based taxation (e.g., SST, GST)
|
|
436
|
+
*/
|
|
437
|
+
const createPercentageTaxLineItem = (params) => {
|
|
438
|
+
const quantity = params.quantity || 1;
|
|
439
|
+
const totalTaxableAmount = params.totalTaxableAmountPerLine || params.unitPrice * quantity;
|
|
440
|
+
const taxAmount = totalTaxableAmount * params.taxRate / 100;
|
|
441
|
+
return {
|
|
442
|
+
itemClassificationCode: params.itemClassificationCode,
|
|
443
|
+
itemDescription: params.itemDescription,
|
|
444
|
+
unitPrice: params.unitPrice,
|
|
445
|
+
taxType: params.taxType,
|
|
446
|
+
taxRate: params.taxRate,
|
|
447
|
+
taxAmount: Math.round(taxAmount * 100) / 100,
|
|
448
|
+
totalTaxableAmountPerLine: totalTaxableAmount,
|
|
449
|
+
totalAmountPerLine: totalTaxableAmount + taxAmount
|
|
450
|
+
};
|
|
451
|
+
};
|
|
452
|
+
/**
|
|
453
|
+
* Creates a line item with fixed rate taxation (e.g., Tourism Tax)
|
|
454
|
+
*/
|
|
455
|
+
const createFixedRateTaxLineItem = (params) => {
|
|
456
|
+
const quantity = params.quantity || 1;
|
|
457
|
+
const totalTaxableAmount = params.totalTaxableAmountPerLine || params.unitPrice * quantity;
|
|
458
|
+
const taxAmount = params.taxPerUnitAmount * params.baseUnitMeasure;
|
|
459
|
+
return {
|
|
460
|
+
itemClassificationCode: params.itemClassificationCode,
|
|
461
|
+
itemDescription: params.itemDescription,
|
|
462
|
+
unitPrice: params.unitPrice,
|
|
463
|
+
taxType: params.taxType,
|
|
464
|
+
taxPerUnitAmount: params.taxPerUnitAmount,
|
|
465
|
+
baseUnitMeasure: params.baseUnitMeasure,
|
|
466
|
+
baseUnitMeasureCode: params.baseUnitMeasureCode,
|
|
467
|
+
taxAmount: Math.round(taxAmount * 100) / 100,
|
|
468
|
+
totalTaxableAmountPerLine: totalTaxableAmount,
|
|
469
|
+
totalAmountPerLine: totalTaxableAmount + taxAmount
|
|
470
|
+
};
|
|
471
|
+
};
|
|
472
|
+
/**
|
|
473
|
+
* Calculates invoice totals from line items
|
|
474
|
+
*/
|
|
475
|
+
const calculateInvoiceTotals = (lineItems) => {
|
|
476
|
+
const taxExclusiveAmount = lineItems.reduce((sum, item) => sum + item.totalTaxableAmountPerLine, 0);
|
|
477
|
+
const totalTaxAmount = lineItems.reduce((sum, item) => sum + item.taxAmount, 0);
|
|
478
|
+
const taxInclusiveAmount = taxExclusiveAmount + totalTaxAmount;
|
|
479
|
+
return {
|
|
480
|
+
legalMonetaryTotal: {
|
|
481
|
+
taxExclusiveAmount: Math.round(taxExclusiveAmount * 100) / 100,
|
|
482
|
+
taxInclusiveAmount: Math.round(taxInclusiveAmount * 100) / 100,
|
|
483
|
+
payableAmount: Math.round(taxInclusiveAmount * 100) / 100
|
|
484
|
+
},
|
|
485
|
+
taxTotal: { taxAmount: Math.round(totalTaxAmount * 100) / 100 }
|
|
486
|
+
};
|
|
487
|
+
};
|
|
404
488
|
|
|
405
489
|
//#endregion
|
|
406
490
|
Object.defineProperty(exports, 'calculateCertificateDigest', {
|
|
@@ -415,6 +499,18 @@ Object.defineProperty(exports, 'calculateDocumentDigest', {
|
|
|
415
499
|
return calculateDocumentDigest;
|
|
416
500
|
}
|
|
417
501
|
});
|
|
502
|
+
Object.defineProperty(exports, 'calculateExpectedTaxAmount', {
|
|
503
|
+
enumerable: true,
|
|
504
|
+
get: function () {
|
|
505
|
+
return calculateExpectedTaxAmount;
|
|
506
|
+
}
|
|
507
|
+
});
|
|
508
|
+
Object.defineProperty(exports, 'calculateInvoiceTotals', {
|
|
509
|
+
enumerable: true,
|
|
510
|
+
get: function () {
|
|
511
|
+
return calculateInvoiceTotals;
|
|
512
|
+
}
|
|
513
|
+
});
|
|
418
514
|
Object.defineProperty(exports, 'calculateSignedPropertiesDigest', {
|
|
419
515
|
enumerable: true,
|
|
420
516
|
get: function () {
|
|
@@ -427,6 +523,18 @@ Object.defineProperty(exports, 'canonicalizeJSON', {
|
|
|
427
523
|
return canonicalizeJSON;
|
|
428
524
|
}
|
|
429
525
|
});
|
|
526
|
+
Object.defineProperty(exports, 'createFixedRateTaxLineItem', {
|
|
527
|
+
enumerable: true,
|
|
528
|
+
get: function () {
|
|
529
|
+
return createFixedRateTaxLineItem;
|
|
530
|
+
}
|
|
531
|
+
});
|
|
532
|
+
Object.defineProperty(exports, 'createPercentageTaxLineItem', {
|
|
533
|
+
enumerable: true,
|
|
534
|
+
get: function () {
|
|
535
|
+
return createPercentageTaxLineItem;
|
|
536
|
+
}
|
|
537
|
+
});
|
|
430
538
|
Object.defineProperty(exports, 'createSignedInfoAndSign', {
|
|
431
539
|
enumerable: true,
|
|
432
540
|
get: function () {
|
|
@@ -463,10 +571,22 @@ Object.defineProperty(exports, 'generateCompleteDocument', {
|
|
|
463
571
|
return generateCompleteDocument;
|
|
464
572
|
}
|
|
465
573
|
});
|
|
574
|
+
Object.defineProperty(exports, 'isFixedRateTax', {
|
|
575
|
+
enumerable: true,
|
|
576
|
+
get: function () {
|
|
577
|
+
return isFixedRateTax;
|
|
578
|
+
}
|
|
579
|
+
});
|
|
580
|
+
Object.defineProperty(exports, 'isPercentageTax', {
|
|
581
|
+
enumerable: true,
|
|
582
|
+
get: function () {
|
|
583
|
+
return isPercentageTax;
|
|
584
|
+
}
|
|
585
|
+
});
|
|
466
586
|
Object.defineProperty(exports, 'sortObjectKeys', {
|
|
467
587
|
enumerable: true,
|
|
468
588
|
get: function () {
|
|
469
589
|
return sortObjectKeys;
|
|
470
590
|
}
|
|
471
591
|
});
|
|
472
|
-
//# sourceMappingURL=document-
|
|
592
|
+
//# sourceMappingURL=document-djvnrrZo.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"document-djvnrrZo.cjs","names":["item: InvoiceV1_1['invoiceLineItems'][0]","obj: unknown","sortedObj: Record<string, unknown>","invoice: InvoiceV1_1","invoices: InvoiceV1_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: string\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: string\n taxRate: number\n totalTaxableAmountPerLine?: number\n}","params: {\n itemClassificationCode: string\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: string\n taxPerUnitAmount: number\n baseUnitMeasure: number\n baseUnitMeasureCode: string\n totalTaxableAmountPerLine?: number\n}","lineItems: InvoiceV1_1['invoiceLineItems']"],"sources":["../src/utils/document.ts"],"sourcesContent":["import crypto, { X509Certificate } from 'crypto'\nimport {\n InvoiceSubmission,\n InvoiceV1_1,\n SigningCredentials,\n SignedPropertiesObject,\n UBLDocument,\n CompleteInvoice,\n SignedInfoObject,\n} 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 = (\n item: InvoiceV1_1['invoiceLineItems'][0],\n): 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 = (\n item: InvoiceV1_1['invoiceLineItems'][0],\n): 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 = (\n item: InvoiceV1_1['invoiceLineItems'][0],\n): 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 * 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: InvoiceV1_1,\n): InvoiceSubmission => {\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 // === 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: [{ _: invoice.invoiceLineItems[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: invoice.invoiceLineItems.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: InvoiceV1_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 = (invoices: InvoiceV1_1[]): 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: InvoiceV1_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: string\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: string\n taxRate: number\n totalTaxableAmountPerLine?: number\n}): InvoiceV1_1['invoiceLineItems'][0] => {\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 as any,\n itemDescription: params.itemDescription,\n unitPrice: params.unitPrice,\n taxType: params.taxType as any,\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: string\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: string\n taxPerUnitAmount: number\n baseUnitMeasure: number\n baseUnitMeasureCode: string\n totalTaxableAmountPerLine?: number\n}): InvoiceV1_1['invoiceLineItems'][0] => {\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 as any,\n itemDescription: params.itemDescription,\n unitPrice: params.unitPrice,\n taxType: params.taxType as any,\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: InvoiceV1_1['invoiceLineItems'],\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":";;;;;;;;;;;;AAoBA,MAAa,iBAAiB,CAC5BA,SACY;AACZ,QACE,KAAK,+BAAkC,KAAK;AAE/C;;;;AAKD,MAAa,kBAAkB,CAC7BA,SACY;AACZ,QAAO,KAAK,uBAA0B,eAAe,KAAK;AAC3D;;;;AAKD,MAAa,6BAA6B,CACxCA,SACW;AACX,KAAI,eAAe,KAAK,CACtB,QAAO,KAAK,mBAAoB,KAAK;UAC5B,gBAAgB,KAAK,CAC9B,QAAQ,KAAK,4BAA4B,KAAK,UAAY;AAE5D,QAAO;AACR;;;;AAKD,SAAgB,eAAeC,KAAuB;AACpD,KAAI,QAAQ,eAAe,QAAQ,SACjC,QAAO;AAGT,KAAI,MAAM,QAAQ,IAAI,CACpB,QAAO,IAAI,IAAI,eAAe;CAGhC,MAAMC,YAAqC,CAAE;CAC7C,MAAM,OAAO,OAAO,KAAK,IAA+B,CAAC,MAAM;AAE/D,MAAK,MAAM,OAAO,KAChB,WAAU,OAAO,eAAgB,IAAgC,KAAK;AAGxE,QAAO;AACR;;;;;AAMD,MAAa,mBAAmB,CAACD,QAAyB;CACxD,MAAM,YAAY,eAAe,IAAI;AAErC,QAAO,KAAK,UAAU,WAAW,MAAM,EAAE;AAC1C;;;;;;;;;;;AAYD,MAAa,6BAA6B,CACxCE,YACsB;AACtB,QAAO;EAEL,IAAI,CAAC,EAAE,GAAG,QAAQ,qBAAsB,CAAC;EACzC,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AG;GAC3D,eAAe,KAAK,MAAM,qBAAqB,IAAI,GAAG;EACvD;EACD,UAAU,EACR,WAAW,KAAK,MAAM,iBAAiB,IAAI,GAAG,IAC/C;CACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const require_document = require('./document-
|
|
1
|
+
const require_document = require('./document-djvnrrZo.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-
|
|
137
|
+
//# sourceMappingURL=documentSubmission-CK1zOsSV.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentSubmission-D5TC0MPC.cjs","names":["context: SubmissionContext","documents: InvoiceV1_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 InvoiceV1_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: InvoiceV1_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,sB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AAK,kBAAkB,QACzB,QAAO;GACL,QAAQ,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"}
|
|
1
|
+
{"version":3,"file":"documentSubmission-CK1zOsSV.cjs","names":["context: SubmissionContext","documents: InvoiceV1_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 InvoiceV1_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: InvoiceV1_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,O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C,QAAO;AACR"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentTypeManagement-DXRLfTsW.cjs","names":["context: DocumentTypeContext","id: number","versionId: number"],"sources":["../src/api/documentTypeManagement.ts"],"sourcesContent":["import type {\n
|
|
1
|
+
{"version":3,"file":"documentTypeManagement-DXRLfTsW.cjs","names":["context: DocumentTypeContext","id: number","versionId: number"],"sources":["../src/api/documentTypeManagement.ts"],"sourcesContent":["import type {\n DocumentTypeResponse,\n DocumentTypesResponse,\n DocumentTypeVersionResponse,\n Fetch,\n} from '../types'\n\ninterface DocumentTypeContext {\n fetch: Fetch\n}\n\nexport async function getDocumentTypes(\n context: DocumentTypeContext,\n): Promise<DocumentTypesResponse> {\n const { fetch } = context\n\n const response = await fetch('/api/v1.0/documenttypes')\n const data = (await response.json()) as DocumentTypesResponse\n\n return data\n}\n\nexport async function getDocumentType(\n context: DocumentTypeContext,\n id: number,\n): Promise<DocumentTypeResponse> {\n const { fetch } = context\n\n const response = await fetch(`/api/v1.0/documenttypes/${id}`)\n const data = (await response.json()) as DocumentTypeResponse\n\n return data\n}\n\nexport async function getDocumentTypeVersion(\n context: DocumentTypeContext,\n id: number,\n versionId: number,\n): Promise<DocumentTypeVersionResponse> {\n const { fetch } = context\n\n const response = await fetch(\n `/api/v1.0/documenttypes/${id}/versions/${versionId}`,\n )\n\n const data = (await response.json()) as DocumentTypeVersionResponse\n\n return data\n}\n"],"mappings":";;AAWA,eAAsB,iBACpBA,SACgC;CAChC,MAAM,EAAE,OAAO,GAAG;CAElB,MAAM,WAAW,MAAM,MAAM,0BAA0B;CACvD,MAAM,OAAQ,MAAM,SAAS,MAAM;AAEnC,QAAO;AACR;AAED,eAAsB,gBACpBA,SACAC,IAC+B;CAC/B,MAAM,EAAE,OAAO,GAAG;CAElB,MAAM,WAAW,MAAM,OAAO,0BAA0B,GAAG,EAAE;CAC7D,MAAM,OAAQ,MAAM,SAAS,MAAM;AAEnC,QAAO;AACR;AAED,eAAsB,uBACpBD,SACAC,IACAC,WACsC;CACtC,MAAM,EAAE,OAAO,GAAG;CAElB,MAAM,WAAW,MAAM,OACpB,0BAA0B,GAAG,YAAY,UAAU,EACrD;CAED,MAAM,OAAQ,MAAM,SAAS,MAAM;AAEnC,QAAO;AACR"}
|