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

Line prices including tax, and part picture saving (#365)

* Option to print line prices including tax

Invoice settings gain a switch. On, every part and labour line, the
category subtotals and the subtotal are printed with tax in them, and the
tax row says how much of the subtotal is tax rather than adding it; off
keeps prices before tax with the tax added below. Applies to invoices,
quotes, their PDFs and the shared copies.

* Keep supplier pictures and older file links storable

* Put the line price switch above the invoice and quote sections

* Keep the line price switch with the other tax settings

* Say where the line price switch applies
Bernt Christian Egeland 2 месяцев назад
Родитель
Сommit
6afb4b5ef2

+ 2 - 0
messages/de/settings.json

@@ -865,6 +865,8 @@
     "modeInclusive": "Inklusiv",
     "modeExclusiveExample": "Beispiel: 100 + {rate}% Steuer = 100 + Steuer obendrauf.",
     "modeInclusiveExample": "Beispiel: 100 enthält bereits {rate}% Steuer — der Steueranteil wird zurückgerechnet.",
+    "lineItemsInclTaxLabel": "Zeilenpreise auf Rechnungen und Angeboten inklusive Steuer anzeigen",
+    "lineItemsInclTaxHint": "Ändert nur, was auf Rechnungen und Angeboten gedruckt wird, einschließlich der PDFs und der Kopien, die Kunden über einen Link öffnen. Ein: Jede Teile- und Arbeitszeile sowie die Zwischensumme werden inklusive Steuer angezeigt, und die Steuerzeile nennt den enthaltenen Steueranteil. Aus: Preise vor Steuer, Steuer wird unten hinzugerechnet. Aufträge und die eingegebenen Preise bleiben unverändert.",
     "labelLabel": "Steuerbezeichnung",
     "labelHint": "Benutzerdefinierter Name, der auf Rechnungen und Angeboten angezeigt wird (z.B. MwSt., USt., VAT). Leer lassen für die übersetzte Standardbezeichnung.",
     "labelPlaceholder": "MwSt.",

+ 2 - 0
messages/en/settings.json

@@ -865,6 +865,8 @@
     "modeInclusive": "Inclusive",
     "modeExclusiveExample": "Example: $100 + {rate}% tax = $100 + tax on top.",
     "modeInclusiveExample": "Example: $100 entered already includes {rate}% tax — the tax portion is reverse-calculated.",
+    "lineItemsInclTaxLabel": "Show line prices including tax on invoices and quotes",
+    "lineItemsInclTaxHint": "Only changes what is printed on invoices and quotes, including their PDFs and the copies customers open from a link. On, each part and labour line and the subtotal are shown with tax included, and the tax row says how much of it is tax. Off shows prices before tax and adds the tax at the bottom. Work orders and the prices you enter are not affected.",
     "labelLabel": "Tax label",
     "labelHint": "Custom name shown on invoices and quotes (e.g. VAT, GST, MVA, MwSt.). Leave blank to use the localized default.",
     "labelPlaceholder": "VAT",

+ 2 - 0
messages/es/settings.json

@@ -865,6 +865,8 @@
     "modeInclusive": "Inclusivo",
     "modeExclusiveExample": "Ejemplo: 100 + {rate}% impuesto = 100 + impuesto encima.",
     "modeInclusiveExample": "Ejemplo: 100 ya incluye {rate}% impuesto — la parte del impuesto se calcula al inverso.",
+    "lineItemsInclTaxLabel": "Mostrar los precios de línea con impuestos en facturas y presupuestos",
+    "lineItemsInclTaxHint": "Solo cambia lo que se imprime en facturas y presupuestos, incluidos sus PDF y las copias que los clientes abren desde un enlace. Activado: cada línea de piezas y mano de obra y el subtotal se muestran con impuestos incluidos, y la fila de impuestos indica qué parte es impuesto. Desactivado: precios sin impuestos y el impuesto se suma al final. Las órdenes de trabajo y los precios que introduces no cambian.",
     "labelLabel": "Etiqueta de impuesto",
     "labelHint": "Nombre personalizado que se muestra en facturas y presupuestos (p. ej. IVA, GST). Dejar vacío para usar el predeterminado localizado.",
     "labelPlaceholder": "IVA",

+ 2 - 0
messages/fr/settings.json

@@ -865,6 +865,8 @@
     "modeInclusive": "Inclusif",
     "modeExclusiveExample": "Exemple : 100 + {rate}% de taxe = 100 + taxe en plus.",
     "modeInclusiveExample": "Exemple : 100 inclut déjà {rate}% de taxe — la part de taxe est calculee en sens inverse.",
+    "lineItemsInclTaxLabel": "Afficher les prix des lignes TTC sur les factures et les devis",
+    "lineItemsInclTaxHint": "Ne change que ce qui est imprimé sur les factures et les devis, y compris leurs PDF et les copies que les clients ouvrent depuis un lien. Activé : chaque ligne de pièces et de main-d'œuvre et le sous-total sont affichés TTC, et la ligne de taxe indique la part de taxe incluse. Désactivé : prix HT avec la taxe ajoutée en bas. Les ordres de travail et les prix que vous saisissez ne sont pas modifiés.",
     "labelLabel": "Libellé de taxe",
     "labelHint": "Nom personnalisé affiché sur les factures et devis (p. ex. TVA, GST). Laisser vide pour utiliser le libellé localisé par défaut.",
     "labelPlaceholder": "TVA",

+ 2 - 0
messages/it/settings.json

@@ -865,6 +865,8 @@
     "modeInclusive": "Inclusivo",
     "modeExclusiveExample": "Esempio: 100 + {rate}% imposta = 100 + imposta sopra.",
     "modeInclusiveExample": "Esempio: 100 include gia {rate}% imposta — la parte fiscale viene calcolata a ritroso.",
+    "lineItemsInclTaxLabel": "Mostra i prezzi delle righe con imposte su fatture e preventivi",
+    "lineItemsInclTaxHint": "Cambia solo ciò che viene stampato su fatture e preventivi, compresi i PDF e le copie che i clienti aprono da un link. Attivo: ogni riga di ricambi e manodopera e il subtotale sono mostrati con imposte incluse, e la riga delle imposte indica quanta parte è imposta. Disattivo: prezzi senza imposte con l'imposta aggiunta in fondo. Gli ordini di lavoro e i prezzi che inserisci non cambiano.",
     "labelLabel": "Etichetta imposta",
     "labelHint": "Nome personalizzato mostrato su fatture e preventivi (es. IVA, GST). Lasciare vuoto per usare il predefinito tradotto.",
     "labelPlaceholder": "IVA",

+ 2 - 0
messages/lt/settings.json

@@ -865,6 +865,8 @@
     "modeInclusive": "Su mokesčiu",
     "modeExclusiveExample": "Pavyzdys: 100 + {rate}% mokesčio = 100 + mokestis viršuje.",
     "modeInclusiveExample": "Pavyzdys: 100 jau apima {rate}% mokesčio — mokesčio dalis apskaičiuojama atgal.",
+    "lineItemsInclTaxLabel": "Sąskaitose ir pasiūlymuose rodyti eilučių kainas su mokesčiu",
+    "lineItemsInclTaxHint": "Keičia tik tai, kas spausdinama sąskaitose ir pasiūlymuose, įskaitant jų PDF ir kopijas, kurias klientai atidaro per nuorodą. Įjungus kiekviena dalių ir darbo eilutė bei tarpinė suma rodomos su mokesčiu, o mokesčio eilutė nurodo, kokia dalis yra mokestis. Išjungus rodomos kainos be mokesčio, o mokestis pridedamas apačioje. Darbo užsakymai ir jūsų įvedamos kainos nesikeičia.",
     "labelLabel": "Mokesčio etiketė",
     "labelHint": "Pasirinktinis pavadinimas, rodomas sąskaitose ir pasiūlymuose (pvz. PVM, VAT). Palikite tuščią, kad būtų naudojama lokalizuota numatytoji.",
     "labelPlaceholder": "PVM",

+ 2 - 0
messages/nb/settings.json

@@ -865,6 +865,8 @@
     "modeInclusive": "Inklusiv",
     "modeExclusiveExample": "Eksempel: 100 + {rate}% avgift = 100 + avgift på toppen.",
     "modeInclusiveExample": "Eksempel: 100 inkluderer allerede {rate}% avgift — avgiftsdelen beregnes baklengs.",
+    "lineItemsInclTaxLabel": "Vis linjepriser inkludert mva på fakturaer og tilbud",
+    "lineItemsInclTaxHint": "Endrer bare det som skrives ut på fakturaer og tilbud, inkludert PDF-ene og kopiene kundene åpner fra en lenke. På: hver dele- og arbeidslinje og delsummen vises inkludert mva, og mva-linjen sier hvor mye av dette som er mva. Av: priser uten mva, med mva lagt til nederst. Arbeidsordrer og prisene du legger inn påvirkes ikke.",
     "labelLabel": "Avgiftsetikett",
     "labelHint": "Tilpasset navn vist på fakturaer og tilbud (f.eks. MVA, GST, MwSt.). La stå tom for å bruke standardverdien.",
     "labelPlaceholder": "MVA",

+ 2 - 0
messages/nl/settings.json

@@ -865,6 +865,8 @@
     "modeInclusive": "Inclusief",
     "modeExclusiveExample": "Voorbeeld: 100 + {rate}% belasting = 100 + belasting erbovenop.",
     "modeInclusiveExample": "Voorbeeld: 100 bevat al {rate}% belasting — het belastingdeel wordt teruggerekend.",
+    "lineItemsInclTaxLabel": "Regelprijzen inclusief btw tonen op facturen en offertes",
+    "lineItemsInclTaxHint": "Verandert alleen wat op facturen en offertes wordt afgedrukt, inclusief de PDF's en de kopieën die klanten via een link openen. Aan: elke onderdelen- en arbeidsregel en het subtotaal worden inclusief btw getoond, en de btw-regel vermeldt hoeveel daarvan btw is. Uit: prijzen exclusief btw, met de btw onderaan erbij. Werkorders en de prijzen die u invoert veranderen niet.",
     "labelLabel": "Belastinglabel",
     "labelHint": "Aangepaste naam getoond op facturen en offertes (bijv. Btw, VAT). Leeg laten voor de gelokaliseerde standaardwaarde.",
     "labelPlaceholder": "Btw",

+ 2 - 0
messages/pl/settings.json

@@ -865,6 +865,8 @@
     "modeInclusive": "Brutto",
     "modeExclusiveExample": "Przyklad: 100 + {rate}% podatku = 100 + podatek doliczony.",
     "modeInclusiveExample": "Przyklad: 100 juz zawiera {rate}% podatku — część podatkowa jest obliczana wstecz.",
+    "lineItemsInclTaxLabel": "Pokazuj ceny pozycji z podatkiem na fakturach i wycenach",
+    "lineItemsInclTaxHint": "Zmienia tylko to, co jest drukowane na fakturach i wycenach, w tym ich PDF-y i kopie otwierane przez klientów z linku. Włączone: każda pozycja części i robocizny oraz suma częściowa są pokazywane z podatkiem, a wiersz podatku podaje, ile z tego stanowi podatek. Wyłączone: ceny bez podatku, z podatkiem doliczonym na dole. Zlecenia i wpisywane ceny pozostają bez zmian.",
     "labelLabel": "Etykieta podatku",
     "labelHint": "Własna nazwa wyświetlana na fakturach i ofertach (np. VAT, MwSt.). Pozostaw puste, aby użyć domyślnej zlokalizowanej nazwy.",
     "labelPlaceholder": "VAT",

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

@@ -865,6 +865,8 @@
     "modeInclusive": "Inclusivo",
     "modeExclusiveExample": "Exemplo: 100 + {rate}% de imposto = 100 + imposto por cima.",
     "modeInclusiveExample": "Exemplo: 100 ja inclui {rate}% de imposto — a parte do imposto e calculada de tras para frente.",
+    "lineItemsInclTaxLabel": "Mostrar preços das linhas com impostos em faturas e orçamentos",
+    "lineItemsInclTaxHint": "Altera apenas o que é impresso em faturas e orçamentos, incluindo os PDFs e as cópias que os clientes abrem por link. Ligado: cada linha de peças e mão de obra e o subtotal aparecem com impostos incluídos, e a linha de impostos indica quanto disso é imposto. Desligado: preços sem impostos, com o imposto somado no final. Ordens de serviço e os preços que você digita não mudam.",
     "labelLabel": "Rótulo de imposto",
     "labelHint": "Nome personalizado exibido em faturas e orçamentos (ex. ICMS, IVA). Deixe em branco para usar o padrão traduzido.",
     "labelPlaceholder": "Imposto",

+ 2 - 0
messages/ru/settings.json

@@ -865,6 +865,8 @@
     "modeInclusive": "С НДС",
     "modeExclusiveExample": "Пример: 100 + {rate}% налога = 100 + налог сверху.",
     "modeInclusiveExample": "Пример: 100 уже включает {rate}% налога — налоговая часть рассчитывается в обратном порядке.",
+    "lineItemsInclTaxLabel": "Показывать цены строк с налогом в счетах и предложениях",
+    "lineItemsInclTaxHint": "Меняет только то, что печатается в счетах и предложениях, включая их PDF и копии, которые клиенты открывают по ссылке. Вкл.: каждая строка запчастей и работ и промежуточный итог показываются с налогом, а строка налога указывает, сколько из этого налог. Выкл.: цены без налога, налог добавляется внизу. Заказ-наряды и вводимые вами цены не меняются.",
     "labelLabel": "Метка налога",
     "labelHint": "Пользовательское название, отображаемое в счетах и коммерческих предложениях (напр. НДС, VAT). Оставьте пустым для локализованного значения по умолчанию.",
     "labelPlaceholder": "НДС",

+ 2 - 0
messages/tr/settings.json

@@ -865,6 +865,8 @@
     "modeInclusive": "Dahil",
     "modeExclusiveExample": "Örnek: 100 + %{rate} vergi = 100 + üstüne vergi.",
     "modeInclusiveExample": "Örnek: 100 zaten %{rate} vergiyi içeriyor — vergi kısmı geriye doğru hesaplanır.",
+    "lineItemsInclTaxLabel": "Fatura ve tekliflerde satır fiyatlarını vergi dahil göster",
+    "lineItemsInclTaxHint": "Yalnızca fatura ve tekliflerde basılanı değiştirir; PDF'leri ve müşterilerin bağlantıdan açtığı kopyalar dahil. Açık: her parça ve işçilik satırı ile ara toplam vergi dahil gösterilir, vergi satırı bunun ne kadarının vergi olduğunu belirtir. Kapalı: fiyatlar vergisiz gösterilir, vergi en altta eklenir. İş emirleri ve girdiğiniz fiyatlar etkilenmez.",
     "labelLabel": "Vergi etiketi",
     "labelHint": "Faturalar ve tekliflerde gösterilen özel ad (örn. KDV, VAT). Yerelleştirilmiş varsayılanı kullanmak için boş bırakın.",
     "labelPlaceholder": "KDV",

+ 146 - 0
src/__tests__/features/settings/line-items-incl-tax.test.ts

@@ -0,0 +1,146 @@
+import { describe, expect, it } from 'vitest'
+import { buildInvoicePrintSpec } from '@/features/invoice-designer/Pdf/buildInvoicePrint'
+import { buildQuotePrintSpec } from '@/features/invoice-designer/Pdf/buildQuotePrint'
+import type { InvoiceData } from '@/features/vehicles/Components/invoice-pdf/types'
+
+/** Every string the sheet prints, for looking up an amount or a label. */
+function printed(spec: unknown): string {
+  return JSON.stringify(spec)
+}
+
+const invoice: InvoiceData = {
+  id: 'svc_1',
+  title: 'Brakes',
+  description: null,
+  type: 'repair',
+  serviceDate: new Date('2026-08-14'),
+  invoiceDate: new Date('2026-08-14'),
+  invoiceDueDate: new Date('2026-08-24'),
+  shopName: 'Testshop',
+  techName: 'Jamie',
+  mileage: 1000,
+  diagnosticNotes: null,
+  invoiceNotes: null,
+  subtotal: 300,
+  taxRate: 25,
+  taxAmount: 75,
+  totalAmount: 375,
+  cost: 375,
+  invoiceNumber: 'INV-1',
+  discountType: null,
+  discountValue: 0,
+  discountAmount: 0,
+  partItems: [{ partNumber: 'P1', name: 'Pads', quantity: 1, unitPrice: 200, total: 200 }],
+  laborItems: [{ description: 'Fit', hours: 1, rate: 100, total: 100 }],
+  customFields: [],
+  findings: [],
+  warrantyMonths: null,
+  warrantyMileage: null,
+  warrantyExpiresAt: null,
+  warrantyNotes: null,
+  customer: {
+    name: 'Alex',
+    email: null,
+    phone: null,
+    address: null,
+    company: null,
+    customerNumber: null,
+  },
+  vehicle: {
+    make: 'Volvo',
+    model: 'V60',
+    year: 2021,
+    vin: null,
+    licensePlate: 'AB 12345',
+    mileage: 1000,
+    customer: null,
+  },
+} as unknown as InvoiceData
+
+const labels = {
+  subtotal: 'Subtotal',
+  subtotalInclTax: 'Subtotal (incl. tax)',
+  tax: 'VAT ({rate}%)',
+  taxIncluded: 'Includes VAT ({rate}%)',
+  total: 'Total',
+}
+
+describe('line prices including tax', () => {
+  it('prints prices before tax by default, with the tax added below', () => {
+    const out = printed(
+      buildInvoicePrintSpec({ data: invoice, labels, invoiceSettings: { currencyCode: 'USD' } })
+    )
+    expect(out).toContain('$200.00')
+    expect(out).toContain('Subtotal')
+    expect(out).not.toContain('Subtotal (incl. tax)')
+    expect(out).toContain('VAT (25%)')
+    expect(out).toContain('$375.00')
+  })
+
+  it('prints each line with tax in it when the workshop asks, and says how much is tax', () => {
+    const out = printed(
+      buildInvoicePrintSpec({
+        data: invoice,
+        labels,
+        invoiceSettings: { currencyCode: 'USD', lineItemsInclTax: true },
+      })
+    )
+    expect(out).toContain('$250.00')
+    expect(out).toContain('$125.00')
+    expect(out).toContain('Subtotal (incl. tax)')
+    expect(out).toContain('$375.00')
+    expect(out).toContain('Includes VAT (25%)')
+    expect(out).toContain('$75.00')
+  })
+
+  it('leaves prices alone when there is no tax', () => {
+    const out = printed(
+      buildInvoicePrintSpec({
+        data: { ...invoice, taxRate: 0, taxAmount: 0, totalAmount: 300, cost: 300 },
+        labels,
+        invoiceSettings: { currencyCode: 'USD', lineItemsInclTax: true },
+      })
+    )
+    expect(out).toContain('$200.00')
+    expect(out).not.toContain('incl. tax')
+  })
+
+  it('does the same on a quote', () => {
+    const quote = {
+      id: 'q1',
+      quoteNumber: 'Q-1',
+      title: 'Brakes',
+      description: null,
+      status: 'sent',
+      validUntil: null,
+      createdAt: new Date('2026-08-14'),
+      taxRate: 25,
+      taxInclusive: false,
+      discountType: null,
+      discountValue: 0,
+      partItems: [{ partNumber: 'P1', name: 'Pads', quantity: 1, unitPrice: 200, total: 200 }],
+      laborItems: [{ description: 'Fit', hours: 1, rate: 100, total: 100 }],
+      customer: { name: 'Alex', email: null, phone: null, address: null },
+      vehicle: {
+        make: 'Volvo',
+        model: 'V60',
+        year: 2021,
+        licensePlate: 'AB 12345',
+        vin: null,
+        mileage: null,
+      },
+      notes: null,
+    }
+    const out = printed(
+      buildQuotePrintSpec({
+        data: quote as unknown as Parameters<typeof buildQuotePrintSpec>[0]['data'],
+        labels,
+        currencyCode: 'USD',
+        lineItemsInclTax: true,
+      })
+    )
+    expect(out).toContain('$250.00')
+    expect(out).toContain('Subtotal (incl. tax)')
+    expect(out).toContain('Includes VAT (25%)')
+  })
+})

+ 41 - 0
src/__tests__/lib/upload-url.test.ts

@@ -4,6 +4,7 @@ import { resolveUploadPath, safeUploadPath, UploadPathError } from '@/lib/resolv
 import {
   assertOwnUploads,
   extensionForType,
+  imageUrlSchema,
   isOwnUploadUrl,
   optionalUploadUrlSchema,
   parseUploadUrl,
@@ -12,6 +13,8 @@ import {
 } from '@/lib/upload-url'
 import { createVehicleSchema } from '@/features/vehicles/Schema/vehicleSchema'
 import { quoteAttachmentSchema } from '@/features/quotes/Schema/quoteSchema'
+import { createInventoryPartSchema } from '@/features/inventory/Schema/inventorySchema'
+import { serviceAttachmentSchema } from '@/features/vehicles/Schema/serviceSchema'
 
 const root = path.join(process.cwd(), 'data', 'uploads')
 
@@ -97,6 +100,44 @@ describe('upload schemas', () => {
     expect(optionalUploadUrlSchema.safeParse('').success).toBe(true)
   })
 
+  it('keep accepting the shapes older records were stored with', () => {
+    // A service edit sends every attachment in the category back, including
+    // ones stored before uploads were served per organisation.
+    expect(
+      serviceAttachmentSchema.shape.fileUrl.safeParse('/api/files/a/services/s.pdf').success
+    ).toBe(true)
+    expect(serviceAttachmentSchema.shape.fileUrl.safeParse('/uploads/services/s.pdf').success).toBe(
+      true
+    )
+    expect(uploadUrlSchema.safeParse('/uploads/../.env').success).toBe(false)
+    expect(uploadUrlSchema.safeParse('/uploads/services/../../.env').success).toBe(false)
+    expect(uploadUrlSchema.safeParse('/uploads/services/deep/s.pdf').success).toBe(false)
+  })
+
+  it('let a part picture be a supplier link as well as an upload', () => {
+    const gallery = createInventoryPartSchema.shape.gallery
+    const supplier = 'https://productimages.example.com/v1/Image/product/xlarge/2000035839/2'
+    expect(gallery.safeParse([{ url: supplier }]).success).toBe(true)
+    expect(gallery.safeParse([{ url: 'http://cdn.example.net/thumb?id=1&m=0' }]).success).toBe(true)
+    expect(gallery.safeParse([{ url: '/api/protected/files/a/inventory/p.jpg' }]).success).toBe(
+      true
+    )
+    for (const bad of [
+      'javascript:alert(1)',
+      'data:image/png;base64,AAAA',
+      'file:///etc/passwd',
+      '/api/protected/files/a/inventory/../../.env',
+      'not a url',
+    ]) {
+      expect(imageUrlSchema.safeParse(bad).success, bad).toBe(false)
+    }
+    // Whose upload it is stays a separate question, answered after parsing.
+    expect(() =>
+      assertOwnUploads({ gallery: [{ url: '/api/protected/files/b/inventory/p.jpg' }] }, 'a')
+    ).toThrow(/not an upload of this workshop/)
+    expect(() => assertOwnUploads({ gallery: [{ url: supplier }] }, 'a')).not.toThrow()
+  })
+
   it('reach the vehicle image and the quote attachment', () => {
     expect(
       createVehicleSchema.shape.imageUrl.safeParse('/api/protected/files/../../.env').success

+ 1 - 0
src/app/(authenticated)/settings/tax/page.tsx

@@ -10,6 +10,7 @@ export default async function TaxSettingsPage() {
       SETTING_KEYS.DEFAULT_TAX_RATE,
       SETTING_KEYS.TAX_INCLUSIVE,
       SETTING_KEYS.TAX_LABEL,
+      SETTING_KEYS.INVOICE_LINE_ITEMS_INCL_TAX,
     ]),
     getTaxBackfillCounts(),
   ])

+ 21 - 0
src/app/(authenticated)/settings/tax/tax-settings.tsx

@@ -37,6 +37,9 @@ export function TaxSettings({
   )
   const [taxInclusive, setTaxInclusive] = useState(settings[SETTING_KEYS.TAX_INCLUSIVE] === 'true')
   const [taxLabel, setTaxLabel] = useState(settings[SETTING_KEYS.TAX_LABEL] || '')
+  const [lineItemsInclTax, setLineItemsInclTax] = useState(
+    settings[SETTING_KEYS.INVOICE_LINE_ITEMS_INCL_TAX] === 'true'
+  )
 
   const handleSave = async () => {
     setSaving(true)
@@ -45,6 +48,7 @@ export function TaxSettings({
       [SETTING_KEYS.DEFAULT_TAX_RATE]: taxEnabled ? defaultTaxRate : '0',
       [SETTING_KEYS.TAX_INCLUSIVE]: String(taxInclusive),
       [SETTING_KEYS.TAX_LABEL]: taxLabel.trim(),
+      [SETTING_KEYS.INVOICE_LINE_ITEMS_INCL_TAX]: String(lineItemsInclTax),
     })
     setSaving(false)
     router.refresh()
@@ -187,6 +191,23 @@ export function TaxSettings({
               </div>
             )}
 
+            {/* How the sheet shows it, as distinct from how it was entered:
+                a shop may key in prices before tax and still hand the
+                customer lines they can add up to the total they pay. */}
+            {taxEnabled && (
+              <div className="flex items-start justify-between gap-4">
+                <div className="space-y-1">
+                  <Label htmlFor="lineItemsInclTax">{t('tax.lineItemsInclTaxLabel')}</Label>
+                  <p className="text-xs text-muted-foreground">{t('tax.lineItemsInclTaxHint')}</p>
+                </div>
+                <Switch
+                  id="lineItemsInclTax"
+                  checked={lineItemsInclTax}
+                  onCheckedChange={setLineItemsInclTax}
+                />
+              </div>
+            )}
+
             {/* Hidden for now: applying tax to existing records can drop
                   exclusive-mode invoices from "paid" to "partial" because the
                   recomputed totalAmount no longer matches the existing payments.

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

@@ -118,6 +118,7 @@ export default async function PublicQuotePage({
             'workshop.serviceType',
             'workshop.taxLabel',
             'workshop.orgNumberLabel',
+            'invoice.lineItemsInclTax',
           ],
         },
       },
@@ -200,6 +201,7 @@ export default async function PublicQuotePage({
 
   const spec = buildQuotePrintSpec({
     data: quote,
+    lineItemsInclTax: settingsMap['invoice.lineItemsInclTax'] === 'true',
     workshop,
     currencyCode,
     currencyFormat,

+ 1 - 0
src/app/api/protected/quotes/[id]/pdf/route.ts

@@ -206,6 +206,7 @@ export async function GET(_request: Request, { params }: { params: Promise<{ id:
     }
 
     const element = React.createElement(QuotePDF, {
+      lineItemsInclTax: settingsMap['invoice.lineItemsInclTax'] === 'true',
       data: quote,
       workshop: {
         name: org?.name || '',

+ 1 - 0
src/app/api/public/share/quote/[orgId]/[token]/pdf/route.ts

@@ -213,6 +213,7 @@ export async function GET(
     const portalUrl = portalEnabled ? `${appUrl}/portal/${portalSlug || orgId}` : undefined
 
     const element = React.createElement(QuotePDF, {
+      lineItemsInclTax: settingsMap['invoice.lineItemsInclTax'] === 'true',
       data: quote,
       workshop: {
         name: org?.name || '',

+ 2 - 2
src/features/inventory/Schema/inventorySchema.ts

@@ -1,5 +1,5 @@
 import { z } from 'zod'
-import { uploadUrlSchema } from '@/lib/upload-url'
+import { imageUrlSchema } from '@/lib/upload-url'
 
 export const createInventoryPartSchema = z.object({
   name: z.string().min(1, 'Part name is required'),
@@ -20,7 +20,7 @@ export const createInventoryPartSchema = z.object({
     .array(
       z.object({
         id: z.string().optional(),
-        url: uploadUrlSchema,
+        url: imageUrlSchema,
         fileName: z.string().optional(),
         description: z.string().optional(),
         sortOrder: z.number().int().default(0),

+ 33 - 16
src/features/invoice-designer/Pdf/buildInvoicePrint.ts

@@ -120,6 +120,12 @@ export function buildInvoicePrintSpec(input: InvoicePrintInput): DocumentSpec {
   const taxRate = data.taxRate
   const taxInclusive = data.taxInclusive ?? false
   const net = (value: number) => netLineTotal(value, taxRate, taxInclusive)
+  // A workshop may print each line with tax in it, the way a consumer
+  // receipt reads: the lines then sum to the subtotal, and the tax row says
+  // how much of that is tax rather than adding it on.
+  const linesInclTax = invoiceSettings?.lineItemsInclTax === true && taxRate > 0
+  const gross = (value: number) => (taxInclusive ? value : value * (1 + taxRate / 100))
+  const shown = linesInclTax ? gross : net
 
   const partsSubtotal = data.partItems.reduce((sum, p) => sum + p.total, 0)
   const laborSubtotal = data.laborItems.reduce((sum, l) => sum + l.total, 0)
@@ -233,8 +239,8 @@ export function buildInvoicePrintSpec(input: InvoicePrintInput): DocumentSpec {
       qty: String(l.hours),
       unit: l.pricingType === 'service' ? L('unit', 'unit') : L('hrs', 'hrs'),
       desc: l.description,
-      price: money(net(l.rate)),
-      total: money(net(l.total)),
+      price: money(shown(l.rate)),
+      total: money(shown(l.total)),
     })),
     ...data.partItems.map((p, i) => ({
       n: String(data.laborItems.length + i + 1),
@@ -242,8 +248,8 @@ export function buildInvoicePrintSpec(input: InvoicePrintInput): DocumentSpec {
       unit: p.unit || '',
       desc: p.name,
       sub: p.partNumber || undefined,
-      price: money(net(p.unitPrice)),
-      total: money(net(p.total)),
+      price: money(shown(p.unitPrice)),
+      total: money(shown(p.total)),
     })),
   ]
 
@@ -251,8 +257,8 @@ export function buildInvoicePrintSpec(input: InvoicePrintInput): DocumentSpec {
     ref: p.partNumber || '-',
     desc: p.name,
     qty: formatQuantity(p.quantity, p.unit),
-    price: money(net(p.unitPrice)),
-    total: money(net(p.total)),
+    price: money(shown(p.unitPrice)),
+    total: money(shown(p.total)),
   }))
 
   const labor: DocumentData['labor'] = data.laborItems.map((l) => {
@@ -261,11 +267,11 @@ export function buildInvoicePrintSpec(input: InvoicePrintInput): DocumentSpec {
       desc: l.description,
       qty: isService ? `${l.hours} ${L('unit', 'unit')}` : `${l.hours} ${L('hrs', 'hrs')}`,
       rate: isService
-        ? money(net(l.rate))
+        ? money(shown(l.rate))
         : labels.ratePerHour
-          ? fillTemplate(labels.ratePerHour, { rate: money(net(l.rate)) })
-          : `${money(net(l.rate))}/hr`,
-      total: money(net(l.total)),
+          ? fillTemplate(labels.ratePerHour, { rate: money(shown(l.rate)) })
+          : `${money(shown(l.rate))}/hr`,
+      total: money(shown(l.total)),
     }
   })
 
@@ -293,16 +299,22 @@ export function buildInvoicePrintSpec(input: InvoicePrintInput): DocumentSpec {
   const itemsTableVisible = layout.sections.some((s) => s.id === 'items_table' && s.visible)
   const totals: TotalLine[] = []
   if (!itemsTableVisible && data.partItems.length > 0) {
-    totals.push({ label: L('parts', 'Parts'), value: money(net(partsSubtotal)), kind: 'line' })
+    totals.push({ label: L('parts', 'Parts'), value: money(shown(partsSubtotal)), kind: 'line' })
   }
   if (!itemsTableVisible && data.laborItems.length > 0) {
-    totals.push({ label: L('labor', 'Labor'), value: money(net(laborSubtotal)), kind: 'line' })
+    totals.push({ label: L('labor', 'Labor'), value: money(shown(laborSubtotal)), kind: 'line' })
   }
-  const displaySubtotal = net(data.subtotal)
+  const displaySubtotal = shown(data.subtotal)
   if (displaySubtotal > 0) {
-    totals.push({ label: L('subtotal', 'Subtotal'), value: money(displaySubtotal), kind: 'line' })
+    totals.push({
+      label: linesInclTax
+        ? L('subtotalInclTax', 'Subtotal (incl. tax)')
+        : L('subtotal', 'Subtotal'),
+      value: money(displaySubtotal),
+      kind: 'line',
+    })
   }
-  const displayDiscount = net(data.discountAmount ?? 0)
+  const displayDiscount = shown(data.discountAmount ?? 0)
   if (displayDiscount > 0) {
     totals.push({
       label:
@@ -316,8 +328,13 @@ export function buildInvoicePrintSpec(input: InvoicePrintInput): DocumentSpec {
     })
   }
   if (taxRate > 0) {
+    const rate = { rate: String(taxRate) }
     totals.push({
-      label: labels.tax ? fillTemplate(labels.tax, { rate: String(taxRate) }) : `Tax (${taxRate}%)`,
+      label: linesInclTax
+        ? fillTemplate(L('taxIncluded', 'Includes tax ({rate}%)'), rate)
+        : labels.tax
+          ? fillTemplate(labels.tax, rate)
+          : `Tax (${taxRate}%)`,
       value: money(data.taxAmount),
       kind: 'line',
     })

+ 35 - 17
src/features/invoice-designer/Pdf/buildQuotePrint.ts

@@ -93,6 +93,8 @@ export interface QuotePrintInput {
   customFields?: Array<{ fieldId: string; label: string; value: string; fieldType: string }>
   labels?: Record<string, string>
   layoutConfig?: InvoiceLayoutConfig
+  /** Print each line with tax included, and say how much of the subtotal is tax. */
+  lineItemsInclTax?: boolean
 }
 
 function fillTemplate(template: string, values: Record<string, string>): string {
@@ -140,6 +142,11 @@ export function buildQuotePrintSpec(input: QuotePrintInput): DocumentSpec {
   const taxRate = data.taxRate
   const taxInclusive = data.taxInclusive ?? false
   const net = (value: number) => netLineTotal(value, taxRate, taxInclusive)
+  // The same choice the invoice offers: lines with tax in them, the subtotal
+  // following, and the tax row saying how much of it is tax.
+  const linesInclTax = input.lineItemsInclTax === true && taxRate > 0
+  const gross = (value: number) => (taxInclusive ? value : value * (1 + taxRate / 100))
+  const shown = linesInclTax ? gross : net
 
   const df = input.dateFormat || DEFAULT_DATE_FORMAT
   const tz = input.timezone || undefined
@@ -203,8 +210,8 @@ export function buildQuotePrintSpec(input: QuotePrintInput): DocumentSpec {
       qty: String(l.hours),
       unit: l.pricingType === 'service' ? L('unit', 'unit') : L('hrs', 'hrs'),
       desc: l.description,
-      price: money(net(l.rate)),
-      total: money(net(l.total)),
+      price: money(shown(l.rate)),
+      total: money(shown(l.total)),
       excluded: l.excluded,
     })),
     ...data.partItems.map((p, i) => ({
@@ -213,8 +220,8 @@ export function buildQuotePrintSpec(input: QuotePrintInput): DocumentSpec {
       unit: p.unit || '',
       desc: p.name,
       sub: p.partNumber || undefined,
-      price: money(net(p.unitPrice)),
-      total: money(net(p.total)),
+      price: money(shown(p.unitPrice)),
+      total: money(shown(p.total)),
       excluded: p.excluded,
     })),
   ]
@@ -223,8 +230,8 @@ export function buildQuotePrintSpec(input: QuotePrintInput): DocumentSpec {
     ref: p.partNumber || '-',
     desc: p.name,
     qty: formatQuantity(p.quantity, p.unit),
-    price: money(net(p.unitPrice)),
-    total: money(net(p.total)),
+    price: money(shown(p.unitPrice)),
+    total: money(shown(p.total)),
     excluded: p.excluded,
   }))
 
@@ -234,11 +241,11 @@ export function buildQuotePrintSpec(input: QuotePrintInput): DocumentSpec {
       desc: l.description,
       qty: isService ? `${l.hours} ${L('unit', 'unit')}` : `${l.hours} ${L('hrs', 'hrs')}`,
       rate: isService
-        ? money(net(l.rate))
+        ? money(shown(l.rate))
         : labels.ratePerHour
-          ? fillTemplate(labels.ratePerHour, { rate: money(net(l.rate)) })
-          : `${money(net(l.rate))}/hr`,
-      total: money(net(l.total)),
+          ? fillTemplate(labels.ratePerHour, { rate: money(shown(l.rate)) })
+          : `${money(shown(l.rate))}/hr`,
+      total: money(shown(l.total)),
       excluded: l.excluded,
     }
   })
