Просмотр исходного кода

Store licence plates in upper case (#628)

* Store licence plates in upper case

A plate typed in lower case was only upper-cased by CSS in the plate box, so lists, work order titles and the invoice PDF showed it as typed. Every write path now stores one form through a shared normaliser, and existing plates are brought to the same form.

* Expect a restored plate in its stored form in the backup round trip

* Clear empty plates in the existing-data update
Bernt Christian Egeland 9 часов назад
Родитель
Сommit
c52242f6a9

+ 32 - 0
prisma/migrations/20261118164631_uppercase_license_plates/migration.sql

@@ -0,0 +1,32 @@
+-- Licence plates (and boat registrations) are stored in one form from now on:
+-- trimmed, single spaces, upper case. Bring the existing rows to it.
+-- ASCII letters are mapped by hand so the result does not depend on the
+-- database locale (a Turkish locale would turn "i" into a dotted capital);
+-- upper() then handles the remaining letters where the locale knows them.
+-- Spaces and hyphens stay; a plate that is empty or only spaces becomes no
+-- plate, as a save stores it. Issued documents and saved job titles are frozen
+-- copies and are not touched.
+BEGIN;
+
+UPDATE "vehicles" AS v
+SET "licensePlate" = n.plate
+FROM (
+  SELECT
+    "id",
+    NULLIF(
+      upper(
+        translate(
+          btrim(regexp_replace("licensePlate", '\s+', ' ', 'g')),
+          'abcdefghijklmnopqrstuvwxyz',
+          'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+        )
+      ),
+      ''
+    ) AS plate
+  FROM "vehicles"
+  WHERE "licensePlate" IS NOT NULL
+) AS n
+WHERE v."id" = n."id"
+  AND n.plate IS DISTINCT FROM v."licensePlate";
+
+COMMIT;

+ 3 - 0
src/__tests__/db/backup-round-trip.db.test.ts

@@ -470,6 +470,8 @@ function compare(before: Dump, after: Dump): Difference[] {
  */
 const OWNED_BY_WHOEVER_RESTORES =
   'The row is owned by whoever restores the backup: the column is required, and the account the file names may not exist here.'
+const PLATE_AS_STORED =
+  'A plate is stored in upper case with single spaces (normalizePlate), as the editor stores it, so a backup from before that rule restores in the same form.'
 const EXPECTED: Readonly<Record<string, string>> = {
   'AppSetting.userId': OWNED_BY_WHOEVER_RESTORES,
   'CustomFieldDefinition.userId': OWNED_BY_WHOEVER_RESTORES,
@@ -482,6 +484,7 @@ const EXPECTED: Readonly<Record<string, string>> = {
   'StockMovement.userId': OWNED_BY_WHOEVER_RESTORES,
   'TireSet.userId': OWNED_BY_WHOEVER_RESTORES,
   'TireWarehouse.userId': OWNED_BY_WHOEVER_RESTORES,
+  'Vehicle.licensePlate': PLATE_AS_STORED,
   'Vehicle.userId': OWNED_BY_WHOEVER_RESTORES,
 }
 

+ 84 - 0
src/__tests__/features/vehicles/vehicle-plate-uppercase.test.ts

@@ -0,0 +1,84 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }))
+vi.mock('@/lib/with-auth', () => ({
+  withAuth: async (fn: (ctx: { userId: string; organizationId: string }) => Promise<unknown>) => ({
+    success: true,
+    data: await fn({ userId: 'user-1', organizationId: 'org-1' }),
+  }),
+}))
+vi.mock('@/lib/workshop-timezone', () => ({
+  workshopTimeZone: vi.fn(async () => 'Pacific/Auckland'),
+}))
+vi.mock('@/lib/owned-records', () => ({ assertOwnedCustomer: vi.fn(async () => undefined) }))
+vi.mock('@/features/integrations/Lib/inspection-sync', () => ({
+  INSPECTION_CAPABILITY: 'inspection',
+  recordRegistryAnswer: vi.fn(),
+}))
+vi.mock('@/integrations/registry', () => ({ getManifest: vi.fn(() => null) }))
+vi.mock('@/lib/files/manager', () => ({ releaseFiles: vi.fn() }))
+vi.mock('@/lib/files/collect', () => ({ vehicleFileUrls: vi.fn(async () => []) }))
+vi.mock('@/lib/db', () => ({
+  db: {
+    vehicle: {
+      create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => ({
+        id: 'veh-1',
+        ...data,
+      })),
+      findFirst: vi.fn(),
+      updateMany: vi.fn(async () => ({ count: 1 })),
+    },
+    vehicleInspectionStatus: { updateMany: vi.fn(), upsert: vi.fn() },
+  },
+}))
+
+import { db } from '@/lib/db'
+import { createVehicle, updateVehicle } from '@/features/vehicles/Actions/vehicleActions'
+
+const created = () => vi.mocked(db.vehicle.create).mock.calls[0][0].data
+const updated = () => vi.mocked(db.vehicle.updateMany).mock.calls[0][0].data
+
+beforeEach(() => {
+  vi.clearAllMocks()
+  vi.mocked(db.vehicle.findFirst).mockResolvedValue({
+    year: 2020,
+    make: 'Testmobile',
+    model: 'Fiction',
+    licensePlate: 'OLD 1',
+    vin: null,
+    imageUrl: null,
+  } as never)
+})
+
+describe('saving a vehicle', () => {
+  it('stores a plate typed in lower case in upper case', async () => {
+    const result = await createVehicle({
+      make: 'Testmobile',
+      model: 'Fiction',
+      year: 2020,
+      licensePlate: ' zz99  tst ',
+    })
+    expect(result.success).toBe(true)
+    expect(created().licensePlate).toBe('ZZ99 TST')
+  })
+
+  it('stores no plate for a vehicle saved without one', async () => {
+    await createVehicle({ make: 'Testmobile', model: 'Fiction', year: 2020, licensePlate: '' })
+    expect(created().licensePlate).toBeNull()
+  })
+
+  it('stores an edited plate in upper case', async () => {
+    await updateVehicle({ id: 'veh-1', licensePlate: 'ab-123 cd' })
+    expect(updated().licensePlate).toBe('AB-123 CD')
+  })
+
+  it('clears the plate when the field is emptied', async () => {
+    await updateVehicle({ id: 'veh-1', licensePlate: '' })
+    expect(updated().licensePlate).toBeNull()
+  })
+
+  it('leaves the plate alone on an edit that does not send it', async () => {
+    await updateVehicle({ id: 'veh-1', color: 'Red' })
+    expect(updated().licensePlate).toBeUndefined()
+  })
+})

