Преглед изворни кода

Send only displayed fields to share pages (#633)

* Send only displayed fields to share pages

The invoice, quote and inspection share pages now build what they hand to
the browser from a named list of fields per document, and the quote is
read through one select shared with the customer portal. A test fills
every column with a marker and fails if one is in what a page sends.

* Keep the share views' optional fields optional

* Drop the share views' unused custom field and finding props
Bernt Christian Egeland пре 8 часа
родитељ
комит
23956db341

+ 722 - 0
src/__tests__/app/share/public-payload.test.tsx

@@ -0,0 +1,722 @@
+/**
+ * What a customer-facing page sends to the browser.
+ *
+ * Whatever a server page passes to a client component is written into the
+ * page, drawn or not, and whatever a portal action returns is the answer the
+ * browser gets. So each surface below is run against a database row in which
+ * every column the surface has no business with carries a marker, and the
+ * marker must not be anywhere in what goes out.
+ *
+ * The rows are filled from the schema's own column lists: a column added
+ * tomorrow gets the marker without anyone touching this file, and a page that
+ * starts spreading a row fails here.
+ *
+ * The fake database honours `select` the way Prisma does, so a narrow select
+ * counts as protection and losing one is caught too.
+ */
+import type { ReactElement } from 'react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { Prisma } from '@/generated/prisma/browser'
+
+const MARK = 'INTERNAL:'
+
+// The first test in each group loads a whole page and its print builders cold.
+vi.setConfig({ testTimeout: 30000 })
+
+type Row = Record<string, unknown>
+type Args = { select?: Record<string, unknown>; include?: Record<string, unknown> } | undefined
+
+const fake = vi.hoisted(() => {
+  const tables: Record<string, Record<string, unknown>[]> = {}
+  /** Relation keys per row, so `include` knows what to leave out by default. */
+  const relations = new WeakMap<object, string[]>()
+
+  const isPlain = (value: unknown): value is Record<string, unknown> =>
+    value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date)
+
+  function project(row: unknown, args: unknown): unknown {
+    if (Array.isArray(row)) return row.map((r) => project(r, args))
+    if (!isPlain(row)) return row
+    const shape = isPlain(args) ? args : {}
+    const related = relations.get(row) ?? []
+    if (isPlain(shape.select)) {
+      const out: Record<string, unknown> = {}
+      for (const [key, want] of Object.entries(shape.select)) {
+        if (!want || key === '_count') continue
+        out[key] = related.includes(key) ? project(row[key] ?? null, want) : row[key]
+      }
+      return out
+    }
+    const out: Record<string, unknown> = {}
+    for (const [key, value] of Object.entries(row)) {
+      if (!related.includes(key)) out[key] = value
+    }
+    if (isPlain(shape.include)) {
+      for (const [key, want] of Object.entries(shape.include)) {
+        if (want && key !== '_count') out[key] = project(row[key] ?? null, want)
+      }
+    }
+    return out
+  }
+
+  const db = new Proxy(
+    {},
+    {
+      get: (_target, model: string) =>
+        new Proxy(
+          {},
+          {
+            get: (_t, method: string) => async (args: unknown) => {
+              const rows = tables[model] ?? []
+              if (method === 'findMany') return project(rows, args)
+              if (method === 'count') return rows.length
+              if (method.startsWith('find')) return rows[0] ? project(rows[0], args) : null
+              return null
+            },
+          }
+        ),
+    }
+  )
+  return { tables, relations, db }
+})
+
+vi.mock('@/lib/db', () => ({ db: fake.db }))
+vi.mock('next-intl/server', async () => {
+  const { useTranslations } = await import('next-intl')
+  return {
+    getTranslations: async (arg: string | { namespace: string }) =>
+      useTranslations(typeof arg === 'string' ? arg : arg.namespace),
+    getLocale: async () => 'en',
+  }
+})
+vi.mock('next/headers', () => ({
+  headers: async () => new Headers({ 'accept-language': 'en' }),
+  cookies: async () => ({ get: () => undefined }),
+}))
+vi.mock('next/navigation', () => ({
+  notFound: () => {
+    throw new Error('not found')
+  },
+}))
+vi.mock('@/lib/customer-session', () => ({
+  getCustomerSession: async () => ({ customerId: 'cust1', organizationId: 'org1' }),
+}))
+vi.mock('@/lib/features', () => ({ getFeatures: async () => ({ brandingRemoved: true }) }))
+vi.mock('@/features/status-reports/Actions/submitFeedback', () => ({
+  submitStatusReportFeedback: vi.fn(),
+}))
+
+/**
+ * A row of a table: every column the schema has carries the marker, then the
+ * ones this surface is allowed to use are given real values on top.
+ */
+function row(columns: Record<string, string>, shown: Row, related: Row = {}): Row {
+  const filled: Row = {}
+  for (const column of Object.values(columns)) filled[column] = `${MARK}${column}`
+  const made = { ...filled, ...shown, ...related }
+  fake.relations.set(made, Object.keys(related))
+  return made
+}
+
+function table(model: string, ...rows: Row[]) {
+  fake.tables[model] = rows
+}
+
+const DAY = new Date('2026-11-10T09:00:00Z')
+
+const customer = () =>
+  row(Prisma.CustomerScalarFieldEnum, {
+    id: 'cust1',
+    name: 'Kari Nordmann',
+    email: 'kari@example.com',
+    phone: null,
+    address: 'Storgata 1',
+    company: null,
+    taxId: null,
+    customerNumber: null,
+    invoiceDesignId: null,
+  })
+
+const vehicle = () =>
+  row(
+    Prisma.VehicleScalarFieldEnum,
+    {
+      id: 'veh1',
+      make: 'Volvo',
+      model: 'V70',
+      year: 2012,
+      vin: null,
+      licensePlate: 'AB12345',
+      hsn: null,
+      tsn: null,
+      mileage: 120000,
+      bodyType: null,
+      // The customer's own car, as their portal describes it to them.
+      color: 'Blue',
+      fuelType: 'Diesel',
+      transmission: 'Manual',
+      soldReportedAt: null,
+      isArchived: false,
+      customerId: 'cust1',
+      organizationId: 'org1',
+    },
+    { customer: customer() }
+  )
+
+function serviceRecord(over: Row = {}) {
+  return row(
+    Prisma.ServiceRecordScalarFieldEnum,
+    {
+      id: 'rec1',
+      title: 'Brake service',
+      type: 'repair',
+      status: 'completed',
+      cost: 300,
+      mileage: 120000,
+      serviceDate: DAY,
+      startDateTime: null,
+      endDateTime: null,
+      promisedAt: null,
+      shopName: null,
+      techName: 'Ola Mekaniker',
+      invoiceNotes: '<p>Thank you for the visit</p>',
+      subtotal: 300,
+      taxRate: 0,
+      taxAmount: 0,
+      taxInclusive: false,
+      taxComponents: null,
+      taxableSubtotal: null,
+      totalAmount: 300,
+      invoiceNumber: 'INV-1',
+      invoiceDate: DAY,
+      invoiceDueDate: null,
+      discountType: null,
+      discountValue: 0,
+      discountAmount: 0,
+      manuallyPaid: false,
+      manuallyPaidAt: null,
+      warrantyStatus: null,
+      warrantyMonths: null,
+      warrantyMileage: null,
+      warrantyExpiresAt: null,
+      warrantyNotes: null,
+      conditionMapOnInvoice: null,
+      publicToken: 'tok',
+      sharedAt: DAY,
+      shareExpiresAt: null,
+      shareNeverExpires: true,
+      shareRenewedAt: null,
+      sentAt: DAY,
+      createdAt: DAY,
+      updatedAt: DAY,
+      designId: null,
+      issuedAt: null,
+      issuedData: null,
+      editUnlockedAt: null,
+      inspectionId: null,
+      organizationId: 'org1',
+      vehicleId: 'veh1',
+      customerId: null,
+      ...over,
+    },
+    {
+      partItems: [
+        row(Prisma.ServicePartScalarFieldEnum, {
+          id: 'part1',
+          partNumber: 'BP-1',
+          name: 'Brake pads',
+          quantity: 1,
+          unit: null,
+          category: null,
+          unitPrice: 100,
+          total: 100,
+          taxable: true,
+        }),
+      ],
+      laborItems: [
+        row(Prisma.ServiceLaborScalarFieldEnum, {
+          id: 'lab1',
+          description: 'Fit brake pads',
+          hours: 2,
+          rate: 100,
+          total: 200,
+          pricingType: 'hourly',
+          taxable: true,
+        }),
+      ],
+      payments: [
+        row(Prisma.PaymentScalarFieldEnum, { id: 'pay1', amount: 50, date: DAY, method: 'cash' }),
+      ],
+      attachments: [
+        row(Prisma.ServiceAttachmentScalarFieldEnum, {
+          id: 'att1',
+          fileName: 'pads.jpg',
+          fileUrl: '/api/protected/files/org1/services/pads.jpg',
+          fileType: 'image/jpeg',
+          fileSize: 1,
+          category: 'image',
+          description: 'Worn pads',
+          includeInInvoice: true,
+        }),
+        // One the workshop kept off the invoice: nothing of it may go out.
+        row(Prisma.ServiceAttachmentScalarFieldEnum, {
+          id: `${MARK}hidden-attachment`,
+          fileUrl: `/api/protected/files/org1/services/${MARK}hidden.jpg`,
+          fileType: 'image/jpeg',
+          fileSize: 1,
+          category: 'image',
+          includeInInvoice: false,
+        }),
+      ],
+      technician: null,
+      customer: null,
+      vehicle: vehicle(),
+      issuedDesignSnapshot: null,
+      issuedLogoSnapshot: null,
+      issuedSignatureSnapshot: null,
+      createdBy: { id: `${MARK}createdBy.id`, name: 'Ola Mekaniker' },
+    }
+  )
+}
+
+function quote() {
+  return row(
+    Prisma.QuoteScalarFieldEnum,
+    {
+      id: 'quote1',
+      quoteNumber: 'Q-1',
+      title: 'New clutch',
+      description: '<p>Includes fitting</p>',
+      status: 'sent',
+      validUntil: new Date('2026-12-10T09:00:00Z'),
+      createdAt: DAY,
+      sentAt: DAY,
+      sharedAt: DAY,
+      shareExpiresAt: null,
+      shareNeverExpires: true,
+      shareRenewedAt: null,
+      subtotal: 300,
+      taxRate: 0,
+      taxAmount: 0,
+      taxInclusive: false,
+      taxComponents: null,
+      taxableSubtotal: null,
+      discountType: null,
+      discountValue: 0,
+      discountAmount: 0,
+      totalAmount: 300,
+      warrantyStatus: null,
+      warrantyMonths: null,
+      warrantyMileage: null,
+      warrantyNotes: null,
+      publicToken: 'tok',
+      organizationId: 'org1',
+      customerId: 'cust1',
+      vehicleId: 'veh1',
+      inspectionId: null,
+    },
+    {
+      partItems: [
+        row(Prisma.QuotePartScalarFieldEnum, {
+          id: 'qpart1',
+          partNumber: 'CL-1',
+          name: 'Clutch kit',
+          quantity: 1,
+          unit: null,
+          category: null,
+          unitPrice: 100,
+          total: 100,
+          excluded: false,
+          taxable: true,
+        }),
+      ],
+      laborItems: [
+        row(Prisma.QuoteLaborScalarFieldEnum, {
+          id: 'qlab1',
+          description: 'Fit clutch',
+          hours: 2,
+          rate: 100,
+          total: 200,
+          pricingType: 'hourly',
+          excluded: false,
+          taxable: true,
+        }),
+      ],
+      attachments: [
+        row(Prisma.QuoteAttachmentScalarFieldEnum, {
+          id: 'qatt1',
+          fileName: 'clutch.jpg',
+          fileUrl: '/api/protected/files/org1/quotes/clutch.jpg',
+          fileType: 'image/jpeg',
+          category: 'image',
+          description: 'The kit',
+        }),
+      ],
+      customer: customer(),
+      vehicle: vehicle(),
+    }
+  )
+}
+
+function inspection() {
+  return row(
+    Prisma.InspectionScalarFieldEnum,
+    {
+      id: 'insp1',
+      status: 'completed',
+      mileage: 120000,
+      notes: 'Ready for winter',
+      publicToken: 'tok',
+      sharedAt: DAY,
+      shareExpiresAt: null,
+      shareNeverExpires: true,
+      shareRenewedAt: null,
+      completedAt: DAY,
+      createdAt: DAY,
+      severityScale: null,
+      country: null,
+      vehicleCategory: null,
+      nextTestDue: null,
+      certificateNumber: null,
+      inspectorName: 'Ola Mekaniker',
+      testLocation: null,
+      designSnapshotId: null,
+      signatureSnapshotId: null,
+      organizationId: 'org1',
+      vehicleId: 'veh1',
+    },
+    {
+      vehicle: vehicle(),
+      template: { name: 'Winter check', severityScale: null, country: null },
+      technician: { name: 'Ola Mekaniker' },
+      items: [
+        row(Prisma.InspectionItemScalarFieldEnum, {
+          id: 'item1',
+          name: 'Brake pads',
+          section: 'Brakes',
+          sectionCode: null,
+          code: null,
+          sortOrder: 0,
+          condition: 'fail',
+          notes: 'Worn to the metal',
+          imageUrls: ['/api/protected/files/org1/inspections/pads.jpg'],
+          inputType: 'condition',
+          unit: null,
+          minValue: null,
+          maxValue: null,
+          measuredValue: null,
+          textValue: null,
+          photoRequired: false,
+        }),
+      ],
+      attachments: [
+        row(Prisma.InspectionAttachmentScalarFieldEnum, {
+          id: 'iatt1',
+          fileName: 'overview.jpg',
+          fileUrl: '/api/protected/files/org1/inspections/overview.jpg',
+          fileType: 'image/jpeg',
+          description: 'The car',
+          includeInReport: true,
+        }),
+      ],
+      quotes: [],
+      designSnapshot: null,
+      signatureSnapshot: null,
+    }
+  )
+}
+
+/** Everything a page handed its client component, as the browser would receive it. */
+function sent(element: unknown): string {
+  const { expiryNote: _chrome, ...props } = (element as ReactElement<Row>).props
+  return JSON.stringify(props)
+}
+
+function propsOf<T = Row>(element: unknown): T {
+  return (element as ReactElement<T>).props
+}
+
+const params = Promise.resolve({ orgId: 'org1', token: 'tok' })
+
+beforeEach(() => {
+  for (const key of Object.keys(fake.tables)) delete fake.tables[key]
+  process.env.BETTER_AUTH_SECRET = 'test-secret-for-handoff-tokens'
+  table('organization', { id: 'org1', name: 'Nordvik Motor', portalSlug: null })
+})
+
+describe('the shared invoice', () => {
+  it('sends the page its amounts and attachments and nothing else of the job', async () => {
+    table('serviceRecord', serviceRecord())
+    const { default: Page } = await import('@/app/(public)/share/invoice/[orgId]/[token]/page')
+    const element = await Page({ params })
+
+    expect(sent(element)).not.toContain(MARK)
+    const { record } = propsOf<{ record: Row }>(element)
+    expect(record.invoiceNumber).toBe('INV-1')
+    expect(record.attachments).toEqual([
+      {
+        id: 'att1',
+        fileName: 'pads.jpg',
+        fileUrl: '/api/public/files/tok/services/pads.jpg',
+        fileType: 'image/jpeg',
+        description: 'Worn pads',
+      },
+    ])
+    expect(Object.keys(record).sort()).toEqual([
+      'attachments',
+      'cost',
+      'discountAmount',
+      'discountType',
+      'discountValue',
+      'id',
+      'invoiceDate',
+      'invoiceNumber',
+      'laborItems',
+      'manuallyPaid',
+      'partItems',
+      'payments',
+      'serviceDate',
+      'shopName',
+      'startDateTime',
+      'taxInclusive',
+      'taxRate',
+      'totalAmount',
+      'vehicle',
+    ])
+  })
+
+  it('sends no more of an issued invoice, whose stored copy stays on the server', async () => {
+    table(
+      'serviceRecord',
+      serviceRecord({
+        issuedAt: DAY,
+        issuedData: {
+          version: 1,
+          workshop: { name: 'Nordvik Motor', address: '', phone: '', email: '' },
+          invoiceSettings: {},
+          customer: { name: 'Kari Nordmann' },
+          vehicle: { make: 'Volvo', model: 'V70', year: 2012 },
+          technicianName: 'Ola Mekaniker',
+          // A finding the sheet prints, a custom field no section of the
+          // design shows, and keys on both that the sheet has no use for.
+          findings: [
+            {
+              description: 'Rear disc worn',
+              severity: 'medium',
+              notes: null,
+              unprinted: `${MARK}finding`,
+            },
+          ],
+          customFields: [
+            {
+              fieldId: 'field1',
+              label: 'Internal reference',
+              value: `${MARK}custom field in no section`,
+              fieldType: 'text',
+              unprinted: `${MARK}customField`,
+            },
+          ],
+          // Anything a snapshot holds beyond what the sheet prints.
+          unprinted: `${MARK}issuedData`,
+        },
+      })
+    )
+    const { default: Page } = await import('@/app/(public)/share/invoice/[orgId]/[token]/page')
+    const element = await Page({ params })
+
+    expect(sent(element)).not.toContain(MARK)
+    expect(propsOf<{ record: Row }>(element).record.invoiceNumber).toBe('INV-1')
+  })
+})
+
+describe('the shared quote', () => {
+  it('sends the page the quote’s number, state and dates and nothing else of it', async () => {
+    table('quote', quote())
+    const { default: Page } = await import('@/app/(public)/share/quote/[orgId]/[token]/page')
+    const element = await Page({ params })
+
+    expect(sent(element)).not.toContain(MARK)
+    const props = propsOf<{ quote: Row; imageAttachments: Row[] }>(element)
+    expect(Object.keys(props.quote).sort()).toEqual([
+      'createdAt',
+      'id',
+      'quoteNumber',
+      'status',
+      'validUntil',
+    ])
+    expect(props.imageAttachments).toEqual([
+      {
+        id: 'qatt1',
+        fileName: 'clutch.jpg',
+        fileUrl: '/api/public/files/tok/quotes/clutch.jpg',
+        fileType: 'image/jpeg',
+        description: 'The kit',
+      },
+    ])
+  })
+})
+
+describe('the shared inspection', () => {
+  it('sends the page the checks and the car and nothing else of the inspection', async () => {
+    table('inspection', inspection())
+    const { default: Page } = await import('@/app/(public)/share/inspection/[orgId]/[token]/page')
+    const element = await Page({ params })
+
+    expect(sent(element)).not.toContain(MARK)
+    const shown = propsOf<{ inspection: { notes: string; items: Row[] } }>(element).inspection
+    expect(shown.notes).toBe('Ready for winter')
+    expect(shown.items[0]).toMatchObject({
+      name: 'Brake pads',
+      notes: 'Worn to the metal',
+      imageUrls: ['/api/public/files/tok/inspections/pads.jpg'],
+    })
+  })
+})
+
+describe('the shared status report', () => {
+  it('sends the page the report and the car and nothing of the job behind it', async () => {
+    table(
+      'statusReport',
+      row(
+        Prisma.StatusReportScalarFieldEnum,
+        {
+          id: 'rep1',
+          title: 'Halfway there',
+          message: 'The pads are on',
+          videoUrl: null,
+          videoFileName: null,
+          publicToken: 'tok',
+          status: 'viewed',
+          viewedAt: DAY,
+          customerFeedback: null,
+          feedbackAt: null,
+          expiresAt: null,
+          createdAt: DAY,
+          organizationId: 'org1',
+        },
+        {
+          serviceRecord: serviceRecord(),
+          inspection: null,
+          technician: { name: 'Ola Mekaniker' },
+          organization: { name: 'Nordvik Motor' },
+        }
+      )
+    )
+    const { default: Page } = await import(
+      '@/app/(public)/share/status-report/[orgId]/[token]/page'
+    )
+    const element = await Page({ params })
+
+    expect(sent(element)).not.toContain(MARK)
+    expect(propsOf<{ report: Row }>(element).report.title).toBe('Halfway there')
+  })
+})
+
+describe('the customer portal', () => {
+  it('answers with a quote’s sheet and nothing else of the quote', async () => {
+    table('quote', quote())
+    const { getPortalQuote } = await import('@/features/portal/Actions/getPortalQuote')
+    const result = await getPortalQuote('quote1')
+
+    expect(result.success).toBe(true)
+    expect(result.data?.quoteNumber).toBe('Q-1')
+    expect(JSON.stringify(result)).not.toContain(MARK)
+  })
+
+  it('answers with an invoice’s sheet and nothing else of the job', async () => {
+    table('serviceRecord', serviceRecord())
+    const { getPortalInvoiceSheet } = await import('@/features/portal/Actions/portalActions')
+    const result = await getPortalInvoiceSheet('rec1')
+
+    expect(result.success).toBe(true)
+    expect(result.data?.invoiceNumber).toBe('INV-1')
+    expect(JSON.stringify(result)).not.toContain(MARK)
+  })
+
+  it('answers with an inspection’s checks and nothing else of the inspection', async () => {
+    table('inspection', inspection())
+    const { getPortalInspection } = await import('@/features/portal/Actions/getPortalInspection')
+    const result = await getPortalInspection('insp1')
+
+    expect(result.success).toBe(true)
+    expect(result.data?.notes).toBe('Ready for winter')
+    expect(JSON.stringify(result)).not.toContain(MARK)
+  })
+
+  it('lists invoices, quotes, inspections and vehicles without the rest of their rows', async () => {
+    table('serviceRecord', serviceRecord())
+    table('quote', quote())
+    table('inspection', inspection())
+    table(
+      'vehicle',
+      (() => {
+        const car = vehicle()
+        fake.relations.set(car, ['customer', 'serviceRecords', 'inspections'])
+        return Object.assign(car, {
+          serviceRecords: [serviceRecord()],
+          inspections: [inspection()],
+        })
+      })()
+    )
+    const portal = await import('@/features/portal/Actions/portalActions')
+    const lists = await Promise.all([
+      portal.getPortalInvoices(),
+      portal.getPortalQuotes(),
+      portal.getPortalInspections(),
+      portal.getPortalVehicles(),
+      portal.getPortalVehicleDetail('veh1'),
+    ])
+
+    for (const list of lists) expect(list.success).toBe(true)
+    expect(JSON.stringify(lists)).not.toContain(MARK)
+  })
+})
+
+describe('the page a phone opens from a code on the desk', () => {
+  it('shows a job’s number and car and nothing of the job', async () => {
+    table('serviceRecord', serviceRecord())
+    const { createPhotoHandoffToken } = await import('@/lib/photo-handoff')
+    const { token } = createPhotoHandoffToken({
+      organizationId: 'org1',
+      serviceRecordId: 'rec1',
+      concernId: null,
+      purpose: 'photos',
+      userId: 'user1',
+    })
+    const { default: Page } = await import('@/app/(public)/p/[token]/page')
+    const element = await Page({
+      params: Promise.resolve({ token }),
+      searchParams: Promise.resolve({}),
+    })
+
+    expect(sent(element)).not.toContain(MARK)
+    expect(propsOf<{ job: Row }>(element).job).toEqual({
+      number: 'INV-1',
+      plate: 'AB12345',
+      vehicle: 'Volvo V70',
+    })
+  })
+
+  it('shows an inspection’s checks by name and nothing they say', async () => {
+    table('inspection', inspection())
+    const { createInspectionHandoffToken } = await import('@/lib/photo-handoff')
+    const { token } = createInspectionHandoffToken({
+      organizationId: 'org1',
+      inspectionId: 'insp1',
+      userId: 'user1',
+    })
+    const { default: Page } = await import('@/app/(public)/p/[token]/page')
+    const outer = await Page({
+      params: Promise.resolve({ token }),
+      searchParams: Promise.resolve({}),
+    })
+    // The inspection's page is a server component of its own; run it.
+    const { type, props } = outer as ReactElement<Row>
+    const element = await (type as (p: Row) => Promise<ReactElement>)(props)
+
+    const out = sent(element)
+    expect(out).not.toContain(MARK)
+    expect(out).toContain('Brake pads')
+    expect(out).not.toContain('Worn to the metal')
+  })
+})

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

