Explorar el Código

Write mileage and a report's day the same on the server and in the browser (#664)

* Write mileage and hours in the app's language, not the browser's number format

A number written with toLocaleString() and no locale is English on the server and whatever the browser is set to on the client. In a browser set to Dutch or French the customer page, the work order's warranty line and the vehicle page hydrated with other text than the server sent, and React drew the page again (error 418).

* Show a status report's day on the workshop's clock

The share page formatted the day in the browser, in the phone's zone and date style. The server had rendered it in UTC and English, so a customer elsewhere hydrated with other text (error 418) and could read another day than the workshop meant. The server now writes it in the workshop's zone and the page's language.
Bernt Christian Egeland hace 5 días
padre
commit
6a4708a03e

+ 111 - 0
src/__tests__/app/customers/vehicle-mileage-any-browser.test.tsx

@@ -0,0 +1,111 @@
+/**
+ * A vehicle's mileage on the customer's page reads the same in every browser.
+ * It was written with the browser's own number format, so a workshop in
+ * Belgium got "96.400" where the server had sent "96,400", and React threw
+ * the page away to draw it again (a hydration mismatch).
+ */
+import { render, screen } from '@testing-library/react'
+import { renderToString } from 'react-dom/server'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ push: vi.fn(), refresh: vi.fn(), replace: vi.fn() }),
+  useSearchParams: () => new URLSearchParams(),
+}))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
+vi.mock('@/features/customers/Actions/customerActions', () => ({
+  updateServiceRequest: vi.fn(),
+  createWorkOrderFromRequest: vi.fn(),
+}))
+vi.mock('@/features/settings/Actions/timezoneActions', () => ({ adoptDetectedTimezone: vi.fn() }))
+vi.mock('@/features/ai/Components/AskAiSheet', () => ({ AskAiSheet: () => null }))
+vi.mock('@/features/sms/Components/SmsConversation', () => ({ SmsConversation: () => null }))
+vi.mock('@/features/whatsapp/Components/WhatsappConversation', () => ({
+  WhatsappConversation: () => null,
+}))
+vi.mock('@/features/telegram/Components/TelegramConversation', () => ({
+  TelegramConversation: () => null,
+}))
+vi.mock('@/features/customers/Components/CustomerForm', () => ({ CustomerForm: () => null }))
+vi.mock('@/features/vehicles/Components/VehicleForm', () => ({ VehicleForm: () => null }))
+vi.mock('@/features/sms/Components/SendSmsDialog', () => ({ SendSmsDialog: () => null }))
+vi.mock('@/features/telegram/Components/TelegramQrCode', () => ({ TelegramQrCode: () => null }))
+vi.mock('@/features/portal/Components/ServiceRequestFiles', () => ({
+  ServiceRequestFiles: () => null,
+}))
+
+import { CustomerDetailClient } from '@/app/(authenticated)/customers/[id]/customer-detail-client'
+
+/**
+ * A browser set to Dutch as written in Belgium, in a zone far from the
+ * server's UTC. Whatever is formatted with no locale comes out its way.
+ */
+const realNumber = Number.prototype.toLocaleString
+const originalTz = process.env.TZ
+beforeAll(() => {
+  process.env.TZ = 'Pacific/Kiritimati'
+  vi.spyOn(Number.prototype, 'toLocaleString').mockImplementation(function (
+    this: number,
+    locales?: Intl.LocalesArgument,
+    options?: Intl.NumberFormatOptions
+  ) {
+    return realNumber.call(this, locales ?? 'nl-BE', options)
+  })
+})
+afterAll(() => {
+  process.env.TZ = originalTz
+  vi.restoreAllMocks()
+})
+
+const page = (
+  <CustomerDetailClient
+    customer={{
+      id: 'c1',
+      customerNumber: null,
+      name: 'Sarah Coleman',
+      email: null,
+      phone: null,
+      address: null,
+      company: null,
+      taxId: null,
+      taxExempt: false,
+      notes: null,
+      vehicles: [
+        {
+          id: 'v1',
+          make: 'Ford',
+          model: 'F-150',
+          year: 2019,
+          mileage: 96400,
+          licensePlate: 'TN-2291',
+          _count: { serviceRecords: 3 },
+        },
+      ],
+    }}
+  />
+)
+
+describe("a vehicle's mileage on the customer's page", () => {
+  it('is in the language of the app, not the way the browser writes numbers', () => {
+    render(page)
+    // The card for a phone and the table row for a desk.
+    expect(screen.getAllByText(/96,400\s+mi/).length).toBeGreaterThan(0)
+    expect(screen.queryByText(/96\.400/)).not.toBeInTheDocument()
+  })
+
+  it('is the text the server sent, so the page is not drawn twice', () => {
+    const mileage = (html: string) => html.match(/96\D?400/g)
+    const browser = mileage(renderToString(page))
+    vi.mocked(Number.prototype.toLocaleString).mockImplementation(function (
+      this: number,
+      locales?: Intl.LocalesArgument,
+      options?: Intl.NumberFormatOptions
+    ) {
+      // The server in Docker: English, UTC.
+      return realNumber.call(this, locales ?? 'en-US', options)
+    })
+    const server = mileage(renderToString(page))
+    expect(browser).toEqual(server)
+    expect(server).toEqual(['96,400', '96,400'])
+  })
+})

