Platform-v2 step 2.4 (APPS_PLATFORM D-11, D-12, §7.2, §8): - i18next 26.7.2 + react-i18next 17.1.13 (exact); en/el locale files (common, dev); createI18n, I18nProvider, useLanguage, setUserLanguage (screen first, then PATCH /api/auth/me through an app-provided save) - resolveLanguage: user -> device -> venue -> en - useFormat(): dates/times always in the venue zone from bootstrap (24 h, DST-safe, business dates never shifted), relative times, money and numbers per language; parseNumber accepts a comma or a dot - scripts/check-i18n.mjs guard: keys missing in en, placeholder mismatches, dates formatted without the venue zone in new code (fails); missing el (warns) - @xenia/ui components read their texts from UiLabelsProvider; useUiLabels() supplies the translated set - dev-only /i18n-sample in the manager; ui.mjs e2e checks it with the browser in New York; unit tests in run-all; lockfile keeps both apps' versions - new pack rule CS-17 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
136 lines
6.8 KiB
JavaScript
136 lines
6.8 KiB
JavaScript
// Formatting dates, times, money and numbers (APPS_PLATFORM §7.2). Every date/time is
|
|
// shown in the VENUE's time zone (from bootstrap), never the device's: a phone or PC set
|
|
// to another zone must still show the restaurant's clock. No React: unit-tested in Node.
|
|
//
|
|
// const f = createFormatters({ language: 'el', timeZone: 'Europe/Athens', currency: 'EUR' })
|
|
// f.formatTime('2026-07-01T10:00:00Z') → "13:00"
|
|
// f.formatMoney(1234.5) → "1.234,50 €" (en: "€1,234.50")
|
|
//
|
|
// The backend sends ISO-8601 UTC with "Z" (§7.1). A string without an offset is read as
|
|
// UTC too (that's what the backend stores); a plain "YYYY-MM-DD" (business dates) is a
|
|
// calendar date and is never shifted by a time zone.
|
|
import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE, intlLocale } from './locale.js'
|
|
|
|
const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/
|
|
const HAS_OFFSET = /(?:[zZ]|[+-]\d\d:?\d\d)$/
|
|
|
|
/** A Date from what the backend sends (ISO string, epoch ms, Date); null if unusable. */
|
|
export function toDate(value) {
|
|
if (value == null || value === '') return null
|
|
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value
|
|
if (typeof value === 'number') return new Date(value)
|
|
if (typeof value !== 'string') return null
|
|
if (DATE_ONLY.test(value)) return new Date(`${value}T00:00:00Z`)
|
|
const iso = HAS_OFFSET.test(value) ? value : `${value.replace(' ', 'T')}Z`
|
|
const d = new Date(iso)
|
|
return Number.isNaN(d.getTime()) ? null : d
|
|
}
|
|
|
|
// Named styles, so screens agree on what "a date" looks like. 24-hour clock everywhere.
|
|
export const DATE_STYLES = {
|
|
time: { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' },
|
|
timeSeconds: { hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23' },
|
|
date: { day: '2-digit', month: '2-digit', year: 'numeric' }, // 13/11/2026
|
|
dateShort: { day: '2-digit', month: '2-digit' }, // 13/11
|
|
dateLong: { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' },
|
|
dateMedium: { day: 'numeric', month: 'short', year: 'numeric' }, // 13 Nov 2026
|
|
weekday: { weekday: 'long' },
|
|
datetime: { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' },
|
|
datetimeShort: { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' },
|
|
}
|
|
|
|
/**
|
|
* The formatters for one language + venue. Cheap to call often: Intl objects are cached.
|
|
* @param {{ language?: string, timeZone?: string, currency?: string }} opts
|
|
*/
|
|
export function createFormatters({ language = 'en', timeZone = DEFAULT_TIMEZONE, currency = DEFAULT_CURRENCY } = {}) {
|
|
const locale = intlLocale(language)
|
|
const cache = new Map()
|
|
const intl = (kind, key, make) => {
|
|
const k = `${kind}|${key}`
|
|
if (!cache.has(k)) cache.set(k, make())
|
|
return cache.get(k)
|
|
}
|
|
const dtf = (style, zone) => intl('dt', `${style}|${zone}`, () => {
|
|
const options = typeof style === 'string' ? DATE_STYLES[style] : style
|
|
if (!options) throw new Error(`unknown date style "${style}"`)
|
|
return new Intl.DateTimeFormat(locale, { ...options, timeZone: zone })
|
|
})
|
|
|
|
/** Any style from DATE_STYLES (or an Intl options object), in venue time. '' for no value. */
|
|
function formatDateTime(value, style = 'datetime') {
|
|
if (typeof value === 'string' && DATE_ONLY.test(value)) return formatDate(value, style)
|
|
const d = toDate(value)
|
|
return d ? dtf(typeof style === 'string' ? style : JSON.stringify(style), timeZone).format(d) : ''
|
|
}
|
|
const formatTime = (value, style = 'time') => formatDateTime(value, style)
|
|
|
|
/** A calendar date. A "YYYY-MM-DD" string is shown as that day exactly; a timestamp as its venue-time day. */
|
|
function formatDate(value, style = 'date') {
|
|
if (typeof value === 'string' && DATE_ONLY.test(value)) {
|
|
const d = toDate(value)
|
|
return dtf(style, 'UTC').format(d)
|
|
}
|
|
const d = toDate(value)
|
|
return d ? dtf(style, timeZone).format(d) : ''
|
|
}
|
|
|
|
/** "5 minutes ago", "in 2 hours", "yesterday", "now"; beyond ~4 weeks, the date. */
|
|
function formatRelative(value, now = Date.now()) {
|
|
const d = toDate(value)
|
|
if (!d) return ''
|
|
const rtf = intl('rt', 'auto', () => new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }))
|
|
const sec = Math.round((d.getTime() - (now instanceof Date ? now.getTime() : now)) / 1000)
|
|
const abs = Math.abs(sec)
|
|
if (abs < 45) return rtf.format(0, 'second')
|
|
if (abs < 45 * 60) return rtf.format(Math.round(sec / 60), 'minute')
|
|
if (abs < 22 * 3600) return rtf.format(Math.round(sec / 3600), 'hour')
|
|
if (abs < 26 * 86400) return rtf.format(Math.round(sec / 86400), 'day')
|
|
return formatDate(d)
|
|
}
|
|
|
|
/** Money in the venue currency: "12,50 €" (el), "€12.50" (en). '' for null. */
|
|
function formatMoney(amount, { currency: cur = currency, signDisplay = 'auto', decimals = 2 } = {}) {
|
|
if (amount == null || amount === '' || !Number.isFinite(Number(amount))) return ''
|
|
const nf = intl('money', `${cur}|${signDisplay}|${decimals}`, () => new Intl.NumberFormat(locale, {
|
|
style: 'currency', currency: cur, signDisplay, minimumFractionDigits: decimals, maximumFractionDigits: decimals,
|
|
}))
|
|
return nf.format(Number(amount))
|
|
}
|
|
|
|
/** A number with the language's separators. decimals: exact digits; maxDecimals: up to. */
|
|
function formatNumber(value, { decimals, maxDecimals = 2 } = {}) {
|
|
if (value == null || value === '' || !Number.isFinite(Number(value))) return ''
|
|
const nf = intl('num', `${decimals}|${maxDecimals}`, () => new Intl.NumberFormat(locale, decimals != null
|
|
? { minimumFractionDigits: decimals, maximumFractionDigits: decimals }
|
|
: { maximumFractionDigits: maxDecimals }))
|
|
return nf.format(Number(value))
|
|
}
|
|
|
|
/** 0.235 → "23,5 %" (el) / "23.5%" (en). */
|
|
function formatPercent(ratio, { maxDecimals = 1 } = {}) {
|
|
if (ratio == null || !Number.isFinite(Number(ratio))) return ''
|
|
return intl('pct', String(maxDecimals), () => new Intl.NumberFormat(locale, { style: 'percent', maximumFractionDigits: maxDecimals })).format(Number(ratio))
|
|
}
|
|
|
|
/** Today's date in the venue, "YYYY-MM-DD" (for date pickers and "today" filters). */
|
|
function venueToday(now = new Date()) {
|
|
return venueDateKey(now)
|
|
}
|
|
|
|
/** The venue-time calendar day of a timestamp, "YYYY-MM-DD". */
|
|
function venueDateKey(value) {
|
|
const d = toDate(value)
|
|
if (!d) return ''
|
|
const parts = intl('key', timeZone, () => new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' })).formatToParts(d)
|
|
const get = t => parts.find(p => p.type === t).value
|
|
return `${get('year')}-${get('month')}-${get('day')}`
|
|
}
|
|
|
|
return {
|
|
language, locale, timeZone, currency,
|
|
formatDateTime, formatTime, formatDate, formatRelative,
|
|
formatMoney, formatNumber, formatPercent, venueToday, venueDateKey,
|
|
}
|
|
}
|