@open-mercato/shared 0.10.1-develop.8289.1.9a25111d49 → 0.10.1-develop.8292.1.59f204debc

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.
@@ -0,0 +1,114 @@
1
+ import { findCurrencyAmountPrecisionError, resolveCurrencyAmountDecimalPlaces, resolveCurrencyDecimalPlaces } from '../currencyPrecision'
2
+ import { registerTelemetryRuntime, resetTelemetryRuntime, type TelemetryRuntime } from '../telemetry/runtime'
3
+
4
+ function registerReporter(reportError: jest.Mock) {
5
+ const runtime: TelemetryRuntime = {
6
+ canUseGlobalTracePropagation: () => false,
7
+ captureTraceContext: () => ({}),
8
+ continueTrace: (_carrier, _name, fn) => fn(),
9
+ recordHttpDuration: () => {},
10
+ reportError,
11
+ shutdown: async () => {},
12
+ }
13
+ registerTelemetryRuntime(runtime)
14
+ }
15
+
16
+ function containerWith(service: unknown) {
17
+ return {
18
+ resolve<T>(name: string): T {
19
+ if (name === 'currencyPrecisionService' && service) return service as T
20
+ throw new Error(`[internal] missing ${name}`)
21
+ },
22
+ }
23
+ }
24
+
25
+ describe('resolveCurrencyAmountDecimalPlaces', () => {
26
+ const lookup = { code: 'ETH', tenantId: 'tenant-1', organizationId: 'org-1' }
27
+
28
+ afterEach(() => resetTelemetryRuntime())
29
+
30
+ it('reports a failed precision lookup and keeps the ISO fallback', async () => {
31
+ const reportError = jest.fn()
32
+ registerReporter(reportError)
33
+ const failure = new Error('[internal] db down')
34
+ const failing = { getDecimalPlaces: async () => { throw failure } }
35
+
36
+ await expect(resolveCurrencyDecimalPlaces(containerWith(failing), { ...lookup, code: 'USD' })).resolves.toBe(2)
37
+ expect(reportError).toHaveBeenCalledWith(failure, {
38
+ module: 'currencies',
39
+ code: 'currencies.precision_lookup_failed',
40
+ })
41
+ })
42
+
43
+ it('keeps the fallback when reporting itself throws', async () => {
44
+ registerReporter(jest.fn(() => { throw new Error('[internal] telemetry down') }))
45
+ const failing = { getDecimalPlaces: async () => { throw new Error('[internal] db down') } }
46
+
47
+ await expect(resolveCurrencyDecimalPlaces(containerWith(failing), { ...lookup, code: 'USD' })).resolves.toBe(2)
48
+ })
49
+
50
+ it('does not report when the optional precision service is absent', async () => {
51
+ const reportError = jest.fn()
52
+ registerReporter(reportError)
53
+
54
+ await expect(resolveCurrencyDecimalPlaces(containerWith(null), { ...lookup, code: 'USD' })).resolves.toBe(2)
55
+ expect(reportError).not.toHaveBeenCalled()
56
+ })
57
+
58
+ it('uses the tenant currency precision when it is higher than the floor', async () => {
59
+ const service = { getDecimalPlaces: jest.fn(async () => 18) }
60
+ await expect(resolveCurrencyAmountDecimalPlaces(containerWith(service), lookup)).resolves.toBe(18)
61
+ expect(service.getDecimalPlaces).toHaveBeenCalledWith(lookup)
62
+ })
63
+
64
+ it('never goes below 4 decimal places', async () => {
65
+ const service = { getDecimalPlaces: async () => 0 }
66
+ await expect(resolveCurrencyAmountDecimalPlaces(containerWith(service), { ...lookup, code: 'JPY' })).resolves.toBe(4)
67
+ })
68
+
69
+ it('falls back to ISO digits when the service is missing or fails', async () => {
70
+ await expect(resolveCurrencyAmountDecimalPlaces(containerWith(null), { ...lookup, code: 'USD' })).resolves.toBe(4)
71
+ const failing = { getDecimalPlaces: async () => { throw new Error('[internal] db down') } }
72
+ await expect(resolveCurrencyAmountDecimalPlaces(containerWith(failing), { ...lookup, code: 'USD' })).resolves.toBe(4)
73
+ })
74
+
75
+ it('falls back to the floor for unknown currency codes', async () => {
76
+ const service = { getDecimalPlaces: async () => null }
77
+ await expect(resolveCurrencyAmountDecimalPlaces(containerWith(service), { ...lookup, code: 'XYZW' })).resolves.toBe(4)
78
+ })
79
+
80
+ it('returns null for well-formed codes the runtime does not know', async () => {
81
+ const service = { getDecimalPlaces: async () => null }
82
+ await expect(resolveCurrencyDecimalPlaces(containerWith(service), { ...lookup, code: 'ETH' })).resolves.toBeNull()
83
+ await expect(resolveCurrencyDecimalPlaces(containerWith(null), { ...lookup, code: 'XYZ' })).resolves.toBeNull()
84
+ await expect(resolveCurrencyDecimalPlaces(containerWith(null), { ...lookup, code: 'KWD' })).resolves.toBe(3)
85
+ })
86
+ })
87
+
88
+ describe('findCurrencyAmountPrecisionError', () => {
89
+ it('returns precision details with canonical amounts and currency codes', () => {
90
+ expect(findCurrencyAmountPrecisionError({ amount: '10.0050', currencyCode: ' usd ', decimalPlaces: 2 })).toEqual({
91
+ amount: '10.005', currencyCode: 'USD', decimalPlaces: 2,
92
+ })
93
+ })
94
+
95
+ it('caps configured precision at ISO minor units', () => {
96
+ expect(findCurrencyAmountPrecisionError({ amount: '10.005', currencyCode: 'USD', decimalPlaces: 4 }))
97
+ .toEqual({ amount: '10.005', currencyCode: 'USD', decimalPlaces: 2 })
98
+ expect(findCurrencyAmountPrecisionError({ amount: '10.5', currencyCode: 'USD', decimalPlaces: 0 }))
99
+ .toEqual({ amount: '10.5', currencyCode: 'USD', decimalPlaces: 0 })
100
+ })
101
+
102
+ it('preserves configured precision for non-ISO currencies', () => {
103
+ expect(findCurrencyAmountPrecisionError({ amount: '0.000000000000000001', currencyCode: 'ETH', decimalPlaces: 18 })).toBeNull()
104
+ expect(findCurrencyAmountPrecisionError({ amount: '0.0000000000000000001', currencyCode: 'ETH', decimalPlaces: 18 }))
105
+ .toEqual({ amount: '0.0000000000000000001', currencyCode: 'ETH', decimalPlaces: 18 })
106
+ })
107
+
108
+ it('accepts trailing zeros and skips unknown precision or invalid inputs', () => {
109
+ expect(findCurrencyAmountPrecisionError({ amount: '10.0500', currencyCode: 'USD', decimalPlaces: 2 })).toBeNull()
110
+ expect(findCurrencyAmountPrecisionError({ amount: '1.123456', currencyCode: 'XYZ', decimalPlaces: null })).toBeNull()
111
+ expect(findCurrencyAmountPrecisionError({ amount: 'invalid', currencyCode: 'USD', decimalPlaces: 2 })).toBeNull()
112
+ expect(findCurrencyAmountPrecisionError({ amount: '10.005', currencyCode: null, decimalPlaces: 2 })).toBeNull()
113
+ })
114
+ })
@@ -0,0 +1,381 @@
1
+ import { z } from 'zod'
2
+ import {
3
+ addDecimals,
4
+ amountComparisonTolerance,
5
+ compareDecimals,
6
+ countDecimalPlaces,
7
+ type DecimalValue,
8
+ decimalStringSchema,
9
+ decimalToString,
10
+ divideDecimals,
11
+ isDecimalInput,
12
+ isZeroDecimal,
13
+ MAX_DECIMAL_EXPONENT,
14
+ MAX_DECIMAL_INPUT_LENGTH,
15
+ MAX_DECIMAL_INTEGER_DIGITS,
16
+ MAX_DECIMAL_SIGNIFICANT_DIGITS,
17
+ maxDecimal,
18
+ minDecimal,
19
+ multiplyDecimals,
20
+ nonNegativeDecimalStringSchema,
21
+ padDecimalPlaces,
22
+ parseDecimal,
23
+ positiveDecimalStringSchema,
24
+ resolveAmountDecimalPlaces,
25
+ resolveExactDecimal,
26
+ resolveCurrencyDisplayDecimalPlaces,
27
+ resolveIsoCurrencyDecimalPlaces,
28
+ roundDecimal,
29
+ subtractDecimals,
30
+ sumDecimals,
31
+ toDecimal,
32
+ withExactAmounts,
33
+ withDecimalCaps,
34
+ withExactListAmounts,
35
+ } from '../decimal'
36
+ import { ISO_4217_MINOR_UNITS } from '../isoCurrencyMinorUnits'
37
+
38
+ describe('decimal', () => {
39
+ it('adds without float drift', () => {
40
+ expect(decimalToString(addDecimals('0.1', '0.2'))).toBe('0.3')
41
+ expect(decimalToString(addDecimals(0.1, 0.2))).toBe('0.3')
42
+ })
43
+
44
+ it('keeps 18+ decimal places exactly', () => {
45
+ const wei = '0.000000000000000001'
46
+ expect(decimalToString(multiplyDecimals(wei, 3))).toBe('0.000000000000000003')
47
+ expect(decimalToString(addDecimals('123456789012345678901234567890', wei))).toBe(
48
+ '123456789012345678901234567890.000000000000000001',
49
+ )
50
+ expect(decimalToString(subtractDecimals('1', '0.0000000000000000000000000001'))).toBe(
51
+ '0.9999999999999999999999999999',
52
+ )
53
+ })
54
+
55
+ it('never outputs exponent notation or padding', () => {
56
+ expect(decimalToString('1e-7')).toBe('0.0000001')
57
+ expect(decimalToString(1e21)).toBe('1000000000000000000000')
58
+ expect(decimalToString('40.0000')).toBe('40')
59
+ expect(decimalToString('-0')).toBe('0')
60
+ expect(decimalToString(' +12.50 ')).toBe('12.5')
61
+ })
62
+
63
+ it('divides with at least the requested decimal places', () => {
64
+ expect(decimalToString(divideDecimals(1, 3, 20))).toBe('0.33333333333333333333')
65
+ expect(decimalToString(divideDecimals(10, 4, 4))).toBe('2.5')
66
+ })
67
+
68
+ it('keeps at least 17 significant digits in a quotient', () => {
69
+ const quotient = decimalToString(divideDecimals('1', '30000000000000000000000000000000000000000000000000000000000', 4))
70
+ const significant = quotient.replace(/^0\.0*/, '')
71
+ expect(significant.length).toBeGreaterThanOrEqual(17)
72
+ expect(divideDecimals('1', '7', 0).toFixed().replace('.', '').length).toBeGreaterThanOrEqual(17)
73
+ })
74
+
75
+ it('rejects division by zero', () => {
76
+ expect(() => divideDecimals(1, 0)).toThrow()
77
+ })
78
+
79
+ it('rounds half away from zero', () => {
80
+ expect(decimalToString(roundDecimal('2.5', 0))).toBe('3')
81
+ expect(decimalToString(roundDecimal('-2.5', 0))).toBe('-3')
82
+ expect(decimalToString(roundDecimal('1.23455', 4))).toBe('1.2346')
83
+ })
84
+
85
+ it('compares, sums and picks extremes', () => {
86
+ expect(compareDecimals('1.10', '1.1')).toBe(0)
87
+ expect(compareDecimals('0.000000000000000002', '0.000000000000000001')).toBe(1)
88
+ expect(decimalToString(sumDecimals(['0.1', '0.2', 0.3]))).toBe('0.6')
89
+ expect(decimalToString(sumDecimals([]))).toBe('0')
90
+ expect(decimalToString(minDecimal('3', '-1', '2'))).toBe('-1')
91
+ expect(decimalToString(maxDecimal('3', '-1', '2'))).toBe('3')
92
+ })
93
+
94
+ it('rejects exponents that would expand into huge strings', () => {
95
+ expect(parseDecimal('1e-100000000')).toBeNull()
96
+ expect(parseDecimal('1e100000000')).toBeNull()
97
+ expect(() => toDecimal('1e-1001')).toThrow()
98
+ expect(decimalStringSchema.safeParse('1e-100000000').success).toBe(false)
99
+ expect(decimalToString('1e-20')).toBe('0.00000000000000000001')
100
+ })
101
+
102
+ it('caps the significant digits of an input', () => {
103
+ const longest = '1'.repeat(MAX_DECIMAL_SIGNIFICANT_DIGITS)
104
+ expect(isDecimalInput(`0.${longest}`)).toBe(true)
105
+ expect(isDecimalInput(`0.${longest}1`)).toBe(false)
106
+ expect(isDecimalInput(`0.${longest}000`)).toBe(true)
107
+ expect(decimalStringSchema.safeParse(`0.${'9'.repeat(MAX_DECIMAL_SIGNIFICANT_DIGITS + 1)}`).success).toBe(false)
108
+ })
109
+
110
+ it('caps the magnitude so the float copy stays finite', () => {
111
+ const largest = '9'.repeat(MAX_DECIMAL_INTEGER_DIGITS)
112
+ expect(isDecimalInput(largest)).toBe(true)
113
+ expect(Number.isFinite(Number(largest))).toBe(true)
114
+ expect(isDecimalInput(`1${'0'.repeat(MAX_DECIMAL_INTEGER_DIGITS)}`)).toBe(false)
115
+ expect(isDecimalInput('9.99e299')).toBe(true)
116
+ expect(isDecimalInput('1e300')).toBe(false)
117
+ expect(isDecimalInput('0.01e301')).toBe(true)
118
+ expect(isDecimalInput('0.01e302')).toBe(false)
119
+ expect(isDecimalInput(1e300)).toBe(false)
120
+ expect(parseDecimal(Number.MAX_VALUE)).toBeNull()
121
+ expect(() => toDecimal(1e300)).toThrow()
122
+ expect(decimalStringSchema.safeParse('1e300').success).toBe(false)
123
+ })
124
+
125
+ it('caps how far below the decimal point a digit may sit', () => {
126
+ expect(isDecimalInput('1e-1000')).toBe(true)
127
+ expect(isDecimalInput('1.5e-1000')).toBe(false)
128
+ expect(isDecimalInput(`0.${'0'.repeat(999)}1`)).toBe(true)
129
+ expect(isDecimalInput(`0.${'0'.repeat(20000)}1`)).toBe(false)
130
+ expect(isDecimalInput(`0.${'0'.repeat(2000)}`)).toBe(true)
131
+ })
132
+
133
+ it('caps the overall input length', () => {
134
+ expect(isDecimalInput(`${'0'.repeat(MAX_DECIMAL_INPUT_LENGTH - 1)}1`)).toBe(true)
135
+ expect(isDecimalInput(`${'0'.repeat(MAX_DECIMAL_INPUT_LENGTH)}1`)).toBe(false)
136
+ expect(isDecimalInput(`0.${'0'.repeat(20000)}`)).toBe(false)
137
+ })
138
+
139
+ it('keeps every arithmetic result parseable', () => {
140
+ const inputs = ['0', '1', '-1', '0.1', '1e-600', '-1e-600', '1e299', `0.${'3'.repeat(999)}`, '123456789.987654321']
141
+ const outOfRange = (operation: () => DecimalValue): DecimalValue[] => {
142
+ try {
143
+ return [operation()]
144
+ } catch (error) {
145
+ expect((error as Error).message).toBe('[internal] Decimal result out of range')
146
+ return []
147
+ }
148
+ }
149
+ const results = inputs.flatMap((left) => inputs.flatMap((right) => [
150
+ ...outOfRange(() => addDecimals(left, right)),
151
+ ...outOfRange(() => subtractDecimals(left, right)),
152
+ ...outOfRange(() => sumDecimals([left, right])),
153
+ ...outOfRange(() => multiplyDecimals(left, right)),
154
+ ...(isZeroDecimal(right) ? [] : outOfRange(() => divideDecimals(left, right))),
155
+ ]))
156
+ expect(results.length).toBeGreaterThan(inputs.length * inputs.length * 3)
157
+ for (const result of results) {
158
+ expect(parseDecimal(decimalToString(result))?.eq(result)).toBe(true)
159
+ }
160
+ })
161
+
162
+ it('rounds chained products to the caps instead of growing past them', () => {
163
+ let value = divideDecimals(1, 3)
164
+ const seventh = divideDecimals(1, 7)
165
+ for (let step = 0; step < 25; step += 1) value = multiplyDecimals(value, seventh)
166
+ expect(countDecimalPlaces(value)).toBeLessThanOrEqual(MAX_DECIMAL_EXPONENT)
167
+ expect(parseDecimal(decimalToString(value))).not.toBeNull()
168
+ expect(decimalToString(multiplyDecimals('1e-600', '1e-600'))).toBe('0')
169
+ })
170
+
171
+ it('throws instead of producing a value past the integer cap', () => {
172
+ expect(() => multiplyDecimals('1e299', '1e299')).toThrow('[internal] Decimal result out of range')
173
+ expect(() => addDecimals(`9${'9'.repeat(299)}`, 1)).toThrow('[internal] Decimal result out of range')
174
+ })
175
+
176
+ it('accepts a Big from another copy of big.js', () => {
177
+ const foreign = { c: [1, 2, 3], e: 0, s: 1, toString: () => '1.23' }
178
+ expect(isDecimalInput(foreign)).toBe(true)
179
+ expect(decimalToString(addDecimals(foreign as unknown as DecimalValue, 1))).toBe('2.23')
180
+ expect(isDecimalInput({ c: [1], e: 999999, s: 1 })).toBe(false)
181
+ expect(() => toDecimal({ c: 'x' } as unknown as DecimalValue)).toThrow('[internal] Invalid decimal value')
182
+ })
183
+
184
+ it('rejects invalid decimal places and empty extremes with internal errors', () => {
185
+ expect(() => divideDecimals(1, 3, Number.NaN)).toThrow('[internal] Invalid decimal places')
186
+ expect(() => divideDecimals(1, 3, 2.5)).toThrow('[internal] Invalid decimal places')
187
+ expect(() => roundDecimal(1, -1)).toThrow('[internal] Invalid decimal places')
188
+ expect(() => padDecimalPlaces(1, 1001)).toThrow('[internal] Invalid decimal places')
189
+ expect(() => amountComparisonTolerance(1200)).toThrow('[internal] Invalid decimal places')
190
+ expect(() => minDecimal()).toThrow('[internal] minDecimal requires at least one value')
191
+ expect(() => maxDecimal()).toThrow('[internal] maxDecimal requires at least one value')
192
+ })
193
+
194
+ it('parses loosely and validates strictly', () => {
195
+ expect(parseDecimal(null)).toBeNull()
196
+ expect(parseDecimal('')).toBeNull()
197
+ expect(parseDecimal('abc')).toBeNull()
198
+ expect(parseDecimal(Number.NaN)).toBeNull()
199
+ expect(decimalToString(parseDecimal('12.3400')!)).toBe('12.34')
200
+ expect(() => toDecimal('1,5')).toThrow()
201
+ expect(() => toDecimal(Number.POSITIVE_INFINITY)).toThrow()
202
+ })
203
+
204
+ it('pads to a minimum number of decimals without cutting digits', () => {
205
+ expect(padDecimalPlaces('12.5', 2)).toBe('12.50')
206
+ expect(padDecimalPlaces('12', 0)).toBe('12')
207
+ expect(padDecimalPlaces('0.000000000000000001', 2)).toBe('0.000000000000000001')
208
+ })
209
+
210
+ it('resolves amount precision with a 4 decimal floor', () => {
211
+ expect(resolveAmountDecimalPlaces(2)).toBe(4)
212
+ expect(resolveAmountDecimalPlaces(8)).toBe(8)
213
+ expect(resolveAmountDecimalPlaces(18)).toBe(18)
214
+ expect(resolveAmountDecimalPlaces(null)).toBe(4)
215
+ expect(resolveAmountDecimalPlaces(-1)).toBe(4)
216
+ })
217
+
218
+ it('resolves ISO currency digits', () => {
219
+ expect(resolveIsoCurrencyDecimalPlaces('USD')).toBe(2)
220
+ expect(resolveIsoCurrencyDecimalPlaces('JPY')).toBe(0)
221
+ expect(resolveIsoCurrencyDecimalPlaces('kwd')).toBe(3)
222
+ expect(resolveIsoCurrencyDecimalPlaces(null)).toBeNull()
223
+ })
224
+
225
+ it('resolves ISO 4217 minor units from the static table, not Intl display digits', () => {
226
+ expect(resolveIsoCurrencyDecimalPlaces('HUF')).toBe(2)
227
+ expect(resolveIsoCurrencyDecimalPlaces('COP')).toBe(2)
228
+ expect(resolveIsoCurrencyDecimalPlaces('IDR')).toBe(2)
229
+ expect(resolveIsoCurrencyDecimalPlaces('huf')).toBe(2)
230
+ expect(resolveIsoCurrencyDecimalPlaces('IQD')).toBe(3)
231
+ expect(resolveIsoCurrencyDecimalPlaces('BHD')).toBe(3)
232
+ expect(resolveIsoCurrencyDecimalPlaces('CLF')).toBe(4)
233
+ expect(resolveIsoCurrencyDecimalPlaces('UYW')).toBe(4)
234
+ expect(resolveIsoCurrencyDecimalPlaces('ISK')).toBe(0)
235
+ expect(resolveIsoCurrencyDecimalPlaces('VND')).toBe(0)
236
+ })
237
+
238
+ it('returns null for ISO codes without a minor unit', () => {
239
+ expect(resolveIsoCurrencyDecimalPlaces('XAU')).toBeNull()
240
+ expect(resolveIsoCurrencyDecimalPlaces('XDR')).toBeNull()
241
+ expect(resolveIsoCurrencyDecimalPlaces('XXX')).toBeNull()
242
+ expect(resolveIsoCurrencyDecimalPlaces('HRK')).toBeNull()
243
+ expect(resolveIsoCurrencyDecimalPlaces('DEM')).toBeNull()
244
+ })
245
+
246
+ it('lists every ISO 4217 code, current and withdrawn', () => {
247
+ expect(Object.keys(ISO_4217_MINOR_UNITS)).toHaveLength(307)
248
+ expect(Object.keys(ISO_4217_MINOR_UNITS).filter((code) => ISO_4217_MINOR_UNITS[code] !== null)).toHaveLength(165)
249
+ expect(ISO_4217_MINOR_UNITS).toHaveProperty('XCG', 2)
250
+ expect(ISO_4217_MINOR_UNITS).toHaveProperty('ANG', null)
251
+ })
252
+
253
+ it('resolves Intl display digits for display only', () => {
254
+ expect(resolveCurrencyDisplayDecimalPlaces('USD')).toBe(2)
255
+ expect(resolveCurrencyDisplayDecimalPlaces('jpy')).toBe(0)
256
+ expect(resolveCurrencyDisplayDecimalPlaces('KWD')).toBe(3)
257
+ expect(resolveCurrencyDisplayDecimalPlaces('ETH')).toBeNull()
258
+ expect(resolveCurrencyDisplayDecimalPlaces(null)).toBeNull()
259
+ })
260
+
261
+ it('returns null for codes Intl formats but does not know', () => {
262
+ expect(resolveIsoCurrencyDecimalPlaces('ETH')).toBeNull()
263
+ expect(resolveIsoCurrencyDecimalPlaces('BTC')).toBeNull()
264
+ expect(resolveIsoCurrencyDecimalPlaces('XYZ')).toBeNull()
265
+ expect(resolveIsoCurrencyDecimalPlaces('XYZW')).toBeNull()
266
+ })
267
+
268
+ it('never widens the amount tolerance past the default precision', () => {
269
+ expect(decimalToString(amountComparisonTolerance())).toBe('0.005')
270
+ expect(decimalToString(amountComparisonTolerance(8))).toBe('0.0000005')
271
+ expect(decimalToString(amountComparisonTolerance(2))).toBe('0.005')
272
+ expect(decimalToString(amountComparisonTolerance(1))).toBe('0.005')
273
+ expect(decimalToString(amountComparisonTolerance(0))).toBe('0.005')
274
+ })
275
+
276
+ it('validates decimal strings with zod', () => {
277
+ expect(decimalStringSchema.parse(12.5)).toBe('12.5')
278
+ expect(decimalStringSchema.parse('0.000000000000000000000001')).toBe('0.000000000000000000000001')
279
+ expect(decimalStringSchema.safeParse('abc').success).toBe(false)
280
+ expect(decimalStringSchema.safeParse(Number.NaN).success).toBe(false)
281
+ expect(nonNegativeDecimalStringSchema.safeParse('-1').success).toBe(false)
282
+ expect(nonNegativeDecimalStringSchema.parse('0')).toBe('0')
283
+ expect(positiveDecimalStringSchema.safeParse('0').success).toBe(false)
284
+ expect(positiveDecimalStringSchema.parse('0.1')).toBe('0.1')
285
+ })
286
+ })
287
+
288
+ describe('resolveExactDecimal', () => {
289
+ it('prefers the exact string while the legacy number still matches it', () => {
290
+ expect(resolveExactDecimal('0.000000000000000000123', 1.23e-19)).toBe('0.000000000000000000123')
291
+ expect(resolveExactDecimal('12345678901234567890.1', Number('12345678901234567890.1'))).toBe('12345678901234567890.1')
292
+ })
293
+
294
+ it('falls back to the legacy number once it was changed on its own', () => {
295
+ expect(resolveExactDecimal('10.123456789', 12)).toBe('12')
296
+ })
297
+
298
+ it('rejects exact values that underflow to zero', () => {
299
+ expect(resolveExactDecimal('-1e-400', -0)).toBe('0')
300
+ expect(resolveExactDecimal('1e-400', 0)).toBe('0')
301
+ expect(resolveExactDecimal('0.000', 0)).toBe('0')
302
+ })
303
+
304
+ it('handles missing values', () => {
305
+ expect(resolveExactDecimal(null, 5)).toBe('5')
306
+ expect(resolveExactDecimal('7.5', undefined)).toBe('7.5')
307
+ expect(resolveExactDecimal(undefined, null)).toBeNull()
308
+ expect(resolveExactDecimal('abc', 'def')).toBeNull()
309
+ })
310
+ })
311
+
312
+ describe('withExactAmounts', () => {
313
+ it('keeps raw string digits next to the coerced numbers', () => {
314
+ const raw = { amount: '0.123456789012345678901', other: 'x', fee: 5 }
315
+ const parsed = { amount: Number(raw.amount), other: 'x', fee: 5, missing: undefined as number | undefined }
316
+ const result = withExactAmounts(parsed, raw, ['amount', 'fee', 'missing'] as const)
317
+ expect(result.amountExact).toBe('0.123456789012345678901')
318
+ expect(result.feeExact).toBe('5')
319
+ expect('missingExact' in result).toBe(false)
320
+ expect(result.amount).toBe(parsed.amount)
321
+ })
322
+
323
+ it('reads the exact string a route attached once the raw field is a number', () => {
324
+ const exactValue = '0.123456789012345678901'
325
+ const routeOutput = { amount: Number(exactValue), amountExact: exactValue }
326
+ const result = withExactAmounts({ amount: Number(exactValue) }, routeOutput, ['amount'] as const)
327
+ expect(result.amountExact).toBe(exactValue)
328
+ })
329
+
330
+ it('ignores an attached exact string that does not match the number', () => {
331
+ const result = withExactAmounts({ amount: 12 }, { amount: 12, amountExact: '99.5' }, ['amount'] as const)
332
+ expect(result.amountExact).toBe('12')
333
+ })
334
+
335
+ it('never pairs a parsed null with a raw exact string', () => {
336
+ const raw = { defaultCreditLimit: null, defaultCreditLimitExact: '-1000' }
337
+ const result = withExactAmounts({ defaultCreditLimit: null }, raw, ['defaultCreditLimit'] as const)
338
+ expect(result.defaultCreditLimitExact).toBeNull()
339
+ const coerced = withExactAmounts({ amount: null }, { amount: '', amountExact: '-1000' }, ['amount'] as const)
340
+ expect(coerced.amountExact).toBeNull()
341
+ })
342
+
343
+ it('reads a raw exact string only when the raw field is a number', () => {
344
+ const missingRaw = withExactAmounts({ amount: 0 }, { amountExact: '-1000' }, ['amount'] as const)
345
+ expect(missingRaw.amountExact).toBe('0')
346
+ const parsedString = withExactAmounts({ amount: '5' }, { amount: 5, amountExact: '-1000' }, ['amount'] as const)
347
+ expect(parsedString.amountExact).toBe('5')
348
+ })
349
+ })
350
+
351
+ describe('withExactListAmounts', () => {
352
+ it('pairs parsed and raw list items by index', () => {
353
+ const raw = { lines: [{ price: '1.000000000000000001' }, { price: 2 }] }
354
+ const parsed = [{ price: Number('1.000000000000000001') }, { price: 2 }]
355
+ const result = withExactListAmounts(parsed, raw, 'lines', ['price'] as const)
356
+ expect(result?.map((line) => line.priceExact)).toEqual(['1.000000000000000001', '2'])
357
+ expect(withExactListAmounts(undefined, raw, 'lines', ['price'] as const)).toBeUndefined()
358
+ })
359
+
360
+ it('never pairs a parsed null item with a raw exact string', () => {
361
+ const raw = { lines: [{ price: null, priceExact: '-1000' }] }
362
+ const result = withExactListAmounts([{ price: null }], raw, 'lines', ['price'] as const)
363
+ expect(result?.[0].priceExact).toBeNull()
364
+ })
365
+ })
366
+
367
+ describe('withDecimalCaps', () => {
368
+ const schema = withDecimalCaps(z.coerce.number().min(0), 'amount_invalid')
369
+
370
+ it('rejects oversized decimals before coercion', () => {
371
+ expect(schema.safeParse(1e305).success).toBe(false)
372
+ expect(schema.safeParse('1e305').success).toBe(false)
373
+ expect(schema.safeParse(`0.${'1'.repeat(1001)}`).success).toBe(false)
374
+ })
375
+
376
+ it('leaves valid, blank and non-numeric input to the wrapped schema', () => {
377
+ expect(schema.parse('12.5')).toBe(12.5)
378
+ expect(schema.parse('')).toBe(0)
379
+ expect(schema.safeParse(-1).success).toBe(false)
380
+ })
381
+ })
@@ -1,4 +1,11 @@
1
- import { formatLocaleNumberInput, parseLocaleNumber, parseNumberWithDefault, resolveLocaleNumberSeparators } from '../number'
1
+ import {
2
+ formatLocaleDecimalInput,
3
+ formatLocaleNumberInput,
4
+ parseLocaleDecimal,
5
+ parseLocaleNumber,
6
+ parseNumberWithDefault,
7
+ resolveLocaleNumberSeparators,
8
+ } from '../number'
2
9
 
