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

Refuse a payment larger than the balance due (#680)

* Refuse a payment larger than the balance due

* Check and send one rounded payment amount, and free the payment buttons when the save before it fails
Bernt Christian Egeland 3 дней назад
Родитель
Сommit
c05c605d58

+ 2 - 0
messages/bg/service.json

@@ -374,6 +374,8 @@
     "received": "Получени плащания",
     "noneYet": "Все още няма плащания.",
     "balanceDue": "Оставаща сума",
+    "aboveBalance": "Оставащата сума е {amount}. Плащането не може да е по-голямо от нея.",
+    "nothingDue": "По тази фактура няма дължима сума.",
     "refund": "Възстановяване"
   },
   "attachments": {

+ 2 - 0
messages/de/service.json

@@ -374,6 +374,8 @@
     "received": "Erhaltene Zahlungen",
     "noneYet": "Noch nichts bezahlt.",
     "balanceDue": "Ausstehend",
+    "aboveBalance": "Offen sind {amount}. Eine Zahlung darf nicht höher sein.",
+    "nothingDue": "Auf dieser Rechnung ist nichts mehr offen.",
     "refund": "Erstattung"
   },
   "attachments": {

+ 2 - 0
messages/en/service.json

@@ -374,6 +374,8 @@
     "received": "Payments received",
     "noneYet": "Nothing paid yet.",
     "balanceDue": "Balance due",
+    "aboveBalance": "The balance due is {amount}. A payment cannot be more than that.",
+    "nothingDue": "Nothing is due on this invoice.",
     "refund": "Refund"
   },
   "attachments": {

+ 2 - 0
messages/es/service.json

@@ -374,6 +374,8 @@
     "received": "Pagos recibidos",
     "noneYet": "Todavía no se ha pagado nada.",
     "balanceDue": "Saldo pendiente",
+    "aboveBalance": "El saldo pendiente es {amount}. Un pago no puede superarlo.",
+    "nothingDue": "No hay nada pendiente en esta factura.",
     "refund": "Reembolso"
   },
   "attachments": {

+ 2 - 0
messages/fr/service.json

@@ -374,6 +374,8 @@
     "received": "Paiements reçus",
     "noneYet": "Rien de payé pour l'instant.",
     "balanceDue": "Solde dû",
+    "aboveBalance": "Le solde dû est de {amount}. Un paiement ne peut pas le dépasser.",
+    "nothingDue": "Rien n’est dû sur cette facture.",
     "refund": "Remboursement"
   },
   "attachments": {

+ 2 - 0
messages/it/service.json

@@ -374,6 +374,8 @@
     "received": "Pagamenti ricevuti",
     "noneYet": "Ancora nessun pagamento.",
     "balanceDue": "Importo dovuto",
+    "aboveBalance": "L’importo dovuto è {amount}. Un pagamento non può superarlo.",
+    "nothingDue": "Non c’è nulla da pagare su questa fattura.",
     "refund": "Rimborso"
   },
   "attachments": {

+ 2 - 0
messages/lt/service.json

@@ -374,6 +374,8 @@
     "received": "Gauti mokėjimai",
     "noneYet": "Dar nieko nesumokėta.",
     "balanceDue": "Mokėtina suma",
+    "aboveBalance": "Mokėtina suma yra {amount}. Mokėjimas negali būti didesnis.",
+    "nothingDue": "Pagal šią sąskaitą nieko nebeliko mokėti.",
     "refund": "Grąžinimas"
   },
   "attachments": {

+ 2 - 0
messages/nb/service.json

@@ -374,6 +374,8 @@
     "received": "Mottatte betalinger",
     "noneYet": "Ingenting betalt ennå.",
     "balanceDue": "Utestående",
+    "aboveBalance": "Utestående er {amount}. En betaling kan ikke være høyere enn det.",
+    "nothingDue": "Det er ingenting utestående på denne fakturaen.",
     "refund": "Refusjon"
   },
   "attachments": {

+ 2 - 0
messages/nl/service.json

@@ -374,6 +374,8 @@
     "received": "Ontvangen betalingen",
     "noneYet": "Nog niets betaald.",
     "balanceDue": "Verschuldigd bedrag",
+    "aboveBalance": "Het verschuldigde bedrag is {amount}. Een betaling kan niet hoger zijn.",
+    "nothingDue": "Er staat niets meer open op deze factuur.",
     "refund": "Terugbetaling"
   },
   "attachments": {

+ 2 - 0
messages/pl/service.json

@@ -374,6 +374,8 @@
     "received": "Otrzymane płatności",
     "noneYet": "Nic jeszcze nie zapłacono.",
     "balanceDue": "Pozostało do zapłaty",
+    "aboveBalance": "Do zapłaty pozostało {amount}. Płatność nie może być wyższa.",
+    "nothingDue": "Na tej fakturze nie ma nic do zapłaty.",
     "refund": "Zwrot"
   },
   "attachments": {

+ 2 - 0
messages/pt-BR/service.json

@@ -374,6 +374,8 @@
     "received": "Pagamentos recebidos",
     "noneYet": "Nada pago ainda.",
     "balanceDue": "Saldo devedor",
+    "aboveBalance": "O saldo devedor é {amount}. Um pagamento não pode ser maior que isso.",
+    "nothingDue": "Não há nada a pagar nesta fatura.",
     "refund": "Reembolso"
   },
   "attachments": {

+ 2 - 0
messages/pt-PT/service.json

@@ -374,6 +374,8 @@
     "received": "Pagamentos recebidos",
     "noneYet": "Ainda nada pago.",
     "balanceDue": "Valor em dívida",
+    "aboveBalance": "O valor em dívida é {amount}. Um pagamento não pode ser superior.",
+    "nothingDue": "Não há nada em dívida nesta fatura.",
     "refund": "Reembolso"
   },
   "attachments": {

+ 2 - 0
messages/ru/service.json

@@ -374,6 +374,8 @@
     "received": "Полученные платежи",
     "noneYet": "Оплат пока нет.",
     "balanceDue": "К оплате",
+    "aboveBalance": "К оплате {amount}. Платёж не может быть больше этой суммы.",
+    "nothingDue": "По этому счёту ничего не причитается.",
     "refund": "Возврат"
   },
   "attachments": {

+ 2 - 0
messages/tr/service.json

@@ -374,6 +374,8 @@
     "received": "Alınan ödemeler",
     "noneYet": "Henüz ödeme yapılmadı.",
     "balanceDue": "Kalan bakiye",
+    "aboveBalance": "Kalan bakiye {amount}. Ödeme bundan fazla olamaz.",
+    "nothingDue": "Bu faturada ödenecek bir şey kalmadı.",
     "refund": "İade"
   },
   "attachments": {

+ 97 - 0
src/__tests__/app/api/webhooks-overpayment.test.ts

@@ -0,0 +1,97 @@
+/**
+ * @vitest-environment node
+ *
+ * A payment the provider has already taken is booked in full, even when it
+ * is more than the invoice still owes. The desk's payment form refuses an
+ * amount above the balance; a customer's card has been charged by then, and
+ * dropping that row would lose real money from the books. The webhooks go
+ * through recordVendorPayment, which writes what the provider confirmed
+ * without asking for the balance.
+ */
+import { createHmac } from 'node:crypto'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const { db, payments, verifyPayment } = vi.hoisted(() => ({
+  db: {
+    serviceRecord: { findUnique: vi.fn(), findFirst: vi.fn() },
+    payment: { createManyAndReturn: vi.fn(), findFirst: vi.fn(), aggregate: vi.fn() },
+    $transaction: vi.fn(),
+    $queryRaw: vi.fn(),
+  },
+  payments: { paymentProviderFor: vi.fn() },
+  verifyPayment: vi.fn(),
+}))
+
+vi.mock('@/lib/backup/freeze', () => ({
+  isRestoring: vi.fn(() => false),
+  RESTORE_IN_PROGRESS_MESSAGE: 'A restore of this workshop is in progress.',
+}))
+vi.mock('@/lib/db', () => ({ db }))
+vi.mock('@/features/integrations/Lib/payments', () => payments)
+vi.mock('@/lib/payment-providers/paystack', async (importOriginal) => {
+  const actual = await importOriginal<typeof import('@/lib/payment-providers/paystack')>()
+  return {
+    ...actual,
+    PaystackProvider: class {
+      lookup(reference: string) {
+        return verifyPayment(reference)
+      }
+    },
+  }
+})
+
+import { POST } from '@/app/api/webhooks/paystack/route'
+
+const ORG = 'org_1'
+const KEY = 'sk_test_workshop'
+
+function post() {
+  const body = JSON.stringify({
+    event: 'charge.success',
+    data: { reference: 'inv-sr_1-1', metadata: { serviceRecordId: 'sr_1', orgId: ORG } },
+  })
+  return POST(
+    new Request('http://app.test/api/webhooks/paystack', {
+      method: 'POST',
+      headers: {
+        'content-type': 'application/json',
+        'x-paystack-signature': createHmac('sha512', KEY).update(body).digest('hex'),
+      },
+      body,
+    })
+  )
+}
+
+beforeEach(() => {
+  vi.clearAllMocks()
+  db.serviceRecord.findUnique.mockResolvedValue({ id: 'sr_1', organizationId: ORG })
+  // The invoice owes £552.74 and has £500 against it already.
+  db.serviceRecord.findFirst.mockResolvedValue({ id: 'sr_1', totalAmount: 552.74, cost: 0 })
+  db.payment.aggregate.mockResolvedValue({ _sum: { amount: 500 } })
+  db.payment.createManyAndReturn.mockResolvedValue([{ id: 'pay_1' }])
+  payments.paymentProviderFor.mockResolvedValue({
+    setup: { credentials: { secretKey: KEY } },
+    provider: { verifyPayment },
+  })
+})
+
+describe('a provider-confirmed payment above the balance due', () => {
+  it('is booked for the full amount the provider took', async () => {
+    verifyPayment.mockResolvedValue({
+      paid: true,
+      amount: 1000,
+      serviceRecordId: 'sr_1',
+      organizationId: ORG,
+    })
+
+    const response = await post()
+
+    expect(response.status).toBe(200)
+    expect(db.payment.createManyAndReturn).toHaveBeenCalledWith(
+      expect.objectContaining({
+        data: [expect.objectContaining({ serviceRecordId: 'sr_1', amount: 1000 })],
+      })
+    )
+    expect(db.$transaction).not.toHaveBeenCalled()
+  })
+})

+ 7 - 1
src/__tests__/features/meters/required-meters-paths.test.ts

@@ -77,8 +77,9 @@ vi.mock('@/lib/db', () => ({
       updateMany: vi.fn(),
     },
     servicePart: { findMany: vi.fn() },
-    payment: { create: vi.fn() },
+    payment: { create: vi.fn(), aggregate: vi.fn() },
     $transaction: vi.fn(),
+    $queryRaw: vi.fn(),
   },
 }))
 
