@open-mercato/shared 0.10.1-develop.8287.1.7313a0fe67 → 0.10.1-develop.8291.1.6ec3aee41c
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/.turbo/turbo-build.log +1 -1
- package/AGENTS.md +2 -1
- package/dist/lib/currencyPrecision.js +51 -0
- package/dist/lib/currencyPrecision.js.map +7 -0
- package/dist/lib/db/exactDecimalType.js +20 -0
- package/dist/lib/db/exactDecimalType.js.map +7 -0
- package/dist/lib/decimal.js +289 -0
- package/dist/lib/decimal.js.map +7 -0
- package/dist/lib/isoCurrencyMinorUnits.js +313 -0
- package/dist/lib/isoCurrencyMinorUnits.js.map +7 -0
- package/dist/lib/number.js +20 -2
- package/dist/lib/number.js.map +2 -2
- package/dist/lib/version.js +1 -1
- package/dist/lib/version.js.map +1 -1
- package/dist/modules/payment_gateways/types.js.map +2 -2
- package/package.json +4 -2
- package/src/lib/__tests__/currencyPrecision.test.ts +114 -0
- package/src/lib/__tests__/decimal.test.ts +381 -0
- package/src/lib/__tests__/number.test.ts +40 -1
- package/src/lib/currencyPrecision.ts +82 -0
- package/src/lib/db/__tests__/exactDecimalType.test.ts +86 -0
- package/src/lib/db/exactDecimalType.ts +25 -0
- package/src/lib/decimal.ts +427 -0
- package/src/lib/isoCurrencyMinorUnits.ts +315 -0
- package/src/lib/number.ts +32 -2
- package/src/modules/payment_gateways/types.ts +18 -0
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { EntitySchema } from '@mikro-orm/core'
|
|
2
|
+
import { MikroORM } from '@mikro-orm/postgresql'
|
|
3
|
+
import { ExactDecimalType } from '../exactDecimalType'
|
|
4
|
+
|
|
5
|
+
describe('ExactDecimalType', () => {
|
|
6
|
+
const type = new ExactDecimalType()
|
|
7
|
+
|
|
8
|
+
it('detects changes beyond float precision', () => {
|
|
9
|
+
expect(Number('1.123456789012345678')).toBe(Number('1.123456789012345679'))
|
|
10
|
+
expect(type.compareValues('1.123456789012345678', '1.123456789012345679')).toBe(false)
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
it('treats the same value with different scale as unchanged', () => {
|
|
14
|
+
expect(type.compareValues('40.0000', '40')).toBe(true)
|
|
15
|
+
expect(type.compareValues('0.000000000000000001', '1e-18')).toBe(true)
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
it('compares missing values strictly', () => {
|
|
19
|
+
expect(type.compareValues(null, null)).toBe(true)
|
|
20
|
+
expect(type.compareValues(null, '0')).toBe(false)
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
it('maps to a string runtime type', () => {
|
|
24
|
+
expect(type.compareAsType()).toBe('string')
|
|
25
|
+
})
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
describe('ExactDecimalType schema generation', () => {
|
|
29
|
+
let orm: MikroORM
|
|
30
|
+
|
|
31
|
+
beforeAll(async () => {
|
|
32
|
+
orm = await MikroORM.init({
|
|
33
|
+
entities: [new EntitySchema({
|
|
34
|
+
name: 'ExactDecimalSchemaProbe',
|
|
35
|
+
tableName: 'exact_decimal_schema_probes',
|
|
36
|
+
properties: {
|
|
37
|
+
id: { type: 'uuid', primary: true },
|
|
38
|
+
amount: { type: ExactDecimalType, columnType: 'numeric' },
|
|
39
|
+
rate: { type: ExactDecimalType },
|
|
40
|
+
percentage: { type: 'decimal', precision: 7, scale: 4 },
|
|
41
|
+
},
|
|
42
|
+
})],
|
|
43
|
+
dbName: 'exact_decimal_schema_probe',
|
|
44
|
+
connect: false,
|
|
45
|
+
})
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
afterAll(async () => {
|
|
49
|
+
await orm?.close(true)
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('discovers unconstrained numeric with and without an explicit column type', () => {
|
|
53
|
+
const metadata = orm.getMetadata().get('ExactDecimalSchemaProbe')
|
|
54
|
+
|
|
55
|
+
expect(metadata.properties.amount.columnTypes).toEqual(['numeric'])
|
|
56
|
+
expect(metadata.properties.rate.columnTypes).toEqual(['numeric'])
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
it('keeps snapshot column types consistent with unconstrained numeric SQL', async () => {
|
|
60
|
+
const table = orm.schema.getTargetSchema().getTable('exact_decimal_schema_probes')!
|
|
61
|
+
|
|
62
|
+
for (const name of ['amount', 'rate']) {
|
|
63
|
+
expect(table.getColumn(name)).toMatchObject({
|
|
64
|
+
type: 'numeric',
|
|
65
|
+
precision: undefined,
|
|
66
|
+
scale: undefined,
|
|
67
|
+
})
|
|
68
|
+
}
|
|
69
|
+
expect(table.getColumn('percentage').type).toBe('numeric(7,4)')
|
|
70
|
+
expect(await orm.schema.getCreateSchemaSQL({ wrap: false })).toContain('"amount" numeric not null')
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('produces no migration when compared repeatedly with unconstrained numeric columns', async () => {
|
|
74
|
+
const existingSchema = orm.schema.getTargetSchema()
|
|
75
|
+
const table = existingSchema.getTable('exact_decimal_schema_probes')!
|
|
76
|
+
|
|
77
|
+
for (const name of ['amount', 'rate']) {
|
|
78
|
+
table.addColumn({ ...table.getColumn(name), type: 'numeric', precision: undefined, scale: undefined })
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
expect(await orm.schema.getUpdateSchemaMigrationSQL({ fromSchema: existingSchema, wrap: false }))
|
|
82
|
+
.toEqual({ up: '', down: '' })
|
|
83
|
+
expect(await orm.schema.getUpdateSchemaMigrationSQL({ fromSchema: existingSchema, wrap: false }))
|
|
84
|
+
.toEqual({ up: '', down: '' })
|
|
85
|
+
})
|
|
86
|
+
})
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { DecimalType, type EntityProperty, type Platform } from '@mikro-orm/core'
|
|
2
|
+
import { parseDecimal } from '../decimal'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Unconstrained `numeric` mapped to a decimal string. MikroORM's `DecimalType`
|
|
6
|
+
* detects changes by comparing `+value`, so an edit beyond float precision
|
|
7
|
+
* (`1.123456789012345678` -> `...679`) is never flushed. This type compares the
|
|
8
|
+
* exact decimal values instead.
|
|
9
|
+
*/
|
|
10
|
+
export class ExactDecimalType extends DecimalType {
|
|
11
|
+
constructor() {
|
|
12
|
+
super('string')
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
getColumnType(_property: EntityProperty, _platform: Platform): string {
|
|
16
|
+
return 'numeric'
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
compareValues(left: unknown, right: unknown): boolean {
|
|
20
|
+
const leftDecimal = parseDecimal(left)
|
|
21
|
+
const rightDecimal = parseDecimal(right)
|
|
22
|
+
if (!leftDecimal || !rightDecimal) return left === right
|
|
23
|
+
return leftDecimal.eq(rightDecimal)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
import BigConstructor from 'big.js'
|
|
2
|
+
import type { Big, BigSource } from 'big.js'
|
|
3
|
+
import { z } from 'zod'
|
|
4
|
+
import { ISO_4217_MINOR_UNITS } from './isoCurrencyMinorUnits'
|
|
5
|
+
|
|
6
|
+
export type DecimalValue = Big
|
|
7
|
+
export type DecimalInput = string | number | Big
|
|
8
|
+
|
|
9
|
+
export const FX_DECIMAL_PLACES = 50
|
|
10
|
+
export const MIN_SIGNIFICANT_DIGITS = 17
|
|
11
|
+
export const DEFAULT_AMOUNT_DECIMAL_PLACES = 4
|
|
12
|
+
|
|
13
|
+
const ROUND_HALF_UP = 1
|
|
14
|
+
|
|
15
|
+
const Decimal = BigConstructor()
|
|
16
|
+
Decimal.DP = FX_DECIMAL_PLACES
|
|
17
|
+
Decimal.RM = ROUND_HALF_UP
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Largest exponent accepted in a decimal string, and the lowest decimal position
|
|
21
|
+
* a digit may sit at (`1e-1000`). Expanding `1e-100000000` to plain notation
|
|
22
|
+
* would allocate a 100M-character string, so anything beyond this bound (far
|
|
23
|
+
* past any real money or FX value) is rejected as invalid input.
|
|
24
|
+
*/
|
|
25
|
+
export const MAX_DECIMAL_EXPONENT = 1000
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Most significant digits a decimal input may carry. Arithmetic cost grows with
|
|
29
|
+
* the digit count, so longer inputs are rejected as invalid.
|
|
30
|
+
*/
|
|
31
|
+
export const MAX_DECIMAL_SIGNIFICANT_DIGITS = 1000
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Most integer digits a decimal input may carry (`|value| < 1e300`), so the
|
|
35
|
+
* legacy float copy of an accepted value is always finite.
|
|
36
|
+
*/
|
|
37
|
+
export const MAX_DECIMAL_INTEGER_DIGITS = 300
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Longest decimal string accepted, so a value padded with millions of zeros is
|
|
41
|
+
* rejected before it is scanned. The longest plain value within the other caps
|
|
42
|
+
* (300 integer and 1000 fractional digits) is about 1300 characters.
|
|
43
|
+
*/
|
|
44
|
+
export const MAX_DECIMAL_INPUT_LENGTH = 2048
|
|
45
|
+
|
|
46
|
+
const DECIMAL_STRING_PATTERN = /^[+-]?(\d+(\.\d*)?|\.\d+)(?:e([+-]?\d+))?$/i
|
|
47
|
+
const NON_ZERO_DIGIT_PATTERN = /[1-9]/
|
|
48
|
+
|
|
49
|
+
function isDecimalString(value: string): boolean {
|
|
50
|
+
if (value.length > MAX_DECIMAL_INPUT_LENGTH) return false
|
|
51
|
+
const match = DECIMAL_STRING_PATTERN.exec(value)
|
|
52
|
+
if (!match) return false
|
|
53
|
+
const exponent = match[3] === undefined ? 0 : Number(match[3])
|
|
54
|
+
if (Math.abs(exponent) > MAX_DECIMAL_EXPONENT) return false
|
|
55
|
+
const [integerPart, fractionPart = ''] = match[1].split('.')
|
|
56
|
+
const digits = `${integerPart}${fractionPart}`
|
|
57
|
+
const firstSignificant = digits.search(NON_ZERO_DIGIT_PATTERN)
|
|
58
|
+
if (firstSignificant === -1) return true
|
|
59
|
+
let lastSignificant = digits.length - 1
|
|
60
|
+
while (digits[lastSignificant] === '0') lastSignificant -= 1
|
|
61
|
+
const unitsIndex = integerPart.length - 1 + exponent
|
|
62
|
+
return (
|
|
63
|
+
lastSignificant - firstSignificant < MAX_DECIMAL_SIGNIFICANT_DIGITS &&
|
|
64
|
+
unitsIndex - firstSignificant < MAX_DECIMAL_INTEGER_DIGITS &&
|
|
65
|
+
unitsIndex - lastSignificant >= -MAX_DECIMAL_EXPONENT
|
|
66
|
+
)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function isDecimalNumber(value: number): boolean {
|
|
70
|
+
return Number.isFinite(value) && isDecimalString(String(value))
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Duck-typed so a `Big` from another copy of big.js (CommonJS and ES module
|
|
75
|
+
* builds, or two installed versions) is still recognised.
|
|
76
|
+
*/
|
|
77
|
+
function isBigLike(value: unknown): value is Big {
|
|
78
|
+
if (typeof value !== 'object' || value === null) return false
|
|
79
|
+
const candidate = value as { c?: unknown; e?: unknown; s?: unknown }
|
|
80
|
+
return Array.isArray(candidate.c) && typeof candidate.e === 'number' && typeof candidate.s === 'number'
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function isZeroBig(value: Big): boolean {
|
|
84
|
+
return value.c.length === 1 && value.c[0] === 0
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function invalidDecimalPlaces(decimalPlaces: number): Error {
|
|
88
|
+
return new Error(`[internal] Invalid decimal places: ${decimalPlaces}`)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function assertDecimalPlaces(decimalPlaces: number): void {
|
|
92
|
+
if (!Number.isInteger(decimalPlaces) || decimalPlaces < 0 || decimalPlaces > MAX_DECIMAL_EXPONENT) {
|
|
93
|
+
throw invalidDecimalPlaces(decimalPlaces)
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Keeps a computed value within the input caps, so every result can be stored
|
|
99
|
+
* and parsed back. Digits beyond 1000 significant digits or below `1e-1000`
|
|
100
|
+
* (chained FX products grow their decimals with every multiplication) are
|
|
101
|
+
* rounded half-up; a value with more than 300 integer digits throws instead of
|
|
102
|
+
* turning into an unparseable string or an infinite float copy.
|
|
103
|
+
*/
|
|
104
|
+
function withinCaps(value: Big): Big {
|
|
105
|
+
if (isZeroBig(value)) return value
|
|
106
|
+
const decimalPlaces = value.c.length - 1 - value.e
|
|
107
|
+
const allowedDecimalPlaces = Math.min(MAX_DECIMAL_EXPONENT, MAX_DECIMAL_SIGNIFICANT_DIGITS - 1 - value.e)
|
|
108
|
+
const capped = decimalPlaces > allowedDecimalPlaces ? value.round(allowedDecimalPlaces, ROUND_HALF_UP) : value
|
|
109
|
+
if (!isZeroBig(capped) && capped.e >= MAX_DECIMAL_INTEGER_DIGITS) {
|
|
110
|
+
throw new Error('[internal] Decimal result out of range')
|
|
111
|
+
}
|
|
112
|
+
return capped
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function isDecimalInput(value: unknown): value is DecimalInput {
|
|
116
|
+
if (typeof value === 'number') return isDecimalNumber(value)
|
|
117
|
+
if (typeof value === 'string') return isDecimalString(value.trim())
|
|
118
|
+
return isBigLike(value) && (isZeroBig(value) || value.e < MAX_DECIMAL_INTEGER_DIGITS)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* A JS number is read as its shortest round-trip decimal form, so `0.1 + 0.2`
|
|
123
|
+
* becomes `0.30000000000000004`; pass the raw string to keep the entered digits.
|
|
124
|
+
* A `Big` is copied and brought within the caps (see `withinCaps`).
|
|
125
|
+
*/
|
|
126
|
+
export function toDecimal(value: DecimalInput): DecimalValue {
|
|
127
|
+
if (typeof value === 'number') {
|
|
128
|
+
if (!isDecimalNumber(value)) throw new Error(`[internal] Invalid decimal value: ${value}`)
|
|
129
|
+
return new Decimal(value)
|
|
130
|
+
}
|
|
131
|
+
if (typeof value === 'string') {
|
|
132
|
+
const trimmed = value.trim()
|
|
133
|
+
if (!isDecimalString(trimmed)) throw new Error(`[internal] Invalid decimal value: ${value.slice(0, 50)}`)
|
|
134
|
+
return new Decimal(trimmed.startsWith('+') ? trimmed.slice(1) : trimmed)
|
|
135
|
+
}
|
|
136
|
+
if (!isBigLike(value)) throw new Error('[internal] Invalid decimal value')
|
|
137
|
+
return withinCaps(new Decimal(value as BigSource))
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function parseDecimal(value: unknown): DecimalValue | null {
|
|
141
|
+
if (value === null || value === undefined || value === '') return null
|
|
142
|
+
if (!isDecimalInput(value)) return null
|
|
143
|
+
return toDecimal(value)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function decimalToString(value: DecimalInput): string {
|
|
147
|
+
return toDecimal(value).toFixed()
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function addDecimals(left: DecimalInput, right: DecimalInput): DecimalValue {
|
|
151
|
+
return withinCaps(toDecimal(left).plus(toDecimal(right)))
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function subtractDecimals(left: DecimalInput, right: DecimalInput): DecimalValue {
|
|
155
|
+
return withinCaps(toDecimal(left).minus(toDecimal(right)))
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function multiplyDecimals(left: DecimalInput, right: DecimalInput): DecimalValue {
|
|
159
|
+
return withinCaps(toDecimal(left).times(toDecimal(right)))
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function sumDecimals(values: DecimalInput[]): DecimalValue {
|
|
163
|
+
return withinCaps(values.reduce<DecimalValue>((total, value) => total.plus(toDecimal(value)), new Decimal(0)))
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Divides with at least `decimalPlaces` decimals and never fewer than
|
|
168
|
+
* MIN_SIGNIFICANT_DIGITS significant digits, so a quotient is never less
|
|
169
|
+
* precise than the same division done on a JS `number`. The quotient is cut,
|
|
170
|
+
* not exact: `1 / 3 * 3` is `0.999...9`, so round before comparing or storing.
|
|
171
|
+
*/
|
|
172
|
+
export function divideDecimals(
|
|
173
|
+
dividend: DecimalInput,
|
|
174
|
+
divisor: DecimalInput,
|
|
175
|
+
decimalPlaces: number = FX_DECIMAL_PLACES,
|
|
176
|
+
): DecimalValue {
|
|
177
|
+
assertDecimalPlaces(decimalPlaces)
|
|
178
|
+
const left = toDecimal(dividend)
|
|
179
|
+
const right = toDecimal(divisor)
|
|
180
|
+
if (right.eq(0)) throw new Error('[internal] Division by zero')
|
|
181
|
+
if (left.eq(0)) return new Decimal(0)
|
|
182
|
+
const significantDecimalPlaces = MIN_SIGNIFICANT_DIGITS - (left.e - right.e)
|
|
183
|
+
const previousDecimalPlaces = Decimal.DP
|
|
184
|
+
Decimal.DP = Math.max(decimalPlaces, significantDecimalPlaces, 0)
|
|
185
|
+
try {
|
|
186
|
+
return withinCaps(left.div(right))
|
|
187
|
+
} finally {
|
|
188
|
+
Decimal.DP = previousDecimalPlaces
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Rounds half away from zero (commercial rounding): `2.5` -> `3`, `-2.5` -> `-3`.
|
|
194
|
+
* There is no banker's rounding mode.
|
|
195
|
+
*/
|
|
196
|
+
export function roundDecimal(value: DecimalInput, decimalPlaces: number): DecimalValue {
|
|
197
|
+
assertDecimalPlaces(decimalPlaces)
|
|
198
|
+
return toDecimal(value).round(decimalPlaces, ROUND_HALF_UP)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function compareDecimals(left: DecimalInput, right: DecimalInput): -1 | 0 | 1 {
|
|
202
|
+
return toDecimal(left).cmp(toDecimal(right)) as -1 | 0 | 1
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export function decimalsEqual(left: DecimalInput, right: DecimalInput): boolean {
|
|
206
|
+
return compareDecimals(left, right) === 0
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function isZeroDecimal(value: DecimalInput): boolean {
|
|
210
|
+
return toDecimal(value).eq(0)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export function isNegativeDecimal(value: DecimalInput): boolean {
|
|
214
|
+
return toDecimal(value).lt(0)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export function absDecimal(value: DecimalInput): DecimalValue {
|
|
218
|
+
return toDecimal(value).abs()
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function negateDecimal(value: DecimalInput): DecimalValue {
|
|
222
|
+
return toDecimal(value).neg()
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function minDecimal(...values: DecimalInput[]): DecimalValue {
|
|
226
|
+
if (values.length === 0) throw new Error('[internal] minDecimal requires at least one value')
|
|
227
|
+
return values.map(toDecimal).reduce((lowest, value) => (value.lt(lowest) ? value : lowest))
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function maxDecimal(...values: DecimalInput[]): DecimalValue {
|
|
231
|
+
if (values.length === 0) throw new Error('[internal] maxDecimal requires at least one value')
|
|
232
|
+
return values.map(toDecimal).reduce((highest, value) => (value.gt(highest) ? value : highest))
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export function countDecimalPlaces(value: DecimalInput): number {
|
|
236
|
+
const fraction = decimalToString(value).split('.')[1]
|
|
237
|
+
return fraction ? fraction.length : 0
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Plain decimal string with at least `minDecimalPlaces` decimals (`12.5` -> `12.50`), never cut. */
|
|
241
|
+
export function padDecimalPlaces(value: DecimalInput, minDecimalPlaces: number): string {
|
|
242
|
+
assertDecimalPlaces(minDecimalPlaces)
|
|
243
|
+
const decimal = toDecimal(value)
|
|
244
|
+
return decimal.toFixed(Math.max(minDecimalPlaces, countDecimalPlaces(decimal)))
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export function decimalToNumber(value: DecimalInput): number {
|
|
248
|
+
return Number(decimalToString(value))
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Whether `exact` is the decimal the validated `legacy` number stands for. A value
|
|
253
|
+
* that underflows to zero (`-1e-400`) must itself be zero, so it cannot slip past
|
|
254
|
+
* a sign or range check made on the number.
|
|
255
|
+
*/
|
|
256
|
+
function matchesLegacyNumber(exact: DecimalValue, legacy: number): boolean {
|
|
257
|
+
if (decimalToNumber(exact) !== legacy) return false
|
|
258
|
+
return legacy !== 0 || exact.eq(0)
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Picks the exact decimal string for a dual `number` + `<field>Exact` pair.
|
|
263
|
+
* The exact value wins unless the legacy `number` was changed on its own
|
|
264
|
+
* (e.g. by a hook unaware of the exact field) - then the number is used.
|
|
265
|
+
*/
|
|
266
|
+
export function resolveExactDecimal(exact: unknown, legacy: unknown): string | null {
|
|
267
|
+
const exactDecimal = parseDecimal(exact)
|
|
268
|
+
const legacyDecimal = parseDecimal(legacy)
|
|
269
|
+
if (exactDecimal && (typeof legacy !== 'number' || matchesLegacyNumber(exactDecimal, legacy))) {
|
|
270
|
+
return decimalToString(exactDecimal)
|
|
271
|
+
}
|
|
272
|
+
return legacyDecimal ? decimalToString(legacyDecimal) : null
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export type WithExactAmounts<T, K extends string> = T & { [P in K as `${P}Exact`]?: string | null }
|
|
276
|
+
|
|
277
|
+
function exactCandidate(source: Record<string, unknown>, field: string, value: unknown): unknown {
|
|
278
|
+
if (typeof value !== 'number') return value
|
|
279
|
+
const rawValue = source[field]
|
|
280
|
+
return typeof rawValue === 'number' ? source[`${field}Exact`] ?? rawValue : rawValue
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Adds `<field>Exact` strings next to number fields a zod schema coerced, taken
|
|
285
|
+
* from the raw input so digits beyond float precision survive the parse. When the
|
|
286
|
+
* raw field is already a number (an API route parsed the body before the command),
|
|
287
|
+
* the `<field>Exact` string that route attached is used instead, and only while it
|
|
288
|
+
* matches that number. A parsed `null` (or a parsed non-number) is never paired
|
|
289
|
+
* with a raw value, so it cannot smuggle unvalidated input past the schema.
|
|
290
|
+
*
|
|
291
|
+
* Only the number was validated, so the exact string may carry digits below float
|
|
292
|
+
* precision that a `max`, `int` or `multipleOf` rule never saw (`100.00000000000000000001`
|
|
293
|
+
* passes `max(100)`); a raw `<field>Exact` sent next to a JSON number is accepted on the
|
|
294
|
+
* same terms. Sign checks hold. Use it only for fields whose rules are sign checks, or
|
|
295
|
+
* re-check the exact value with decimal-aware rules.
|
|
296
|
+
*/
|
|
297
|
+
export function withExactAmounts<T extends object, K extends string>(
|
|
298
|
+
parsed: T,
|
|
299
|
+
raw: unknown,
|
|
300
|
+
fields: readonly K[],
|
|
301
|
+
): WithExactAmounts<T, K> {
|
|
302
|
+
const source = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {}
|
|
303
|
+
const values = parsed as Record<string, unknown>
|
|
304
|
+
const exact: Record<string, string | null> = {}
|
|
305
|
+
for (const field of fields) {
|
|
306
|
+
const value = values[field]
|
|
307
|
+
if (value === undefined) continue
|
|
308
|
+
exact[`${field}Exact`] = resolveExactDecimal(exactCandidate(source, field, value), value)
|
|
309
|
+
}
|
|
310
|
+
return { ...parsed, ...exact } as WithExactAmounts<T, K>
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Applies `withExactAmounts` to each item of the `key` list, pairing parsed and raw
|
|
315
|
+
* items by index. Lets an API route keep exact digits for nested lines. The list
|
|
316
|
+
* schema must not filter or reorder items, or exact strings pair with the wrong item
|
|
317
|
+
* (the float-equality check limits this to items whose floats are equal).
|
|
318
|
+
*/
|
|
319
|
+
export function withExactListAmounts<T extends object, K extends string>(
|
|
320
|
+
parsedItems: readonly T[] | null | undefined,
|
|
321
|
+
raw: unknown,
|
|
322
|
+
key: string,
|
|
323
|
+
fields: readonly K[],
|
|
324
|
+
): WithExactAmounts<T, K>[] | undefined {
|
|
325
|
+
if (!parsedItems) return undefined
|
|
326
|
+
const source = raw && typeof raw === 'object' ? (raw as Record<string, unknown>)[key] : undefined
|
|
327
|
+
const rawItems = Array.isArray(source) ? source : []
|
|
328
|
+
return parsedItems.map((item, index) => withExactAmounts(item, rawItems[index], fields))
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Tolerance for comparing money amounts rounded to `decimalPlaces`: half a
|
|
333
|
+
* minor unit of a 2-decimal currency at the default 4 places (0.005), scaled
|
|
334
|
+
* down with higher precision and never wider than that default.
|
|
335
|
+
*/
|
|
336
|
+
export function amountComparisonTolerance(decimalPlaces: number = DEFAULT_AMOUNT_DECIMAL_PLACES): DecimalValue {
|
|
337
|
+
assertDecimalPlaces(decimalPlaces)
|
|
338
|
+
return toDecimal(`5e-${Math.max(decimalPlaces, DEFAULT_AMOUNT_DECIMAL_PLACES) - 1}`)
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export function resolveAmountDecimalPlaces(currencyDecimalPlaces?: number | null): number {
|
|
342
|
+
if (typeof currencyDecimalPlaces !== 'number' || !Number.isInteger(currencyDecimalPlaces) || currencyDecimalPlaces < 0) {
|
|
343
|
+
return DEFAULT_AMOUNT_DECIMAL_PLACES
|
|
344
|
+
}
|
|
345
|
+
return Math.max(DEFAULT_AMOUNT_DECIMAL_PLACES, currencyDecimalPlaces)
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
let isoCurrencyCodes: Set<string> | null | undefined
|
|
349
|
+
|
|
350
|
+
function resolveIsoCurrencyCodes(): Set<string> | null {
|
|
351
|
+
if (isoCurrencyCodes !== undefined) return isoCurrencyCodes
|
|
352
|
+
try {
|
|
353
|
+
isoCurrencyCodes = typeof Intl.supportedValuesOf === 'function' ? new Set(Intl.supportedValuesOf('currency')) : null
|
|
354
|
+
} catch {
|
|
355
|
+
isoCurrencyCodes = null
|
|
356
|
+
}
|
|
357
|
+
return isoCurrencyCodes
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Decimal places `Intl.NumberFormat` displays for `currencyCode`, or `null` when
|
|
362
|
+
* the runtime does not know the code. These are CLDR display digits, not ISO 4217
|
|
363
|
+
* minor units (HUF, COP and IDR display 0 digits but have 2 minor units), and may
|
|
364
|
+
* change with the ICU version, so use them to format amounts, never to validate
|
|
365
|
+
* or round stored ones. `Intl.NumberFormat` accepts any well-formed code (ETH,
|
|
366
|
+
* XYZ) and reports 2 digits for it, so only codes listed by
|
|
367
|
+
* `Intl.supportedValuesOf` count.
|
|
368
|
+
*/
|
|
369
|
+
export function resolveCurrencyDisplayDecimalPlaces(currencyCode?: string | null): number | null {
|
|
370
|
+
if (!currencyCode) return null
|
|
371
|
+
const code = currencyCode.toUpperCase()
|
|
372
|
+
const knownCodes = resolveIsoCurrencyCodes()
|
|
373
|
+
if (knownCodes && !knownCodes.has(code)) return null
|
|
374
|
+
try {
|
|
375
|
+
return new Intl.NumberFormat('en', { style: 'currency', currency: code }).resolvedOptions()
|
|
376
|
+
.maximumFractionDigits ?? null
|
|
377
|
+
} catch {
|
|
378
|
+
return null
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* ISO 4217 minor units (decimal places) of `currencyCode`, read from a static table
|
|
384
|
+
* of every ISO 4217 code so the result does not depend on the ICU version. `null`
|
|
385
|
+
* when ISO defines no minor unit (N.A. or withdrawn codes) or the code is not ISO
|
|
386
|
+
* 4217; a non-ISO code the runtime supports falls back to its `Intl` digits.
|
|
387
|
+
*/
|
|
388
|
+
export function resolveIsoCurrencyDecimalPlaces(currencyCode?: string | null): number | null {
|
|
389
|
+
if (!currencyCode) return null
|
|
390
|
+
const code = currencyCode.toUpperCase()
|
|
391
|
+
if (Object.hasOwn(ISO_4217_MINOR_UNITS, code)) return ISO_4217_MINOR_UNITS[code]
|
|
392
|
+
return resolveCurrencyDisplayDecimalPlaces(code)
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Whether a raw money input may reach a number-coercing schema: blank strings and
|
|
397
|
+
* non-numeric values are left to that schema, numbers and strings must be decimals
|
|
398
|
+
* within the size caps, so an oversized value is rejected instead of turning into 0.
|
|
399
|
+
* The wrapped schema decides what a blank string means: `z.coerce.number()` turns
|
|
400
|
+
* `''` into `0`, as it did before this wrapper; preprocess blanks to `null` or
|
|
401
|
+
* `undefined` where an empty field must not mean zero.
|
|
402
|
+
*/
|
|
403
|
+
export function isWithinDecimalCaps(value: unknown): boolean {
|
|
404
|
+
if (typeof value === 'string' && value.trim().length === 0) return true
|
|
405
|
+
if (typeof value !== 'string' && typeof value !== 'number') return true
|
|
406
|
+
return isDecimalInput(value)
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
export function withDecimalCaps<T extends z.ZodType>(schema: T, message?: string) {
|
|
410
|
+
return z.unknown().refine(isWithinDecimalCaps, message === undefined ? undefined : { message }).pipe(schema)
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const decimalInputSchema = z.union([z.string(), z.number()]).refine(isDecimalInput, {
|
|
414
|
+
message: 'invalidDecimal',
|
|
415
|
+
})
|
|
416
|
+
|
|
417
|
+
export const decimalStringSchema = decimalInputSchema.transform((value) => decimalToString(value))
|
|
418
|
+
|
|
419
|
+
export const nonNegativeDecimalStringSchema = decimalStringSchema.refine(
|
|
420
|
+
(value) => !isNegativeDecimal(value),
|
|
421
|
+
{ message: 'decimalMustBeNonNegative' },
|
|
422
|
+
)
|
|
423
|
+
|
|
424
|
+
export const positiveDecimalStringSchema = decimalStringSchema.refine(
|
|
425
|
+
(value) => toDecimal(value).gt(0),
|
|
426
|
+
{ message: 'decimalMustBePositive' },
|
|
427
|
+
)
|