feat(inbox): make custom-domain dialog ship-ready while gate stays off (#1377)

* feat(inbox): make custom-domain dialog ship-ready while gate stays off

Polish the gated custom inbox-domain dialog from issue #814: full sv/en
i18n via next-intl, admin/owner role gating on manage actions, explicit
load-error state with retry, resilient clipboard copy with failure toast,
and locale-aware verified-date formatting.

The INBOX_CUSTOM_DOMAINS_ENABLED gate (product decision 2026-07-02) stays
in place: routes still return 403 FEATURE_DISABLED when off and the
workspace entry point remains removed. Enabling is a deliberate release
decision.

Refs #814

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(inbox): narrow useFormat locale to ErrorLocale for error messages

The zero-extensions build failed type check: useFormat() returns a plain
string locale while getErrorMessage expects ErrorLocale. Use the
established repo idiom (cast once, reuse) as in DimensionsManager and
AgentSkillsPanel, and point the useCallback deps at the derived value.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-08-03 18:01:15 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent cd7d7f52b9
commit c1888fcd5e
4 changed files with 235 additions and 98 deletions
@@ -1,6 +1,7 @@
'use client'
import { useState, useCallback, useEffect } from 'react'
import { useTranslations } from 'next-intl'
import {
Dialog,
DialogContent,
@@ -14,19 +15,21 @@ import { Input } from '@/components/ui/input'
import { Skeleton } from '@/components/ui/skeleton'
import { useToast } from '@/components/ui/use-toast'
import { AlertTriangle, Check, Copy, Loader2, RefreshCw, Trash2 } from 'lucide-react'
import { formatDateLong } from '@/lib/utils'
import type { CompanyInboundDomain, InboundDomainDnsRecord } from '@/types'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { getErrorMessage as getUserErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
import { useFormat } from '@/lib/hooks/use-format'
import { useCompany } from '@/contexts/CompanyContext'
import { copyToClipboard } from '@/lib/browser/copy-to-clipboard'
const BASE = '/api/extensions/ext/invoice-inbox/inbox/domain'
const STATUS_BADGE: Record<
const STATUS_VARIANT: Record<
CompanyInboundDomain['status'],
{ label: string; variant: 'secondary' | 'success' | 'destructive' }
'secondary' | 'success' | 'destructive'
> = {
pending: { label: 'Väntar på DNS', variant: 'secondary' },
verified: { label: 'Verifierad', variant: 'success' },
failed: { label: 'Misslyckades', variant: 'destructive' },
pending: 'secondary',
verified: 'success',
failed: 'destructive',
}
interface Props {
@@ -40,7 +43,13 @@ interface Props {
// server-side: this surface only manages the claim lifecycle.
export default function InboxCustomDomainDialog({ open, onOpenChange }: Props) {
const { toast } = useToast()
const t = useTranslations('inbox_custom_domain')
const { locale, formatDateLong } = useFormat()
const errorLocale = locale as ErrorLocale
const { role } = useCompany()
const canManage = role === 'owner' || role === 'admin'
const [isLoading, setIsLoading] = useState(true)
const [loadFailed, setLoadFailed] = useState(false)
const [domain, setDomain] = useState<CompanyInboundDomain | null>(null)
const [domainInput, setDomainInput] = useState('')
const [isClaiming, setIsClaiming] = useState(false)
@@ -49,12 +58,17 @@ export default function InboxCustomDomainDialog({ open, onOpenChange }: Props) {
const fetchDomain = useCallback(async () => {
setIsLoading(true)
setLoadFailed(false)
try {
const res = await fetch(BASE)
if (!res.ok) {
setLoadFailed(true)
return
}
const json = await res.json()
if (res.ok) setDomain(json.data ?? null)
setDomain(json.data ?? null)
} catch {
// Leave the previous state; the dialog shows the claim form on null.
setLoadFailed(true)
} finally {
setIsLoading(false)
}
@@ -74,86 +88,98 @@ export default function InboxCustomDomainDialog({ open, onOpenChange }: Props) {
body: JSON.stringify({ domain: domainInput }),
})
const json = await res.json()
if (!res.ok) throw new Error(json.error ?? 'Kunde inte lägga till domänen')
if (!res.ok) throw new Error(json.error ?? t('claim_error_title'))
setDomain(json.data)
setDomainInput('')
toast({
title: 'Domän tillagd',
description: 'Lägg till DNS-posterna nedan hos din domänleverantör.',
title: t('claim_success_title'),
description: t('claim_success_description'),
})
} catch (err) {
toast({
title: 'Kunde inte lägga till domänen',
description: err instanceof Error ? getUserErrorMessage(err) : 'Försök igen.',
title: t('claim_error_title'),
description: err instanceof Error ? getUserErrorMessage(err, { locale: errorLocale }) : t('try_again'),
variant: 'destructive',
})
} finally {
setIsClaiming(false)
}
}, [domainInput, toast])
}, [domainInput, errorLocale, t, toast])
const handleVerify = useCallback(async () => {
setIsChecking(true)
try {
const res = await fetch(`${BASE}/verify`, { method: 'POST' })
const json = await res.json()
if (!res.ok) throw new Error(json.error ?? 'Kontrollen misslyckades')
if (!res.ok) throw new Error(json.error ?? t('verify_error_title'))
setDomain(json.data)
toast(
json.data.status === 'verified'
? { title: 'Domänen är verifierad', description: 'E-post till domänen landar nu i dokumentinkorgen.' }
: { title: 'Inte verifierad än', description: 'DNS-ändringar kan ta upp till någon timme att slå igenom.' }
? { title: t('verify_success_title'), description: t('verify_success_description') }
: { title: t('verify_pending_title'), description: t('verify_pending_description') }
)
} catch (err) {
toast({
title: 'Kontrollen misslyckades',
description: err instanceof Error ? getUserErrorMessage(err) : 'Försök igen.',
title: t('verify_error_title'),
description: err instanceof Error ? getUserErrorMessage(err, { locale: errorLocale }) : t('try_again'),
variant: 'destructive',
})
} finally {
setIsChecking(false)
}
}, [toast])
}, [errorLocale, t, toast])
const handleRemove = useCallback(async () => {
if (!domain) return
if (!confirm(`Ta bort ${domain.domain}? E-post till domänen slutar landa i Accounted.`)) return
if (!confirm(t('remove_confirm', { domain: domain.domain }))) return
setIsRemoving(true)
try {
const res = await fetch(BASE, { method: 'DELETE' })
const json = await res.json()
if (!res.ok) throw new Error(json.error ?? 'Borttagningen misslyckades')
if (!res.ok) throw new Error(json.error ?? t('remove_error_title'))
setDomain(null)
toast({ title: 'Domänen borttagen' })
toast({ title: t('remove_success_title') })
} catch (err) {
toast({
title: 'Borttagningen misslyckades',
description: err instanceof Error ? getUserErrorMessage(err) : 'Försök igen.',
title: t('remove_error_title'),
description: err instanceof Error ? getUserErrorMessage(err, { locale: errorLocale }) : t('try_again'),
variant: 'destructive',
})
} finally {
setIsRemoving(false)
}
}, [domain, toast])
}, [domain, errorLocale, t, toast])
const handleCopy = useCallback(
(value: string) => {
navigator.clipboard.writeText(value).catch(() => {})
toast({ title: 'Kopierat' })
async (value: string) => {
const result = await copyToClipboard(value)
toast(
result === 'copied'
? { title: t('copied') }
: {
title: t('copy_failed_title'),
description: t('copy_failed_description'),
variant: 'destructive',
}
)
},
[toast]
[t, toast]
)
const records: InboundDomainDnsRecord[] = domain?.dns_records ?? []
const statusLabels: Record<CompanyInboundDomain['status'], string> = {
pending: t('status_pending'),
verified: t('status_verified'),
failed: t('status_failed'),
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-2xl">
<DialogHeader>
<DialogTitle>Egen domän för inkorgen</DialogTitle>
<DialogTitle>{t('title')}</DialogTitle>
<DialogDescription>
Ta emot leverantörsfakturor direkt på bolagets egen adress, t.ex.
faktura@dittbolag.se: utan vidarebefordran.
{t('description')}
</DialogDescription>
</DialogHeader>
@@ -162,71 +188,94 @@ export default function InboxCustomDomainDialog({ open, onOpenChange }: Props) {
<Skeleton className="h-8 w-full" />
<Skeleton className="h-24 w-full" />
</div>
) : loadFailed ? (
<div role="status" className="flex items-center justify-between gap-4 text-sm">
<p className="text-muted-foreground">{t('load_error')}</p>
<Button
variant="outline"
size="sm"
onClick={() => {
void fetchDomain()
}}
>
{t('retry')}
</Button>
</div>
) : !domain ? (
<div className="space-y-4">
<div className="flex items-start gap-3 rounded-lg border border-border p-4 text-sm">
<AlertTriangle className="h-4 w-4 shrink-0 mt-0.5 text-muted-foreground" />
<div className="space-y-1">
<p className="font-medium">Viktigt om din domän redan tar emot e-post</p>
<p className="font-medium">{t('warning_title')}</p>
<p className="text-muted-foreground">
Domänens MX-poster pekas om till Accounted. Om domänen redan används för
e-post (Google Workspace, Microsoft 365) slutar din vanliga e-post att
fungera: använd då en underdomän, t.ex.{' '}
<code className="font-mono text-xs">faktura.dittbolag.se</code>, eller
fortsätt vidarebefordra till din vanliga inkorgsadress.
{t('warning_before_subdomain')}{' '}
<code className="font-mono text-xs">faktura.dittbolag.se</code>{' '}
{t('warning_after_subdomain')}
</p>
</div>
</div>
<div className="flex gap-2">
<Input
value={domainInput}
onChange={(e) => setDomainInput(e.target.value)}
placeholder="faktura.dittbolag.se"
onKeyDown={(e) => {
if (e.key === 'Enter') handleClaim()
}}
/>
<Button onClick={handleClaim} disabled={isClaiming || !domainInput.trim()}>
{isClaiming ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : null}
Lägg till
</Button>
</div>
{canManage ? (
<div className="flex gap-2">
<Input
value={domainInput}
onChange={(e) => setDomainInput(e.target.value)}
placeholder="faktura.dittbolag.se"
aria-label={t('domain_input_aria')}
onKeyDown={(e) => {
if (e.key === 'Enter') handleClaim()
}}
/>
<Button onClick={handleClaim} disabled={isClaiming || !domainInput.trim()}>
{isClaiming ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : null}
{t('add_button')}
</Button>
</div>
) : (
<p className="text-sm text-muted-foreground">{t('manage_permission')}</p>
)}
</div>
) : (
<div className="space-y-4">
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2 min-w-0">
<code className="font-mono text-sm truncate">{domain.domain}</code>
<Badge variant={STATUS_BADGE[domain.status].variant}>
{STATUS_BADGE[domain.status].label}
<Badge variant={STATUS_VARIANT[domain.status]}>
{statusLabels[domain.status]}
</Badge>
</div>
<div className="flex items-center gap-2 shrink-0">
<Button variant="outline" size="sm" onClick={handleVerify} disabled={isChecking}>
{isChecking ? (
<Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />
) : (
<RefreshCw className="h-3.5 w-3.5 mr-1.5" />
)}
Kontrollera igen
</Button>
<Button
variant="outline"
size="sm"
onClick={handleRemove}
disabled={isRemoving}
aria-label="Ta bort domän"
>
{isRemoving ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Trash2 className="h-3.5 w-3.5" />
)}
</Button>
</div>
{canManage ? (
<div className="flex items-center gap-2 shrink-0">
<Button
variant="outline"
size="sm"
onClick={handleVerify}
disabled={isChecking}
>
{isChecking ? (
<Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />
) : (
<RefreshCw className="h-3.5 w-3.5 mr-1.5" />
)}
{t('check_again')}
</Button>
<Button
variant="outline"
size="icon"
onClick={handleRemove}
disabled={isRemoving}
aria-label={t('remove_aria')}
>
{isRemoving ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Trash2 className="h-3.5 w-3.5" />
)}
</Button>
</div>
) : null}
</div>
{domain.status === 'verified' ? (
@@ -234,31 +283,32 @@ export default function InboxCustomDomainDialog({ open, onOpenChange }: Props) {
<Check className="h-4 w-4 shrink-0 mt-0.5 text-muted-foreground" />
<div className="space-y-1">
<p className="font-medium">
Klart: ge dina leverantörer{' '}
{t('verified_title')}{' '}
<code className="font-mono text-xs">faktura@{domain.domain}</code>
</p>
<p className="text-muted-foreground">
Alla adresser på domänen fungerar; allt landar i dokumentinkorgen.
{domain.verified_at ? ` Verifierad ${formatDateLong(domain.verified_at)}.` : ''}
{domain.verified_at
? t('verified_description_with_date', {
date: formatDateLong(domain.verified_at),
})
: t('verified_description')}
</p>
</div>
</div>
) : (
<div className="space-y-3">
<p className="text-sm text-muted-foreground">
Lägg till posterna nedan hos din domänleverantör (Loopia, one.com,
Cloudflare …) och klicka sedan på Kontrollera igen. Ändringar kan ta upp
till någon timme att slå igenom.
{t('dns_instructions')}
</p>
{records.length > 0 ? (
<div className="rounded-lg border border-border overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border">
<th className="px-3 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground">Typ</th>
<th className="px-3 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground">Namn</th>
<th className="px-3 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground">Värde</th>
<th className="px-3 py-2 text-right text-[11px] font-medium uppercase tracking-wider text-muted-foreground">Prio</th>
<th className="px-3 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground">{t('dns_type')}</th>
<th className="px-3 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground">{t('dns_name')}</th>
<th className="px-3 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground">{t('dns_value')}</th>
<th className="px-3 py-2 text-right text-[11px] font-medium uppercase tracking-wider text-muted-foreground">{t('dns_priority')}</th>
<th className="px-3 py-2" />
</tr>
</thead>
@@ -272,14 +322,17 @@ export default function InboxCustomDomainDialog({ open, onOpenChange }: Props) {
{r.priority ?? '-'}
</td>
<td className="px-3 py-2 text-right">
<button
<Button
type="button"
className="text-muted-foreground hover:text-foreground"
onClick={() => handleCopy(r.value)}
aria-label={`Kopiera ${r.type}-värde`}
variant="ghost"
size="icon"
onClick={() => {
void handleCopy(r.value)
}}
aria-label={t('copy_record_aria', { type: r.type })}
>
<Copy className="h-3.5 w-3.5" />
</button>
</Button>
</td>
</tr>
))}
@@ -288,7 +341,7 @@ export default function InboxCustomDomainDialog({ open, onOpenChange }: Props) {
</div>
) : (
<p className="text-sm text-muted-foreground">
Inga DNS-poster tillgängliga: klicka på Kontrollera igen.
{t('dns_empty')}
</p>
)}
</div>