+ 1 - 0
src/__tests__/app/share/share-link-pages.test.tsx

@@ -15,6 +15,7 @@ vi.mock('server-only', () => ({}))
 vi.mock('next-intl/server', async () => {
   const { useTranslations } = await import('next-intl')
   return {
+    getLocale: async () => 'en',
     getTranslations: async (arg: string | { namespace: string }) =>
       useTranslations(typeof arg === 'string' ? arg : arg.namespace),
   }

+ 72 - 0
src/__tests__/features/status-reports/report-day.test.tsx

@@ -0,0 +1,72 @@
+/**
+ * The day on a status report's share page is the workshop's day, written by
+ * the server. The browser used to write it, in the phone's zone and the
+ * phone's date style, so a customer far from the server read another day
+ * than the server had rendered and React drew the page twice.
+ */
+import { render, screen } from '@testing-library/react'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/features/status-reports/Actions/submitFeedback', () => ({
+  submitStatusReportFeedback: vi.fn(),
+}))
+
+import { StatusReportView } from '@/app/(public)/share/status-report/[orgId]/[token]/status-report-view'
+import { formatReportDay } from '@/features/status-reports/Lib/reportDay'
+
+// 22:30 on 30 November in UTC: already 1 December in Sydney, still the
+// morning of 30 November in Honolulu.
+const MADE = new Date('2026-11-30T22:30:00Z')
+
+// The machine doing the formatting is fourteen hours ahead of UTC.
+const originalTz = process.env.TZ
+beforeAll(() => {
+  process.env.TZ = 'Pacific/Kiritimati'
+})
+afterAll(() => {
+  process.env.TZ = originalTz
+})
+
+describe('the day a status report was made', () => {
+  it("is the workshop's day, whatever clock the machine has", () => {
+    expect(formatReportDay(MADE, 'en', 'Australia/Sydney')).toBe('December 1, 2026')
+    expect(formatReportDay(MADE, 'en', 'Pacific/Honolulu')).toBe('November 30, 2026')
+  })
+
+  it("is written in the page's language", () => {
+    expect(formatReportDay(MADE, 'nl', 'Europe/Brussels')).toBe('30 november 2026')
+    expect(formatReportDay(MADE, 'fr', 'Europe/Brussels')).toBe('30 novembre 2026')
+  })
+
+  it('falls back to the day in UTC for a zone the runtime does not know', () => {
+    expect(formatReportDay(MADE, 'en', 'Mars/Olympus')).toBe('November 30, 2026')
+  })
+
+  it('is shown on the share page exactly as the server wrote it', () => {
+    render(
+      <StatusReportView
+        report={{
+          id: 'r1',
+          title: 'Brake pads',
+          message: null,
+          videoUrl: null,
+          videoFileName: null,
+          status: 'sent',
+          createdDay: formatReportDay(MADE, 'en', 'Australia/Sydney'),
+          customerFeedback: null,
+          feedbackAt: null,
+        }}
+        vehicle={null}
+        serviceTitle="Brake service"
+        subject="service"
+        technicianName={null}
+        workshopName="Riverside Auto"
+        workshopPhone=""
+        primaryColor="#3b82f6"
+        token="t"
+        showBranding={false}
+      />
+    )
+    expect(screen.getByText('December 1, 2026')).toBeInTheDocument()
+  })
+})

