@ripwords/myinvois-client 0.2.35 → 0.2.37
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 +3 -3
- package/dist/api/documentSubmission.js +2 -2
- package/dist/api/documentTypeManagement.d.ts +2 -2
- package/dist/api/notificationManagement.d.ts +2 -2
- package/dist/api/platformLogin.d.ts +3 -3
- package/dist/api/platformLogin.js +1 -1
- package/dist/api/taxpayerValidation.d.ts +2 -2
- package/dist/{apiQueue-BE3-DB1A.js → apiQueue-CfneHIgD.js} +53 -19
- package/dist/{apiQueue-DDXeQJDC.cjs → apiQueue-CiZxlntc.cjs} +54 -20
- package/dist/apiQueue-CiZxlntc.cjs.map +1 -0
- package/dist/{document-DWsGewNs.cjs → document-CCza2JPL.cjs} +30 -4
- package/dist/document-CCza2JPL.cjs.map +1 -0
- package/dist/{document-DI6hw1MO.js → document-DLFdGSK1.js} +29 -3
- package/dist/{documentSubmission-YwuM4ap1.cjs → documentSubmission-M4UlirJ7.cjs} +8 -7
- package/dist/documentSubmission-M4UlirJ7.cjs.map +1 -0
- package/dist/{documentSubmission-CgW1Cm0W.js → documentSubmission-ZAgXsd3X.js} +7 -6
- package/dist/{documents-4B5YOXeb.d.cts → documents-DCZ3Ffya.d.cts} +39 -1
- package/dist/{documents-ChNlyKB2.d.ts → documents-DzZA3NHj.d.ts} +38 -0
- package/dist/index.cjs +9 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +9 -6
- package/dist/index10.cjs +195 -4
- package/dist/index10.cjs.map +1 -0
- package/dist/index11.cjs +0 -22
- package/dist/index12.cjs +24 -2
- package/dist/{index20.cjs.map → index12.cjs.map} +1 -1
- package/dist/index13.cjs +0 -3
- package/dist/index14.cjs +0 -330
- package/dist/index15.cjs +25 -189
- package/dist/index15.cjs.map +1 -1
- package/dist/index16.cjs +16 -53
- package/dist/index16.cjs.map +1 -1
- package/dist/index17.cjs +0 -532
- package/dist/index18.cjs +25 -187
- package/dist/index18.cjs.map +1 -1
- package/dist/index19.cjs +24 -0
- package/dist/{index27.cjs.map → index19.cjs.map} +1 -1
- package/dist/index20.cjs +0 -25
- package/dist/index23.cjs +3 -28
- package/dist/index24.cjs +9 -21
- package/dist/index24.cjs.map +1 -1
- package/dist/index25.cjs +5 -0
- package/dist/index26.cjs +21 -33
- package/dist/index27.cjs +2 -23
- package/dist/index28.cjs +3 -0
- package/dist/index29.cjs +330 -0
- package/dist/{index14.cjs.map → index29.cjs.map} +1 -1
- package/dist/index3.cjs +2 -2
- package/dist/index30.cjs +193 -0
- package/dist/index30.cjs.map +1 -0
- package/dist/index6.cjs +1 -1
- package/dist/index62.cts.map +1 -1
- package/dist/index65.cts.map +1 -1
- package/dist/index67.cts.map +1 -1
- package/dist/index71.cts.map +1 -1
- package/dist/index8.cjs +61 -3
- package/dist/index8.cjs.map +1 -0
- package/dist/index9.cjs +528 -9
- package/dist/index9.cjs.map +1 -1
- package/dist/{platformLogin-CqI9OLYP.js → platformLogin-B6f18bB7.js} +2 -2
- package/dist/{platformLogin-Ch6hFKoU.cjs → platformLogin-BVTUzLjd.cjs} +3 -3
- package/dist/platformLogin-BVTUzLjd.cjs.map +1 -0
- package/dist/{taxpayer-C9VMf0iv.d.ts → taxpayer-DmHW0m7o.d.ts} +1 -1
- package/dist/{taxpayer-DubRo4qZ.d.cts → taxpayer-Pm90MrPj.d.cts} +2 -2
- 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/apiQueue.js +1 -1
- package/dist/utils/document.d.ts +6 -2
- package/dist/utils/document.js +1 -1
- package/dist/utils/signature-diagnostics.d.ts +2 -2
- package/dist/utils/signature-diagnostics.js +1 -1
- package/dist/utils/validation.d.ts +2 -2
- package/package.json +1 -1
- package/dist/apiQueue-DDXeQJDC.cjs.map +0 -1
- package/dist/document-DWsGewNs.cjs.map +0 -1
- package/dist/documentSubmission-YwuM4ap1.cjs.map +0 -1
- package/dist/index17.cjs.map +0 -1
- package/dist/index23.cjs.map +0 -1
- package/dist/index26.cjs.map +0 -1
- package/dist/platformLogin-Ch6hFKoU.cjs.map +0 -1
|
@@ -51,11 +51,11 @@ import "../YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "../ZX-CDQOfsHh.js";
|
|
52
52
|
import "../XX-DOA-10JW.js";
|
|
53
53
|
import "../unit-types-VgYXIwTT.js";
|
|
54
|
-
import { DocumentStatus, DocumentSummary, DocumentValidationResult, DocumentValidationStepResult } from "../documents-
|
|
54
|
+
import { DocumentStatus, DocumentSummary, DocumentValidationResult, DocumentValidationStepResult } from "../documents-DzZA3NHj.js";
|
|
55
55
|
import "../payment-modes-g3DzLmWb.js";
|
|
56
56
|
import "../signatures-CerHUrj3.js";
|
|
57
57
|
import "../notifications-sFhgh3rJ.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-DmHW0m7o.js";
|
|
59
59
|
import { Fetch } from "../utils-C4FoVKLq.js";
|
|
60
60
|
import "../index-CygwSf0x.js";
|
|
61
61
|
|
|
@@ -51,11 +51,11 @@ import "../YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "../ZX-CDQOfsHh.js";
|
|
52
52
|
import "../XX-DOA-10JW.js";
|
|
53
53
|
import "../unit-types-VgYXIwTT.js";
|
|
54
|
-
import { AllDocumentsV1_1, DocumentSummary, SigningCredentials, StandardError, SubmissionResponse, SubmissionStatus } from "../documents-
|
|
54
|
+
import { AllDocumentsV1_1, DocumentSummary, SigningCredentials, StandardError, SubmissionResponse, SubmissionStatus } from "../documents-DzZA3NHj.js";
|
|
55
55
|
import "../payment-modes-g3DzLmWb.js";
|
|
56
56
|
import "../signatures-CerHUrj3.js";
|
|
57
57
|
import "../notifications-sFhgh3rJ.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-DmHW0m7o.js";
|
|
59
59
|
import { Fetch } from "../utils-C4FoVKLq.js";
|
|
60
60
|
import "../index-CygwSf0x.js";
|
|
61
61
|
|
|
@@ -83,7 +83,7 @@ declare function getSubmissionStatus(context: Pick<SubmissionContext, "fetch" |
|
|
|
83
83
|
}[];
|
|
84
84
|
};
|
|
85
85
|
}>;
|
|
86
|
-
declare function performDocumentAction(documentUid: string, status: "rejected" | "cancelled", reason: string): Promise<{
|
|
86
|
+
declare function performDocumentAction(context: Pick<SubmissionContext, "fetch">, documentUid: string, status: "rejected" | "cancelled", reason: string): Promise<{
|
|
87
87
|
uuid: string;
|
|
88
88
|
status: string;
|
|
89
89
|
error: StandardError;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "../formatIdValue-qTxJqj9o.js";
|
|
2
|
-
import "../document-
|
|
3
|
-
import { getSubmissionStatus, performDocumentAction, submitDocument } from "../documentSubmission-
|
|
2
|
+
import "../document-DLFdGSK1.js";
|
|
3
|
+
import { getSubmissionStatus, performDocumentAction, submitDocument } from "../documentSubmission-ZAgXsd3X.js";
|
|
4
4
|
|
|
5
5
|
export { getSubmissionStatus, performDocumentAction, submitDocument };
|
|
@@ -51,11 +51,11 @@ import "../YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "../ZX-CDQOfsHh.js";
|
|
52
52
|
import "../XX-DOA-10JW.js";
|
|
53
53
|
import "../unit-types-VgYXIwTT.js";
|
|
54
|
-
import { DocumentTypeResponse, DocumentTypeVersionResponse, DocumentTypesResponse } from "../documents-
|
|
54
|
+
import { DocumentTypeResponse, DocumentTypeVersionResponse, DocumentTypesResponse } from "../documents-DzZA3NHj.js";
|
|
55
55
|
import "../payment-modes-g3DzLmWb.js";
|
|
56
56
|
import "../signatures-CerHUrj3.js";
|
|
57
57
|
import "../notifications-sFhgh3rJ.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-DmHW0m7o.js";
|
|
59
59
|
import { Fetch } from "../utils-C4FoVKLq.js";
|
|
60
60
|
import "../index-CygwSf0x.js";
|
|
61
61
|
|
|
@@ -51,11 +51,11 @@ import "../YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "../ZX-CDQOfsHh.js";
|
|
52
52
|
import "../XX-DOA-10JW.js";
|
|
53
53
|
import "../unit-types-VgYXIwTT.js";
|
|
54
|
-
import "../documents-
|
|
54
|
+
import "../documents-DzZA3NHj.js";
|
|
55
55
|
import "../payment-modes-g3DzLmWb.js";
|
|
56
56
|
import "../signatures-CerHUrj3.js";
|
|
57
57
|
import { NotificationResponse, NotificationSearchParams } from "../notifications-sFhgh3rJ.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-DmHW0m7o.js";
|
|
59
59
|
import { Fetch } from "../utils-C4FoVKLq.js";
|
|
60
60
|
import "../index-CygwSf0x.js";
|
|
61
61
|
|
|
@@ -51,16 +51,16 @@ import "../YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "../ZX-CDQOfsHh.js";
|
|
52
52
|
import "../XX-DOA-10JW.js";
|
|
53
53
|
import "../unit-types-VgYXIwTT.js";
|
|
54
|
-
import "../documents-
|
|
54
|
+
import "../documents-DzZA3NHj.js";
|
|
55
55
|
import "../payment-modes-g3DzLmWb.js";
|
|
56
56
|
import "../signatures-CerHUrj3.js";
|
|
57
57
|
import "../notifications-sFhgh3rJ.js";
|
|
58
|
-
import "../taxpayer-
|
|
58
|
+
import "../taxpayer-DmHW0m7o.js";
|
|
59
59
|
import "../utils-C4FoVKLq.js";
|
|
60
60
|
import { ClientCredentials } from "../index-CygwSf0x.js";
|
|
61
61
|
|
|
62
62
|
//#region src/api/platformLogin.d.ts
|
|
63
|
-
declare const platformLogin: (client: ClientCredentials) => Promise<{
|
|
63
|
+
declare const platformLogin: (client: ClientCredentials, fetchFn?: (url: string, options?: RequestInit) => Promise<Response>) => Promise<{
|
|
64
64
|
token: string;
|
|
65
65
|
tokenExpiration: Date;
|
|
66
66
|
}>;
|
|
@@ -51,11 +51,11 @@ import "../YX-F34sJ7Ik.js";
|
|
|
51
51
|
import "../ZX-CDQOfsHh.js";
|
|
52
52
|
import "../XX-DOA-10JW.js";
|
|
53
53
|
import "../unit-types-VgYXIwTT.js";
|
|
54
|
-
import { RegistrationType } from "../documents-
|
|
54
|
+
import { RegistrationType } from "../documents-DzZA3NHj.js";
|
|
55
55
|
import "../payment-modes-g3DzLmWb.js";
|
|
56
56
|
import "../signatures-CerHUrj3.js";
|
|
57
57
|
import "../notifications-sFhgh3rJ.js";
|
|
58
|
-
import { TaxpayerQRCodeResponse, TinSearchParams, TinSearchResponse } from "../taxpayer-
|
|
58
|
+
import { TaxpayerQRCodeResponse, TinSearchParams, TinSearchResponse } from "../taxpayer-DmHW0m7o.js";
|
|
59
59
|
import { Fetch } from "../utils-C4FoVKLq.js";
|
|
60
60
|
import "../index-CygwSf0x.js";
|
|
61
61
|
|
|
@@ -55,11 +55,9 @@ const RATE_LIMITS = {
|
|
|
55
55
|
}
|
|
56
56
|
};
|
|
57
57
|
/**
|
|
58
|
-
* A
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
* <limit>/<window> budget at all times. Each category gets its own
|
|
62
|
-
* instance so limits remain isolated.
|
|
58
|
+
* A token-bucket style rate-limiter with queuing.
|
|
59
|
+
* Uses a sliding window approach to allow bursts while respecting overall limits.
|
|
60
|
+
* Each category gets its own instance so limits remain isolated.
|
|
63
61
|
*/
|
|
64
62
|
var RateLimiter = class {
|
|
65
63
|
limit;
|
|
@@ -68,32 +66,68 @@ var RateLimiter = class {
|
|
|
68
66
|
queue = [];
|
|
69
67
|
nextAvailable = 0;
|
|
70
68
|
timer = null;
|
|
69
|
+
requestTimes = [];
|
|
70
|
+
isProcessing = false;
|
|
71
71
|
constructor(config) {
|
|
72
72
|
this.limit = config.limit;
|
|
73
73
|
this.windowMs = config.windowMs;
|
|
74
|
-
const baseInterval = Math.ceil(this.windowMs / this.limit);
|
|
74
|
+
const baseInterval = Math.ceil(this.windowMs / this.limit * .5);
|
|
75
75
|
const isTestEnv = process.env.NODE_ENV === "test";
|
|
76
76
|
const forceReal = process.env.APIQUEUE_REAL_INTERVAL === "true";
|
|
77
|
-
this.minInterval = isTestEnv && !forceReal ?
|
|
77
|
+
this.minInterval = isTestEnv && !forceReal ? Math.min(10, baseInterval) : baseInterval;
|
|
78
78
|
}
|
|
79
79
|
drainQueue() {
|
|
80
|
-
if (this.queue.length === 0) return;
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
80
|
+
if (this.isProcessing || this.queue.length === 0) return;
|
|
81
|
+
this.isProcessing = true;
|
|
82
|
+
try {
|
|
83
|
+
const now = Date.now();
|
|
84
|
+
this.requestTimes = this.requestTimes.filter((time) => now - time < this.windowMs);
|
|
85
|
+
if (this.requestTimes.length >= this.limit) {
|
|
86
|
+
const oldestRequest = Math.min(...this.requestTimes);
|
|
87
|
+
const nextAvailable = oldestRequest + this.windowMs;
|
|
88
|
+
this.scheduleNextDrain(nextAvailable - now);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
if (now < this.nextAvailable) {
|
|
92
|
+
this.scheduleNextDrain(this.nextAvailable - now);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
const next = this.queue.shift();
|
|
96
|
+
const requestStartTime = Date.now();
|
|
97
|
+
this.requestTimes.push(requestStartTime);
|
|
98
|
+
this.nextAvailable = requestStartTime + this.minInterval;
|
|
99
|
+
this.executeRequest(next);
|
|
100
|
+
} finally {
|
|
101
|
+
this.isProcessing = false;
|
|
88
102
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
this.
|
|
103
|
+
}
|
|
104
|
+
scheduleNextDrain(delay) {
|
|
105
|
+
if (this.timer) clearTimeout(this.timer);
|
|
106
|
+
this.timer = setTimeout(() => {
|
|
107
|
+
this.timer = null;
|
|
108
|
+
this.drainQueue();
|
|
109
|
+
}, Math.max(0, delay));
|
|
110
|
+
}
|
|
111
|
+
async executeRequest(requestFn) {
|
|
112
|
+
try {
|
|
113
|
+
await requestFn();
|
|
114
|
+
} catch {}
|
|
115
|
+
setTimeout(() => {
|
|
116
|
+
this.drainQueue();
|
|
117
|
+
}, 50);
|
|
93
118
|
}
|
|
94
119
|
get queueSize() {
|
|
95
120
|
return this.queue.length;
|
|
96
121
|
}
|
|
122
|
+
cleanup() {
|
|
123
|
+
if (this.timer) {
|
|
124
|
+
clearTimeout(this.timer);
|
|
125
|
+
this.timer = null;
|
|
126
|
+
}
|
|
127
|
+
this.queue = [];
|
|
128
|
+
this.requestTimes = [];
|
|
129
|
+
this.isProcessing = false;
|
|
130
|
+
}
|
|
97
131
|
schedule(fn, debug = false, category) {
|
|
98
132
|
return new Promise((resolve, reject) => {
|
|
99
133
|
const execute = () => {
|
|
@@ -56,11 +56,9 @@ const RATE_LIMITS = {
|
|
|
56
56
|
}
|
|
57
57
|
};
|
|
58
58
|
/**
|
|
59
|
-
* A
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
* <limit>/<window> budget at all times. Each category gets its own
|
|
63
|
-
* instance so limits remain isolated.
|
|
59
|
+
* A token-bucket style rate-limiter with queuing.
|
|
60
|
+
* Uses a sliding window approach to allow bursts while respecting overall limits.
|
|
61
|
+
* Each category gets its own instance so limits remain isolated.
|
|
64
62
|
*/
|
|
65
63
|
var RateLimiter = class {
|
|
66
64
|
limit;
|
|
@@ -69,32 +67,68 @@ var RateLimiter = class {
|
|
|
69
67
|
queue = [];
|
|
70
68
|
nextAvailable = 0;
|
|
71
69
|
timer = null;
|
|
70
|
+
requestTimes = [];
|
|
71
|
+
isProcessing = false;
|
|
72
72
|
constructor(config) {
|
|
73
73
|
this.limit = config.limit;
|
|
74
74
|
this.windowMs = config.windowMs;
|
|
75
|
-
const baseInterval = Math.ceil(this.windowMs / this.limit);
|
|
75
|
+
const baseInterval = Math.ceil(this.windowMs / this.limit * .5);
|
|
76
76
|
const isTestEnv = process.env.NODE_ENV === "test";
|
|
77
77
|
const forceReal = process.env.APIQUEUE_REAL_INTERVAL === "true";
|
|
78
|
-
this.minInterval = isTestEnv && !forceReal ?
|
|
78
|
+
this.minInterval = isTestEnv && !forceReal ? Math.min(10, baseInterval) : baseInterval;
|
|
79
79
|
}
|
|
80
80
|
drainQueue() {
|
|
81
|
-
if (this.queue.length === 0) return;
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
81
|
+
if (this.isProcessing || this.queue.length === 0) return;
|
|
82
|
+
this.isProcessing = true;
|
|
83
|
+
try {
|
|
84
|
+
const now = Date.now();
|
|
85
|
+
this.requestTimes = this.requestTimes.filter((time) => now - time < this.windowMs);
|
|
86
|
+
if (this.requestTimes.length >= this.limit) {
|
|
87
|
+
const oldestRequest = Math.min(...this.requestTimes);
|
|
88
|
+
const nextAvailable = oldestRequest + this.windowMs;
|
|
89
|
+
this.scheduleNextDrain(nextAvailable - now);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
if (now < this.nextAvailable) {
|
|
93
|
+
this.scheduleNextDrain(this.nextAvailable - now);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const next = this.queue.shift();
|
|
97
|
+
const requestStartTime = Date.now();
|
|
98
|
+
this.requestTimes.push(requestStartTime);
|
|
99
|
+
this.nextAvailable = requestStartTime + this.minInterval;
|
|
100
|
+
this.executeRequest(next);
|
|
101
|
+
} finally {
|
|
102
|
+
this.isProcessing = false;
|
|
89
103
|
}
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
this.
|
|
104
|
+
}
|
|
105
|
+
scheduleNextDrain(delay) {
|
|
106
|
+
if (this.timer) clearTimeout(this.timer);
|
|
107
|
+
this.timer = setTimeout(() => {
|
|
108
|
+
this.timer = null;
|
|
109
|
+
this.drainQueue();
|
|
110
|
+
}, Math.max(0, delay));
|
|
111
|
+
}
|
|
112
|
+
async executeRequest(requestFn) {
|
|
113
|
+
try {
|
|
114
|
+
await requestFn();
|
|
115
|
+
} catch {}
|
|
116
|
+
setTimeout(() => {
|
|
117
|
+
this.drainQueue();
|
|
118
|
+
}, 50);
|
|
94
119
|
}
|
|
95
120
|
get queueSize() {
|
|
96
121
|
return this.queue.length;
|
|
97
122
|
}
|
|
123
|
+
cleanup() {
|
|
124
|
+
if (this.timer) {
|
|
125
|
+
clearTimeout(this.timer);
|
|
126
|
+
this.timer = null;
|
|
127
|
+
}
|
|
128
|
+
this.queue = [];
|
|
129
|
+
this.requestTimes = [];
|
|
130
|
+
this.isProcessing = false;
|
|
131
|
+
}
|
|
98
132
|
schedule(fn, debug = false, category) {
|
|
99
133
|
return new Promise((resolve, reject) => {
|
|
100
134
|
const execute = () => {
|
|
@@ -166,4 +200,4 @@ Object.defineProperty(exports, 'queueRequest', {
|
|
|
166
200
|
return queueRequest;
|
|
167
201
|
}
|
|
168
202
|
});
|
|
169
|
-
//# sourceMappingURL=apiQueue-
|
|
203
|
+
//# sourceMappingURL=apiQueue-CiZxlntc.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"apiQueue-CiZxlntc.cjs","names":["RATE_LIMITS: Record<ApiCategory, RateLimitConfig>","config: RateLimitConfig","delay: number","requestFn: () => void","fn: () => Promise<T>","debug: boolean","category?: ApiCategory","category: ApiCategory","path: string","method: string"],"sources":["../src/utils/apiQueue.ts"],"sourcesContent":["// A very small utility that provides per-endpoint request queuing with fixed-window rate-limits.\n// The goal is to make sure that we never exceed the vendor-defined limits while also ensuring\n// that every request is eventually executed.\n//\n// NOTE: This is intentionally minimal – no external dependencies are introduced.\n// If you need more advanced features (persistence, jitter, etc.) consider a library such as `bottleneck`.\n\n/*\nRate-limit specification (per 60-second window)\n----------------------------------------------\nLogin as Taxpayer System : 12\nLogin as Intermediary System : 12\nSubmit Documents : 100\nGet Submission : 300\nCancel Document : 12\nReject Document : 12\nGet Document : 60\nGet Document Details : 125\nGet Recent Documents : 12\nSearch Documents : 12\nSearch Taxpayer's TIN : 60\nTaxpayer's QR Code : 60\n*/\n\nexport type ApiCategory =\n | 'loginTaxpayer'\n | 'loginIntermediary'\n | 'submitDocuments'\n | 'getSubmission'\n | 'cancelDocument'\n | 'rejectDocument'\n | 'getDocument'\n | 'getDocumentDetails'\n | 'getRecentDocuments'\n | 'searchDocuments'\n | 'searchTin'\n | 'taxpayerQr'\n | 'default'\n\ninterface RateLimitConfig {\n limit: number\n windowMs: number\n}\n\nconst WINDOW = 60_000 // 60 seconds\n\n// Hard-coded limits based on the specification above.\nconst RATE_LIMITS: Record<ApiCategory, RateLimitConfig> = {\n loginTaxpayer: { limit: 12, windowMs: WINDOW },\n loginIntermediary: { limit: 12, windowMs: WINDOW },\n submitDocuments: { limit: 100, windowMs: WINDOW },\n getSubmission: { limit: 300, windowMs: WINDOW },\n cancelDocument: { limit: 12, windowMs: WINDOW },\n rejectDocument: { limit: 12, windowMs: WINDOW },\n getDocument: { limit: 60, windowMs: WINDOW },\n getDocumentDetails: { limit: 125, windowMs: WINDOW },\n getRecentDocuments: { limit: 12, windowMs: WINDOW },\n searchDocuments: { limit: 12, windowMs: WINDOW },\n searchTin: { limit: 60, windowMs: WINDOW },\n taxpayerQr: { limit: 60, windowMs: WINDOW },\n default: { limit: 10_000, windowMs: WINDOW }, // effectively no limit\n}\n\n/**\n * A token-bucket style rate-limiter with queuing.\n * Uses a sliding window approach to allow bursts while respecting overall limits.\n * Each category gets its own instance so limits remain isolated.\n */\nclass RateLimiter {\n private readonly limit: number\n private readonly windowMs: number\n private readonly minInterval: number\n\n private queue: Array<() => void> = []\n private nextAvailable = 0 // timestamp (ms) when the next request can be executed\n private timer: NodeJS.Timeout | null = null\n private requestTimes: number[] = [] // Track request timestamps for sliding window\n private isProcessing = false // Prevent race conditions in drainQueue\n\n constructor(config: RateLimitConfig) {\n this.limit = config.limit\n this.windowMs = config.windowMs\n // Use a more reasonable interval that allows bursts while preventing 429s\n // Allow bursts up to 50% of the limit, then space out remaining requests\n const baseInterval = Math.ceil((this.windowMs / this.limit) * 0.5) // 50% of even spacing\n const isTestEnv = process.env.NODE_ENV === 'test'\n const forceReal = process.env.APIQUEUE_REAL_INTERVAL === 'true'\n // In unit-test envs we use minimal spacing unless explicitly forced back on.\n // This prevents test failures while still maintaining some rate limiting\n this.minInterval =\n isTestEnv && !forceReal ? Math.min(10, baseInterval) : baseInterval\n }\n\n private drainQueue() {\n // Prevent race conditions by ensuring only one drainQueue runs at a time\n if (this.isProcessing || this.queue.length === 0) {\n return\n }\n\n this.isProcessing = true\n\n try {\n const now = Date.now()\n\n // Clean up old request times outside the window\n this.requestTimes = this.requestTimes.filter(\n time => now - time < this.windowMs,\n )\n\n // Check if we can make another request within the rate limit\n if (this.requestTimes.length >= this.limit) {\n // We've hit the limit, schedule for when the oldest request expires\n const oldestRequest = Math.min(...this.requestTimes)\n const nextAvailable = oldestRequest + this.windowMs\n\n this.scheduleNextDrain(nextAvailable - now)\n return\n }\n\n // Check minimum interval constraint\n if (now < this.nextAvailable) {\n // Too early – schedule when we're allowed to execute next\n this.scheduleNextDrain(this.nextAvailable - now)\n return\n }\n\n // Execute the next queued task\n const next = this.queue.shift()!\n const requestStartTime = Date.now()\n this.requestTimes.push(requestStartTime)\n this.nextAvailable = requestStartTime + this.minInterval\n\n // Execute the request and handle completion\n this.executeRequest(next)\n } finally {\n this.isProcessing = false\n }\n }\n\n private scheduleNextDrain(delay: number) {\n if (this.timer) {\n clearTimeout(this.timer)\n }\n\n this.timer = setTimeout(\n () => {\n this.timer = null\n this.drainQueue()\n },\n Math.max(0, delay),\n )\n }\n\n private async executeRequest(requestFn: () => void) {\n try {\n await requestFn()\n } catch {\n // Request failed, but we still count it against rate limits\n // This is important to prevent retry storms\n }\n\n // Continue processing the queue after a short delay\n // This allows the request to complete before scheduling the next one\n setTimeout(() => {\n this.drainQueue()\n }, 50) // Reduced delay for better responsiveness\n }\n\n get queueSize() {\n return this.queue.length\n }\n\n // Cleanup method to prevent memory leaks\n cleanup() {\n if (this.timer) {\n clearTimeout(this.timer)\n this.timer = null\n }\n this.queue = []\n this.requestTimes = []\n this.isProcessing = false\n }\n\n schedule<T>(\n fn: () => Promise<T>,\n debug: boolean = false,\n category?: ApiCategory,\n ): Promise<T> {\n return new Promise((resolve, reject) => {\n const execute = () => {\n if (debug && category) {\n console.log(\n `[apiQueue] ▶️ Executing request (${category}). Remaining queue: ${this.queue.length}`,\n )\n }\n try {\n const result = fn()\n if (result && typeof (result as any).then === 'function') {\n ;(result as Promise<T>).then(resolve).catch(reject)\n } else {\n resolve(result as T)\n }\n } catch (err) {\n reject(err)\n }\n }\n\n if (debug && category) {\n console.log(\n `[apiQueue] ⏳ Queued request (${category}). Queue length before push: ${this.queue.length}`,\n )\n }\n\n this.queue.push(execute)\n this.drainQueue()\n })\n }\n}\n\n// A shared registry of limiters keyed by category\nconst limiterRegistry = new Map<ApiCategory, RateLimiter>()\n\nfunction getLimiter(category: ApiCategory): RateLimiter {\n if (!limiterRegistry.has(category)) {\n limiterRegistry.set(category, new RateLimiter(RATE_LIMITS[category]))\n }\n // Non-null because we just set it if missing.\n return limiterRegistry.get(category) as RateLimiter\n}\n\n/**\n * Public helper to schedule a request according to the category's limits.\n */\nexport function queueRequest<T>(\n category: ApiCategory,\n fn: () => Promise<T>,\n debug: boolean = false,\n): Promise<T> {\n const limiter = getLimiter(category)\n return limiter.schedule(fn, debug, category)\n}\n\n/**\n * Very naive path-based category detection. If no matcher fits, the `default` category\n * (effectively unlimited) is returned. Adjust these heuristics as your API surface evolves.\n */\nexport function categorizeRequest(\n path: string,\n method: string = 'GET',\n): ApiCategory {\n const cleanPath = path.toLowerCase()\n const isPost = method?.toUpperCase() === 'POST'\n\n if (cleanPath.includes('/documentsubmissions')) {\n return isPost ? 'submitDocuments' : 'getSubmission'\n }\n\n if (cleanPath.includes('/documentmanagement')) {\n if (cleanPath.endsWith('/cancel')) return 'cancelDocument'\n if (cleanPath.endsWith('/reject')) return 'rejectDocument'\n if (cleanPath.endsWith('/details')) return 'getDocumentDetails'\n if (cleanPath.includes('/recent')) return 'getRecentDocuments'\n // Fallbacks inside document management\n return method === 'GET' ? 'getDocument' : 'searchDocuments'\n }\n\n if (cleanPath.includes('/searchtin')) return 'searchTin'\n if (cleanPath.includes('/qrcode')) return 'taxpayerQr'\n if (cleanPath.includes('/connect/token')) {\n // Distinguish between taxpayer & intermediary based on path hint if possible\n return 'loginTaxpayer'\n }\n\n // -----------------------------\n // New path matchers (v1.0 endpoints)\n // -----------------------------\n\n // Search Documents\n if (cleanPath.includes('/documents/search')) {\n return 'searchDocuments'\n }\n\n // Document raw content\n if (/\\/documents\\/[^/]+\\/raw$/.test(cleanPath)) {\n return 'getDocument'\n }\n\n // Document details\n if (/\\/documents\\/[^/]+\\/details$/.test(cleanPath)) {\n return 'getDocumentDetails'\n }\n\n // Document state actions (cancel/reject)\n if (cleanPath.includes('/documents/state/')) {\n return isPost ? 'cancelDocument' : 'getDocument'\n }\n\n // Taxpayer TIN search & validation share same limit bucket\n if (cleanPath.includes('/taxpayer/search/tin')) return 'searchTin'\n if (cleanPath.includes('/taxpayer/validate/')) return 'searchTin'\n\n // Taxpayer QR code info\n if (cleanPath.includes('/taxpayer/qrcode')) return 'taxpayerQr'\n\n return 'default'\n}\n"],"mappings":";;AA4CA,MAAM,SAAS;AAGf,MAAMA,cAAoD;CACxD,eAAe;EAAE,OAAO;EAAI,UAAU;CAAQ;CAC9C,mBAAmB;EAAE,OAAO;EAAI,UAAU;CAAQ;CAClD,iBAAiB;EAAE,OAAO;EAAK,UAAU;CAAQ;CACjD,eAAe;EAAE,OAAO;EAAK,UAAU;CAAQ;CAC/C,gBAAgB;EAAE,OAAO;EAAI,UAAU;CAAQ;CAC/C,gBAAgB;EAAE,OAAO;EAAI,UAAU;CAAQ;CAC/C,aAAa;EAAE,OAAO;EAAI,UAAU;CAAQ;CAC5C,oBAAoB;EAAE,OAAO;EAAK,UA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escription }]
|
|
190
190
|
}],
|
|
191
191
|
ItemPriceExtension: [{ Amount: [{
|
|
192
|
-
_: item.totalTaxableAmountPerLine,
|
|
192
|
+
_: (item.totalTaxableAmountPerLine ?? 0) + (item.discountAmount ?? 0),
|
|
193
193
|
currencyID: invoice.invoiceCurrencyCode
|
|
194
194
|
}] }],
|
|
195
195
|
LineExtensionAmount: [{
|
|
@@ -200,6 +200,20 @@ const generateCleanInvoiceObject = (invoice) => {
|
|
|
200
200
|
_: item.unitPrice,
|
|
201
201
|
currencyID: invoice.invoiceCurrencyCode
|
|
202
202
|
}] }],
|
|
203
|
+
...item.discountAmount !== void 0 || item.discountRate !== void 0 ? { AllowanceCharge: [{
|
|
204
|
+
ChargeIndicator: [{ _: false }],
|
|
205
|
+
Amount: [{
|
|
206
|
+
_: item.discountAmount ?? 0,
|
|
207
|
+
currencyID: invoice.invoiceCurrencyCode
|
|
208
|
+
}],
|
|
209
|
+
...item.discountRate !== void 0 ? {
|
|
210
|
+
MultiplierFactorNumeric: [{ _: item.discountRate }],
|
|
211
|
+
BaseAmount: [{
|
|
212
|
+
_: (item.totalTaxableAmountPerLine ?? 0) + (item.discountAmount ?? 0),
|
|
213
|
+
currencyID: invoice.invoiceCurrencyCode
|
|
214
|
+
}]
|
|
215
|
+
} : {}
|
|
216
|
+
}] } : {},
|
|
203
217
|
TaxTotal: [{
|
|
204
218
|
TaxAmount: [{
|
|
205
219
|
_: item.taxAmount,
|
|
@@ -533,7 +547,11 @@ const generateCompleteDocument = (invoices, signingCredentials) => {
|
|
|
533
547
|
*/
|
|
534
548
|
const createPercentageTaxLineItem = (params) => {
|
|
535
549
|
const quantity = params.quantity || 1;
|
|
536
|
-
const
|
|
550
|
+
const preDiscountAmount = params.unitPrice * quantity;
|
|
551
|
+
const hasDiscount = params.discountAmount !== void 0 || params.discountRate !== void 0;
|
|
552
|
+
const computedDiscountByRate = hasDiscount && params.discountRate !== void 0 ? preDiscountAmount * params.discountRate : 0;
|
|
553
|
+
const discountAmount = hasDiscount && params.discountAmount !== void 0 ? params.discountAmount : computedDiscountByRate;
|
|
554
|
+
const totalTaxableAmount = Math.max(0, preDiscountAmount - (hasDiscount ? discountAmount : 0));
|
|
537
555
|
const taxAmount = totalTaxableAmount * params.taxRate / 100;
|
|
538
556
|
return {
|
|
539
557
|
itemClassificationCode: params.itemClassificationCode,
|
|
@@ -541,6 +559,8 @@ const createPercentageTaxLineItem = (params) => {
|
|
|
541
559
|
unitPrice: params.unitPrice,
|
|
542
560
|
taxType: params.taxType,
|
|
543
561
|
taxRate: params.taxRate,
|
|
562
|
+
...hasDiscount && discountAmount !== void 0 ? { discountAmount } : {},
|
|
563
|
+
...hasDiscount && params.discountRate !== void 0 ? { discountRate: params.discountRate } : {},
|
|
544
564
|
taxAmount: Math.round(taxAmount * 100) / 100,
|
|
545
565
|
totalTaxableAmountPerLine: totalTaxableAmount,
|
|
546
566
|
totalAmountPerLine: totalTaxableAmount + taxAmount
|
|
@@ -551,7 +571,11 @@ const createPercentageTaxLineItem = (params) => {
|
|
|
551
571
|
*/
|
|
552
572
|
const createFixedRateTaxLineItem = (params) => {
|
|
553
573
|
const quantity = params.quantity || 1;
|
|
554
|
-
const
|
|
574
|
+
const preDiscountAmount = params.unitPrice * quantity;
|
|
575
|
+
const hasDiscount = params.discountAmount !== void 0 || params.discountRate !== void 0;
|
|
576
|
+
const computedDiscountByRate = hasDiscount && params.discountRate !== void 0 ? preDiscountAmount * params.discountRate : 0;
|
|
577
|
+
const discountAmount = hasDiscount && params.discountAmount !== void 0 ? params.discountAmount : computedDiscountByRate;
|
|
578
|
+
const totalTaxableAmount = Math.max(0, preDiscountAmount - (hasDiscount ? discountAmount : 0));
|
|
555
579
|
const taxAmount = params.taxPerUnitAmount * params.baseUnitMeasure;
|
|
556
580
|
return {
|
|
557
581
|
itemClassificationCode: params.itemClassificationCode,
|
|
@@ -561,6 +585,8 @@ const createFixedRateTaxLineItem = (params) => {
|
|
|
561
585
|
taxPerUnitAmount: params.taxPerUnitAmount,
|
|
562
586
|
baseUnitMeasure: params.baseUnitMeasure,
|
|
563
587
|
baseUnitMeasureCode: params.baseUnitMeasureCode,
|
|
588
|
+
...hasDiscount && discountAmount !== void 0 ? { discountAmount } : {},
|
|
589
|
+
...hasDiscount && params.discountRate !== void 0 ? { discountRate: params.discountRate } : {},
|
|
564
590
|
taxAmount: Math.round(taxAmount * 100) / 100,
|
|
565
591
|
totalTaxableAmountPerLine: totalTaxableAmount,
|
|
566
592
|
totalAmountPerLine: totalTaxableAmount + taxAmount
|
|
@@ -698,4 +724,4 @@ Object.defineProperty(exports, 'transformDocumentForHashing', {
|
|
|
698
724
|
return transformDocumentForHashing;
|
|
699
725
|
}
|
|
700
726
|
});
|
|
701
|
-
//# sourceMappingURL=document-
|
|
727
|
+
//# sourceMappingURL=document-CCza2JPL.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"document-CCza2JPL.cjs","names":["item: InvoiceLineItem","doc: AllDocumentsV1_1","obj: unknown","sortedObj: Record<string, unknown>","invoice: AllDocumentsV1_1","invoices: AllDocumentsV1_1[]","invoice: InvoiceSubmission","certificatePem: string","X509Certificate","str: string","issuer: string","serialHex: string","error: unknown","certificateDigest: string","signingTime: string","issuerName: string","serialNumber: string","signedProperties: SignedPropertiesObject","useTargetWrapper: boolean","digestObj: unknown","docDigest: string","propsDigest: string","privateKeyPem: string","signedInfo: SignedInfoObject","documentString: 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 discountAmount?: number\n discountRate?: 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 discountAmount?: number\n discountRate?: 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'\nimport { formatIdValue } from './formatIdValue'\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 'originalEInvoiceInternalId' 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.originalEInvoiceInternalId,\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 _: formatIdValue(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 _: formatIdValue(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 _:\n (item.totalTaxableAmountPerLine ?? 0) +\n (item.discountAmount ?? 0),\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 // Line-level discount (AllowanceCharge with ChargeIndicator=false) – include only if a discount exists\n ...(item.discountAmount !== undefined || item.discountRate !== undefined\n ? {\n AllowanceCharge: [\n {\n ChargeIndicator: [{ _: false }],\n Amount: [\n {\n _: item.discountAmount ?? 0,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n ...(item.discountRate !== undefined\n ? {\n MultiplierFactorNumeric: [{ _: item.discountRate }],\n BaseAmount: [\n {\n _:\n (item.totalTaxableAmountPerLine ?? 0) +\n (item.discountAmount ?? 0),\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n }\n : {}),\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 1: Transform the document for hashing or transmission\n * Removes UBLExtensions and Signature, and minifies the JSON\n * Returns the minified, cleaned JSON string\n *\n * FIXED: Use regex-based minification to match PowerShell script exactly\n */\nexport const transformDocumentForHashing = (\n invoices: AllDocumentsV1_1[],\n): string => {\n // Generate clean UBL document structure\n const cleanDocument = generateCleanUBLDocument(invoices)\n\n // Deep clone to avoid mutating input\n const documentForTransform = JSON.parse(JSON.stringify(cleanDocument))\n if (\n documentForTransform.Invoice &&\n Array.isArray(documentForTransform.Invoice)\n ) {\n documentForTransform.Invoice.forEach((invoice: InvoiceSubmission) => {\n delete invoice.UBLExtensions\n delete invoice.Signature\n })\n }\n\n // Convert to JSON string first\n const jsonString = JSON.stringify(documentForTransform)\n\n // Apply the exact same regex-based minification as PowerShell script\n // This regex preserves whitespace within quoted strings but removes all other whitespace\n const minifiedJson = jsonString.replace(\n /(\"(?:\\\\.|[^\"\\\\])*\")|\\s+/g,\n (match, quotedString) => {\n if (quotedString) {\n return quotedString // Keep string content exactly as-is\n } else {\n return '' // Remove all other whitespace\n }\n },\n )\n\n return minifiedJson\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 // Use the transformation function to get the minified, cleaned JSON string\n const documentString = transformDocumentForHashing(invoices)\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 * FIXED: Match PowerShell script exactly - use raw certificate data like $cert.RawData\n */\nexport const calculateCertificateDigest = (certificatePem: string): string => {\n try {\n // Create X509Certificate object to get raw data (like PowerShell $cert.RawData)\n const cert = new X509Certificate(certificatePem)\n\n // Get the raw certificate data (DER-encoded, like PowerShell $cert.RawData)\n const rawCertificateData = cert.raw\n\n // Calculate SHA-256 hash of raw certificate data (like PowerShell $sha256.ComputeHash($cert.RawData))\n const hash = crypto.createHash('sha256')\n hash.update(rawCertificateData)\n\n // Return as Base64 (like PowerShell [Convert]::ToBase64String($certHash))\n return hash.digest('base64')\n } catch {\n // Fallback to the previous method if X509Certificate fails\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/**\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 // FIXED: Use raw issuer name like PowerShell $cert.IssuerName.Name\n // Apply XML escaping to match PowerShell [System.Security.SecurityElement]::Escape()\n const escapeXmlSpecialChars = (str: string): string => {\n return str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n }\n\n // FIXED: Normalize issuer name to match MyInvois expectations\n // The issuer name should be in the format: \"CN=Trial LHDNM Sub CA V1, OU=Terms of use at http://www.testcertcomp.com.my, O=LHDNM, C=MY\"\n const normalizeIssuerName = (issuer: string): string => {\n // Node returns issuer DN in reverse RDN order (C, O, ... , CN).\n // The MyInvois validator expects forward order (CN first).\n // 1. Break DN into components separated by newline or commas.\n // 2. Reverse to get CN → ... → C ordering.\n // 3. Join with \", \" and ensure single '=' spacing.\n const parts = issuer\n .split(/\\r?\\n|,\\s*/)\n .map(part => part.trim())\n .filter(part => part.length > 0)\n .reverse()\n return parts.join(', ').replace(/\\s*=\\s*/g, '=')\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 // FIXED: Use raw subject name without normalization to match PowerShell $cert.SubjectName.Name\n // The subject name should be in the format shown in the specification\n const rawSubjectName = cert.subject\n\n return {\n issuerName: escapeXmlSpecialChars(normalizeIssuerName(cert.issuer)),\n serialNumber: formatSerialNumber(serialNumberHex),\n subjectName: rawSubjectName, // Use raw subject name like PowerShell\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 _: '',\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 * Calculates the digest over the correct structure for validator compliance.\n * FIXED: Calculate digest from SignedProperties only (without Target wrapper)\n */\nexport const calculateSignedPropertiesDigest = (\n signedProperties: SignedPropertiesObject,\n useTargetWrapper: boolean = true, // Changed to true - validator calculates digest from embedded structure with Target wrapper\n): string => {\n let digestObj: unknown\n if (useTargetWrapper) {\n digestObj = {\n Target: 'signature',\n SignedProperties: signedProperties.SignedProperties,\n }\n } else {\n digestObj = signedProperties.SignedProperties\n }\n\n // FIXED: Don't sort object keys - use exact structure as embedded\n // The validator calculates digest from the exact embedded structure\n const signedPropertiesString = JSON.stringify(digestObj)\n\n // Apply the same regex-based minification as the document transformation\n const minifiedSignedProperties = signedPropertiesString.replace(\n /(\"(?:\\\\.|[^\"\\\\])*\")|\\s+/g,\n (match, quotedString) => {\n if (quotedString) {\n return quotedString // Keep string content exactly as-is\n } else {\n return '' // Remove all other whitespace\n }\n },\n )\n\n const hash = crypto.createHash('sha256')\n hash.update(minifiedSignedProperties, 'utf8')\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: SignedInfoObject = {\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 // Serialize the SignedInfo exactly as it will be embedded (no reordering)\n const signedInfoRaw = JSON.stringify(signedInfo)\n\n try {\n const signer = crypto.createSign('RSA-SHA256')\n signer.update(signedInfoRaw, 'utf8')\n const signatureValue = signer.sign(privateKeyPem, 'base64')\n\n // Reuse the original object so ordering is preserved\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 * Signs the minified document string using the provided private key PEM\n * Returns the signature as a base64 string\n * FIXED: Match PowerShell script exactly - first compute hash, then sign the hash\n */\nexport const signDocumentString = (\n documentString: string,\n privateKeyPem: string,\n): string => {\n // Create signer with RSA-SHA256 (matches PowerShell RSAPKCS1SignatureFormatter)\n const signer = crypto.createSign('RSA-SHA256')\n signer.update(documentString, 'utf8')\n return signer.sign(privateKeyPem, 'base64')\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 // Get the minified, cleaned JSON string for signing\n const documentString = transformDocumentForHashing(invoices)\n\n // Step 3: Sign the minified document string (not the digest)\n const docSignature = signDocumentString(\n documentString,\n signingCredentials.privateKeyPem,\n )\n\n // Generate signing time in proper ISO format matching PowerShell exactly\n // PowerShell: Get-Date -Format \"yyyy-MM-ddTHH:mm:ssZ\"\n const now = new Date()\n const signingTime =\n now.getFullYear() +\n '-' +\n String(now.getMonth() + 1).padStart(2, '0') +\n '-' +\n String(now.getDate()).padStart(2, '0') +\n 'T' +\n String(now.getHours()).padStart(2, '0') +\n ':' +\n String(now.getMinutes()).padStart(2, '0') +\n ':' +\n String(now.getSeconds()).padStart(2, '0') +\n 'Z'\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 using the dedicated function\n const propsDigest = calculateSignedPropertiesDigest(signedProperties)\n\n // Create simple SignedInfo structure (matching PowerShell approach)\n const signedInfo: SignedInfoObject = {\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 // Extract certificate content using raw data (like PowerShell $cert.RawData)\n const cert = new X509Certificate(signingCredentials.certificatePem)\n const certificate = cert.raw.toString('base64')\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: [{ _: docSignature }],\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 discountAmount?: number\n discountRate?: number\n}): InvoiceLineItem => {\n const quantity = params.quantity || 1\n // Compute pre-discount from unit price and quantity only to avoid double-discounting\n const preDiscountAmount = params.unitPrice * quantity\n const hasDiscount =\n params.discountAmount !== undefined || params.discountRate !== undefined\n const computedDiscountByRate =\n hasDiscount && params.discountRate !== undefined\n ? preDiscountAmount * params.discountRate\n : 0\n const discountAmount =\n hasDiscount && params.discountAmount !== undefined\n ? params.discountAmount\n : computedDiscountByRate\n const totalTaxableAmount = Math.max(\n 0,\n preDiscountAmount - (hasDiscount ? discountAmount : 0),\n )\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 ...(hasDiscount && discountAmount !== undefined ? { discountAmount } : {}),\n ...(hasDiscount && params.discountRate !== undefined\n ? { discountRate: params.discountRate }\n : {}),\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 discountAmount?: number\n discountRate?: number\n}): InvoiceLineItem => {\n const quantity = params.quantity || 1\n // Compute pre-discount from unit price and quantity only to avoid double-discounting\n const preDiscountAmount = params.unitPrice * quantity\n const hasDiscount =\n params.discountAmount !== undefined || params.discountRate !== undefined\n const computedDiscountByRate =\n hasDiscount && params.discountRate !== undefined\n ? preDiscountAmount * params.discountRate\n : 0\n const discountAmount =\n hasDiscount && params.discountAmount !== undefined\n ? params.discountAmount\n : computedDiscountByRate\n const totalTaxableAmount = Math.max(\n 0,\n preDiscountAmount - (hasDiscount ? discountAmount : 0),\n )\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 ...(hasDiscount && discountAmount !== undefined ? { discountAmount } : {}),\n ...(hasDiscount && params.discountRate !== undefined\n ? { discountRate: params.discountRate }\n : {}),\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":";;;;;;;;;;;;;AAyBA,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,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