@@ -323,6 +324,11 @@ describe('handing the invoice over', () => {
 describe('money, with a required reading missing', () => {
   it('a payment recorded at the desk is taken and issues the invoice as before', async () => {
     vi.mocked(db.payment.create).mockResolvedValue({ id: 'pay-1' } as never)
+    // Taken under the job's row lock, against what is still owed on it.
+    vi.mocked(db.$transaction).mockImplementation((async (cb: (tx: unknown) => unknown) =>
+      cb(db)) as never)
+    vi.mocked(db.$queryRaw).mockResolvedValue([{ totalAmount: 100, cost: 0 }] as never)
+    vi.mocked(db.payment.aggregate).mockResolvedValue({ _sum: { amount: 0 } } as never)
     const result = await createPayment({
       serviceRecordId: 'job-1',
       amount: 100,

+ 150 - 0
src/__tests__/features/payments/create-payment-balance.test.ts

@@ -0,0 +1,150 @@
+/**
+ * A payment taken at the desk may settle what is owed, never pass it.
+ *
+ * £1000 recorded against a £552.74 balance was saved, and the invoice then
+ * read "PAID IN FULL -£447.26". createPayment now reads the balance from the
+ * stored total and the payments already recorded, under the job's row lock,
+ * and refuses anything above it in the workshop's own currency.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import service from '../../../../messages/en/service.json'
+
+vi.mock('@/lib/cached-session', () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}))
+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }))
+vi.mock('@/lib/audit', () => ({ logAudit: vi.fn() }))
+vi.mock('@/features/invoices/Lib/issueInvoice', () => ({
+  issueInvoice: vi.fn().mockResolvedValue(false),
+}))
+vi.mock('@/lib/workshop-timezone', () => ({
+  workshopTimeZone: vi.fn().mockResolvedValue('Pacific/Auckland'),
+}))
+vi.mock('next-intl/server', () => ({
+  getTranslations: async (namespace: string) => {
+    const messages = (service as Record<string, unknown>)[namespace.split('.')[1]] as Record<
+      string,
+      string
+    >
+    return (key: string, values?: Record<string, string>) =>
+      Object.entries(values ?? {}).reduce(
+        (text, [name, value]) => text.replace(`{${name}}`, value),
+        messages[key]
+      )
+  },
+}))
+
+const tx = {
+  $queryRaw: vi.fn(),
+  payment: { aggregate: vi.fn(), create: vi.fn() },
+}
+vi.mock('@/lib/db', () => ({
+  db: {
+    user: { findUnique: vi.fn() },
+    appSetting: { findMany: vi.fn() },
+    serviceRecord: { findFirst: vi.fn() },
+    payment: { create: vi.fn() },
+    $transaction: vi.fn(),
+  },
+}))
+
+import { getCachedMembership, getCachedSession } from '@/lib/cached-session'
+import { db } from '@/lib/db'
+import { SETTING_KEYS } from '@/features/settings/Schema/settingsSchema'
+import { createPayment } from '@/features/payments/Actions/paymentActions'
+
+const ORG = 'org-1'
+
+/** A £552.74 invoice; `paid` is what has already been recorded against it. */
+function invoice({ total = 552.74, paid = 0 }: { total?: number; paid?: number } = {}) {
+  vi.mocked(db.serviceRecord.findFirst).mockResolvedValue({ id: 'job-1', vehicleId: 'v-1' } as any)
+  tx.$queryRaw.mockResolvedValue([{ totalAmount: total, cost: 0 }])
+  tx.payment.aggregate.mockResolvedValue({ _sum: { amount: paid } })
+}
+
+const pay = (amount: number) =>
+  createPayment({ serviceRecordId: 'job-1', amount, date: '2026-11-24', method: 'card' })
+
+beforeEach(() => {
+  vi.clearAllMocks()
+  vi.mocked(getCachedSession).mockResolvedValue({ user: { id: 'user-1' } } as any)
+  vi.mocked(getCachedMembership).mockResolvedValue({
+    organizationId: ORG,
+    role: 'owner',
+    roleId: null,
+    customRole: null,
+  } as any)
+  vi.mocked(db.user.findUnique).mockResolvedValue({ isSuperAdmin: false } as any)
+  vi.mocked(db.appSetting.findMany).mockResolvedValue([
+    { key: SETTING_KEYS.CURRENCY_CODE, value: 'GBP' },
+  ] as any)
+  vi.mocked(db.$transaction).mockImplementation(async (cb: any) => cb(tx))
+  tx.payment.create.mockImplementation(async ({ data }: any) => ({ id: 'pay-1', ...data }))
+})
+
+describe('recording a payment at the desk', () => {
+  it('refuses more than the balance due, and says how much is due', async () => {
+    invoice()
+    const result = await pay(1000)
+
+    expect(result.success).toBe(false)
+    expect(result.error).toBe('The balance due is £552.74. A payment cannot be more than that.')
+    expect(tx.payment.create).not.toHaveBeenCalled()
+  })
+
+  it('counts what has already been paid', async () => {
+    invoice({ paid: 500 })
+    const result = await pay(60)
+
+    expect(result.error).toBe('The balance due is £52.74. A payment cannot be more than that.')
+    expect(tx.payment.create).not.toHaveBeenCalled()
+  })
+
+  it('takes exactly the balance due', async () => {
+    invoice({ paid: 500 })
+    const result = await pay(52.74)
+
+    expect(result.success).toBe(true)
+    expect(tx.payment.create).toHaveBeenCalledWith({
+      data: expect.objectContaining({ serviceRecordId: 'job-1', amount: 52.74 }),
+    })
+  })
+
+  it('takes the balance of a total stored a hair off the cent, as the invoice prints it', async () => {
+    // 0.18 plus 25% was once stored as 0.22499999999999998, printed 0.22.
+    invoice({ total: 0.22499999999999998 })
+    expect((await pay(0.22)).success).toBe(true)
+  })
+
+  it('takes a part payment', async () => {
+    invoice()
+    expect((await pay(100)).success).toBe(true)
+    expect(tx.payment.create).toHaveBeenCalledTimes(1)
+  })
+
+  it('says nothing is due once the invoice is paid in full', async () => {
+    invoice({ paid: 552.74 })
+    const result = await pay(10)
+
+    expect(result.error).toBe('Nothing is due on this invoice.')
+    expect(tx.payment.create).not.toHaveBeenCalled()
+  })
+
+  it('reads the balance under the job row lock, scoped to the workshop', async () => {
+    invoice()
+    await pay(100)
+
+    const [strings, ...values] = tx.$queryRaw.mock.calls[0]
+    expect(strings.join('?')).toMatch(/"service_records"[\s\S]*FOR UPDATE/)
+    expect(values).toEqual(['job-1', ORG])
+  })
+
+  it('refuses a job of another workshop before reading any balance', async () => {
+    vi.mocked(db.serviceRecord.findFirst).mockResolvedValue(null)
+    const result = await pay(10)
+
+    expect(result.error).toBe('Service record not found')
+    expect(db.$transaction).not.toHaveBeenCalled()
+  })
+})

+ 115 - 0
src/__tests__/features/vehicles/payment-above-balance.test.tsx

@@ -0,0 +1,115 @@
+/**
+ * The payment form opens with the balance due already in Amount, and refuses
+ * an amount above it next to the field, saying how much is due, before
+ * anything is sent. The server refuses it too (create-payment-balance.test).
+ */
+import { fireEvent, render, screen } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { WorkOrderLayoutProvider } from '@/components/work-order-layout-context'
+import { PaymentsSection } from '@/features/vehicles/Components/service-detail/PaymentsSection'
+
+const noop = vi.fn()
+const onCreatePayment = vi.fn(async () => true)
+
+function Section({
+  modern,
+  payments = [],
+}: {
+  modern: boolean
+  payments?: { id: string; amount: number; date: string; method: string; note: string | null }[]
+}) {
+  const paid = payments.reduce((sum, p) => sum + p.amount, 0)
+  return (
+    <WorkOrderLayoutProvider value={modern}>
+      <PaymentsSection
+        payments={payments as never}
+        paymentStatus={paid ? 'partial' : 'unpaid'}
+        manuallyPaid={false}
+        totalPaid={paid}
+        displayTotal={552.74}
+        balanceDue={552.74 - paid}
+        currencyCode="GBP"
+        onCreatePayment={onCreatePayment}
+        onDeletePayment={noop}
+        onTogglePaid={noop}
+        paymentLoading={false}
+        deletingPayment={null}
+      />
+    </WorkOrderLayoutProvider>
+  )
+}
+
+function openForm() {
+  fireEvent.click(screen.getByRole('button', { name: /record payment/i }))
+  return screen.getByLabelText('Amount') as HTMLInputElement
+}
+
+beforeEach(() => {
+  onCreatePayment.mockClear()
+})
+
+describe.each([
+  ['the overhauled work order', true],
+  ['the classic work order', false],
+])('the payment form on %s', (_, modern) => {
+  it('opens with the balance due in Amount', () => {
+    render(<Section modern={modern} />)
+    expect(openForm().value).toBe('552.74')
+  })
+
+  it('opens with what is left once part has been paid', () => {
+    render(
+      <Section
+        modern={modern}
+        payments={[{ id: 'p1', amount: 500, date: '2026-11-20', method: 'cash', note: null }]}
+      />
+    )
+    expect(openForm().value).toBe('52.74')
+  })
+
+  it('refuses more than the balance due and says how much is due, beside Amount', () => {
+    render(<Section modern={modern} />)
+    const amount = openForm()
+    fireEvent.change(amount, { target: { value: '1000' } })
+    fireEvent.click(screen.getByRole('button', { name: /save payment/i }))
+
+    expect(screen.getByRole('alert')).toHaveTextContent(
+      'The balance due is £552.74. A payment cannot be more than that.'
+    )
+    expect(amount).toHaveAttribute('aria-invalid', 'true')
+    expect(amount).toHaveAccessibleDescription(
+      'The balance due is £552.74. A payment cannot be more than that.'
+    )
+    expect(onCreatePayment).not.toHaveBeenCalled()
+  })
+
+  it('takes exactly the balance due', () => {
+    render(<Section modern={modern} />)
+    openForm()
+    fireEvent.click(screen.getByRole('button', { name: /save payment/i }))
+
+    expect(screen.queryByRole('alert')).toBeNull()
+    expect(onCreatePayment).toHaveBeenCalledWith(expect.objectContaining({ amount: 552.74 }))
+  })
+
+  it('sends the same figure, to the cent, that it checked against the balance', () => {
+    render(<Section modern={modern} />)
+    const amount = openForm()
+    // A hair over the balance as typed, the balance itself to the cent.
+    fireEvent.change(amount, { target: { value: '552.744' } })
+    fireEvent.click(screen.getByRole('button', { name: /save payment/i }))
+
+    expect(screen.queryByRole('alert')).toBeNull()
+    expect(onCreatePayment).toHaveBeenCalledWith(expect.objectContaining({ amount: 552.74 }))
+  })
+
+  it('clears the message once the amount is changed', () => {
+    render(<Section modern={modern} />)
+    const amount = openForm()
+    fireEvent.change(amount, { target: { value: '1000' } })
+    fireEvent.click(screen.getByRole('button', { name: /save payment/i }))
+    fireEvent.change(amount, { target: { value: '500' } })
+
+    expect(screen.queryByRole('alert')).toBeNull()
+  })
+})

+ 19 - 0
src/__tests__/features/vehicles/work-order-payments-dropped-connection.test.ts

@@ -52,6 +52,8 @@ function renderActions() {
     autosaveTimer: { current: null },
     setHasUnsavedChanges: vi.fn(),
     setLocalManuallyPaid: vi.fn(),
+    isDirty: () => false,
+    saveNow: vi.fn(),
   }
   const hook = renderHook(() =>
     useServiceActions({
@@ -106,6 +108,23 @@ describe('work order payments on a dropped connection', () => {
     expect(router.refresh).not.toHaveBeenCalled()
   })
 
+  it('says a payment was not recorded when saving the job first fails, and frees the buttons', async () => {
+    const { form, hook } = renderActions()
+    // Unsaved edits are saved before the payment is sent; that save throws.
+    form.isDirty = () => true
+    form.saveNow.mockImplementation(offline)
+
+    let recorded: boolean | undefined
+    await act(async () => {
+      recorded = await hook.result.current.handleCreatePayment(PAYMENT)
+    })
+
+    expect(recorded).toBe(false)
+    expect(createPayment).not.toHaveBeenCalled()
+    expect(modalMessage()).toBe('Failed to record payment')
+    expect(hook.result.current.paymentLoading).toBe(false)
+  })
+
   it('offers the payment message in the default wording when the saved texts cannot be read', async () => {
     createPayment.mockResolvedValue({ success: true })
     getSmsTemplates.mockImplementation(offline)

+ 49 - 9
src/features/payments/Actions/paymentActions.ts

@@ -8,6 +8,10 @@ import { withAuth } from '@/lib/with-auth'
 import { PermissionAction, PermissionSubject } from '@/lib/permissions'
 import { createPaymentSchema } from '../Schema/paymentSchema'
 import { revalidatePath } from 'next/cache'
+import { getTranslations } from 'next-intl/server'
+import { roundMoney } from '@/lib/money'
+import { workshopMoneyFormatter } from '@/lib/workshop-currency'
+import { paymentBalanceDue } from '../Lib/balanceDue'
 import { getDocumentLockSettings } from '@/lib/document-lock.server'
 import { DocumentLockedError, invoiceLockState } from '@/lib/document-lock'
 
@@ -23,15 +27,51 @@ export async function createPayment(input: unknown) {
       })
       if (!serviceRecord) throw new Error('Service record not found')
 
-      const payment = await db.payment.create({
-        data: {
-          serviceRecordId: data.serviceRecordId,
-          amount: data.amount,
-          date: toSafeWorkshopDate(data.date, await workshopTimeZone(organizationId)) ?? new Date(),
-          method: data.method,
-          note: data.note || null,
-        },
+      const date =
+        toSafeWorkshopDate(data.date, await workshopTimeZone(organizationId)) ?? new Date()
+      const amount = roundMoney(data.amount)
+
+      // A payment taken at the desk may settle the balance, never pass it:
+      // £1000 against £552.74 left the invoice reading "PAID IN FULL -£447.26".
+      // The balance is read under the job's row lock, so two people taking the
+      // last payment at once take turns instead of both getting through.
+      // Money a provider has already taken (Stripe, Vipps, PayPal, Paystack)
+      // and ledger syncs are booked by recordVendorPayment, never through here,
+      // so a real payment is never refused for being more than was owed.
+      const outcome = await db.$transaction(async (tx) => {
+        const locked = await tx.$queryRaw<{ totalAmount: number; cost: number }[]>`
+          SELECT "totalAmount", "cost" FROM "public"."service_records"
+          WHERE "id" = ${serviceRecord.id} AND "organizationId" = ${organizationId}
+          FOR UPDATE`
+        const job = locked[0]
+        if (!job) throw new Error('Service record not found')
+        const paid = await tx.payment.aggregate({
+          where: { serviceRecordId: serviceRecord.id },
+          _sum: { amount: true },
+        })
+        const balanceDue = paymentBalanceDue(job, paid._sum.amount ?? 0)
+        if (amount > balanceDue) return { refused: true as const, balanceDue }
+        const payment = await tx.payment.create({
+          data: {
+            serviceRecordId: data.serviceRecordId,
+            amount,
+            date,
+            method: data.method,
+            note: data.note || null,
+          },
+        })
+        return { refused: false as const, payment }
       })
+      if (outcome.refused) {
+        const t = await getTranslations('service.payments')
+        const format = await workshopMoneyFormatter(organizationId)
+        throw new Error(
+          outcome.balanceDue > 0
+            ? t('aboveBalance', { amount: format(outcome.balanceDue) })
+            : t('nothingDue')
+        )
+      }
+      const { payment } = outcome
       // Money against it makes the invoice the customer's document, even one
       // handed over on paper and never sent through the app.
       await issueInvoice(data.serviceRecordId, organizationId, 'paid')
@@ -44,7 +84,7 @@ export async function createPayment(input: unknown) {
       return {
         ...payment,
         serviceRecordId: data.serviceRecordId,
-        amount: data.amount,
+        amount,
         method: data.method,
       }
     },

+ 16 - 0
src/features/payments/Lib/balanceDue.ts

@@ -0,0 +1,16 @@
+import { roundAsPrinted, roundMoney } from '@/lib/money'
+
+/**
+ * What may still be paid on a job, to the cent: its total as the invoice
+ * prints it (or `cost`, for records older than itemised totals, as the header
+ * and the PDF show it) less every payment recorded against it. "Mark as paid"
+ * is a status, not money, so it does not count here: the actual payment can
+ * still be booked after it.
+ *
+ * Shared by the payment form and createPayment, so the amount the form offers
+ * is the amount the server takes.
+ */
+export function paymentBalanceDue(job: { totalAmount: number; cost: number }, paid: number) {
+  const total = job.totalAmount > 0 ? job.totalAmount : job.cost
+  return Math.max(0, roundMoney(roundAsPrinted(total) - roundMoney(paid)))
+}

+ 45 - 5
src/features/vehicles/Components/service-detail/PaymentsSection.tsx

@@ -23,6 +23,8 @@ import { workshopTodayKey } from '@/lib/workshop-datetime'
 import { paymentStatusColors, paymentStatusLabels } from './types'
 import type { Payment } from './types'
 import { useModernWorkOrder } from '@/components/work-order-layout-context'
+import { paymentBalanceDue } from '@/features/payments/Lib/balanceDue'
+import { roundMoney } from '@/lib/money'
 import { isRefund, paymentMethodLabel } from '@/features/payments/Lib/paymentMethod'
 import { cn } from '@/lib/utils'
 
@@ -84,6 +86,13 @@ export function PaymentsSection({
   const formRef = useRef<HTMLDivElement>(null)
   const methodName = (method: string) => paymentMethodLabel(method, (m) => t(`methodOptions.${m}`))
   const sectionRef = useRef<HTMLDivElement>(null)
+  const [amountError, setAmountError] = useState<string | null>(null)
+  // What may still be paid, counted the way createPayment counts it: recorded
+  // payments only, since "Mark as paid" is a status and not money.
+  const payable = paymentBalanceDue(
+    { totalAmount: displayTotal, cost: 0 },
+    payments.reduce((sum, p) => sum + p.amount, 0)
+  )
 
   useEffect(() => {
     if (openFormSignal === 0) return
@@ -110,9 +119,21 @@ export function PaymentsSection({
     const amount = formRef.current.querySelector<HTMLInputElement>('[name="paymentAmount"]')
     const date = formRef.current.querySelector<HTMLInputElement>('[name="paymentDate"]')
     const note = formRef.current.querySelector<HTMLInputElement>('[name="paymentNote"]')
-    if (!amount?.value || Number(amount.value) <= 0) return
+    // Read once, to the cent: the figure checked is the figure sent.
+    const value = roundMoney(amount?.value)
+    if (!amount || value <= 0) return
+    // Never more than is owed; createPayment refuses it too.
+    if (value > payable) {
+      setAmountError(
+        payable > 0
+          ? t('aboveBalance', { amount: formatCurrency(payable, currencyCode) })
+          : t('nothingDue')
+      )
+      amount.focus()
+      return
+    }
     const success = await onCreatePayment({
-      amount: Number(amount.value),
+      amount: value,
       date: date?.value || new Date().toISOString(),
       method: paymentMethod,
       note: note?.value || undefined,
@@ -147,9 +168,17 @@ export function PaymentsSection({
             type="number"
             step="0.01"
             min="0.01"
-            defaultValue={balanceDue > 0 ? balanceDue.toFixed(2) : ''}
+            defaultValue={payable > 0 ? payable.toFixed(2) : ''}
             required
+            aria-invalid={amountError ? true : undefined}
+            aria-describedby={amountError ? 'paymentAmountError' : undefined}
+            onChange={() => setAmountError(null)}
           />
+          {amountError && (
+            <p id="paymentAmountError" role="alert" className="text-xs text-destructive">
+              {amountError}
+            </p>
+          )}
         </div>
         <div className="space-y-1">
           <Label htmlFor="paymentDate" className="text-xs">
@@ -188,7 +217,15 @@ export function PaymentsSection({
           {paymentLoading && <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" />}
           {t('savePayment')}
         </Button>
-        <Button type="button" variant="ghost" size="sm" onClick={() => setShowForm(false)}>
+        <Button
+          type="button"
+          variant="ghost"
+          size="sm"
+          onClick={() => {
+            setShowForm(false)
+            setAmountError(null)
+          }}
+        >
           {tc('cancel')}
         </Button>
       </div>
@@ -336,7 +373,10 @@ export function PaymentsSection({
               variant="outline"
               size="sm"
               className="h-7 text-xs"
-              onClick={() => setShowForm(!showForm)}
+              onClick={() => {
+                setShowForm(!showForm)
+                setAmountError(null)
+              }}
             >
               <Plus className="mr-1 h-3 w-3" />
               {t('recordPayment')}

+ 13 - 2
src/features/vehicles/Components/service-page/useServiceActions.ts

@@ -479,8 +479,19 @@ export function useServiceActions({
     note?: string
   }) => {
     setPaymentLoading(true)
-    const result = await createPayment({ serviceRecordId: record.id, ...data }).catch(() => null)
-    setPaymentLoading(false)
+    let result: Awaited<ReturnType<typeof createPayment>> | null = null
+    try {
+      // The server takes payments up to the saved total, and the form offers
+      // the total on screen: a line added in the last few seconds is saved
+      // first, so the two agree.
+      if (formState.isDirty()) await formState.saveNow()
+      result = await createPayment({ serviceRecordId: record.id, ...data })
+    } catch {
+      // A save or a request that never came back: said below, never left spinning.
+      result = null
+    } finally {
+      setPaymentLoading(false)
+    }
     if (result?.success) {
       toast.success(t('payments.recorded'))
       router.refresh()