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

Let Unpaid in the work order header take a payment, and stop the read-only pills looking like controls (#668)

Bernt Christian Egeland 5 дней назад
Родитель
Сommit
7bd3c84f98

+ 305 - 0
src/__tests__/features/vehicles/work-order-header-pills.test.tsx

@@ -0,0 +1,305 @@
+/**
+ * The pills in the work order header. People clicked the status pill and the
+ * payment pill and nothing happened: they sat in the same outlined box as the
+ * type dropdown beside them. Now "Unpaid" (and "Partial") is the page's own
+ * "Take payment" for somebody who may record a payment, and every pill that
+ * does nothing has lost the outline and the hand cursor. A locked invoice and
+ * somebody without billing rights gain no control.
+ *
+ * The status pill stays read only: its menus belong to the status stepper.
+ */
+import { useState } from 'react'
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const paymentStatus = vi.hoisted(() => ({ value: 'unpaid' }))
+const membership = vi.hoisted(() => ({ value: null as unknown }))
+
+vi.mock('@/lib/cached-session', () => ({
+  getCachedMembership: async () => membership.value,
+}))
+vi.mock('@/features/inspections/Components/NewInspectionDialog', () => ({
+  NewInspectionDialog: () => null,
+}))
+
+const deleteFinding = vi.fn()
+const router = { push: vi.fn(), refresh: vi.fn(), replace: vi.fn() }
+
+vi.mock('next/navigation', () => ({ useRouter: () => router }))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
+vi.mock('@/features/vehicles/Actions/findingActions', () => ({
+  deleteFinding: (id: string) => deleteFinding(id),
+}))
+vi.mock('@/features/vehicles/Actions/serviceActions', () => ({
+  updateServiceRecordTitle: vi.fn(),
+  updateServiceStatus: vi.fn(),
+  updateServiceRecord: vi.fn(),
+}))
+vi.mock('@/features/email/Actions/emailActions', () => ({ sendInvoiceEmail: vi.fn() }))
+vi.mock('@/features/settings/Actions/documentLockActions', () => ({
+  setInvoiceEditUnlocked: vi.fn(),
+}))
+vi.mock('@/features/inventory/Actions/lookupPartByBarcode', () => ({
+  lookupPartByBarcode: vi.fn(),
+}))
+vi.mock('@/features/sms/Actions/smsActions', () => ({ getSmsTemplates: vi.fn() }))
+vi.mock('@/lib/analytics', () => ({ track: vi.fn() }))
+vi.mock('@/components/confirm-dialog', () => ({ useConfirm: () => vi.fn() }))
+vi.mock('@/hooks/use-hardware-scanner', () => ({ useHardwareScanner: () => undefined }))
+vi.mock('@/hooks/use-save-shortcut', () => ({ useSaveShortcut: () => undefined }))
+vi.mock('@/features/realtime/hooks', () => ({ useLiveRecord: () => undefined }))
+
+const { passThrough } = vi.hoisted(() => ({
+  passThrough: ({ children }: { children?: React.ReactNode }) => children,
+}))
+vi.mock('@/features/settings/Components/ShopFeeContext', () => ({ ShopFeeProvider: passThrough }))
+vi.mock('@/features/settings/Components/LineTaxContext', () => ({ LineTaxProvider: passThrough }))
+vi.mock('@/features/settings/Components/WorkshopTaxOffer', () => ({
+  useTaxOfferValue: () => null,
+  WorkshopTaxOfferProvider: passThrough,
+}))
+vi.mock('@/features/fault-codes/Components/FaultCodesOnJob', () => ({
+  FaultCodesJobProvider: passThrough,
+}))
+vi.mock('@/components/document-lock-banner', () => ({ DocumentLockBanner: () => null }))
+vi.mock('@/features/vehicles/Components/service-page/InvoiceDesignMenu', () => ({
+  InvoiceDesignMenu: () => null,
+}))
+vi.mock('@/features/vehicles/Components/service-page/PayCodeButton', () => ({
+  PayCodeButton: () => null,
+}))
+vi.mock('@/features/messaging/Components/SendDocumentDialog', () => ({
+  SendDocumentDialog: () => null,
+}))
+vi.mock('@/features/vehicles/Components/service-detail/ImageCarousel', () => ({
+  ImageCarousel: () => null,
+}))
+vi.mock('@/features/vehicles/Components/service-detail/ShareDialog', () => ({
+  ShareDialog: () => null,
+}))
+vi.mock('@/components/notify-customer-dialog', () => ({ NotifyCustomerDialog: () => null }))
+vi.mock('@/components/pdf-preview-dialog', () => ({ PdfPreviewDialog: () => null }))
+vi.mock('@/features/vehicles/Components/service-edit/InventoryPickerDialog', () => ({
+  InventoryPickerDialog: () => null,
+}))
+vi.mock('@/components/barcode-scanner-dialog', () => ({ BarcodeScannerDialog: () => null }))
+vi.mock('@/features/labor-presets/Components/LaborPresetPickerDialog', () => ({
+  LaborPresetPickerDialog: () => null,
+}))
+vi.mock('@/features/status-reports/Components/StatusReportList', () => ({
+  StatusReportList: () => null,
+}))
+vi.mock('@/features/vehicles/Components/service-page/ServiceHeaderActions', () => ({
+  ServiceHeaderActions: () => null,
+}))
+vi.mock('@/features/vehicles/Components/service-page/LaborAddedBanner', () => ({
+  LaborAddedBanner: () => null,
+}))
+vi.mock('@/features/vehicles/Components/service-page/LeaveUnsavedDialog', () => ({
+  LeaveUnsavedDialog: () => null,
+}))
+vi.mock('@/features/realtime/Components/PresenceChips', () => ({ PresenceChips: () => null }))
+
+type Line = { description: string }
+
+/** The payments form's signal, as the details hand it to the payments section. */
+vi.mock('@/features/vehicles/Components/service-page/modern/ModernDetails', () => ({
+  ModernDetails: ({ paymentSignal }: { paymentSignal: number }) => (
+    <output data-testid="payment-form-opened">{paymentSignal}</output>
+  ),
+}))
+vi.mock('@/features/vehicles/Components/service-page/ObservationsManager', () => ({
+  ObservationsManager: () => null,
+}))
+
+/** The form state, with real lines and nothing else the page needs here. */
+vi.mock('@/features/vehicles/Components/service-page/useServiceFormState', () => ({
+  useServiceFormState: () => {
+    const [laborItems, setLaborItems] = useState<Line[]>([])
+    return {
+      laborItems,
+      dirtySetLaborItems: setLaborItems,
+      dirtySetPartItems: vi.fn(),
+      dirtySetType: vi.fn(),
+      concerns: [],
+      status: 'pending',
+      paymentStatus: paymentStatus.value,
+      taxRate: 0,
+      type: 'repair',
+      warranty: { warrantyStatus: 'none' },
+      vehicleName: '2019 Volvo V70',
+      hasUnsavedChanges: false,
+      isDirty: () => false,
+      loading: false,
+      showSaved: false,
+      balanceDue: 0,
+      formRef: { current: null },
+      blockedLeave: null,
+      laborAddedElsewhere: [],
+      partsAddedElsewhere: [],
+      imageAttachments: [],
+      showPresetPicker: false,
+      showInventoryPicker: false,
+      showBarcodeScanner: false,
+      setShowPresetPicker: vi.fn(),
+      setShowInventoryPicker: vi.fn(),
+      setShowBarcodeScanner: vi.fn(),
+      setStatus: vi.fn(),
+      markDirty: vi.fn(),
+      flashSaved: vi.fn(),
+      saveNow: vi.fn(),
+      stayOnPage: vi.fn(),
+      leaveWithoutSaving: vi.fn(),
+      applyLaborAddedElsewhere: vi.fn(),
+      applyPartsAddedElsewhere: vi.fn(),
+    }
+  },
+}))
+vi.mock('@/features/vehicles/Components/service-page/useServiceActions', () => ({
+  useServiceActions: () => ({
+    carouselIndex: null,
+    setCarouselIndex: vi.fn(),
+    downloading: false,
+    handleDelete: vi.fn(),
+    handleDownloadPDF: vi.fn(),
+    handleSubmit: vi.fn(),
+    saveNow: vi.fn(),
+    paymentNotifyMessage: '',
+    showPaymentNotifyDialog: false,
+    setShowPaymentNotifyDialog: vi.fn(),
+    showEmailDialog: false,
+    setShowEmailDialog: vi.fn(),
+    showShareDialog: false,
+    setShowShareDialog: vi.fn(),
+  }),
+}))
+
+import { ServicePageClient } from '@/features/vehicles/Components/service-page/ServicePageClient'
+import { canTakePayments } from '@/lib/billing-access'
+
+function renderPage({
+  canTakePayment = true,
+  locked = false,
+}: {
+  canTakePayment?: boolean
+  locked?: boolean
+} = {}) {
+  const props = {
+    record: {
+      id: 'job1',
+      title: 'Annual service',
+      invoiceNumber: 'WO-1001',
+      customer: null,
+      vehicle: { id: 'v1', year: 2019, make: 'Volvo', model: 'V70', customer: null },
+      publicToken: null,
+    },
+    vehicleId: 'v1',
+    organizationId: 'org1',
+    lockState: { locked, unlockedAt: null },
+    canUnlock: false,
+    canTakePayment,
+    currencyCode: 'NOK',
+    unitSystem: 'metric',
+    initialData: { invoiceDate: null, invoiceDueDate: null },
+    openObservations: [],
+  }
+  // Only what this part of the page reads is given.
+  render(<ServicePageClient {...(props as unknown as Parameters<typeof ServicePageClient>[0])} />)
+}
+
+const opened = () => screen.getByTestId('payment-form-opened').textContent
+
+describe('the payment pill in the work order header', () => {
+  beforeEach(() => {
+    paymentStatus.value = 'unpaid'
+  })
+
+  it('opens the payment form when the job is unpaid and the viewer may take payments', async () => {
+    renderPage()
+    const pill = screen.getByRole('button', { name: 'Unpaid: Take payment' })
+    expect(opened()).toBe('0')
+
+    await act(async () => {
+      fireEvent.click(pill)
+    })
+
+    expect(opened()).toBe('1')
+  })
+
+  it('does the same for a job paid in part, which still has a balance', () => {
+    paymentStatus.value = 'partial'
+    renderPage()
+    expect(screen.getByRole('button', { name: 'Partial: Take payment' })).toBeTruthy()
+  })
+
+  it('only reads for somebody who may not record a payment', () => {
+    renderPage({ canTakePayment: false })
+    expect(screen.queryByRole('button', { name: /Take payment/ })).toBeNull()
+    expect(screen.getByTestId('service-payment').tagName).toBe('SPAN')
+    expect(screen.getByTestId('service-payment').textContent).toBe('Unpaid')
+  })
+
+  it('only reads once the job is paid', () => {
+    paymentStatus.value = 'paid'
+    renderPage()
+    expect(screen.queryByRole('button', { name: /Take payment/ })).toBeNull()
+    expect(screen.getByTestId('service-payment').tagName).toBe('SPAN')
+    expect(screen.getByTestId('service-payment').textContent).toBe('Paid')
+  })
+
+  it('offers nothing on a locked invoice', () => {
+    renderPage({ locked: true })
+    expect(screen.queryByRole('button', { name: /Take payment/ })).toBeNull()
+    expect(screen.getByTestId('service-payment').tagName).toBe('SPAN')
+  })
+
+  it('reads as a label when it only reads: no outline, no hand cursor', () => {
+    paymentStatus.value = 'paid'
+    renderPage()
+    const pill = screen.getByTestId('service-payment')
+    expect(pill.className).toContain('border-transparent')
+    expect(pill.className).toContain('cursor-default')
+  })
+})
+
+describe('the status pill in the work order header', () => {
+  it('is a label, not a control, whoever is looking and however the job stands', () => {
+    for (const options of [{}, { locked: true }, { canTakePayment: false }]) {
+      renderPage(options)
+      const status = screen.getByTestId('service-status')
+      expect(status.tagName).toBe('SPAN')
+      expect(status.textContent).toBe('Pending')
+      expect(status.className).toContain('border-transparent')
+      expect(status.className).toContain('cursor-default')
+      cleanup()
+    }
+  })
+
+  it('leaves the type dropdown as the box in the row that opens something', () => {
+    renderPage()
+    expect(screen.getByRole('combobox', { name: 'Type' })).toBeTruthy()
+  })
+})
+
+describe('who may take payments', () => {
+  it('lets owners and admins through', async () => {
+    expect(await canTakePayments({ userId: 'u1', isAdmin: true })).toBe(true)
+  })
+
+  it('needs CREATE on billing from a custom role', async () => {
+    membership.value = {
+      customRole: { isAdmin: false, permissions: [{ action: 'create', subject: 'billing' }] },
+    }
+    expect(await canTakePayments({ userId: 'u1', isAdmin: false })).toBe(true)
+    membership.value = {
+      customRole: { isAdmin: false, permissions: [{ action: 'read', subject: 'billing' }] },
+    }
+    expect(await canTakePayments({ userId: 'u1', isAdmin: false })).toBe(false)
+  })
+
+  it('gives a member with no role nothing, as the server does', async () => {
+    membership.value = { customRole: null }
+    expect(await canTakePayments({ userId: 'u1', isAdmin: false })).toBe(false)
+    expect(await canTakePayments(null)).toBe(false)
+  })
+})

+ 9 - 0
src/features/vehicles/Components/service-page/ServicePageClient.tsx

@@ -91,6 +91,7 @@ export function ServicePageClient({
   workOrderStatuses = [],
   workOrderStatuses = [],
   canAddStatus = false,
   canAddStatus = false,
   canSetCustomer = false,
   canSetCustomer = false,
+  canTakePayment = false,
   videoCall = { link: null, providers: [] },
   videoCall = { link: null, providers: [] },
   tireThresholds,
   tireThresholds,
   defaultTaxRate,
   defaultTaxRate,
@@ -175,6 +176,10 @@ export function ServicePageClient({
   // the page holds it and the form carries it as a hidden field. It follows
   // the page holds it and the form carries it as a hidden field. It follows
   // the record again after every save.
   // the record again after every save.
   const [title, setTitle] = useState(record.title)
   const [title, setTitle] = useState(record.title)
+  // Bumped by "Take payment" in the money bar and by "Unpaid" in the header:
+  // the payments form opens and scrolls into view.
+  const [paymentSignal, setPaymentSignal] = useState(0)
+  const takePayment = useCallback(() => setPaymentSignal((n) => n + 1), [])
   useEffect(() => {
   useEffect(() => {
     setTitle(record.title)
     setTitle(record.title)
   }, [record.title])
   }, [record.title])
@@ -678,6 +683,8 @@ export function ServicePageClient({
               type={record.vehicle ? formState.type : undefined}
               type={record.vehicle ? formState.type : undefined}
               onTypeChange={formState.dirtySetType}
               onTypeChange={formState.dirtySetType}
               locked={lockState.locked}
               locked={lockState.locked}
+              // Not on a locked invoice: the header offers nothing there.
+              onTakePayment={canTakePayment && !lockState.locked ? takePayment : undefined}
             />
             />
 
 
             <LaborAddedBanner
             <LaborAddedBanner
@@ -725,6 +732,8 @@ export function ServicePageClient({
                   workOrderStatuses={workOrderStatuses}
                   workOrderStatuses={workOrderStatuses}
                   canAddStatus={canAddStatus}
                   canAddStatus={canAddStatus}
                   canSetCustomer={canSetCustomer}
                   canSetCustomer={canSetCustomer}
+                  paymentSignal={paymentSignal}
+                  onTakePayment={takePayment}
                   onNotifyForStatus={handleNotifyForStatus}
                   onNotifyForStatus={handleNotifyForStatus}
                   locked={lockState.locked}
                   locked={lockState.locked}
                   lockedLabel={t('invoice.lockedFieldsetLabel')}
                   lockedLabel={t('invoice.lockedFieldsetLabel')}

+ 4 - 0
src/features/vehicles/Components/service-page/ServiceRecordPage.tsx

@@ -49,6 +49,7 @@ import { invoiceDesignPrintsConditionMap } from '@/features/invoices/Lib/assembl
 import { getCachedSession, getCachedMembership } from '@/lib/cached-session'
 import { getCachedSession, getCachedMembership } from '@/lib/cached-session'
 import { canEditSettings } from '@/lib/settings-access'
 import { canEditSettings } from '@/lib/settings-access'
 import { canEditVehicles } from '@/lib/vehicle-access'
 import { canEditVehicles } from '@/lib/vehicle-access'
+import { canTakePayments } from '@/lib/billing-access'
 import { ServicePageClient } from '@/features/vehicles/Components/service-page/ServicePageClient'
 import { ServicePageClient } from '@/features/vehicles/Components/service-page/ServicePageClient'
 import { listDesignOptions } from '@/features/invoice-designer/Actions/documentDesignActions'
 import { listDesignOptions } from '@/features/invoice-designer/Actions/documentDesignActions'
 import { rendersFromIssue } from '@/features/invoices/Lib/issuedInvoice'
 import { rendersFromIssue } from '@/features/invoices/Lib/issuedInvoice'
@@ -192,6 +193,8 @@ export async function ServiceRecordPage({
   const canAddStatus = await canEditSettings(session?.user?.id ?? '', membership?.role)
   const canAddStatus = await canEditSettings(session?.user?.id ?? '', membership?.role)
   // Whether a job whose vehicle has no owner offers to add one.
   // Whether a job whose vehicle has no owner offers to add one.
   const canSetCustomer = await canEditVehicles(authContext)
   const canSetCustomer = await canEditVehicles(authContext)
+  // Whether the header's "Unpaid" opens the payment form.
+  const canTakePayment = await canTakePayments(authContext)
 
 
   const [currentUser, features, aiProvider, dictation, tireHotel] = await Promise.all([
   const [currentUser, features, aiProvider, dictation, tireHotel] = await Promise.all([
     session?.user?.id
     session?.user?.id
@@ -514,6 +517,7 @@ export async function ServiceRecordPage({
         onlinePayments={onlinePayments}
         onlinePayments={onlinePayments}
         canAddStatus={canAddStatus}
         canAddStatus={canAddStatus}
         canSetCustomer={canSetCustomer}
         canSetCustomer={canSetCustomer}
+        canTakePayment={canTakePayment}
         workOrderStatuses={
         workOrderStatuses={
           workOrderStatusesResult.success && workOrderStatusesResult.data
           workOrderStatusesResult.success && workOrderStatusesResult.data
             ? workOrderStatusesResult.data
             ? workOrderStatusesResult.data

+ 5 - 4
src/features/vehicles/Components/service-page/modern/ModernDetails.tsx

@@ -51,6 +51,9 @@ export interface ModernDetailsProps
   canAddStatus?: boolean
   canAddStatus?: boolean
   /** The viewer may edit vehicles, so an empty Customer box offers to add one. */
   /** The viewer may edit vehicles, so an empty Customer box offers to add one. */
   canSetCustomer?: boolean
   canSetCustomer?: boolean
+  /** Bumped by every "Take payment", the money bar's and the header's: the payments form opens. */
+  paymentSignal: number
+  onTakePayment: () => void
   /** Offers to tell the customer about a status that asks for it. */
   /** Offers to tell the customer about a status that asks for it. */
   onNotifyForStatus?: (status: WorkOrderStatusOption) => void
   onNotifyForStatus?: (status: WorkOrderStatusOption) => void
   /**
   /**
@@ -151,8 +154,6 @@ export function ModernDetails(props: ModernDetailsProps) {
   // comes back. It is asked about, not refused: a routine service has nothing
   // comes back. It is asked about, not refused: a routine service has nothing
   // to confirm, and a shop may know better than the tick does.
   // to confirm, and a shop may know better than the tick does.
   const confirmUnconfirmed = useConfirm()
   const confirmUnconfirmed = useConfirm()
-  // Bumped by the bar's "Take payment": the payments form opens and scrolls into view.
-  const [paymentSignal, setPaymentSignal] = useState(0)
   // The workshop's own status the job carries. Held here as well as on the
   // The workshop's own status the job carries. Held here as well as on the
   // record so the stepper answers at once, before the page has been re-read.
   // record so the stepper answers at once, before the page has been re-read.
   const [customStatus, setCustomStatus] = useState(record.customStatus ?? null)
   const [customStatus, setCustomStatus] = useState(record.customStatus ?? null)
@@ -580,7 +581,7 @@ export function ModernDetails(props: ModernDetailsProps) {
                       onTogglePaid={actions.handleTogglePaid}
                       onTogglePaid={actions.handleTogglePaid}
                       paymentLoading={actions.paymentLoading}
                       paymentLoading={actions.paymentLoading}
                       deletingPayment={actions.deletingPayment}
                       deletingPayment={actions.deletingPayment}
-                      openFormSignal={paymentSignal}
+                      openFormSignal={props.paymentSignal}
                       extraAction={props.payCode}
                       extraAction={props.payCode}
                     />
                     />
                   </div>
                   </div>
@@ -655,7 +656,7 @@ export function ModernDetails(props: ModernDetailsProps) {
         paid={formState.totalPaid}
         paid={formState.totalPaid}
         balance={formState.balanceDue}
         balance={formState.balanceDue}
         currencyCode={currencyCode}
         currencyCode={currencyCode}
-        onTakePayment={() => setPaymentSignal((n) => n + 1)}
+        onTakePayment={props.onTakePayment}
         payCode={props.payCode}
         payCode={props.payCode}
         onPreview={props.onPreviewInvoice}
         onPreview={props.onPreviewInvoice}
         onSend={props.onSendToCustomer}
         onSend={props.onSendToCustomer}

+ 51 - 15
src/features/vehicles/Components/service-page/modern/ModernHero.tsx

@@ -5,7 +5,7 @@ import { isPromiseOverdue } from '@/features/vehicles/Lib/promise'
 import Link from 'next/link'
 import Link from 'next/link'
 import { useTranslations } from 'next-intl'
 import { useTranslations } from 'next-intl'
 import { Fragment, useState, type ReactNode } from 'react'
 import { Fragment, useState, type ReactNode } from 'react'
-import { ArrowLeft, CalendarClock, ClipboardCheck, Pencil, Shield } from 'lucide-react'
+import { ArrowLeft, CalendarClock, ClipboardCheck, CreditCard, Pencil, Shield } from 'lucide-react'
 import {
 import {
   Select,
   Select,
   SelectContent,
   SelectContent,
@@ -40,6 +40,12 @@ interface ModernHeroProps {
   onTypeChange?: (type: string) => void
   onTypeChange?: (type: string) => void
   /** A locked invoice shows the title and type and edits neither. */
   /** A locked invoice shows the title and type and edits neither. */
   locked?: boolean
   locked?: boolean
+  /**
+   * The page's "Take payment", for somebody who may record one. Given, an
+   * unpaid or part-paid job's payment pill is a button that opens the payment
+   * form; absent (no permission, a locked invoice), the pill only reads.
+   */
+  onTakePayment?: () => void
 }
 }
 
 
 /** How much of a title the header shows before it is cut. */
 /** How much of a title the header shows before it is cut. */
@@ -171,6 +177,14 @@ const factLink =
 const pill =
 const pill =
   'inline-flex h-6 items-center gap-1 whitespace-nowrap rounded-md border px-2.5 text-xs font-semibold leading-none'
   'inline-flex h-6 items-center gap-1 whitespace-nowrap rounded-md border px-2.5 text-xs font-semibold leading-none'
 
 
+/**
+ * A pill that only says something: its tint and no outline, and the ordinary
+ * arrow. The type dropdown beside it is the box with a border and a chevron,
+ * and the pills that looked like it drew clicks that did nothing. The tint
+ * comes first so the transparent border wins over the one in its colour.
+ */
+const plainPill = (tint: string) => cn(pill, tint, 'cursor-default border-transparent')
+
 /**
 /**
  * The top of the overhauled page, and the only header it has: the work order
  * The top of the overhauled page, and the only header it has: the work order
  * number and how far along the job is, then what the job is and who and what
  * number and how far along the job is, then what the job is and who and what
@@ -191,6 +205,7 @@ export function ModernHero({
   type,
   type,
   onTypeChange,
   onTypeChange,
   locked = false,
   locked = false,
+  onTakePayment,
 }: ModernHeroProps) {
 }: ModernHeroProps) {
   const t = useTranslations('service')
   const t = useTranslations('service')
   const { formatDate, formatDateTime } = useFormatDate()
   const { formatDate, formatDateTime } = useFormatDate()
@@ -220,6 +235,8 @@ export function ModernHero({
   // One rule for the header, the work order list and the board card.
   // One rule for the header, the work order list and the board card.
   const promiseOverdue = isPromiseOverdue(record.promisedAt, status)
   const promiseOverdue = isPromiseOverdue(record.promisedAt, status)
 
 
+  const paymentLabel = paymentStatusLabels[paymentStatus] || t('header.unpaid')
+
   const warrantyLabel =
   const warrantyLabel =
     warranty.warrantyStatus === 'included'
     warranty.warrantyStatus === 'included'
       ? warranty.warrantyMonths
       ? warranty.warrantyMonths
@@ -258,9 +275,11 @@ export function ModernHero({
                   {number ?? titleEditor}
                   {number ?? titleEditor}
                 </h1>
                 </h1>
                 <div className="flex flex-wrap items-center gap-1.5">
                 <div className="flex flex-wrap items-center gap-1.5">
+                  {/* Read only. Its stage is changed on the status stepper below,
+                    which has the menus. */}
                   <span
                   <span
                     // The status's own colour, the one it has in every list.
                     // The status's own colour, the one it has in every list.
-                    className={cn(pill, statusBadgeClass('workOrder', status))}
+                    className={plainPill(statusBadgeClass('workOrder', status))}
                     data-status={status}
                     data-status={status}
                     data-testid="service-status"
                     data-testid="service-status"
                   >
                   >
@@ -268,9 +287,32 @@ export function ModernHero({
                       ? t(`basicInfo.statusOptions.${statusMessageKeys[status]}`)
                       ? t(`basicInfo.statusOptions.${statusMessageKeys[status]}`)
                       : status}
                       : status}
                   </span>
                   </span>
-                  <span className={cn(pill, paymentStatusColors[paymentStatus])}>
-                    {paymentStatusLabels[paymentStatus] || t('header.unpaid')}
-                  </span>
+                  {onTakePayment && paymentStatus !== 'paid' ? (
+                    // What is owed is the thing to do something about: the
+                    // same "Take payment" as the money bar along the bottom.
+                    <button
+                      type="button"
+                      data-testid="service-payment"
+                      aria-label={`${paymentLabel}: ${t('modern.moneyBar.takePayment')}`}
+                      title={t('modern.moneyBar.takePayment')}
+                      onClick={onTakePayment}
+                      className={cn(
+                        pill,
+                        paymentStatusColors[paymentStatus],
+                        'cursor-pointer transition-colors hover:border-primary hover:bg-primary/10 hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'
+                      )}
+                    >
+                      <CreditCard className="h-3 w-3" aria-hidden="true" />
+                      {paymentLabel}
+                    </button>
+                  ) : (
+                    <span
+                      data-testid="service-payment"
+                      className={plainPill(paymentStatusColors[paymentStatus] ?? '')}
+                    >
+                      {paymentLabel}
+                    </span>
+                  )}
                   {type && onTypeChange && (
                   {type && onTypeChange && (
                     <Select value={type} onValueChange={onTypeChange} disabled={locked}>
                     <Select value={type} onValueChange={onTypeChange} disabled={locked}>
                       <SelectTrigger
                       <SelectTrigger
@@ -295,11 +337,10 @@ export function ModernHero({
                     <span
                     <span
                       data-testid="service-promised"
                       data-testid="service-promised"
                       suppressHydrationWarning
                       suppressHydrationWarning
-                      className={cn(
-                        pill,
+                      className={plainPill(
                         promiseOverdue
                         promiseOverdue
-                          ? 'border-amber-500/40 bg-amber-500/15 text-amber-700 dark:text-amber-300'
-                          : 'border-border text-muted-foreground'
+                          ? 'bg-amber-500/15 text-amber-700 dark:text-amber-300'
+                          : 'bg-muted text-muted-foreground'
                       )}
                       )}
                     >
                     >
                       <CalendarClock className="h-3 w-3" aria-hidden="true" />
                       <CalendarClock className="h-3 w-3" aria-hidden="true" />
@@ -309,12 +350,7 @@ export function ModernHero({
                     </span>
                     </span>
                   )}
                   )}
                   {warrantyLabel && (
                   {warrantyLabel && (
-                    <span
-                      className={cn(
-                        pill,
-                        'border-teal-600/25 bg-teal-600/10 text-teal-700 dark:text-teal-300'
-                      )}
-                    >
+                    <span className={plainPill('bg-teal-600/10 text-teal-700 dark:text-teal-300')}>
                       <Shield className="h-3 w-3" aria-hidden="true" />
                       <Shield className="h-3 w-3" aria-hidden="true" />
                       {t('warranty.title')} · {warrantyLabel}
                       {t('warranty.title')} · {warrantyLabel}
                     </span>
                     </span>

+ 2 - 0
src/features/vehicles/Components/service-page/service-page-types.ts

@@ -134,6 +134,8 @@ export interface ServicePageClientProps {
   canAddStatus?: boolean
   canAddStatus?: boolean
   /** The viewer may edit vehicles, so an empty Customer box offers to add one. */
   /** The viewer may edit vehicles, so an empty Customer box offers to add one. */
   canSetCustomer?: boolean
   canSetCustomer?: boolean
+  /** The viewer may record payments, so the header's "Unpaid" opens the payment form. */
+  canTakePayment?: boolean
   /** The work order's video call, and the connected services that could add one. */
   /** The work order's video call, and the connected services that could add one. */
   videoCall?: ServiceVideoCall
   videoCall?: ServiceVideoCall
   /** The workshop's tread limits, so a set checked in here grades correctly. */
   /** The workshop's tread limits, so a set checked in here grades correctly. */

+ 24 - 0
src/lib/billing-access.ts

@@ -0,0 +1,24 @@
+import { getCachedMembership } from '@/lib/cached-session'
+import { hasAllPermissions, PermissionAction, PermissionSubject } from '@/lib/permissions'
+import type { AuthContext } from '@/lib/with-auth'
+
+/**
+ * Whether this person may record a payment on a job. The answer `withAuth`
+ * gives `createPayment`, asked ahead of time so a page does not offer a
+ * button that would be refused.
+ *
+ * As in `withAuth`: super admins, owners, admins and custom roles marked as
+ * admin always pass. Everyone else needs CREATE on billing from their custom
+ * role, and a member with no custom role has no permissions.
+ */
+export async function canTakePayments(
+  context: Pick<AuthContext, 'userId' | 'isAdmin'> | null | undefined
+): Promise<boolean> {
+  if (!context) return false
+  if (context.isAdmin) return true
+
+  const membership = await getCachedMembership(context.userId)
+  return hasAllPermissions(membership?.customRole?.permissions ?? [], [
+    { action: PermissionAction.CREATE, subject: PermissionSubject.BILLING },
+  ])
+}