3
10
  describe('parseNumberWithDefault', () => {
4
11
  it('returns the fallback when raw is missing or blank', () => {
@@ -122,6 +129,21 @@ describe('parseLocaleNumber', () => {
122
129
  })
123
130
  })
124
131
 
132
+ describe('parseLocaleDecimal', () => {
133
+ it('keeps every digit a user typed', () => {
134
+ expect(parseLocaleDecimal('0,000000000000000000000001', 'pl-PL')).toBe('0.000000000000000000000001')
135
+ expect(parseLocaleDecimal('1 234,567891234567891234', 'pl-PL')).toBe('1234.567891234567891234')
136
+ expect(parseLocaleDecimal('12345678901234567890.5', 'en-US')).toBe('12345678901234567890.5')
137
+ })
138
+
139
+ it('normalizes padding and rejects garbage', () => {
140
+ expect(parseLocaleDecimal('40.0000', 'en-US')).toBe('40')
141
+ expect(parseLocaleDecimal('', 'en-US')).toBeNull()
142
+ expect(parseLocaleDecimal('abc', 'en-US')).toBeNull()
143
+ expect(parseLocaleDecimal('1 2', 'en-US')).toBeNull()
144
+ })
145
+ })
146
+
125
147
  describe('formatLocaleNumberInput (issue #6309)', () => {
126
148
  it('uses the locale decimal separator instead of the dot String() always emits', () => {
127
149
  expect(formatLocaleNumberInput(2.5, 'pl-PL')).toBe('2,5')
@@ -144,3 +166,20 @@ describe('formatLocaleNumberInput (issue #6309)', () => {
144
166
  }
145
167
  })
146
168
  })
169
+
170
+ describe('formatLocaleDecimalInput', () => {
171
+ it('redisplays an exact decimal with the locale separator and every digit', () => {
172
+ expect(formatLocaleDecimalInput('1234.567891234567891234', 'pl-PL')).toBe('1234,567891234567891234')
173
+ expect(formatLocaleDecimalInput('-0.000000000000000000000001', 'de-DE')).toBe('-0,000000000000000000000001')
174
+ expect(formatLocaleDecimalInput('40.0000', 'pl-PL')).toBe('40')
175
+ expect(formatLocaleDecimalInput(2.5, 'en-US')).toBe('2.5')
176
+ })
177
+
178
+ it('round-trips through parseLocaleDecimal', () => {
179
+ for (const value of ['1234.567891234567891234', '-0.125', '7', '0.000000000000000000000001']) {
180
+ for (const locale of ['pl-PL', 'de-DE', 'en-US', 'fr-FR']) {
181
+ expect(parseLocaleDecimal(formatLocaleDecimalInput(value, locale), locale)).toBe(value)
182
+ }
183
+ }
184
+ })
185
+ })
@@ -0,0 +1,82 @@
1
+ import {
2
+ countDecimalPlaces,
3
+ decimalToString,
4
+ parseDecimal,
5
+ resolveAmountDecimalPlaces,
6
+ resolveIsoCurrencyDecimalPlaces,
7
+ } from './decimal'
8
+ import { getTelemetryRuntime } from './telemetry/runtime'
9
+
10
+ export function findCurrencyAmountPrecisionError(input: {
11
+ amount: number | string | null | undefined
12
+ currencyCode: string | null | undefined
13
+ decimalPlaces: number | null
14
+ }): { amount: string; currencyCode: string; decimalPlaces: number } | null {
15
+ const amount = parseDecimal(input.amount)
16
+ const currencyCode = input.currencyCode?.trim().toUpperCase()
17
+ if (amount === null || !currencyCode) return null
18
+ const isoDecimalPlaces = resolveIsoCurrencyDecimalPlaces(currencyCode)
19
+ const decimalPlaces = input.decimalPlaces !== null && isoDecimalPlaces !== null
20
+ ? Math.min(input.decimalPlaces, isoDecimalPlaces)
21
+ : input.decimalPlaces
22
+ if (decimalPlaces === null || countDecimalPlaces(amount) <= decimalPlaces) return null
23
+ return { amount: decimalToString(amount), currencyCode, decimalPlaces }
24
+ }
25
+
26
+ export type CurrencyPrecisionLookup = {
27
+ code: string
28
+ tenantId: string
29
+ organizationId?: string | null
30
+ }
31
+
32
+ export type CurrencyPrecisionResolver = {
33
+ getDecimalPlaces(lookup: CurrencyPrecisionLookup): Promise<number | null>
34
+ }
35
+
36
+ type ServiceContainer = {
37
+ resolve<T = unknown>(name: string): T
38
+ }
39
+
40
+ /**
41
+ * The currency's own decimal places: the tenant's currency precision (via the
42
+ * optional `currencyPrecisionService`), else the ISO 4217 digits, else `null`.
43
+ */
44
+ export async function resolveCurrencyDecimalPlaces(
45
+ container: ServiceContainer,
46
+ lookup: CurrencyPrecisionLookup,
47
+ ): Promise<number | null> {
48
+ if (!lookup.code) return null
49
+ let resolver: CurrencyPrecisionResolver | null = null
50
+ try {
51
+ resolver = container.resolve<CurrencyPrecisionResolver>('currencyPrecisionService')
52
+ } catch {
53
+ resolver = null
54
+ }
55
+ let decimalPlaces: number | null = null
56
+ if (resolver) {
57
+ try {
58
+ decimalPlaces = await resolver.getDecimalPlaces(lookup)
59
+ } catch (error) {
60
+ try {
61
+ getTelemetryRuntime()?.reportError(error, {
62
+ module: 'currencies',
63
+ code: 'currencies.precision_lookup_failed',
64
+ })
65
+ } catch {}
66
+ decimalPlaces = null
67
+ }
68
+ }
69
+ return decimalPlaces ?? resolveIsoCurrencyDecimalPlaces(lookup.code)
70
+ }
71
+
72
+ /**
73
+ * Decimal places money amounts in `code` are rounded to after a division:
74
+ * the tenant's currency precision (via the optional `currencyPrecisionService`),
75
+ * else the ISO 4217 digits, never fewer than DEFAULT_AMOUNT_DECIMAL_PLACES.
76
+ */
77
+ export async function resolveCurrencyAmountDecimalPlaces(
78
+ container: ServiceContainer,
79
+ lookup: CurrencyPrecisionLookup,
80
+ ): Promise<number> {
81
+ return resolveAmountDecimalPlaces(await resolveCurrencyDecimalPlaces(container, lookup))
82
+ }