Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

61.5 KB
Raw Blame
import { useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate, useParams } from 'react-router-dom'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
  ArrowLeft, Ban, Check, CheckCircle2, CircleSlash, Copy, Download, FileText, Link2,
  MinusCircle, MoreHorizontal, Pencil, Repeat, RotateCcw, Send, Share2, Trash2, Unlink,
} from 'lucide-react'
import { toast } from 'sonner'

import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { PageHeader } from '@/components/page-header'
import { InvoiceSuggestions } from '@/components/invoice-suggestions'
import {
  IconAction,
  SectionCard,
  SectionHeader,
  Segmented,
  StateBadge,
} from '@/components/invoice-ui'
import { InvoiceDocumentView } from '@/components/invoice-document'
import { InvoiceDocumentBrowser } from '@/components/invoice-documents'
import { InvoiceLineEditor } from '@/components/invoice-line-editor'
import { InvoiceInstallmentsEditor } from '@/components/invoice-installments-editor'
import { DEDUCTION_KINDS, displayDue, installmentsTotal } from '@/lib/installment-utils'
import { EndConditionFields, SchedulePeriodChip } from '@/components/invoice-schedule-ui'
import { FREQUENCIES, endPayload } from '@/lib/invoice-schedule-utils'
import type {
  DeductionKind,
  InstallmentInput,
  Invoice,
  InvoiceDirection,
  InvoiceLineInput,
  InvoiceScheduleEndType,
  InvoiceScheduleFrequency,
} from '@/types'
import { cn } from '@/lib/utils'
import { formatCurrency } from '@/lib/format'
import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'
import { usePrivacyMode } from '@/hooks/use-privacy-mode'
import { useAuth } from '@/contexts/auth-context'
import { useWorkspace } from '@/contexts/workspace-context'
import {
  invoices as invoicesApi,
  payees as payeesApi,
  transactions as transactionsApi,
} from '@/lib/api'
import {
  allocationOrigin,
  availableActions,
  customFieldDefs,
  displayNumber,
  invoiceErrorKey,
  linesTotal,
} from '@/lib/invoice-utils'

/**
 * One invoice: what is owed, the money bound to it, and the document.
 *
 * The tab split is the point. "Details" is the operator's view — the
 * ledger side, where money gets linked. "Document" is what the client
 * receives, rendered from the same structure the PDF is. Mixing the two
 * on one screen is what made the first version feel like neither.
 */
type Tab = 'details' | 'document'