+ 55 - 0
src/__tests__/features/vehicles/warranty-distance-any-browser.test.tsx

@@ -0,0 +1,55 @@
+/**
+ * The distance limit in a work order's warranty line reads the same in every
+ * browser. Written with the browser's own number format it was "20.000 km"
+ * in Belgium where the server had sent "20,000 km", a hydration mismatch.
+ */
+import { fireEvent, render, screen } from '@testing-library/react'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/features/settings/Actions/timezoneActions', () => ({ adoptDetectedTimezone: vi.fn() }))
+
+import { WarrantySection } from '@/features/vehicles/Components/service-page/WarrantySection'
+
+// A browser set to Dutch as written in Belgium, far from the server's UTC.
+const realNumber = Number.prototype.toLocaleString
+const originalTz = process.env.TZ
+beforeAll(() => {
+  process.env.TZ = 'Pacific/Kiritimati'
+  vi.spyOn(Number.prototype, 'toLocaleString').mockImplementation(function (
+    this: number,
+    locales?: Intl.LocalesArgument,
+    options?: Intl.NumberFormatOptions
+  ) {
+    return realNumber.call(this, locales ?? 'nl-BE', options)
+  })
+})
+afterAll(() => {
+  process.env.TZ = originalTz
+  vi.restoreAllMocks()
+})
+
+describe('the warranty line on a work order', () => {
+  it('writes the distance limit in the language of the app', () => {
+    render(
+      <WarrantySection
+        value={{
+          warrantyStatus: 'included',
+          warrantyMonths: 12,
+          warrantyMileage: 20000,
+          warrantyNotes: null,
+        }}
+        onChange={vi.fn()}
+        texts={{
+          includedTerms: '',
+          notIncludedText: '',
+          defaultMonths: null,
+          defaultMileage: null,
+        }}
+        distanceUnit="km"
+      />
+    )
+    // Folded, the card says the warranty in one line.
+    fireEvent.click(screen.getByRole('button', { expanded: true }))
+    expect(screen.getByTestId('warranty-summary')).toHaveTextContent('20,000 km')
+  })
+})

+ 4 - 3
src/app/(authenticated)/(dashboard)/dashboard-client.tsx

@@ -5,7 +5,7 @@ import { useTableKeyboardNav } from '@/hooks/use-table-keyboard-nav'
 import { interactiveRow } from '@/lib/interactive-row'
 import { useState, useTransition } from 'react'
 import { useRouter } from 'next/navigation'
-import { useTranslations } from 'next-intl'
+import { useFormatter, useTranslations } from 'next-intl'
 import { useFormatDate } from '@/lib/use-format-date'
 import { AppCard } from '@/components/app-card'
 import type { InspectionsDueSummary } from '@/features/vehicles/Actions/inspectionStatusActions'
