Free & Open-Source Invoice Generator - No Sign-Up, No Ads, Instant PDF Export, 100% In-Browser, and Fully Customizable Templates.
TypeScript fintechinvoiceinvoice-generatorinvoice-pdfinvoice-templateinvoicesnextjsopen-sourcequotesreactreact-pdf-rendererself-hostedshadcn-uitailwindcsstypescript
feat: per-item discounts (percentage or fixed amount) (#285)
Vlad Sazonauba7225eb4b11
diff --git a/e2e/item-discount.test.ts b/e2e/item-discount.test.tsnew file mode 100644index 0000000..676d577--- /dev/null+++ b/e2e/item-discount.test.ts@@ -0,0 +1,232 @@+import type { Page } from "@playwright/test";++import { type InvoiceData, PDF_DATA_LOCAL_STORAGE_KEY } from "@/app/schema";++// IMPORTANT: we use custom extended test fixture that provides a temporary download directory for each test+import { test, expect } from "./utils/extended-playwright-test";+import {+ expectPdfScreenshot,+ waitForPdfRegeneration,+} from "./utils/pdf-download";++test.describe("Item discounts", () => {+ test.beforeEach(async ({ page }) => {+ // we set the system time to a fixed date, so that the invoice number and other dates are consistent across tests+ await page.clock.setSystemTime(new Date("2025-12-17T00:00:00Z"));++ await page.goto("/");+ await expect(page).toHaveURL("/");+ });++ test("applies percentage and fixed discounts before tax and saves them", async ({+ page,+ }) => {+ const invoiceItemsSection = page.getByTestId("invoice-items-section");++ await fillDiscountedItems(page);++ // Item 1: 10,000.00 - 10% = 9,000.00, VAT 23% on it = 2,070.00+ await expect(+ invoiceItemsSection.getByText(+ "−1,000.00 EUR off. Net after discount: 9,000.00 EUR.",+ ),+ ).toBeVisible();+ await expect(+ invoiceItemsSection+ .getByRole("textbox", { name: "Net Amount", exact: true })+ .nth(0),+ ).toHaveValue("9,000.00");+ await expect(+ invoiceItemsSection+ .getByRole("textbox", { name: "VAT Amount", exact: true })+ .nth(0),+ ).toHaveValue("2,070.00");+ await expect(+ invoiceItemsSection+ .getByRole("textbox", { name: "Pre-tax Amount", exact: true })+ .nth(0),+ ).toHaveValue("11,070.00");++ // Item 2: 4 x 1,250.00 = 5,000.00, minus a fixed 1,000.00 off the whole line = 4,000.00+ await expect(+ invoiceItemsSection+ .getByRole("textbox", { name: "Net Amount", exact: true })+ .nth(1),+ ).toHaveValue("4,000.00");+ await expect(+ invoiceItemsSection+ .getByRole("textbox", { name: "VAT Amount", exact: true })+ .nth(1),+ ).toHaveValue("400.00");++ // 11,070.00 + 4,400.00+ await expect(+ page+ .getByTestId("final-section")+ .getByRole("textbox", { name: "Total", exact: true }),+ ).toHaveValue("15,470.00");++ const storedData = (await page.evaluate((key) => {+ return localStorage.getItem(key);+ }, PDF_DATA_LOCAL_STORAGE_KEY)) as string;+ const parsedData = JSON.parse(storedData) as InvoiceData;++ expect(parsedData.items[0]).toMatchObject({+ discountType: "percentage",+ discountValue: 10,+ discountLabel: "Charitable donation",+ discountAmount: 1000,+ netAmount: 9000,+ });+ expect(parsedData.items[1]).toMatchObject({+ discountType: "amount",+ discountValue: 1000,+ discountAmount: 1000,+ netAmount: 4000,+ });+ expect(parsedData.total).toBe(15_470);++ // a percentage above 100 is rejected+ const discountValueInput = invoiceItemsSection+ .getByRole("spinbutton", { name: "Discount value", exact: true })+ .nth(0);++ await discountValueInput.fill("150");++ await expect(+ invoiceItemsSection.getByText("Discount must be between 0 and 100%"),+ ).toBeVisible();++ // removing the discount brings the item back to its full price+ await discountValueInput.fill("10");+ await invoiceItemsSection+ .getByRole("button", { name: "Remove discount" })+ .nth(0)+ .click();++ await expect(+ invoiceItemsSection+ .getByRole("textbox", { name: "Net Amount", exact: true })+ .nth(0),+ ).toHaveValue("10,000.00");+ });++ test("shows a discount column in the default template PDF", async ({+ page,+ browserName,+ downloadDir,+ }) => {+ await fillDiscountedItems(page);++ const { numPages } = await expectPdfScreenshot(page, {+ downloadDir,+ browserName,+ name: "item-discounts-default-template.png",+ notes: "Item discounts, default template",+ });++ // the extra column does not push the invoice onto a second page+ expect(numPages).toBe(1);+ });++ test("shows a discount row under each discounted item in the Stripe template PDF", async ({+ page,+ browserName,+ downloadDir,+ }) => {+ await page+ .getByTestId("general-information-section")+ .getByRole("combobox", { name: "Invoice Template" })+ .selectOption("stripe");++ await expect(page).toHaveURL("/stripe-template");++ await fillDiscountedItems(page);++ await expectPdfScreenshot(page, {+ downloadDir,+ browserName,+ name: "item-discounts-stripe-template.png",+ notes: "Item discounts, Stripe template",+ });+ });+});++/**+ * Two items: 10,000.00 at 23% VAT with a labelled 10% discount, and 4 x 1,250.00 at 10%+ * VAT with a fixed 1,000.00 discount and no label.+ */+async function fillDiscountedItems(page: Page) {+ const invoiceItemsSection = page.getByTestId("invoice-items-section");++ await invoiceItemsSection+ .getByRole("textbox", { name: "Name", exact: true })+ .nth(0)+ .fill("Frontend engineering");+ await invoiceItemsSection+ .getByRole("spinbutton", {+ name: "Net Price (Rate or Unit Price)",+ exact: true,+ })+ .nth(0)+ .fill("10000");+ await invoiceItemsSection+ .getByRole("textbox", { name: "VAT Rate", exact: true })+ .nth(0)+ .fill("23");++ await invoiceItemsSection+ .getByRole("button", { name: "Add discount" })+ .nth(0)+ .click();+ await invoiceItemsSection+ .getByRole("spinbutton", { name: "Discount value", exact: true })+ .nth(0)+ .fill("10");+ await invoiceItemsSection+ .getByRole("textbox", { name: "Label (optional)", exact: true })+ .nth(0)+ .fill("Charitable donation");++ await invoiceItemsSection+ .getByRole("button", { name: "Add invoice item" })+ .click();+ await expect(+ invoiceItemsSection.getByText("Item 2", { exact: true }),+ ).toBeVisible();++ await invoiceItemsSection+ .getByRole("textbox", { name: "Name", exact: true })+ .nth(1)+ .fill("Backend engineering");+ await invoiceItemsSection+ .getByRole("spinbutton", { name: "Amount (Quantity)", exact: true })+ .nth(1)+ .fill("4");+ await invoiceItemsSection+ .getByRole("spinbutton", {+ name: "Net Price (Rate or Unit Price)",+ exact: true,+ })+ .nth(1)+ .fill("1250");+ await invoiceItemsSection+ .getByRole("textbox", { name: "VAT Rate", exact: true })+ .nth(1)+ .fill("10");++ await invoiceItemsSection+ .getByRole("button", { name: "Add discount" })+ .click();+ await invoiceItemsSection+ .getByRole("radio", { name: "Fixed amount" })+ .nth(1)+ .click();++ await waitForPdfRegeneration(page, async () => {+ await invoiceItemsSection+ .getByTestId("itemDiscount1")+ .getByRole("spinbutton", { name: "Discount value", exact: true })+ .fill("1000");+ });+}diff --git a/e2e/item-discount.test.ts-snapshots/item-discounts-default-template-Desktop-Chrome-darwin.png b/e2e/item-discount.test.ts-snapshots/item-discounts-default-template-Desktop-Chrome-darwin.pngnew file mode 100644index 0000000..e2663bbBinary files /dev/null and b/e2e/item-discount.test.ts-snapshots/item-discounts-default-template-Desktop-Chrome-darwin.png differdiff --git a/e2e/item-discount.test.ts-snapshots/item-discounts-stripe-template-Desktop-Chrome-darwin.png b/e2e/item-discount.test.ts-snapshots/item-discounts-stripe-template-Desktop-Chrome-darwin.pngnew file mode 100644index 0000000..8b97b11Binary files /dev/null and b/e2e/item-discount.test.ts-snapshots/item-discounts-stripe-template-Desktop-Chrome-darwin.png differdiff --git a/e2e/saved-invoice-load-error.test.ts b/e2e/saved-invoice-load-error.test.tsnew file mode 100644index 0000000..c5759af--- /dev/null+++ b/e2e/saved-invoice-load-error.test.ts@@ -0,0 +1,32 @@+import { expect, test } from "@playwright/test";++import { PDF_DATA_LOCAL_STORAGE_KEY } from "@/app/schema";++/** Not an invoice the schema accepts, so loading it fails. */+const UNREADABLE_SAVED_INVOICE = JSON.stringify({ items: "not an array" });++test.describe("Saved invoice that cannot be loaded", () => {+ test("starts a new invoice and says so", async ({ page }) => {+ await page.addInitScript(+ ({ key, value }) => {+ localStorage.setItem(key, value);+ },+ { key: PDF_DATA_LOCAL_STORAGE_KEY, value: UNREADABLE_SAVED_INVOICE },+ );++ await page.goto("/");++ await expect(+ page.getByText(+ "Your saved invoice couldn't be loaded, so you're starting with a new one.",+ ),+ ).toBeVisible();++ // the form shows a blank invoice+ await expect(+ page.getByTestId("invoice-items-section").getByText("Item 1", {+ exact: true,+ }),+ ).toBeVisible();+ });+});diff --git a/src/app/(main)/(app)/components/invoice-form/index.tsx b/src/app/(main)/(app)/components/invoice-form/index.tsxindex b5b7fe4..124b48d 100644--- a/src/app/(main)/(app)/components/invoice-form/index.tsx+++ b/src/app/(main)/(app)/components/invoice-form/index.tsx@@ -493,6 +493,7 @@ export const InvoiceForm = memo(function InvoiceForm({taxLabelText={taxLabelText}numberFormatLocale={numberFormatLocale}getValues={getValues}+ setValue={setValue}/></AccordionContent></AccordionItem>diff --git a/src/app/(main)/(app)/components/invoice-form/sections/__tests__/invoice-items.test.tsx b/src/app/(main)/(app)/components/invoice-form/sections/__tests__/invoice-items.test.tsxindex bac424e..e1e5614 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/__tests__/invoice-items.test.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/__tests__/invoice-items.test.tsx@@ -13,7 +13,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { getInitialInvoiceData } from "@/app/constants";import type * as InvoiceSchema from "@/app/schema";-import type { InvoiceData, SupportedNumberFormatLocale } from "@/app/schema";+import type {+ InvoiceData,+ InvoiceItemData,+ SupportedNumberFormatLocale,+} from "@/app/schema";import { TooltipProvider } from "@/components/ui/tooltip";import { MOCK_INVOICE_ITEM_DATA } from "@/utils/__tests__/data";import "@testing-library/jest-dom/vitest";@@ -61,6 +65,8 @@ interface InvoiceItemsTestHarnessProps {numberFormatLocale?: SupportedNumberFormatLocale;/** The invoice's template, `default` unless a test picks another one. */template?: InvoiceData["template"];+ /** Overrides applied to every item, e.g. to start with a discount. */+ itemOverrides?: Partial<InvoiceItemData>;}function InvoiceItemsTestHarness({@@ -70,6 +76,7 @@ function InvoiceItemsTestHarness({itemNames,numberFormatLocale = "en",template = "default",+ itemOverrides,}: InvoiceItemsTestHarnessProps) {const invoiceData = useMemo(() => {return {@@ -77,13 +84,14 @@ function InvoiceItemsTestHarness({items: Array.from({ length: itemCount }, (_, index) => {return {...MOCK_INVOICE_ITEM_DATA,+ ...itemOverrides,name: itemNames?.[index] ?? MOCK_INVOICE_ITEM_DATA.name,};}),};- }, [itemCount, itemNames]);+ }, [itemCount, itemNames, itemOverrides]);- const { control, getValues } = useForm<InvoiceData>({+ const { control, getValues, setValue } = useForm<InvoiceData>({defaultValues: invoiceData,});@@ -112,6 +120,7 @@ function InvoiceItemsTestHarness({taxLabelText="VAT"numberFormatLocale={numberFormatLocale}getValues={getValues}+ setValue={setValue}/></TooltipProvider>);@@ -190,6 +199,10 @@ describe("InvoiceItems max invoice items", () => {vatAmountFieldIsVisible: true,preTaxAmount: 0,preTaxAmountFieldIsVisible: true,+ discountType: "percentage",+ discountValue: 0,+ discountLabel: "",+ discountAmount: 0,typeOfGTU: "",typeOfGTUFieldIsVisible: true,});@@ -580,3 +593,189 @@ describe("InvoiceItems read-only amounts", () => {},);});++describe("InvoiceItems discount", () => {+ afterEach(() => {+ cleanup();+ });++ it("keeps the discount collapsed behind a button when the item has none", () => {+ renderInvoiceItems({ itemCount: 1 });++ expect(+ screen.getByRole("button", { name: "Add discount" }),+ ).toBeInTheDocument();+ expect(screen.queryByLabelText("Discount value")).not.toBeInTheDocument();+ });++ it("opens the discount fields and focuses the value", async () => {+ const user = userEvent.setup();++ renderInvoiceItems({ itemCount: 1 });++ await user.click(screen.getByRole("button", { name: "Add discount" }));++ expect(screen.getByLabelText("Discount value")).toHaveFocus();+ expect(screen.getByRole("radio", { name: "Percentage" })).toBeChecked();+ expect(screen.getByLabelText(/^Label/)).toHaveValue("");+ });++ it("switches between a percentage and a fixed amount", async () => {+ const user = userEvent.setup();++ renderInvoiceItems({ itemCount: 1 });++ await user.click(screen.getByRole("button", { name: "Add discount" }));+ await user.click(screen.getByRole("radio", { name: "Fixed amount" }));++ expect(screen.getByRole("radio", { name: "Fixed amount" })).toBeChecked();+ expect(screen.getByRole("radio", { name: "Percentage" })).not.toBeChecked();+ });++ it("moves between discount types with the arrow keys, as one tab stop", async () => {+ const user = userEvent.setup();++ renderInvoiceItems({ itemCount: 1 });++ await user.click(screen.getByRole("button", { name: "Add discount" }));++ const percentage = screen.getByRole("radio", { name: "Percentage" });+ const fixedAmount = screen.getByRole("radio", { name: "Fixed amount" });++ expect(percentage).toHaveAttribute("tabindex", "0");+ expect(fixedAmount).toHaveAttribute("tabindex", "-1");++ percentage.focus();+ await user.keyboard("{ArrowRight}");++ expect(fixedAmount).toBeChecked();+ expect(fixedAmount).toHaveFocus();++ // wraps around+ await user.keyboard("{ArrowRight}");++ expect(percentage).toBeChecked();+ expect(percentage).toHaveFocus();+ });++ it("takes both a percentage and a fixed amount as numbers", async () => {+ const user = userEvent.setup();++ renderInvoiceItems({ itemCount: 1 });++ await user.click(screen.getByRole("button", { name: "Add discount" }));++ expect(screen.getByLabelText("Discount value")).toHaveAttribute(+ "type",+ "number",+ );++ await user.click(screen.getByRole("radio", { name: "Fixed amount" }));++ expect(screen.getByLabelText("Discount value")).toHaveAttribute(+ "type",+ "number",+ );+ });++ it("clears the value when switching between a percentage and a fixed amount", async () => {+ const user = userEvent.setup();++ renderInvoiceItems({ itemCount: 1 });++ await user.click(screen.getByRole("button", { name: "Add discount" }));+ await user.type(screen.getByLabelText("Discount value"), "10");++ expect(screen.getByLabelText("Discount value")).toHaveValue(10);++ await user.click(screen.getByRole("radio", { name: "Fixed amount" }));++ expect(screen.getByLabelText("Discount value")).toHaveValue(null);++ // picking the type that is already selected keeps the value+ await user.type(screen.getByLabelText("Discount value"), "50");+ await user.click(screen.getByRole("radio", { name: "Fixed amount" }));++ expect(screen.getByLabelText("Discount value")).toHaveValue(50);+ });++ it("explains a percentage and a fixed amount before a value is entered", async () => {+ const user = userEvent.setup();++ renderInvoiceItems({ itemCount: 1 });++ await user.click(screen.getByRole("button", { name: "Add discount" }));++ expect(+ screen.getByText(+ "Enter a percentage from 0 to 100. It applies to the line total, before tax.",+ ),+ ).toBeInTheDocument();++ await user.click(screen.getByRole("radio", { name: "Fixed amount" }));++ expect(+ screen.getByText(+ "Enter an amount up to the line total. It applies once to the whole line, not per unit.",+ ),+ ).toBeInTheDocument();+ });++ it("says there is nothing to discount while the line total is 0", async () => {+ const user = userEvent.setup();++ renderInvoiceItems({ itemCount: 1, itemOverrides: { netPrice: 0 } });++ await user.click(screen.getByRole("button", { name: "Add discount" }));++ expect(+ screen.getByText(+ "The line total (Amount × Net Price) is 0, so there's nothing to discount yet.",+ ),+ ).toBeInTheDocument();+ expect(+ screen.queryByText(/Enter a percentage from 0 to 100/),+ ).not.toBeInTheDocument();+ });++ it("starts open for an item that already has a discount", () => {+ renderInvoiceItems({+ itemCount: 1,+ itemOverrides: {+ discountType: "amount",+ discountValue: 50,+ discountLabel: "Charitable donation",+ },+ });++ expect(screen.getByLabelText("Discount value")).toHaveValue(50);+ expect(screen.getByLabelText("Discount value")).not.toHaveFocus();+ expect(screen.getByLabelText(/^Label/)).toHaveValue("Charitable donation");+ expect(screen.getByRole("radio", { name: "Fixed amount" })).toBeChecked();+ });++ it("clears the discount on remove and hands focus back to the add button", async () => {+ const user = userEvent.setup();++ renderInvoiceItems({+ itemCount: 1,+ itemOverrides: { discountValue: 10, discountLabel: "Loyalty" },+ });++ await user.click(screen.getByRole("button", { name: "Remove discount" }));++ const addButton = await screen.findByRole("button", {+ name: "Add discount",+ });+ await vi.waitFor(() => {+ expect(addButton).toHaveFocus();+ });++ // reopening shows the cleared fields, not the removed discount+ await user.click(addButton);++ // the cleared zero shows as the empty placeholder+ expect(screen.getByLabelText("Discount value")).toHaveValue(null);+ expect(screen.getByLabelText(/^Label/)).toHaveValue("");+ });+});diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/delete-icon-button.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/delete-icon-button.tsxnew file mode 100644index 0000000..ca99319--- /dev/null+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/delete-icon-button.tsx@@ -0,0 +1,47 @@+import { Trash2 } from "lucide-react";++import { CustomTooltip } from "@/components/ui/tooltip";++/**+ * The round red trash button that sits on the corner of a form section, used to delete an+ * invoice item and to remove an item's discount.+ */+export function DeleteIconButton({+ label,+ tooltip = label,+ onClick,+}: DeleteIconButtonProps) {+ return (+ <CustomTooltip+ trigger={+ <button+ type="button"+ // Safari does not focus a button on mousedown, so focus leaves the+ // field the user was editing and lands on the nearest focusable+ // ancestor -- on mobile that is Radix's tab panel, which Safari then+ // scrolls into view (smoothly, see `globals.css`). The button drifts+ // out from under the finger between mousedown and mouseup, and the+ // browser dispatches the `click` on the common ancestor instead: the+ // tap does nothing. Keeping focus where it is avoids the scroll.+ onMouseDown={(event) => {+ event.preventDefault();+ }}+ onClick={onClick}+ className="flex items-center justify-center rounded-full bg-red-600 p-2 transition-colors hover:bg-red-700 active:scale-[98%] active:transition-transform"+ >+ <span className="sr-only">{label}</span>+ <Trash2 className="h-4 w-4 text-white" />+ </button>+ }+ content={tooltip}+ />+ );+}++interface DeleteIconButtonProps {+ /** What the button does, read out by screen readers, e.g. "Delete Invoice Item 2". */+ label: string;+ /** The tooltip shown on hover. Defaults to `label`. */+ tooltip?: string;+ onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;+}diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/item-discount-fields.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/item-discount-fields.tsxnew file mode 100644index 0000000..1a66d81--- /dev/null+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/item-discount-fields.tsx@@ -0,0 +1,420 @@+import { Plus } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import {+ type Control,+ Controller,+ type FieldErrors,+ type UseFormGetValues,+ type UseFormSetValue,+ useWatch,+} from "react-hook-form";++import {+ ErrorMessage,+ inputErrorClassName,+} from "@/app/(main)/(app)/components/invoice-form/common";+import { DeleteIconButton } from "@/app/(main)/(app)/components/invoice-form/sections/components/delete-icon-button";+import { formatMoneyForTemplate } from "@/app/(main)/(app)/utils/format-money-for-template";+import {+ type InvoiceData,+ type ItemDiscountType,+ type SupportedCurrencies,+ type SupportedNumberFormatLocale,+ MAX_ITEM_DISCOUNT_LABEL_LENGTH,+} from "@/app/schema";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { InputHelperMessage } from "@/components/ui/input-helper-message";+import { Label } from "@/components/ui/label";+import { MoneyInput } from "@/components/ui/money-input";+import { cn } from "@/lib/utils";++/**+ * The per-item discount: collapsed behind an "Add discount" button, since most invoices+ * have none, and open with a type switch (% or fixed amount), the value and an optional+ * label. Removing it resets the fields, so a closed section never leaves a discount behind.+ */+export function ItemDiscountFields({+ control,+ index,+ errors,+ currency,+ template,+ numberFormatLocale,+ getValues,+ setValue,+}: ItemDiscountFieldsProps) {+ const [isOpen, setIsOpen] = useState(() => {+ const item = getValues(`items.${index}`);++ // oxlint-disable-next-line typescript/no-unnecessary-type-conversion -- `<Input type="number">` gives back a string at runtime, the schema type says number+ return Number(item?.discountValue) > 0 || Boolean(item?.discountLabel);+ });+ // focus the value input only when the user opens the section, not when it mounts open+ // for an item that already has a discount (a restored invoice, a shared link)+ const [shouldFocusValue, setShouldFocusValue] = useState(false);+ const addButtonRef = useRef<HTMLButtonElement>(null);++ if (!isOpen) {+ return (+ <Button+ ref={addButtonRef}+ variant="default"+ size="sm"+ className="gap-1.5"+ onClick={() => {+ setIsOpen(true);+ setShouldFocusValue(true);+ }}+ data-testid={`addItemDiscount${index}`}+ >+ <Plus className="size-3.5" />+ Add discount+ </Button>+ );+ }++ return (+ <OpenItemDiscountFields+ control={control}+ index={index}+ errors={errors}+ currency={currency}+ template={template}+ numberFormatLocale={numberFormatLocale}+ shouldFocusValue={shouldFocusValue}+ setValue={setValue}+ onRemove={() => {+ // validate only to clear an error: a validating `setValue` re-renders the whole+ // form in the click's task, see `selectDiscountType`+ setValue(`items.${index}.discountValue`, 0, {+ shouldValidate: !!errors.items?.[index]?.discountValue,+ });+ setValue(`items.${index}.discountLabel`, "");+ setValue(`items.${index}.discountType`, "percentage");+ setIsOpen(false);++ // the section unmounts with the focused button in it, so hand focus to the+ // "Add discount" button that takes its place+ requestAnimationFrame(() => {+ addButtonRef.current?.focus();+ });+ }}+ />+ );+}++/**+ * The open discount section. Its own component so that only an item whose discount is+ * open subscribes to the discount type and the calculated amounts: a collapsed item would+ * otherwise re-render on every keystroke in its net price just to show the same button.+ */+function OpenItemDiscountFields({+ control,+ index,+ errors,+ currency,+ template,+ numberFormatLocale,+ shouldFocusValue,+ setValue,+ onRemove,+}: OpenItemDiscountFieldsProps) {+ // Focus the value once, as the section opens. Not `autoFocus`: switching the type swaps+ // the value input for another one, which would take focus off the type switch. The ref+ // holds what was true at mount, so moving the item (a new `index`) does not refocus it.+ const focusOnMountRef = useRef({ shouldFocusValue, index });++ useEffect(() => {+ const { shouldFocusValue: shouldFocus, index: mountIndex } =+ focusOnMountRef.current;++ if (shouldFocus) {+ document+ .querySelector<HTMLElement>(`#itemDiscountValue${mountIndex}`)+ ?.focus();+ }+ }, []);++ const discountType = useWatch({+ control,+ name: `items.${index}.discountType`,+ });+ const discountAmount = useWatch({+ control,+ name: `items.${index}.discountAmount`,+ });+ const netAmount = useWatch({ control, name: `items.${index}.netAmount` });+ const amount = useWatch({ control, name: `items.${index}.amount` });+ const netPrice = useWatch({ control, name: `items.${index}.netPrice` });++ // Read from the fields rather than the calculated amounts, which only catch up after+ // the totals effect runs, so the message does not flash while typing+ const isLineTotalZero =+ // oxlint-disable-next-line typescript/no-unnecessary-type-conversion -- `<Input type="number">` gives back strings at runtime, the schema types say number+ (Number(amount) || 0) * (Number(netPrice) || 0) === 0;++ const itemErrors = errors.items?.[index];++ const formatMoney = (amount: number) => {+ return formatMoneyForTemplate({+ amount,+ currency,+ numberFormatLocale,+ template,+ });+ };++ return (+ <fieldset+ className="relative rounded-md border px-4 pb-4"+ data-testid={`itemDiscount${index}`}+ >+ <legend className="text-base font-semibold lg:text-lg">Discount</legend>++ {/* Remove discount button, the same one that deletes an invoice item */}+ <div className="absolute -right-3 -top-8">+ <DeleteIconButton+ label="Remove discount"+ tooltip={`Remove discount from Invoice Item ${index + 1}`}+ onClick={onRemove}+ />+ </div>++ <div className="space-y-4">+ <div className="mt-4">+ <Label htmlFor={`itemDiscountValue${index}`}>Discount value</Label>++ <div className="mt-1 flex items-start gap-2">+ {/* Discount type: percentage or fixed amount */}+ <Controller+ name={`items.${index}.discountType`}+ control={control}+ render={({ field }) => {+ // a value means something else under the other type (10% is not 10.00),+ // so switching starts the value over rather than reinterpreting it+ const selectDiscountType = (nextType: ItemDiscountType) => {+ if (nextType === field.value) return;++ field.onChange(nextType);+ // Validate only to clear an error the old value left behind. A+ // validating `setValue` publishes new form errors, which re-renders the+ // whole form in the same task as the click and makes the switch flicker.+ setValue(`items.${index}.discountValue`, 0, {+ shouldValidate: !!itemErrors?.discountValue,+ });+ };++ return (+ <div+ role="radiogroup"+ aria-label={`Discount type for item ${index + 1}`}+ className="inline-flex h-9 shrink-0 items-center gap-0.5 rounded-lg border border-gray-300 bg-slate-100 p-1"+ >+ {DISCOUNT_TYPE_OPTIONS.map((option, optionIndex) => {+ const isSelected = field.value === option.value;++ return (+ <button+ key={option.value}+ type="button"+ role="radio"+ aria-checked={isSelected}+ aria-label={option.ariaLabel}+ // one tab stop for the group, arrows move between the options,+ // as in a native radio group+ tabIndex={isSelected ? 0 : -1}+ onClick={() => {+ selectDiscountType(option.value);+ }}+ onKeyDown={(event) => {+ const step = ARROW_KEY_STEPS[event.key];++ if (!step) return;++ event.preventDefault();++ const nextIndex =+ (optionIndex ++ step ++ DISCOUNT_TYPE_OPTIONS.length) %+ DISCOUNT_TYPE_OPTIONS.length;++ selectDiscountType(+ DISCOUNT_TYPE_OPTIONS[nextIndex].value,+ );+ const radios =+ event.currentTarget.parentElement?.querySelectorAll<HTMLButtonElement>(+ '[role="radio"]',+ );++ radios?.[nextIndex]?.focus();+ }}+ className={cn(+ // no transition: a fading background under a shadow that moves at once+ // reads as a flicker, and a segmented control should switch instantly+ "h-full min-w-7 rounded-md px-1.5 text-xs font-medium tabular-nums",+ isSelected+ ? "bg-white text-slate-950 shadow-sm"+ : "text-slate-600 hover:text-slate-950",+ )}+ >+ {option.value === "amount" ? currency : option.text}+ </button>+ );+ })}+ </div>+ );+ }}+ />++ {/* Discount value */}+ <Controller+ name={`items.${index}.discountValue`}+ control={control}+ render={({ field }) => {+ const inputProps = {+ ...field,+ // the stored zero of an item without a discount shows as the empty+ // placeholder, so typing "10" gives 10 rather than "010". Only the number+ // 0: a typed "0" or "0." is a string and stays, and the schema reads ""+ // back as 0+ value: field.value === 0 ? "" : field.value,+ id: `itemDiscountValue${index}`,+ className: cn(+ "w-full",+ inputErrorClassName(!!itemErrors?.discountValue),+ ),+ } as const;++ return discountType === "amount" ? (+ <div className="w-full">+ <MoneyInput+ {...inputProps}+ type="number"+ step="0.01"+ min="0"+ currency={currency}+ dataTestId={`itemDiscountValue${index}`}+ />+ </div>+ ) : (+ <div className="relative w-full">+ <Input+ {...inputProps}+ type="number"+ step="0.01"+ min="0"+ max="100"+ placeholder="0"+ className={cn(inputProps.className, "pe-8")}+ data-testid={`itemDiscountValue${index}`}+ />+ <span className="pointer-events-none absolute inset-y-0 end-0 flex items-center pe-3 text-sm text-slate-600">+ %+ </span>+ </div>+ );+ }}+ />+ </div>++ {itemErrors?.discountValue ? (+ <ErrorMessage>{itemErrors.discountValue.message}</ErrorMessage>+ ) : (+ <InputHelperMessage>+ {discountAmount > 0 ? (+ <>+ −{formatMoney(discountAmount)} off. Net after discount:{" "}+ {formatMoney(netAmount)}.+ <br />+ Tax is calculated after the discount.+ </>+ ) : isLineTotalZero ? (+ "The line total (Amount × Net Price) is 0, so there's nothing to discount yet."+ ) : discountType === "amount" ? (+ "Enter an amount up to the line total. It applies once to the whole line, not per unit."+ ) : (+ "Enter a percentage from 0 to 100. It applies to the line total, before tax."+ )}+ </InputHelperMessage>+ )}+ </div>++ {/* Discount label */}+ <div>+ <Label htmlFor={`itemDiscountLabel${index}`}>+ Label <span className="font-normal text-slate-500">(optional)</span>+ </Label>+ <Controller+ name={`items.${index}.discountLabel`}+ control={control}+ render={({ field }) => {+ return (+ <Input+ {...field}+ id={`itemDiscountLabel${index}`}+ type="text"+ maxLength={MAX_ITEM_DISCOUNT_LABEL_LENGTH}+ placeholder="e.g. Charitable donation"+ className={cn(+ "mt-1",+ inputErrorClassName(!!itemErrors?.discountLabel),+ )}+ />+ );+ }}+ />+ {itemErrors?.discountLabel ? (+ <ErrorMessage>{itemErrors.discountLabel.message}</ErrorMessage>+ ) : (+ <InputHelperMessage>+ Shown next to the discount in the PDF. Leave empty to show+ "Discount" in the invoice language.+ </InputHelperMessage>+ )}+ </div>+ </div>+ </fieldset>+ );+}++const DISCOUNT_TYPE_OPTIONS = [+ { value: "percentage", text: "%", ariaLabel: "Percentage" },+ { value: "amount", text: "", ariaLabel: "Fixed amount" },+] as const satisfies ReadonlyArray<{+ value: ItemDiscountType;+ text: string;+ ariaLabel: string;+}>;++/** How far each arrow key moves the selection in the discount type switch. */+const ARROW_KEY_STEPS: Partial<Record<string, number>> = {+ ArrowLeft: -1,+ ArrowUp: -1,+ ArrowRight: 1,+ ArrowDown: 1,+};++interface ItemDiscountFieldsProps {+ control: Control<InvoiceData>;+ /** Position of the item in the `items` field array. */+ index: number;+ errors: FieldErrors<InvoiceData>;+ currency: SupportedCurrencies;+ template: InvoiceData["template"];+ /** The invoice's number format, already resolved against its language. */+ numberFormatLocale: SupportedNumberFormatLocale;+ getValues: UseFormGetValues<InvoiceData>;+ setValue: UseFormSetValue<InvoiceData>;+}++interface OpenItemDiscountFieldsProps extends Omit<+ ItemDiscountFieldsProps,+ "getValues"+> {+ /** Focus the value input on mount: the user just opened the section. */+ shouldFocusValue: boolean;+ /** Clears the discount and collapses the section. */+ onRemove: () => void;+}diff --git a/src/app/(main)/(app)/components/invoice-form/sections/invoice-items.tsx b/src/app/(main)/(app)/components/invoice-form/sections/invoice-items.tsxindex 61e3a9b..6db92fc 100644--- a/src/app/(main)/(app)/components/invoice-form/sections/invoice-items.tsx+++ b/src/app/(main)/(app)/components/invoice-form/sections/invoice-items.tsx@@ -1,4 +1,4 @@-import { Plus, Trash2 } from "lucide-react";+import { Plus } from "lucide-react";import { memo, useRef, useState } from "react";import {type Control,@@ -7,13 +7,16 @@ import {type FieldErrors,type UseFieldArrayAppend,type UseFormGetValues,+ type UseFormSetValue,} from "react-hook-form";import { inputErrorClassName } from "@/app/(main)/(app)/components/invoice-form/common";+import { DeleteIconButton } from "@/app/(main)/(app)/components/invoice-form/sections/components/delete-icon-button";import {DeleteInvoiceItemDialog,type ItemPendingDeletion,} from "@/app/(main)/(app)/components/invoice-form/sections/components/delete-invoice-item-dialog";+import { ItemDiscountFields } from "@/app/(main)/(app)/components/invoice-form/sections/components/item-discount-fields";import { INVOICE_PDF_TRANSLATIONS } from "@/app/(main)/(app)/pdf-i18n-translations/pdf-translations";import { formatAmount } from "@/app/(main)/(app)/utils/format-amount";import { formatMoneyForTemplate } from "@/app/(main)/(app)/utils/format-money-for-template";@@ -57,6 +60,7 @@ interface InvoiceItemsSettingsProps {/** The invoice's number format, already resolved against its language. */numberFormatLocale: SupportedNumberFormatLocale;getValues: UseFormGetValues<InvoiceData>;+ setValue: UseFormSetValue<InvoiceData>;}export const InvoiceItems = memo(function InvoiceItems({@@ -71,6 +75,7 @@ export const InvoiceItems = memo(function InvoiceItems({taxLabelText,numberFormatLocale,getValues,+ setValue,}: InvoiceItemsSettingsProps) {const [itemPendingDeletion, setItemPendingDeletion] =useState<ItemPendingDeletion | null>(null);@@ -92,41 +97,20 @@ export const InvoiceItems = memo(function InvoiceItems({{/* Delete invoice item button */}{isNotFirstItem ? (<div className="absolute -right-3 -top-10">- <CustomTooltip- trigger={- <button- type="button"- // Safari does not focus a button on mousedown, so focus leaves the- // field the user was editing and lands on the nearest focusable- // ancestor -- on mobile that is Radix's tab panel, which Safari then- // scrolls into view (smoothly, see `globals.css`). The button drifts- // out from under the finger between mousedown and mouseup, and the- // browser dispatches the `click` on the common ancestor instead: the- // tap does nothing. Keeping focus where it is avoids the scroll.- onMouseDown={(event) => {- event.preventDefault();- }}- onClick={(event) => {- // Radix returns focus to its `Trigger` on close, and this dialog is- // controlled rather than triggered, so remember the button ourselves.- deleteTriggerRef.current = event.currentTarget;-- // Read the name from the form rather than from the parent's debounced- // copy of it, so the dialog names what the user is actually looking at.- return setItemPendingDeletion({- index,- name: getValues(`items.${index}.name`),- });- }}- className="flex items-center justify-center rounded-full bg-red-600 p-2 transition-colors hover:bg-red-700 active:scale-[98%] active:transition-transform"- >- <span className="sr-only">- Delete Invoice Item {index + 1}- </span>- <Trash2 className="h-4 w-4 text-white" />- </button>- }- content={`Delete Invoice Item ${index + 1}`}+ <DeleteIconButton+ label={`Delete Invoice Item ${index + 1}`}+ onClick={(event) => {+ // Radix returns focus to its `Trigger` on close, and this dialog is+ // controlled rather than triggered, so remember the button ourselves.+ deleteTriggerRef.current = event.currentTarget;++ // Read the name from the form rather than from the parent's debounced+ // copy of it, so the dialog names what the user is actually looking at.+ setItemPendingDeletion({+ index,+ name: getValues(`items.${index}.name`),+ });+ }}/></div>) : null}@@ -505,6 +489,18 @@ export const InvoiceItems = memo(function InvoiceItems({) : null}</div>+ {/* Invoice Item Discount */}+ <ItemDiscountFields+ control={control}+ index={index}+ errors={errors}+ currency={currency}+ template={template}+ numberFormatLocale={numberFormatLocale}+ getValues={getValues}+ setValue={setValue}+ />+{/* Invoice Item Tax Settings */}<fieldset className="rounded-md border px-4 pb-4"><legend className="text-base font-semibold lg:text-lg">@@ -678,7 +674,8 @@ export const InvoiceItems = memo(function InvoiceItems({</ErrorMessage>) : (<InputHelperMessage>- Calculated automatically based on Amount and Net Price+ Calculated automatically based on Amount, Net Price and+ Discount</InputHelperMessage>)}</div>@@ -859,6 +856,10 @@ export const InvoiceItems = memo(function InvoiceItems({vatAmountFieldIsVisible: true,preTaxAmount: 0,preTaxAmountFieldIsVisible: true,+ discountType: "percentage",+ discountValue: 0,+ discountLabel: "",+ discountAmount: 0,typeOfGTU: "",typeOfGTUFieldIsVisible: true,});diff --git a/src/app/(main)/(app)/components/invoice-form/utils/__tests__/calculate-item-totals.test.ts b/src/app/(main)/(app)/components/invoice-form/utils/__tests__/calculate-item-totals.test.tsindex 6e2a107..fe6dc28 100644--- a/src/app/(main)/(app)/components/invoice-form/utils/__tests__/calculate-item-totals.test.ts+++ b/src/app/(main)/(app)/components/invoice-form/utils/__tests__/calculate-item-totals.test.ts@@ -279,6 +279,104 @@ describe("calculateItemTotals", () => {});});+ describe("discount", () => {+ it("takes a percentage off the line and calculates VAT on what is left", () => {+ const result = calculateItemTotals(+ createItem({+ amount: 1,+ netPrice: 10_000,+ vat: 23,+ discountType: "percentage",+ discountValue: 10,+ }),+ );++ expect(result?.discountAmount).toBe(1000);+ expect(result?.netAmount).toBe(9000);+ expect(result?.vatAmount).toBe(2070);+ expect(result?.preTaxAmount).toBe(11_070);+ });++ it("takes a fixed amount off the whole line, not off each unit", () => {+ const result = calculateItemTotals(+ createItem({+ amount: 5,+ netPrice: 100,+ vat: 10,+ discountType: "amount",+ discountValue: 50,+ }),+ );++ expect(result?.discountAmount).toBe(50);+ expect(result?.netAmount).toBe(450);+ expect(result?.vatAmount).toBe(45);+ expect(result?.preTaxAmount).toBe(495);+ });++ it("rounds a percentage discount to two decimals", () => {+ const result = calculateItemTotals(+ createItem({+ amount: 3,+ netPrice: 33.33,+ vat: 0,+ discountType: "percentage",+ discountValue: 12.5,+ }),+ );++ // 99.99 * 12.5% = 12.49875+ expect(result?.discountAmount).toBe(12.5);+ expect(result?.netAmount).toBe(87.49);+ });++ it("never takes more than the line", () => {+ const result = calculateItemTotals(+ createItem({+ amount: 1,+ netPrice: 100,+ vat: 23,+ discountType: "amount",+ discountValue: 500,+ }),+ );++ expect(result?.discountAmount).toBe(100);+ expect(result?.netAmount).toBe(0);+ expect(result?.vatAmount).toBe(0);+ expect(result?.preTaxAmount).toBe(0);+ });++ it("treats an empty or invalid discount value as no discount", () => {+ for (const discountValue of ["", "abc", undefined]) {+ const result = calculateItemTotals(+ createItem({+ discountType: "amount",+ discountValue: discountValue as unknown as number,+ }),+ );++ expect(result?.discountAmount).toBe(0);+ expect(result?.netAmount).toBe(201);+ }+ });++ it("coerces a string discount value", () => {+ const result = calculateItemTotals(+ createItem({+ amount: 1,+ netPrice: 200,+ vat: 0,+ discountType: "percentage",+ discountValue: "25" as unknown as number,+ }),+ );++ expect(result?.discountAmount).toBe(50);+ expect(result?.netAmount).toBe(150);+ });+ });+describe("integration-style case", () => {it("matches MOCK_INVOICE_ITEM_DATA expected totals", () => {const result = calculateItemTotals(createItem());@@ -294,6 +392,7 @@ describe("calculateItemTotals", () => {expect(result).toEqual({...item,+ discountAmount: 0,netAmount: 201,vatAmount: 46.23,preTaxAmount: 247.23,diff --git a/src/app/(main)/(app)/components/invoice-form/utils/__tests__/validated-invoice-items.test.ts b/src/app/(main)/(app)/components/invoice-form/utils/__tests__/validated-invoice-items.test.tsindex bb7c0a0..0010055 100644--- a/src/app/(main)/(app)/components/invoice-form/utils/__tests__/validated-invoice-items.test.ts+++ b/src/app/(main)/(app)/components/invoice-form/utils/__tests__/validated-invoice-items.test.ts@@ -59,4 +59,84 @@ describe("parseValidatedInvoiceItems", () => {expect(result.success).toBe(false);});++ describe("discount", () => {+ it("accepts a percentage discount up to 100%", () => {+ const result = parseValidatedInvoiceItems([+ createItem({ discountType: "percentage", discountValue: 100 }),+ ]);++ expect(result.success).toBe(true);+ });++ it("rejects a percentage discount above 100%", () => {+ const result = parseValidatedInvoiceItems([+ createItem({ discountType: "percentage", discountValue: 101 }),+ ]);++ assert(!result.success);++ expect(result.error.issues[0].path).toEqual([0, "discountValue"]);+ });++ it("rejects a fixed discount larger than the line", () => {+ // MOCK_INVOICE_ITEM_DATA: 2 x 100.50 = 201.00+ const result = parseValidatedInvoiceItems([+ createItem({ discountType: "amount", discountValue: 201.01 }),+ ]);++ assert(!result.success);++ expect(result.error.issues[0]).toMatchObject({+ path: [0, "discountValue"],+ message:+ "Discount must not exceed the line amount (Amount × Net Price)",+ });+ });++ it("accepts a fixed discount equal to the line", () => {+ const result = parseValidatedInvoiceItems([+ createItem({ discountType: "amount", discountValue: 201 }),+ ]);++ expect(result.success).toBe(true);+ });++ it("rejects a negative discount", () => {+ const result = parseValidatedInvoiceItems([+ createItem({ discountValue: -5 }),+ ]);++ expect(result.success).toBe(false);+ });++ it("reads a cleared discount input as no discount", () => {+ const result = parseValidatedInvoiceItems([+ createItem({ discountValue: "" as unknown as number }),+ ]);++ assert(result.success);++ expect(result.data[0].discountValue).toBe(0);+ });++ it("fills in the discount fields for items saved before discounts existed", () => {+ const legacyItem = Object.fromEntries(+ Object.entries(createItem()).filter(([key]) => {+ return !key.startsWith("discount");+ }),+ );++ const result = parseValidatedInvoiceItems([legacyItem]);++ assert(result.success);++ expect(result.data[0]).toMatchObject({+ discountType: "percentage",+ discountValue: 0,+ discountLabel: "",+ discountAmount: 0,+ });+ });+ });});diff --git a/src/app/(main)/(app)/components/invoice-form/utils/calculate-item-totals.ts b/src/app/(main)/(app)/components/invoice-form/utils/calculate-item-totals.tsindex 6820bfc..8bf95e4 100644--- a/src/app/(main)/(app)/components/invoice-form/utils/calculate-item-totals.ts+++ b/src/app/(main)/(app)/components/invoice-form/utils/calculate-item-totals.ts@@ -1,8 +1,11 @@-import type { InvoiceItemData } from "@/app/schema";+import { type InvoiceItemData, parseDiscountValue } from "@/app/schema";/**- * Calculates netAmount, vatAmount, and preTaxAmount for invoice item.+ * Calculates discountAmount, netAmount, vatAmount, and preTaxAmount for invoice item.*+ * - The discount comes off the line (amount * netPrice) before tax: a percentage of the+ * line, or a fixed amount capped at the line, so netAmount never goes below 0.+ * - netAmount is the line after the discount, and VAT is calculated on it.* - If item.vat is numeric (e.g. "23"), computes VAT as (netAmount * vat / 100).* - If item.vat is not a number (e.g. "NP", "OO"), sets vatAmount to 0.* - Rounds all computed amounts to two decimal places.@@ -19,8 +22,12 @@ export function calculateItemTotals(const amount = Number(item.amount) || 0;// oxlint-disable-next-line typescript/no-unnecessary-type-conversion -- same as aboveconst netPrice = Number(item.netPrice) || 0;- const calculatedNetAmount = amount * netPrice;- const formattedNetAmount = Number(calculatedNetAmount.toFixed(2));+ const lineAmount = Number((amount * netPrice).toFixed(2));+ const discountAmount = calculateDiscountAmount({+ item,+ lineAmount,+ });+ const formattedNetAmount = Number((lineAmount - discountAmount).toFixed(2));let vatAmount = 0;@@ -49,8 +56,38 @@ export function calculateItemTotals(return {...item,+ discountAmount,netAmount: formattedNetAmount,vatAmount: formattedVatAmount,preTaxAmount: formattedPreTaxAmount,};}++interface CalculateDiscountAmountParams {+ /** The item whose `discountType` and `discountValue` say what to take off. */+ item: InvoiceItemData;+ /** The line before the discount (amount * netPrice), rounded to two decimals. */+ lineAmount: number;+}++/**+ * The money an item's discount takes off its line, rounded to two decimal places and never+ * more than the line itself.+ */+function calculateDiscountAmount({+ item,+ lineAmount,+}: CalculateDiscountAmountParams) {+ // read the same way the schema reads it; an invalid value never gets this far, since the+ // totals only run on items that pass validation, but it counts as no discount+ const discountValue = parseDiscountValue(item.discountValue) || 0;++ if (discountValue <= 0 || lineAmount <= 0) return 0;++ const discountAmount =+ item.discountType === "amount"+ ? discountValue+ : (lineAmount * discountValue) / 100;++ return Number(Math.min(discountAmount, lineAmount).toFixed(2));+}diff --git a/src/app/(main)/(app)/components/invoice-form/utils/has-item-totals-changed.ts b/src/app/(main)/(app)/components/invoice-form/utils/has-item-totals-changed.tsindex ebdc454..9dfc421 100644--- a/src/app/(main)/(app)/components/invoice-form/utils/has-item-totals-changed.ts+++ b/src/app/(main)/(app)/components/invoice-form/utils/has-item-totals-changed.ts@@ -3,7 +3,7 @@ import type { InvoiceItemData } from "@/app/schema";import { calculateItemTotals } from "./calculate-item-totals";/**- * Check if calculated item totals (netAmount, vatAmount, preTaxAmount)+ * Check if calculated item totals (discountAmount, netAmount, vatAmount, preTaxAmount)* differ from existing item's values.** @param item InvoiceItemData to check for changes@@ -13,6 +13,7 @@ export function hasItemTotalsChanged(item: InvoiceItemData): boolean {const calculated = calculateItemTotals(item);return (+ calculated?.discountAmount !== item.discountAmount ||calculated?.netAmount !== item.netAmount ||calculated?.vatAmount !== item.vatAmount ||calculated?.preTaxAmount !== item.preTaxAmountdiff --git a/src/app/(main)/(app)/components/invoice-templates/__tests__/item-discount-pdf.test.tsx b/src/app/(main)/(app)/components/invoice-templates/__tests__/item-discount-pdf.test.tsxnew file mode 100644index 0000000..0897ce0--- /dev/null+++ b/src/app/(main)/(app)/components/invoice-templates/__tests__/item-discount-pdf.test.tsx@@ -0,0 +1,144 @@+// @vitest-environment node++// IMPORTANT: it's fine to use this import directly in a node test+// eslint-disable-next-line no-restricted-imports+import { Font, renderToBuffer } from "@react-pdf/renderer";+import { describe, expect, it, vi } from "vitest";++import { calculateInvoiceTotal } from "@/app/(main)/(app)/components/invoice-form/utils/calculate-invoice-total";+import { calculateItemTotals } from "@/app/(main)/(app)/components/invoice-form/utils/calculate-item-totals";+import {+ extractPdfText,+ SERVER_PDF_MOCK_INVOICE_DATA,+} from "@/app/api/generate-invoice/__tests__/pdf-test-utils";+import { renderInvoicePdfBuffer } from "@/app/api/generate-invoice/render-pdf-on-server";+import type { InvoiceData, InvoiceItemData } from "@/app/schema";+import { INVOICE_PDF_FONTS } from "@/config";++import { StripeInvoicePdfTemplate } from "../invoice-pdf-stripe-template";++// Real PDF rendering (font fetch + @react-pdf layout) takes seconds on a cold worker+vi.setConfig({ testTimeout: 30_000, hookTimeout: 30_000 });++vi.mock("@/env", async () => {+ // dynamic import: vi.mock factories are hoisted above the static imports+ const { TEST_ENV } =+ await import("@/app/api/generate-invoice/__tests__/test-env");++ return { env: TEST_ENV };+});++// The template registers Inter on the browser build of react-pdf; `renderToBuffer` here is+// the node build, which keeps its own font registry+Font.register({+ family: "Inter",+ fonts: [+ { src: INVOICE_PDF_FONTS.STRIPE_TEMPLATE.INTER_REGULAR, fontWeight: 400 },+ { src: INVOICE_PDF_FONTS.STRIPE_TEMPLATE.INTER_MEDIUM, fontWeight: 500 },+ { src: INVOICE_PDF_FONTS.STRIPE_TEMPLATE.INTER_SEMIBOLD, fontWeight: 600 },+ ],+});++/**+ * The default template's "Discount" column header, which pdf.js returns right after the+ * "Net price" header. Whitespace-agnostic, so it does not depend on how pdf.js joins runs.+ */+const DISCOUNT_COLUMN_HEADER = /Net price\s+Discount/;++describe("item discounts in the PDF", () => {+ it("shows the discount column and the label under the item name in the default template", async () => {+ const invoiceData = buildInvoice({+ items: [+ {+ netPrice: 10_000,+ vat: 23,+ discountType: "percentage",+ discountValue: 10,+ discountLabel: "Charitable donation",+ },+ ],+ });++ const text = await extractPdfText(+ await renderInvoicePdfBuffer({ invoiceData }),+ );++ expect(text).toMatch(DISCOUNT_COLUMN_HEADER);+ expect(text).toContain("Charitable donation");+ expect(text).toContain("10%");+ // 9,000.00 after the discount, plus 23% VAT. Table cells come out in thousands+ // chunks, so check the SUM line, which is one run+ expect(text).toMatch(/SUM\s*:\s*11,070\.00/);+ });++ it("leaves the discount column out of the default template when no item has a discount", async () => {+ const invoiceData = buildInvoice({+ items: [{ netPrice: 10_000, vat: 23 }],+ });++ const text = await extractPdfText(+ await renderInvoicePdfBuffer({ invoiceData }),+ );++ expect(text).not.toMatch(DISCOUNT_COLUMN_HEADER);+ });++ it("shows the discount row but no tax base when the Stripe item's tax is not a rate", async () => {+ const invoiceData = buildInvoice({+ template: "stripe",+ items: [+ {+ netPrice: 1000,+ vat: "NP",+ discountType: "amount",+ discountValue: 100,+ discountLabel: "",+ },+ ],+ });++ const text = await extractPdfText(+ await renderToBuffer(+ <StripeInvoicePdfTemplate invoiceData={invoiceData} />,+ ),+ );++ expect(text).toContain("Discount (€100.00 off)");+ expect(text).toContain("NP");+ // "(on €900.00)" only makes sense next to a rate+ expect(text).not.toContain("(on");+ });+});++interface BuildInvoiceParams {+ template?: InvoiceData["template"];+ /** Overrides for each item, on top of the fixture's first item. */+ items: Partial<InvoiceItemData>[];+}++/** The server fixture with the given items, their totals calculated the way the form does. */+function buildInvoice({+ template = "default",+ items,+}: BuildInvoiceParams): InvoiceData {+ const calculatedItems = items.map((overrides) => {+ const item = calculateItemTotals({+ ...SERVER_PDF_MOCK_INVOICE_DATA.items[0],+ amount: 1,+ ...overrides,+ });++ if (!item) {+ throw new Error("Expected an item to calculate totals for");+ }++ return item;+ });++ return {+ ...SERVER_PDF_MOCK_INVOICE_DATA,+ template,+ items: calculatedItems,+ total: calculateInvoiceTotal(calculatedItems),+ };+}diff --git a/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-default-template/index.tsx b/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-default-template/index.tsxindex d5e0430..91a5a23 100644--- a/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-default-template/index.tsx+++ b/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-default-template/index.tsx@@ -130,10 +130,13 @@ export const PDF_DEFAULT_TEMPLATE_STYLES = StyleSheet.create({// styles for specific column widths for invoice items tablecolNo: { flex: 0.45 }, // smallest width for numberscolName: { flex: 4.8 }, // larger width for text+ colNameWithDiscount: { flex: 3.2 }, // gives up exactly the discount column's width, so no other column narrowscolGTU: { flex: 0.9 }, // small width for codescolAmount: { flex: 1.2 }, // medium width for numberscolUnit: { flex: 1 }, // medium width for textcolNetPrice: { flex: 1.5 }, // medium-large for prices+ // wide enough that react-pdf does not hyphenate the bold header ("Dis-count", "Des-cuento")+ colDiscount: { flex: 1.6 }, // percentage or amountcolVAT: { flex: 0.8 }, // small width for percentagescolNetAmount: { flex: 1.5 }, // medium-large for amountscolVATAmount: { flex: 1.5 }, // medium-large for amountsdiff --git a/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-default-template/invoice-items-table.tsx b/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-default-template/invoice-items-table.tsxindex 2265fb7..fd9a888 100644--- a/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-default-template/invoice-items-table.tsx+++ b/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-default-template/invoice-items-table.tsx@@ -5,6 +5,11 @@ import { type InvoiceData, resolveNumberFormatLocale } from "@/app/schema";import type { PDF_DEFAULT_TEMPLATE_STYLES } from ".";import { formatAmountChunks } from "../../../utils/format-amount";+import {+ formatDiscountPercent,+ hasAnyItemDiscount,+ hasItemDiscount,+} from "../../../utils/item-discount";import { WrappableAmount } from "../common/wrappable-amount";export function InvoiceItemsTable({@@ -33,6 +38,14 @@ export function InvoiceItemsTable({const isVATAmountFieldVisible = invoiceData.items[0].vatAmountFieldIsVisible;const isPreTaxAmountFieldVisible =invoiceData.items[0].preTaxAmountFieldIsVisible;+ // the discount column only earns its width when some item actually has a discount+ const hasDiscountColumn = hasAnyItemDiscount(invoiceData.items);++ // the name column has width to spare, so it pays for the discount column, rather than+ // the narrow numeric columns whose headers would start to hyphenate ("Cantid-ad")+ const nameColumnStyle = hasDiscountColumn+ ? styles.colNameWithDiscount+ : styles.colName;/*** Custom tax label text i.e. "VAT", "Sales Tax", "IVA", "GST", etc.@@ -71,7 +84,7 @@ export function InvoiceItemsTable({{/* Name of goods/service column */}{isNameFieldVisible ? (- <View style={[styles.tableCol, styles.colName, styles.center]}>+ <View style={[styles.tableCol, nameColumnStyle, styles.center]}><Text style={styles.tableCellBold}>{t.invoiceItemsTable.nameOfGoodsService}</Text>@@ -115,6 +128,15 @@ export function InvoiceItemsTable({</View>) : null}+ {/* Discount column */}+ {hasDiscountColumn ? (+ <View style={[styles.tableCol, styles.colDiscount, styles.center]}>+ <Text style={styles.tableCellBold}>+ {t.invoiceItemsTable.discount}+ </Text>+ </View>+ ) : null}+{/* VAT column */}{isVATFieldVisible ? (<View style={[styles.tableCol, styles.colVAT, styles.center]}>@@ -183,6 +205,27 @@ export function InvoiceItemsTable({numberFormatLocale,});+ const itemHasDiscount = hasItemDiscount(item);++ const formattedDiscountPercent = formatDiscountPercent({+ value: item.discountValue,+ numberFormatLocale,+ });++ // a percentage reads as itself, a fixed discount as the money it takes off the line+ const discountChunks =+ item.discountType === "percentage"+ ? [formattedDiscountPercent]+ : formatAmountChunks({+ amount: item.discountAmount,+ numberFormatLocale,+ });++ const customDiscountLabel = item.discountLabel?.trim();++ // the column carries the number, the name cell says what the discount is for+ const discountNote = itemHasDiscount ? customDiscountLabel : null;+const formattedVat = Number.isNaN(Number(item.vat))? item.vat: `${Number(item.vat)}%`;@@ -204,7 +247,7 @@ export function InvoiceItemsTable({{/* Name of goods/service */}{isNameFieldVisible ? (- <View style={[styles.tableCol, styles.colName]}>+ <View style={[styles.tableCol, nameColumnStyle]}><Textstyle={[styles.tableCell,@@ -213,6 +256,23 @@ export function InvoiceItemsTable({>{item.name}</Text>+ {discountNote ? (+ <Text+ style={[+ styles.tableCell,+ styles.fontSize7,+ {+ textAlign: "left",+ marginLeft: 2,+ marginRight: 2,+ marginTop: 0,+ color: "#555",+ },+ ]}+ >+ {discountNote}+ </Text>+ ) : null}</View>) : null}@@ -258,6 +318,21 @@ export function InvoiceItemsTable({</View>) : null}+ {/* Discount */}+ {hasDiscountColumn ? (+ <View style={[styles.tableCol, styles.colDiscount]}>+ {itemHasDiscount ? (+ <WrappableAmount+ chunks={discountChunks}+ style={[+ styles.tableCell,+ { textAlign: "right", marginRight: 2 },+ ]}+ />+ ) : null}+ </View>+ ) : null}+{/* VAT */}{isVATFieldVisible ? (<Viewdiff --git a/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-stripe-template/index.tsx b/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-stripe-template/index.tsxindex f937302..ddc61bf 100644--- a/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-stripe-template/index.tsx+++ b/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-stripe-template/index.tsx@@ -178,7 +178,25 @@ export const STRIPE_TEMPLATE_STYLES = StyleSheet.create({},colUnitPrice: { flex: 1.2, textAlign: "right" },colTax: { flex: 0.8, textAlign: "right" },+ // as wide as the unit price, so "10% (on" sits over a whole "€4,000.00)" on invoices+ // whose tax cells name the discounted base+ colTaxWithDiscount: { flex: 1.2, textAlign: "right" },colAmount: { flex: 1.3, textAlign: "right" },+ // The row under a discounted item, set off by hairlines above it and above the item+ // that follows: its label indented under the item's name, its negative amount in the+ // amount column+ discountRow: {+ marginTop: 4,+ paddingVertical: 8,+ borderTopWidth: 0.5,+ borderTopColor: "#e5e7eb",+ },+ discountLabel: { paddingLeft: 8 },+ rowAfterDiscount: {+ paddingTop: 8,+ borderTopWidth: 0.5,+ borderTopColor: "#e5e7eb",+ },// Due amount highlightdueAmountBox: {backgroundColor: "#f9fafb",diff --git a/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-stripe-template/stripe-items-table.tsx b/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-stripe-template/stripe-items-table.tsxindex dd63b5c..472e815 100644--- a/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-stripe-template/stripe-items-table.tsx+++ b/src/app/(main)/(app)/components/invoice-templates/invoice-pdf-stripe-template/stripe-items-table.tsx@@ -5,8 +5,17 @@ import { WrappableAmount } from "@/app/(main)/(app)/components/invoice-templatesimport type { STRIPE_TEMPLATE_STYLES } from "@/app/(main)/(app)/components/invoice-templates/invoice-pdf-stripe-template";import { INVOICE_PDF_TRANSLATIONS } from "@/app/(main)/(app)/pdf-i18n-translations/pdf-translations";import { formatAmountChunks } from "@/app/(main)/(app)/utils/format-amount";-import { formatCurrencyChunks } from "@/app/(main)/(app)/utils/format-currency";+import {+ formatCurrency,+ formatCurrencyChunks,+} from "@/app/(main)/(app)/utils/format-currency";import { formatServicePeriodRange } from "@/app/(main)/(app)/utils/format-service-period";+import {+ getItemAmountBeforeDiscount,+ hasAnyItemDiscount,+ formatDiscountPercent,+ hasItemDiscount,+} from "@/app/(main)/(app)/utils/item-discount";import { type InvoiceData, resolveNumberFormatLocale } from "@/app/schema";import "dayjs/locale/de";@@ -40,6 +49,9 @@ export function StripeItemsTable({const unitFieldIsVisible = invoiceData.items[0].unitFieldIsVisible;const vatAmountFieldIsVisible = invoiceData.items[0].vatFieldIsVisible;+ const taxColumnStyle = hasAnyItemDiscount(invoiceData.items)+ ? styles.colTaxWithDiscount+ : styles.colTax;return (<View style={[styles.table, styles.mt24]}>@@ -64,7 +76,7 @@ export function StripeItemsTable({</View>{vatAmountFieldIsVisible ? (- <View style={styles.colTax}>+ <View style={taxColumnStyle}><Text style={styles.fontSize8}>{taxLabelText}</Text></View>) : null}@@ -82,12 +94,60 @@ export function StripeItemsTable({numberFormatLocale,});+ const itemHasDiscount = hasItemDiscount(item);++ // Format VAT value+ const formattedVat = Number.isNaN(Number(item.vat))+ ? item.vat+ : `${Number(item.vat)}%`;++ // the row shows the line before its discount, and the discount row under it takes+ // the discount off, the way Stripe lays out a discounted lineconst preTaxAmountChunks = formatCurrencyChunks({- amount: item.netAmount,+ amount: getItemAmountBeforeDiscount(item),currency: invoiceData.currency,numberFormatLocale,});+ const discountAmountChunks = formatCurrencyChunks({+ amount: -item.discountAmount,+ currency: invoiceData.currency,+ numberFormatLocale,+ });++ // with a discount, the tax applies to less than the amount on the row, so say what+ // it applies to, always on two lines: "20% (on" over "€9,990.00)". The amount keeps+ // its thousands chunks, so only an amount too wide for the column wraps further.+ const taxBaseAmountChunks =+ itemHasDiscount && typeof item.vat === "number"+ ? formatCurrencyChunks({+ amount: item.netAmount,+ currency: invoiceData.currency,+ numberFormatLocale,+ }).map((chunk, chunkIndex, chunks) => {+ return chunkIndex === chunks.length - 1 ? `${chunk})` : chunk;+ })+ : null;++ // "test discount (10% off)", "Discount (€50.00 off)"+ const discountValueText =+ item.discountType === "percentage"+ ? formatDiscountPercent({+ value: item.discountValue,+ numberFormatLocale,+ })+ : formatCurrency({+ amount: item.discountAmount,+ currency: invoiceData.currency,+ numberFormatLocale,+ });+ const discountLabel = item.discountLabel?.trim() || t.stripe.discount;+ const discountRowText = `${discountLabel} (${discountValueText} ${t.stripe.discountOff})`;++ // a hairline closes the discount row above, before the next item starts+ const isAfterDiscountRow =+ index > 0 && hasItemDiscount(invoiceData.items[index - 1]);+// The quantity column carries no currency, and the Stripe template rounds it to// whole unitsconst amountChunks = formatAmountChunks({@@ -97,62 +157,92 @@ export function StripeItemsTable({maximumFractionDigits: 0,});- // Format VAT value- const formattedVat = Number.isNaN(Number(item.vat))- ? item.vat- : `${Number(item.vat)}%`;-return (- <View- key={index}- style={styles.tableRow}- wrap={false}- minPresenceAhead={60}- >- <View style={styles.colDescription}>- <Text style={[styles.fontSize10]}>{item.name}</Text>- {invoiceData.servicePeriodFieldIsVisible ? (- <Text style={[styles.fontSize9, styles.mt4]}>- {servicePeriod}- </Text>+ // the item and its discount row move to the next page together+ <View key={index} wrap={false} minPresenceAhead={60}>+ <View+ style={[+ styles.tableRow,+ isAfterDiscountRow ? styles.rowAfterDiscount : {},+ ]}+ >+ <View style={styles.colDescription}>+ <Text style={[styles.fontSize10]}>{item.name}</Text>+ {invoiceData.servicePeriodFieldIsVisible ? (+ <Text style={[styles.fontSize9, styles.mt4]}>+ {servicePeriod}+ </Text>+ ) : null}+ </View>+ <View style={styles.colQty}>+ <WrappableAmount+ chunks={amountChunks}+ style={[styles.fontSize11, styles.textDark]}+ />+ </View>+ {unitFieldIsVisible ? (+ <View style={styles.colUnit}>+ <Text style={[styles.fontSize11, styles.textDark]}>+ {item.unit}+ </Text>+ </View>) : null}- </View>- <View style={styles.colQty}>- <WrappableAmount- chunks={amountChunks}- style={[styles.fontSize11, styles.textDark]}- />- </View>- {unitFieldIsVisible ? (- <View style={styles.colUnit}>- <Text style={[styles.fontSize11, styles.textDark]}>- {item.unit}- </Text>+ <View style={styles.colUnitPrice}>+ <WrappableAmount+ chunks={netPriceChunks}+ style={[styles.fontSize11, styles.textDark]}+ />+ </View>+ {vatAmountFieldIsVisible ? (+ <View style={taxColumnStyle}>+ {taxBaseAmountChunks ? (+ <>+ <Text style={[styles.fontSize11, styles.textDark]}>+ {formattedVat} ({t.stripe.taxOn}+ </Text>+ <WrappableAmount+ chunks={taxBaseAmountChunks}+ style={[styles.fontSize11, styles.textDark]}+ />+ </>+ ) : (+ <Text style={[styles.fontSize11, styles.textDark]}>+ {formattedVat}+ </Text>+ )}+ </View>+ ) : null}+ <View style={[styles.colAmount]}>+ <WrappableAmount+ chunks={preTaxAmountChunks}+ style={[+ styles.fontSize11,+ styles.textDark,+ { paddingLeft: 10 },+ ]}+ /></View>- ) : null}- <View style={styles.colUnitPrice}>- <WrappableAmount- chunks={netPriceChunks}- style={[styles.fontSize11, styles.textDark]}- /></View>- {vatAmountFieldIsVisible ? (- <View style={styles.colTax}>- <Text style={[styles.fontSize11, styles.textDark]}>- {formattedVat}- </Text>++ {itemHasDiscount ? (+ <View style={[styles.tableRow, styles.discountRow]}>+ <View style={[styles.colDescription, styles.discountLabel]}>+ <Text style={[styles.fontSize10, styles.textDark]}>+ {discountRowText}+ </Text>+ </View>+ <View style={styles.colAmount}>+ <WrappableAmount+ chunks={discountAmountChunks}+ style={[+ styles.fontSize11,+ styles.textDark,+ { paddingLeft: 10 },+ ]}+ />+ </View></View>) : null}- <View style={[styles.colAmount]}>- <WrappableAmount- chunks={preTaxAmountChunks}- style={[- styles.fontSize11,- styles.textDark,- { paddingLeft: 10 },- ]}- />- </View></View>);})}diff --git a/src/app/(main)/(app)/page.client.tsx b/src/app/(main)/(app)/page.client.tsxindex f11bd7b..85b8bdd 100644--- a/src/app/(main)/(app)/page.client.tsx+++ b/src/app/(main)/(app)/page.client.tsx@@ -273,7 +273,7 @@ export function AppPageClient({setInvoiceDataState(getInitialInvoiceData(urlTemplate ?? undefined));toast.error(- "Unable to load your saved invoice data. For your convenience, we've reset the form to default values. Please try creating a new invoice.",+ "Your saved invoice couldn't be loaded, so you're starting with a new one.",{id: "unable-to-load-saved-invoice-data-error-toast",duration: Infinity,diff --git a/src/app/(main)/(app)/pdf-i18n-translations/pdf-translations-schema.ts b/src/app/(main)/(app)/pdf-i18n-translations/pdf-translations-schema.tsindex a5b8e40..ab5a925 100644--- a/src/app/(main)/(app)/pdf-i18n-translations/pdf-translations-schema.ts+++ b/src/app/(main)/(app)/pdf-i18n-translations/pdf-translations-schema.ts@@ -79,6 +79,8 @@ const invoiceItemsTableTranslationSchema = z*/preTaxAmount: functionCustomTaxLabelInputSchema,sum: z.string(),+ /** Discount column header. */+ discount: z.string(),}).strict();@@ -155,6 +157,12 @@ const stripeTranslationSchema = zamountDue: z.string(),page: z.string(),of: z.string(),+ /** Fallback label of the row under a discounted item. */+ discount: z.string(),+ /** Joins a tax rate to the amount it applies to, e.g. "23% (on €9,000.00)". */+ taxOn: z.string(),+ /** Follows the size of a discount in its row, e.g. "(10% off)", "(€50.00 off)". */+ discountOff: z.string(),}).strict();diff --git a/src/app/(main)/(app)/pdf-i18n-translations/pdf-translations.ts b/src/app/(main)/(app)/pdf-i18n-translations/pdf-translations.tsindex 809061f..d124b16 100644--- a/src/app/(main)/(app)/pdf-i18n-translations/pdf-translations.ts+++ b/src/app/(main)/(app)/pdf-i18n-translations/pdf-translations.ts@@ -80,6 +80,7 @@ export const INVOICE_PDF_TRANSLATIONS = {return `Pre-tax amount `;},sum: "SUM",+ discount: "Discount",},paymentInfo: {paymentMethod: "Payment method",@@ -149,6 +150,9 @@ export const INVOICE_PDF_TRANSLATIONS = {amountDue: "Amount Due",page: "Page",of: "of",+ discount: "Discount",+ taxOn: "on",+ discountOff: "off",},},pl: {@@ -189,6 +193,7 @@ export const INVOICE_PDF_TRANSLATIONS = {return `Kwota\n brutto`;},sum: "SUMA",+ discount: "Rabat",},paymentInfo: {paymentMethod: "Sposób wpłaty",@@ -237,6 +242,9 @@ export const INVOICE_PDF_TRANSLATIONS = {amountDue: "Kwota do zapłaty",page: "Strona",of: "z",+ discount: "Rabat",+ taxOn: "od",+ discountOff: "rabatu",},},de: {@@ -277,6 +285,7 @@ export const INVOICE_PDF_TRANSLATIONS = {return `Bruttobetrag`;},sum: "SUMME",+ discount: "Rabatt",},paymentInfo: {paymentMethod: "Zahlungsart",@@ -325,6 +334,9 @@ export const INVOICE_PDF_TRANSLATIONS = {amountDue: "Zu zahlender Betrag",page: "Seite",of: "von",+ discount: "Rabatt",+ taxOn: "auf",+ discountOff: "Rabatt",},},es: {@@ -365,6 +377,7 @@ export const INVOICE_PDF_TRANSLATIONS = {return `Importe bruto`;},sum: "TOTAL",+ discount: "Descuento",},paymentInfo: {paymentMethod: "Forma de pago",@@ -413,6 +426,9 @@ export const INVOICE_PDF_TRANSLATIONS = {amountDue: "Monto a pagar",page: "Página",of: "de",+ discount: "Descuento",+ taxOn: "sobre",+ discountOff: "de descuento",},},pt: {@@ -453,6 +469,7 @@ export const INVOICE_PDF_TRANSLATIONS = {return `Valor bruto`;},sum: "TOTAL",+ discount: "Desconto",},paymentInfo: {paymentMethod: "Forma de pagamento",@@ -501,6 +518,9 @@ export const INVOICE_PDF_TRANSLATIONS = {amountDue: "Valor a pagar",page: "Página",of: "de",+ discount: "Desconto",+ taxOn: "sobre",+ discountOff: "de desconto",},},/**@@ -548,6 +568,7 @@ export const INVOICE_PDF_TRANSLATIONS = {return `Valor bruto`;},sum: "TOTAL",+ discount: "Desconto",},paymentInfo: {paymentMethod: "Forma de pagamento",@@ -596,6 +617,9 @@ export const INVOICE_PDF_TRANSLATIONS = {amountDue: "Valor a pagar",page: "Página",of: "de",+ discount: "Desconto",+ taxOn: "sobre",+ discountOff: "de desconto",},},ru: {@@ -636,6 +660,7 @@ export const INVOICE_PDF_TRANSLATIONS = {return `Сумма с ${customTaxLabel || "НДС"}`;},sum: "ИТОГО",+ discount: "Скидка",},paymentInfo: {paymentMethod: "Способ оплаты",@@ -684,6 +709,9 @@ export const INVOICE_PDF_TRANSLATIONS = {amountDue: "Сумма к оплате",page: "Страница",of: "из",+ discount: "Скидка",+ taxOn: "от",+ discountOff: "скидка",},},uk: {@@ -724,6 +752,7 @@ export const INVOICE_PDF_TRANSLATIONS = {return `Сума з ${customTaxLabel || "ПДВ"}`;},sum: "РАЗОМ",+ discount: "Знижка",},paymentInfo: {paymentMethod: "Спосіб оплати",@@ -772,6 +801,9 @@ export const INVOICE_PDF_TRANSLATIONS = {amountDue: "Сума до сплати",page: "Сторінка",of: "з",+ discount: "Знижка",+ taxOn: "від",+ discountOff: "знижка",},},fr: {@@ -812,6 +844,7 @@ export const INVOICE_PDF_TRANSLATIONS = {return `Total TTC`;},sum: "TOTAL",+ discount: "Remise",},paymentInfo: {paymentMethod: "Mode de paiement",@@ -860,6 +893,9 @@ export const INVOICE_PDF_TRANSLATIONS = {amountDue: "Montant dû",page: "Page",of: "de",+ discount: "Remise",+ taxOn: "sur",+ discountOff: "de remise",},},it: {@@ -900,6 +936,7 @@ export const INVOICE_PDF_TRANSLATIONS = {return `Importo lordo`;},sum: "TOTALE",+ discount: "Sconto",},paymentInfo: {paymentMethod: "Metodo di pagamento",@@ -948,6 +985,9 @@ export const INVOICE_PDF_TRANSLATIONS = {amountDue: "Importo da pagare",page: "Pagina",of: "di",+ discount: "Sconto",+ taxOn: "su",+ discountOff: "di sconto",},},nl: {@@ -988,6 +1028,7 @@ export const INVOICE_PDF_TRANSLATIONS = {return `Brutobedrag`;},sum: "TOTAAL",+ discount: "Korting",},paymentInfo: {paymentMethod: "Betaalmethode",@@ -1036,6 +1077,9 @@ export const INVOICE_PDF_TRANSLATIONS = {amountDue: "Te betalen bedrag",page: "Pagina",of: "van",+ discount: "Korting",+ taxOn: "over",+ discountOff: "korting",},},sv: {@@ -1081,6 +1125,7 @@ export const INVOICE_PDF_TRANSLATIONS = {return `Brutto\n belopp`;},sum: "SUMMA",+ discount: "Rabatt",},paymentInfo: {paymentMethod: "Betalningsmetod",@@ -1129,6 +1174,9 @@ export const INVOICE_PDF_TRANSLATIONS = {amountDue: "Att betala",page: "Sida",of: "av",+ discount: "Rabatt",+ taxOn: "på",+ discountOff: "rabatt",},},nb: {@@ -1177,6 +1225,7 @@ export const INVOICE_PDF_TRANSLATIONS = {return `Brutto\n beløp`;},sum: "SUM",+ discount: "Rabatt",},paymentInfo: {paymentMethod: "Betalingsmåte",@@ -1225,6 +1274,9 @@ export const INVOICE_PDF_TRANSLATIONS = {amountDue: "Å betale",page: "Side",of: "av",+ discount: "Rabatt",+ taxOn: "av",+ discountOff: "rabatt",},},} as const satisfies Record<SupportedLanguages, TranslationSchema>;diff --git a/src/app/(main)/(app)/utils/__tests__/item-discount.test.ts b/src/app/(main)/(app)/utils/__tests__/item-discount.test.tsnew file mode 100644index 0000000..f3445fb--- /dev/null+++ b/src/app/(main)/(app)/utils/__tests__/item-discount.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from "vitest";++import type { InvoiceItemData } from "@/app/schema";+import { MOCK_INVOICE_ITEM_DATA } from "@/utils/__tests__/data";++import {+ getItemAmountBeforeDiscount,+ formatDiscountPercent,+ hasAnyItemDiscount,+} from "../item-discount";++function createItem(overrides: Partial<InvoiceItemData> = {}): InvoiceItemData {+ return { ...MOCK_INVOICE_ITEM_DATA, ...overrides };+}++describe("hasAnyItemDiscount", () => {+ it("is false when no item has a discount amount", () => {+ expect(hasAnyItemDiscount([createItem(), createItem()])).toBe(false);+ });++ it("is true when one item has a discount amount", () => {+ expect(+ hasAnyItemDiscount([createItem(), createItem({ discountAmount: 1 })]),+ ).toBe(true);+ });+});++describe("getItemAmountBeforeDiscount", () => {+ it("adds the discount back onto the net amount", () => {+ expect(+ getItemAmountBeforeDiscount({ netAmount: 9000, discountAmount: 1000 }),+ ).toBe(10_000);+ });++ it("does not leak floating point noise", () => {+ expect(+ getItemAmountBeforeDiscount({ netAmount: 0.1, discountAmount: 0.2 }),+ ).toBe(0.3);+ });+});++describe("formatDiscountPercent", () => {+ it("writes the percentage in the invoice's number format", () => {+ expect(+ formatDiscountPercent({ value: 12.5, numberFormatLocale: "en" }),+ ).toBe("12.5%");+ expect(+ formatDiscountPercent({ value: 12.5, numberFormatLocale: "de" }),+ ).toBe("12,5%");+ });++ it("prints a whole percentage without decimals", () => {+ expect(formatDiscountPercent({ value: 10, numberFormatLocale: "pl" })).toBe(+ "10%",+ );+ });+});diff --git a/src/app/(main)/(app)/utils/item-discount.ts b/src/app/(main)/(app)/utils/item-discount.tsnew file mode 100644index 0000000..a60aae1--- /dev/null+++ b/src/app/(main)/(app)/utils/item-discount.ts@@ -0,0 +1,55 @@+import type {+ InvoiceItemData,+ SupportedNumberFormatLocale,+} from "@/app/schema";++import { formatAmount } from "./format-amount";++/** Whether the item has a discount that takes money off its line. */+export function hasItemDiscount(item: Pick<InvoiceItemData, "discountAmount">) {+ return item.discountAmount > 0;+}++/** Whether any item on the invoice has a discount. */+export function hasAnyItemDiscount(+ items: ReadonlyArray<Pick<InvoiceItemData, "discountAmount">>,+) {+ return items.some((item) => {+ return hasItemDiscount(item);+ });+}++/**+ * The line before its discount (quantity * net price), derived from the stored totals so+ * it always adds up with them: `netAmount` is already the line after the discount.+ */+export function getItemAmountBeforeDiscount(+ item: Pick<InvoiceItemData, "netAmount" | "discountAmount">,+) {+ return Number((item.netAmount + item.discountAmount).toFixed(2));+}++interface FormatDiscountPercentParams {+ /** The percentage, e.g. `12.5` for 12.5% off. */+ value: number;+ /** The invoice's number format, already resolved against its language. */+ numberFormatLocale: SupportedNumberFormatLocale;+}++/**+ * A percentage discount in the invoice's number format, so it matches the amounts around+ * it: "12.5%" in English, "12,5%" in Polish or German.+ */+export function formatDiscountPercent({+ value,+ numberFormatLocale,+}: FormatDiscountPercentParams) {+ const formattedValue = formatAmount({+ amount: value,+ numberFormatLocale,+ minimumFractionDigits: 0,+ maximumFractionDigits: 2,+ });++ return `${formattedValue}%`;+}diff --git a/src/app/(main)/changelog/content/item-discounts.mdx b/src/app/(main)/changelog/content/item-discounts.mdxnew file mode 100644index 0000000..8412c74--- /dev/null+++ b/src/app/(main)/changelog/content/item-discounts.mdx@@ -0,0 +1,42 @@+export const metadata = {+ title: "EasyInvoicePDF v1.0.6 - Item Discounts",+ description:+ 'Give a discount on any invoice item, as a percentage or a fixed amount, with an optional label like "Charitable donation". Tax is calculated on the discounted amount.',+ date: "2026-10-20",+ version: "1.0.6",+ type: "minor",+ popupSummary:+ "Add a percentage or fixed-amount discount to any invoice item.",+};++## ✨ Highlights++- **Discounts on invoice items** - click **Add discount** under an item's net price and take a percentage (`10%`) or a fixed amount (`50.00 EUR`) off that line. A fixed amount comes off the whole line, whatever the quantity+- **Your own label** - name the discount, e.g. `Charitable donation` or `Loyalty discount`, and it shows on the invoice. Leave it empty and the PDF says "Discount" in the invoice language+- **Tax on the discounted amount** - VAT is calculated after the discount, and the tax summary, totals and amount in words all use the discounted figures. The form shows what comes off and what is left as you type+- **Default template** - a new **Discount** column appears only when an item has a discount, and the label sits under the item name+- **Stripe template** - the item keeps its full price, and a row under it takes the discount off, e.g. `Charitable donation (10% off) -€1,000.00`. The tax column says what the tax applies to: `23% (on €9,000.00)`++---++### Changed++- Invoices saved in your browser or shared by link before this release open with no discount, so nothing about them changes until you add one++---++<div className="rounded-lg border-2 border-blue-200 bg-blue-50 px-8 py-4 dark:border-blue-900 dark:bg-blue-950" data-testid="ready-to-start-invoicing-cta">+<h2 className="!mt-4">Create your next invoice</h2>++EasyInvoicePDF is free and open source. There's no sign-up, and you can go from blank form to downloaded PDF in under a minute.++<div className="mt-6">+ <a+ href="https://easyinvoicepdf.com?ref=changelog"+ className="inline-flex h-12 w-full items-center justify-center rounded-lg bg-slate-900 px-8 text-lg font-medium no-underline transition-all hover:bg-slate-800 active:scale-[0.98]"+ >+ <span className="text-white">Start Invoicing</span>+ </a>+</div>++</div>diff --git a/src/app/api/generate-invoice/__tests__/server-pdf-fixture.ts b/src/app/api/generate-invoice/__tests__/server-pdf-fixture.tsindex c262334..6cfbf45 100644--- a/src/app/api/generate-invoice/__tests__/server-pdf-fixture.ts+++ b/src/app/api/generate-invoice/__tests__/server-pdf-fixture.ts@@ -29,6 +29,10 @@ export const SERVER_PDF_MOCK_INVOICE_DATA = {vatAmountFieldIsVisible: true,preTaxAmount: 10_000,preTaxAmountFieldIsVisible: true,+ discountType: "percentage",+ discountValue: 0,+ discountLabel: "",+ discountAmount: 0,};}),total: 10_000,diff --git a/src/app/api/generate-invoice/render-pdf-on-server.tsx b/src/app/api/generate-invoice/render-pdf-on-server.tsxindex 1517f82..2ce8c88 100644--- a/src/app/api/generate-invoice/render-pdf-on-server.tsx+++ b/src/app/api/generate-invoice/render-pdf-on-server.tsx@@ -187,6 +187,10 @@ const ENGLISH_INVOICE_PROD_DATA_BASE = {vatAmountFieldIsVisible: true,preTaxAmount: INVOICE_NET_PRICE,preTaxAmountFieldIsVisible: true,+ discountType: "percentage",+ discountValue: 0,+ discountLabel: "",+ discountAmount: 0,},],total: INVOICE_NET_PRICE,diff --git a/src/app/api/generate-invoice/sample-invoice-data.ts b/src/app/api/generate-invoice/sample-invoice-data.tsindex 5356bd6..6f6b563 100644--- a/src/app/api/generate-invoice/sample-invoice-data.ts+++ b/src/app/api/generate-invoice/sample-invoice-data.ts@@ -87,6 +87,10 @@ export const SAMPLE_INVOICE_DATA = {vatAmountFieldIsVisible: true,preTaxAmount: 1000,preTaxAmountFieldIsVisible: true,+ discountType: "percentage",+ discountValue: 0,+ discountLabel: "",+ discountAmount: 0,},],total: 1000,diff --git a/src/app/constants/index.ts b/src/app/constants/index.tsindex fbef789..4c3d15d 100644--- a/src/app/constants/index.ts+++ b/src/app/constants/index.ts@@ -171,6 +171,11 @@ export const INITIAL_INVOICE_DATA = {preTaxAmount: 0,preTaxAmountFieldIsVisible: true,++ discountType: "percentage",+ discountValue: 0,+ discountLabel: "",+ discountAmount: 0,},],total: 0,diff --git a/src/app/schema/index.ts b/src/app/schema/index.tsindex a6ab307..fb70368 100644--- a/src/app/schema/index.ts+++ b/src/app/schema/index.ts@@ -1017,165 +1017,243 @@ export const APP_VERSION = "1.0.0";*/export const SCHEMA_VERSION = "1.0.0";-export const invoiceItemSchema = z.object({- // Show/hide Number column on PDF- invoiceItemNumberIsVisible: z.boolean().default(true),+/**+ * How an item's discount is entered: a percentage of the line (`10` -> 10% off), or a fixed+ * amount taken off the whole line (`50` -> 50.00 off, whatever the quantity).+ */+export const ITEM_DISCOUNT_TYPES = ["percentage", "amount"] as const;+export type ItemDiscountType = (typeof ITEM_DISCOUNT_TYPES)[number];- name: z- .string()- .max(500, "Item name must not exceed 500 characters")- .trim()- .optional(),- nameFieldIsVisible: z.boolean().default(true),+/**+ * Reads a discount value as the form holds it: a number, or the string a number input gives+ * back. Empty means no discount (0), and anything that is not a number comes back as `NaN`+ * for the schema to reject.+ *+ * The schema and `calculateItemTotals` both read discounts through this, so a value the form+ * accepts is always the value the totals apply.+ */+export function parseDiscountValue(raw: unknown) {+ if (raw === null || raw === undefined) return 0;+ if (typeof raw === "string" && raw.trim() === "") return 0;- typeOfGTU: z- .string()- .max(50, "Type of GTU must not exceed 50 characters")- .trim()- .optional()- .default(""),- typeOfGTUFieldIsVisible: z.boolean().default(true),+ return Number(raw);+}- amount: z- .any()- .refine(- (val) => {- return val !== "";- },- {- message: "Amount is required",- },- )- .transform(Number)- .refine(- (val) => {- return val >= 0;- },- {- message: "Amount must be >= 0",- },- )- .refine(- (val) => {- return val <= 999_999.99;- },- {- message: "Amount must not exceed 999 999.99",- },- ),- amountFieldIsVisible: z.boolean().default(true),+/** Longest custom discount label, e.g. "Charitable donation". */+export const MAX_ITEM_DISCOUNT_LABEL_LENGTH = 100;- unit: z.string().trim().optional(),- unitFieldIsVisible: z.boolean().default(true),+export const invoiceItemSchema = z+ .object({+ // Show/hide Number column on PDF+ invoiceItemNumberIsVisible: z.boolean().default(true),++ name: z+ .string()+ .max(500, "Item name must not exceed 500 characters")+ .trim()+ .optional(),+ nameFieldIsVisible: z.boolean().default(true),++ typeOfGTU: z+ .string()+ .max(50, "Type of GTU must not exceed 50 characters")+ .trim()+ .optional()+ .default(""),+ typeOfGTUFieldIsVisible: z.boolean().default(true),++ amount: z+ .any()+ .refine(+ (val) => {+ return val !== "";+ },+ {+ message: "Amount is required",+ },+ )+ .transform(Number)+ .refine(+ (val) => {+ return val >= 0;+ },+ {+ message: "Amount must be >= 0",+ },+ )+ .refine(+ (val) => {+ return val <= 999_999.99;+ },+ {+ message: "Amount must not exceed 999 999.99",+ },+ ),+ amountFieldIsVisible: z.boolean().default(true),- netPrice: z- .any()- .refine(- (val) => {- return val !== "";- },- {- message: "Net price is required",- },- )- .transform(Number)- .refine(- (val) => {- return val >= 0;- },- {- message: "Net price must be >= 0",- },- )- .refine(- (val) => {- return val <= 1_000_000_000;- },- {- message: "Net price must not exceed 1 billion",- },- ),- netPriceFieldIsVisible: z.boolean().default(true),-- // Tax rate. Accepts numbers 0-100 or any text string (i.e. NP, OO, etc)- // Valid inputs and their outputs:- // - "23" -> 23 (number)- // - "100" -> 100 (number)- // - "NP" -> "NP" (string)- vat: z- .preprocess(- // z.preprocess runs before Zod does any validation, parsing, or type checking on the schema it wraps.- (raw) => {- // Handle null/undefined by returning empty string for validation- if (raw === null || raw === undefined) return "";-- // Trim whitespace from string inputs, pass through other types as-is- const val = typeof raw === "string" ? raw.trim() : raw;-- // Empty strings should fail the required validation- if (val === "") return "";-- // Attempt to convert to number- const num = Number(val);-- // If conversion succeeds, return as number (for 0-100 validation)- // Otherwise, return as string (for text values like "NP", "OO", etc)- return Number.isNaN(num) ? val : num;- },- z.union(- [- z- .number()- .min(- 0,- `Tax rate must be a number between 0-100 or any text (i.e. NP, OO, etc).`,- )- .max(- 100,- `Tax rate must be a number between 0-100 or any text (i.e. NP, OO, etc).`,- ),- z- .string()- .min(- 1,- `Tax rate is required. Enter a number (0-100) or any text (i.e. NP, OO, etc).`,- ),- ],+ unit: z.string().trim().optional(),+ unitFieldIsVisible: z.boolean().default(true),++ netPrice: z+ .any()+ .refine(+ (val) => {+ return val !== "";+ },{- // zod v4 replaced `errorMap` with `error`, which returns the message- // string directly instead of a `{ message }` object.- error: () => {- return "Tax rate is required. Enter a number (0-100) or any text (i.e. NP, OO, etc).";- },+ message: "Net price is required",+ },+ )+ .transform(Number)+ .refine(+ (val) => {+ return val >= 0;+ },+ {+ message: "Net price must be >= 0",+ },+ )+ .refine(+ (val) => {+ return val <= 1_000_000_000;+ },+ {+ message: "Net price must not exceed 1 billion",},),- )- .describe(- "Tax rate. Accepts numbers 0-100 or any text (i.e. NP, OO, etc).",- ),+ netPriceFieldIsVisible: z.boolean().default(true),++ // Tax rate. Accepts numbers 0-100 or any text string (i.e. NP, OO, etc)+ // Valid inputs and their outputs:+ // - "23" -> 23 (number)+ // - "100" -> 100 (number)+ // - "NP" -> "NP" (string)+ vat: z+ .preprocess(+ // z.preprocess runs before Zod does any validation, parsing, or type checking on the schema it wraps.+ (raw) => {+ // Handle null/undefined by returning empty string for validation+ if (raw === null || raw === undefined) return "";++ // Trim whitespace from string inputs, pass through other types as-is+ const val = typeof raw === "string" ? raw.trim() : raw;++ // Empty strings should fail the required validation+ if (val === "") return "";++ // Attempt to convert to number+ const num = Number(val);++ // If conversion succeeds, return as number (for 0-100 validation)+ // Otherwise, return as string (for text values like "NP", "OO", etc)+ return Number.isNaN(num) ? val : num;+ },+ z.union(+ [+ z+ .number()+ .min(+ 0,+ `Tax rate must be a number between 0-100 or any text (i.e. NP, OO, etc).`,+ )+ .max(+ 100,+ `Tax rate must be a number between 0-100 or any text (i.e. NP, OO, etc).`,+ ),+ z+ .string()+ .min(+ 1,+ `Tax rate is required. Enter a number (0-100) or any text (i.e. NP, OO, etc).`,+ ),+ ],+ {+ // zod v4 replaced `errorMap` with `error`, which returns the message+ // string directly instead of a `{ message }` object.+ error: () => {+ return "Tax rate is required. Enter a number (0-100) or any text (i.e. NP, OO, etc).";+ },+ },+ ),+ )+ .describe(+ "Tax rate. Accepts numbers 0-100 or any text (i.e. NP, OO, etc).",+ ),- vatFieldIsVisible: z.boolean().default(true),+ vatFieldIsVisible: z.boolean().default(true),++ /**+ * Net Amount (**calculated automatically** - read only field in the UI)+ */+ netAmount: z.coerce.number().nonnegative("Net amount must be non-negative"),+ netAmountFieldIsVisible: z.boolean().default(true),++ /**+ * VAT Amount (**calculated automatically** - read only field in the UI)+ */+ vatAmount: z.coerce.number().nonnegative("VAT amount must be non-negative"),+ vatAmountFieldIsVisible: z.boolean().default(true),++ /**+ * Pre-tax Amount (**calculated automatically** - read only field in the UI)+ */+ preTaxAmount: z.coerce+ .number()+ .nonnegative("Pre-tax amount must be non-negative"),+ preTaxAmountFieldIsVisible: z.boolean().default(true),++ discountType: z.enum(ITEM_DISCOUNT_TYPES).default("percentage"),++ // Discount value, read according to `discountType`. An empty input means no discount.+ // Its upper bound depends on the type and the line amount, see the `superRefine` below:+ // at most 100 for a percentage, at most Amount × Net Price for a fixed amount.+ discountValue: z.preprocess(+ parseDiscountValue,+ z+ .number({ error: "Discount must be a number" })+ .min(0, "Discount must be >= 0"),+ ),- /**- * Net Amount (**calculated automatically** - read only field in the UI)- */- netAmount: z.coerce.number().nonnegative("Net amount must be non-negative"),- netAmountFieldIsVisible: z.boolean().default(true),+ // Optional text shown next to the discount in the PDF, e.g. "Charitable donation".+ // Empty falls back to the translated "Discount".+ discountLabel: z+ .string()+ .max(+ MAX_ITEM_DISCOUNT_LABEL_LENGTH,+ `Discount label must not exceed ${MAX_ITEM_DISCOUNT_LABEL_LENGTH} characters`,+ )+ .trim()+ .optional()+ .default(""),++ /**+ * Discount Amount, the money taken off the line (**calculated automatically** - read only field in the UI)+ */+ discountAmount: z.coerce+ .number()+ .nonnegative("Discount amount must be non-negative")+ .default(0),+ })+ .superRefine((item, ctx) => {+ if (item.discountType === "percentage" && item.discountValue > 100) {+ ctx.addIssue({+ code: "custom",+ path: ["discountValue"],+ message: "Discount must be between 0 and 100%",+ });+ }- /**- * VAT Amount (**calculated automatically** - read only field in the UI)- */- vatAmount: z.coerce.number().nonnegative("VAT amount must be non-negative"),- vatAmountFieldIsVisible: z.boolean().default(true),+ const lineAmount = Number((item.amount * item.netPrice).toFixed(2));- /**- * Pre-tax Amount (**calculated automatically** - read only field in the UI)- */- preTaxAmount: z.coerce- .number()- .nonnegative("Pre-tax amount must be non-negative"),- preTaxAmountFieldIsVisible: z.boolean().default(true),-});+ if (item.discountType === "amount" && item.discountValue > lineAmount) {+ ctx.addIssue({+ code: "custom",+ path: ["discountValue"],+ message:+ "Discount must not exceed the line amount (Amount × Net Price)",+ });+ }+ });export type InvoiceItemData = z.infer<typeof invoiceItemSchema>;diff --git a/src/utils/__tests__/data.ts b/src/utils/__tests__/data.tsindex 6f6c491..7f01b40 100644--- a/src/utils/__tests__/data.ts+++ b/src/utils/__tests__/data.ts@@ -56,6 +56,10 @@ export const MOCK_INVOICE_ITEM_DATA = {vatAmountFieldIsVisible: true,preTaxAmount: 247.23,preTaxAmountFieldIsVisible: true,+ discountType: "percentage",+ discountValue: 0,+ discountLabel: "",+ discountAmount: 0,} as const satisfies InvoiceItemData;export const MOCK_INVOICE_DATA = {diff --git a/src/utils/__tests__/url-compression.test.ts b/src/utils/__tests__/url-compression.test.tsindex 6f80e35..1b74879 100644--- a/src/utils/__tests__/url-compression.test.ts+++ b/src/utils/__tests__/url-compression.test.ts@@ -186,6 +186,10 @@ describe("URL Compression Utilities", () => {vatAmountFieldIsVisible: true,preTaxAmount: 100,preTaxAmountFieldIsVisible: true,+ discountType: "percentage",+ discountValue: 0,+ discountLabel: "",+ discountAmount: 0,},],invoiceTypeFieldIsVisible: true,@@ -606,6 +610,68 @@ describe("URL Compression Utilities", () => {});});+ describe("item discounts", () => {+ it("leaves the discount fields out of items without a discount", () => {+ const compressed = compressInvoiceData(MOCK_INVOICE_DATA);+ const compressedItem = (compressed.m as Record<string, unknown>[])[0];++ for (const key of [+ "discountType",+ "discountValue",+ "discountLabel",+ "discountAmount",+ ] as const) {+ expect(compressedItem).not.toHaveProperty(+ INVOICE_KEY_COMPRESSION_MAP[key],+ );+ }++ // and puts them back on the way out+ expect(decompressInvoiceData(compressed)).toEqual(MOCK_INVOICE_DATA);+ });++ it("keeps the discount fields of a discounted item", () => {+ const invoiceData = {+ ...MOCK_INVOICE_DATA,+ items: [+ {+ ...MOCK_INVOICE_DATA.items[0],+ discountType: "amount",+ discountValue: 50,+ discountLabel: "Loyalty",+ discountAmount: 50,+ },+ ],+ } satisfies InvoiceData;++ const compressed = compressInvoiceData(invoiceData);++ expect(decompressInvoiceData(compressed)).toEqual(invoiceData);+ });++ it("gives items from links made before discounts existed no discount", () => {+ const {+ discountType,+ discountValue,+ discountLabel,+ discountAmount,+ ...legacyItem+ } = MOCK_INVOICE_DATA.items[0];+ const compressed = compressInvoiceData({+ ...MOCK_INVOICE_DATA,+ items: [legacyItem as InvoiceData["items"][number]],+ });++ expect(decompressInvoiceData(compressed)).toEqual(MOCK_INVOICE_DATA);+ expect([+ discountType,+ discountValue,+ discountLabel,+ discountAmount,+ ]).toEqual(["percentage", 0, "", 0]);+ });+ });+describe("size reduction verification", () => {it("should reduce the size of JSON when compressed", () => {const originalJson = JSON.stringify(MOCK_INVOICE_DATA);diff --git a/src/utils/url-compression.ts b/src/utils/url-compression.tsindex 6fd4d12..e31be97 100644--- a/src/utils/url-compression.ts+++ b/src/utils/url-compression.ts@@ -116,6 +116,10 @@ export const INVOICE_KEY_COMPRESSION_MAP = {vatAmountFieldIsVisible: "Y",preTaxAmount: "Z",preTaxAmountFieldIsVisible: "0",+ discountType: "&",+ discountValue: "*",+ discountLabel: "~",+ discountAmount: "=",} as const satisfies Record<AllInvoiceKeys, string>;/**@@ -239,7 +243,23 @@ function restoreKeys<T>(* ```*/export function compressInvoiceData(invoiceData: InvoiceData) {- const res = remapKeys(invoiceData);+ // guard for callers handing over something that is not an invoice at all; remapKeys+ // passes those through as they are+ const hasItems =+ typeof invoiceData === "object" &&+ invoiceData !== null &&+ Array.isArray(invoiceData.items);++ const res = remapKeys(+ hasItems+ ? {+ ...invoiceData,+ items: invoiceData.items.map((item) => {+ return omitDefaultDiscount(item);+ }),+ }+ : invoiceData,+ );return res;}@@ -257,5 +277,53 @@ export function compressInvoiceData(invoiceData: InvoiceData) {export function decompressInvoiceData(compressedData: Record<string, unknown>) {const res = restoreKeys(compressedData);+ if (Array.isArray(res.items)) {+ res.items = res.items.map((item: unknown) => {+ return withDefaultDiscount(item);+ });+ }+return res;}++/**+ * An item without a discount, as the form stores it. Share links leave these fields out of+ * such items, so every item does not pay for four keys it does not use.+ */+const NO_DISCOUNT = {+ discountType: "percentage",+ discountValue: 0,+ discountLabel: "",+ discountAmount: 0,+} as const satisfies Partial<InvoiceItemData>;++const NO_DISCOUNT_KEYS = Object.keys(+ NO_DISCOUNT,+) as (keyof typeof NO_DISCOUNT)[];++/** Drops the discount fields of an item that has no discount, see {@link NO_DISCOUNT}. */+function omitDefaultDiscount(item: InvoiceItemData) {+ const hasNoDiscount = NO_DISCOUNT_KEYS.every((key) => {+ return item[key] === NO_DISCOUNT[key];+ });++ if (!hasNoDiscount) return item;++ return Object.fromEntries(+ Object.entries(item).filter(([key]) => {+ return !(key in NO_DISCOUNT);+ }),+ );+}++/**+ * Puts back the discount fields {@link omitDefaultDiscount} left out. Links made before+ * discounts existed have none either, and get the same "no discount" values.+ */+function withDefaultDiscount(item: unknown) {+ if (item === null || typeof item !== "object" || Array.isArray(item)) {+ return item;+ }++ return { ...NO_DISCOUNT, ...item };+}