/** Money amount rules aligned with DECIMAL(18,2) and normal reimbursement UX. */ export const MONEY_MAX = 99_999_999.99 export const MONEY_MIN = 0.01 const MONEY_PATTERN = /^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/ export type MoneyAmountIssue = | 'empty' | 'invalid' | 'non_positive' | 'too_many_decimals' | 'too_large' const MESSAGES: Record = { empty: '请填写金额', invalid: '金额须为有效数字,例如 128.50', non_positive: '金额须大于 0', too_many_decimals: '金额最多保留两位小数', too_large: `单笔金额不能超过 ${MONEY_MAX.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} 元`, } export const moneyAmountMessage = (issue: MoneyAmountIssue, label = '金额') => { if (issue === 'empty') return `请填写${label}` if (issue === 'invalid') return `${label}须为有效数字,例如 128.50` if (issue === 'non_positive') return `${label}须大于 0` if (issue === 'too_many_decimals') return `${label}最多保留两位小数` if (issue === 'too_large') { return `${label}不能超过 ${MONEY_MAX.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} 元` } return MESSAGES[issue] } /** Inspect a typed amount (input string or numeric model). */ export const inspectMoneyAmount = (value: unknown): MoneyAmountIssue | null => { if (value == null || value === '') return 'empty' if (typeof value === 'number') { if (!Number.isFinite(value)) return 'invalid' if (value <= 0) return 'non_positive' if (Math.round(value * 100) / 100 !== value) return 'too_many_decimals' if (value > MONEY_MAX) return 'too_large' return null } const text = String(value).trim() if (!text) return 'empty' if (/[eE]/.test(text) || !/^-?\d/.test(text)) return 'invalid' if (text.startsWith('-')) return 'non_positive' if (!/^\d+(\.\d+)?$/.test(text)) return 'invalid' if (text.includes('.') && text.split('.')[1].length > 2) return 'too_many_decimals' if (!MONEY_PATTERN.test(text)) return 'invalid' const amount = Number(text) if (!Number.isFinite(amount)) return 'invalid' if (amount <= 0) return 'non_positive' if (amount > MONEY_MAX) return 'too_large' return null } export const normalizeMoneyAmount = (value: unknown): number => { const issue = inspectMoneyAmount(value) if (issue) return 0 const amount = typeof value === 'number' ? value : Number(String(value).trim()) return Math.round(amount * 100) / 100 }