export default function InvoiceDetailPage() {
  const { t } = useTranslation()
  const { id = '' } = useParams()
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const locale = useDisplayLocale()
  const dateLocale = useDateLocale()
  const { mask } = usePrivacyMode()
  const { user } = useAuth()
  const { canWrite } = useWorkspace()
  const fallbackCurrency = user?.preferences?.currency_display ?? 'USD'

  const [linkOpen, setLinkOpen] = useState(false)
  const [editOpen, setEditOpen] = useState(false)
  const [recurringOpen, setRecurringOpen] = useState(false)
  const [deductionOpen, setDeductionOpen] = useState(false)
  const [tab, setTab] = useState<Tab>('details')
  const [copied, setCopied] = useState(false)

  const { data: invoice, isLoading } = useQuery({
    queryKey: ['invoice', id],
    queryFn: () => invoicesApi.get(id),
    enabled: Boolean(id),
  })
  const { data: settings } = useQuery({
    queryKey: ['invoice-settings'],
    queryFn: invoicesApi.settings,
  })
  // Only when the tab is open: it resolves the snapshot and builds the
  // whole page server-side, and the ledger view has no use for any of it.
  // Fetched here rather than only inside the Documents section: the
  // header has to know whether a real document exists before it offers
  // to download one. Same query key as the section, so this is one
  // request shared through the cache, not two.
  const { data: attachments = [] } = useQuery({
    queryKey: ['invoice-attachments', id],
    queryFn: () => invoicesApi.attachments.list(id!),
    enabled: Boolean(id),
  })
  const hasFiledDocument = attachments.some((a) => a.is_primary)

  const { data: documentPayload } = useQuery({
    queryKey: ['invoice-document', id],
    queryFn: () => invoicesApi.document(id),
    enabled: Boolean(id) && tab === 'document',
  })

  const refresh = () => {
    void queryClient.invalidateQueries({ queryKey: ['invoice', id] })
    void queryClient.invalidateQueries({ queryKey: ['invoice-document', id] })
    void queryClient.invalidateQueries({ queryKey: ['invoices'] })
    void queryClient.invalidateQueries({ queryKey: ['invoice-summary'] })
    void queryClient.invalidateQueries({ queryKey: ['invoice-facets'] })
    // An invoice of an agreement changes what the agreement reads:
    // issuing it moves "invoiced", a payment moves "received".
    void queryClient.invalidateQueries({ queryKey: ['invoice-schedule'] })
    void queryClient.invalidateQueries({ queryKey: ['invoice-schedule-invoices'] })
    void queryClient.invalidateQueries({ queryKey: ['invoice-schedules'] })
    void queryClient.invalidateQueries({ queryKey: ['invoice-schedule-summary'] })
  }

  const onError = (error: unknown) => {
    const key = invoiceErrorKey(error)
    toast.error(key ? t(key, t('invoices.errors.generic')) : t('invoices.errors.generic'))
  }

  const decision = (run: () => Promise<unknown>, successKey: string) => ({
    mutationFn: run,
    onSuccess: () => {
      toast.success(t(successKey))
      refresh()
    },
    onError,
  })

  const issueMutation = useMutation(decision(() => invoicesApi.issue(id), 'invoices.issued'))
  const voidMutation = useMutation(decision(() => invoicesApi.void(id), 'invoices.voided'))
  const writeOffMutation = useMutation(
    decision(() => invoicesApi.writeOff(id), 'invoices.writtenOff'),
  )
  const reopenMutation = useMutation(decision(() => invoicesApi.reopen(id), 'invoices.reopened'))
  const deleteMutation = useMutation({
    mutationFn: () => invoicesApi.remove(id),
    onSuccess: () => {
      toast.success(t('invoices.deleted'))
      refresh()
      navigate('/invoices')
    },
    onError,
  })
  const unlinkScheduleMutation = useMutation({
    mutationFn: () => invoicesApi.unlinkSchedule(id),
    onSuccess: () => {
      toast.success(t('invoices.schedules.unlinked'))
      refresh()
      void queryClient.invalidateQueries({ queryKey: ['invoice-schedules'] })
    },
    onError,
  })
  const undeductMutation = useMutation({
    mutationFn: (deductionId: string) => invoicesApi.undeduct(id, deductionId),
    onSuccess: () => {
      toast.success(t('invoices.deductions.removed'))
      refresh()
    },
    onError,
  })
  const unlinkMutation = useMutation({
    mutationFn: (allocationId: string) => invoicesApi.unallocate(id, allocationId),
    onSuccess: () => {
      toast.success(t('invoices.unlinked'))
      refresh()
    },
    onError,
  })

  // Fetched as a blob rather than opened as a link: the PDF route needs
  // the auth and workspace headers the axios interceptor adds, which a
  // plain anchor would not carry.
  const downloadMutation = useMutation({
    mutationFn: async () => {
      const blob = await invoicesApi.pdf(id)
      const url = URL.createObjectURL(blob)
      const anchor = window.document.createElement('a')
      anchor.href = url
      anchor.download = `${invoice?.number ?? 'invoice'}.pdf`
      anchor.click()
      URL.revokeObjectURL(url)
    },
    onError,
  })

  // The statement of account: what was paid and deducted since issue,
  // and how that arrives at the balance. The invoice PDF is the document
  // as issued and never shows it.
  const statementMutation = useMutation({
    mutationFn: async () => {
      const blob = await invoicesApi.statement(id)
      const url = URL.createObjectURL(blob)
      const anchor = window.document.createElement('a')
      anchor.href = url
      anchor.download = `${invoice?.number ?? 'invoice'}-statement.pdf`
      anchor.click()
      URL.revokeObjectURL(url)
    },
    onError,
  })

  const shareMutation = useMutation({
    mutationFn: () => invoicesApi.share(id),
    onSuccess: async (link) => {
      const url = `${window.location.origin}${link.path}`
      try {
        await navigator.clipboard.writeText(url)
        setCopied(true)
        setTimeout(() => setCopied(false), 2500)
        toast.success(t('invoices.shareCopied'))
      } catch {
        // A blocked clipboard is not a failed share — the link exists.
        toast.success(url)
      }
      refresh()
    },
    onError,
  })

  const unshareMutation = useMutation({
    mutationFn: () => invoicesApi.unshare(id),
    onSuccess: () => {
      toast.success(t('invoices.shareRevoked'))
      refresh()
    },
    onError,
  })

  if (isLoading || !invoice) {
    return (
      <div>
        <Skeleton className="h-4 w-28 mb-6" />
        <Skeleton className="h-40 w-full rounded-xl" />
      </div>
    )
  }

  const actions = availableActions(invoice)
  const currency = invoice.currency || fallbackCurrency
  const money = (value: string | number | null | undefined) =>
    mask(formatCurrency(Number(value ?? 0), currency, locale))
  const showDate = (iso: string) => new Date(`${iso}T00:00:00`).toLocaleDateString(dateLocale)
  const number = displayNumber(invoice, settings?.number_prefix)
  const customFields = customFieldDefs(settings?.template)
    .map((def) => ({ ...def, value: invoice.custom_fields?.[def.key] }))
    .filter((field): field is typeof field & { value: string } => Boolean(field.value))
  const shareUrl = invoice.share_token
    ? `${window.location.origin}/i/${invoice.share_token}`
    : null
  // "Repeat this": an issued receivable that is not already a period of
  // an agreement. A draft has nothing agreed yet, and a bill received is
  // the supplier's to repeat.
  const canRecur =
    invoice.direction === 'receivable' &&
    invoice.status !== 'draft' &&
    invoice.status !== 'void' &&
    !invoice.schedule_id
  // Only for what we issued: a draft was sent to nobody, and a bill we
  // received is the supplier's to state.
  const canStatement =
    invoice.direction === 'receivable' &&
    invoice.status !== 'draft' &&
    invoice.origin !== 'imported'
  const hasDeductions = Number(invoice.amount_deducted) > 0
  // Once money has moved, the invoice PDF (frozen at issue) no longer says
  // everything: what was paid and deducted since is on the statement, and
  // the page offers both instead of letting the first pass for the whole.
  const offerStatement = canStatement && (Number(invoice.amount_paid) > 0 || hasDeductions)

  return (
    <div>
      <button
        onClick={() => navigate('/invoices')}
        className="inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors mb-3"
      >
        <ArrowLeft className="h-3.5 w-3.5" />
        {t('invoices.backToList')}
      </button>

      <PageHeader
        section={
          invoice.payee?.name ??
          t(invoice.direction === 'payable' ? 'invoices.noSupplier' : 'invoices.noClient')
        }
        title={number ?? t('invoices.draftTitle')}
        action={
          canWrite ? (
            <div className="flex flex-wrap items-center gap-2">
              {actions.canEdit && (
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => setEditOpen(true)}
                  data-testid="invoice-edit"
                >
                  <Pencil className="h-4 w-4 mr-1.5" />
                  {t('common.edit')}
                </Button>
              )}
              {actions.canIssue && (
                <Button size="sm" onClick={() => issueMutation.mutate()} data-testid="invoice-issue">
                  <Send className="h-4 w-4 mr-1.5" />
                  {t('invoices.action.issue')}
                </Button>
              )}
              {actions.canAllocate && (
                <Button size="sm" onClick={() => setLinkOpen(true)} data-testid="invoice-link-payment">
                  <Link2 className="h-4 w-4 mr-1.5" />
                  {t('invoices.action.markPaid')}
                </Button>
              )}
              {invoice.status !== 'draft' && (
                <>
                  {/* Downloading an imported invoice with nothing filed
                      would hand over a page we drew for a document
                      somebody else issued — the same invention the
                      Document tab refuses to make. Nothing to download
                      until the real file arrives. */}
                  {offerStatement ? (
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button size="sm" variant="outline" data-testid="invoice-download-pdf">
                          <Download className="h-4 w-4 mr-1.5" />
                          {t('invoices.action.downloadPdf')}
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent
                        align="end"
                        className="w-[260px] p-1 bg-card border border-border rounded-xl shadow-md"
                      >
                        <DropdownMenuItem
                          onClick={() => downloadMutation.mutate()}
                          disabled={downloadMutation.isPending}
                          data-testid="invoice-download-issued"
                          className="flex-col items-start gap-0.5 text-sm"
                        >
                          <span>{t('invoices.statement.asIssued')}</span>
                          <span className="text-[11px] text-muted-foreground">{t('invoices.statement.asIssuedHint')}</span>
                        </DropdownMenuItem>
                        <DropdownMenuItem
                          onClick={() => statementMutation.mutate()}
                          disabled={statementMutation.isPending}
                          data-testid="invoice-download-statement"
                          className="flex-col items-start gap-0.5 text-sm"
                        >
                          <span>{t('invoices.statement.title')}</span>
                          <span className="text-[11px] text-muted-foreground">{t('invoices.statement.hint')}</span>
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  ) : (invoice.origin !== 'imported' || hasFiledDocument) && (
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => downloadMutation.mutate()}
                      disabled={downloadMutation.isPending}
                      data-testid="invoice-download-pdf"
                    >
                      <Download className="h-4 w-4 mr-1.5" />
                      {t('invoices.action.downloadPdf')}
                    </Button>
                  )}
                  {/* Sharing is for sending your invoice to your client.
                      A bill you received belongs to your supplier and has
                      nobody to be sent to. */}
                  {invoice.direction === 'receivable' && (
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() =>
                      invoice.share_token ? unshareMutation.mutate() : shareMutation.mutate()
                    }
                    data-testid={invoice.share_token ? 'invoice-unshare' : 'invoice-share'}
                  >
                    {copied ? (
                      <Check className="h-4 w-4 mr-1.5" />
                    ) : (
                      <Share2 className="h-4 w-4 mr-1.5" />
                    )}
                    {invoice.share_token
                      ? t('invoices.action.revokeLink')
                      : t('invoices.action.share')}
                  </Button>
                  )}
                </>
              )}
              {/* The rare and irreversible decisions live behind an
                  overflow menu, with words. Two bare icons side by side
                  were indistinguishable, and giving "void" the same
                  weight as "mark as paid" is how someone voids by
                  reflex. */}
              {(canRecur ||
                invoice.schedule_id ||
                actions.canWriteOff ||
                actions.canReopen ||
                actions.canVoid ||
                actions.canDelete) && (
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <button
                      type="button"
                      aria-label={t('invoices.moreActions')}
                      data-testid="invoice-more-actions"
                      className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-border/80 bg-card text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
                    >
                      <MoreHorizontal className="h-4 w-4" />
                    </button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent
                    align="end"
                    className="w-[220px] p-1 bg-card border border-border rounded-xl shadow-md"
                  >
                    {canRecur && (
                      <DropdownMenuItem
                        onClick={() => setRecurringOpen(true)}
                        data-testid="invoice-make-recurring"
                        className="gap-2 text-sm"
                      >
                        <Repeat className="h-4 w-4 text-muted-foreground" />
                        {t('invoices.schedules.action.makeRecurring')}
                      </DropdownMenuItem>
                    )}
                    {invoice.schedule_id && (
                      <DropdownMenuItem
                        onClick={() => unlinkScheduleMutation.mutate()}
                        data-testid="invoice-unlink-schedule"
                        className="gap-2 text-sm"
                      >
                        <Unlink className="h-4 w-4 text-muted-foreground" />
                        {t('invoices.schedules.action.unlink')}
                      </DropdownMenuItem>
                    )}
                    {actions.canWriteOff && (
                      <DropdownMenuItem
                        onClick={() => writeOffMutation.mutate()}
                        data-testid="invoice-writeoff"
                        className="gap-2 text-sm"
                      >
                        <Ban className="h-4 w-4 text-muted-foreground" />
                        {t('invoices.action.writeOff')}
                      </DropdownMenuItem>
                    )}
                    {actions.canReopen && (
                      <DropdownMenuItem
                        onClick={() => reopenMutation.mutate()}
                        data-testid="invoice-reopen"
                        className="gap-2 text-sm"
                      >
                        <RotateCcw className="h-4 w-4 text-muted-foreground" />
                        {t('invoices.action.reopen')}
                      </DropdownMenuItem>
                    )}
                    {actions.canVoid && (
                      <DropdownMenuItem
                        onClick={() => voidMutation.mutate()}
                        data-testid="invoice-void"
                        className="gap-2 text-sm text-destructive focus:text-destructive"
                      >
                        <CircleSlash className="h-4 w-4" />
                        {t('invoices.action.void')}
                      </DropdownMenuItem>
                    )}
                    {actions.canDelete && (
                      <DropdownMenuItem
                        onClick={() => deleteMutation.mutate()}
                        data-testid="invoice-delete"
                        className="gap-2 text-sm text-destructive focus:text-destructive"
                      >
                        <Trash2 className="h-4 w-4" />
                        {t('common.delete')}
                      </DropdownMenuItem>
                    )}
                  </DropdownMenuContent>
                </DropdownMenu>
              )}
            </div>
          ) : undefined
        }
      />

      <div className="flex flex-wrap items-center gap-x-4 gap-y-2 mb-5">
        <Segmented<Tab>
          value={tab}
          onChange={setTab}
          testIdPrefix="invoice-tab"
          options={[
            { value: 'details', label: t('invoices.tab.details') },
            { value: 'document', label: t('invoices.tab.document') },
          ]}
        />
        <StateBadge state={invoice.state} />
        {invoice.days_overdue > 0 && (
          <span className="text-xs font-medium text-rose-500">
            {t('invoices.daysLate', { count: invoice.days_overdue })}
          </span>
        )}
        <SchedulePeriodChip invoice={invoice} />
      </div>

      {tab === 'document' ? (
        <div className="space-y-4">
          {offerStatement && (
            <SectionCard>
              <div
                className="flex flex-wrap items-center gap-3 px-4 sm:px-5 py-3 text-sm"
                data-testid="invoice-statement-banner"
              >
                <FileText className="h-4 w-4 text-muted-foreground shrink-0" />
                <p className="flex-1 min-w-[16rem] text-muted-foreground">
                  {t('invoices.statement.banner', {
                    paid: money(invoice.amount_paid),
                    deducted: money(invoice.amount_deducted),
                  })}
                </p>
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => statementMutation.mutate()}
                  disabled={statementMutation.isPending}
                >
                  <Download className="h-4 w-4 mr-1.5" />
                  {t('invoices.action.downloadStatement')}
                </Button>
              </div>
            </SectionCard>
          )}
          {shareUrl && (
            <SectionCard>
              <div
                className="flex flex-wrap items-center gap-2 px-4 sm:px-5 py-3 text-xs"
                data-testid="invoice-share-banner"
              >
                <Share2 className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
                <span className="text-muted-foreground">{t('invoices.shareActive')}</span>
                <code className="truncate font-mono text-[11px] text-foreground">{shareUrl}</code>
                <div className="ml-auto">
                  <IconAction
                    onClick={() => {
                      void navigator.clipboard.writeText(shareUrl)
                      toast.success(t('invoices.shareCopied'))
                    }}
                    label={t('invoices.shareCopy')}
                  >
                    <Copy className="h-3.5 w-3.5" />
                  </IconAction>
                </div>
              </div>
            </SectionCard>
          )}
          {documentPayload ? (
            // Every page this invoice has, in one browser: the files down
            // the left, the selected one read on the right. Our own
            // render is one entry among them — and not offered at all on
            // an import, where drawing it would invent a document
            // somebody else issued.
            <InvoiceDocumentBrowser
              invoiceId={invoice.id}
              origin={invoice.origin}
              canWrite={canWrite}
              ourPageLabel={number}
              ourPageDate={invoice.issue_date}
              ourPage={<InvoiceDocumentView document={documentPayload} />}
              onChanged={refresh}
            />
          ) : (
            <Skeleton className="h-[520px] w-full rounded-xl" />
          )}
        </div>
      ) : (
        <div className="space-y-5">
          <SectionCard>
            {/* Total, then what reduced it, then what is left: read left
                to right it is the arithmetic. Deductions only when there
                are any, so an ordinary invoice keeps its four figures. */}
            <div
              className={cn(
                'grid grid-cols-2 divide-x divide-border',
                hasDeductions ? 'sm:grid-cols-5' : 'sm:grid-cols-4',
              )}
            >
              {[
                { label: t('invoices.column.total'), value: money(invoice.total) },
                {
                  label:
                    invoice.direction === 'payable'
                      ? t('invoices.field.paidOut')
                      : t('invoices.field.paid'),
                  value: money(invoice.amount_paid),
                },
                ...(hasDeductions
                  ? [{
                      label: t('invoices.deductions.figure'),
                      value: money(invoice.amount_deducted),
                      testId: 'invoice-deducted',
                    }]
                  : []),
                {
                  label: t('invoices.column.balance'),
                  value: money(invoice.balance),
                  tone:
                    Number(invoice.balance) > 0
                      ? 'text-foreground'
                      : 'text-emerald-600',
                  testId: 'invoice-balance',
                },
                {
                  label: invoice.installments.length ? t('invoices.installments.nextDue') : t('invoices.column.due'),
                  value: showDate(displayDue(invoice)),
                  testId: 'invoice-due-figure',
                },
              ].map((figure) => (
                <div key={figure.label} className="px-4 sm:px-5 py-4" data-testid={figure.testId}>
                  <p className="text-xs font-medium text-muted-foreground mb-0.5">{figure.label}</p>
                  <p
                    className={cn(
                      'text-lg font-bold tabular-nums',
                      figure.tone ?? 'text-foreground',
                    )}
                  >
                    {figure.value}
                  </p>
                </div>
              ))}
            </div>
          </SectionCard>

          {invoice.installments.length > 0 && (
            <SectionCard>
              <SectionHeader
                title={t('invoices.installments.schedule')}
                description={t('invoices.installments.count', { count: invoice.installments.length })}
              />
              <table className="w-full" data-testid="invoice-installments">
                <tbody>
                  {invoice.installments.map((row, index) => (
                    <tr key={row.id} className="border-b border-border last:border-0" data-testid="invoice-installment-row">
                      <td className="py-2.5 pl-4 sm:pl-5 text-sm">
                        {row.label ?? `${index + 1}/${invoice.installments.length}`}
                      </td>
                      <td className="py-2.5 text-xs text-muted-foreground tabular-nums">{showDate(row.due_date)}</td>
                      <td className="py-2.5 text-right text-sm tabular-nums">
                        {money(row.amount)}
                        {Number(row.settled) > 0 && Number(row.settled) < Number(row.amount) && (
                          <span className="ml-1.5 text-[11px] text-muted-foreground">
                            {t('invoices.field.paid').toLowerCase()} {money(row.settled)}
                          </span>
                        )}
                      </td>
                      <td className="py-2.5 pr-4 sm:pr-5 text-right w-28">
                        <span
                          data-testid={`installment-state-${row.state}`}
                          className={cn(
                            'text-[11px] font-semibold px-2 py-0.5 rounded-full border whitespace-nowrap',
                            row.state === 'paid' && 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/20',
                            row.state === 'overdue' && 'bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-500/10 dark:text-rose-400 dark:border-rose-500/20',
                            row.state === 'partial' && 'bg-amber-50 text-amber-700 border-amber-100 dark:bg-amber-500/10 dark:text-amber-400 dark:border-amber-500/20',
                            !['paid', 'overdue', 'partial'].includes(row.state) && 'bg-muted text-muted-foreground border-border',
                          )}
                        >
                          {t(`invoices.installments.state.${row.state}`)}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </SectionCard>
          )}

          {(invoice.lines.length > 0 || invoice.notes || customFields.length > 0) && (
            <SectionCard>
              <SectionHeader title={t('invoices.detailsTitle')} />
              <div className="px-4 sm:px-5 py-4 space-y-4">
                {/* Competence only earns a row when it disagrees with the
                    issue date; otherwise it is noise on every invoice. */}
                {invoice.competence_date && invoice.competence_date !== invoice.issue_date && (
                  <p className="text-xs text-muted-foreground" data-testid="invoice-competence">
                    {t('invoices.competenceDiverges', {
                      competence: showDate(invoice.competence_date),
                      issue: showDate(invoice.issue_date),
                    })}
                  </p>
                )}

                {/* Driven by the workspace's definitions, so the label
                    the sender chose is what shows — never the raw key —
                    and a field removed from settings stops appearing. */}
                {customFields.length > 0 && (
                  <div className="flex flex-wrap gap-x-8 gap-y-2">
                    {customFields.map((field) => (
                      <div key={field.key}>
                        <p className="text-xs font-medium text-muted-foreground mb-0.5">
                          {field.label}
                        </p>
                        <p className="text-sm">{field.value}</p>
                      </div>
                    ))}
                  </div>
                )}

                {invoice.lines.length > 0 && (
                  <table className="w-full">
                    <tbody>
                      {invoice.lines.map((line) => (
                        <tr key={line.id} className="border-b border-border last:border-0">
                          <td className="py-2.5 text-sm text-foreground">{line.description}</td>
                          <td className="py-2.5 text-right text-xs text-muted-foreground tabular-nums">
                            {Number(line.quantity)} × {money(line.unit_price)}
                          </td>
                          <td className="py-2.5 text-right text-sm font-medium tabular-nums w-32">
                            {money(line.total)}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                )}

                {invoice.notes && (
                  <p className="text-sm text-muted-foreground">{invoice.notes}</p>
                )}
              </div>
            </SectionCard>
          )}

          {/* Above the payments, because it is a question about them and
              because an answer here changes the list below. Renders
              nothing when nothing is waiting. */}
          <InvoiceSuggestions invoiceId={invoice.id} canWrite={canWrite} />

          <SectionCard>
            <SectionHeader
              title={t('invoices.payments')}
              action={
                actions.canAllocate && canWrite ? (
                  <div className="flex items-center gap-2">
                    {/* The other way a debt closes: without money. Quieter
                        than the payment button, because it is the exception. */}
                    <Button size="sm" variant="ghost" onClick={() => setDeductionOpen(true)} data-testid="invoice-record-deduction">
                      <MinusCircle className="h-3.5 w-3.5 mr-1.5" />
                      {t('invoices.deductions.action')}
                    </Button>
                    <Button size="sm" variant="outline" onClick={() => setLinkOpen(true)}>
                      <Link2 className="h-3.5 w-3.5 mr-1.5" />
                      {t('invoices.action.link')}
                    </Button>
                  </div>
                ) : undefined
              }
            />
            {invoice.deductions.length > 0 && (
              <table className="w-full border-b border-border" data-testid="invoice-deductions">
                <tbody>
                  {invoice.deductions.map((deduction) => (
                    <tr key={deduction.id} data-testid="invoice-deduction" className="border-b border-border last:border-0 bg-muted/20">
                      <td className="py-3 pl-4 sm:pl-5">
                        <div className="text-sm font-medium text-foreground truncate">
                          {t(`invoices.deductions.kind.${deduction.kind}`)}
                          {deduction.tax_kind && (
                            <span className="ml-1.5 text-xs uppercase text-muted-foreground">{deduction.tax_kind}</span>
                          )}
                        </div>
                        <div className="text-xs text-muted-foreground truncate">
                          {t('invoices.deductions.settledWithout')}
                          {deduction.note ? ` · ${deduction.note}` : ''}
                        </div>
                      </td>
                      <td className="py-3 text-right text-sm font-bold tabular-nums text-muted-foreground">
                        {money(deduction.amount)}
                      </td>
                      <td className="py-3 pr-4 sm:pr-5 text-right w-16">
                        {canWrite && invoice.status === 'open' && (
                          <IconAction
                            onClick={() => undeductMutation.mutate(deduction.id)}
                            label={t('common.delete')}
                            destructive
                          >
                            <Trash2 className="h-4 w-4" />
                          </IconAction>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
            {invoice.allocations.length === 0 ? (
              <p
                className="px-4 sm:px-5 py-8 text-center text-sm text-muted-foreground"
                data-testid="invoice-no-payments"
              >
                {t('invoices.noPayments')}
              </p>
            ) : (
              <table className="w-full">
                <tbody>
                  {invoice.allocations.map((allocation) => (
                    <tr
                      key={allocation.id}
                      data-testid="invoice-allocation"
                      className="border-b border-border last:border-0"
                    >
                      <td className="py-3 pl-4 sm:pl-5">
                        <div className="text-sm font-medium text-foreground truncate">
                          {allocation.transaction?.description ?? t('invoices.linkedPayment')}
                        </div>
                        <div className="text-xs text-muted-foreground tabular-nums mt-0.5">
                          {allocation.transaction?.date
                            ? showDate(allocation.transaction.date)
                            : ''}
                          {' · '}
                          {(() => {
                            const origin = allocationOrigin(allocation.method)
                            if (!origin.automatic) return t('invoices.linkedManually')
                            // The strategy id is shown as the title rather
                            // than the label: it is a machine name today
                            // and becomes a readable one when the policy
                            // is fetchable, without this line changing.
                            return (
                              <span title={origin.strategyId ?? undefined}>
                                {t('invoices.linkedAutomatically')}
                              </span>
                            )
                          })()}
                        </div>
                      </td>
                      <td className="py-3 text-right text-sm font-bold tabular-nums text-emerald-600">
                        {money(allocation.amount)}
                      </td>
                      <td className="py-3 pr-4 sm:pr-5 text-right w-16">
                        {canWrite && (
                          <IconAction
                            onClick={() => unlinkMutation.mutate(allocation.id)}
                            label={t('invoices.action.unlink')}
                            destructive
                          >
                            <Unlink className="h-4 w-4" />
                          </IconAction>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </SectionCard>
        </div>
      )}

      <EditDraftDialog
        open={editOpen}
        onOpenChange={setEditOpen}
        invoice={invoice}
        showTax={(settings?.tax_fields ?? 'hidden') !== 'hidden'}
        currency={currency}
        onSaved={refresh}
      />

      <MakeRecurringDialog

        key={recurringOpen ? 'recurring-open' : 'recurring-closed'}

        open={recurringOpen}

        onOpenChange={setRecurringOpen}

        invoice={invoice}

        onCreated={(scheduleId) => {

          refresh()

          navigate(`/invoices/schedules/${scheduleId}`)

        }}

      />

      <LinkPaymentDialog
        open={linkOpen}
        onOpenChange={setLinkOpen}
        invoiceId={id}
        direction={invoice.direction}
        balance={invoice.balance}
        // With a schedule, a short payment is short of the installment
        // being paid, not of the whole invoice.
        settleTarget={(() => {
          const next = invoice.installments.find((row) => Number(row.settled) < Number(row.amount))
          return next ? (Number(next.amount) - Number(next.settled)).toFixed(2) : invoice.balance
        })()}
        currency={currency}
        onLinked={refresh}
      />
      <RecordDeductionDialog
        key={deductionOpen ? 'deduction-open' : 'deduction-closed'}
        open={deductionOpen}
        onOpenChange={setDeductionOpen}
        invoiceId={id}
        balance={invoice.balance}
        currency={currency}
        onRecorded={refresh}
      />
    </div>
  )
}

/**
 * Closing part of the debt without money. The exception to the payment
 * flow, kept as its own small dialog: a reason, an amount defaulting to
 * whatever is left, and a note the accountant will thank you for.
 */
function RecordDeductionDialog({
  open,
  onOpenChange,
  invoiceId,
  balance,
  currency,
  onRecorded,
  initialAmount,
  transactionId,
}: {
  open: boolean
  onOpenChange: (open: boolean) => void
  invoiceId: string
  balance: string
  currency: string
  onRecorded: () => void
  initialAmount?: string
  transactionId?: string | null
}) {
  const { t } = useTranslation()
  const locale = useDisplayLocale()
  const [kind, setKind] = useState<DeductionKind>('withholding_tax')
  const [amount, setAmount] = useState(initialAmount ?? balance)
  const [taxKind, setTaxKind] = useState('')
  const [note, setNote] = useState('')
  const mutation = useMutation({
    mutationFn: () =>
      invoicesApi.deduct(invoiceId, {
        kind,
        amount,
        tax_kind: kind === 'withholding_tax' ? taxKind || null : null,
        note: note || null,
        transaction_id: transactionId ?? null,
      }),
    onSuccess: () => {
      toast.success(t('invoices.deductions.recorded'))
      onOpenChange(false)
      onRecorded()
    },
    onError: (error) => {
      const key = invoiceErrorKey(error)
      toast.error(key ? t(key, t('invoices.errors.generic')) : t('invoices.errors.generic'))
    },
  })
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>{t('invoices.deductions.title')}</DialogTitle>
          <DialogDescription>{t('invoices.deductions.description')}</DialogDescription>
        </DialogHeader>
        <div className="space-y-4">
          <div className="space-y-1.5">
            <Label>{t('invoices.deductions.kindLabel')}</Label>
            <Select value={kind} onValueChange={(v) => setKind(v as DeductionKind)}>
              <SelectTrigger data-testid="deduction-kind"><SelectValue /></SelectTrigger>
              <SelectContent>
                {DEDUCTION_KINDS.map((k) => (
                  <SelectItem key={k} value={k}>{t(`invoices.deductions.kind.${k}`)}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1.5">
              <Label htmlFor="deduction-amount">{t('invoices.deductions.amount')}</Label>
              <Input id="deduction-amount" data-testid="deduction-amount" inputMode="decimal" value={amount} onChange={(e) => setAmount(e.target.value)} />
              <p className="text-[11px] text-muted-foreground">
                {t('invoices.deductions.amountHint', { balance: formatCurrency(Number(balance), currency, locale) })}
              </p>
            </div>
            {kind === 'withholding_tax' && (
              <div className="space-y-1.5">
                <Label htmlFor="deduction-tax-kind">{t('invoices.deductions.taxKind')}</Label>
                <Input id="deduction-tax-kind" data-testid="deduction-tax-kind" value={taxKind} onChange={(e) => setTaxKind(e.target.value)} placeholder={t('invoices.deductions.taxKindPlaceholder')} maxLength={30} />
              </div>
            )}
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="deduction-note">{t('invoices.deductions.note')}</Label>
            <Input id="deduction-note" data-testid="deduction-note" value={note} onChange={(e) => setNote(e.target.value)} maxLength={500} />
          </div>
        </div>
        <DialogFooter className="gap-2">
          <Button variant="ghost" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>
          <Button onClick={() => mutation.mutate()} disabled={!(Number(amount) > 0) || mutation.isPending} data-testid="deduction-submit">
            {t('invoices.deductions.action')}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}

export function LinkPaymentDialog({
  open,
  onOpenChange,
  invoiceId,
  direction,
  balance,
  settleTarget,
  currency,
  onLinked,
}: {
  open: boolean
  onOpenChange: (open: boolean) => void
  invoiceId: string
  direction: InvoiceDirection
  balance: string
  /** What this payment is expected to cover: the next installment's
   *  remainder, or the balance. The "short by" reading uses it. */
  settleTarget?: string
  currency: string
  onLinked: () => void
}) {
  const { t } = useTranslation()
  const locale = useDisplayLocale()
  const [selected, setSelected] = useState<string>('')
  const [amount, setAmount] = useState('')
  // When the payment is short of the balance: what the difference is,
  // or nothing. Answered once, here, instead of leaving the invoice
  // partial and sending the person to find another button.
  const [differenceKind, setDifferenceKind] = useState<DeductionKind | 'none'>('none')

  // Money moving the way this invoice is settled: a receivable by money
  // coming in, a payable by money going out. Asking for credits either
  // way — which this did — means the payment that actually settled a
  // supplier's bill is never in the list, and the bill stays open
  // forever with no way to close it.
  const settlingType = direction === 'payable' ? 'debit' : 'credit'
  const { data } = useQuery({
    queryKey: ['transactions', 'for-invoice', settlingType],
    queryFn: () => transactionsApi.list({ type: settlingType, limit: 50 }),
    enabled: open,
  })

  // Same currency only — the server refuses a cross-currency allocation
  // rather than inventing a rate, so offering one here would only be
  // offering an error.
  //
  // And only money with something left to give: a payment already linked
  // to this invoice, or spent in full on others, was offered here too, and
  // picking it could only fail.
  const candidates = useMemo(
    () =>
      (data?.items ?? []).filter((tx) => {
        if ((tx.currency ?? currency) !== currency) return false
        const links = tx.invoice_links ?? []
        if (links.some((link) => link.invoice_id === invoiceId)) return false
        const used = links.reduce((sum, link) => sum + Number(link.amount), 0)
        return Math.abs(Number(tx.amount)) - used > 0.005
      }),
    [data, currency, invoiceId],
  )

  const selectedTx = candidates.find((tx) => tx.id === selected)
  const target = Number(settleTarget ?? balance)
  const applied = amount ? Number(amount) : Math.min(Number(balance), Math.abs(Number(selectedTx?.amount ?? 0)))
  const difference = selectedTx ? Math.round((target - applied) * 100) / 100 : 0

  // Linking and deducting are two requests. Once the first has landed
  // the invoice is already different, so if the second fails the dialog
  // still closes and refreshes: left open, "try again" would link the
  // same payment a second time.
  const linked = useRef(false)
  const close = () => {
    onOpenChange(false)
    setSelected('')
    setAmount('')
    setDifferenceKind('none')
    onLinked()
  }
  const mutation = useMutation({
    mutationFn: async () => {
      linked.current = false
      const after = await invoicesApi.allocate(invoiceId, selected, amount || undefined)
      linked.current = true
      if (differenceKind !== 'none' && difference > 0) {
        await invoicesApi.deduct(invoiceId, {
          kind: differenceKind,
          amount: difference.toFixed(2),
          transaction_id: selected,
        })
      }
      return after
    },
    onSuccess: () => {
      toast.success(t('invoices.linked'))
      close()
    },
    onError: (error) => {
      const key = invoiceErrorKey(error)
      toast.error(key ? t(key, t('invoices.errors.generic')) : t('invoices.errors.generic'))
      if (linked.current) {
        toast.success(t('invoices.linked'))
        close()
      }
    },
  })

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>{t('invoices.action.markPaid')}</DialogTitle>
          <DialogDescription>{t('invoices.linkDescription')}</DialogDescription>
        </DialogHeader>

        <div className="space-y-3 max-h-72 overflow-y-auto">
          {candidates.length === 0 && (
            <p className="text-sm text-muted-foreground">{t('invoices.noCandidates')}</p>
          )}
          {candidates.map((tx) => (
            <button
              key={tx.id}
              onClick={() => setSelected(tx.id)}
              data-testid="invoice-candidate"
              className={cn(
                'w-full flex items-center justify-between gap-3 rounded-lg border px-3 py-2 text-left transition-colors',
                selected === tx.id ? 'border-primary bg-primary/5' : 'hover:bg-muted/40',
              )}
            >
              <div className="min-w-0">
                <div className="text-sm truncate">{tx.description}</div>
                <div className="text-xs text-muted-foreground tabular-nums">{tx.date}</div>
              </div>
              <div className="flex items-center gap-2 shrink-0">
                <span className="text-sm tabular-nums">
                  {formatCurrency(Number(tx.amount), tx.currency ?? currency, 'en')}
                </span>
                {selected === tx.id && <CheckCircle2 className="h-4 w-4 text-primary" />}
              </div>
            </button>
          ))}
        </div>

        <div className="space-y-1.5">
          <Label htmlFor="allocation-amount">{t('invoices.field.amountToApply')}</Label>
          <Input
            id="allocation-amount"
            data-testid="invoice-allocation-amount"
            inputMode="decimal"
            value={amount}
            onChange={(e) => setAmount(e.target.value)}
            placeholder={balance}
          />
          {/* Leaving it blank is the common case — one payment closing one
              invoice should not require typing the number twice. */}
          <p className="text-[11px] text-muted-foreground">{t('invoices.field.amountHint')}</p>
        </div>

        {selectedTx && difference > 0 && (
          <div className="rounded-lg border border-border bg-muted/30 px-3 py-2.5 space-y-2" data-testid="invoice-difference">
            <p className="text-sm font-medium">
              {t('invoices.deductions.differenceTitle', { difference: formatCurrency(difference, currency, locale) })}
            </p>
            <p className="text-[11px] text-muted-foreground">{t('invoices.deductions.differenceHint')}</p>
            <Select value={differenceKind} onValueChange={(v) => setDifferenceKind(v as DeductionKind | 'none')}>
              <SelectTrigger data-testid="invoice-difference-kind"><SelectValue /></SelectTrigger>
              <SelectContent>
                <SelectItem value="none">{t('invoices.deductions.differenceNone')}</SelectItem>
                {DEDUCTION_KINDS.map((k) => (
                  <SelectItem key={k} value={k}>{t(`invoices.deductions.kind.${k}`)}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        )}

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            {t('common.cancel')}
          </Button>
          <Button
            onClick={() => mutation.mutate()}
            disabled={!selected || mutation.isPending}
            data-testid="invoice-allocation-submit"
          >
            {t('invoices.action.link')}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}

/**
 * Editing a draft.
 *
 * Only a draft: once issued, the financial substance is frozen and the
 * server refuses the change, because a document that changes after the
 * client received it is not an edit, it is a second document. The button
 * that opens this disappears at the same moment.
 *
 * Notes stay editable after issuance through the detail view, since they
 * are the seller's own record and never left the building.
 */
function EditDraftDialog({
  open,
  onOpenChange,
  invoice,
  showTax,
  currency,
  onSaved,
}: {
  open: boolean
  onOpenChange: (open: boolean) => void
  invoice: Invoice
  showTax: boolean
  currency: string
  onSaved: () => void
}) {
  const { t } = useTranslation()
  const { data: clients = [] } = useQuery({
    queryKey: ['payees', 'for-invoice'],
    queryFn: () => payeesApi.list({}),
    enabled: open,
  })

  // Seeded from the invoice each time the dialog opens, keyed so a
  // reopen after a save starts from what was saved.
  const [payeeId, setPayeeId] = useState(invoice.payee_id ?? '')
  const [total, setTotal] = useState(invoice.total)
  const [dueDate, setDueDate] = useState(invoice.due_date)
  const [notes, setNotes] = useState(invoice.notes ?? '')
  const [installments, setInstallments] = useState<InstallmentInput[] | null>(() =>
    invoice.installments.length
      ? invoice.installments.map((row) => ({ due_date: row.due_date, amount: row.amount, label: row.label }))
      : null,
  )
  const [lines, setLines] = useState<InvoiceLineInput[]>(() =>
    invoice.lines.map((line) => ({
      description: line.description,
      quantity: String(Number(line.quantity)),
      unit_price: line.unit_price,
      tax_rate: line.tax_rate,
    })),
  )

  const mutation = useMutation({
    mutationFn: () =>
      invoicesApi.update(invoice.id, {
        payee_id: payeeId || null,
        due_date: dueDate,
        notes: notes || null,
        // Always sent: the server takes an omitted key as "leave the
        // schedule alone" and an empty list as "clear it".
        installments: installments ?? [],
        // Lines are the source of truth once they exist: the server
        // recomputes the total from them and ignores what was typed.
        //
        // An empty list is sent when the draft had lines and no longer
        // does, because omitting the key means "leave them alone" — so
        // deleting every row used to save successfully and change
        // nothing, and the rows came back on the next read.
        ...(lines.length
          ? { lines }
          : invoice.lines.length
            ? { lines: [], total }
            : { total }),
      }),
    onSuccess: () => {
      toast.success(t('invoices.updated'))
      onOpenChange(false)
      onSaved()
    },
    onError: (error) => {
      const key = invoiceErrorKey(error)
      toast.error(key ? t(key, t('invoices.errors.generic')) : t('invoices.errors.generic'))
    },
  })

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      {/* Same rule as the create dialog: the line-item table needs the
          room, and without it the row overflows and the remove button
          falls off the right edge. */}
      <DialogContent
        className={cn(
          'flex flex-col max-h-[calc(100dvh-2rem)]',
          lines.length ? 'sm:max-w-3xl' : 'sm:max-w-lg',
        )}
      >
        <DialogHeader>
          <DialogTitle>{t('invoices.editDraft')}</DialogTitle>
          <DialogDescription>{t('invoices.editDraftDescription')}</DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div className="space-y-1.5">
            <Label>{t('invoices.field.client')}</Label>
            <Select value={payeeId} onValueChange={setPayeeId}>
              <SelectTrigger data-testid="edit-client-select">
                <SelectValue placeholder={t('invoices.field.clientPlaceholder')} />
              </SelectTrigger>
              <SelectContent>
                {clients.map((client) => (
                  <SelectItem key={client.id} value={client.id}>
                    {client.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1.5">
              <Label htmlFor="edit-total">{t('invoices.field.total')}</Label>
              <Input
                id="edit-total"
                data-testid="edit-total-input"
                inputMode="decimal"
                value={lines.length ? linesTotal(lines).toFixed(2) : total}
                onChange={(e) => setTotal(e.target.value)}
                disabled={lines.length > 0}
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="edit-due">{t('invoices.field.dueDate')}</Label>
              <Input
                id="edit-due"
                data-testid="edit-due-input"
                type="date"
                value={installments ? installments[installments.length - 1]?.due_date ?? '' : dueDate}
                onChange={(e) => setDueDate(e.target.value)}
                disabled={installments !== null}
              />
            </div>
          </div>

          <InvoiceLineEditor
            lines={lines}
            onChange={setLines}
            currency={currency}
            showTax={showTax}
          />

          <InvoiceInstallmentsEditor
            value={installments}
            onChange={setInstallments}
            total={lines.length ? linesTotal(lines) : Number(total || 0)}
            currency={currency}
            firstDueDate={dueDate}
            minDate={invoice.issue_date}
          />

          <div className="space-y-1.5">
            <Label htmlFor="edit-notes">{t('invoices.field.notes')}</Label>
            <Input
              id="edit-notes"
              data-testid="edit-notes-input"
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
            />
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            {t('common.cancel')}
          </Button>
          <Button
            onClick={() => mutation.mutate()}
            disabled={mutation.isPending || (installments !== null && Math.abs(installmentsTotal(installments) - (lines.length ? linesTotal(lines) : Number(total || 0))) >= 0.005)}
            data-testid="edit-submit"
          >
            {t('common.save')}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}

function MakeRecurringDialog({
  open,
  onOpenChange,
  invoice,
  onCreated,
}: {
  open: boolean
  onOpenChange: (open: boolean) => void
  invoice: Invoice
  onCreated: (scheduleId: string) => void
}) {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const dateLocale = useDateLocale()
  const [name, setName] = useState(invoice.lines[0]?.description ?? invoice.payee?.name ?? '')
  const [frequency, setFrequency] = useState<InvoiceScheduleFrequency>('monthly')
  // The invoice's own date by default. Earlier makes this invoice a
  // later period, so the ones billed by hand before it can be linked.
  const [startDate, setStartDate] = useState(invoice.issue_date)
  const [endType, setEndType] = useState<InvoiceScheduleEndType>('never')
  const [endDate, setEndDate] = useState('')
  const [endCount, setEndCount] = useState('')

  const mutation = useMutation({
    mutationFn: () =>
      invoicesApi.makeRecurring(invoice.id, {
        frequency,
        name: name.trim() || undefined,
        start_date: startDate,
        ...endPayload(endType, endDate, endCount),
      }),
    onSuccess: (schedule) => {
      toast.success(t('invoices.schedules.created'))
      void queryClient.invalidateQueries({ queryKey: ['invoice-schedules'] })
      void queryClient.invalidateQueries({ queryKey: ['invoice-schedule-summary'] })
      onOpenChange(false)
      onCreated(schedule.id)
    },
    onError: (error) => {
      const key = invoiceErrorKey(error)
      toast.error(key ? t(key, t('invoices.errors.generic')) : t('invoices.errors.generic'))
    },
  })

  const ready =
    name.trim().length > 0 &&
    Boolean(startDate) &&
    (endType !== 'on_date' || Boolean(endDate)) &&
    (endType !== 'after_count' || Number(endCount) >= 1)

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>{t('invoices.schedules.action.makeRecurring')}</DialogTitle>
          <DialogDescription>
            {t('invoices.schedules.makeRecurringDescription', {
              date: new Date(`${invoice.issue_date}T00:00:00`).toLocaleDateString(dateLocale),
            })}
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4">
          <div className="space-y-1.5">
            <Label htmlFor="recurring-name">{t('invoices.schedules.field.name')}</Label>
            <Input
              id="recurring-name"
              data-testid="recurring-name-input"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder={t('invoices.schedules.field.namePlaceholder')}
            />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1.5">
              <Label>{t('invoices.schedules.field.frequency')}</Label>
              <Select value={frequency} onValueChange={(v) => setFrequency(v as InvoiceScheduleFrequency)}>
                <SelectTrigger data-testid="recurring-frequency-select">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {FREQUENCIES.map((value) => (
                    <SelectItem key={value} value={value}>
                      {t(`invoices.schedules.frequency.${value}`)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="recurring-start">{t('invoices.schedules.field.startDate')}</Label>
              <Input
                id="recurring-start"
                data-testid="recurring-start-input"
                type="date"
                max={invoice.issue_date}
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
              />
              <p className="text-[11px] text-muted-foreground">{t('invoices.schedules.field.startDateHint')}</p>
            </div>
          </div>
          <EndConditionFields
            idPrefix="recurring"
            endType={endType}
            endDate={endDate}
            endCount={endCount}
            onChange={(next) => {
              setEndType(next.endType)
              setEndDate(next.endDate)
              setEndCount(next.endCount)
            }}
          />
        </div>
        <DialogFooter className="gap-2">
          <Button variant="ghost" onClick={() => onOpenChange(false)}>
            {t('common.cancel')}
          </Button>
          <Button onClick={() => mutation.mutate()} disabled={!ready || mutation.isPending} data-testid="recurring-submit">
            <Repeat className="h-4 w-4 mr-1.5" />
            {t('invoices.schedules.action.makeRecurring')}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}