import type * as Customers from "@hazel/domain/customers" import type { DateTime } from "effect" import { toEpochMs } from "~/lib/utils" /** * Display formatting for the Customers area: money (integer minor units), counts, percents, deltas, * relative ages and dates. Pure: anything time-relative takes `now`, anything zoned takes `timeZone` * (default: the browser's), so views and tests agree. */ /** What the synced rows carry for an instant (`JsonDate`). */ export type Instant = Date | DateTime.Utc /** U+2212, so a negative number lines up with a positive one in tabular figures. */ const MINUS = "−" const DAY_MS = 86_400_000 /** Building an `Intl` formatter is slow (a 10k-row table formats every cell), so each is built once. */ const cached = (make: (options: O) => F) => { const formatters = new Map() return (options: O): F => { const key = JSON.stringify(options) const existing = formatters.get(key) if (existing !== undefined) return existing const formatter = make(options) formatters.set(key, formatter) return formatter } } const numberFormat = cached((options: Intl.NumberFormatOptions) => new Intl.NumberFormat("en-US", options)) const validCurrencies = new Map() /** Providers send the currency code as is; one `Intl` does not know is shown as a plain number + code. */ const isKnownCurrency = (currency: string): boolean => { const known = validCurrencies.get(currency) if (known !== undefined) return known let isKnown = true try { numberFormat({ style: "currency", currency }) } catch { isKnown = false } validCurrencies.set(currency, isKnown) return isKnown } const fractionDigitsOf = (currency: string): number => isKnownCurrency(currency) ? (numberFormat({ style: "currency", currency }).resolvedOptions().maximumFractionDigits ?? 2) : 2 /** Minor units → major units, using the currency's own exponent (JPY has none). */ export const toMajor = (minor: number, currency = "USD"): number => minor / 10 ** fractionDigitsOf(currency) /** `2150.00` (`2150` for JPY): the plain major amount, for an export. */ export const formatMajor = (minor: number, currency = "USD"): string => toMajor(minor, currency).toFixed(fractionDigitsOf(currency)) /** Major units → whole minor units: `toMajor`'s inverse, for amounts a user types. */ export const toMinor = (major: number, currency = "USD"): number => Math.round(major * 10 ** fractionDigitsOf(currency)) /** What labels an amount field: `$`, `¥`, `€`; the code itself for a currency `Intl` does not know. */ export const currencySymbol = (currency: string): string => isKnownCurrency(currency) ? (numberFormat({ style: "currency", currency }) .formatToParts(0) .find((part) => part.type === "currency")?.value ?? currency) : currency /** `value` is what the text shows, rounded: a negative that rounds to zero reads `$0`, not `−$0`. */ const withSign = (value: number, text: string, signed: boolean): string => value < 0 ? `${MINUS}${text}` : signed && value > 0 ? `+${text}` : text /** Rounds to `digits` decimals half away from zero, as the formatter does. */ const roundTo = (value: number, digits: number): number => (Math.sign(value) * Math.round(Math.abs(value) * 10 ** digits)) / 10 ** digits const currencyText = (major: number, currency: string, options: Intl.NumberFormatOptions): string => isKnownCurrency(currency) ? numberFormat({ style: "currency", currency, ...options }).format(major) : `${numberFormat(options).format(major)} ${currency}` /** `$48,210`; `cents` keeps the minor units (`$1,240.00`); `signed` adds `+` to a gain. */ export const formatMoney = ( minor: number, currency = "USD", options: Readonly<{ cents?: boolean; signed?: boolean }> = {}, ): string => { const digits = options.cents ? fractionDigitsOf(currency) : 0 const major = toMajor(minor, currency) const text = currencyText(Math.abs(major), currency, { minimumFractionDigits: digits, maximumFractionDigits: digits, }) return withSign(roundTo(major, digits), text, options.signed ?? false) } /** `$940`, `$48.2K`, `$1.2M`: KPI subtitles, axis ticks, tight cells. */ export const formatMoneyCompact = ( minor: number, currency = "USD", options: Readonly<{ signed?: boolean }> = {}, ): string => { const major = toMajor(minor, currency) const text = currencyText(Math.abs(major), currency, { notation: "compact", minimumFractionDigits: 0, maximumFractionDigits: 1, }) // Compact keeps one decimal at most, so anything under 0.05 shows as 0. return withSign(roundTo(major, 1), text, options.signed ?? false) } /** `1,611`. */ export const formatCount = (value: number): string => numberFormat({ maximumFractionDigits: 0 }).format(value) /** A metric's exact value, up to two decimals, then its unit: `8.27 GB`, `1,204.5`, `3 seats`. */ export const formatMetricValue = (value: number, unit: string | null): string => { const text = numberFormat({ maximumFractionDigits: 2 }).format(value) return unit === null ? text : `${text} ${unit}` } const BYTE_UNITS = ["B", "KB", "MB", "GB", "TB", "PB"] as const /** `38.6 GB`, `512 B` (decimal units, as Maple bills). */ export const formatBytes = (value: number): string => { let scaled = Math.abs(value) let unit = 0 while (scaled >= 1000 && unit < BYTE_UNITS.length - 1) { scaled /= 1000 unit++ } const digits = scaled < 10 && unit > 0 ? 1 : 0 return withSign( value, `${numberFormat({ maximumFractionDigits: digits }).format(scaled)} ${BYTE_UNITS[unit]}`, false, ) } /** `850 ms`, `1.4 s`, `3.2 min`. */ const formatDurationMs = (value: number): string => { const abs = Math.abs(value) const text = abs < 1000 ? `${numberFormat({ maximumFractionDigits: 0 }).format(abs)} ms` : abs < 60_000 ? `${numberFormat({ maximumFractionDigits: 1 }).format(abs / 1000)} s` : `${numberFormat({ maximumFractionDigits: 1 }).format(abs / 60_000)} min` return withSign(value, text, false) } /** * A metric's value as its `MetricFormat` reads (`docs/customers/overview-layouts.md`): compact * numbers with the unit, bytes, percent, money in minor units of `currency`, durations. */ export const formatMetric = ( value: number, metric: Readonly<{ format: Customers.MetricFormat; unit: string | null }>, currency = "USD", ): string => { switch (metric.format) { case "bytes": return formatBytes(value) case "percent": return formatPct(value) case "money": return formatMoney(Math.round(value), currency) case "duration_ms": return formatDurationMs(value) case "number": { const text = Math.abs(value) >= 10_000 ? formatCompact(value) : numberFormat({ maximumFractionDigits: 2 }).format(value) // A number in minor units is money, whatever its format says. if (metric.unit === "minor") return formatMoney(Math.round(value), currency) return metric.unit === null ? text : `${text} ${metric.unit}` } } } /** `461K`, `1.2M`, `980`. */ export const formatCompact = (value: number): string => withSign( value, numberFormat({ notation: "compact", maximumFractionDigits: 1 }).format(Math.abs(value)), false, ) /** One decimal under 10, none above: `6.2`, `42`, `0`. */ const percentNumber = (value: number, digits?: number): string => { const abs = Math.abs(value) const fraction = digits ?? (abs !== 0 && abs < 10 ? 1 : 0) return numberFormat({ minimumFractionDigits: 0, maximumFractionDigits: fraction }).format(abs) } /** A percent given as a percent number (`61` → `61%`, `2.8` → `2.8%`). */ export const formatPct = (value: number, options: Readonly<{ digits?: number }> = {}): string => withSign(value, `${percentNumber(value, options.digits)}%`, false) /** A change in percent: `+6.2%`, `−38%`, `0%`. */ export const formatDeltaPct = (value: number, options: Readonly<{ digits?: number }> = {}): string => withSign(value, `${percentNumber(value, options.digits)}%`, true) /** A change in percentage points (or score points): `+0.9 pt`, `−20 pts`. */ export const formatDeltaPoints = (value: number, unit: "pt" | "pts" = "pt"): string => withSign(value, `${percentNumber(value)} ${unit}`, true) /** Signed count: `+12`, `−3`. */ export const formatDeltaCount = (value: number): string => withSign(value, formatCount(Math.abs(value)), true) /** Whether a change reads as good, bad or neither, given which direction is good for the metric. */ export type DeltaTone = "positive" | "negative" | "neutral" export const deltaTone = (delta: number | null, goodWhen: "up" | "down" = "up"): DeltaTone => delta === null || delta === 0 ? "neutral" : delta > 0 === (goodWhen === "up") ? "positive" : "negative" /** Whole days between two instants, floored (`now - at`). */ export const daysBetween = (at: Instant, now: Instant): number => Math.floor((toEpochMs(now) - toEpochMs(at)) / DAY_MS) /** `just now`, `5m ago`, `2h ago`, `18d ago`, `3mo ago`, `2y ago`; a future instant reads `in 4d`. */ export const formatRelative = (at: Instant, now: Instant): string => { const deltaMs = toEpochMs(now) - toEpochMs(at) const future = deltaMs < 0 const minutes = Math.floor(Math.abs(deltaMs) / 60_000) const text = minutes < 1 ? null : minutes < 60 ? `${minutes}m` : minutes < 60 * 24 ? `${Math.floor(minutes / 60)}h` : minutes < 60 * 24 * 60 ? `${Math.floor(minutes / (60 * 24))}d` : minutes < 60 * 24 * 365 ? `${Math.floor(minutes / (60 * 24 * 30))}mo` : `${Math.floor(minutes / (60 * 24 * 365))}y` return text === null ? "just now" : future ? `in ${text}` : `${text} ago` } /** `1 day`, `4 days`. */ export const formatDays = (days: number): string => `${formatCount(days)} ${Math.abs(days) === 1 ? "day" : "days"}` /** `4 days left`, `1 day left`, `Ends today`, `Ended 2 days ago`. */ export const formatDaysLeft = (days: number): string => days > 0 ? `${formatDays(days)} left` : days === 0 ? "Ends today" : `Ended ${formatDays(-days)} ago` const dateTimeFormat = cached( (options: Intl.DateTimeFormatOptions) => new Intl.DateTimeFormat("en-US", options), ) const dateFormat = (options: Intl.DateTimeFormatOptions, timeZone: string | undefined) => dateTimeFormat({ ...options, timeZone }) const yearOf = (ms: number, timeZone: string | undefined) => Number(dateFormat({ year: "numeric" }, timeZone).format(ms)) /** `Nov 9`, or `Nov 9, 2025` outside `now`'s year. */ export const formatDate = ( at: Instant, options: Readonly<{ now?: Instant; timeZone?: string; withYear?: boolean }> = {}, ): string => { const ms = toEpochMs(at) const withYear = options.withYear ?? (options.now !== undefined && yearOf(ms, options.timeZone) !== yearOf(toEpochMs(options.now), options.timeZone)) return dateFormat( { month: "short", day: "numeric", year: withYear ? "numeric" : undefined }, options.timeZone, ).format(ms) } /** `Nov 9, 18:42`. */ export const formatDateTime = (at: Instant, options: Readonly<{ timeZone?: string }> = {}): string => dateFormat( { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }, options.timeZone, ).format(toEpochMs(at)) /** `Wed, 9:00 AM`: snooze targets. */ export const formatWeekdayTime = (at: Instant, options: Readonly<{ timeZone?: string }> = {}): string => dateFormat({ weekday: "short", hour: "numeric", minute: "2-digit" }, options.timeZone).format( toEpochMs(at), ) /** A UTC `Day` (`YYYY-MM-DD`) as epoch ms at its midnight. */ export const dayToMs = (day: string): number => Date.parse(`${day}T00:00:00Z`) /** Day labels are UTC: a `Day` names a UTC calendar day. */ const dayFormat = (options: Intl.DateTimeFormatOptions) => dateTimeFormat({ ...options, timeZone: "UTC" }) /** `Nov 2` (axis ticks). */ export const formatDay = (day: string): string => dayFormat({ month: "short", day: "numeric" }).format(dayToMs(day)) /** `Sun, Nov 2` (tooltip headings). */ export const formatDayLong = (day: string): string => dayFormat({ weekday: "short", month: "short", day: "numeric" }).format(dayToMs(day)) /** `Oct` (monthly axis ticks). */ export const formatMonthShort = (day: string): string => dayFormat({ month: "short" }).format(dayToMs(day)) /** `October 2026` (monthly tooltip headings). */ export const formatMonthLong = (day: string): string => dayFormat({ month: "long", year: "numeric" }).format(dayToMs(day)) /** `Week of Nov 2` (weekly tooltip headings). */ export const formatWeekOf = (day: string): string => `Week of ${formatDay(day)}` /** A chart bucket's heading and axis label. */ export const bucketLabels = ( bucket: "day" | "week" | "month", day: string, ): Readonly<{ tick: string; heading: string }> => bucket === "month" ? { tick: formatMonthShort(day), heading: formatMonthLong(day) } : bucket === "week" ? { tick: formatDay(day), heading: formatWeekOf(day) } : { tick: formatDay(day), heading: formatDayLong(day) }