A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(number-utils): add a shared price formatting package
Hampus2550c9ded32a
diff --git a/fluxer_app_proxy/Dockerfile b/fluxer_app_proxy/Dockerfileindex 98fff76af..ca0fd35dc 100644--- a/fluxer_app_proxy/Dockerfile+++ b/fluxer_app_proxy/Dockerfile@@ -40,6 +40,7 @@ COPY packages/desktop_ipc/package.json ./packages/desktop_ipc/COPY packages/geo_utils/package.json ./packages/geo_utils/COPY packages/instance_bootstrap/package.json ./packages/instance_bootstrap/COPY packages/limits/package.json ./packages/limits/+COPY packages/number_utils/package.json ./packages/number_utils/COPY packages/record_utils/package.json ./packages/record_utils/COPY packages/schema/package.json ./packages/schema/COPY packages/snowflake/package.json ./packages/snowflake/@@ -55,6 +56,7 @@ COPY packages/desktop_ipc/ ./packages/desktop_ipc/COPY packages/geo_utils/ ./packages/geo_utils/COPY packages/instance_bootstrap/ ./packages/instance_bootstrap/COPY packages/limits/ ./packages/limits/+COPY packages/number_utils/ ./packages/number_utils/COPY packages/record_utils/ ./packages/record_utils/COPY packages/schema/ ./packages/schema/COPY packages/snowflake/ ./packages/snowflake/diff --git a/packages/number_utils/package.json b/packages/number_utils/package.jsonnew file mode 100644index 000000000..1f0e3fdb5--- /dev/null+++ b/packages/number_utils/package.json@@ -0,0 +1,21 @@+{+ "name": "@fluxer/number_utils",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "exports": {+ "./*": "./*"+ },+ "scripts": {+ "test": "vitest run",+ "typecheck": "tsc --noEmit"+ },+ "dependencies": {+ "@fluxer/constants": "workspace:*"+ },+ "devDependencies": {+ "@types/node": "catalog:",+ "typescript": "catalog:ts7",+ "vitest": "catalog:"+ }+}diff --git a/packages/number_utils/src/NumberConstants.ts b/packages/number_utils/src/NumberConstants.tsnew file mode 100644index 000000000..68b153b6b--- /dev/null+++ b/packages/number_utils/src/NumberConstants.ts@@ -0,0 +1,5 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {Locales} from '@fluxer/constants/src/Locales';++export const DEFAULT_NUMBER_LOCALE = Locales.EN_US;diff --git a/packages/number_utils/src/NumberFormatterCache.ts b/packages/number_utils/src/NumberFormatterCache.tsnew file mode 100644index 000000000..9facfb278--- /dev/null+++ b/packages/number_utils/src/NumberFormatterCache.ts@@ -0,0 +1,25 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++const numberFormatterCache = new Map<string, Intl.NumberFormat>();++export function getNumberFormatter(+ locale: string,+ numberFormatOptions: Intl.NumberFormatOptions = {},+): Intl.NumberFormat {+ const cacheKey = buildFormatterCacheKey(locale, numberFormatOptions);+ const cachedFormatter = numberFormatterCache.get(cacheKey);+ if (cachedFormatter !== undefined) {+ return cachedFormatter;+ }+ const formatter = new Intl.NumberFormat(locale, numberFormatOptions);+ numberFormatterCache.set(cacheKey, formatter);+ return formatter;+}++function buildFormatterCacheKey(locale: string, numberFormatOptions: Intl.NumberFormatOptions): string {+ const optionEntries = Object.entries(numberFormatOptions)+ .filter(([, value]) => value !== undefined)+ .sort(([left], [right]) => left.localeCompare(right));+ const optionKey = optionEntries.map(([key, value]) => `${key}:${String(value)}`).join('|');+ return `${locale}|${optionKey}`;+}diff --git a/packages/number_utils/src/PriceFormatting.test.ts b/packages/number_utils/src/PriceFormatting.test.tsnew file mode 100644index 000000000..478d0369e--- /dev/null+++ b/packages/number_utils/src/PriceFormatting.test.ts@@ -0,0 +1,112 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {formatMinorUnitPrice} from '@fluxer/number_utils/src/PriceFormatting';+import {describe, expect, test} from 'vitest';++describe('formatMinorUnitPrice', () => {+ test.each([+ [1234567, 'USD', 'en-US', '$12,345.67'],+ [1234567, 'BRL', 'pt-BR', 'R$ 12.345,67'],+ [1234567, 'INR', 'hi', '₹12,345.67'],+ [1234567, 'TRY', 'tr', '₺12.345,67'],+ [1234567, 'SEK', 'sv-SE', '12 345,67 kr'],+ [999, 'USD', 'en-GB', 'US$9.99'],+ [999, 'USD', 'es-ES', '9,99 US$'],+ [999, 'USD', 'es-419', 'US$9.99'],+ [999, 'USD', 'fr', '9,99 $US'],+ [999, 'USD', 'pt-BR', 'US$ 9,99'],+ [999, 'USD', 'zh-TW', 'US$9.99'],+ ] as const)('formats %i %s for %s', (amount, currency, locale, expected) => {+ expect(formatMinorUnitPrice(amount, currency, locale)).toBe(expected);+ });++ test.each([+ ['ar', undefined, '\u20669.99 US$\u2069'],+ ['ar', 'US', '\u20669.99 $\u2069'],+ ['he', undefined, '\u20669.99 $\u2069'],+ ] as const)('isolates right-to-left prices for %s in %s', (locale, country, expected) => {+ expect(formatMinorUnitPrice(999, 'USD', locale, country)).toBe(expected);+ });++ test.each([+ [999, 'ISK', 'de', '10 kr'],+ [999, 'HUF', 'en-US', 'HUF 10'],+ [999, 'UGX', 'en-US', 'UGX 10'],+ ] as const)('rounds Stripe whole-unit prices for %i %s', (amount, currency, locale, expected) => {+ expect(formatMinorUnitPrice(amount, currency, locale)).toBe(expected);+ });++ test('shows the plain symbol for the currency of the reader country', () => {+ expect(formatMinorUnitPrice(999, 'SEK', 'en-US', 'SE')).toBe('9.99 kr');+ expect(formatMinorUnitPrice(999, 'NOK', 'sv-SE', 'NO')).toBe('9,99 kr');+ expect(formatMinorUnitPrice(999, 'DKK', 'da', 'SE')).toBe('9,99 kr.');+ expect(formatMinorUnitPrice(999, 'SEK', 'en-US', null)).toBe('SEK 9.99');+ expect(formatMinorUnitPrice(999, 'USD', 'en-GB', 'GB')).toBe('US$9.99');+ expect(formatMinorUnitPrice(999, 'USD', 'en-GB', 'us')).toBe('$9.99');+ expect(formatMinorUnitPrice(999, 'NOK', 'sv', 'SE')).toBe('9,99 Nkr');+ expect(formatMinorUnitPrice(999, 'DKK', 'en', 'GL')).toBe('9.99 kr');+ expect(formatMinorUnitPrice(59000, 'ISK', 'en-US', 'IS')).toBe('590 kr');+ });++ test('drops the fraction only on whole amounts', () => {+ expect(formatMinorUnitPrice(4900, 'SEK', 'sv-SE')).toBe('49 kr');+ expect(formatMinorUnitPrice(4950, 'SEK', 'sv-SE')).toBe('49,50 kr');+ expect(formatMinorUnitPrice(19900, 'USD', 'en-US')).toBe('$199');+ expect(formatMinorUnitPrice(499, 'USD', 'en-US')).toBe('$4.99');+ expect(formatMinorUnitPrice(59000, 'ISK', 'de')).toBe('590 kr');+ expect(formatMinorUnitPrice(700, 'JPY', 'ja')).toBe('¥700');+ });++ test('qualifies the dollar only where a reader has a dollar or peso of their own', () => {+ expect(formatMinorUnitPrice(999, 'USD', 'en-GB')).toBe('US$9.99');+ expect(formatMinorUnitPrice(999, 'USD', 'pt_BR')).toBe('US$ 9,99');+ expect(formatMinorUnitPrice(999, 'USD', 'fr-CA')).toBe('9,99 $US');+ expect(formatMinorUnitPrice(999, 'USD', 'de')).toBe('9,99 $');+ });++ test('writes kronor and złoty after the amount', () => {+ expect(formatMinorUnitPrice(4900, 'NOK', 'de')).toBe('49 kr');+ expect(formatMinorUnitPrice(3500, 'DKK', 'da')).toBe('35 kr.');+ expect(formatMinorUnitPrice(1799, 'PLN', 'nl')).toBe('17,99 zł');+ });++ test('keeps the plain krona for its own readers', () => {+ expect(formatMinorUnitPrice(999, 'SEK', 'sv-SE')).toBe('9,99 kr');+ expect(formatMinorUnitPrice(999, 'DKK', 'da-DK')).toBe('9,99 kr.');+ expect(formatMinorUnitPrice(999, 'NOK', 'nb-NO')).toBe('9,99 kr');+ expect(formatMinorUnitPrice(999, 'NOK', 'nn')).toBe('9,99 kr');+ expect(formatMinorUnitPrice(999, 'NOK', 'no')).toBe('9,99 kr');+ });++ test('tells a krona apart when the reader has another krona or none', () => {+ expect(formatMinorUnitPrice(999, 'NOK', 'sv')).toBe('9,99 Nkr');+ expect(formatMinorUnitPrice(999, 'DKK', 'sv-SE')).toBe('9,99 Dkr');+ expect(formatMinorUnitPrice(59000, 'ISK', 'sv-SE')).toBe('590 ISK');+ expect(formatMinorUnitPrice(999, 'SEK', 'da')).toBe('9,99 SEK');+ expect(formatMinorUnitPrice(999, 'NOK', 'da')).toBe('9,99 NOK');+ expect(formatMinorUnitPrice(999, 'SEK', 'nb')).toBe('9,99 SEK');+ expect(formatMinorUnitPrice(999, 'DKK', 'no')).toBe('9,99 DKK');+ expect(formatMinorUnitPrice(999, 'SEK', 'en-US')).toBe('SEK 9.99');+ expect(formatMinorUnitPrice(4900, 'NOK', 'en-AU')).toBe('NOK 49');+ expect(formatMinorUnitPrice(999, 'DKK', null)).toBe('DKK 9.99');+ });++ test('uses the standard symbol for other currencies', () => {+ expect(formatMinorUnitPrice(999, 'CAD', 'en-US')).toBe('CA$9.99');+ expect(formatMinorUnitPrice(999, 'AUD', 'en-US')).toBe('A$9.99');+ expect(formatMinorUnitPrice(999, 'CAD', 'de')).toBe('9,99 CA$');+ expect(formatMinorUnitPrice(999, 'GBP', 'en-GB')).toBe('£9.99');+ expect(formatMinorUnitPrice(999, 'CHF', 'de')).toBe('9,99 CHF');+ });++ test('falls back to American English for unknown locales', () => {+ expect(formatMinorUnitPrice(19900, 'usd', null)).toBe('$199');+ expect(formatMinorUnitPrice(19950, 'EUR', 'not a locale')).toBe('€199.50');+ expect(formatMinorUnitPrice(19950, 'EUR', 'zz')).toBe('€199.50');+ });++ test('returns null without an amount or currency', () => {+ expect(formatMinorUnitPrice(null, 'USD', 'en-US')).toBeNull();+ expect(formatMinorUnitPrice(100, '', 'en-US')).toBeNull();+ });+});diff --git a/packages/number_utils/src/PriceFormatting.ts b/packages/number_utils/src/PriceFormatting.tsnew file mode 100644index 000000000..6481e1eef--- /dev/null+++ b/packages/number_utils/src/PriceFormatting.ts@@ -0,0 +1,213 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {type LocaleCode, Locales} from '@fluxer/constants/src/Locales';+import {DEFAULT_NUMBER_LOCALE} from '@fluxer/number_utils/src/NumberConstants';+import {getNumberFormatter} from '@fluxer/number_utils/src/NumberFormatterCache';++const SIGN_SYMBOLS: Readonly<Record<string, string>> = {+ BRL: 'R$',+ EUR: '€',+ INR: '₹',+ TRY: '₺',+ USD: '$',+};++const WORD_SYMBOLS: Readonly<Record<string, string>> = {+ DKK: 'kr',+ ISK: 'kr',+ NOK: 'kr',+ PLN: 'zł',+ SEK: 'kr',+};++const DANISH_KRONE_ABBREVIATION = 'kr.';++const OWN_KRONE_BY_LANGUAGE: Readonly<Record<string, string | null>> = {+ da: 'DKK',+ en: null,+ nb: 'NOK',+ nn: 'NOK',+ no: 'NOK',+ sv: 'SEK',+};++const UNIQUE_KRONE_SYMBOLS_BY_LANGUAGE: Readonly<Record<string, Readonly<Record<string, string>>>> = {+ sv: {DKK: 'Dkr', NOK: 'Nkr'},+};++const QUALIFIED_DOLLAR_BY_LOCALE: Readonly<Partial<Record<LocaleCode, string>>> = {+ [Locales.AR]: 'US$',+ [Locales.EN_GB]: 'US$',+ [Locales.ES_ES]: 'US$',+ [Locales.ES_419]: 'US$',+ [Locales.FR]: '$US',+ [Locales.PT_BR]: 'US$',+ [Locales.ZH_TW]: 'US$',+};++const HOME_COUNTRIES_BY_CURRENCY: Readonly<Record<string, ReadonlySet<string>>> = {+ DKK: new Set(['DK', 'FO', 'GL']),+ ISK: new Set(['IS']),+ NOK: new Set(['BV', 'NO', 'SJ']),+ SEK: new Set(['SE']),+ USD: new Set([+ 'AS',+ 'BQ',+ 'EC',+ 'FM',+ 'GU',+ 'IO',+ 'MH',+ 'MP',+ 'PA',+ 'PR',+ 'PW',+ 'SV',+ 'TC',+ 'TL',+ 'UM',+ 'US',+ 'VG',+ 'VI',+ ]),+};++const STRIPE_TWO_DECIMAL_WHOLE_UNIT_CURRENCIES = new Set(['ISK', 'HUF', 'UGX']);+const RIGHT_TO_LEFT_LANGUAGES = new Set(['ar', 'he']);+const BIDI_MARKS = /[]/g;+const LEFT_TO_RIGHT_ISOLATE = '';+const POP_DIRECTIONAL_ISOLATE = '';+const NO_BREAK_SPACE = ' ';++const localeByLowerCaseTag = new Map<string, LocaleCode>(+ Object.values(Locales).map((locale) => [locale.toLowerCase(), locale]),+);++function resolveLocale(locale: string | null | undefined): string {+ if (!locale) {+ return DEFAULT_NUMBER_LOCALE;+ }+ const tag = locale.replaceAll('_', '-');+ try {+ return Intl.NumberFormat.supportedLocalesOf(tag).length > 0 ? tag : DEFAULT_NUMBER_LOCALE;+ } catch (error) {+ if (error instanceof RangeError) {+ return DEFAULT_NUMBER_LOCALE;+ }+ throw error;+ }+}++function findSupportedLocale(locale: string): LocaleCode | null {+ const tag = locale.toLowerCase();+ return localeByLowerCaseTag.get(tag) ?? localeByLowerCaseTag.get(tag.split('-')[0]) ?? null;+}++function currencyFractionDigits(currency: string): number {+ return (+ getNumberFormatter(DEFAULT_NUMBER_LOCALE, {style: 'currency', currency}).resolvedOptions().maximumFractionDigits ??+ 2+ );+}++function isHomeCurrency(currency: string, countryCode: string | null | undefined): boolean {+ return countryCode != null && (HOME_COUNTRIES_BY_CURRENCY[currency]?.has(countryCode.toUpperCase()) ?? false);+}++function signSymbol(+ currency: string,+ locale: LocaleCode | null,+ countryCode: string | null | undefined,+): string | undefined {+ if (currency === 'USD' && locale && !isHomeCurrency(currency, countryCode)) {+ return QUALIFIED_DOLLAR_BY_LOCALE[locale] ?? SIGN_SYMBOLS.USD;+ }+ return SIGN_SYMBOLS[currency];+}++function wordSymbolFor(+ currency: string,+ language: string,+ locale: LocaleCode | null,+ countryCode: string | null | undefined,+): string | null {+ const wordSymbol = WORD_SYMBOLS[currency];+ if (+ wordSymbol !== 'kr' ||+ isHomeCurrency(currency, countryCode) ||+ !Object.hasOwn(OWN_KRONE_BY_LANGUAGE, language) ||+ OWN_KRONE_BY_LANGUAGE[language] === currency+ ) {+ return wordSymbol === 'kr' && locale === Locales.DA ? DANISH_KRONE_ABBREVIATION : wordSymbol;+ }+ return UNIQUE_KRONE_SYMBOLS_BY_LANGUAGE[language]?.[currency] ?? null;+}++function formatWithCurrency(+ amount: number,+ currency: string,+ locale: string,+ digits: number,+ countryCode: string | null | undefined,+): string {+ const supportedLocale = findSupportedLocale(locale);+ if (WORD_SYMBOLS[currency]) {+ const symbol = wordSymbolFor(currency, locale.split('-')[0].toLowerCase(), supportedLocale, countryCode);+ if (!symbol) {+ return getNumberFormatter(locale, {+ style: 'currency',+ currency,+ currencyDisplay: 'code',+ minimumFractionDigits: digits,+ maximumFractionDigits: digits,+ }).format(amount);+ }+ const number = getNumberFormatter(locale, {minimumFractionDigits: digits, maximumFractionDigits: digits}).format(+ amount,+ );+ return `${number}${NO_BREAK_SPACE}${symbol}`;+ }+ const symbol = signSymbol(currency, supportedLocale, countryCode);+ const parts = getNumberFormatter(locale, {+ style: 'currency',+ currency,+ currencyDisplay: symbol ? 'narrowSymbol' : 'symbol',+ minimumFractionDigits: digits,+ maximumFractionDigits: digits,+ }).formatToParts(amount);+ return parts.map((part) => (part.type === 'currency' && symbol ? symbol : part.value)).join('');+}++export function formatMinorUnitPrice(+ amountMinor: number,+ currency: string,+ locale: string | null | undefined,+ countryCode?: string | null,+): string;+export function formatMinorUnitPrice(+ amountMinor: number | null | undefined,+ currency: string | null | undefined,+ locale: string | null | undefined,+ countryCode?: string | null,+): string | null;+export function formatMinorUnitPrice(+ amountMinor: number | null | undefined,+ currency: string | null | undefined,+ locale: string | null | undefined,+ countryCode?: string | null,+): string | null {+ if (amountMinor == null || !currency) {+ return null;+ }+ const code = currency.toUpperCase();+ const resolvedLocale = resolveLocale(locale);+ const wholeUnitDisplay = STRIPE_TWO_DECIMAL_WHOLE_UNIT_CURRENCIES.has(code);+ const fractionDigits = wholeUnitDisplay ? 0 : currencyFractionDigits(code);+ const exponent = wholeUnitDisplay ? 2 : fractionDigits;+ const digits = amountMinor % 10 ** exponent === 0 ? 0 : fractionDigits;+ const formatted = formatWithCurrency(amountMinor / 10 ** exponent, code, resolvedLocale, digits, countryCode);+ if (!RIGHT_TO_LEFT_LANGUAGES.has(resolvedLocale.split(/[-_]/)[0].toLowerCase())) {+ return formatted;+ }+ return `${LEFT_TO_RIGHT_ISOLATE}${formatted.replace(BIDI_MARKS, '')}${POP_DIRECTIONAL_ISOLATE}`;+}diff --git a/packages/number_utils/tsconfig.json b/packages/number_utils/tsconfig.jsonnew file mode 100644index 000000000..a8426e011--- /dev/null+++ b/packages/number_utils/tsconfig.json@@ -0,0 +1,5 @@+{+ "extends": "../../tsconfigs/package.json",+ "compilerOptions": {},+ "include": ["src/**/*"]+}diff --git a/packages/number_utils/vitest.config.ts b/packages/number_utils/vitest.config.tsnew file mode 100644index 000000000..99766af5f--- /dev/null+++ b/packages/number_utils/vitest.config.ts@@ -0,0 +1,3 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++export {default} from '../../tsconfigs/vitest.base.mts';