@@ -263,15 +270,21 @@ export function buildQuotePrintSpec(input: QuotePrintInput): DocumentSpec {
   const itemsTableVisible = layout.sections.some((s) => s.id === 'items_table' && s.visible)
   const totals: TotalLine[] = []
   if (!itemsTableVisible && data.laborItems.length > 0) {
-    totals.push({ label: L('labor', 'Labor'), value: money(net(laborTotal)), kind: 'line' })
+    totals.push({ label: L('labor', 'Labor'), value: money(shown(laborTotal)), kind: 'line' })
   }
   if (!itemsTableVisible && data.partItems.length > 0) {
-    totals.push({ label: L('parts', 'Parts'), value: money(net(partsTotal)), kind: 'line' })
+    totals.push({ label: L('parts', 'Parts'), value: money(shown(partsTotal)), kind: 'line' })
   }
-  if (net(subtotal) > 0) {
-    totals.push({ label: L('subtotal', 'Subtotal'), value: money(net(subtotal)), kind: 'line' })
+  if (shown(subtotal) > 0) {
+    totals.push({
+      label: linesInclTax
+        ? L('subtotalInclTax', 'Subtotal (incl. tax)')
+        : L('subtotal', 'Subtotal'),
+      value: money(shown(subtotal)),
+      kind: 'line',
+    })
   }
-  if (net(discount) > 0) {
+  if (shown(discount) > 0) {
     totals.push({
       label:
         data.discountType === 'percentage'
@@ -279,13 +292,18 @@ export function buildQuotePrintSpec(input: QuotePrintInput): DocumentSpec {
             ? fillTemplate(labels.discountPercent, { percent: String(data.discountValue) })
             : `Discount (${data.discountValue}%)`
           : L('discount', 'Discount'),
-      value: money(-net(discount)),
+      value: money(-shown(discount)),
       kind: 'discount',
     })
   }
   if (taxRate > 0) {
+    const rate = { rate: String(taxRate) }
     totals.push({
-      label: labels.tax ? fillTemplate(labels.tax, { rate: String(taxRate) }) : `Tax (${taxRate}%)`,
+      label: linesInclTax
+        ? fillTemplate(L('taxIncluded', 'Includes tax ({rate}%)'), rate)
+        : labels.tax
+          ? fillTemplate(labels.tax, rate)
+          : `Tax (${taxRate}%)`,
       value: money(taxAmount),
       kind: 'line',
     })

+ 1 - 0
src/features/invoices/Lib/assembleInvoicePrint.ts

@@ -176,6 +176,7 @@ function liveInvoiceSettings(settingsMap: Record<string, string>): InvoiceSettin
     footerNote: settingsMap['invoice.footerNote'] || '',
     showBankAccount: settingsMap['invoice.showBankAccount'] === 'true',
     showOrgNumber: settingsMap['invoice.showOrgNumber'] === 'true',
+    lineItemsInclTax: settingsMap['invoice.lineItemsInclTax'] === 'true',
     dueDays: Number(settingsMap['invoice.dueDays']) || 0,
     currencyCode: settingsMap['workshop.currencyCode'] || 'USD',
     currencyFormat: settingsMap['workshop.currencyFormat'] === 'code' ? 'code' : 'symbol',

+ 3 - 0
src/features/quotes/Components/QuotePDF.tsx

@@ -41,6 +41,7 @@ export function QuotePDF({
   customFields = [],
   labels = {},
   layoutConfig,
+  lineItemsInclTax,
 }: {
   data: QuotePrintData
   workshop?: { name: string; address: string; phone: string; email: string; slogan?: string }
@@ -57,10 +58,12 @@ export function QuotePDF({
   pdfAttachmentNames?: string[]
   customFields?: Array<{ fieldId: string; label: string; value: string; fieldType: string }>
   labels?: Record<string, string>
+  lineItemsInclTax?: boolean
   layoutConfig?: InvoiceLayoutConfig
 }) {
   const spec = buildQuotePrintSpec({
     data,
+    lineItemsInclTax,
     workshop,
     currencyCode,
     currencyFormat,

+ 2 - 0
src/features/settings/Schema/settingsSchema.ts

@@ -24,6 +24,7 @@ export const SETTING_KEYS = {
   INVOICE_FOOTER_NOTE: 'invoice.footerNote',
   INVOICE_SHOW_BANK_ACCOUNT: 'invoice.showBankAccount',
   INVOICE_SHOW_ORG_NUMBER: 'invoice.showOrgNumber',
+  INVOICE_LINE_ITEMS_INCL_TAX: 'invoice.lineItemsInclTax',
   INVOICE_DUE_DAYS: 'invoice.dueDays',
   /** See src/lib/document-lock.ts for what these freeze and when. */
   INVOICE_LOCK_ENABLED: 'invoice.lockEnabled',
@@ -254,6 +255,7 @@ export const invoiceSettingsSchema = z.object({
   [SETTING_KEYS.INVOICE_FOOTER_NOTE]: z.string().optional(),
   [SETTING_KEYS.INVOICE_SHOW_BANK_ACCOUNT]: z.string().optional(),
   [SETTING_KEYS.INVOICE_SHOW_ORG_NUMBER]: z.string().optional(),
+  [SETTING_KEYS.INVOICE_LINE_ITEMS_INCL_TAX]: z.string().optional(),
   [SETTING_KEYS.INVOICE_DUE_DAYS]: z.string().optional(),
   [SETTING_KEYS.INVOICE_LOCK_ENABLED]: z.string().optional(),
   [SETTING_KEYS.INVOICE_LOCK_TRIGGER]: z.string().optional(),

+ 2 - 0
src/features/vehicles/Components/invoice-pdf/types.ts

@@ -124,6 +124,8 @@ export interface InvoiceSettingsProps {
   footerNote?: string
   showBankAccount?: boolean
   showOrgNumber?: boolean
+  /** Print each line with tax included, and say how much of the subtotal is tax. */
+  lineItemsInclTax?: boolean
   dueDays?: number
   currencyCode?: string
   currencyFormat?: 'symbol' | 'code'

+ 46 - 4
src/lib/upload-url.ts

@@ -25,7 +25,16 @@ export const UPLOAD_CATEGORIES = [
 export type UploadCategory = (typeof UPLOAD_CATEGORIES)[number]
 
 const UPLOAD_URL =
-  /^\/api\/protected\/files\/([A-Za-z0-9_-]{1,64})\/([a-z-]{1,32})\/([A-Za-z0-9][A-Za-z0-9._-]{0,200})$/
+  /^\/api\/(?:protected\/)?files\/([A-Za-z0-9_-]{1,64})\/([a-z-]{1,32})\/([A-Za-z0-9][A-Za-z0-9._-]{0,200})$/
+
+/**
+ * The shape files had before uploads were served per organisation: a
+ * category folder under public/uploads and one file name. Nothing left on
+ * disk is written this way any more, but records that still carry one are
+ * sent back whole when their owner edits them, so the shape stays storable.
+ * There is no organisation in it to check; the path resolver contains it.
+ */
+const LEGACY_UPLOAD_URL = /^\/uploads\/([a-z-]{1,32})\/([A-Za-z0-9][A-Za-z0-9._-]{0,200})$/
 
 export interface UploadUrlParts {
   organizationId: string
@@ -44,6 +53,29 @@ export function parseUploadUrl(value: string | null | undefined): UploadUrlParts
   return { organizationId, category, file }
 }
 
+/** Whether a value is a file of ours in any of the shapes we have stored. */
+export function isStoredUploadUrl(value: string | null | undefined): boolean {
+  if (!value) return false
+  if (parseUploadUrl(value)) return true
+  const legacy = LEGACY_UPLOAD_URL.exec(value)
+  return !!legacy && !legacy[2].includes('..')
+}
+
+/**
+ * Whether a value is a picture on another site: the address a supplier's
+ * catalogue gives for a part. It never reaches the disk, only an <img>, so
+ * the only thing to refuse is a scheme that could run something.
+ */
+export function isRemoteImageUrl(value: string | null | undefined): boolean {
+  if (!value || value.length > 2000) return false
+  try {
+    const url = new URL(value)
+    return url.protocol === 'https:' || url.protocol === 'http:'
+  } catch {
+    return false
+  }
+}
+
 /** Whether a stored URL names one of this organisation's own uploads. */
 export function isOwnUploadUrl(value: string | null | undefined, organizationId: string): boolean {
   return parseUploadUrl(value)?.organizationId === organizationId
@@ -68,15 +100,25 @@ export function assertOwnUploadUrl(
 export const uploadUrlSchema = z
   .string()
   .max(300)
-  .refine((value) => parseUploadUrl(value) !== null, 'Not an upload of this workshop')
+  .refine((value) => isStoredUploadUrl(value), 'Not an upload of this workshop')
 
 /** The same, but an empty string is allowed for "no file". */
 export const optionalUploadUrlSchema = z
   .string()
   .max(300)
+  .refine((value) => value === '' || isStoredUploadUrl(value), 'Not an upload of this workshop')
+
+/**
+ * A picture that may be one of our uploads or live on another site. Part
+ * images are the case: "fetch from supplier" keeps the catalogue's own
+ * address rather than copying the file, and the record is saved with it.
+ */
+export const imageUrlSchema = z
+  .string()
+  .max(2000)
   .refine(
-    (value) => value === '' || parseUploadUrl(value) !== null,
-    'Not an upload of this workshop'
+    (value) => isStoredUploadUrl(value) || isRemoteImageUrl(value),
+    'Not an upload of this workshop or a web address'
   )
 
 const UPLOAD_PREFIXES = ['/api/protected/files/', '/api/files/']