+ 53 - 0
src/__tests__/lib/license-plate.test.ts

@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest'
+import { normalizePlate } from '@/lib/license-plate'
+import { normalizePlate as importerNormalizePlate } from '@/features/import/Lib/normalize'
+
+describe('normalizePlate', () => {
+  it('stores a plate typed in lower or mixed case in upper case', () => {
+    expect(normalizePlate('zz99 tst')).toBe('ZZ99 TST')
+    expect(normalizePlate('Ab12 cDe')).toBe('AB12 CDE')
+    expect(normalizePlate('AB12 CDE')).toBe('AB12 CDE')
+  })
+
+  it('keeps the spaces and hyphens people typed', () => {
+    expect(normalizePlate('ab-123-cd')).toBe('AB-123-CD')
+    expect(normalizePlate('m ab 1234')).toBe('M AB 1234')
+    expect(normalizePlate('ab12345')).toBe('AB12345')
+  })
+
+  it('trims and collapses runs of whitespace to one space', () => {
+    expect(normalizePlate('  zz99   tst ')).toBe('ZZ99 TST')
+    expect(normalizePlate('zz99\t\ttst')).toBe('ZZ99 TST')
+  })
+
+  it('treats an empty plate as no plate', () => {
+    expect(normalizePlate('')).toBeNull()
+    expect(normalizePlate('   ')).toBeNull()
+    expect(normalizePlate(null)).toBeNull()
+    expect(normalizePlate(undefined)).toBeNull()
+  })
+
+  it('upper-cases letters outside the Latin alphabet that have case', () => {
+    expect(normalizePlate('а123вс')).toBe('А123ВС')
+    expect(normalizePlate('αβγ-1234')).toBe('ΑΒΓ-1234')
+    expect(normalizePlate('hü-ö 12')).toBe('HÜ-Ö 12')
+  })
+
+  it('passes scripts without case through unchanged', () => {
+    expect(normalizePlate('أ ب ج 1234')).toBe('أ ب ج 1234')
+    expect(normalizePlate('京A·12345')).toBe('京A·12345')
+    expect(normalizePlate('กข 1234')).toBe('กข 1234')
+    expect(normalizePlate('品川 300 あ 12-34')).toBe('品川 300 あ 12-34')
+  })
+
+  it('gives a plain I for i whatever the locale, and never changes the length', () => {
+    expect(normalizePlate('34 ist 34')).toBe('34 IST 34')
+    // Dotless i has a single-letter capital; sharp s does not, so it stays.
+    expect(normalizePlate('ı')).toBe('I')
+    expect(normalizePlate('ß1')).toBe('ß1')
+  })
+
+  it('is the rule the importer uses', () => {
+    expect(importerNormalizePlate).toBe(normalizePlate)
+  })
+})