@@ -22,6 +22,7 @@ import { QuoteRequestDialog } from '@/features/inspections/Components/QuoteReque
 import { MediaLightbox, type LightboxImage } from '@/features/inspections/Components/MediaLightbox'
 import { MediaLightbox, type LightboxImage } from '@/features/inspections/Components/MediaLightbox'
 import { SpecSheet } from '@/features/invoice-designer/Render/SpecSheet'
 import { SpecSheet } from '@/features/invoice-designer/Render/SpecSheet'
 import type { DocumentSpec } from '@/features/invoice-designer/Spec/documentSpec'
 import type { DocumentSpec } from '@/features/invoice-designer/Spec/documentSpec'
+import type { PublicInspection, PublicInspectionItem } from '@/lib/public-payload'
 import {
 import {
   CONDITION_TOKENS,
   CONDITION_TOKENS,
   TEST_RESULT_TOKENS,
   TEST_RESULT_TOKENS,
@@ -35,63 +36,6 @@ import {
 } from '@/features/inspections/Lib/conditions'
 } from '@/features/inspections/Lib/conditions'
 import { toast } from 'sonner'
 import { toast } from 'sonner'
 
 
-interface InspectionItem {
-  id: string
-  name: string
-  section: string
-  sortOrder: number
-  condition: string
-  notes: string | null
-  imageUrls: string[]
-  description?: string | null
-  code?: string | null
-  sectionCode?: string | null
-  inputType?: string | null
-  unit?: string | null
-  minValue?: number | null
-  maxValue?: number | null
-  measuredValue?: number | null
-  textValue?: string | null
-}
-
-interface InspectionRecord {
-  id: string
-  status: string
-  mileage: number | null
-  notes: string | null
-  completedAt: Date | null
-  createdAt: Date
-  severityScale?: string | null
-  country?: string | null
-  vehicleCategory?: string | null
-  nextTestDue?: Date | null
-  certificateNumber?: string | null
-  inspectorName?: string | null
-  testLocation?: string | null
-  vehicle: {
-    make: string
-    model: string
-    year: number
-    vin: string | null
-    licensePlate: string | null
-    /** Null unless the workshop records the German type key. */
-    hsn?: string | null
-    tsn?: string | null
-    mileage: number
-    customer: { name: string } | null
-  }
-  template: { name: string; severityScale?: string | null; country?: string | null }
-  items: InspectionItem[]
-  /** Files on the inspection as a whole that the workshop chose to show. */
-  attachments?: {
-    id: string
-    fileName: string
-    fileUrl: string
-    fileType: string
-    description: string | null
-  }[]
-}
-
 const CONDITION_ICONS: Record<Condition, React.ComponentType<{ className?: string }>> = {
 const CONDITION_ICONS: Record<Condition, React.ComponentType<{ className?: string }>> = {
   pass: Check,
   pass: Check,
   attention: TriangleAlert,
   attention: TriangleAlert,
@@ -120,7 +64,7 @@ export function InspectionView({
   serviceType = 'automotive',
   serviceType = 'automotive',
   spec,
   spec,
 }: {
 }: {
-  inspection: InspectionRecord
+  inspection: PublicInspection
   workshop: { name: string; address: string; phone: string; email: string }
   workshop: { name: string; address: string; phone: string; email: string }
   logoUrl: string
   logoUrl: string
   primaryColor: string
   primaryColor: string
@@ -178,7 +122,7 @@ export function InspectionView({
 
 
   const sections = useMemo(() => {
   const sections = useMemo(() => {
     const order: string[] = []
     const order: string[] = []
-    const grouped: Record<string, InspectionItem[]> = {}
+    const grouped: Record<string, PublicInspectionItem[]> = {}
     for (const item of gradedItems) {
     for (const item of gradedItems) {
       if (!grouped[item.section]) {
       if (!grouped[item.section]) {
         grouped[item.section] = []
         grouped[item.section] = []
@@ -264,7 +208,7 @@ export function InspectionView({
       : []),
       : []),
   ]
   ]
 
 
-  const renderValue = (item: InspectionItem) => {
+  const renderValue = (item: PublicInspectionItem) => {
     if (
     if (
       item.inputType === 'measurement' &&
       item.inputType === 'measurement' &&
       item.measuredValue !== null &&
       item.measuredValue !== null &&
@@ -292,7 +236,7 @@ export function InspectionView({
     return null
     return null
   }
   }
 
 
-  const renderMedia = (item: InspectionItem) =>
+  const renderMedia = (item: PublicInspectionItem) =>
     item.imageUrls.length > 0 && (
     item.imageUrls.length > 0 && (
       <ul className="mt-2 flex flex-wrap gap-2">
       <ul className="mt-2 flex flex-wrap gap-2">
         {item.imageUrls.map((url, index) => (
         {item.imageUrls.map((url, index) => (

+ 10 - 17
src/app/(public)/share/inspection/[orgId]/[token]/page.tsx

@@ -1,6 +1,7 @@
 import { getTranslations } from 'next-intl/server'
 import { getTranslations } from 'next-intl/server'
 import { closedShareLinkTitle, ShareLinkClosed } from '@/components/share-link-expired'
 import { closedShareLinkTitle, ShareLinkClosed } from '@/components/share-link-expired'
 import { ShareLinkOpenUntil } from '@/components/share-link-open-until'
 import { ShareLinkOpenUntil } from '@/components/share-link-open-until'
+import { publicInspection } from '@/lib/public-payload'
 import { lookUpShareLink } from '@/lib/share-link.server'
 import { lookUpShareLink } from '@/lib/share-link.server'
 import { db } from '@/lib/db'
 import { db } from '@/lib/db'
 import { notFound } from 'next/navigation'
 import { notFound } from 'next/navigation'
@@ -162,19 +163,11 @@ export default async function PublicInspectionPage({
   const portalUrl = portalEnabled ? `${appUrl}/portal/${portalSlug || orgId}` : undefined
   const portalUrl = portalEnabled ? `${appUrl}/portal/${portalSlug || orgId}` : undefined
 
 
   // Gated here, once, so neither the certificate nor the page's own data
   // Gated here, once, so neither the certificate nor the page's own data
-  // carries the type key while the workshop has it switched off.
-  const publicInspection = {
-    ...inspection,
-    vehicle: gateTypeKey(inspection.vehicle, typeKeyEnabledIn(settingsMap)),
-    items: inspection.items.map((item) => ({
-      ...item,
-      imageUrls: item.imageUrls.map(toPublic),
-    })),
-    attachments: inspection.attachments.map((file) => ({
-      ...file,
-      fileUrl: toPublic(file.fileUrl),
-    })),
-  }
+  // carries the type key while the workshop has it switched off. What the
+  // browser gets is named field by field, never the row: a prop of a client
+  // component is readable by anyone holding the link, drawn or not.
+  const gatedVehicle = gateTypeKey(inspection.vehicle, typeKeyEnabledIn(settingsMap))
+  const publicView = publicInspection({ ...inspection, vehicle: gatedVehicle }, toPublic)
 
 
   const linkedQuote = inspection.quotes?.[0]
   const linkedQuote = inspection.quotes?.[0]
   const quoteShareUrl = linkedQuote?.publicToken
   const quoteShareUrl = linkedQuote?.publicToken
@@ -195,7 +188,7 @@ export default async function PublicInspectionPage({
     const labels = await loadCertificateLabels(locale, settingsMap)
     const labels = await loadCertificateLabels(locale, settingsMap)
     const design = templateConfigFromSource(source)
     const design = templateConfigFromSource(source)
     const itemPhotos: Record<string, { dataUri: string }[]> = {}
     const itemPhotos: Record<string, { dataUri: string }[]> = {}
-    for (const item of publicInspection.items) {
+    for (const item of publicView.items) {
       const photos = item.imageUrls.filter((url) => !isVideo(url)).map((url) => ({ dataUri: url }))
       const photos = item.imageUrls.filter((url) => !isVideo(url)).map((url) => ({ dataUri: url }))
       if (photos.length > 0) itemPhotos[item.id] = photos
       if (photos.length > 0) itemPhotos[item.id] = photos
     }
     }
@@ -203,7 +196,7 @@ export default async function PublicInspectionPage({
     spec = buildCertificatePrintSpec({
     spec = buildCertificatePrintSpec({
       data: {
       data: {
         ...inspection,
         ...inspection,
-        vehicle: publicInspection.vehicle,
+        vehicle: gatedVehicle,
       },
       },
       conditionMarks: hasMap ? await loadVehicleConditionMarks(orgId, inspection.vehicleId) : [],
       conditionMarks: hasMap ? await loadVehicleConditionMarks(orgId, inspection.vehicleId) : [],
       bodyType: hasMap ? inspection.vehicle.bodyType : null,
       bodyType: hasMap ? inspection.vehicle.bodyType : null,
@@ -228,7 +221,7 @@ export default async function PublicInspectionPage({
       layoutConfig: design.layoutConfig,
       layoutConfig: design.layoutConfig,
       portalUrl,
       portalUrl,
       itemPhotos,
       itemPhotos,
-      overviewPhotos: publicInspection.attachments
+      overviewPhotos: publicView.attachments
         .filter((file) => file.fileType.startsWith('image/'))
         .filter((file) => file.fileType.startsWith('image/'))
         .map((file) => ({ dataUri: file.fileUrl, caption: file.description })),
         .map((file) => ({ dataUri: file.fileUrl, caption: file.description })),
       attachedDocuments: certificateDocuments(inspection.attachments).map((file) => file.fileName),
       attachedDocuments: certificateDocuments(inspection.attachments).map((file) => file.fileName),
@@ -238,7 +231,7 @@ export default async function PublicInspectionPage({
   return (
   return (
     <InspectionView
     <InspectionView
       expiryNote={<ShareLinkOpenUntil organizationId={orgId} expiry={shared.expiry} />}
       expiryNote={<ShareLinkOpenUntil organizationId={orgId} expiry={shared.expiry} />}
-      inspection={publicInspection}
+      inspection={publicView}
       spec={spec}
       spec={spec}
       workshop={workshop}
       workshop={workshop}
       logoUrl={logoUrl}
       logoUrl={logoUrl}

+ 2 - 92
src/app/(public)/share/invoice/[orgId]/[token]/invoice-view.tsx

@@ -38,93 +38,7 @@ const PAY_VENDORS: {
   { id: 'paystack', label: 'payWithPaystack' },
   { id: 'paystack', label: 'payWithPaystack' },
 ]
 ]
 import type { DocumentSpec } from '@/features/invoice-designer/Spec/documentSpec'
 import type { DocumentSpec } from '@/features/invoice-designer/Spec/documentSpec'
-
-interface InvoiceRecord {
-  id: string
-  title: string
-  description: string | null
-  type: string
-  status: string
-  serviceDate: Date
-  startDateTime: Date | null
-  invoiceDate: Date | null
-  invoiceDueDate: Date | null
-  shopName: string | null
-  techName: string | null
-  mileage: number | null
-  diagnosticNotes: string | null
-  invoiceNotes: string | null
-  subtotal: number
-  taxRate: number
-  taxAmount: number
-  taxInclusive?: boolean
-  totalAmount: number
-  cost: number
-  invoiceNumber: string | null
-  manuallyPaid: boolean
-  discountType: string | null
-  discountValue: number
-  discountAmount: number
-  warrantyMonths: number | null
-  warrantyMileage: number | null
-  warrantyExpiresAt: Date | string | null
-  warrantyNotes: string | null
-  partItems: {
-    partNumber: string | null
-    name: string
-    quantity: number
-    unit?: string | null
-    unitPrice: number
-    total: number
-  }[]
-  laborItems: {
-    description: string
-    hours: number
-    rate: number
-    total: number
-    pricingType?: string
-  }[]
-  payments: {
-    amount: number
-    date: Date
-    method: string
-  }[]
-  attachments: {
-    id: string
-    fileName: string
-    fileUrl: string
-    fileType: string
-    fileSize: number
-    category: string
-    description: string | null
-  }[]
-  customer?: {
-    name: string
-    email: string | null
-    phone: string | null
-    address: string | null
-    company: string | null
-    taxId?: string | null
-  } | null
-  vehicle: {
-    make: string
-    model: string
-    year: number
-    vin: string | null
-    licensePlate: string | null
-    hsn?: string | null
-    tsn?: string | null
-    mileage: number
-    customer: {
-      name: string
-      email: string | null
-      phone: string | null
-      address: string | null
-      company: string | null
-      taxId?: string | null
-    } | null
-  } | null
-}
+import type { PublicInvoiceRecord } from '@/lib/public-payload'
 
 
 interface InvoiceSettings {
 interface InvoiceSettings {
   bankAccount: string
   bankAccount: string
@@ -247,14 +161,12 @@ export function InvoiceView({
   logoSize = 100,
   logoSize = 100,
   portalUrl,
   portalUrl,
   layoutConfig,
   layoutConfig,
-  customFields = [],
-  findings = [],
   serviceType = 'automotive',
   serviceType = 'automotive',
   taxLabel,
   taxLabel,
 }: {
 }: {
   /** The document the workshop designed, built server-side from this job. */
   /** The document the workshop designed, built server-side from this job. */
   spec: DocumentSpec
   spec: DocumentSpec
-  record: InvoiceRecord
+  record: PublicInvoiceRecord
   workshop: { name: string; address: string; phone: string; email: string }
   workshop: { name: string; address: string; phone: string; email: string }
   currencyCode: string
   currencyCode: string
   currencyFormat?: 'symbol' | 'code'
   currencyFormat?: 'symbol' | 'code'
@@ -278,8 +190,6 @@ export function InvoiceView({
   logoSize?: number
   logoSize?: number
   portalUrl?: string
   portalUrl?: string
   layoutConfig?: InvoiceLayoutConfig
   layoutConfig?: InvoiceLayoutConfig
-  customFields?: CustomField[]
-  findings?: Array<{ description: string; severity: string; notes: string | null }>
   serviceType?: 'automotive' | 'marine'
   serviceType?: 'automotive' | 'marine'
   taxLabel?: string
   taxLabel?: string
 }) {
 }) {

+ 8 - 29
src/app/(public)/share/invoice/[orgId]/[token]/page.tsx

@@ -17,6 +17,7 @@ import { offeredPaymentProviders } from '@/features/integrations/Lib/payments'
 import { getAppBaseUrl } from '@/lib/app-url'
 import { getAppBaseUrl } from '@/lib/app-url'
 import { closedShareLinkTitle, ShareLinkClosed } from '@/components/share-link-expired'
 import { closedShareLinkTitle, ShareLinkClosed } from '@/components/share-link-expired'
 import { ShareLinkOpenUntil } from '@/components/share-link-open-until'
 import { ShareLinkOpenUntil } from '@/components/share-link-open-until'
+import { publicInvoiceRecord } from '@/lib/public-payload'
 import { lookUpShareLink } from '@/lib/share-link.server'
 import { lookUpShareLink } from '@/lib/share-link.server'
 
 
 /** Rewrites /api/protected/files/[orgId]/[category]/[filename] to /api/public/files/[token]/[category]/[filename] */
 /** Rewrites /api/protected/files/[orgId]/[category]/[filename] to /api/public/files/[token]/[category]/[filename] */
@@ -100,33 +101,13 @@ export default async function PublicInvoicePage({
   // into the integrations catalog they were connected on.
   // into the integrations catalog they were connected on.
   const enabledProviders = await offeredPaymentProviders(orgId)
   const enabledProviders = await offeredPaymentProviders(orgId)
 
 
-  // What reaches the browser: internal unitCost/markupPercent must never be
-  // in the customer-facing payload, attachment URLs go through the public
-  // file route, and the customer, vehicle and technician are the ones the
-  // sheet prints, frozen at issue or live for a draft.
-  const publicRecord = {
-    ...record,
-    techName: assembly.data.techName,
-    customer: assembly.data.customer,
-    vehicle: assembly.data.vehicle,
-    partItems: record.partItems.map((p) => ({
-      id: p.id,
-      partNumber: p.partNumber,
-      name: p.name,
-      quantity: p.quantity,
-      unit: p.unit,
-      category: p.category,
-      unitPrice: p.unitPrice,
-      total: p.total,
-      taxable: p.taxable,
-    })),
-    attachments: record.attachments
-      .filter((att) => att.includeInInvoice !== false)
-      .map((att) => ({
-        ...att,
-        fileUrl: toPublicFileUrl(att.fileUrl, token),
-      })),
-  }
+  // What reaches the browser is named field by field, never the row: a prop
+  // of a client component is readable by anyone holding the link, drawn or
+  // not. The vehicle is the one the sheet prints, frozen at issue or live for
+  // a draft, and attachment addresses go through the public file route.
+  const publicRecord = publicInvoiceRecord(record, assembly.data.vehicle, (url) =>
+    toPublicFileUrl(url, token)
+  )
 
 
   const acceptLanguage = (await headers()).get('accept-language')
   const acceptLanguage = (await headers()).get('accept-language')
   const locale = await resolveCustomerLocale(orgId, acceptLanguage)
   const locale = await resolveCustomerLocale(orgId, acceptLanguage)
@@ -192,8 +173,6 @@ export default async function PublicInvoicePage({
       logoSize={assembly.template.logoSize || 100}
       logoSize={assembly.template.logoSize || 100}
       portalUrl={portalUrl}
       portalUrl={portalUrl}
       layoutConfig={assembly.layoutConfig}
       layoutConfig={assembly.layoutConfig}
-      customFields={assembly.data.customFields}
-      findings={assembly.data.findings}
       serviceType={assembly.serviceType}
       serviceType={assembly.serviceType}
       taxLabel={assembly.taxLabel}
       taxLabel={assembly.taxLabel}
       expiryNote={<ShareLinkOpenUntil organizationId={orgId} expiry={shared.expiry} />}
       expiryNote={<ShareLinkOpenUntil organizationId={orgId} expiry={shared.expiry} />}

+ 20 - 59
src/app/(public)/share/quote/[orgId]/[token]/page.tsx

@@ -19,6 +19,7 @@ import { getCustomFieldsForPrint } from '@/features/custom-fields/Lib/getCustomF
 import { getAppBaseUrl } from '@/lib/app-url'
 import { getAppBaseUrl } from '@/lib/app-url'
 import { closedShareLinkTitle, ShareLinkClosed } from '@/components/share-link-expired'
 import { closedShareLinkTitle, ShareLinkClosed } from '@/components/share-link-expired'
 import { ShareLinkOpenUntil } from '@/components/share-link-open-until'
 import { ShareLinkOpenUntil } from '@/components/share-link-open-until'
+import { PUBLIC_QUOTE_SELECT, publicAttachment, publicQuoteRecord } from '@/lib/public-payload'
 import { lookUpShareLink } from '@/lib/share-link.server'
 import { lookUpShareLink } from '@/lib/share-link.server'
 import { documentSigner } from '@/features/signatures/Lib/memberSignature.server'
 import { documentSigner } from '@/features/signatures/Lib/memberSignature.server'
 import { SETTING_KEYS } from '@/features/settings/Schema/settingsSchema'
 import { SETTING_KEYS } from '@/features/settings/Schema/settingsSchema'
@@ -60,49 +61,20 @@ export default async function PublicQuotePage({
   }
   }
   const { organizationId: orgId, shared } = link
   const { organizationId: orgId, shared } = link
 
 
+  // Only the columns a customer's copy is built from are read: the
+  // workshop's own notes and a line's cost and markup never leave the database.
   const quote = await db.quote.findFirst({
   const quote = await db.quote.findFirst({
     where: { publicToken: token, organizationId: orgId },
     where: { publicToken: token, organizationId: orgId },
-    include: {
-      // Explicit select: internal unitCost/markupPercent must never reach
-      // the public customer-facing payload
-      partItems: {
+    select: {
+      ...PUBLIC_QUOTE_SELECT,
+      attachments: {
         select: {
         select: {
           id: true,
           id: true,
-          partNumber: true,
-          name: true,
-          quantity: true,
-          unit: true,
+          fileName: true,
+          fileUrl: true,
+          fileType: true,
           category: true,
           category: true,
-          unitPrice: true,
-          total: true,
-          excluded: true,
-          // The sheet works its tax out from the lines, so each has to say
-          // whether it is taxed; left out here, every line would be.
-          taxable: true,
-        },
-        orderBy: { sortOrder: 'asc' },
-      },
-      laborItems: { orderBy: { sortOrder: 'asc' } },
-      attachments: true,
-      customer: {
-        select: {
-          name: true,
-          email: true,
-          phone: true,
-          address: true,
-          company: true,
-          taxId: true,
-        },
-      },
-      vehicle: {
-        select: {
-          make: true,
-          model: true,
-          year: true,
-          vin: true,
-          licensePlate: true,
-          hsn: true,
-          tsn: true,
+          description: true,
         },
         },
       },
       },
     },
     },
@@ -199,25 +171,15 @@ export default async function PublicQuotePage({
     else logoUrl = rawLogoUrl
     else logoUrl = rawLogoUrl
   }
   }
 
 
-  // Rewrite attachment URLs for public access
-  const imageAttachments = (quote.attachments || [])
-    .filter((a) => a.category === 'image')
-    .map((a) => ({
-      ...a,
-      fileUrl: a.fileUrl.replace(
-        /^\/api\/protected\/files\/[^/]+\//,
-        `/api/public/files/${token}/`
-      ),
-    }))
-  const documentAttachments = (quote.attachments || [])
-    .filter((a) => a.category === 'document')
-    .map((a) => ({
-      ...a,
-      fileUrl: a.fileUrl.replace(
-        /^\/api\/protected\/files\/[^/]+\//,
-        `/api/public/files/${token}/`
-      ),
-    }))
+  // Attachments, named field by field, with addresses this link's token opens.
+  const toPublicUrl = (url: string) =>
+    url.replace(/^\/api\/protected\/files\/[^/]+\//, `/api/public/files/${token}/`)
+  const attachmentsOf = (category: string) =>
+    quote.attachments
+      .filter((file) => file.category === category)
+      .map((file) => publicAttachment(file, toPublicUrl))
+  const imageAttachments = attachmentsOf('image')
+  const documentAttachments = attachmentsOf('document')
 
 
   // Parse layout config
   // Parse layout config
   const layoutConfig = mergeWithDefaults(
   const layoutConfig = mergeWithDefaults(
@@ -291,7 +253,7 @@ export default async function PublicQuotePage({
   return (
   return (
     <QuoteView
     <QuoteView
       spec={spec}
       spec={spec}
-      quote={shownQuote}
+      quote={publicQuoteRecord(quote)}
       workshop={workshop}
       workshop={workshop}
       currencyCode={currencyCode}
       currencyCode={currencyCode}
       currencyFormat={currencyFormat}
       currencyFormat={currencyFormat}
@@ -308,7 +270,6 @@ export default async function PublicQuotePage({
       imageAttachments={imageAttachments}
       imageAttachments={imageAttachments}
       documentAttachments={documentAttachments}
       documentAttachments={documentAttachments}
       layoutConfig={layoutConfig}
       layoutConfig={layoutConfig}
-      customFields={customFields}
       serviceType={(settingsMap['workshop.serviceType'] || 'automotive') as 'automotive' | 'marine'}
       serviceType={(settingsMap['workshop.serviceType'] || 'automotive') as 'automotive' | 'marine'}
       taxLabel={settingsMap['workshop.taxLabel']?.trim() || undefined}
       taxLabel={settingsMap['workshop.taxLabel']?.trim() || undefined}
       expiryNote={<ShareLinkOpenUntil organizationId={orgId} expiry={shared.expiry} />}
       expiryNote={<ShareLinkOpenUntil organizationId={orgId} expiry={shared.expiry} />}

+ 4 - 69
src/app/(public)/share/quote/[orgId]/[token]/quote-view.tsx

@@ -23,59 +23,7 @@ import {
 } from '@/features/settings/Schema/invoiceLayoutSchema'
 } from '@/features/settings/Schema/invoiceLayoutSchema'
 import { SpecSheet } from '@/features/invoice-designer/Render/SpecSheet'
 import { SpecSheet } from '@/features/invoice-designer/Render/SpecSheet'
 import type { DocumentSpec } from '@/features/invoice-designer/Spec/documentSpec'
 import type { DocumentSpec } from '@/features/invoice-designer/Spec/documentSpec'
-
-interface QuoteRecord {
-  id: string
-  quoteNumber: string | null
-  title: string
-  description: string | null
-  status: string
-  validUntil: Date | null
-  createdAt: Date
-  subtotal: number
-  taxRate: number
-  taxAmount: number
-  taxInclusive?: boolean
-  discountType: string | null
-  discountValue: number
-  discountAmount: number
-  totalAmount: number
-  notes: string | null
-  partItems: {
-    partNumber: string | null
-    name: string
-    quantity: number
-    unit?: string | null
-    unitPrice: number
-    total: number
-    excluded?: boolean
-  }[]
-  laborItems: {
-    description: string
-    hours: number
-    rate: number
-    total: number
-    pricingType?: string
-    excluded?: boolean
-  }[]
-  customer: {
-    name: string
-    email: string | null
-    phone: string | null
-    address: string | null
-    company: string | null
-    taxId?: string | null
-  } | null
-  vehicle: {
-    make: string
-    model: string
-    year: number
-    vin: string | null
-    licensePlate: string | null
-    hsn?: string | null
-    tsn?: string | null
-  } | null
-}
+import type { PublicAttachment, PublicQuoteRecord } from '@/lib/public-payload'
 
 
 interface InvoiceLayoutConfig {
 interface InvoiceLayoutConfig {
   sections: Array<{
   sections: Array<{
@@ -151,17 +99,6 @@ function getUnassignedCustomFields(
   return allCustomFields.filter((cf) => !cf.fieldId || !assignedFieldIds.has(cf.fieldId))
   return allCustomFields.filter((cf) => !cf.fieldId || !assignedFieldIds.has(cf.fieldId))
 }
 }
 
 
-interface QuoteAttachmentView {
-  id: string
-  fileName: string
-  fileUrl: string
-  fileType: string
-  fileSize: number
-  category: string
-  description: string | null
-  includeInInvoice: boolean
-}
-
 export function QuoteView({
 export function QuoteView({
   spec,
   spec,
   quote,
   quote,
@@ -183,13 +120,12 @@ export function QuoteView({
   imageAttachments = [],
   imageAttachments = [],
   documentAttachments = [],
   documentAttachments = [],
   layoutConfig,
   layoutConfig,
-  customFields = [],
   serviceType = 'automotive',
   serviceType = 'automotive',
   taxLabel,
   taxLabel,
 }: {
 }: {
   /** The document the workshop designed, built server-side from this quote. */
   /** The document the workshop designed, built server-side from this quote. */
   spec: DocumentSpec
   spec: DocumentSpec
-  quote: QuoteRecord
+  quote: PublicQuoteRecord
   workshop: { name: string; address: string; phone: string; email: string }
   workshop: { name: string; address: string; phone: string; email: string }
   currencyCode: string
   currencyCode: string
   currencyFormat?: 'symbol' | 'code'
   currencyFormat?: 'symbol' | 'code'
@@ -207,10 +143,9 @@ export function QuoteView({
   headerStyle?: string
   headerStyle?: string
   logoSize?: number
   logoSize?: number
   portalUrl?: string
   portalUrl?: string
-  imageAttachments?: QuoteAttachmentView[]
-  documentAttachments?: QuoteAttachmentView[]
+  imageAttachments?: PublicAttachment[]
+  documentAttachments?: PublicAttachment[]
   layoutConfig?: InvoiceLayoutConfig
   layoutConfig?: InvoiceLayoutConfig
-  customFields?: CustomField[]
   serviceType?: 'automotive' | 'marine'
   serviceType?: 'automotive' | 'marine'
   taxLabel?: string
   taxLabel?: string
 }) {
 }) {

+ 2 - 1
src/features/invoice-designer/Pdf/buildQuotePrint.ts

@@ -60,7 +60,8 @@ export interface QuotePrintData {
   discountValue: number
   discountValue: number
   discountAmount: number
   discountAmount: number
   totalAmount: number
   totalAmount: number
-  notes: string | null
+  /** The workshop's own note. Never printed: the sheet's note is `description`. */
+  notes?: string | null
   /** The warranty the customer is offered; see src/lib/warranty.ts. */
   /** The warranty the customer is offered; see src/lib/warranty.ts. */
   warrantyStatus?: string | null
   warrantyStatus?: string | null
   warrantyMonths?: number | null
   warrantyMonths?: number | null

+ 4 - 40
src/features/portal/Actions/getPortalQuote.ts

@@ -18,6 +18,7 @@ import { resolveCustomerLocale } from '@/i18n/locale-from-request'
 import { resolveCurrencyCode, resolveCurrencyFormat } from '@/lib/currencies'
 import { resolveCurrencyCode, resolveCurrencyFormat } from '@/lib/currencies'
 import { db } from '@/lib/db'
 import { db } from '@/lib/db'
 import { getFeatures } from '@/lib/features'
 import { getFeatures } from '@/lib/features'
+import { PUBLIC_QUOTE_SELECT } from '@/lib/public-payload'
 import { resolveUploadPath } from '@/lib/resolve-upload-path'
 import { resolveUploadPath } from '@/lib/resolve-upload-path'
 import { resolveWorkshopTimeZone } from '@/lib/timezone'
 import { resolveWorkshopTimeZone } from '@/lib/timezone'
 import { getTorqvoiceLogoDataUri } from '@/lib/torqvoice-branding'
 import { getTorqvoiceLogoDataUri } from '@/lib/torqvoice-branding'
@@ -56,46 +57,9 @@ export async function getPortalQuote(quoteId: string) {
   return withPortalAuth(async ({ customerId, organizationId }) => {
   return withPortalAuth(async ({ customerId, organizationId }) => {
     const quote = await db.quote.findFirst({
     const quote = await db.quote.findFirst({
       where: { id: quoteId, customerId, organizationId, ...SENT_TO_CUSTOMER },
       where: { id: quoteId, customerId, organizationId, ...SENT_TO_CUSTOMER },
-      include: {
-        // Explicit select: internal unitCost/markupPercent never reach the customer.
-        partItems: {
-          select: {
-            id: true,
-            partNumber: true,
-            name: true,
-            quantity: true,
-            unit: true,
-            category: true,
-            unitPrice: true,
-            total: true,
-            excluded: true,
-            taxable: true,
-          },
-          orderBy: { sortOrder: 'asc' },
-        },
-        laborItems: { orderBy: { sortOrder: 'asc' } },
-        customer: {
-          select: {
-            name: true,
-            email: true,
-            phone: true,
-            address: true,
-            company: true,
-            taxId: true,
-          },
-        },
-        vehicle: {
-          select: {
-            make: true,
-            model: true,
-            year: true,
-            vin: true,
-            licensePlate: true,
-            hsn: true,
-            tsn: true,
-          },
-        },
-      },
+      // Only the columns a customer's copy is built from; the workshop's
+      // own notes and a line's cost and markup are never read.
+      select: PUBLIC_QUOTE_SELECT,
     })
     })
     if (!quote) return null
     if (!quote) return null
 
 

+ 329 - 0
src/lib/public-payload.ts

@@ -0,0 +1,329 @@
+/**
+ * What a page opened from a share link hands to the browser.
+ *
+ * A prop given to a client component is serialised into the page, whether or
+ * not anything draws it, so anyone holding the link can read every field of
+ * it. Each mapper here names the fields its view draws and copies those, one
+ * by one. A field that is not listed does not leave the server: a column
+ * added to a table tomorrow stays out until somebody adds it here on purpose.
+ *
+ * Never spread a database row into one of these. The tests in
+ * `src/__tests__/app/share/public-payload.test.tsx` fill every column of a
+ * row with a marker and fail when one shows up in what a page sends.
+ */
+
+/**
+ * Turns a stored upload address into the one this link's token opens. Each
+ * page brings its own, because each has rewritten a different set of forms.
+ */
+export type ToPublicUrl = (fileUrl: string) => string
+
+/* ── Invoice ─────────────────────────────────────────────────────────── */
+
+export interface PublicInvoiceRecord {
+  id: string
+  invoiceNumber: string | null
+  shopName: string | null
+  serviceDate: Date
+  startDateTime: Date | null
+  invoiceDate: Date | null
+  taxRate: number
+  taxInclusive?: boolean
+  totalAmount: number
+  cost: number
+  manuallyPaid: boolean
+  discountType: string | null
+  discountValue: number
+  discountAmount: number
+  partItems: { total: number; taxable?: boolean | null }[]
+  laborItems: { total: number; taxable?: boolean | null }[]
+  payments: { amount: number }[]
+  attachments: PublicAttachment[]
+  vehicle: { make: string; model: string; year: number } | null
+}
+
+export interface PublicAttachment {
+  id: string
+  fileName: string
+  fileUrl: string
+  fileType: string
+  description: string | null
+}
+
+type InvoiceSource = Omit<PublicInvoiceRecord, 'attachments' | 'vehicle'> & {
+  attachments: (PublicAttachment & { includeInInvoice?: boolean | null })[]
+}
+
+/**
+ * The invoice as the share page's own chrome needs it: the amounts the pay
+ * buttons work from, the number in the file name and the files the workshop
+ * attached for the customer. The sheet itself arrives as a finished spec.
+ */
+export function publicInvoiceRecord(
+  record: InvoiceSource,
+  vehicle: { make: string; model: string; year: number } | null | undefined,
+  toPublicUrl: ToPublicUrl
+): PublicInvoiceRecord {
+  return {
+    id: record.id,
+    invoiceNumber: record.invoiceNumber,
+    shopName: record.shopName,
+    serviceDate: record.serviceDate,
+    startDateTime: record.startDateTime,
+    invoiceDate: record.invoiceDate,
+    taxRate: record.taxRate,
+    taxInclusive: record.taxInclusive,
+    totalAmount: record.totalAmount,
+    cost: record.cost,
+    manuallyPaid: record.manuallyPaid,
+    discountType: record.discountType,
+    discountValue: record.discountValue,
+    discountAmount: record.discountAmount,
+    partItems: record.partItems.map((part) => ({ total: part.total, taxable: part.taxable })),
+    laborItems: record.laborItems.map((line) => ({ total: line.total, taxable: line.taxable })),
+    payments: record.payments.map((payment) => ({ amount: payment.amount })),
+    attachments: record.attachments
+      .filter((file) => file.includeInInvoice !== false)
+      .map((file) => publicAttachment(file, toPublicUrl)),
+    vehicle: vehicle ? { make: vehicle.make, model: vehicle.model, year: vehicle.year } : null,
+  }
+}
+
+export function publicAttachment(
+  file: PublicAttachment,
+  toPublicUrl: ToPublicUrl
+): PublicAttachment {
+  return {
+    id: file.id,
+    fileName: file.fileName,
+    fileUrl: toPublicUrl(file.fileUrl),
+    fileType: file.fileType,
+    description: file.description,
+  }
+}
+
+/* ── Quote ───────────────────────────────────────────────────────────── */
+
+const PUBLIC_QUOTE_PARTY = {
+  name: true,
+  email: true,
+  phone: true,
+  address: true,
+  company: true,
+  taxId: true,
+} as const
+
+/**
+ * The columns of a quote a customer's copy is built from, for the share page
+ * and the portal alike. The sheet prints `description`, the note written for
+ * the customer. `notes` is the workshop's own and is not read at all, and
+ * neither is a line's cost or markup.
+ */
+export const PUBLIC_QUOTE_SELECT = {
+  id: true,
+  quoteNumber: true,
+  title: true,
+  description: true,
+  status: true,
+  validUntil: true,
+  createdAt: true,
+  sentAt: true,
+  subtotal: true,
+  taxRate: true,
+  taxAmount: true,
+  taxInclusive: true,
+  taxComponents: true,
+  taxableSubtotal: true,
+  discountType: true,
+  discountValue: true,
+  discountAmount: true,
+  totalAmount: true,
+  warrantyStatus: true,
+  warrantyMonths: true,
+  warrantyMileage: true,
+  warrantyNotes: true,
+  // Whose signature the sheet carries, and which car and inspection it reads.
+  userId: true,
+  vehicleId: true,
+  inspectionId: true,
+  partItems: {
+    select: {
+      id: true,
+      partNumber: true,
+      name: true,
+      quantity: true,
+      unit: true,
+      category: true,
+      unitPrice: true,
+      total: true,
+      excluded: true,
+      // The sheet works its tax out from the lines, so each has to say
+      // whether it is taxed; left out here, every line would be.
+      taxable: true,
+    },
+    orderBy: { sortOrder: 'asc' as const },
+  },
+  laborItems: {
+    select: {
+      id: true,
+      description: true,
+      hours: true,
+      rate: true,
+      total: true,
+      pricingType: true,
+      excluded: true,
+      taxable: true,
+    },
+    orderBy: { sortOrder: 'asc' as const },
+  },
+  customer: { select: PUBLIC_QUOTE_PARTY },
+  vehicle: {
+    select: {
+      make: true,
+      model: true,
+      year: true,
+      vin: true,
+      licensePlate: true,
+      hsn: true,
+      tsn: true,
+    },
+  },
+} as const
+
+export interface PublicQuoteRecord {
+  id: string
+  quoteNumber: string | null
+  status: string
+  validUntil: Date | null
+  createdAt: Date
+}
+
+/** The quote as the share page's own chrome needs it; the sheet arrives as a finished spec. */
+export function publicQuoteRecord(quote: PublicQuoteRecord): PublicQuoteRecord {
+  return {
+    id: quote.id,
+    quoteNumber: quote.quoteNumber,
+    status: quote.status,
+    validUntil: quote.validUntil,
+    createdAt: quote.createdAt,
+  }
+}
+
+/* ── Inspection ──────────────────────────────────────────────────────── */
+
+export interface PublicInspectionItem {
+  id: string
+  name: string
+  section: string
+  sectionCode?: string | null
+  code?: string | null
+  sortOrder: number
+  condition: string
+  notes: string | null
+  imageUrls: string[]
+  inputType?: string | null
+  unit?: string | null
+  minValue?: number | null
+  maxValue?: number | null
+  measuredValue?: number | null
+  textValue?: string | null
+}
+
+export interface PublicInspectionVehicle {
+  make: string
+  model: string
+  year: number
+  vin: string | null
+  licensePlate: string | null
+  /** Null unless the workshop records the German type key. */
+  hsn?: string | null
+  tsn?: string | null
+  mileage: number
+  customer: { name: string } | null
+}
+
+export interface PublicInspection {
+  id: string
+  mileage: number | null
+  notes: string | null
+  completedAt: Date | null
+  createdAt: Date
+  severityScale?: string | null
+  country?: string | null
+  vehicleCategory?: string | null
+  nextTestDue?: Date | null
+  certificateNumber?: string | null
+  inspectorName?: string | null
+  testLocation?: string | null
+  vehicle: PublicInspectionVehicle
+  template: { name: string; severityScale?: string | null; country?: string | null }
+  items: PublicInspectionItem[]
+  /** Files on the inspection as a whole that the workshop chose to show. */
+  attachments?: PublicAttachment[]
+}
+
+type InspectionSource = Omit<PublicInspection, 'attachments'> & {
+  attachments: (PublicAttachment & { includeInReport?: boolean | null })[]
+}
+
+/**
+ * The inspection as the report page draws it: the checks with their grades,
+ * notes and photographs, the car, and the files the workshop chose to show.
+ * The guidance an inspector reads beside a check is theirs and stays behind.
+ */
+export function publicInspection(
+  inspection: InspectionSource,
+  toPublicUrl: ToPublicUrl
+): PublicInspection & { attachments: PublicAttachment[] } {
+  const { vehicle, template } = inspection
+  return {
+    id: inspection.id,
+    mileage: inspection.mileage,
+    notes: inspection.notes,
+    completedAt: inspection.completedAt,
+    createdAt: inspection.createdAt,
+    severityScale: inspection.severityScale,
+    country: inspection.country,
+    vehicleCategory: inspection.vehicleCategory,
+    nextTestDue: inspection.nextTestDue,
+    certificateNumber: inspection.certificateNumber,
+    inspectorName: inspection.inspectorName,
+    testLocation: inspection.testLocation,
+    vehicle: {
+      make: vehicle.make,
+      model: vehicle.model,
+      year: vehicle.year,
+      vin: vehicle.vin,
+      licensePlate: vehicle.licensePlate,
+      hsn: vehicle.hsn ?? null,
+      tsn: vehicle.tsn ?? null,
+      mileage: vehicle.mileage,
+      customer: vehicle.customer ? { name: vehicle.customer.name } : null,
+    },
+    template: {
+      name: template.name,
+      severityScale: template.severityScale,
+      country: template.country,
+    },
+    items: inspection.items.map((item) => ({
+      id: item.id,
+      name: item.name,
+      section: item.section,
+      sectionCode: item.sectionCode,
+      code: item.code,
+      sortOrder: item.sortOrder,
+      condition: item.condition,
+      notes: item.notes,
+      imageUrls: item.imageUrls.map(toPublicUrl),
+      inputType: item.inputType,
+      unit: item.unit,
+      minValue: item.minValue,
+      maxValue: item.maxValue,
+      measuredValue: item.measuredValue,
+      textValue: item.textValue,
+    })),
+    attachments: inspection.attachments
+      .filter((file) => file.includeInReport !== false)
+      .map((file) => publicAttachment(file, toPublicUrl)),
+  }
+}