feat/pre-registration #7
@@ -8,7 +8,8 @@
|
|||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"icons": "bun run scripts/generate-icons.ts",
|
"icons": "bun run scripts/generate-icons.ts",
|
||||||
"typecheck": "tsc --noEmit"
|
"typecheck": "tsc --noEmit",
|
||||||
|
"test": "bun test"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@better-auth/passkey": "^1.7.2",
|
"@better-auth/passkey": "^1.7.2",
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import type { BillingType, PaymentDto, WeekDay } from '@gruperly/shared'
|
import type { BillingType, PaymentDto, WeekDay } from '@gruperly/shared'
|
||||||
|
|
||||||
|
import { countryOf, currencyForRegion, localeForRegion } from './region'
|
||||||
|
|
||||||
export const WEEK_DAY_FULL_LABELS: Record<WeekDay, string> = {
|
export const WEEK_DAY_FULL_LABELS: Record<WeekDay, string> = {
|
||||||
MONDAY: 'Lunes',
|
MONDAY: 'Lunes',
|
||||||
TUESDAY: 'Martes',
|
TUESDAY: 'Martes',
|
||||||
@@ -49,70 +51,163 @@ export function formatSchedule(days: readonly WeekDay[], time: string | null): s
|
|||||||
return time ? `${dayNames.join(', ')} · ${time}` : dayNames.join(', ')
|
return time ? `${dayNames.join(', ')} · ${time}` : dayNames.join(', ')
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Moneda por defecto de la app (Argentina). Solo define cómo se pinta: el
|
/* Un importe se escribe con el país de la persona: su moneda y su regional
|
||||||
valor persistido no cambia. La firma acepta la moneda para que el paso a
|
(separadores, posición del símbolo), sin conversión — el importe lo fija
|
||||||
multi-moneda no obligue a tocar los call sites. */
|
quien creó el grupo y no se toca. El país sale de la zona horaria del
|
||||||
export const DEFAULT_CURRENCY = 'ARS'
|
sistema y, si no se conoce, del idioma del browser (ver countryOf). Sin
|
||||||
|
país conocido se pinta con el símbolo $ genérico, nunca con un código
|
||||||
|
inventado. La firma acepta moneda y locale para forzarlas (tests, print)
|
||||||
|
sin tocar los call sites. */
|
||||||
|
|
||||||
export function formatPrice(price: number | null, currency: string = DEFAULT_CURRENCY): string {
|
/* La configuración regional del browser manda en cómo se pintan los datos.
|
||||||
|
Se lee en cada llamada (es un accessor barato) para que un cambio de idioma
|
||||||
|
del sistema se refleje sin recargar; lo caro es construir el formatter, así
|
||||||
|
que esos se memorizan por locale/moneda. */
|
||||||
|
type BrowserNavigator = { language?: string; languages?: readonly string[] }
|
||||||
|
|
||||||
|
function browserLocale(): string | undefined {
|
||||||
|
const nav = (globalThis as { navigator?: BrowserNavigator }).navigator
|
||||||
|
return nav?.language || nav?.languages?.[0] || undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
const priceFormatters = new Map<string, Intl.NumberFormat>()
|
||||||
|
|
||||||
|
export function formatPrice(
|
||||||
|
price: number | null,
|
||||||
|
currency?: string,
|
||||||
|
locale?: string,
|
||||||
|
): string {
|
||||||
if (price == null) return '—'
|
if (price == null) return '—'
|
||||||
// Importes enteros sin decimales ($50.000); con centavos se respetan.
|
// Importes enteros sin decimales ($50.000); con centavos se respetan.
|
||||||
const hasCents = !Number.isInteger(price)
|
const hasCents = !Number.isInteger(price)
|
||||||
return new Intl.NumberFormat('es-AR', {
|
const browser = locale ?? browserLocale()
|
||||||
|
const country = countryOf(browser)
|
||||||
|
const resolvedCurrency = currency ?? currencyForRegion(country)
|
||||||
|
// Los separadores y la posición del símbolo siguen al país: un browser en
|
||||||
|
// inglés en Argentina tiene que ver $50.000, no ARS 50,000. Con la locale
|
||||||
|
// pasada explícita no se toca nada (tests, print).
|
||||||
|
const resolved = locale === undefined ? (localeForRegion(country) ?? browser) : browser
|
||||||
|
const key = `${resolved ?? ''}|${resolvedCurrency ?? '$'}|${hasCents ? 'c' : 'i'}`
|
||||||
|
|
||||||
|
let formatter = priceFormatters.get(key)
|
||||||
|
if (!formatter) {
|
||||||
|
formatter = new Intl.NumberFormat(resolved, {
|
||||||
style: 'currency',
|
style: 'currency',
|
||||||
currency,
|
currency: resolvedCurrency ?? 'USD',
|
||||||
|
currencyDisplay: resolvedCurrency ? 'symbol' : 'narrowSymbol',
|
||||||
minimumFractionDigits: hasCents ? 2 : 0,
|
minimumFractionDigits: hasCents ? 2 : 0,
|
||||||
maximumFractionDigits: 2,
|
maximumFractionDigits: 2,
|
||||||
})
|
})
|
||||||
.format(price)
|
priceFormatters.set(key, formatter)
|
||||||
// es-AR separa el símbolo con un espacio duro (U+00A0): preferimos "$50.000".
|
}
|
||||||
.replace(/\u00A0/g, '')
|
return tidyCurrencySpacing(formatter.format(price))
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Presentación de teléfonos (Argentina). Nunca altera el valor persistido:
|
/* Intl separa el símbolo de la moneda con un espacio duro: "$ 50.000" se lee
|
||||||
es maquillaje de salida, y los links wa.me siguen usando los dígitos crudos.
|
como dos tokens sueltos. Lo quitamos solo cuando separa símbolo de número;
|
||||||
|
entre dígitos y código ("50.000 ARS") el no-break space evita el corte. */
|
||||||
|
const SYMBOL_GAP = /([^\p{L}\p{N}])\u00A0/gu
|
||||||
|
|
||||||
Estrategia: se normalizan los prefijos conocidos (0054 / 54 / 0 nacional y
|
function tidyCurrencySpacing(value: string): string {
|
||||||
el 9 de móvil argentino). Si el resultado no parece un número plausible
|
return value.replace(SYMBOL_GAP, '$1')
|
||||||
(6 a 10 dígitos nacionales) se devuelve el valor original tal cual: es
|
}
|
||||||
preferible un número sin maquillar a uno inventado. */
|
|
||||||
export function formatPhoneDisplay(value: string | null | undefined): string | null {
|
/* ── Teléfonos ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
Presentación, nunca persistencia: los links wa.me siguen usando los dígitos
|
||||||
|
crudos. El formato sale de la región del propio número cuando su prefijo de
|
||||||
|
país es reconocible; si el número es nacional, manda la región del browser
|
||||||
|
(y si esa región no la conocemos, la de la app: AR). Si nada encaja se cae
|
||||||
|
a E.164 (+331234567890) o al valor original, siempre preferible a un número
|
||||||
|
inventado. */
|
||||||
|
|
||||||
|
type PhoneRegion = 'AR' | 'US' | 'ES' | 'MX'
|
||||||
|
|
||||||
|
/** Prefijos de país que sabemos agrupar. */
|
||||||
|
const COUNTRY_CALLING_CODES: { region: PhoneRegion; code: string }[] = [
|
||||||
|
{ region: 'AR', code: '54' },
|
||||||
|
{ region: 'ES', code: '34' },
|
||||||
|
{ region: 'MX', code: '52' },
|
||||||
|
{ region: 'US', code: '1' },
|
||||||
|
]
|
||||||
|
|
||||||
|
export function formatPhoneDisplay(
|
||||||
|
value: string | null | undefined,
|
||||||
|
locale?: string,
|
||||||
|
): string | null {
|
||||||
if (value == null) return null
|
if (value == null) return null
|
||||||
const raw = value.trim()
|
const raw = value.trim()
|
||||||
if (!raw) return null
|
if (!raw) return null
|
||||||
|
|
||||||
|
const hasPlus = raw.startsWith('+')
|
||||||
let digits = raw.replace(/\D/g, '')
|
let digits = raw.replace(/\D/g, '')
|
||||||
|
// "0054…" es el mismo indicio internacional que "+54…".
|
||||||
|
const hasDoubleZero = !hasPlus && raw.startsWith('00')
|
||||||
|
if (hasDoubleZero) digits = digits.slice(2)
|
||||||
if (digits.length < 6) return raw
|
if (digits.length < 6) return raw
|
||||||
|
|
||||||
let isAr = false
|
const withCallingCode = formatWithCallingCode(digits)
|
||||||
|
if (withCallingCode) return withCallingCode
|
||||||
|
if (hasPlus || hasDoubleZero) return `+${digits}`
|
||||||
|
|
||||||
|
return formatNational(digits, appRegion(countryOf(locale ?? browserLocale())), false) ?? raw
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Prueba el prefijo de país solo si lo que sigue encaja en sus reglas. */
|
||||||
|
function formatWithCallingCode(digits: string): string | null {
|
||||||
|
for (const { region, code } of COUNTRY_CALLING_CODES) {
|
||||||
|
if (!digits.startsWith(code)) continue
|
||||||
|
const formatted = formatNational(digits.slice(code.length), region, true)
|
||||||
|
if (formatted) return formatted
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Región ISO → región con reglas propias. CA comparte NANP con US. */
|
||||||
|
function appRegion(region: string | undefined): PhoneRegion {
|
||||||
|
if (region === 'US' || region === 'CA') return 'US'
|
||||||
|
if (region === 'ES') return 'ES'
|
||||||
|
if (region === 'MX') return 'MX'
|
||||||
|
// Sin región reconocible seguimos siendo una app de Argentina.
|
||||||
|
return 'AR'
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatNational(
|
||||||
|
digits: string,
|
||||||
|
region: PhoneRegion,
|
||||||
|
hasCallingCode: boolean,
|
||||||
|
): string | null {
|
||||||
|
switch (region) {
|
||||||
|
case 'AR':
|
||||||
|
return formatArNational(digits, hasCallingCode)
|
||||||
|
case 'US':
|
||||||
|
return formatUsNational(digits)
|
||||||
|
case 'ES':
|
||||||
|
return formatEsNational(digits, hasCallingCode)
|
||||||
|
case 'MX':
|
||||||
|
return formatMxNational(digits, hasCallingCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatArNational(digits: string, withCountry: boolean): string | null {
|
||||||
|
let national = digits
|
||||||
let isMobile = false
|
let isMobile = false
|
||||||
|
|
||||||
if (digits.startsWith('0054')) {
|
|
||||||
digits = digits.slice(4)
|
|
||||||
isAr = true
|
|
||||||
} else if (digits.startsWith('54') && digits.length >= 12) {
|
|
||||||
digits = digits.slice(2)
|
|
||||||
isAr = true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Móvil argentino: 9 + 10 dígitos nacionales.
|
// Móvil argentino: 9 + 10 dígitos nacionales.
|
||||||
if (digits.length === 11 && digits.startsWith('9')) {
|
if (national.length === 11 && national.startsWith('9')) {
|
||||||
digits = digits.slice(1)
|
national = national.slice(1)
|
||||||
isMobile = true
|
isMobile = true
|
||||||
isAr = true
|
|
||||||
}
|
}
|
||||||
|
// 0 de trunk nacional: además implica que el número es argentino.
|
||||||
// 0 de trunk nacional (0 + 10 dígitos; o 0 + 9 tras el 9 de móvil).
|
if (national.startsWith('0') && national.length >= 9) {
|
||||||
if (digits.startsWith('0') && digits.length >= 9) {
|
national = national.slice(1)
|
||||||
digits = digits.slice(1)
|
withCountry = true
|
||||||
isAr = true
|
|
||||||
}
|
}
|
||||||
|
if (national.length < 6 || national.length > 10) return null
|
||||||
|
|
||||||
if (digits.length < 6 || digits.length > 10) return raw
|
const local = groupArNational(national)
|
||||||
|
const body = isMobile ? `9 ${local}` : local
|
||||||
const local = groupArNational(digits)
|
return withCountry ? `+54 ${body}` : body
|
||||||
if (!isAr) return local
|
|
||||||
return isMobile ? `+54 9 ${local}` : `+54 ${local}`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function groupArNational(digits: string): string {
|
function groupArNational(digits: string): string {
|
||||||
@@ -128,6 +223,29 @@ function groupArNational(digits: string): string {
|
|||||||
return digits
|
return digits
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** NANP (US/CA): 10 dígitos con área e intercambio que arrancan en 2–9. */
|
||||||
|
function formatUsNational(digits: string): string | null {
|
||||||
|
if (digits.length === 11 && digits.startsWith('1')) digits = digits.slice(1)
|
||||||
|
if (digits.length !== 10) return null
|
||||||
|
if (digits[0] === '0' || digits[0] === '1' || digits[3] === '0' || digits[3] === '1') return null
|
||||||
|
// Convención doméstica: el "1" del país no se escribe.
|
||||||
|
return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** España: 9 dígitos (móvil 6/7, fijo 8/9) agrupados 3-2-2-2. */
|
||||||
|
function formatEsNational(digits: string, withCountry: boolean): string | null {
|
||||||
|
if (digits.length !== 9 || !'6789'.includes(digits[0])) return null
|
||||||
|
const local = `${digits.slice(0, 3)} ${digits.slice(3, 5)} ${digits.slice(5, 7)} ${digits.slice(7)}`
|
||||||
|
return withCountry ? `+34 ${local}` : local
|
||||||
|
}
|
||||||
|
|
||||||
|
/** México: 10 dígitos agrupados 2-4-4. */
|
||||||
|
function formatMxNational(digits: string, withCountry: boolean): string | null {
|
||||||
|
if (digits.length !== 10 || digits[0] === '0' || digits[0] === '1') return null
|
||||||
|
const local = `${digits.slice(0, 2)} ${digits.slice(2, 6)} ${digits.slice(6)}`
|
||||||
|
return withCountry ? `+52 ${local}` : local
|
||||||
|
}
|
||||||
|
|
||||||
// El vencimiento se cuenta como frase ("Vence el día 10 de cada mes") en vez
|
// El vencimiento se cuenta como frase ("Vence el día 10 de cada mes") en vez
|
||||||
// de "Vence día 10": se lee como una promesa, no como un dato suelto.
|
// de "Vence día 10": se lee como una promesa, no como un dato suelto.
|
||||||
export function formatBillingMeta(
|
export function formatBillingMeta(
|
||||||
|
|||||||
271
apps/web/src/lib/region.ts
Normal file
271
apps/web/src/lib/region.ts
Normal file
@@ -0,0 +1,271 @@
|
|||||||
|
/* De dónde es la persona y cómo se le escriben los números.
|
||||||
|
|
||||||
|
El idioma del browser dice en qué idioma se está, no en qué país se está:
|
||||||
|
con "en-US" a alguien en Argentina lo trata como estadounidense, y con
|
||||||
|
"es-419" no dice ningún país. La zona horaria —que sí expone el sistema—
|
||||||
|
es la señal del país real; el idioma solo define cuando la zona no se
|
||||||
|
conoce. Con el país resuelto salen la moneda (REGION_CURRENCY) y la
|
||||||
|
regional con la que se formatea (REGION_LOCALE), para que un browser en
|
||||||
|
inglés en Argentina vea $50.000 y no ARS 50,000.
|
||||||
|
|
||||||
|
Estos mapas son dato a mano (Intl no expone región → moneda ni región →
|
||||||
|
locale). Solo definen cómo se PINTA un importe: el valor persistido no
|
||||||
|
cambia ni se convierte. Si el país no está en ninguno, formatPrice cae al
|
||||||
|
símbolo $ genérico. */
|
||||||
|
|
||||||
|
export const REGION_CURRENCY: Record<string, string> = {
|
||||||
|
// Norteamérica
|
||||||
|
CA: 'CAD',
|
||||||
|
US: 'USD',
|
||||||
|
|
||||||
|
// Latinoamérica y Caribe
|
||||||
|
AR: 'ARS',
|
||||||
|
BO: 'BOB',
|
||||||
|
BR: 'BRL',
|
||||||
|
CL: 'CLP',
|
||||||
|
CO: 'COP',
|
||||||
|
CR: 'CRC',
|
||||||
|
CU: 'CUP',
|
||||||
|
DO: 'DOP',
|
||||||
|
EC: 'USD',
|
||||||
|
GT: 'GTQ',
|
||||||
|
HN: 'HNL',
|
||||||
|
MX: 'MXN',
|
||||||
|
NI: 'NIO',
|
||||||
|
PA: 'USD',
|
||||||
|
PE: 'PEN',
|
||||||
|
PR: 'USD',
|
||||||
|
PY: 'PYG',
|
||||||
|
SV: 'USD',
|
||||||
|
UY: 'UYU',
|
||||||
|
VE: 'VES',
|
||||||
|
|
||||||
|
// Zona euro
|
||||||
|
AT: 'EUR',
|
||||||
|
BE: 'EUR',
|
||||||
|
HR: 'EUR',
|
||||||
|
CY: 'EUR',
|
||||||
|
EE: 'EUR',
|
||||||
|
FI: 'EUR',
|
||||||
|
FR: 'EUR',
|
||||||
|
DE: 'EUR',
|
||||||
|
GR: 'EUR',
|
||||||
|
IE: 'EUR',
|
||||||
|
IT: 'EUR',
|
||||||
|
LV: 'EUR',
|
||||||
|
LT: 'EUR',
|
||||||
|
LU: 'EUR',
|
||||||
|
MT: 'EUR',
|
||||||
|
NL: 'EUR',
|
||||||
|
PT: 'EUR',
|
||||||
|
SK: 'EUR',
|
||||||
|
SI: 'EUR',
|
||||||
|
ES: 'EUR',
|
||||||
|
|
||||||
|
// Fuera de la zona euro
|
||||||
|
CH: 'CHF',
|
||||||
|
GB: 'GBP',
|
||||||
|
CZ: 'CZK',
|
||||||
|
DK: 'DKK',
|
||||||
|
NO: 'NOK',
|
||||||
|
PL: 'PLN',
|
||||||
|
RU: 'RUB',
|
||||||
|
SE: 'SEK',
|
||||||
|
TR: 'TRY',
|
||||||
|
UA: 'UAH',
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Regional con la que se formatea para cada país. México y Argentina usan
|
||||||
|
separadores distintos (1,234.56 vs 1.234,56), así que el locale va con el
|
||||||
|
país y no solo con el idioma. */
|
||||||
|
export const REGION_LOCALE: Record<string, string> = {
|
||||||
|
// Norteamérica
|
||||||
|
CA: 'en-CA',
|
||||||
|
US: 'en-US',
|
||||||
|
|
||||||
|
// Latinoamérica y Caribe
|
||||||
|
AR: 'es-AR',
|
||||||
|
BO: 'es-BO',
|
||||||
|
BR: 'pt-BR',
|
||||||
|
CL: 'es-CL',
|
||||||
|
CO: 'es-CO',
|
||||||
|
CR: 'es-CR',
|
||||||
|
CU: 'es-CU',
|
||||||
|
DO: 'es-DO',
|
||||||
|
EC: 'es-EC',
|
||||||
|
GT: 'es-GT',
|
||||||
|
HN: 'es-HN',
|
||||||
|
MX: 'es-MX',
|
||||||
|
NI: 'es-NI',
|
||||||
|
PA: 'es-PA',
|
||||||
|
PE: 'es-PE',
|
||||||
|
PR: 'es-PR',
|
||||||
|
PY: 'es-PY',
|
||||||
|
SV: 'es-SV',
|
||||||
|
UY: 'es-UY',
|
||||||
|
VE: 'es-VE',
|
||||||
|
|
||||||
|
// Zona euro
|
||||||
|
AT: 'de-AT',
|
||||||
|
BE: 'nl-BE',
|
||||||
|
HR: 'hr-HR',
|
||||||
|
CY: 'el-CY',
|
||||||
|
EE: 'et-EE',
|
||||||
|
FI: 'fi-FI',
|
||||||
|
FR: 'fr-FR',
|
||||||
|
DE: 'de-DE',
|
||||||
|
GR: 'el-GR',
|
||||||
|
IE: 'en-IE',
|
||||||
|
IT: 'it-IT',
|
||||||
|
LV: 'lv-LV',
|
||||||
|
LT: 'lt-LT',
|
||||||
|
LU: 'fr-LU',
|
||||||
|
MT: 'mt-MT',
|
||||||
|
NL: 'nl-NL',
|
||||||
|
PT: 'pt-PT',
|
||||||
|
SK: 'sk-SK',
|
||||||
|
SI: 'sl-SI',
|
||||||
|
ES: 'es-ES',
|
||||||
|
|
||||||
|
// Fuera de la zona euro
|
||||||
|
CH: 'de-CH',
|
||||||
|
GB: 'en-GB',
|
||||||
|
CZ: 'cs-CZ',
|
||||||
|
DK: 'da-DK',
|
||||||
|
NO: 'nb-NO',
|
||||||
|
PL: 'pl-PL',
|
||||||
|
RU: 'ru-RU',
|
||||||
|
SE: 'sv-SE',
|
||||||
|
TR: 'tr-TR',
|
||||||
|
UA: 'uk-UA',
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Zona horaria IANA → región ISO 3166-1 alpha-2.
|
||||||
|
|
||||||
|
Cobertura: las zonas de los países de arriba, agrupadas por prefijo
|
||||||
|
(America/Argentina/*) o por la ciudad en la zona (Sao_Paulo). Cubre las
|
||||||
|
zonas principales; una zona desconocida cae al país del idioma. */
|
||||||
|
export const TIMEZONE_REGION: Record<string, string> = {
|
||||||
|
// ── Latinoamérica ─────────────────────────────────────────────────────────
|
||||||
|
'America/Argentina/': 'AR',
|
||||||
|
// Chromium/ICU reporta en la forma legacy (sin el prefijo "Argentina/") las
|
||||||
|
// zonas argentinas más comunes: America/Argentina/Buenos_Aires → America/Buenos_Aires.
|
||||||
|
'America/Buenos_Aires': 'AR',
|
||||||
|
'America/Catamarca': 'AR',
|
||||||
|
'America/Cordoba': 'AR',
|
||||||
|
'America/Jujuy': 'AR',
|
||||||
|
'America/Mendoza': 'AR',
|
||||||
|
'America/La_Paz': 'BO',
|
||||||
|
'America/Sao_Paulo': 'BR',
|
||||||
|
'America/Fortaleza': 'BR',
|
||||||
|
'America/Recife': 'BR',
|
||||||
|
'America/Bahia': 'BR',
|
||||||
|
'America/Manaus': 'BR',
|
||||||
|
'America/Cuiaba': 'BR',
|
||||||
|
'America/Porto_Velho': 'BR',
|
||||||
|
'America/Noronha': 'BR',
|
||||||
|
'America/Campo_Grande': 'BR',
|
||||||
|
'America/Santiago': 'CL',
|
||||||
|
'America/Bogota': 'CO',
|
||||||
|
'America/Lima': 'PE',
|
||||||
|
'America/Asuncion': 'PY',
|
||||||
|
'America/Montevideo': 'UY',
|
||||||
|
'America/Caracas': 'VE',
|
||||||
|
'America/Guayaquil': 'EC',
|
||||||
|
'America/Panama': 'PA',
|
||||||
|
'America/Managua': 'NI',
|
||||||
|
'America/Tegucigalpa': 'HN',
|
||||||
|
'America/El_Salvador': 'SV',
|
||||||
|
'America/Guatemala': 'GT',
|
||||||
|
'America/Costa_Rica': 'CR',
|
||||||
|
'America/Havana': 'CU',
|
||||||
|
'America/Santo_Domingo': 'DO',
|
||||||
|
'America/Puerto_Rico': 'PR',
|
||||||
|
|
||||||
|
// ── Norteamérica ─────────────────────────────────────────────────────────
|
||||||
|
'America/New_York': 'US',
|
||||||
|
'America/Detroit': 'US',
|
||||||
|
'America/Chicago': 'US',
|
||||||
|
'America/Denver': 'US',
|
||||||
|
'America/Phoenix': 'US',
|
||||||
|
'America/Los_Angeles': 'US',
|
||||||
|
'America/Anchorage': 'US',
|
||||||
|
'Pacific/Honolulu': 'US',
|
||||||
|
'America/Toronto': 'CA',
|
||||||
|
'America/Vancouver': 'CA',
|
||||||
|
'America/Winnipeg': 'CA',
|
||||||
|
'America/Edmonton': 'CA',
|
||||||
|
'America/Halifax': 'CA',
|
||||||
|
'America/Regina': 'CA',
|
||||||
|
'America/St_Johns': 'CA',
|
||||||
|
|
||||||
|
// ── Europa ───────────────────────────────────────────────────────────────
|
||||||
|
'Europe/Madrid': 'ES',
|
||||||
|
'Atlantic/Canary': 'ES',
|
||||||
|
'Atlantic/Faeroe': 'ES',
|
||||||
|
'Europe/Lisbon': 'PT',
|
||||||
|
'Europe/Rome': 'IT',
|
||||||
|
'Europe/Paris': 'FR',
|
||||||
|
'Europe/Berlin': 'DE',
|
||||||
|
'Europe/Vienna': 'AT',
|
||||||
|
'Europe/Brussels': 'BE',
|
||||||
|
'Europe/Amsterdam': 'NL',
|
||||||
|
'Europe/Dublin': 'IE',
|
||||||
|
'Europe/Zurich': 'CH',
|
||||||
|
'Europe/London': 'GB',
|
||||||
|
'Europe/Copenhagen': 'DK',
|
||||||
|
'Europe/Oslo': 'NO',
|
||||||
|
'Europe/Stockholm': 'SE',
|
||||||
|
'Europe/Warsaw': 'PL',
|
||||||
|
'Europe/Prague': 'CZ',
|
||||||
|
'Europe/Helsinki': 'FI',
|
||||||
|
'Europe/Athens': 'GR',
|
||||||
|
'Europe/Kyiv': 'UA',
|
||||||
|
'Europe/Kiev': 'UA',
|
||||||
|
'Europe/Moscow': 'RU',
|
||||||
|
'Europe/Istanbul': 'TR',
|
||||||
|
}
|
||||||
|
|
||||||
|
const ZONE_PREFIXES = Object.keys(TIMEZONE_REGION).filter((zone) => zone.endsWith('/'))
|
||||||
|
|
||||||
|
export function browserTimezone(): string | undefined {
|
||||||
|
try {
|
||||||
|
return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined
|
||||||
|
} catch {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function regionForTimezone(timezone: string | undefined): string | undefined {
|
||||||
|
if (!timezone) return undefined
|
||||||
|
const exact = TIMEZONE_REGION[timezone]
|
||||||
|
if (exact) return exact
|
||||||
|
const prefix = ZONE_PREFIXES.find((zone) => timezone.startsWith(zone))
|
||||||
|
return prefix ? TIMEZONE_REGION[prefix] : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Región del locale (es-MX → MX). Un locale sin país se maximiza, pero solo
|
||||||
|
como último recurso: countryOf prefiere la zona horaria. */
|
||||||
|
export function regionOf(locale: string | undefined): string | undefined {
|
||||||
|
if (!locale || typeof Intl.Locale === 'undefined') return undefined
|
||||||
|
try {
|
||||||
|
return new Intl.Locale(locale).maximize().region
|
||||||
|
} catch {
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** País de la persona: el de la zona horaria, y si no se conoce, el del
|
||||||
|
idioma. `en` sin país no se maximiza a US a propósito: un usuario en
|
||||||
|
México con el browser en inglés caería en dólares. */
|
||||||
|
export function countryOf(locale: string | undefined): string | undefined {
|
||||||
|
return regionForTimezone(browserTimezone()) ?? regionOf(locale)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function currencyForRegion(region: string | undefined): string | undefined {
|
||||||
|
return region ? REGION_CURRENCY[region] : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
export function localeForRegion(region: string | undefined): string | undefined {
|
||||||
|
return region ? REGION_LOCALE[region] : undefined
|
||||||
|
}
|
||||||
299
apps/web/test/format.test.ts
Normal file
299
apps/web/test/format.test.ts
Normal file
@@ -0,0 +1,299 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
|
||||||
|
import { formatPhoneDisplay, formatPrice } from '../src/lib/format'
|
||||||
|
import {
|
||||||
|
browserTimezone,
|
||||||
|
countryOf,
|
||||||
|
currencyForRegion,
|
||||||
|
localeForRegion,
|
||||||
|
REGION_CURRENCY,
|
||||||
|
REGION_LOCALE,
|
||||||
|
regionForTimezone,
|
||||||
|
regionOf,
|
||||||
|
TIMEZONE_REGION,
|
||||||
|
} from '../src/lib/region'
|
||||||
|
|
||||||
|
/* Un importe se pinta con el país de la persona: su moneda y su regional
|
||||||
|
(separadores, posición del símbolo). El país sale de la zona horaria del
|
||||||
|
sistema y, si no se conoce, del idioma del browser. El valor persistido no
|
||||||
|
cambia: no hay conversión. */
|
||||||
|
|
||||||
|
const nav = globalThis as { navigator?: { language?: string; languages?: string[] } }
|
||||||
|
|
||||||
|
function stubLanguage(language: string) {
|
||||||
|
Object.defineProperty(globalThis, 'navigator', {
|
||||||
|
value: { language, languages: [language] },
|
||||||
|
configurable: true,
|
||||||
|
writable: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function restoreNavigator() {
|
||||||
|
delete (nav as { navigator?: unknown }).navigator
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Simula el navegador: idioma y zona horaria del sistema. */
|
||||||
|
function stubLocation(language: string, timezone: string) {
|
||||||
|
stubLanguage(language)
|
||||||
|
const original = Intl.DateTimeFormat
|
||||||
|
// Callable sin new, como Intl.DateTimeFormat().
|
||||||
|
const fake = () => ({ resolvedOptions: () => ({ timeZone: timezone }) })
|
||||||
|
;(Intl as { DateTimeFormat: unknown }).DateTimeFormat = fake as never
|
||||||
|
return () => {
|
||||||
|
;(Intl as { DateTimeFormat: unknown }).DateTimeFormat = original
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ejecuta fn con un navegador simulado y deja todo como estaba. */
|
||||||
|
function withLocation(language: string, timezone: string, fn: () => void) {
|
||||||
|
const restore = stubLocation(language, timezone)
|
||||||
|
try {
|
||||||
|
fn()
|
||||||
|
} finally {
|
||||||
|
restore()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pinta el importe como lo vería un browser con esa locale. */
|
||||||
|
function priceFor(amount: number, language: string): string {
|
||||||
|
stubLanguage(language)
|
||||||
|
return formatPrice(amount)
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('formatPrice — país del browser', () => {
|
||||||
|
beforeEach(() => stubLanguage('es-AR'))
|
||||||
|
afterEach(() => restoreNavigator())
|
||||||
|
|
||||||
|
test('el idioma del browser define moneda y regional', () => {
|
||||||
|
expect(priceFor(50_000, 'es-AR')).toBe('$50.000')
|
||||||
|
expect(priceFor(50_000, 'es-MX')).toBe('$50,000')
|
||||||
|
expect(priceFor(50_000, 'es-PE')).toBe('S/50,000')
|
||||||
|
expect(priceFor(50_000, 'pt-BR')).toBe('R$50.000')
|
||||||
|
expect(priceFor(50_000, 'es-ES')).toBe('50.000\u00A0€')
|
||||||
|
expect(priceFor(50_000, 'en-US')).toBe('$50,000')
|
||||||
|
expect(priceFor(50_000, 'en-CA')).toBe('$50,000')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('la zona horaria define el país si el idioma no lo dice', () => {
|
||||||
|
// Browser en inglés, usuario en Argentina: pesos y separador de miles argentino.
|
||||||
|
withLocation('en-US', 'America/Argentina/Buenos_Aires', () => {
|
||||||
|
expect(formatPrice(50_000)).toBe('$50.000')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('la zona horaria gana sobre el idioma del browser', () => {
|
||||||
|
withLocation('es-MX', 'America/Argentina/Buenos_Aires', () => {
|
||||||
|
expect(formatPrice(50_000)).toBe('$50.000')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('la zona horaria cubre otros países', () => {
|
||||||
|
withLocation('es-419', 'America/Lima', () => {
|
||||||
|
expect(formatPrice(50_000)).toBe('S/50,000')
|
||||||
|
})
|
||||||
|
withLocation('es-419', 'America/Mexico_City', () => {
|
||||||
|
expect(formatPrice(50_000)).toBe('$50,000')
|
||||||
|
})
|
||||||
|
withLocation('es-419', 'Europe/Madrid', () => {
|
||||||
|
expect(formatPrice(50_000)).toBe('50.000\u00A0€')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('los centavos se conservan', () => {
|
||||||
|
expect(priceFor(50_000.5, 'es-AR')).toBe('$50.000,50')
|
||||||
|
expect(priceFor(50_000.5, 'es-MX')).toBe('$50,000.50')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('sin país ni zona conocida se ve el símbolo $', () => {
|
||||||
|
withLocation('es-419', 'Africa/Algiers', () => {
|
||||||
|
expect(formatPrice(50_000)).toBe('$50,000')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('sin browser se ve el símbolo $ con la regional del runtime', () => {
|
||||||
|
restoreNavigator()
|
||||||
|
const value = formatPrice(50_000)
|
||||||
|
expect(value).toContain('$')
|
||||||
|
expect(value).toContain('50')
|
||||||
|
expect(value).not.toContain('ARS')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('por defecto usa la locale del browser', () => {
|
||||||
|
stubLanguage('en-US')
|
||||||
|
expect(formatPrice(50_000)).toBe('$50,000')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('importes nulos y cero', () => {
|
||||||
|
expect(formatPrice(null)).toBe('—')
|
||||||
|
expect(priceFor(0, 'es-AR')).toBe('$0')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('formatPrice — moneda y locale explícitos', () => {
|
||||||
|
beforeEach(() => stubLanguage('es-AR'))
|
||||||
|
afterEach(() => restoreNavigator())
|
||||||
|
|
||||||
|
test('separa y posiciona según la locale pedida', () => {
|
||||||
|
expect(formatPrice(50_000, 'ARS', 'es-AR')).toBe('$50.000')
|
||||||
|
expect(formatPrice(50_000, 'ARS', 'en-US')).toBe('ARS\u00A050,000')
|
||||||
|
expect(formatPrice(50_000, 'ARS', 'es-ES')).toBe('50.000\u00A0ARS')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('muestra centavos solo cuando el importe los tiene', () => {
|
||||||
|
expect(formatPrice(50_000.5, 'ARS', 'en-US')).toBe('ARS\u00A050,000.50')
|
||||||
|
expect(formatPrice(50_000.5, 'ARS', 'es-AR')).toBe('$50.000,50')
|
||||||
|
expect(formatPrice(50_000, 'ARS', 'en-US')).toBe('ARS\u00A050,000')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('ganan sobre el país del browser', () => {
|
||||||
|
withLocation('en-US', 'America/Lima', () => {
|
||||||
|
expect(formatPrice(50_000, 'ARS', 'es-AR')).toBe('$50.000')
|
||||||
|
expect(formatPrice(50_000, 'ARS', 'en-US')).toBe('ARS\u00A050,000')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('region', () => {
|
||||||
|
test('el mapa de monedas usa códigos ISO válidos', () => {
|
||||||
|
const known = Intl.supportedValuesOf('currency')
|
||||||
|
for (const [region, currency] of Object.entries(REGION_CURRENCY)) {
|
||||||
|
expect(region).toMatch(/^[A-Z]{2}$/)
|
||||||
|
expect(currency).toMatch(/^[A-Z]{3}$/)
|
||||||
|
expect(known).toContain(currency)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('el mapa de zonas usa códigos ISO y zonas reales', () => {
|
||||||
|
for (const [zone, region] of Object.entries(TIMEZONE_REGION)) {
|
||||||
|
expect(region).toMatch(/^[A-Z]{2}$/)
|
||||||
|
if (zone.endsWith('/')) continue
|
||||||
|
expect(() => new Intl.DateTimeFormat('en-US', { timeZone: zone })).not.toThrow()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('las locales por país son tags válidos y cubren a los países', () => {
|
||||||
|
for (const [region, locale] of Object.entries(REGION_LOCALE)) {
|
||||||
|
expect(region).toMatch(/^[A-Z]{2}$/)
|
||||||
|
expect(locale).toMatch(/^[a-z]{2}-[A-Z]{2}$/)
|
||||||
|
expect(() => new Intl.NumberFormat(locale)).not.toThrow()
|
||||||
|
}
|
||||||
|
for (const region of Object.keys(REGION_CURRENCY)) {
|
||||||
|
expect(localeForRegion(region)).toBeDefined()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('el mapa de zonas cubre países que tienen moneda', () => {
|
||||||
|
for (const zone of Object.keys(TIMEZONE_REGION)) {
|
||||||
|
const resolvable = zone.endsWith('/') ? `${zone}Test` : zone
|
||||||
|
expect(currencyForRegion(regionForTimezone(resolvable))).toBeDefined()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('resuelve la zona por ciudad y por prefijo', () => {
|
||||||
|
expect(regionForTimezone('America/Argentina/Buenos_Aires')).toBe('AR')
|
||||||
|
expect(regionForTimezone('America/Argentina/Catamarca')).toBe('AR')
|
||||||
|
expect(regionForTimezone('America/Sao_Paulo')).toBe('BR')
|
||||||
|
expect(regionForTimezone('America/Lima')).toBe('PE')
|
||||||
|
expect(regionForTimezone('Europe/Madrid')).toBe('ES')
|
||||||
|
expect(regionForTimezone('Asia/Tokyo')).toBeUndefined()
|
||||||
|
expect(regionForTimezone('Africa/Algiers')).toBeUndefined()
|
||||||
|
expect(regionForTimezone('UTC')).toBeUndefined()
|
||||||
|
expect(regionForTimezone(undefined)).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('las zonas legacy que reporta el browser también resuelven', () => {
|
||||||
|
// Chromium/ICU canonicaliza America/Argentina/X a America/X.
|
||||||
|
expect(regionForTimezone('America/Buenos_Aires')).toBe('AR')
|
||||||
|
expect(regionForTimezone('America/Catamarca')).toBe('AR')
|
||||||
|
expect(regionForTimezone('America/Mendoza')).toBe('AR')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('resuelve el país: la zona horaria primero', () => {
|
||||||
|
withLocation('en-US', 'America/Argentina/Buenos_Aires', () => {
|
||||||
|
expect(countryOf('en-US')).toBe('AR')
|
||||||
|
})
|
||||||
|
withLocation('es-419', 'America/Lima', () => {
|
||||||
|
expect(countryOf('es-419')).toBe('PE')
|
||||||
|
})
|
||||||
|
// Sin zona conocida manda el idioma.
|
||||||
|
withLocation('es-MX', 'Africa/Algiers', () => {
|
||||||
|
expect(countryOf('es-MX')).toBe('MX')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('regionOf usa el locale que le pasan', () => {
|
||||||
|
expect(regionOf('es-MX')).toBe('MX')
|
||||||
|
expect(regionOf('es-419')).toBe('419')
|
||||||
|
expect(regionOf('pt-BR')).toBe('BR')
|
||||||
|
expect(regionOf(undefined)).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('lookup de moneda y regional por región', () => {
|
||||||
|
expect(currencyForRegion('PE')).toBe('PEN')
|
||||||
|
expect(currencyForRegion('MX')).toBe('MXN')
|
||||||
|
expect(currencyForRegion('ES')).toBe('EUR')
|
||||||
|
expect(currencyForRegion('US')).toBe('USD')
|
||||||
|
expect(currencyForRegion('419')).toBeUndefined()
|
||||||
|
expect(currencyForRegion('SE')).toBe('SEK')
|
||||||
|
expect(currencyForRegion(undefined)).toBeUndefined()
|
||||||
|
expect(localeForRegion('AR')).toBe('es-AR')
|
||||||
|
expect(localeForRegion('BR')).toBe('pt-BR')
|
||||||
|
expect(localeForRegion('419')).toBeUndefined()
|
||||||
|
expect(localeForRegion(undefined)).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('el runtime expone una zona horaria', () => {
|
||||||
|
// bun test corre en UTC; en el browser es la zona del sistema.
|
||||||
|
expect(browserTimezone()).toBeTruthy()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('formatPhoneDisplay — región del número y país del browser', () => {
|
||||||
|
beforeEach(() => stubLanguage('es-AR'))
|
||||||
|
afterEach(() => restoreNavigator())
|
||||||
|
|
||||||
|
test('números argentinos conservan el formato actual', () => {
|
||||||
|
expect(formatPhoneDisplay('+5492954667788', 'es-AR')).toBe('+54 9 2954 66-7788')
|
||||||
|
expect(formatPhoneDisplay('5490989009988', 'es-AR')).toBe('+54 9 989 00-9988')
|
||||||
|
expect(formatPhoneDisplay('0989009988', 'es-AR')).toBe('+54 989 00-9988')
|
||||||
|
expect(formatPhoneDisplay('2983649550', 'es-AR')).toBe('2983 64-9550')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('número irreconocible se devuelve tal cual', () => {
|
||||||
|
expect(formatPhoneDisplay('3209872223344', 'es-AR')).toBe('3209872223344')
|
||||||
|
expect(formatPhoneDisplay('12345', 'es-AR')).toBe('12345')
|
||||||
|
expect(formatPhoneDisplay(null)).toBeNull()
|
||||||
|
expect(formatPhoneDisplay('')).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('números de otra región usan las reglas de esa región', () => {
|
||||||
|
expect(formatPhoneDisplay('+12125551234', 'es-AR')).toBe('(212) 555-1234')
|
||||||
|
expect(formatPhoneDisplay('+34612345678', 'es-AR')).toBe('+34 612 34 56 78')
|
||||||
|
expect(formatPhoneDisplay('+525512345678', 'es-AR')).toBe('+52 55 1234 5678')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('nacional sin prefijo se agrupa según el país del browser', () => {
|
||||||
|
expect(formatPhoneDisplay('2125551234', 'en-US')).toBe('(212) 555-1234')
|
||||||
|
expect(formatPhoneDisplay('612345678', 'es-ES')).toBe('612 34 56 78')
|
||||||
|
expect(formatPhoneDisplay('5512345678', 'es-MX')).toBe('55 1234 5678')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('la zona horaria define el país de los números nacionales', () => {
|
||||||
|
withLocation('en-US', 'America/Argentina/Buenos_Aires', () => {
|
||||||
|
expect(formatPhoneDisplay('3364609550')).toBe('3364 60-9550')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('el prefijo del número manda sobre el país del browser', () => {
|
||||||
|
expect(formatPhoneDisplay('+5492954667788', 'en-US')).toBe('+54 9 2954 66-7788')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('región sin reglas propias cae a E.164', () => {
|
||||||
|
expect(formatPhoneDisplay('+331234567890', 'es-AR')).toBe('+331234567890')
|
||||||
|
expect(formatPhoneDisplay('00331234567890', 'es-AR')).toBe('+331234567890')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('por defecto usa el país del browser', () => {
|
||||||
|
stubLanguage('en-US')
|
||||||
|
expect(formatPhoneDisplay('2125551234')).toBe('(212) 555-1234')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -13,7 +13,7 @@
|
|||||||
"lint": "turbo lint",
|
"lint": "turbo lint",
|
||||||
"lint:fix": "turbo lint:fix",
|
"lint:fix": "turbo lint:fix",
|
||||||
"typecheck": "turbo typecheck",
|
"typecheck": "turbo typecheck",
|
||||||
"test": "bun --filter @gruperly/backend test",
|
"test": "bun --filter @gruperly/backend test && bun --filter @gruperly/web test",
|
||||||
"db:generate": "bun --filter @gruperly/backend db:generate",
|
"db:generate": "bun --filter @gruperly/backend db:generate",
|
||||||
"db:migrate": "bun --filter @gruperly/backend db:migrate",
|
"db:migrate": "bun --filter @gruperly/backend db:migrate",
|
||||||
"db:push": "bun --filter @gruperly/backend db:push",
|
"db:push": "bun --filter @gruperly/backend db:push",
|
||||||
|
|||||||
Reference in New Issue
Block a user