Files
petvity/lib/utils/format.ts
T
GandClaude Opus 5 3d6ac9bed3 fix: prices were 100x wrong for zero-decimal currencies (#58)
Two real defects in the repo I can actually reach, found by auditing my own
work rather than someone else's.

formatPrice divided by 100 unconditionally. That assumes every currency has two
decimals, and several have none: with NEXT_PUBLIC_APP_CURRENCY=JPY a 2999-unit
product rendered as ¥30 instead of ¥2,999 — a hundredfold error, silently, on
every price in the shop. KRW, VND and ISK behave the same way, and KWD errs in
the other direction with three decimals. APP_CURRENCY is an environment
variable, so this was one deployment away from being real.

It now delegates to commercekit's money module, which takes the exponent from
the currency. That also removes a second money formatter from a repo that had
just adopted the first — exactly the duplication this whole exercise is about,
introduced by me.

TEMPLATE_MAP typed its payload as `any`, so the cron dispatching welcome emails
could hand a template the wrong shape and the compiler would agree — on mail
that goes to real users, built from a jsonb column nothing else validates. All
four templates take the same WelcomePayload, so the `any` bought nothing.

Typing it immediately produced an error, which turned out to be a typing gap
rather than a live bug: the cron spread `item.payload as object`, erasing the
shape, while enqueueWelcomeSequence does write { name, email }. So the emails
were correct and the types were lying about why. The cast now narrows to
WelcomePayload and the compiler can see it.

Verification: lint, tsc, css-vars, 901 tests / 87 files (8 new, including the
JPY case that would have caught the price bug).

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 16:07:54 +00:00

136 lines
5.3 KiB
TypeScript

import { APP_CURRENCY } from "@/lib/config/app";
import { money, format } from "@/packages/commercekit/src/money";
/**
* Format a YYYY-MM-DD date string for display.
* Defaults to "en", never the runtime's own locale — the server box (de_CH)
* and the visitor's browser disagree, causing hydration mismatches.
* e.g. "2026-01-15" → "Jan 15, 2026" (en) / "2026年1月15日" (ja)
*/
export function formatDateShort(date: string, locale?: string): string {
const d = date.includes("T") ? new Date(date) : new Date(date + "T00:00:00");
return d.toLocaleDateString(locale ?? "en", { year: "numeric", month: "short", day: "numeric" });
}
/**
* Format grams as a human-readable weight string.
* e.g. 3500 → "3.5 kg"; 500 → "500 g"
*/
export function formatWeight(grams: number): string {
if (grams >= 1000) return `${(grams / 1000).toFixed(1)} kg`;
return `${grams} g`;
}
/**
* Format centidegrees as a temperature string.
* e.g. 3850 → "38.5°C"
*/
export function formatTemperature(centidegrees: number): string {
return `${(centidegrees / 100).toFixed(1)}°C`;
}
type AgeT = (key: string, values?: Record<string, number>) => string;
/**
* Format a pet's age compactly, locale-aware.
* Requires translation keys: petAgeShortLess1Month, petAgeShortMonths, petAgeShortYears
* e.g. en: "3mo" / "1yr" · de: "3Mo" / "1J"
*/
export function formatPetAgeShort(birthDate: string | null, t: AgeT): string {
if (!birthDate) return "";
const months = Math.floor(
(Date.now() - new Date(birthDate).getTime()) / (1000 * 60 * 60 * 24 * 30.4),
);
if (months < 1) return t("petAgeShortLess1Month");
if (months < 12) return t("petAgeShortMonths", { n: months });
return t("petAgeShortYears", { n: Math.floor(months / 12) });
}
/**
* Format a pet's age verbosely, locale-aware.
* Requires translation keys: petAgeLess1Month, petAgeMonths, petAgeYears, petAgeYearsMonths
* e.g. en: "3 months old" / "1 year old" · de: "3 Monate alt" / "1 Jahr alt"
*/
export function formatPetAge(birthDate: string | null, t: AgeT): string {
if (!birthDate) return "";
const months = Math.floor(
(Date.now() - new Date(birthDate).getTime()) / (1000 * 60 * 60 * 24 * 30.4),
);
if (months < 1) return t("petAgeLess1Month");
if (months < 12) return t("petAgeMonths", { n: months });
const years = Math.floor(months / 12);
const rem = months % 12;
return rem > 0 ? t("petAgeYearsMonths", { years, months: rem }) : t("petAgeYears", { n: years });
}
/**
* Format an integer minor-unit amount as a locale-aware price string.
* Currency determined by APP_CURRENCY (NEXT_PUBLIC_APP_CURRENCY env, default "USD").
* e.g. 2999, "en" → "$29.99" · 2999, "de" → "29,99 $" · 2999 JPY → "¥2,999"
*
* Delegates to commercekit rather than dividing by 100, because dividing by 100
* assumes every currency has two decimals. It does not: JPY, KRW, VND and ISK
* have none, so `NEXT_PUBLIC_APP_CURRENCY=JPY` rendered a ¥2,999 product as
* ¥30 — a hundredfold price error, silently. KWD has three and errs the other
* way. The exponent belongs to the currency, which is what `money()` knows.
*/
export function formatPrice(cents: number, locale?: string): string {
// Default to "en", never the runtime's own locale: the server box and the
// visitor's browser disagree, which would hydrate "8,90 $" into "$8.90".
return format(money(cents, APP_CURRENCY), locale ?? "en");
}
/**
* Format an adoption fee. Returns "Free" for null/0, whole units otherwise.
* Currency determined by APP_CURRENCY (NEXT_PUBLIC_APP_CURRENCY env, default "USD").
* e.g. null → "Free"; 2500, "en" → "$25"
*/
export function formatAdoptionFee(feeCents: number | null, locale?: string): string {
if (feeCents === null || feeCents === 0) return "Free";
// A fee is shown without minor units — it is a headline number, not an invoice.
return format(money(feeCents, APP_CURRENCY), locale ?? "en", {
maximumFractionDigits: 0,
});
}
/**
* Format an ISO datetime string for compact display.
* e.g. "2026-01-15T10:30:00Z" → "Jan 15, 2026"
*/
export function formatIsoDate(iso: string, locale?: string): string {
return new Date(iso).toLocaleDateString(locale ?? "en", {
year: "numeric",
month: "short",
day: "numeric",
});
}
/**
* Format an ISO datetime string with time for compact display.
* e.g. "2026-01-15T10:30:00Z" → "Jan 15, 10:30 AM"
*/
export function formatIsoDateTime(iso: string, locale?: string): string {
return new Date(iso).toLocaleString(locale ?? "en", {
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
});
}
/**
* Format a date relative to now using the browser/runtime locale.
* e.g. locale="de": "heute", "morgen", "in 7 Tagen", "vor 30 Tagen"
* locale="en": "today", "tomorrow", "in 7 days", "30 days ago"
*/
export function formatRelativeDate(date: string, locale?: string, now = new Date()): string {
// Use UTC midnight on both sides so the comparison is timezone-agnostic.
const target = new Date(date + "T00:00:00Z");
const nowUtcMidnight = new Date(
Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()),
);
const diffMs = target.getTime() - nowUtcMidnight.getTime();
const diffDays = Math.round(diffMs / (1000 * 60 * 60 * 24));
return new Intl.RelativeTimeFormat(locale ?? "en", { numeric: "auto" }).format(diffDays, "day");
}