+ 2 - 1
src/app/api/protected/backup/import-lubelog/route.ts

@@ -22,6 +22,7 @@ import { resolveWithinDir } from '@/lib/safe-path'
 import { uploadsRoot } from '@/lib/upload-root'
 import { prepareImportedFile, writeImportedFile } from '@/lib/backup/import-photo'
 import { releaseFiles } from '@/lib/files/manager'
+import { normalizePlate } from '@/lib/license-plate'
 
 // Allow up to 5 minutes for large imports
 export const maxDuration = 300
@@ -357,7 +358,7 @@ export async function POST(request: NextRequest) {
               make: v.Make,
               model: v.Model,
               year: v.Year,
-              licensePlate: v.LicensePlate || null,
+              licensePlate: normalizePlate(v.LicensePlate),
               fuelType: determineFuelType(v),
               mileage: vehicleMileage.get(v._id) || 0,
               purchasePrice: parseDecimal(v.PurchasePrice) || null,

+ 1 - 1
src/features/ai/tools/workshop-tools.ts

@@ -670,7 +670,7 @@ export async function executeTool(
 export const DB_SCHEMA = `
 PostgreSQL database schema (use these exact table/column names in queries):
 
-vehicles (id, make, model, year, vin, "licensePlate", color, mileage, "fuelType", transmission, "engineSize", "purchaseDate", "purchasePrice", "isArchived", "createdAt", "updatedAt", "customerId")
+vehicles (id, make, model, year, vin, "licensePlate", color, mileage, "fuelType", transmission, "engineSize", "purchaseDate", "purchasePrice", "isArchived", "createdAt", "updatedAt", "customerId") -- "licensePlate" is stored in upper case with the spaces and hyphens as typed; match it with ILIKE
 
 service_records (id, title, description, type, status, cost, mileage, "serviceDate", "startDateTime", "endDateTime", "shopName", "techName", parts, "laborHours", "diagnosticNotes", "invoiceNotes", subtotal, "taxRate", "taxAmount", "totalAmount", "invoiceNumber", "discountType", "discountValue", "discountAmount", "manuallyPaid", "createdAt", "updatedAt", "vehicleId", "customerId", "technicianId", "sortOrder") -- "vehicleId" is NULL for parts-only counter sales; those link "customerId" directly
 

+ 1 - 5
src/features/import/Lib/normalize.ts

@@ -574,11 +574,7 @@ export function normalizeTypeKey(
   }
 }
 
-/** Uppercase, single spaces. The plate is stored as people write it. */
-export function normalizePlate(value: string | null | undefined): string | null {
-  const cleaned = cleanText(value)
-  return cleaned ? cleaned.toUpperCase() : null
-}
+export { normalizePlate } from '@/lib/license-plate'
 
 /** "AB 12345", "AB-12345" and "ab12345" are the same plate. */
 export function plateKey(value: string | null | undefined): string | null {

+ 2 - 1
src/features/portal/Actions/portalActions.ts

@@ -8,6 +8,7 @@ import { loadWorkshopCalendar } from '@/features/workshop-calendar/Lib/loadCalen
 import { addDays, dayState } from '@/features/workshop-calendar/Lib/calendar'
 import { toSafeWorkshopDate } from '@/lib/workshop-datetime'
 import { db } from '@/lib/db'
+import { normalizePlate } from '@/lib/license-plate'
 import { readPortalOpeningHours } from '@/features/portal/Lib/openingHours.server'
 import { withPortalAuth } from '@/features/portal/Lib/portalAuth'
 import { SENT_TO_CUSTOMER } from '@/features/portal/Lib/quoteVisibility'
@@ -382,7 +383,7 @@ export async function createServiceRequest(input: {
       } else if (input.newVehicle) {
         const make = input.newVehicle.make?.trim().slice(0, 60)
         const model = input.newVehicle.model?.trim().slice(0, 60)
-        const licensePlate = input.newVehicle.licensePlate?.trim().slice(0, 20) || null
+        const licensePlate = normalizePlate(input.newVehicle.licensePlate?.trim().slice(0, 20))
         const currentYear = new Date().getFullYear()
         const year =
           Number.isInteger(input.newVehicle.year) &&

+ 8 - 2
src/features/vehicles/Actions/vehicleActions.ts

@@ -15,6 +15,7 @@ import { PermissionAction, PermissionSubject } from '@/lib/permissions'
 import { createVehicleSchema, updateVehicleSchema } from '../Schema/vehicleSchema'
 import { holdsRegistryDate, lookupAppliesTo, type RegistryLookup } from '../Lib/registryLookup'
 import { revalidatePath } from 'next/cache'
+import { normalizePlate } from '@/lib/license-plate'
 import { releaseFiles } from '@/lib/files/manager'
 import { vehicleFileUrls } from '@/lib/files/collect'
 import { auditDetails } from '@/lib/audit'
@@ -301,6 +302,7 @@ export async function createVehicle(input: unknown) {
       const vehicle = await db.vehicle.create({
         data: {
           ...data,
+          licensePlate: normalizePlate(data.licensePlate),
           hsn: data.hsn || null,
           tsn: data.tsn || null,
           purchaseDate: toSafeWorkshopDate(data.purchaseDate, timeZone) ?? null,
@@ -336,6 +338,10 @@ export async function updateVehicle(input: unknown) {
   return withAuth(
     async ({ organizationId, userId }) => {
       const { id, inspectionDueAt, registryLookup, ...data } = updateVehicleSchema.parse(input)
+      // An edit that leaves the plate out leaves it alone; one that sends it
+      // stores the same form a new vehicle gets.
+      const licensePlate =
+        data.licensePlate !== undefined ? normalizePlate(data.licensePlate) : undefined
       assertOwnUploads(data, organizationId)
 
       // Fetch current record for display/diff, and the image it had
@@ -358,7 +364,7 @@ export async function updateVehicle(input: unknown) {
         data: {
           ...data,
           vin: data.vin !== undefined ? data.vin || null : undefined,
-          licensePlate: data.licensePlate !== undefined ? data.licensePlate || null : undefined,
+          licensePlate,
           color: data.color !== undefined ? data.color || null : undefined,
           fuelType: data.fuelType !== undefined ? data.fuelType || null : undefined,
           transmission: data.transmission !== undefined ? data.transmission || null : undefined,
@@ -382,7 +388,7 @@ export async function updateVehicle(input: unknown) {
         await releaseFiles([before.imageUrl], { organizationId, reason: 'vehicle image replaced' })
       }
       await saveInspectionDate(organizationId, id, inspectionDueAt, registryLookup, {
-        licensePlate: data.licensePlate !== undefined ? data.licensePlate : before.licensePlate,
+        licensePlate: licensePlate !== undefined ? licensePlate : before.licensePlate,
         vin: data.vin !== undefined ? data.vin : before.vin,
       })
       const vehicleDisplay = `${before.year} ${before.make} ${before.model}${before.licensePlate ? ` (${before.licensePlate})` : ''}`

+ 2 - 1
src/lib/backup/import.ts

@@ -35,6 +35,7 @@ import { extractEntry, type OpenedZip, readJsonFile, type ZipEntry } from '@/lib
 import { releaseFilesNotRestored } from '@/lib/files/manager'
 import { uploadsRoot } from '@/lib/upload-root'
 import { randomUUID } from 'node:crypto'
+import { normalizePlate } from '@/lib/license-plate'
 import { tenantScoped } from './tenant-guard'
 import {
   acquireRestoreLock,
@@ -1113,7 +1114,7 @@ export async function restoreBackup(
                 model: v.model as string,
                 year: v.year as number,
                 vin: (v.vin as string) || null,
-                licensePlate: (v.licensePlate as string) || null,
+                licensePlate: normalizePlate(v.licensePlate as string | null | undefined),
                 color: (v.color as string) || null,
                 mileage: (v.mileage as number) || 0,
                 fuelType: (v.fuelType as string) || null,

+ 27 - 0
src/lib/license-plate.ts

@@ -0,0 +1,27 @@
+const ASCII_LOWER = /[a-z]/
+
+/**
+ * Upper case for one character, independent of the server's and the viewer's
+ * locale. `toUpperCase` (never `toLocaleUpperCase`) maps "i" to "I" in every
+ * locale, Turkish included. A letter whose upper case is more than one
+ * character ("ß" becomes "SS") is left alone, so a plate never changes
+ * length, and a script without case (Arabic, Thai, Chinese) passes through.
+ */
+function upperChar(char: string): string {
+  if (ASCII_LOWER.test(char)) return char.toUpperCase()
+  const upper = char.toUpperCase()
+  return Array.from(upper).length === 1 ? upper : char
+}
+
+/**
+ * The one form a licence plate (or a boat's registration) is stored in:
+ * trimmed, runs of whitespace collapsed to a single space, letters in upper
+ * case. Spaces and hyphens people typed are kept; nothing is removed. An
+ * empty plate is `null`.
+ */
+export function normalizePlate(value: string | null | undefined): string | null {
+  if (value == null) return null
+  const cleaned = String(value).replace(/\s+/g, ' ').trim()
+  if (!cleaned) return null
+  return Array.from(cleaned, upperChar).join('')
+}