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

Show payments as money received with a translated method (#677)

* Show payments as money received with a translated method

* Give the payment lines test a complete workshop
Bernt Christian Egeland 3 дней назад
Родитель
Сommit
2a9095bbf7
36 измененных файлов с 470 добавлено и 28 удалено
  1. 1 1
      e2e/specs/invoices/payments.spec.ts
  2. 5 0
      messages/bg/pdf.json
  3. 2 1
      messages/bg/service.json
  4. 5 0
      messages/de/pdf.json
  5. 2 1
      messages/de/service.json
  6. 5 0
      messages/en/pdf.json
  7. 2 1
      messages/en/service.json
  8. 5 0
      messages/es/pdf.json
  9. 2 1
      messages/es/service.json
  10. 5 0
      messages/fr/pdf.json
  11. 2 1
      messages/fr/service.json
  12. 5 0
      messages/it/pdf.json
  13. 2 1
      messages/it/service.json
  14. 5 0
      messages/lt/pdf.json
  15. 2 1
      messages/lt/service.json
  16. 5 0
      messages/nb/pdf.json
  17. 2 1
      messages/nb/service.json
  18. 5 0
      messages/nl/pdf.json
  19. 2 1
      messages/nl/service.json
  20. 5 0
      messages/pl/pdf.json
  21. 2 1
      messages/pl/service.json
  22. 5 0
      messages/pt-BR/pdf.json
  23. 2 1
      messages/pt-BR/service.json
  24. 5 0
      messages/pt-PT/pdf.json
  25. 2 1
      messages/pt-PT/service.json
  26. 5 0
      messages/ru/pdf.json
  27. 2 1
      messages/ru/service.json
  28. 5 0
      messages/tr/pdf.json
  29. 2 1
      messages/tr/service.json
  30. 165 0
      src/__tests__/features/invoice-designer/payment-lines.test.tsx
  31. 100 0
      src/__tests__/features/vehicles/payments-section-lines.test.tsx
  32. 7 2
      src/features/invoice-designer/Components/sample.ts
  33. 29 3
      src/features/invoice-designer/Pdf/buildInvoicePrint.ts
  34. 7 3
      src/features/invoice-designer/Spec/buildSpec.ts
  35. 44 0
      src/features/payments/Lib/paymentMethod.ts
  36. 19 5
      src/features/vehicles/Components/service-detail/PaymentsSection.tsx

+ 1 - 1
e2e/specs/invoices/payments.spec.ts

@@ -119,7 +119,7 @@ test.describe('paying an invoice', () => {
     // The payment itself is listed, with the method it came in by.
     const row = paymentRow(page, '$400.00')
     await expect(row).toHaveCount(1)
-    await expect(row).toContainText('cash')
+    await expect(row).toContainText('Cash')
 
     await expect(moneyBar(page, 'balance')).toHaveText('$500.00')
     await expect(paymentsPanel(page).getByTestId('balance-due')).toHaveText('$500.00')

+ 5 - 0
messages/bg/pdf.json

@@ -49,6 +49,11 @@
     "taxIncludedNamed": "Включва {name} ({rate}%)",
     "taxableAmount": "Данъчна основа",
     "paymentsReceived": "Получени плащания",
+    "paymentMethodCash": "В брой",
+    "paymentMethodCard": "Карта",
+    "paymentMethodTransfer": "Банков превод",
+    "paymentMethodOther": "Друго",
+    "refund": "Възстановяване",
     "paidInFull": "ПЛАТЕНО ИЗЦЯЛО",
     "amountDue": "Сума за плащане",
     "notes": "Бележки",

+ 2 - 1
messages/bg/service.json

@@ -373,7 +373,8 @@
     "failedPdf": "PDF фактурата не можа да бъде генерирана",
     "received": "Получени плащания",
     "noneYet": "Все още няма плащания.",
-    "balanceDue": "Оставаща сума"
+    "balanceDue": "Оставаща сума",
+    "refund": "Възстановяване"
   },
   "attachments": {
     "deleteTitle": "Изтриване на прикачен файл",

+ 5 - 0
messages/de/pdf.json

@@ -48,6 +48,11 @@
     "taxIncludedNamed": "Inkl. {name} ({rate}%)",
     "taxableAmount": "Steuerpflichtiger Betrag",
     "paymentsReceived": "Eingegangene Zahlungen",
+    "paymentMethodCash": "Bargeld",
+    "paymentMethodCard": "Karte",
+    "paymentMethodTransfer": "Überweisung",
+    "paymentMethodOther": "Sonstige",
+    "refund": "Erstattung",
     "paidInFull": "VOLLSTÄNDIG BEZAHLT",
     "amountDue": "Fälliger Betrag",
     "notes": "Hinweise",

+ 2 - 1
messages/de/service.json

@@ -373,7 +373,8 @@
     "failedPdf": "PDF-Rechnung konnte nicht erstellt werden",
     "received": "Erhaltene Zahlungen",
     "noneYet": "Noch nichts bezahlt.",
-    "balanceDue": "Ausstehend"
+    "balanceDue": "Ausstehend",
+    "refund": "Erstattung"
   },
   "attachments": {
     "deleteTitle": "Anlage löschen",

+ 5 - 0
messages/en/pdf.json

@@ -49,6 +49,11 @@
     "taxIncludedNamed": "Includes {name} ({rate}%)",
     "taxableAmount": "Taxable amount",
     "paymentsReceived": "Payments Received",
+    "paymentMethodCash": "Cash",
+    "paymentMethodCard": "Card",
+    "paymentMethodTransfer": "Bank transfer",
+    "paymentMethodOther": "Other",
+    "refund": "Refund",
     "paidInFull": "PAID IN FULL",
     "amountDue": "Amount Due",
     "notes": "Notes",

+ 2 - 1
messages/en/service.json

@@ -373,7 +373,8 @@
     "failedPdf": "Failed to generate PDF invoice",
     "received": "Payments received",
     "noneYet": "Nothing paid yet.",
-    "balanceDue": "Balance due"
+    "balanceDue": "Balance due",
+    "refund": "Refund"
   },
   "attachments": {
     "deleteTitle": "Delete Attachment",

+ 5 - 0
messages/es/pdf.json

@@ -48,6 +48,11 @@
     "taxIncludedNamed": "Con {name} ({rate}%)",
     "taxableAmount": "Base imponible",
     "paymentsReceived": "Pagos recibidos",
+    "paymentMethodCash": "Efectivo",
+    "paymentMethodCard": "Tarjeta",
+    "paymentMethodTransfer": "Transferencia",
+    "paymentMethodOther": "Otro",
+    "refund": "Reembolso",
     "paidInFull": "PAGADO EN SU TOTALIDAD",
     "amountDue": "Monto adeudado",
     "notes": "Notas",

+ 2 - 1
messages/es/service.json

@@ -373,7 +373,8 @@
     "failedPdf": "Error al generar factura en PDF",
     "received": "Pagos recibidos",
     "noneYet": "Todavía no se ha pagado nada.",
-    "balanceDue": "Saldo pendiente"
+    "balanceDue": "Saldo pendiente",
+    "refund": "Reembolso"
   },
   "attachments": {
     "deleteTitle": "Eliminar Archivo",

+ 5 - 0
messages/fr/pdf.json

@@ -48,6 +48,11 @@
     "taxIncludedNamed": "{name} incluse ({rate}%)",
     "taxableAmount": "Montant taxable",
     "paymentsReceived": "Paiements reçus",
+    "paymentMethodCash": "Comptant",
+    "paymentMethodCard": "Carte",
+    "paymentMethodTransfer": "Virement",
+    "paymentMethodOther": "Autre",
+    "refund": "Remboursement",
     "paidInFull": "ENTIÈREMENT PAYÉ",
     "amountDue": "Montant dû",
     "notes": "Notes",

+ 2 - 1
messages/fr/service.json

@@ -373,7 +373,8 @@
     "failedPdf": "Impossible de générer la facture PDF",
     "received": "Paiements reçus",
     "noneYet": "Rien de payé pour l'instant.",
-    "balanceDue": "Solde dû"
+    "balanceDue": "Solde dû",
+    "refund": "Remboursement"
   },
   "attachments": {
     "deleteTitle": "Supprimer la Pièce Jointe",

+ 5 - 0
messages/it/pdf.json

@@ -48,6 +48,11 @@
     "taxIncludedNamed": "{name} inclusa ({rate}%)",
     "taxableAmount": "Imponibile",
     "paymentsReceived": "Pagamenti Ricevuti",
+    "paymentMethodCash": "Contanti",
+    "paymentMethodCard": "Carta",
+    "paymentMethodTransfer": "Trasferimento",
+    "paymentMethodOther": "Altro",
+    "refund": "Rimborso",
     "paidInFull": "SALDATO",
     "amountDue": "Importo Dovuto",
     "notes": "Note",

+ 2 - 1
messages/it/service.json

@@ -373,7 +373,8 @@
     "failedPdf": "Impossibile generare PDF fattura",
     "received": "Pagamenti ricevuti",
     "noneYet": "Ancora nessun pagamento.",
-    "balanceDue": "Importo dovuto"
+    "balanceDue": "Importo dovuto",
+    "refund": "Rimborso"
   },
   "attachments": {
     "deleteTitle": "Elimina Allegato",

+ 5 - 0
messages/lt/pdf.json

@@ -49,6 +49,11 @@
     "taxIncludedNamed": "Su {name} ({rate}%)",
     "taxableAmount": "Apmokestinama suma",
     "paymentsReceived": "Gauti mokėjimai",
+    "paymentMethodCash": "Grynaisiais",
+    "paymentMethodCard": "Kortele",
+    "paymentMethodTransfer": "Pavedimu",
+    "paymentMethodOther": "Kita",
+    "refund": "Grąžinimas",
     "paidInFull": "PILNAI APMOKĖTA",
     "amountDue": "Mokėtina suma",
     "notes": "Pastabos",

+ 2 - 1
messages/lt/service.json

@@ -373,7 +373,8 @@
     "failedPdf": "Nepavyko sugeneruoti PDF sąskaitos",
     "received": "Gauti mokėjimai",
     "noneYet": "Dar nieko nesumokėta.",
-    "balanceDue": "Mokėtina suma"
+    "balanceDue": "Mokėtina suma",
+    "refund": "Grąžinimas"
   },
   "attachments": {
     "deleteTitle": "Ištrinti priedą",

+ 5 - 0
messages/nb/pdf.json

@@ -48,6 +48,11 @@
     "taxIncludedNamed": "Inkluderer {name} ({rate}%)",
     "taxableAmount": "Avgiftspliktig beløp",
     "paymentsReceived": "Mottatte betalinger",
+    "paymentMethodCash": "Kontant",
+    "paymentMethodCard": "Kort",
+    "paymentMethodTransfer": "Overføring",
+    "paymentMethodOther": "Annet",
+    "refund": "Refusjon",
     "paidInFull": "FULLT BETALT",
     "amountDue": "Beløp å betale",
     "notes": "Notater",

+ 2 - 1
messages/nb/service.json

@@ -373,7 +373,8 @@
     "failedPdf": "Kunne ikke generere PDF-faktura",
     "received": "Mottatte betalinger",
     "noneYet": "Ingenting betalt ennå.",
-    "balanceDue": "Utestående"
+    "balanceDue": "Utestående",
+    "refund": "Refusjon"
   },
   "attachments": {
     "deleteTitle": "Slett vedlegg",

+ 5 - 0
messages/nl/pdf.json

@@ -48,6 +48,11 @@
     "taxIncludedNamed": "Incl. {name} ({rate}%)",
     "taxableAmount": "Belastbaar bedrag",
     "paymentsReceived": "Ontvangen betalingen",
+    "paymentMethodCash": "Contant",
+    "paymentMethodCard": "Kaart",
+    "paymentMethodTransfer": "Overboeking",
+    "paymentMethodOther": "Overig",
+    "refund": "Terugbetaling",
     "paidInFull": "VOLLEDIG BETAALD",
     "amountDue": "Te betalen bedrag",
     "notes": "Notities",

+ 2 - 1
messages/nl/service.json

@@ -373,7 +373,8 @@
     "failedPdf": "PDF-factuur genereren mislukt",
     "received": "Ontvangen betalingen",
     "noneYet": "Nog niets betaald.",
-    "balanceDue": "Verschuldigd bedrag"
+    "balanceDue": "Verschuldigd bedrag",
+    "refund": "Terugbetaling"
   },
   "attachments": {
     "deleteTitle": "Bijlage verwijderen",

+ 5 - 0
messages/pl/pdf.json

@@ -48,6 +48,11 @@
     "taxIncludedNamed": "Zawiera {name} ({rate}%)",
     "taxableAmount": "Podstawa opodatkowania",
     "paymentsReceived": "Otrzymane płatności",
+    "paymentMethodCash": "Gotówka",
+    "paymentMethodCard": "Karta",
+    "paymentMethodTransfer": "Przelew",
+    "paymentMethodOther": "Inne",
+    "refund": "Zwrot",
     "paidInFull": "ZAPŁACONO W CAŁOŚCI",
     "amountDue": "Kwota do zapłaty",
     "notes": "Uwagi",

+ 2 - 1
messages/pl/service.json

@@ -373,7 +373,8 @@
     "failedPdf": "Nie udało się wygenerować faktury PDF",
     "received": "Otrzymane płatności",
     "noneYet": "Nic jeszcze nie zapłacono.",
-    "balanceDue": "Pozostało do zapłaty"
+    "balanceDue": "Pozostało do zapłaty",
+    "refund": "Zwrot"
   },
   "attachments": {
     "deleteTitle": "Usuń Załącznik",

+ 5 - 0
messages/pt-BR/pdf.json

@@ -48,6 +48,11 @@
     "taxIncludedNamed": "{name} incluído ({rate}%)",
     "taxableAmount": "Base tributável",
     "paymentsReceived": "Pagamentos Recebidos",
+    "paymentMethodCash": "Dinheiro",
+    "paymentMethodCard": "Cartão",
+    "paymentMethodTransfer": "Transferência",
+    "paymentMethodOther": "Outro",
+    "refund": "Reembolso",
     "paidInFull": "PAGO INTEGRALMENTE",
     "amountDue": "Valor a Pagar",
     "notes": "Observações",

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

@@ -373,7 +373,8 @@
     "failedPdf": "Falha ao gerar PDF da fatura",
     "received": "Pagamentos recebidos",
     "noneYet": "Nada pago ainda.",
-    "balanceDue": "Saldo devedor"
+    "balanceDue": "Saldo devedor",
+    "refund": "Reembolso"
   },
   "attachments": {
     "deleteTitle": "Deletar Anexo",

+ 5 - 0
messages/pt-PT/pdf.json

@@ -48,6 +48,11 @@
     "taxIncludedNamed": "{name} incluído ({rate}%)",
     "taxableAmount": "Valor tributável",
     "paymentsReceived": "Pagamentos Recebidos",
+    "paymentMethodCash": "Numerário",
+    "paymentMethodCard": "Cartão",
+    "paymentMethodTransfer": "Transferência",
+    "paymentMethodOther": "Outro",
+    "refund": "Reembolso",
     "paidInFull": "PAGO NA TOTALIDADE",
     "amountDue": "Valor a Pagar",
     "notes": "Observações",

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

@@ -373,7 +373,8 @@
     "failedPdf": "Não foi possível gerar o PDF da fatura",
     "received": "Pagamentos recebidos",
     "noneYet": "Ainda nada pago.",
-    "balanceDue": "Valor em dívida"
+    "balanceDue": "Valor em dívida",
+    "refund": "Reembolso"
   },
   "attachments": {
     "deleteTitle": "Eliminar anexo",

+ 5 - 0
messages/ru/pdf.json

@@ -48,6 +48,11 @@
     "taxIncludedNamed": "С {name} ({rate}%)",
     "taxableAmount": "Налогооблагаемая сумма",
     "paymentsReceived": "Полученные платежи",
+    "paymentMethodCash": "Наличные",
+    "paymentMethodCard": "Карта",
+    "paymentMethodTransfer": "Перевод",
+    "paymentMethodOther": "Другое",
+    "refund": "Возврат",
     "paidInFull": "ПОЛНОСТЬЮ ОПЛАЧЕНО",
     "amountDue": "К оплате",
     "notes": "Заметки",

+ 2 - 1
messages/ru/service.json

@@ -373,7 +373,8 @@
     "failedPdf": "Не удалось сгенерировать PDF-счёт",
     "received": "Полученные платежи",
     "noneYet": "Оплат пока нет.",
-    "balanceDue": "К оплате"
+    "balanceDue": "К оплате",
+    "refund": "Возврат"
   },
   "attachments": {
     "deleteTitle": "Удалить вложение",

+ 5 - 0
messages/tr/pdf.json

@@ -48,6 +48,11 @@
     "taxIncludedNamed": "{name} dahil (%{rate})",
     "taxableAmount": "Vergiye tabi tutar",
     "paymentsReceived": "Alınan Ödemeler",
+    "paymentMethodCash": "Nakit",
+    "paymentMethodCard": "Kart",
+    "paymentMethodTransfer": "Havale",
+    "paymentMethodOther": "Diğer",
+    "refund": "İade",
     "paidInFull": "TAMAMEN ÖDENDİ",
     "amountDue": "Ödenecek Tutar",
     "notes": "Notlar",

+ 2 - 1
messages/tr/service.json

@@ -373,7 +373,8 @@
     "failedPdf": "PDF fatura oluşturulamadı",
     "received": "Alınan ödemeler",
     "noneYet": "Henüz ödeme yapılmadı.",
-    "balanceDue": "Kalan bakiye"
+    "balanceDue": "Kalan bakiye",
+    "refund": "İade"
   },
   "attachments": {
     "deleteTitle": "Eki Sil",

+ 165 - 0
src/__tests__/features/invoice-designer/payment-lines.test.tsx

@@ -0,0 +1,165 @@
+/**
+ * The payments a customer reads on the invoice: on the shared page, in the PDF
+ * and in the portal, which all draw the same sheet.
+ *
+ * A payment received is money in and reads as the amount the customer paid,
+ * not with a minus in front of it. Its method is a word in the document's
+ * language ("Kort", not "(card)"). Money handed back is called a refund and is
+ * the one figure with a minus, so Total less Payments received is still the
+ * Amount Due under it.
+ */
+
+import { render, screen, within } from '@testing-library/react'
+import { describe, expect, it, vi } from 'vitest'
+
+vi.mock('lucide-react', () => ({
+  Camera: () => <span />,
+  ChevronLeft: () => <span />,
+  ChevronRight: () => <span />,
+  CreditCard: () => <span />,
+  Download: () => <span />,
+  FileText: () => <span />,
+  Film: () => <span />,
+  Loader2: () => <span />,
+  Paperclip: () => <span />,
+  X: () => <span />,
+}))
+
+import { InvoiceView } from '@/app/(public)/share/invoice/[orgId]/[token]/invoice-view'
+import { buildInvoicePrintSpec } from '@/features/invoice-designer/Pdf/buildInvoicePrint'
+import { loadPrintLabels } from '@/features/invoice-designer/Pdf/printLabels'
+import type { InvoiceData, PaymentSummary } from '@/features/vehicles/Components/invoice-pdf/types'
+
+const invoice: InvoiceData = {
+  id: 'svc_payments01',
+  title: 'Brake pads',
+  description: null,
+  type: 'repair',
+  serviceDate: new Date('2026-11-20'),
+  invoiceDate: new Date('2026-11-20'),
+  invoiceDueDate: null,
+  shopName: 'ZZ Test Garage',
+  techName: null,
+  mileage: null,
+  diagnosticNotes: null,
+  invoiceNotes: null,
+  subtotal: 500,
+  taxRate: 0,
+  taxAmount: 0,
+  totalAmount: 500,
+  cost: 500,
+  invoiceNumber: 'INV-1001',
+  discountType: null,
+  discountValue: 0,
+  discountAmount: 0,
+  partItems: [{ partNumber: 'P-1', name: 'Pads', quantity: 1, unitPrice: 500, total: 500 }],
+  laborItems: [],
+  vehicle: null,
+}
+
+/** A card payment, a cash payment and a refund of part of the card one. */
+const payments: PaymentSummary = {
+  totalPaid: 250,
+  payments: [
+    { amount: 200, date: '24/11/2026', method: 'card' },
+    { amount: 100, date: '24/11/2026', method: 'cash' },
+    { amount: -50, date: '25/11/2026', method: 'card' },
+  ],
+}
+
+const WORKSHOP = { name: 'ZZ Test Garage', address: '', phone: '', email: '' }
+
+function totalsText(labels?: Record<string, string>, summary: PaymentSummary = payments) {
+  const spec = buildInvoicePrintSpec({
+    data: invoice,
+    workshop: WORKSHOP,
+    invoiceSettings: { currencyCode: 'GBP' },
+    paymentSummary: summary,
+    labels,
+  })
+  const totals = spec.blocks.find((b) => b.id === 'totals')
+  const texts: string[] = []
+  const walk = (node: unknown) => {
+    if (!node || typeof node !== 'object') return
+    const n = node as Record<string, unknown>
+    if (n.kind === 'text' && typeof n.text === 'string') texts.push(n.text)
+    for (const value of Object.values(n)) {
+      if (Array.isArray(value)) value.forEach(walk)
+      else if (value && typeof value === 'object') walk(value)
+    }
+  }
+  walk(totals)
+  return texts
+}
+
+/** The figure printed beside a label: the text right after it. */
+function figureBeside(texts: string[], label: string) {
+  const at = texts.indexOf(label)
+  expect(at, `no line labelled "${label}" in ${JSON.stringify(texts)}`).toBeGreaterThan(-1)
+  return texts[at + 1]
+}
+
+describe('payments on the invoice a customer reads', () => {
+  it('lists each payment as money received, with its method in words', async () => {
+    const texts = totalsText(await loadPrintLabels('en', {}))
+    expect(figureBeside(texts, 'Total')).toBe('£500.00')
+    expect(figureBeside(texts, 'Payments Received')).toBe('£250.00')
+    expect(figureBeside(texts, '24/11/2026 (Card)')).toBe('£200.00')
+    expect(figureBeside(texts, '24/11/2026 (Cash)')).toBe('£100.00')
+    expect(figureBeside(texts, 'Amount Due')).toBe('£250.00')
+    expect(texts.join(' ')).not.toMatch(/\(card\)|\(cash\)|-£200|-£100/)
+  })
+
+  it('calls money handed back a refund, the one figure with a minus', async () => {
+    const texts = totalsText(await loadPrintLabels('en', {}))
+    expect(figureBeside(texts, 'Refund 25/11/2026 (Card)')).toBe('-£50.00')
+  })
+
+  it('writes the method and the refund in the language of the document', async () => {
+    const texts = totalsText(await loadPrintLabels('nb', {}))
+    expect(figureBeside(texts, 'Mottatte betalinger')).toBe('£250.00')
+    expect(figureBeside(texts, '24/11/2026 (Kort)')).toBe('£200.00')
+    expect(figureBeside(texts, '24/11/2026 (Kontant)')).toBe('£100.00')
+    expect(figureBeside(texts, 'Refusjon 25/11/2026 (Kort)')).toBe('-£50.00')
+  })
+
+  it('names a payment taken online after the vendor that took it', async () => {
+    const texts = totalsText(await loadPrintLabels('de', {}), {
+      totalPaid: 500,
+      payments: [
+        { amount: 300, date: '24/11/2026', method: 'stripe' },
+        { amount: 200, date: '24/11/2026', method: 'transfer' },
+      ],
+    })
+    expect(figureBeside(texts, '24/11/2026 (Stripe)')).toBe('£300.00')
+    expect(figureBeside(texts, '24/11/2026 (Überweisung)')).toBe('£200.00')
+    expect(texts).toContain('VOLLSTÄNDIG BEZAHLT')
+  })
+
+  it('shows the same on the shared page', async () => {
+    const spec = buildInvoicePrintSpec({
+      data: invoice,
+      workshop: WORKSHOP,
+      invoiceSettings: { currencyCode: 'GBP' },
+      paymentSummary: payments,
+      labels: await loadPrintLabels('en', {}),
+    })
+    const { container } = render(
+      <InvoiceView
+        spec={spec}
+        record={{ ...invoice, manuallyPaid: false, payments: [], attachments: [] } as never}
+        workshop={WORKSHOP}
+        currencyCode="GBP"
+        orgId="org-1"
+        token="tok-1"
+        enabledProviders={[]}
+      />
+    )
+    const page = within(container)
+    expect(page.getAllByText('24/11/2026 (Card)').length).toBeGreaterThan(0)
+    expect(page.getAllByText('£200.00').length).toBeGreaterThan(0)
+    expect(page.getAllByText('Refund 25/11/2026 (Card)').length).toBeGreaterThan(0)
+    expect(screen.queryByText('-£200.00')).toBeNull()
+    expect(screen.queryByText(/\(card\)/)).toBeNull()
+  })
+})

+ 100 - 0
src/__tests__/features/vehicles/payments-section-lines.test.tsx

@@ -0,0 +1,100 @@
+/**
+ * The payments on the work order, as the workshop reads them: what came in is
+ * the amount that came in, not a minus figure, and the method is a word, not
+ * the code it is stored as. A refund (a negative payment, from a ledger sync)
+ * says it is a refund.
+ */
+
+import { render, screen } from '@testing-library/react'
+import { 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 payments = [
+  {
+    id: 'p1',
+    amount: 200,
+    date: new Date('2026-11-24T10:00:00Z'),
+    method: 'card',
+    note: null,
+    createdAt: new Date(),
+  },
+  {
+    id: 'p2',
+    amount: 100,
+    date: new Date('2026-11-24T11:00:00Z'),
+    method: 'cash',
+    note: null,
+    createdAt: new Date(),
+  },
+  {
+    id: 'p3',
+    amount: -50,
+    date: new Date('2026-11-25T11:00:00Z'),
+    method: 'transfer',
+    note: null,
+    createdAt: new Date(),
+  },
+  {
+    id: 'p4',
+    amount: 80,
+    date: new Date('2026-11-25T12:00:00Z'),
+    method: 'paypal',
+    note: null,
+    createdAt: new Date(),
+  },
+]
+
+function Section({ modern }: { modern: boolean }) {
+  return (
+    <WorkOrderLayoutProvider value={modern}>
+      <PaymentsSection
+        payments={payments}
+        paymentStatus="partial"
+        manuallyPaid={false}
+        totalPaid={330}
+        displayTotal={500}
+        balanceDue={170}
+        currencyCode="USD"
+        onCreatePayment={async () => true}
+        onDeletePayment={noop}
+        onTogglePaid={noop}
+        paymentLoading={false}
+        deletingPayment={null}
+      />
+    </WorkOrderLayoutProvider>
+  )
+}
+
+describe('payments on the work order', () => {
+  it('lists money received as positive amounts with the method in words', () => {
+    render(<Section modern />)
+    const rows = screen.getAllByRole('listitem')
+    expect(rows[0]).toHaveTextContent('Card')
+    expect(rows[0]).toHaveTextContent('$200.00')
+    expect(rows[0]).not.toHaveTextContent('-$200.00')
+    expect(rows[1]).toHaveTextContent('Cash')
+    expect(rows[1]).toHaveTextContent('$100.00')
+    expect(rows[1]).not.toHaveTextContent('-$100.00')
+    expect(rows[3]).toHaveTextContent('PayPal')
+    expect(screen.getByTestId('balance-due')).toHaveTextContent('$170.00')
+  })
+
+  it('says a refund is a refund', () => {
+    render(<Section modern />)
+    const refund = screen.getAllByRole('listitem')[2]
+    expect(refund).toHaveTextContent('Refund')
+    expect(refund).toHaveTextContent('Transfer')
+    expect(refund).toHaveTextContent('-$50.00')
+  })
+
+  it('translates the method in the classic table too', () => {
+    render(<Section modern={false} />)
+    expect(screen.getByText('Card')).toBeInTheDocument()
+    expect(screen.getByText('Cash')).toBeInTheDocument()
+    expect(screen.getByText('Refund')).toBeInTheDocument()
+    expect(screen.queryByText('card')).toBeNull()
+  })
+})

+ 7 - 2
src/features/invoice-designer/Components/sample.ts

@@ -410,8 +410,13 @@ export function buildSampleData(
       ...(docType === 'invoice'
         ? [
             {
-              label: `${sample.date} (Visa)`,
-              value: `-${tax.total}`,
+              label: L('paymentsReceived', 'Payments Received'),
+              value: tax.total,
+              kind: 'line' as const,
+            },
+            {
+              label: `${sample.date} (${L('paymentMethodCard', 'Card')})`,
+              value: tax.total,
               kind: 'payment' as const,
             },
             { label: L('paidInFull', 'PAID IN FULL'), value: '', kind: 'paid' as const },

+ 29 - 3
src/features/invoice-designer/Pdf/buildInvoicePrint.ts

@@ -47,6 +47,19 @@ import {
   inspectionResultsForPrint,
 } from '@/features/inspections/Lib/inspectionResults'
 import { vehicleName as vehicleNameOf } from '@/lib/vehicle-name'
+import {
+  isRefund,
+  type PaymentMethod,
+  paymentMethodLabel,
+} from '@/features/payments/Lib/paymentMethod'
+
+/** Each method's label key in `pdf.json`, with the English it falls back to. */
+const PAYMENT_METHOD_LABELS: Record<PaymentMethod, [string, string]> = {
+  cash: ['paymentMethodCash', 'Cash'],
+  card: ['paymentMethodCard', 'Card'],
+  transfer: ['paymentMethodTransfer', 'Bank transfer'],
+  other: ['paymentMethodOther', 'Other'],
+}
 
 /**
  * A real job, expressed as the document the designer edits.
@@ -416,11 +429,24 @@ export function buildInvoicePrintSpec(input: InvoicePrintInput): DocumentSpec {
   )
   totals.push({ label: L('total', 'Total'), value: money(displayTotal), kind: 'total' })
   if (paymentSummary && paymentSummary.payments.length > 0) {
+    // Money in reads as money in: what came in all told, under the total,
+    // then each payment as the amount the customer paid, so Total less
+    // Payments received is the Amount Due below. Money handed back is named
+    // a refund and is the one figure with a minus.
+    const methodName = (method: string) =>
+      paymentMethodLabel(method, (m) => L(...PAYMENT_METHOD_LABELS[m]))
+    totals.push({
+      label: L('paymentsReceived', 'Payments Received'),
+      value: money(paymentSummary.payments.reduce((sum, p) => sum + p.amount, 0)),
+      kind: 'line',
+    })
     for (const payment of paymentSummary.payments) {
+      const refund = isRefund(payment.amount)
+      const when = `${payment.date} (${methodName(payment.method)})`
       totals.push({
-        label: `${payment.date} (${payment.method})`,
-        value: money(-payment.amount),
-        kind: 'payment',
+        label: refund ? `${L('refund', 'Refund')} ${when}` : when,
+        value: money(payment.amount),
+        kind: refund ? 'refund' : 'payment',
       })
     }
     totals.push(

+ 7 - 3
src/features/invoice-designer/Spec/buildSpec.ts

@@ -49,7 +49,11 @@ import {
 export interface TotalLine {
   label: string
   value: string
-  kind: 'line' | 'discount' | 'total' | 'payment' | 'due' | 'paid'
+  /**
+   * `payment` is money received, drawn as the positive amount it was;
+   * `refund` is money handed back, the one line under the payments with a minus.
+   */
+  kind: 'line' | 'discount' | 'total' | 'payment' | 'refund' | 'due' | 'paid'
 }
 
 /** A label over a value in the payment panel. Gated ids follow the layout. */
@@ -1502,7 +1506,7 @@ function totals(section: InvoiceSection, theme: DocumentTheme, data: DocumentDat
     if (entry.kind === 'paid') return paidBadge(entry)
     const emphasized = entry.kind === 'total' || entry.kind === 'due'
     const valueColor =
-      entry.kind === 'discount'
+      entry.kind === 'discount' || entry.kind === 'refund'
         ? '#dc2626'
         : entry.kind === 'payment'
           ? '#059669'
@@ -1527,7 +1531,7 @@ function totals(section: InvoiceSection, theme: DocumentTheme, data: DocumentDat
               color: emphasized ? look.text : look.muted,
               bold: emphasized,
               fontSize:
-                entry.kind === 'payment'
+                entry.kind === 'payment' || entry.kind === 'refund'
                   ? scale(size, 0.85)
                   : bare && emphasized
                     ? scale(size, 1.15)

+ 44 - 0
src/features/payments/Lib/paymentMethod.ts

@@ -0,0 +1,44 @@
+/**
+ * How a payment's method reads to a person.
+ *
+ * A payment stores its method as a code: one of the four the payments form
+ * offers, or the vendor that took it online. The code is not a word anybody
+ * should read; a Norwegian invoice saying "(card)" is a bug. The four are
+ * translated by whoever draws them (the app in the viewer's language, a
+ * printed or shared document in the document's), and a vendor is its own
+ * name in every language. Anything else, from an old backup or an import,
+ * prints as it was stored rather than not at all.
+ */
+
+/** The methods the payments form offers, in the order it offers them. */
+export const PAYMENT_METHODS = ['cash', 'card', 'transfer', 'other'] as const
+export type PaymentMethod = (typeof PAYMENT_METHODS)[number]
+
+/** The vendors a payment can come in through online, as they write their own names. */
+const VENDOR_NAMES: Record<string, string> = {
+  stripe: 'Stripe',
+  paypal: 'PayPal',
+  vipps: 'Vipps',
+  paystack: 'Paystack',
+}
+
+export function isPaymentMethod(method: string): method is PaymentMethod {
+  return (PAYMENT_METHODS as readonly string[]).includes(method)
+}
+
+export function paymentMethodLabel(
+  method: string,
+  translate: (method: PaymentMethod) => string
+): string {
+  if (isPaymentMethod(method)) return translate(method)
+  return VENDOR_NAMES[method] ?? method
+}
+
+/**
+ * A payment of less than nothing is money handed back: a refund booked in the
+ * ledger and synced in, or a correction. It is listed as a refund, never as a
+ * payment with a minus in front.
+ */
+export function isRefund(amount: number): boolean {
+  return amount < 0
+}

+ 19 - 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 { isRefund, paymentMethodLabel } from '@/features/payments/Lib/paymentMethod'
+import { cn } from '@/lib/utils'
 
 interface PaymentsSectionProps {
   payments: Payment[]
@@ -80,6 +82,7 @@ export function PaymentsSection({
   const [paymentDate, setPaymentDate] = useState(() => workshopTodayKey(timezone))
   const { formatDate } = useFormatDate()
   const formRef = useRef<HTMLDivElement>(null)
+  const methodName = (method: string) => paymentMethodLabel(method, (m) => t(`methodOptions.${m}`))
   const sectionRef = useRef<HTMLDivElement>(null)
 
   useEffect(() => {
@@ -228,17 +231,23 @@ export function PaymentsSection({
             {payments.map((payment) => (
               <li
                 key={payment.id}
-                className="flex items-center justify-between gap-2 rounded-lg bg-emerald-500/10 px-3 py-2 text-sm text-emerald-800 dark:text-emerald-300"
+                className={cn(
+                  'flex items-center justify-between gap-2 rounded-lg px-3 py-2 text-sm',
+                  isRefund(payment.amount)
+                    ? 'bg-muted text-foreground'
+                    : 'bg-emerald-500/10 text-emerald-800 dark:text-emerald-300'
+                )}
               >
                 <span className="min-w-0 truncate">
-                  <strong className="font-semibold capitalize">{payment.method}</strong>
+                  {isRefund(payment.amount) && `${t('refund')} · `}
+                  <strong className="font-semibold">{methodName(payment.method)}</strong>
                   {' · '}
                   {formatDate(new Date(payment.date))}
                   {payment.note ? ` · ${payment.note}` : ''}
                 </span>
                 <span className="flex shrink-0 items-center gap-1">
                   <span className="font-mono font-medium tabular-nums">
-                    {formatCurrency(-payment.amount, currencyCode)}
+                    {formatCurrency(payment.amount, currencyCode)}
                   </span>
                   <Button
                     type="button"
@@ -367,9 +376,14 @@ export function PaymentsSection({
                         {formatCurrency(payment.amount, currencyCode)}
                       </td>
                       <td className="py-1.5">
-                        <Badge variant="outline" className="text-xs capitalize">
-                          {payment.method}
+                        <Badge variant="outline" className="text-xs">
+                          {methodName(payment.method)}
                         </Badge>
+                        {isRefund(payment.amount) && (
+                          <span className="ml-1.5 text-xs text-muted-foreground">
+                            {t('refund')}
+                          </span>
+                        )}
                       </td>
                       <td className="py-1.5 text-muted-foreground">{payment.note || '-'}</td>
                       <td className="py-1.5">