Skip to content
TypeScript

feat: add Invoice page

Vipul Kumard12ac42ad627
diff --git a/src/app/invoice/page.tsx b/src/app/invoice/page.tsx
new file mode 100644
index 0000000..7b3612e
--- /dev/null
+++ b/src/app/invoice/page.tsx
@@ -0,0 +1,19 @@
+import type { Metadata } from "next";
+import { Suspense } from "react";
+import { InvoiceDeepLink } from "@/components/pages/invoice/invoice-deep-link";
+import { InvoicePage } from "@/components/pages/invoice/invoice-page";
+
+export const metadata: Metadata = { title: "Invoice" };
+
+export default function Page() {
+ return (
+ <>
+ <InvoicePage />
+ {/* Reads ?open=<id> (linked from global search). useSearchParams needs a
+ Suspense boundary so the rest of the page can still be prerendered. */}
+ <Suspense fallback={null}>
+ <InvoiceDeepLink />
+ </Suspense>
+ </>
+ );
+}
diff --git a/src/components/pages/invoice/invoice-deep-link.tsx b/src/components/pages/invoice/invoice-deep-link.tsx
new file mode 100644
index 0000000..88a331f
--- /dev/null
+++ b/src/components/pages/invoice/invoice-deep-link.tsx
@@ -0,0 +1,27 @@
+"use client";
+
+import { useRouter, useSearchParams } from "next/navigation";
+import { useEffect } from "react";
+import { toast } from "sonner";
+import { useAppStore } from "@/stores/app-store";
+import { useInvoiceUi } from "./invoice-ui-store";
+
+/** Opens the invoice named by `?open=<id>` (the global search links here), then clears the param. */
+export function InvoiceDeepLink() {
+ const router = useRouter();
+ const openId = useSearchParams().get("open");
+ const found = useAppStore((s) => (openId ? s.invoices.some((i) => i.id === openId) : false));
+
+ useEffect(() => {
+ if (!openId) return;
+ if (found) {
+ useInvoiceUi.getState().view(openId);
+ router.replace("/invoice", { scroll: false });
+ } else if (useAppStore.persist.hasHydrated()) {
+ toast.error("Invoice not found", { description: "It may have been deleted." });
+ router.replace("/invoice", { scroll: false });
+ }
+ }, [openId, found, router]);
+
+ return null;
+}
diff --git a/src/components/pages/invoice/invoice-editor.tsx b/src/components/pages/invoice/invoice-editor.tsx
new file mode 100644
index 0000000..7408ed7
--- /dev/null
+++ b/src/components/pages/invoice/invoice-editor.tsx
@@ -0,0 +1,321 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { PlusIcon, Trash2Icon } from "lucide-react";
+import { toast } from "sonner";
+import { Field } from "@/components/dialogs/field";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Textarea } from "@/components/ui/textarea";
+import { addDays } from "@/lib/dates";
+import type { Invoice, InvoiceStatus } from "@/lib/types";
+import { useToday } from "@/hooks/use-today";
+import { uid, useAppStore } from "@/stores/app-store";
+import { useInvoiceUi } from "./invoice-ui-store";
+import { CURRENCIES, formatMoney, lineTotal, nextInvoiceNumber } from "./invoice-utils";
+
+type Line = { id: string; description: string; quantity: string; rate: string };
+type Draft = Omit<Invoice, "id" | "items" | "status"> & { items: Line[] };
+
+export function InvoiceEditor() {
+ const editor = useInvoiceUi((s) => s.editor);
+ const closeEditor = useInvoiceUi((s) => s.closeEditor);
+ return (
+ <Dialog open={editor.open} onOpenChange={(v) => !v && closeEditor()}>
+ <DialogContent className="max-h-[calc(100dvh-48px)] grid-rows-[auto_minmax(0,1fr)_auto] gap-0 p-0 sm:max-w-[720px]">
+ <EditorForm key={editor.session} invoiceId={editor.id} onDone={closeEditor} />
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+const blankLine = (): Line => ({ id: uid("it"), description: "", quantity: "1", rate: "" });
+
+function EditorForm({ invoiceId, onDone }: { invoiceId?: string; onDone: () => void }) {
+ const today = useToday();
+ const invoices = useAppStore((s) => s.invoices);
+ const saveInvoice = useAppStore((s) => s.saveInvoice);
+ const existing = invoices.find((i) => i.id === invoiceId);
+
+ const [draft, setDraft] = useState<Draft>(() =>
+ existing
+ ? {
+ number: existing.number,
+ client: existing.client,
+ issueDate: existing.issueDate,
+ dueDate: existing.dueDate,
+ currency: existing.currency,
+ notes: existing.notes,
+ items: existing.items.map((i) => ({
+ id: i.id,
+ description: i.description,
+ quantity: String(i.quantity),
+ rate: String(i.rate),
+ })),
+ }
+ : {
+ number: nextInvoiceNumber(invoices, today),
+ client: "",
+ issueDate: today,
+ dueDate: addDays(today, 30),
+ currency: invoices[0]?.currency ?? "USD",
+ notes: "Thank you for your business.",
+ items: [blankLine()],
+ },
+ );
+ const [touched, setTouched] = useState(false);
+
+ const set = <K extends keyof Draft>(k: K, v: Draft[K]) => setDraft((d) => ({ ...d, [k]: v }));
+ const setLine = (id: string, patch: Partial<Line>) =>
+ setDraft((d) => ({ ...d, items: d.items.map((l) => (l.id === id ? { ...l, ...patch } : l)) }));
+
+ const clients = useMemo(() => [...new Set(invoices.map((i) => i.client))].sort(), [invoices]);
+ const total = draft.items.reduce((n, l) => n + lineTotal({ quantity: Number(l.quantity), rate: Number(l.rate) }), 0);
+ const filled = draft.items.filter((l) => l.description.trim() && Number(l.quantity) > 0);
+ const duplicateNumber = invoices.some((i) => i.number === draft.number.trim() && i.id !== invoiceId);
+
+ const error = !draft.client.trim()
+ ? "Add a client."
+ : !draft.number.trim()
+ ? "Add an invoice number."
+ : duplicateNumber
+ ? "Another invoice already uses this number."
+ : draft.dueDate < draft.issueDate
+ ? "The due date can't be before the issue date."
+ : filled.length === 0
+ ? "Add at least one line item with a description and quantity."
+ : null;
+
+ const save = (status: InvoiceStatus) => {
+ setTouched(true);
+ if (error) return;
+ const saved = saveInvoice({
+ id: existing?.id,
+ number: draft.number.trim(),
+ client: draft.client.trim(),
+ issueDate: draft.issueDate,
+ dueDate: draft.dueDate,
+ currency: draft.currency,
+ notes: draft.notes,
+ status,
+ items: filled.map((l) => ({
+ id: l.id,
+ description: l.description.trim(),
+ quantity: Number(l.quantity),
+ rate: Number(l.rate) || 0,
+ })),
+ });
+ toast.success(existing ? "Invoice updated" : status === "sent" ? "Invoice created and sent" : "Draft saved", {
+ description: `${saved.number} · ${saved.client}`,
+ action: { label: "View", onClick: () => useInvoiceUi.getState().view(saved.id) },
+ });
+ onDone();
+ };
+
+ return (
+ <form
+ className="contents"
+ onSubmit={(e) => {
+ e.preventDefault();
+ save(existing ? existing.status : "draft");
+ }}
+ >
+ <DialogHeader className="gap-1.5 border-b border-hairline px-5 pt-5 pb-4">
+ <DialogTitle className="t-16">{existing ? `Edit ${existing.number}` : "New invoice"}</DialogTitle>
+ <DialogDescription className="t-14">
+ {existing ? "Changes apply immediately to the invoice." : "Drafts stay private until you send them."}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="grid content-start gap-5 overflow-y-auto scroll-thin px-5 py-5">
+ <div className="grid grid-cols-[1.4fr_1fr_120px] gap-3">
+ <Field label="Client" htmlFor="inv-client">
+ <Input
+ id="inv-client"
+ list="inv-clients"
+ autoFocus={!existing}
+ placeholder="Company name"
+ value={draft.client}
+ aria-invalid={touched && !draft.client.trim()}
+ onChange={(e) => set("client", e.target.value)}
+ />
+ <datalist id="inv-clients">
+ {clients.map((c) => (
+ <option key={c} value={c} />
+ ))}
+ </datalist>
+ </Field>
+ <Field label="Invoice number" htmlFor="inv-number">
+ <Input
+ id="inv-number"
+ value={draft.number}
+ aria-invalid={touched && (duplicateNumber || !draft.number.trim())}
+ onChange={(e) => set("number", e.target.value)}
+ />
+ </Field>
+ <Field label="Currency" htmlFor="inv-currency">
+ <Select value={draft.currency} onValueChange={(v) => set("currency", v)}>
+ <SelectTrigger id="inv-currency" className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {CURRENCIES.map((c) => (
+ <SelectItem key={c} value={c}>
+ {c}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ </div>
+ <div className="grid grid-cols-2 gap-3">
+ <Field label="Issue date" htmlFor="inv-issue">
+ <Input
+ id="inv-issue"
+ type="date"
+ required
+ value={draft.issueDate}
+ onChange={(e) => set("issueDate", e.target.value)}
+ />
+ </Field>
+ <Field label="Due date" htmlFor="inv-due">
+ <div className="flex gap-1.5">
+ <Input
+ id="inv-due"
+ type="date"
+ required
+ min={draft.issueDate}
+ value={draft.dueDate}
+ aria-invalid={draft.dueDate < draft.issueDate}
+ onChange={(e) => set("dueDate", e.target.value)}
+ />
+ {[15, 30].map((n) => (
+ <Button
+ key={n}
+ type="button"
+ className="h-8 shrink-0 px-2"
+ onClick={() => set("dueDate", addDays(draft.issueDate, n))}
+ >
+ Net {n}
+ </Button>
+ ))}
+ </div>
+ </Field>
+ </div>
+
+ <div className="grid gap-2">
+ <span className="t-12 text-fg-2">Line items</span>
+ <div className="overflow-hidden rounded-lg border border-hairline">
+ <div className="grid h-8 grid-cols-[1fr_72px_104px_104px_36px] items-center gap-2 bg-app px-2">
+ <span className="t-12 pl-0.5 text-fg-2">Description</span>
+ <span className="t-12 text-right text-fg-2">Qty</span>
+ <span className="t-12 text-right text-fg-2">Rate</span>
+ <span className="t-12 text-right text-fg-2">Amount</span>
+ <span />
+ </div>
+ {draft.items.map((l, idx) => (
+ <div
+ key={l.id}
+ className="grid grid-cols-[1fr_72px_104px_104px_36px] items-center gap-2 border-t border-subtle px-2 py-1.5"
+ >
+ <Input
+ aria-label={`Line ${idx + 1} description`}
+ placeholder="Service or product"
+ value={l.description}
+ onChange={(e) => setLine(l.id, { description: e.target.value })}
+ />
+ <Input
+ aria-label={`Line ${idx + 1} quantity`}
+ type="number"
+ inputMode="decimal"
+ min={0}
+ step="any"
+ className="text-right tabular-nums"
+ value={l.quantity}
+ onChange={(e) => setLine(l.id, { quantity: e.target.value })}
+ />
+ <Input
+ aria-label={`Line ${idx + 1} rate`}
+ type="number"
+ inputMode="decimal"
+ min={0}
+ step="any"
+ placeholder="0.00"
+ className="text-right tabular-nums"
+ value={l.rate}
+ onChange={(e) => setLine(l.id, { rate: e.target.value })}
+ />
+ <span className="t-14 truncate text-right text-table tabular-nums">
+ {formatMoney(lineTotal({ quantity: Number(l.quantity), rate: Number(l.rate) }), draft.currency)}
+ </span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label={`Remove line ${idx + 1}`}
+ disabled={draft.items.length === 1}
+ onClick={() => set("items", draft.items.filter((x) => x.id !== l.id))}
+ >
+ <Trash2Icon />
+ </Button>
+ </div>
+ ))}
+ <div className="flex items-center justify-between border-t border-subtle bg-app px-2 py-2">
+ <Button type="button" size="sm" onClick={() => set("items", [...draft.items, blankLine()])}>
+ <PlusIcon /> Add line
+ </Button>
+ <dl className="grid grid-cols-[auto_120px] items-center gap-x-4 gap-y-2 pr-[44px]">
+ <dt className="t-12 text-right text-fg-2">Subtotal</dt>
+ <dd className="t-14 text-right text-table tabular-nums">{formatMoney(total, draft.currency)}</dd>
+ <dt className="t-14 text-right text-fg">Total</dt>
+ <dd className="t-16 text-right text-fg tabular-nums">{formatMoney(total, draft.currency)}</dd>
+ </dl>
+ </div>
+ </div>
+ </div>
+
+ <Field label="Notes" htmlFor="inv-notes">
+ <Textarea
+ id="inv-notes"
+ rows={2}
+ placeholder="Payment terms, bank details or a thank-you note"
+ value={draft.notes}
+ onChange={(e) => set("notes", e.target.value)}
+ />
+ </Field>
+ </div>
+
+ <DialogFooter className="m-0 items-center rounded-b-xl border-t border-hairline bg-app px-5 py-3">
+ {touched && error ? (
+ <p className="t-12 mr-auto text-danger" role="alert">
+ {error}
+ </p>
+ ) : null}
+ <Button type="button" onClick={onDone}>
+ Cancel
+ </Button>
+ {existing ? (
+ <Button type="submit" variant="brand">
+ Save changes
+ </Button>
+ ) : (
+ <>
+ <Button type="submit">Save draft</Button>
+ <Button type="button" variant="brand" onClick={() => save("sent")}>
+ Create &amp; send
+ </Button>
+ </>
+ )}
+ </DialogFooter>
+ </form>
+ );
+}
diff --git a/src/components/pages/invoice/invoice-page.tsx b/src/components/pages/invoice/invoice-page.tsx
new file mode 100644
index 0000000..3f277f9
--- /dev/null
+++ b/src/components/pages/invoice/invoice-page.tsx
@@ -0,0 +1,336 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { CheckIcon, CopyIcon, EyeIcon, PencilIcon, PlusIcon, ReceiptIcon, SendIcon, Trash2Icon, XIcon } from "lucide-react";
+import { toast } from "sonner";
+import { Icon } from "@/components/icon";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { addDays, formatShort } from "@/lib/dates";
+import type { Invoice, InvoiceStatus } from "@/lib/types";
+import { cn } from "@/lib/utils";
+import { useToday } from "@/hooks/use-today";
+import { uid, useAppStore } from "@/stores/app-store";
+import { InvoiceEditor } from "./invoice-editor";
+import { useInvoiceUi } from "./invoice-ui-store";
+import { effectiveStatus, formatMoney, formatTotals, invoiceTotal, nextInvoiceNumber } from "./invoice-utils";
+import { InvoiceView } from "./invoice-view";
+import { InvoiceStatusBadge, STATUS_LABELS } from "./status-badge";
+
+type StatusFilter = "all" | InvoiceStatus;
+const STATUSES: InvoiceStatus[] = ["draft", "sent", "paid", "overdue"];
+
+export function InvoicePage() {
+ const today = useToday();
+ const invoices = useAppStore((s) => s.invoices);
+ const view = useInvoiceUi((s) => s.view);
+ const edit = useInvoiceUi((s) => s.edit);
+ const [query, setQuery] = useState("");
+ const [status, setStatus] = useState<StatusFilter>("all");
+
+ const rows = useMemo(
+ () =>
+ invoices
+ .map((inv) => ({ inv, status: effectiveStatus(inv, today), total: invoiceTotal(inv) }))
+ .sort((a, b) => b.inv.issueDate.localeCompare(a.inv.issueDate) || b.inv.number.localeCompare(a.inv.number)),
+ [invoices, today],
+ );
+
+ const visible = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ return rows.filter(
+ (r) =>
+ (status === "all" || r.status === status) &&
+ (!q || r.inv.number.toLowerCase().includes(q) || r.inv.client.toLowerCase().includes(q)),
+ );
+ }, [rows, query, status]);
+
+ const stats = useMemo(() => {
+ const pick = (...s: InvoiceStatus[]) => rows.filter((r) => s.includes(r.status)).map((r) => r.inv);
+ return {
+ outstanding: pick("sent", "overdue"),
+ overdue: pick("overdue"),
+ paid: pick("paid"),
+ drafts: pick("draft"),
+ };
+ }, [rows]);
+
+ const filtered = query.trim() !== "" || status !== "all";
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto scroll-thin bg-app">
+ <header className="sticky top-0 z-10 flex h-[68px] shrink-0 items-center gap-3 border-b border-hairline bg-surface px-4">
+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">
+ <h2 className="t-16 text-fg">Invoices</h2>
+ <p className="t-14 truncate text-fg-2">
+ {invoices.length} {invoices.length === 1 ? "invoice" : "invoices"} · {formatTotals(stats.outstanding)} outstanding
+ </p>
+ </div>
+ <label className="flex h-[30px] w-56 items-center gap-2 rounded-lg border border-control bg-surface px-2.5 transition-[border-color,box-shadow] duration-150 focus-within:border-brand/60 focus-within:ring-3 focus-within:ring-brand/15">
+ <Icon name="search" />
+ <input
+ type="search"
+ placeholder="Search number or client"
+ aria-label="Search invoices"
+ className="t-14 min-w-0 flex-1 bg-transparent text-fg outline-none placeholder:text-placeholder [&::-webkit-search-cancel-button]:hidden"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ />
+ {query && (
+ <button
+ type="button"
+ aria-label="Clear search"
+ className="-mr-1 rounded p-0.5 text-icon hover-fine:text-fg"
+ onClick={() => setQuery("")}
+ >
+ <XIcon className="size-3.5" />
+ </button>
+ )}
+ </label>
+ <Select value={status} onValueChange={(v) => setStatus(v as StatusFilter)}>
+ <SelectTrigger size="sm" className="h-[30px] w-[132px]" aria-label="Filter by status">
+ <Icon name="filter" />
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper" align="end">
+ <SelectItem value="all">All statuses</SelectItem>
+ {STATUSES.map((s) => (
+ <SelectItem key={s} value={s}>
+ {STATUS_LABELS[s]}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <div className="h-4 w-px bg-hairline" aria-hidden />
+ <Button variant="brand" onClick={() => edit()}>
+ <PlusIcon /> New invoice
+ </Button>
+ </header>
+
+ <div className="flex flex-col gap-4 p-4">
+ <div className="grid grid-cols-4 overflow-hidden rounded-xl border border-hairline bg-surface">
+ <Stat label="Outstanding" value={formatTotals(stats.outstanding)} count={stats.outstanding.length} />
+ <Stat
+ label="Overdue"
+ value={formatTotals(stats.overdue)}
+ count={stats.overdue.length}
+ danger={stats.overdue.length > 0}
+ onClick={() => setStatus("overdue")}
+ />
+ <Stat label="Paid" value={formatTotals(stats.paid)} count={stats.paid.length} onClick={() => setStatus("paid")} />
+ <Stat label="Drafts" value={formatTotals(stats.drafts)} count={stats.drafts.length} onClick={() => setStatus("draft")} />
+ </div>
+
+ <section className="overflow-hidden rounded-xl border border-hairline bg-surface">
+ {visible.length === 0 ? (
+ <div className="flex flex-col items-center gap-3 px-4 py-16 text-center">
+ <span className="flex size-10 items-center justify-center rounded-lg bg-app">
+ <ReceiptIcon className="size-4 text-icon" />
+ </span>
+ <div className="flex flex-col gap-1.5">
+ <p className="t-14 text-fg">{filtered ? "No invoices match" : "No invoices yet"}</p>
+ <p className="t-14 text-fg-2">
+ {filtered ? "Try a different search or status." : "Create your first invoice to get paid."}
+ </p>
+ </div>
+ {filtered ? (
+ <Button
+ onClick={() => {
+ setQuery("");
+ setStatus("all");
+ }}
+ >
+ Clear filters
+ </Button>
+ ) : (
+ <Button onClick={() => edit()}>
+ <PlusIcon /> New invoice
+ </Button>
+ )}
+ </div>
+ ) : (
+ <table className="w-full table-fixed border-collapse">
+ <colgroup>
+ <col className="w-[160px]" />
+ <col />
+ <col className="w-[120px]" />
+ <col className="w-[120px]" />
+ <col className="w-[150px]" />
+ <col className="w-[120px]" />
+ <col className="w-[56px]" />
+ </colgroup>
+ <thead>
+ <tr className="h-10 bg-app text-left">
+ <th className="t-14 px-4 font-medium text-fg-2">Number</th>
+ <th className="t-14 px-2 font-medium text-fg-2">Client</th>
+ <th className="t-14 px-2 font-medium text-fg-2">Issued</th>
+ <th className="t-14 px-2 font-medium text-fg-2">Due</th>
+ <th className="t-14 px-2 text-right font-medium text-fg-2">Amount</th>
+ <th className="t-14 px-4 font-medium text-fg-2">Status</th>
+ <th className="pr-3">
+ <span className="sr-only">Actions</span>
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {visible.map(({ inv, status: st, total }) => (
+ <tr
+ key={inv.id}
+ onClick={() => view(inv.id)}
+ className="h-14 cursor-pointer border-b border-subtle transition-colors duration-150 last:border-b-0 hover-fine:bg-hover/50"
+ >
+ <td className="px-4">
+ <button
+ type="button"
+ className="t-14 rounded text-table outline-none focus-visible:ring-3 focus-visible:ring-brand/15"
+ onClick={(e) => {
+ e.stopPropagation();
+ view(inv.id);
+ }}
+ >
+ {inv.number}
+ </button>
+ </td>
+ <td className="t-14 truncate px-2 text-table">{inv.client}</td>
+ <td className="t-14 px-2 text-table">{formatShort(inv.issueDate)}, {inv.issueDate.slice(0, 4)}</td>
+ <td className={cn("t-14 px-2", st === "overdue" ? "text-danger" : "text-table")}>
+ {formatShort(inv.dueDate)}, {inv.dueDate.slice(0, 4)}
+ </td>
+ <td className="t-14 px-2 text-right text-table tabular-nums">{formatMoney(total, inv.currency)}</td>
+ <td className="px-4">
+ <InvoiceStatusBadge status={st} />
+ </td>
+ <td className="pr-3 text-right" onClick={(e) => e.stopPropagation()}>
+ <RowMenu invoice={inv} today={today} />
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </section>
+ </div>
+
+ <InvoiceView />
+ <InvoiceEditor />
+ </div>
+ );
+}
+
+function Stat({
+ label,
+ value,
+ count,
+ danger,
+ onClick,
+}: {
+ label: string;
+ value: string;
+ count: number;
+ danger?: boolean;
+ onClick?: () => void;
+}) {
+ const body = (
+ <>
+ <span className="t-12 flex w-full items-center justify-between text-fg-2">
+ {label}
+ <span className="text-placeholder tabular-nums">{count}</span>
+ </span>
+ <span
+ className={cn(
+ "truncate text-[20px] leading-none font-medium tracking-[-0.4px] tabular-nums",
+ danger ? "text-danger" : "text-fg",
+ )}
+ >
+ {value}
+ </span>
+ </>
+ );
+ const base = "flex min-w-0 flex-col gap-2.5 border-r border-hairline px-4 py-3.5 text-left last:border-r-0";
+ if (!onClick) return <div className={base}>{body}</div>;
+ return (
+ <button
+ type="button"
+ title={`Show ${label.toLowerCase()}`}
+ onClick={onClick}
+ className={cn(base, "outline-none transition-colors duration-150 hover-fine:bg-hover/50 focus-visible:bg-hover")}
+ >
+ {body}
+ </button>
+ );
+}
+
+function RowMenu({ invoice, today }: { invoice: Invoice; today: string }) {
+ const invoices = useAppStore((s) => s.invoices);
+ const saveInvoice = useAppStore((s) => s.saveInvoice);
+ const setInvoiceStatus = useAppStore((s) => s.setInvoiceStatus);
+ const deleteInvoice = useAppStore((s) => s.deleteInvoice);
+ const view = useInvoiceUi((s) => s.view);
+ const edit = useInvoiceUi((s) => s.edit);
+
+ const mark = (status: InvoiceStatus) => {
+ setInvoiceStatus(invoice.id, status);
+ toast.success(status === "paid" ? "Marked as paid" : "Marked as sent", {
+ description: `${invoice.number} · ${invoice.client}`,
+ action: { label: "Undo", onClick: () => useAppStore.getState().setInvoiceStatus(invoice.id, invoice.status) },
+ });
+ };
+
+ const duplicate = () => {
+ const copy = saveInvoice({
+ ...invoice,
+ id: undefined,
+ number: nextInvoiceNumber(invoices, today),
+ status: "draft",
+ issueDate: today,
+ dueDate: addDays(today, 30),
+ items: invoice.items.map((i) => ({ ...i, id: uid("it") })),
+ });
+ toast.success("Invoice duplicated", {
+ description: `${copy.number} · draft`,
+ action: { label: "Edit", onClick: () => useInvoiceUi.getState().edit(copy.id) },
+ });
+ };
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon-sm" aria-label={`Actions for ${invoice.number}`}>
+ <Icon name="more" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-48">
+ <DropdownMenuItem onSelect={() => view(invoice.id)}>
+ <EyeIcon /> View
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => edit(invoice.id)}>
+ <PencilIcon /> Edit
+ </DropdownMenuItem>
+ {invoice.status === "draft" && (
+ <DropdownMenuItem onSelect={() => mark("sent")}>
+ <SendIcon /> Mark as sent
+ </DropdownMenuItem>
+ )}
+ {invoice.status !== "paid" && (
+ <DropdownMenuItem onSelect={() => mark("paid")}>
+ <CheckIcon /> Mark as paid
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem onSelect={duplicate}>
+ <CopyIcon /> Duplicate
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onSelect={() => deleteInvoice(invoice.id)}>
+ <Trash2Icon /> Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/src/components/pages/invoice/invoice-ui-store.ts b/src/components/pages/invoice/invoice-ui-store.ts
new file mode 100644
index 0000000..9103948
--- /dev/null
+++ b/src/components/pages/invoice/invoice-ui-store.ts
@@ -0,0 +1,22 @@
+"use client";
+
+import { create } from "zustand";
+
+/** Page-local UI state, shared with the ?open=<id> deep-link reader. */
+type InvoiceUi = {
+ viewId: string | null;
+ editor: { open: boolean; session: number; id?: string };
+ view: (id: string) => void;
+ closeView: () => void;
+ edit: (id?: string) => void;
+ closeEditor: () => void;
+};
+
+export const useInvoiceUi = create<InvoiceUi>()((set) => ({
+ viewId: null,
+ editor: { open: false, session: 0 },
+ view: (id) => set({ viewId: id }),
+ closeView: () => set({ viewId: null }),
+ edit: (id) => set((s) => ({ viewId: null, editor: { open: true, session: s.editor.session + 1, id } })),
+ closeEditor: () => set((s) => ({ editor: { ...s.editor, open: false } })),
+}));
diff --git a/src/components/pages/invoice/invoice-utils.ts b/src/components/pages/invoice/invoice-utils.ts
new file mode 100644
index 0000000..8352243
--- /dev/null
+++ b/src/components/pages/invoice/invoice-utils.ts
@@ -0,0 +1,156 @@
+import { formatLong } from "@/lib/dates";
+import type { Invoice, InvoiceItem, InvoiceStatus, Profile } from "@/lib/types";
+
+export const CURRENCIES = ["USD", "EUR", "GBP", "INR"] as const;
+
+const formatters = new Map<string, Intl.NumberFormat>();
+
+export function formatMoney(amount: number, currency: string): string {
+ let f = formatters.get(currency);
+ if (!f) {
+ f = new Intl.NumberFormat("en-US", { style: "currency", currency });
+ formatters.set(currency, f);
+ }
+ return f.format(amount);
+}
+
+export const lineTotal = (item: Pick<InvoiceItem, "quantity" | "rate">) =>
+ Math.round((Number(item.quantity) || 0) * (Number(item.rate) || 0) * 100) / 100;
+
+export const invoiceTotal = (inv: Pick<Invoice, "items">) =>
+ Math.round(inv.items.reduce((n, i) => n + lineTotal(i), 0) * 100) / 100;
+
+/** A sent invoice past its due date is shown as overdue even before the store says so. */
+export function effectiveStatus(inv: Invoice, today: string): InvoiceStatus {
+ return inv.status === "sent" && inv.dueDate < today ? "overdue" : inv.status;
+}
+
+/** Next number in the INV-YYYY-NNN sequence. */
+export function nextInvoiceNumber(invoices: Invoice[], today: string): string {
+ const year = today.slice(0, 4);
+ let max = 0;
+ for (const inv of invoices) {
+ const m = /^INV-(\d{4})-(\d+)$/.exec(inv.number);
+ if (m && m[1] === year) max = Math.max(max, Number(m[2]));
+ }
+ return `INV-${year}-${String(max + 1).padStart(3, "0")}`;
+}
+
+/** Sums amounts per currency: "$5,200.00 · €900.00". */
+export function formatTotals(list: Invoice[]): string {
+ const by = new Map<string, number>();
+ for (const inv of list) by.set(inv.currency, (by.get(inv.currency) ?? 0) + invoiceTotal(inv));
+ if (!by.size) return formatMoney(0, "USD");
+ return [...by.entries()].map(([c, n]) => formatMoney(n, c)).join(" · ");
+}
+
+const esc = (s: string) =>
+ s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]!);
+
+/** Standalone, print-ready HTML document for an invoice (used for Print and Download). */
+export function invoiceHtml(inv: Invoice, from: Profile): string {
+ const total = invoiceTotal(inv);
+ const rows = inv.items
+ .map(
+ (i) => `<tr>
+ <td>${esc(i.description)}</td>
+ <td class="num">${i.quantity}</td>
+ <td class="num">${formatMoney(i.rate, inv.currency)}</td>
+ <td class="num">${formatMoney(lineTotal(i), inv.currency)}</td>
+ </tr>`,
+ )
+ .join("");
+ return `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<title>${esc(inv.number)} · ${esc(inv.client)}</title>
+<style>
+ * { box-sizing: border-box; }
+ body { margin: 0; padding: 48px; font: 14px/1.45 -apple-system, BlinkMacSystemFont, "Geist", "Segoe UI", sans-serif; color: #1d1d1d; background: #fff; }
+ .doc { max-width: 760px; margin: 0 auto; }
+ header { display: flex; justify-content: space-between; align-items: flex-start; padding-bottom: 24px; border-bottom: 1px solid #e5e7e1; }
+ h1 { margin: 0 0 6px; font-size: 24px; font-weight: 600; letter-spacing: -0.02em; }
+ .muted { color: #757575; }
+ .grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 24px; padding: 24px 0; }
+ .label { font-size: 12px; color: #757575; margin-bottom: 6px; }
+ table { width: 100%; border-collapse: collapse; margin-top: 8px; }
+ th { text-align: left; font-size: 12px; font-weight: 500; color: #757575; padding: 10px 0; border-bottom: 1px solid #e5e7e1; }
+ td { padding: 12px 0; border-bottom: 1px solid #f2f2f2; }
+ .num { text-align: right; font-variant-numeric: tabular-nums; }
+ .totals { margin-left: auto; width: 260px; margin-top: 16px; }
+ .totals div { display: flex; justify-content: space-between; padding: 6px 0; }
+ .totals .grand { border-top: 1px solid #e5e7e1; margin-top: 6px; padding-top: 12px; font-size: 16px; font-weight: 600; }
+ .notes { margin-top: 32px; padding-top: 16px; border-top: 1px solid #e5e7e1; white-space: pre-wrap; }
+ @page { margin: 16mm; }
+ @media print { body { padding: 0; } }
+</style>
+</head>
+<body>
+<div class="doc">
+ <header>
+ <div>
+ <h1>Invoice</h1>
+ <div class="muted">${esc(inv.number)}</div>
+ </div>
+ <div style="text-align:right">
+ <div><strong>${esc(from.name)}</strong></div>
+ <div class="muted">${esc(from.email)}</div>
+ <div class="muted">${esc(from.address)}</div>
+ </div>
+ </header>
+ <section class="grid">
+ <div><div class="label">Bill to</div><strong>${esc(inv.client)}</strong></div>
+ <div><div class="label">Issued</div>${formatLong(inv.issueDate)}</div>
+ <div><div class="label">Due</div>${formatLong(inv.dueDate)}</div>
+ </section>
+ <table>
+ <thead><tr><th>Description</th><th class="num">Qty</th><th class="num">Rate</th><th class="num">Amount</th></tr></thead>
+ <tbody>${rows}</tbody>
+ </table>
+ <div class="totals">
+ <div><span class="muted">Subtotal</span><span class="num">${formatMoney(total, inv.currency)}</span></div>
+ <div class="grand"><span>Total due</span><span class="num">${formatMoney(total, inv.currency)}</span></div>
+ </div>
+ ${inv.notes.trim() ? `<div class="notes"><div class="label">Notes</div>${esc(inv.notes)}</div>` : ""}
+</div>
+</body>
+</html>`;
+}
+
+export function downloadInvoice(inv: Invoice, from: Profile) {
+ const blob = new Blob([invoiceHtml(inv, from)], { type: "text/html;charset=utf-8" });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `${inv.number}.html`;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+}
+
+/** Prints just the invoice document through a hidden iframe, so the app chrome stays out of the printout. */
+export function printInvoice(inv: Invoice, from: Profile) {
+ const frame = document.createElement("iframe");
+ frame.setAttribute("aria-hidden", "true");
+ frame.style.cssText = "position:fixed;right:0;bottom:0;width:0;height:0;border:0;visibility:hidden";
+ document.body.appendChild(frame);
+ const win = frame.contentWindow;
+ if (!win) {
+ frame.remove();
+ window.print();
+ return;
+ }
+ win.document.open();
+ win.document.write(invoiceHtml(inv, from));
+ win.document.close();
+ const cleanup = () => setTimeout(() => frame.remove(), 500);
+ win.addEventListener("afterprint", cleanup, { once: true });
+ // Let the iframe lay out before opening the print dialog.
+ setTimeout(() => {
+ win.focus();
+ win.print();
+ }, 50);
+ setTimeout(() => frame.remove(), 60_000);
+}
diff --git a/src/components/pages/invoice/invoice-view.tsx b/src/components/pages/invoice/invoice-view.tsx
new file mode 100644
index 0000000..9841868
--- /dev/null
+++ b/src/components/pages/invoice/invoice-view.tsx
@@ -0,0 +1,166 @@
+"use client";
+
+import { CheckIcon, DownloadIcon, PencilIcon, PrinterIcon, SendIcon } from "lucide-react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
+import { formatLong } from "@/lib/dates";
+import { useToday } from "@/hooks/use-today";
+import { useAppStore } from "@/stores/app-store";
+import { useInvoiceUi } from "./invoice-ui-store";
+import { downloadInvoice, effectiveStatus, formatMoney, invoiceTotal, lineTotal, printInvoice } from "./invoice-utils";
+import { InvoiceStatusBadge } from "./status-badge";
+
+export function InvoiceView() {
+ const viewId = useInvoiceUi((s) => s.viewId);
+ const closeView = useInvoiceUi((s) => s.closeView);
+ const edit = useInvoiceUi((s) => s.edit);
+ const invoice = useAppStore((s) => s.invoices.find((i) => i.id === viewId));
+ const profile = useAppStore((s) => s.profile);
+ const setInvoiceStatus = useAppStore((s) => s.setInvoiceStatus);
+ const today = useToday();
+
+ const open = !!viewId && !!invoice;
+ const status = invoice ? effectiveStatus(invoice, today) : "draft";
+ const total = invoice ? invoiceTotal(invoice) : 0;
+
+ return (
+ <Dialog open={open} onOpenChange={(v) => !v && closeView()}>
+ <DialogContent className="max-h-[calc(100dvh-48px)] grid-rows-[auto_minmax(0,1fr)] gap-0 overflow-hidden bg-app p-0 sm:max-w-[680px]">
+ {invoice && (
+ <>
+ <div className="flex items-center gap-2 border-b border-hairline bg-surface py-3 pr-12 pl-4">
+ <DialogTitle className="t-14 min-w-0 flex-1 truncate text-fg">{invoice.number}</DialogTitle>
+ <DialogDescription className="sr-only">Invoice for {invoice.client}</DialogDescription>
+ {invoice.status !== "paid" && (
+ <Button
+ size="sm"
+ className="px-2"
+ onClick={() => edit(invoice.id)}
+ >
+ <PencilIcon className="text-icon" /> Edit
+ </Button>
+ )}
+ <Button size="sm" className="px-2" onClick={() => printInvoice(invoice, profile)}>
+ <PrinterIcon className="text-icon" /> Print
+ </Button>
+ <Button
+ size="sm"
+ className="px-2"
+ onClick={() => {
+ downloadInvoice(invoice, profile);
+ toast.success("Invoice downloaded", { description: `${invoice.number}.html` });
+ }}
+ >
+ <DownloadIcon className="text-icon" /> Download
+ </Button>
+ {invoice.status === "draft" ? (
+ <Button
+ size="sm"
+ variant="brand"
+ className="px-2"
+ onClick={() => {
+ setInvoiceStatus(invoice.id, "sent");
+ toast.success("Invoice sent", { description: `${invoice.number} · ${invoice.client}` });
+ }}
+ >
+ <SendIcon /> Send
+ </Button>
+ ) : invoice.status !== "paid" ? (
+ <Button
+ size="sm"
+ variant="brand"
+ className="px-2"
+ onClick={() => {
+ setInvoiceStatus(invoice.id, "paid");
+ toast.success("Marked as paid", { description: `${invoice.number} · ${formatMoney(total, invoice.currency)}` });
+ }}
+ >
+ <CheckIcon /> Mark as paid
+ </Button>
+ ) : null}
+ </div>
+
+ <div className="overflow-y-auto scroll-thin p-4">
+ {/* The "paper": always reads like a printed document */}
+ <article className="flex flex-col gap-7 rounded-lg border border-hairline bg-surface p-8 shadow-[0_1px_2px_rgba(0,0,0,0.03)]">
+ <header className="flex items-start justify-between gap-6">
+ <div className="flex flex-col gap-2.5">
+ <h2 className="text-[24px] leading-none font-medium tracking-[-0.48px] text-heading">Invoice</h2>
+ <span className="t-14 text-fg-2">{invoice.number}</span>
+ <InvoiceStatusBadge status={status} className="mt-1 self-start" />
+ </div>
+ <div className="flex flex-col items-end gap-1.5 text-right">
+ <span className="t-14 text-fg">{profile.name}</span>
+ <span className="t-12 text-fg-2">{profile.email}</span>
+ <span className="t-12 max-w-[220px] leading-[1.35] text-fg-2">{profile.address}</span>
+ </div>
+ </header>
+
+ <dl className="grid grid-cols-3 gap-6 border-y border-hairline py-5">
+ <Meta label="Bill to" value={invoice.client} />
+ <Meta label="Issued" value={formatLong(invoice.issueDate)} />
+ <Meta
+ label="Due"
+ value={formatLong(invoice.dueDate)}
+ danger={status === "overdue"}
+ />
+ </dl>
+
+ <table className="w-full border-collapse">
+ <thead>
+ <tr className="border-b border-hairline">
+ <th className="t-12 pb-2.5 text-left font-medium text-fg-2">Description</th>
+ <th className="t-12 w-16 pb-2.5 text-right font-medium text-fg-2">Qty</th>
+ <th className="t-12 w-28 pb-2.5 text-right font-medium text-fg-2">Rate</th>
+ <th className="t-12 w-28 pb-2.5 text-right font-medium text-fg-2">Amount</th>
+ </tr>
+ </thead>
+ <tbody>
+ {invoice.items.map((i) => (
+ <tr key={i.id} className="border-b border-subtle">
+ <td className="t-14 py-3.5 pr-4 leading-[1.3] text-table">{i.description}</td>
+ <td className="t-14 py-3.5 text-right text-table tabular-nums">{i.quantity}</td>
+ <td className="t-14 py-3.5 text-right text-table tabular-nums">
+ {formatMoney(i.rate, invoice.currency)}
+ </td>
+ <td className="t-14 py-3.5 text-right text-table tabular-nums">
+ {formatMoney(lineTotal(i), invoice.currency)}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+
+ <dl className="ml-auto grid w-64 grid-cols-[1fr_auto] gap-x-4 gap-y-3">
+ <dt className="t-14 text-fg-2">Subtotal</dt>
+ <dd className="t-14 text-right text-table tabular-nums">{formatMoney(total, invoice.currency)}</dd>
+ <dt className="t-14 border-t border-hairline pt-3 text-fg">{status === "paid" ? "Total paid" : "Total due"}</dt>
+ <dd className="border-t border-hairline pt-3 text-right text-[20px] leading-none font-medium tracking-[-0.4px] text-fg tabular-nums">
+ {formatMoney(total, invoice.currency)}
+ </dd>
+ </dl>
+
+ {invoice.notes.trim() && (
+ <div className="flex flex-col gap-2 border-t border-hairline pt-5">
+ <span className="t-12 text-fg-2">Notes</span>
+ <p className="t-14 leading-[1.45] whitespace-pre-wrap text-table">{invoice.notes}</p>
+ </div>
+ )}
+ </article>
+ </div>
+ </>
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function Meta({ label, value, danger }: { label: string; value: string; danger?: boolean }) {
+ return (
+ <div className="flex flex-col gap-2">
+ <dt className="t-12 text-fg-2">{label}</dt>
+ <dd className={danger ? "t-14 text-danger" : "t-14 text-fg"}>{value}</dd>
+ </div>
+ );
+}
diff --git a/src/components/pages/invoice/status-badge.tsx b/src/components/pages/invoice/status-badge.tsx
new file mode 100644
index 0000000..b1b3817
--- /dev/null
+++ b/src/components/pages/invoice/status-badge.tsx
@@ -0,0 +1,35 @@
+import { AlertCircleIcon, Clock3Icon, PencilLineIcon } from "lucide-react";
+import { Icon } from "@/components/icon";
+import { cn } from "@/lib/utils";
+import type { InvoiceStatus } from "@/lib/types";
+
+const STYLES: Record<InvoiceStatus, { label: string; tone: string }> = {
+ draft: { label: "Draft", tone: "neutral" },
+ sent: { label: "Sent", tone: "warning" },
+ paid: { label: "Paid", tone: "success" },
+ overdue: { label: "Overdue", tone: "danger" },
+};
+
+export const STATUS_LABELS = Object.fromEntries(
+ Object.entries(STYLES).map(([k, v]) => [k, v.label]),
+) as Record<InvoiceStatus, string>;
+
+export function InvoiceStatusBadge({ status, className }: { status: InvoiceStatus; className?: string }) {
+ const { label, tone } = STYLES[status];
+ return (
+ <span
+ className={cn("inline-flex h-[22px] shrink-0 items-center gap-1 rounded-[6px] border pr-1.5 pl-1", className)}
+ style={{
+ background: `var(--status-${tone}-tint)`,
+ borderColor: `var(--status-${tone}-border)`,
+ color: `var(--status-${tone})`,
+ }}
+ >
+ {status === "paid" && <Icon name="status-approved" className="text-success" />}
+ {status === "sent" && <Clock3Icon className="size-3.5" strokeWidth={2.25} />}
+ {status === "overdue" && <AlertCircleIcon className="size-3.5" strokeWidth={2.25} />}
+ {status === "draft" && <PencilLineIcon className="size-3.5" strokeWidth={2.25} />}
+ <span className="salt text-[12px] leading-none tracking-[-0.24px] whitespace-nowrap">{label}</span>
+ </span>
+ );
+}