@@ -371,6 +371,7 @@ export function DashboardClient({
 }) {
   const formatCurrency = useFormatCurrency()
   const t = useTranslations('dashboard')
+  const format = useFormatter()
   const tcm = useTranslations('common.contextMenu')
   const serviceLabel = useServiceLabels()
   const tAudit = useTranslations('audit')
@@ -807,12 +808,12 @@ export function DashboardClient({
                               <p className="text-xs text-muted-foreground truncate">
                                 {v.licensePlate && `${v.licensePlate} · `}
                                 {t('maintenance.estimated', {
-                                  mileage: v.predictedMileage.toLocaleString(),
+                                  mileage: format.number(v.predictedMileage),
                                   unit: distUnit,
                                 })}
                                 {' · '}
                                 {t('maintenance.sinceLastService', {
-                                  mileage: v.mileageSinceLastService.toLocaleString(),
+                                  mileage: format.number(v.mileageSinceLastService),
                                   unit: distUnit,
                                 })}
                                 {' · '}

+ 4 - 3
src/app/(authenticated)/customers/[id]/customer-detail-client.tsx

@@ -9,7 +9,7 @@ import { interactiveRow } from '@/lib/interactive-row'
 import { useCallback, useMemo, useState, useTransition } from 'react'
 import Link from 'next/link'
 import { useRouter, useSearchParams } from 'next/navigation'
-import { useTranslations } from 'next-intl'
+import { useFormatter, useTranslations } from 'next-intl'
 import { Card, CardContent } from '@/components/ui/card'
 import { useFormatDate } from '@/lib/use-format-date'
 import { useFormatCurrency } from '@/components/currency-settings-context'
@@ -222,6 +222,7 @@ export function CustomerDetailClient({
   aiEnabled?: boolean
 }) {
   const t = useTranslations('customers.detail')
+  const format = useFormatter()
   const tVehicles = useTranslations('vehicles.list')
   const tForm = useTranslations('customers.form')
   const referenceEnabled = useCustomerReferenceEnabled()
@@ -639,7 +640,7 @@ export function CustomerDetailClient({
                       </div>
                       <div className="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
                         <span className="font-mono">
-                          {v.mileage.toLocaleString()} {readingUnit}
+                          {format.number(v.mileage)} {readingUnit}
                         </span>
                         <span>
                           {t('vehicleTable.services')}: {v._count.serviceRecords}
@@ -682,7 +683,7 @@ export function CustomerDetailClient({
                           </TableCell>
                           <TableCell className="font-medium">{vehicleName(v)}</TableCell>
                           <TableCell className="hidden sm:table-cell text-right font-mono text-sm">
-                            {v.mileage.toLocaleString()} {readingUnit}
+                            {format.number(v.mileage)} {readingUnit}
                           </TableCell>
                           <TableCell className="text-center">{v._count.serviceRecords}</TableCell>
                         </TableRow>

+ 4 - 3
src/app/(authenticated)/vehicles/[id]/_classic/service-records-table.tsx

@@ -41,7 +41,7 @@ import { getWarrantyStatus, type WarrantyStatus } from '@/lib/warranty'
 import { effectiveInvoiceDate } from '@/lib/invoice-utils'
 import { Download, ExternalLink, Gauge, Loader2, Paperclip, Plus, Search, User } from 'lucide-react'
 import { toast } from 'sonner'
-import { useTranslations } from 'next-intl'
+import { useFormatter, useTranslations } from 'next-intl'
 import { useServiceType } from '@/components/service-type-context'
 import { useServiceLabels } from '@/features/vehicles/Lib/useServiceLabels'
 
@@ -118,6 +118,7 @@ export function ServiceRecordsTable({
   const [navigatingId, setNavigatingId] = useState<string | null>(null)
   const [isExporting, setIsExporting] = useState(false)
   const t = useTranslations('vehicles.services')
+  const format = useFormatter()
   const serviceLabel = useServiceLabels()
   const tcm = useTranslations('common.contextMenu')
   const serviceType = useServiceType()
@@ -310,7 +311,7 @@ export function ServiceRecordsTable({
                   {record.mileage ? (
                     <span className="inline-flex items-center gap-1">
                       <Gauge className="h-3 w-3" />
-                      {record.mileage.toLocaleString()}
+                      {format.number(record.mileage)}
                     </span>
                   ) : null}
                   {record.techName && (
@@ -404,7 +405,7 @@ export function ServiceRecordsTable({
                           </StatusBadge>
                         </TableCell>
                         <TableCell className="text-right font-mono text-xs">
-                          {record.mileage ? record.mileage.toLocaleString() : '-'}
+                          {record.mileage ? format.number(record.mileage) : '-'}
                         </TableCell>
                         <TableCell className="hidden text-sm sm:table-cell">
                           {record.techName || '-'}

+ 5 - 6
src/app/(authenticated)/vehicles/[id]/_classic/vehicle-detail-classic.tsx

@@ -100,7 +100,7 @@ import {
   DropdownMenuSeparator,
   DropdownMenuTrigger,
 } from '@/components/ui/dropdown-menu'
-import { useTranslations } from 'next-intl'
+import { useFormatter, useTranslations } from 'next-intl'
 import { quoteStatusLabel } from '@/features/quotes/Lib/quoteStatus'
 import { useConfirm } from '@/components/confirm-dialog'
 import { useServiceType } from '@/components/service-type-context'
@@ -348,6 +348,7 @@ export function VehicleDetailClassic({
   const searchParams = useSearchParams()
   const { formatDate, formatDateTime } = useFormatDate()
   const t = useTranslations('vehicles.detail')
+  const format = useFormatter()
   const typeKeyEnabled = useTypeKeyEnabled()
   const ti = useTranslations('vehicles.inspections')
   const tr = useTranslations('vehicles.reminders')
@@ -836,9 +837,7 @@ export function VehicleDetailClassic({
         <div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm">
           <div className="flex items-center gap-1.5 text-muted-foreground">
             <Gauge className="h-3.5 w-3.5" />
-            <span className="font-semibold text-foreground">
-              {vehicle.mileage.toLocaleString()}
-            </span>
+            <span className="font-semibold text-foreground">{format.number(vehicle.mileage)}</span>
             <span className="text-xs">{distUnit}</span>
           </div>
           {predictionData && (
@@ -856,7 +855,7 @@ export function VehicleDetailClassic({
                             : t('predictedMileage')}
                       </span>
                       <span className="font-semibold text-foreground">
-                        ~{predictionData.predictedMileage.toLocaleString()}
+                        ~{format.number(predictionData.predictedMileage)}
                       </span>
                       <span className="text-[10px] text-muted-foreground/70">
                         ({predictionData.confidencePercent}%)
@@ -1765,7 +1764,7 @@ export function VehicleDetailClassic({
                                   : formatDate(new Date(r.dueDate)),
                               })}
                             {r.dueMileage &&
-                              `${r.dueDate ? ' · ' : ''}${tr('dueAt', { mileage: r.dueMileage.toLocaleString(), unit: distUnit })}`}
+                              `${r.dueDate ? ' · ' : ''}${tr('dueAt', { mileage: format.number(r.dueMileage), unit: distUnit })}`}
                           </p>
                           {r.description && (
                             <p className="mt-1 text-xs text-muted-foreground">{r.description}</p>

+ 1 - 1
src/app/(public)/share/inspection/[orgId]/[token]/inspection-view.tsx

@@ -365,7 +365,7 @@ export function InspectionView({
                     <dt className="text-xs text-gray-500">
                       {serviceType === 'marine' ? t('engineHoursLabel') : t('odometerLabel')}
                     </dt>
-                    <dd className="text-sm">{inspection.mileage.toLocaleString()}</dd>
+                    <dd className="text-sm">{inspection.mileage.toLocaleString(locale)}</dd>
                   </div>
                 )}
                 {inspection.vehicle.customer && (

+ 7 - 3
src/app/(public)/share/status-report/[orgId]/[token]/page.tsx

@@ -1,4 +1,4 @@
-import { getTranslations } from 'next-intl/server'
+import { getLocale, getTranslations } from 'next-intl/server'
 import { cache } from 'react'
 import { closedShareLinkTitle, ShareLinkClosed } from '@/components/share-link-expired'
 import { ShareLinkOpenUntil } from '@/components/share-link-open-until'
@@ -8,6 +8,8 @@ import { notFound } from 'next/navigation'
 import { StatusReportView } from './status-report-view'
 import { resolvePortalOrg } from '@/lib/portal-slug'
 import { getFeatures } from '@/lib/features'
+import { formatReportDay } from '@/features/status-reports/Lib/reportDay'
+import { workshopTimeZone } from '@/lib/workshop-timezone'
 import type { Metadata } from 'next'
 
 function toPublicFileUrl(fileUrl: string, token: string): string {
@@ -106,7 +108,7 @@ export default async function PublicStatusReportPage({
   }
 
   // Fetch workshop settings
-  const [settings, features] = await Promise.all([
+  const [settings, features, locale, timeZone] = await Promise.all([
     db.appSetting.findMany({
       where: {
         organizationId: orgId,
@@ -123,6 +125,8 @@ export default async function PublicStatusReportPage({
       },
     }),
     getFeatures(orgId),
+    getLocale(),
+    workshopTimeZone(orgId),
   ])
 
   const settingsMap: Record<string, string> = {}
@@ -140,7 +144,7 @@ export default async function PublicStatusReportPage({
         videoUrl,
         videoFileName: report.videoFileName,
         status: report.status,
-        createdAt: report.createdAt.toISOString(),
+        createdDay: formatReportDay(report.createdAt, locale, timeZone),
         customerFeedback: report.customerFeedback,
         feedbackAt: report.feedbackAt?.toISOString() || null,
       }}

+ 3 - 7
src/app/(public)/share/status-report/[orgId]/[token]/status-report-view.tsx

@@ -17,7 +17,8 @@ interface StatusReportViewProps {
     videoUrl: string | null
     videoFileName: string | null
     status: string
-    createdAt: string
+    /** The day it was made, already written on the workshop's clock by the server. */
+    createdDay: string
     customerFeedback: string | null
     feedbackAt: string | null
   }
@@ -53,11 +54,6 @@ export function StatusReportView({
   const [submitting, setSubmitting] = useState(false)
   const [submitted, setSubmitted] = useState(!!report.customerFeedback)
 
-  const createdDate = new Date(report.createdAt).toLocaleDateString(undefined, {
-    year: 'numeric',
-    month: 'long',
-    day: 'numeric',
-  })
   const vehicleLabel = vehicle ? `${vehicleName(vehicle)}` : null
 
   async function handleSubmitFeedback() {
@@ -153,7 +149,7 @@ export function StatusReportView({
             </span>
           )}
           <span className="flex items-center gap-1.5">
-            <Calendar className="h-4 w-4" /> {createdDate}
+            <Calendar className="h-4 w-4" /> {report.createdDay}
           </span>
         </div>
 

+ 17 - 0
src/features/status-reports/Lib/reportDay.ts

@@ -0,0 +1,17 @@
+/**
+ * The day a status report was made, as the customer reads it on the share
+ * page: on the workshop's clock and in the page's language.
+ *
+ * Written on the server and sent down as text. Formatted in the browser it
+ * was the phone's own day and the phone's own way of writing one, which is
+ * neither, and differs from what the server had already rendered.
+ */
+export function formatReportDay(createdAt: Date, locale: string, timeZone: string): string {
+  const options: Intl.DateTimeFormatOptions = { year: 'numeric', month: 'long', day: 'numeric' }
+  try {
+    return new Intl.DateTimeFormat(locale, { ...options, timeZone }).format(createdAt)
+  } catch {
+    // A zone this runtime does not know: the day in UTC rather than no day.
+    return new Intl.DateTimeFormat(locale, { ...options, timeZone: 'UTC' }).format(createdAt)
+  }
+}

+ 3 - 2
src/features/vehicles/Components/RemindersPageClient.tsx

@@ -2,7 +2,7 @@
 
 import { useState } from 'react'
 import { useRouter } from 'next/navigation'
-import { useTranslations } from 'next-intl'
+import { useFormatter, useTranslations } from 'next-intl'
 import { useFormatDate } from '@/lib/use-format-date'
 import { Card, CardContent } from '@/components/ui/card'
 import { Badge } from '@/components/ui/badge'
@@ -84,6 +84,7 @@ function getUrgency(r: Reminder): 'overdue' | 'due-soon' | 'normal' {
 
 export function RemindersPageClient({ reminders, unitSystem }: RemindersPageClientProps) {
   const t = useTranslations('reminders')
+  const format = useFormatter()
   const tv = useTranslations('vehicles.reminders')
   const tc = useTranslations('common.buttons')
   const tcm = useTranslations('common.contextMenu')
@@ -250,7 +251,7 @@ export function RemindersPageClient({ reminders, unitSystem }: RemindersPageClie
                           )}
                           {r.dueMileage && (
                             <span>
-                              {r.dueMileage.toLocaleString()} {distUnit}
+                              {format.number(r.dueMileage)} {distUnit}
                             </span>
                           )}
                         </div>

+ 3 - 2
src/features/vehicles/Components/VehicleSafetyPanel.tsx

@@ -2,7 +2,7 @@
 
 import { useCallback, useEffect, useMemo, useState } from 'react'
 import { useRouter } from 'next/navigation'
-import { useTranslations } from 'next-intl'
+import { useFormatter, useTranslations } from 'next-intl'
 import { toast } from 'sonner'
 import {
   AlertOctagon,
@@ -480,6 +480,7 @@ function Stat({
   tone: 'good' | 'warn' | 'danger' | 'neutral'
   hint?: string
 }) {
+  const format = useFormatter()
   const color =
     tone === 'danger'
       ? 'text-red-600'
@@ -494,7 +495,7 @@ function Stat({
         {label}
       </p>
       <p className={cn('mt-0.5 text-2xl font-semibold tabular-nums leading-tight', color)}>
-        {value.toLocaleString()}
+        {format.number(value)}
       </p>
       {hint && <p className="mt-0.5 truncate text-xs text-muted-foreground">{hint}</p>}
     </div>

+ 11 - 5
src/features/vehicles/Components/service-edit/ScheduleTimesSection.tsx

@@ -5,7 +5,7 @@ import { useState, useEffect, useCallback, useRef } from 'react'
 import { useModernWorkOrder } from '@/components/work-order-layout-context'
 import { useRouter } from 'next/navigation'
 import { AddPersonDialog } from '@/features/team/Components/AddPersonDialog'
-import { useTranslations } from 'next-intl'
+import { useFormatter, useTranslations } from 'next-intl'
 import { Label } from '@/components/ui/label'
 import { Button } from '@/components/ui/button'
 import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
@@ -83,8 +83,8 @@ function initialsOf(name: string): string {
 }
 
 /** Minutes as hours with at most one decimal: 330 is 5.5, 480 is 8. */
-function hoursOf(minutes: number): string {
-  return (Math.round(minutes / 6) / 10).toLocaleString()
+function hoursOf(minutes: number): number {
+  return Math.round(minutes / 6) / 10
 }
 
 interface WorkBay {
@@ -128,6 +128,7 @@ export function ScheduleTimesSection({
   onSaved,
 }: ScheduleTimesSectionProps) {
   const t = useTranslations('service.schedule')
+  const format = useFormatter()
   const tCal = useTranslations('workshopCalendar')
   const router = useRouter()
   const modern = useModernWorkOrder()
@@ -756,14 +757,19 @@ export function ScheduleTimesSection({
                             {tech.skills ||
                               (full
                                 ? t('loadFull')
-                                : t('loadFree', { hours: hoursOf(capacity - booked) }))}
+                                : t('loadFree', {
+                                    hours: format.number(hoursOf(capacity - booked)),
+                                  }))}
                           </span>
                         )}
                       </span>
                     </span>
                     <span className="flex flex-col gap-1">
                       <span className="text-right text-xs tabular-nums text-muted-foreground">
-                        {t('loadOf', { booked: hoursOf(booked), capacity: hoursOf(capacity) })}
+                        {t('loadOf', {
+                          booked: format.number(hoursOf(booked)),
+                          capacity: format.number(hoursOf(capacity)),
+                        })}
                       </span>
                       <span className="block h-1.5 overflow-hidden rounded-full bg-muted">
                         <span

+ 3 - 2
src/features/vehicles/Components/service-page/WarrantySection.tsx

@@ -1,7 +1,7 @@
 'use client'
 
 import { useMemo, useState } from 'react'
-import { useTranslations } from 'next-intl'
+import { useFormatter, useTranslations } from 'next-intl'
 import { ChevronDown, ChevronRight, Shield } from 'lucide-react'
 import { Input } from '@/components/ui/input'
 import { Label } from '@/components/ui/label'
@@ -50,6 +50,7 @@ export function WarrantySection({
   serviceDate,
 }: WarrantySectionProps) {
   const t = useTranslations('service.warranty')
+  const format = useFormatter()
   const { formatDate } = useFormatDate()
   const modern = useModernWorkOrder()
 
@@ -75,7 +76,7 @@ export function WarrantySection({
         ? [
             value.warrantyMonths ? t('summaryMonths', { count: value.warrantyMonths }) : null,
             value.warrantyMileage
-              ? `${value.warrantyMileage.toLocaleString()} ${distanceUnit}`
+              ? `${format.number(value.warrantyMileage)} ${distanceUnit}`
               : null,
           ]
             .filter(Boolean)