fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,318 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useId } from 'react'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { AttnLine } from '@/components/ui/attn-line'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { RetentionNotice } from '@/components/ui/retention-notice'
|
||||
import { ExternalLink, Loader2 } from 'lucide-react'
|
||||
import { SupportLink } from '@/components/ui/support-link'
|
||||
import { getErrorMessage as getUserErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
import {
|
||||
canDeleteAccount,
|
||||
type OwnedCompanyBlocker,
|
||||
} from '@/components/settings/account-deletion'
|
||||
import {
|
||||
SettingsDangerZone,
|
||||
SettingsRow,
|
||||
SettingsRowEnd,
|
||||
SettingsRowNote,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
|
||||
export function AccountDangerZone() {
|
||||
const t = useTranslations('settings_account_danger')
|
||||
const tRetention = useTranslations('retention_notice')
|
||||
const errorLocale = useLocale() as ErrorLocale
|
||||
const router = useRouter()
|
||||
const [email, setEmail] = useState<string | null>(null)
|
||||
// null = the blocker list is not known: still loading, or the read failed
|
||||
// (loadError). "Cannot read the blockers" must mean "cannot permit
|
||||
// deletion", never "no blockers": canDeleteAccount() only unlocks the
|
||||
// button for a confirmed empty list.
|
||||
const [blockers, setBlockers] = useState<OwnedCompanyBlocker[] | null>(null)
|
||||
// detail === null: transient, so the line carries a retry. A detail sentence
|
||||
// means the user has to act (an expired session) and a retry cannot help.
|
||||
const [loadError, setLoadError] = useState<{ detail: string | null } | null>(null)
|
||||
const [reloadKey, setReloadKey] = useState(0)
|
||||
const [showDialog, setShowDialog] = useState(false)
|
||||
const [confirmText, setConfirmText] = useState('')
|
||||
const [isDeleting, setIsDeleting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const errorId = useId()
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
async function load() {
|
||||
setLoadError(null)
|
||||
const supabase = createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!cancelled) setEmail(user?.email ?? null)
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/company?owned=true&archived=false')
|
||||
if (!res.ok) {
|
||||
// Not-JSON bodies (an HTML error page, an empty 502) leave null, and
|
||||
// getErrorMessage falls back to the status map.
|
||||
const body = await res.json().catch(() => null)
|
||||
if (cancelled) return
|
||||
const sessionGone = res.status === 401 || res.status === 403
|
||||
setBlockers(null)
|
||||
setLoadError({
|
||||
detail: sessionGone
|
||||
? getUserErrorMessage(body, { statusCode: res.status, locale: errorLocale })
|
||||
: null,
|
||||
})
|
||||
return
|
||||
}
|
||||
// A 200 whose body will not parse throws into the catch below; a 200
|
||||
// whose data is not a list is a failed read too. Neither may become a
|
||||
// fabricated "no blockers".
|
||||
const body = await res.json()
|
||||
if (cancelled) return
|
||||
if (Array.isArray(body?.data)) {
|
||||
setBlockers(body.data)
|
||||
} else {
|
||||
setBlockers(null)
|
||||
setLoadError({ detail: null })
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) {
|
||||
setBlockers(null)
|
||||
setLoadError({ detail: null })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void load()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [reloadKey, errorLocale])
|
||||
|
||||
async function handleDelete() {
|
||||
if (!email) return
|
||||
if (confirmText.trim().toLowerCase() !== email.toLowerCase()) return
|
||||
|
||||
setIsDeleting(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/account/delete', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ confirm_email: email }),
|
||||
})
|
||||
|
||||
if (response.status === 409) {
|
||||
const body = await response.json().catch(() => null)
|
||||
// Precondition tripped mid-flow: refresh the list and show inline. A
|
||||
// 409 without a readable list still means blockers exist, so drop to
|
||||
// unknown (button stays locked) and re-read the authoritative list
|
||||
// instead of fabricating an empty one.
|
||||
if (Array.isArray(body?.blockers)) {
|
||||
setBlockers(body.blockers)
|
||||
} else {
|
||||
setBlockers(null)
|
||||
setReloadKey((k) => k + 1)
|
||||
}
|
||||
setError(
|
||||
typeof body?.error === 'string' && body.error
|
||||
? body.error
|
||||
: t('delete_failed_blockers'),
|
||||
)
|
||||
setIsDeleting(false)
|
||||
setShowDialog(false)
|
||||
return
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({}))
|
||||
throw new Error(body.error || t('delete_failed_default'))
|
||||
}
|
||||
|
||||
router.push('/login')
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? getUserErrorMessage(err) : t('delete_failed_default'))
|
||||
setIsDeleting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const canDelete = canDeleteAccount(blockers)
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsDangerZone label={t('heading')}>
|
||||
{/* Owned companies block deletion: functional state, kept visible as
|
||||
rows (only the first row carries the label and the why-help). */}
|
||||
{blockers !== null &&
|
||||
blockers.map((b, i) => (
|
||||
<SettingsRow
|
||||
key={b.id}
|
||||
label={i === 0 ? t('blockers_title') : ''}
|
||||
help={i === 0 ? t('blockers_description') : undefined}
|
||||
>
|
||||
<span className="text-sm">{b.name}</span>
|
||||
<SettingsRowEnd>
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<Link href="/settings/company">{t('blockers_manage')}</Link>
|
||||
</Button>
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
))}
|
||||
|
||||
<SettingsRow
|
||||
label={t('delete_button')}
|
||||
borderless
|
||||
// The full anonymization/BFL retention copy (incl. the backup link)
|
||||
// lives behind the "?": the visible row stays one quiet line.
|
||||
help={<RetentionNotice variant="account" className="border-0 bg-transparent p-0" />}
|
||||
>
|
||||
<div className="flex min-w-0 flex-col gap-0.5">
|
||||
<SettingsRowNote>{tRetention('account_title')}</SettingsRowNote>
|
||||
{/* Says up front that a typed confirmation follows (issue #2214,
|
||||
same as CompanyDangerZone). */}
|
||||
<SettingsRowNote>{t('confirm_hint')}</SettingsRowNote>
|
||||
</div>
|
||||
{/* Live region always mounted so the failure is announced when it
|
||||
appears, not merely inserted. */}
|
||||
<div id={errorId} role="status" aria-live="polite" className="min-w-0">
|
||||
{/* The button is disabled while companies remain, so the reason has
|
||||
to be visible next to it: hiding it behind the blocker row's "?"
|
||||
left users reading the greyed-out button as broken. */}
|
||||
{!loadError && blockers !== null && blockers.length > 0 && (
|
||||
<AttnLine>{t('blocked_reason', { count: blockers.length })}</AttnLine>
|
||||
)}
|
||||
{loadError && (
|
||||
<AttnLine
|
||||
action={
|
||||
loadError.detail
|
||||
? undefined
|
||||
: { label: t('blockers_load_retry'), onClick: () => setReloadKey((k) => k + 1) }
|
||||
}
|
||||
>
|
||||
{loadError.detail
|
||||
? `${t('blockers_load_failed')} ${loadError.detail}`
|
||||
: t('blockers_load_failed')}
|
||||
</AttnLine>
|
||||
)}
|
||||
</div>
|
||||
<SettingsRowEnd>
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<Link href="/reports?type=sie">
|
||||
<ExternalLink className="mr-2 h-3.5 w-3.5" />
|
||||
{t('export_sie')}
|
||||
</Link>
|
||||
</Button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowDialog(true)}
|
||||
disabled={!canDelete}
|
||||
aria-describedby={canDelete ? undefined : errorId}
|
||||
className="text-sm font-medium text-destructive underline underline-offset-2 transition-colors duration-150 hover:text-destructive/80 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{t('delete_button')}
|
||||
</button>
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
|
||||
{error && !showDialog && (
|
||||
<p className="px-1 text-sm text-destructive">{error}</p>
|
||||
)}
|
||||
|
||||
<p className="px-1 pt-3">
|
||||
<SettingsRowNote>
|
||||
{t('support_question')}{' '}
|
||||
<SupportLink variant="inline" subject={t('support_subject')} />
|
||||
</SettingsRowNote>
|
||||
</p>
|
||||
</SettingsDangerZone>
|
||||
|
||||
<Dialog
|
||||
open={showDialog}
|
||||
onOpenChange={(open) => {
|
||||
if (isDeleting) return
|
||||
setShowDialog(open)
|
||||
if (!open) {
|
||||
setConfirmText('')
|
||||
setError(null)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('dialog_title')}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t('dialog_description')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-2">
|
||||
{/* data-ph-mask: the label interpolates the user's email */}
|
||||
<Label data-ph-mask="" htmlFor="delete-confirm">
|
||||
{t.rich('confirm_label', {
|
||||
email: email ?? '',
|
||||
strong: (chunks) => <strong>{chunks}</strong>,
|
||||
})}
|
||||
</Label>
|
||||
<Input
|
||||
id="delete-confirm"
|
||||
type="email"
|
||||
value={confirmText}
|
||||
onChange={(e) => setConfirmText(e.target.value)}
|
||||
placeholder={email ?? ''}
|
||||
autoComplete="off"
|
||||
// ph-no-capture: the placeholder is the user's email, and
|
||||
// replay masking covers values, not attributes.
|
||||
className="ph-no-capture"
|
||||
/>
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setShowDialog(false)
|
||||
setConfirmText('')
|
||||
setError(null)
|
||||
}}
|
||||
disabled={isDeleting}
|
||||
>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={handleDelete}
|
||||
disabled={
|
||||
!email ||
|
||||
confirmText.trim().toLowerCase() !== email.toLowerCase() ||
|
||||
isDeleting
|
||||
}
|
||||
>
|
||||
{isDeleting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t('deleting')}
|
||||
</>
|
||||
) : (
|
||||
t('delete_confirm_button')
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import {
|
||||
SettingsRow,
|
||||
SettingsRowNote,
|
||||
SettingsSelect,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import type { AccountingFramework } from '@/types'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
|
||||
interface AccountingFrameworkFormProps {
|
||||
/** Current framework on the company row. */
|
||||
current: AccountingFramework
|
||||
/** Bubble up after a successful save so parent state can refresh. */
|
||||
onSaved?: (next: AccountingFramework) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* K2/K3 selector row for AB. Lives in the Grunder group on the bookkeeping
|
||||
* settings page. Renders nothing for non-AB entities: the parent gates this
|
||||
* component by entity_type.
|
||||
*
|
||||
* UX rules (regulatory area: kept in Swedish):
|
||||
* - Default is K2 (matches the column default and BFNAR 2016:10 baseline).
|
||||
* - Switching in either direction fires a confirmation dialog. K2 → K3
|
||||
* names what the system then does (K3-mallen for the årsredovisning,
|
||||
* komponentuppdelning in the asset register) and the one obligation the
|
||||
* choice itself carries: komponentavskrivning is mandatory under K3 where
|
||||
* component useful lives differ materially (punkt 17.4,
|
||||
* .claude/skills/swedish-year-end-closing/references/k2-vs-k3.md:5).
|
||||
* Kassaflödesanalys is NOT a consequence of K3: it follows from being a
|
||||
* större företag (references/reporting-and-filing.md:10), so the copy
|
||||
* says the product includes one, it does not blame the regelverk.
|
||||
* The recommendation per BFN is that the choice is permanent once made,
|
||||
* surfaced as a warning, not a block.
|
||||
* K3 → K2 warns about what the system does NOT do: uppskjuten skatt
|
||||
* (2240/8940) balances and komponentavskrivningar are not unwound
|
||||
* automatically, and the K3 årsredovisning content stops applying.
|
||||
* - The save is its own request (PATCH /api/company/current): separate
|
||||
* from /api/settings because the column lives on companies, not on
|
||||
* company_settings.
|
||||
*/
|
||||
export function AccountingFrameworkForm({ current, onSaved }: AccountingFrameworkFormProps) {
|
||||
const { toast } = useToast()
|
||||
const [selected, setSelected] = useState<AccountingFramework>(current)
|
||||
const [pending, setPending] = useState<AccountingFramework | null>(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
async function persist(next: AccountingFramework) {
|
||||
setSaving(true)
|
||||
try {
|
||||
const res = await fetch('/api/company/current', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ accounting_framework: next }),
|
||||
})
|
||||
const body = await res.json()
|
||||
if (!res.ok) {
|
||||
toast({
|
||||
title: 'Kunde inte spara',
|
||||
description: body?.error ?? 'Försök igen.',
|
||||
variant: 'destructive',
|
||||
})
|
||||
setSelected(current)
|
||||
return
|
||||
}
|
||||
toast({
|
||||
title: 'Sparat',
|
||||
description:
|
||||
next === 'k3'
|
||||
? 'Bolaget redovisar nu enligt K3 (BFNAR 2012:1).'
|
||||
: 'Bolaget redovisar nu enligt K2 (BFNAR 2016:10).',
|
||||
})
|
||||
onSaved?.(next)
|
||||
} catch {
|
||||
toast({
|
||||
title: 'Kunde inte spara',
|
||||
description: 'Försök igen.',
|
||||
variant: 'destructive',
|
||||
})
|
||||
setSelected(current)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
setPending(null)
|
||||
}
|
||||
}
|
||||
|
||||
function handleChange(next: string) {
|
||||
const value = next as AccountingFramework
|
||||
if (value === selected) return
|
||||
// Both directions are consequential: K2 → K3 adds obligations, K3 → K2
|
||||
// leaves K3-only balances behind. Confirm before persisting either way.
|
||||
setPending(value)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsRow
|
||||
label="Regelverk"
|
||||
htmlFor="accounting_framework"
|
||||
help={
|
||||
<>
|
||||
K2 är standard för mindre bolag och innebär förenklade regler. Större företag
|
||||
ska tillämpa K3 och upprätta kassaflödesanalys: dit räknas bland annat bolag
|
||||
som överskrider mer än ett av tre tröskelvärden (nettoomsättning > 80 MSEK,
|
||||
tillgångar > 40 MSEK, fler än 50 anställda) under vart och ett av de två
|
||||
senaste räkenskapsåren, och bolag med noterade värdepapper. För räkenskapsår
|
||||
som börjar efter 2025-12-31 är K2 dessutom stängt för bolag med utländsk
|
||||
filial, kryptotillgångar eller aktierelaterade ersättningar, och för bolag där
|
||||
byggnader ger minst 75 % av nettoomsättningen. Med K3
|
||||
valt bygger Accounted årsredovisningen enligt K3-mallen: kassaflödesanalys,
|
||||
förändring av eget kapital som egen räkning och utökade noter.
|
||||
Anläggningsregistret tar emot komponentuppdelning först med K3, som kräver
|
||||
komponentavskrivning när komponenterna har väsentligt olika nyttjandeperioder.
|
||||
Obeskattade reserver redovisas brutto i juridisk person enligt K3 punkt 29.37.
|
||||
</>
|
||||
}
|
||||
>
|
||||
<SettingsSelect
|
||||
id="accounting_framework"
|
||||
value={selected}
|
||||
onChange={(e) => handleChange(e.target.value)}
|
||||
// Saves via its own PATCH; the row sits inside the page's
|
||||
// SettingsFormWrapper form, so keep the wrapper's dirty tracking
|
||||
// (onInput on the form) from reacting to this select. No `name`
|
||||
// either, so the wrapper's FormData never picks it up.
|
||||
onInput={(e) => e.stopPropagation()}
|
||||
disabled={saving}
|
||||
>
|
||||
<option value="k2">K2 (BFNAR 2016:10): mindre företag</option>
|
||||
<option value="k3">K3 (BFNAR 2012:1): större företag</option>
|
||||
</SettingsSelect>
|
||||
{saving && <SettingsRowNote>Sparar…</SettingsRowNote>}
|
||||
</SettingsRow>
|
||||
|
||||
<Dialog
|
||||
open={pending !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setPending(null)
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{pending === 'k2' ? 'Byta till K2?' : 'Byta till K3?'}</DialogTitle>
|
||||
<DialogDescription className="space-y-2 pt-2">
|
||||
{pending === 'k2' ? (
|
||||
<>
|
||||
<span className="block">
|
||||
Bokförda saldon för uppskjuten skatt (konto 2240 / 8940) och gjorda
|
||||
komponentavskrivningar återförs inte automatiskt: de måste hanteras
|
||||
manuellt.
|
||||
</span>
|
||||
<span className="block">
|
||||
Årsredovisningens K3-innehåll (kassaflödesanalys, K3-noter och
|
||||
uppskjuten skatt) gäller inte längre. Fortsätt?
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="block">
|
||||
Årsredovisningen byggs då enligt K3-mallen: kassaflödesanalys,
|
||||
förändring av eget kapital som egen räkning och utökade noter.
|
||||
Kassaflödesanalys är i sig ett krav för större företag, inte en följd
|
||||
av regelverksvalet.
|
||||
</span>
|
||||
<span className="block">
|
||||
Komponentavskrivning blir obligatorisk för tillgångar vars komponenter
|
||||
har väsentligt olika nyttjandeperioder (K3 punkt 17.4).
|
||||
Anläggningsregistret tar emot komponentuppdelning först när K3 är valt.
|
||||
</span>
|
||||
<span className="block">
|
||||
Bytet är permanent enligt rekommendation. Fortsätt?
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setPending(null)}
|
||||
disabled={saving}
|
||||
>
|
||||
Avbryt
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (!pending) return
|
||||
setSelected(pending)
|
||||
void persist(pending)
|
||||
}}
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" /> Sparar…
|
||||
</>
|
||||
) : pending === 'k2' ? (
|
||||
'Byt till K2'
|
||||
) : (
|
||||
'Byt till K3'
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
'use client'
|
||||
|
||||
import { Briefcase } from 'lucide-react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { useByraSettingsScope } from './useSettingsNavItems'
|
||||
|
||||
/**
|
||||
* Quiet chip naming the active company. Settings surfaces (the routed modal
|
||||
* and the full-page fallback) cover or dim the sidebar's CompanySwitcher, so
|
||||
* without this the user edits company-scoped settings with no visible answer
|
||||
* to "which company am I on?" (support feedback 2026-07-19).
|
||||
*
|
||||
* Byrå scope (?ctx=byra): no chip. The cockpit sits above the companies and
|
||||
* only account-level sections show, so naming a technically-active client
|
||||
* here would read as "you are inside this company" (mirrors SettingsModal).
|
||||
*/
|
||||
export function ActiveCompanyBadge({ className }: { className?: string }) {
|
||||
const { company } = useCompany()
|
||||
const byraScope = useByraSettingsScope()
|
||||
const t = useTranslations('common')
|
||||
|
||||
if (!company || byraScope) return null
|
||||
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={cn(
|
||||
'max-w-full min-w-0 gap-1.5 font-normal text-muted-foreground',
|
||||
className,
|
||||
)}
|
||||
title={`${t('active_company')}: ${company.name}`}
|
||||
>
|
||||
<Briefcase className="h-3 w-3 shrink-0" aria-hidden="true" />
|
||||
<span className="sr-only">{t('active_company')}: </span>
|
||||
<span className="truncate">{company.name}</span>
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,299 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useLocale } from 'next-intl'
|
||||
import { ChevronDown, GraduationCap, Loader2 } from 'lucide-react'
|
||||
import ReactMarkdown from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import { AttnLine } from '@/components/ui/attn-line'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { HelpPopover } from '@/components/ui/help-popover'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { SettingsGroup, SettingsRowNote } from '@/components/settings/SettingsRows'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
|
||||
import type { AtomTier as Tier } from '@/lib/agent-context/agent-competence'
|
||||
|
||||
interface AtomMeta {
|
||||
id: string
|
||||
tier: Tier
|
||||
title: string
|
||||
description: string
|
||||
active: boolean
|
||||
}
|
||||
|
||||
const TIER_ORDER: Tier[] = ['horizontal', 'vertical', 'modifier']
|
||||
|
||||
const TIER_SECTION: Record<Tier, { title: string; blurb: string }> = {
|
||||
horizontal: {
|
||||
title: 'Kärnkompetens',
|
||||
blurb: 'Svenska bokförings- och skatteregler som assistenten alltid har med sig.',
|
||||
},
|
||||
vertical: {
|
||||
title: 'Anpassat för din bransch',
|
||||
blurb: 'Branschkunskap som valts utifrån vad ditt företag gör. Vilande områden finns men används inte för dig.',
|
||||
},
|
||||
modifier: {
|
||||
title: 'Din bolagssituation',
|
||||
blurb: 'Särskilda regler för hur just ditt bolag är uppbyggt.',
|
||||
},
|
||||
}
|
||||
|
||||
// Mirror of the chat surface's markdown styling (components/agent/AgentChat.tsx),
|
||||
// trimmed for a wider settings column.
|
||||
const PROSE =
|
||||
'prose prose-sm max-w-none text-foreground [&>*:first-child]:mt-0 [&>*:last-child]:mb-0 ' +
|
||||
'prose-headings:font-display prose-headings:font-normal prose-headings:tracking-tight ' +
|
||||
'prose-h1:text-lg prose-h2:text-base prose-h3:text-sm prose-p:my-2 prose-p:leading-6 ' +
|
||||
'prose-strong:font-semibold prose-strong:text-foreground prose-ul:my-2 prose-li:my-0.5 ' +
|
||||
'prose-a:text-foreground prose-a:underline prose-a:underline-offset-2 ' +
|
||||
'prose-code:bg-secondary prose-code:rounded-sm prose-code:px-1 prose-code:py-0.5 prose-code:text-xs ' +
|
||||
'prose-code:before:content-none prose-code:after:content-none ' +
|
||||
'prose-table:my-2 prose-table:text-xs [&_table]:w-full ' +
|
||||
'[&_th]:border-b [&_th]:border-border [&_th]:py-1.5 [&_th]:px-2 [&_th]:text-left [&_th]:font-medium ' +
|
||||
'[&_th]:text-muted-foreground [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-[10px] ' +
|
||||
'[&_td]:border-b [&_td]:border-border [&_td]:py-1.5 [&_td]:px-2 [&_td]:align-top'
|
||||
|
||||
export function AgentSkillsPanel() {
|
||||
const { toast } = useToast()
|
||||
const errorLocale = useLocale() as ErrorLocale
|
||||
|
||||
// null = the atom list is not known: still loading, or the read failed
|
||||
// (loadError). A failed read must never render the "Inga kunskapsområden
|
||||
// ännu" EmptyState: that is a claim about the assistant's composition, and
|
||||
// it is only true after a confirmed empty read.
|
||||
const [atoms, setAtoms] = useState<AtomMeta[] | null>(null)
|
||||
// detail === null: transient, so the line carries a retry. A detail sentence
|
||||
// means the user has to act (an expired session) and a retry cannot help.
|
||||
const [loadError, setLoadError] = useState<{ detail: string | null } | null>(null)
|
||||
const [reloadKey, setReloadKey] = useState(0)
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null)
|
||||
const [bodies, setBodies] = useState<Record<string, string>>({})
|
||||
const [loadingBody, setLoadingBody] = useState<string | null>(null)
|
||||
|
||||
// The cancelled closure is the same idiom every sibling panel uses
|
||||
// (TeamPanel, AccountDangerZone): a response that lands after unmount, or
|
||||
// after a newer load superseded this one, must not setState.
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
async function load() {
|
||||
setLoadError(null)
|
||||
try {
|
||||
const res = await fetch('/api/agent/skills')
|
||||
if (!res.ok) {
|
||||
// Not-JSON bodies (an HTML error page, an empty 502) leave null, and
|
||||
// getErrorMessage falls back to the status map.
|
||||
const json = await res.json().catch(() => null)
|
||||
if (cancelled) return
|
||||
const sessionGone = res.status === 401 || res.status === 403
|
||||
setAtoms(null)
|
||||
setLoadError({
|
||||
detail: sessionGone
|
||||
? getErrorMessage(json, { statusCode: res.status, locale: errorLocale })
|
||||
: null,
|
||||
})
|
||||
return
|
||||
}
|
||||
// A 200 whose body will not parse throws into the catch below; a 200
|
||||
// without the list is a failed read too. Neither may become a
|
||||
// fabricated "Inga kunskapsområden ännu".
|
||||
const json = await res.json()
|
||||
if (cancelled) return
|
||||
if (!Array.isArray(json?.data)) {
|
||||
setAtoms(null)
|
||||
setLoadError({ detail: null })
|
||||
return
|
||||
}
|
||||
setAtoms(json.data as AtomMeta[])
|
||||
} catch {
|
||||
if (!cancelled) {
|
||||
setAtoms(null)
|
||||
setLoadError({ detail: null })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void load()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [reloadKey, errorLocale])
|
||||
|
||||
const grouped = useMemo(() => {
|
||||
const map: Record<Tier, AtomMeta[]> = { horizontal: [], vertical: [], modifier: [] }
|
||||
for (const a of atoms ?? []) map[a.tier]?.push(a)
|
||||
return map
|
||||
}, [atoms])
|
||||
|
||||
const counts = useMemo(() => {
|
||||
const total = atoms?.length ?? 0
|
||||
const active = atoms?.filter((a) => a.active).length ?? 0
|
||||
return { total, active }
|
||||
}, [atoms])
|
||||
|
||||
async function toggle(atom: AtomMeta) {
|
||||
if (expandedId === atom.id) {
|
||||
setExpandedId(null)
|
||||
return
|
||||
}
|
||||
setExpandedId(atom.id)
|
||||
if (bodies[atom.id] !== undefined) return
|
||||
setLoadingBody(atom.id)
|
||||
try {
|
||||
const res = await fetch(`/api/agent/skills?slug=${encodeURIComponent(atom.id)}`)
|
||||
if (!res.ok) {
|
||||
// Not-JSON bodies (an HTML error page, an empty 502) leave null, and
|
||||
// getErrorMessage falls back to the status map.
|
||||
const json = await res.json().catch(() => null)
|
||||
toast({
|
||||
title: 'Kunde inte läsa kunskapen',
|
||||
description: getErrorMessage(json, { statusCode: res.status, locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
const json = await res.json()
|
||||
setBodies((prev) => ({ ...prev, [atom.id]: (json.data?.body as string) ?? '' }))
|
||||
} catch (err) {
|
||||
// A rejected fetch or a 200 whose body will not parse never reaches the
|
||||
// !res.ok arm above: without this toast the expanded row just sits
|
||||
// empty with zero feedback. One toast per outcome, never two:
|
||||
// TOAST_LIMIT is 1 (components/ui/use-toast.tsx) and a second would
|
||||
// evict the first.
|
||||
toast({
|
||||
title: 'Kunde inte läsa kunskapen',
|
||||
description: getErrorMessage(err, { locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setLoadingBody(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Dynamic status stays visible; the static "what this is" copy sits
|
||||
behind the "?" next to it. */}
|
||||
{atoms && (
|
||||
<div className="flex items-center gap-2 px-1">
|
||||
<SettingsRowNote className="tabular-nums">
|
||||
{counts.total} kunskapsområden · {counts.active} aktiva för ditt företag
|
||||
</SettingsRowNote>
|
||||
<HelpPopover className="shrink-0">
|
||||
Utöver vad den minns om ditt företag bygger assistenten på en uppsättning
|
||||
kunskapsområden om svensk bokföring och skatt. Kärnkompetensen gäller alla;
|
||||
bransch- och bolagsanpassningen väljs utifrån ditt företag. Klicka på ett
|
||||
område för att läsa hela kunskapen.
|
||||
</HelpPopover>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Live region always mounted so the failure is announced when it
|
||||
appears, not merely inserted. */}
|
||||
<div role="status" aria-live="polite" className="min-w-0 px-1">
|
||||
{loadError && (
|
||||
<AttnLine
|
||||
action={
|
||||
loadError.detail
|
||||
? undefined
|
||||
: { label: 'Försök igen', onClick: () => setReloadKey((k) => k + 1) }
|
||||
}
|
||||
>
|
||||
{loadError.detail
|
||||
? `Kunskapsområdena kunde inte läsas in just nu. ${loadError.detail}`
|
||||
: 'Kunskapsområdena kunde inte läsas in just nu.'}
|
||||
</AttnLine>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{atoms === null && !loadError && (
|
||||
<div className="space-y-3">
|
||||
{[0, 1, 2, 3].map((i) => (
|
||||
<Skeleton key={i} className="h-12 w-full" />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{atoms && atoms.length === 0 && (
|
||||
<EmptyState
|
||||
icon={GraduationCap}
|
||||
title="Inga kunskapsområden ännu"
|
||||
description="När din assistent har komponerats dyker dess kunskapsområden upp här."
|
||||
/>
|
||||
)}
|
||||
|
||||
{atoms && atoms.length > 0 &&
|
||||
TIER_ORDER.filter((tier) => grouped[tier].length > 0).map((tier) => (
|
||||
<SettingsGroup key={tier} label={TIER_SECTION[tier].title} help={TIER_SECTION[tier].blurb}>
|
||||
{grouped[tier].map((atom) => {
|
||||
const isOpen = expandedId === atom.id
|
||||
const isLoading = loadingBody === atom.id
|
||||
const body = bodies[atom.id]
|
||||
const dormant = !atom.active
|
||||
return (
|
||||
<div key={atom.id} className="border-b border-border">
|
||||
<button
|
||||
onClick={() => toggle(atom)}
|
||||
aria-expanded={isOpen}
|
||||
className="flex w-full items-start gap-3 px-1 py-3 text-left"
|
||||
>
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
'mt-0.5 h-4 w-4 shrink-0 text-muted-foreground transition-transform',
|
||||
!isOpen && '-rotate-90',
|
||||
)}
|
||||
/>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span
|
||||
className={cn(
|
||||
'block text-sm font-medium',
|
||||
dormant ? 'text-muted-foreground' : 'text-foreground',
|
||||
)}
|
||||
>
|
||||
{atom.title}
|
||||
</span>
|
||||
<span className="block text-xs text-muted-foreground">{atom.description}</span>
|
||||
</span>
|
||||
{/* Chips mark exceptions: active is the normal state and
|
||||
renders as muted text, only dormant gets a Badge. */}
|
||||
{tier !== 'horizontal' && (
|
||||
atom.active ? (
|
||||
<span className="mt-0.5 shrink-0 text-xs text-muted-foreground">Aktiv</span>
|
||||
) : (
|
||||
<Badge variant="outline" className="mt-0.5 shrink-0">Vilande</Badge>
|
||||
)
|
||||
)}
|
||||
</button>
|
||||
|
||||
{isOpen && (
|
||||
<div className="px-1 pb-4 pl-8">
|
||||
{isLoading && (
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
Läser in…
|
||||
</div>
|
||||
)}
|
||||
{!isLoading && body !== undefined && body.length > 0 && (
|
||||
<div className={PROSE}>
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]}>{body}</ReactMarkdown>
|
||||
</div>
|
||||
)}
|
||||
{!isLoading && body !== undefined && body.length === 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Innehållet kunde inte läsas in.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</SettingsGroup>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,90 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { SettingsRow } from '@/components/settings/SettingsRows'
|
||||
import { isSelfHosted as readSelfHostedFlag } from '@/lib/env/public-flags'
|
||||
|
||||
// Session timeouts are a hosted concern: self-hosted deployments have them
|
||||
// disabled at the config level, so the toggle would be a no-op there.
|
||||
const isSelfHosted = readSelfHostedFlag()
|
||||
|
||||
/**
|
||||
* Per-user opt-in for automatic logout. Off by default: the session then
|
||||
* lives as long as the Supabase refresh token. On: the hosted idle/absolute
|
||||
* timeouts apply (enforced by the middleware via the signed timeout cookie,
|
||||
* which the preferences API resets on change).
|
||||
*/
|
||||
export function AutoLogoutToggle() {
|
||||
const t = useTranslations('settings_security')
|
||||
const { toast } = useToast()
|
||||
const [enabled, setEnabled] = useState(false)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (isSelfHosted) return
|
||||
let active = true
|
||||
;(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/user/preferences', { cache: 'no-store' })
|
||||
if (!res.ok) return
|
||||
const payload = (await res.json()) as {
|
||||
data?: { auto_logout?: boolean }
|
||||
}
|
||||
if (active) setEnabled(payload.data?.auto_logout === true)
|
||||
} catch {
|
||||
// Leave the default (off); a failed read must not block the page.
|
||||
} finally {
|
||||
if (active) setLoading(false)
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
if (isSelfHosted) return null
|
||||
|
||||
async function handleChange(next: boolean) {
|
||||
setEnabled(next)
|
||||
setSaving(true)
|
||||
try {
|
||||
const res = await fetch('/api/user/preferences', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ auto_logout: next }),
|
||||
})
|
||||
if (!res.ok) throw new Error('Could not save')
|
||||
toast({
|
||||
title: next
|
||||
? t('auto_logout_enabled_toast')
|
||||
: t('auto_logout_disabled_toast'),
|
||||
})
|
||||
} catch {
|
||||
setEnabled(!next)
|
||||
toast({ title: t('auto_logout_save_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsRow
|
||||
label={t('auto_logout_label')}
|
||||
help={t('auto_logout_description')}
|
||||
>
|
||||
<Switch
|
||||
id="auto-logout"
|
||||
checked={enabled}
|
||||
onCheckedChange={(value) => void handleChange(value)}
|
||||
disabled={loading || saving}
|
||||
/>
|
||||
<label htmlFor="auto-logout" className="cursor-pointer text-sm">
|
||||
{t('auto_logout_switch_label')}
|
||||
</label>
|
||||
</SettingsRow>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
'use client'
|
||||
|
||||
import Image from 'next/image'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { BankIdAuth } from '@/components/auth/BankIdAuth'
|
||||
import type { BankIdResult } from '@/components/auth/BankIdAuth'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { formatDateLong } from '@/lib/utils'
|
||||
import {
|
||||
SettingsRow,
|
||||
SettingsRowEnd,
|
||||
SettingsRowNote,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
|
||||
interface BankIdIdentity {
|
||||
given_name: string | null
|
||||
surname: string | null
|
||||
linked_at: string
|
||||
}
|
||||
|
||||
export function BankIdSettings() {
|
||||
const t = useTranslations('settings_bankid')
|
||||
const [identity, setIdentity] = useState<BankIdIdentity | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isLinking, setIsLinking] = useState(false)
|
||||
const [isUnlinking, setIsUnlinking] = useState(false)
|
||||
const { toast } = useToast()
|
||||
|
||||
const fetchIdentity = useCallback(async () => {
|
||||
const supabase = createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) { setIsLoading(false); return }
|
||||
|
||||
const { data } = await supabase
|
||||
.from('bankid_identities')
|
||||
.select('given_name, surname, linked_at')
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
|
||||
setIdentity(data)
|
||||
setIsLoading(false)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetchIdentity()
|
||||
}, [fetchIdentity])
|
||||
|
||||
const handleLinkComplete = async (result: BankIdResult) => {
|
||||
if (result.error) {
|
||||
const message = result.error === 'already_linked'
|
||||
? t('toast_already_linked')
|
||||
: t('toast_link_failed')
|
||||
toast({ title: message, variant: 'destructive' })
|
||||
setIsLinking(false)
|
||||
return
|
||||
}
|
||||
|
||||
toast({ title: t('toast_linked') })
|
||||
setIsLinking(false)
|
||||
fetchIdentity()
|
||||
}
|
||||
|
||||
const handleUnlink = async () => {
|
||||
if (!confirm(t('confirm_unlink'))) return
|
||||
|
||||
setIsUnlinking(true)
|
||||
try {
|
||||
const res = await fetch('/api/extensions/ext/tic/bankid/unlink', { method: 'POST' })
|
||||
if (!res.ok) throw new Error('Unlink failed')
|
||||
|
||||
setIdentity(null)
|
||||
toast({ title: t('toast_unlinked') })
|
||||
} catch {
|
||||
toast({ title: t('toast_unlink_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setIsUnlinking(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<SettingsRow label={t('title')}>
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
</SettingsRow>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsRow
|
||||
label={
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<Image
|
||||
src="/logos/bankid-seeklogo.svg"
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
width={16}
|
||||
height={16}
|
||||
className="dark:invert"
|
||||
/>
|
||||
{t('title')}
|
||||
</span>
|
||||
}
|
||||
help={identity ? t('linked_description') : t('not_linked_description')}
|
||||
borderless={isLinking}
|
||||
>
|
||||
{identity ? (
|
||||
<>
|
||||
<span className="text-sm font-medium">
|
||||
{identity.given_name} {identity.surname}
|
||||
</span>
|
||||
<SettingsRowNote>
|
||||
{t('linked_on', { date: formatDateLong(identity.linked_at) })}
|
||||
</SettingsRowNote>
|
||||
<SettingsRowEnd>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleUnlink}
|
||||
disabled={isUnlinking}
|
||||
className="text-destructive hover:text-destructive"
|
||||
>
|
||||
{isUnlinking ? t('unlinking') : t('unlink_button')}
|
||||
</Button>
|
||||
</SettingsRowEnd>
|
||||
</>
|
||||
) : isLinking ? (
|
||||
// Active flow: the scan instruction is the actionable content and
|
||||
// stays visible while the QR block below is open.
|
||||
<SettingsRowNote>{t('link_bankid_description')}</SettingsRowNote>
|
||||
) : (
|
||||
<SettingsRowEnd>
|
||||
<Button variant="outline" size="sm" onClick={() => setIsLinking(true)}>
|
||||
<Image
|
||||
src="/logos/bankid-seeklogo.svg"
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
width={16}
|
||||
height={16}
|
||||
className="mr-2 dark:invert"
|
||||
/>
|
||||
{t('link_button')}
|
||||
</Button>
|
||||
</SettingsRowEnd>
|
||||
)}
|
||||
</SettingsRow>
|
||||
|
||||
{/* QR flow: an expanding block below the row. Mounted only while
|
||||
linking so the BankID session starts exactly when requested. */}
|
||||
{isLinking && (
|
||||
<div className="flex flex-col items-center gap-3 border-b border-border px-1 py-4">
|
||||
<BankIdAuth mode="link" onComplete={handleLinkComplete} />
|
||||
{/* BankIdAuth's own Avbryt only resets its internal session; give
|
||||
the row an exit so isLinking can't get stuck. */}
|
||||
<Button variant="outline" size="sm" onClick={() => setIsLinking(false)}>
|
||||
{t('cancel_linking')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface BankOption {
|
||||
name: string
|
||||
logo?: string
|
||||
bic?: string
|
||||
}
|
||||
|
||||
const FALLBACK_BANKS: BankOption[] = [
|
||||
{ name: 'Nordea', bic: 'NDEASESS' },
|
||||
{ name: 'SEB', bic: 'ESSESESS' },
|
||||
{ name: 'Swedbank', bic: 'SWEDSESS' },
|
||||
{ name: 'Handelsbanken', bic: 'HANDSESS' },
|
||||
{ name: 'Danske Bank', bic: 'DABASES' },
|
||||
{ name: 'Länsförsäkringar', bic: 'ELLFSESS' },
|
||||
{ name: 'Skandiabanken', bic: 'SKIASESS' },
|
||||
{ name: 'ICA Banken' },
|
||||
{ name: 'Avanza Bank' },
|
||||
{ name: 'Sparbanken' },
|
||||
]
|
||||
|
||||
interface BankNameComboboxProps {
|
||||
defaultValue?: string
|
||||
value?: string
|
||||
onChange?: (value: string) => void
|
||||
enableBankingEnabled?: boolean
|
||||
'aria-label'?: string
|
||||
}
|
||||
|
||||
export function BankNameCombobox({ defaultValue = '', value: controlledValue, onChange, enableBankingEnabled = false, 'aria-label': ariaLabel }: BankNameComboboxProps) {
|
||||
const isControlled = controlledValue !== undefined
|
||||
const [internalValue, setInternalValue] = useState(defaultValue)
|
||||
const value = isControlled ? controlledValue : internalValue
|
||||
const setValue = (v: string) => {
|
||||
if (!isControlled) setInternalValue(v)
|
||||
onChange?.(v)
|
||||
}
|
||||
const [banks, setBanks] = useState<BankOption[]>(FALLBACK_BANKS)
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const [highlightedIndex, setHighlightedIndex] = useState(-1)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const listRef = useRef<HTMLUListElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!enableBankingEnabled) return
|
||||
|
||||
let cancelled = false
|
||||
async function fetchBanks() {
|
||||
try {
|
||||
const res = await fetch('/api/extensions/ext/enable-banking/banks')
|
||||
if (!res.ok) return
|
||||
const data = await res.json()
|
||||
if (!cancelled && data.banks?.length > 0) {
|
||||
setBanks(data.banks)
|
||||
}
|
||||
} catch {
|
||||
// Keep fallback list
|
||||
}
|
||||
}
|
||||
fetchBanks()
|
||||
return () => { cancelled = true }
|
||||
}, [enableBankingEnabled])
|
||||
|
||||
const filtered = value.trim()
|
||||
? banks.filter((b) => b.name.toLowerCase().includes(value.toLowerCase()))
|
||||
: banks
|
||||
|
||||
useEffect(() => {
|
||||
setHighlightedIndex(-1)
|
||||
}, [value])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return
|
||||
function handleClickOutside(e: MouseEvent) {
|
||||
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
|
||||
setIsOpen(false)
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', handleClickOutside)
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside)
|
||||
}, [isOpen])
|
||||
|
||||
// Scroll highlighted item into view
|
||||
useEffect(() => {
|
||||
if (highlightedIndex < 0 || !listRef.current) return
|
||||
const item = listRef.current.children[highlightedIndex] as HTMLElement
|
||||
item?.scrollIntoView({ block: 'nearest' })
|
||||
}, [highlightedIndex])
|
||||
|
||||
function selectBank(bank: BankOption) {
|
||||
setValue(bank.name)
|
||||
setIsOpen(false)
|
||||
inputRef.current?.focus()
|
||||
}
|
||||
|
||||
function handleKeyDown(e: React.KeyboardEvent) {
|
||||
if (!isOpen && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
|
||||
setIsOpen(true)
|
||||
e.preventDefault()
|
||||
return
|
||||
}
|
||||
|
||||
if (!isOpen) return
|
||||
|
||||
switch (e.key) {
|
||||
case 'ArrowDown':
|
||||
e.preventDefault()
|
||||
setHighlightedIndex((i) => (i < filtered.length - 1 ? i + 1 : 0))
|
||||
break
|
||||
case 'ArrowUp':
|
||||
e.preventDefault()
|
||||
setHighlightedIndex((i) => (i > 0 ? i - 1 : filtered.length - 1))
|
||||
break
|
||||
case 'Enter':
|
||||
e.preventDefault()
|
||||
if (highlightedIndex >= 0 && filtered[highlightedIndex]) {
|
||||
selectBank(filtered[highlightedIndex])
|
||||
}
|
||||
break
|
||||
case 'Escape':
|
||||
setIsOpen(false)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="relative">
|
||||
<input type="hidden" name="bank_name" value={value} />
|
||||
<Input
|
||||
aria-label={ariaLabel}
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
placeholder="t.ex. Nordea"
|
||||
maxLength={100}
|
||||
value={value}
|
||||
onChange={(e) => {
|
||||
setValue(e.target.value)
|
||||
if (!isOpen) setIsOpen(true)
|
||||
}}
|
||||
onFocus={() => setIsOpen(true)}
|
||||
onKeyDown={handleKeyDown}
|
||||
role="combobox"
|
||||
aria-expanded={isOpen}
|
||||
aria-autocomplete="list"
|
||||
aria-controls="bank-name-listbox"
|
||||
autoComplete="off"
|
||||
/>
|
||||
{isOpen && filtered.length > 0 && (
|
||||
<ul
|
||||
ref={listRef}
|
||||
id="bank-name-listbox"
|
||||
role="listbox"
|
||||
className="absolute z-50 mt-1 max-h-56 w-full overflow-auto rounded-lg border border-border bg-popover shadow-md"
|
||||
>
|
||||
{filtered.map((bank, i) => (
|
||||
<li
|
||||
key={bank.name}
|
||||
role="option"
|
||||
aria-selected={highlightedIndex === i}
|
||||
className={cn(
|
||||
'flex items-center gap-2 px-3 py-2 text-sm cursor-pointer transition-colors',
|
||||
highlightedIndex === i && 'bg-accent text-accent-foreground',
|
||||
)}
|
||||
onMouseEnter={() => setHighlightedIndex(i)}
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault() // prevent blur before click registers
|
||||
selectBank(bank)
|
||||
}}
|
||||
>
|
||||
{bank.logo ? (
|
||||
<img
|
||||
src={bank.logo}
|
||||
alt=""
|
||||
className="h-5 w-5 flex-shrink-0 rounded-sm object-contain"
|
||||
/>
|
||||
) : (
|
||||
<svg
|
||||
className="h-5 w-5 flex-shrink-0 text-muted-foreground"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
strokeWidth={1.5}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M3 21h18M3 10h18M5 6l7-3 7 3M4 10v11M20 10v11M8 14v4M12 14v4M16 14v4" />
|
||||
</svg>
|
||||
)}
|
||||
<span className="truncate">{bank.name}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { ChevronRight } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import type { BillingPlan } from '@/lib/stripe/client'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { PLAN_PRICES } from '@/components/settings/billing-plans'
|
||||
|
||||
/**
|
||||
* The billing call to action. Paying companies get the Stripe Customer
|
||||
* Portal (manage/cancel) as a quiet row action; everyone else gets the
|
||||
* Checkout button for the plan chosen in the offer rows above it. Both POST
|
||||
* to a route that returns a hosted Stripe URL we redirect to.
|
||||
*
|
||||
* `firstChargeDeferred`: the checkout route will defer the first charge to
|
||||
* the trial's end (see billing/checkout), so the CTA can truthfully say
|
||||
* "0 kr idag" instead of quoting a price.
|
||||
*/
|
||||
export function BillingActions({
|
||||
isPaying,
|
||||
configured,
|
||||
plan = 'yearly',
|
||||
firstChargeDeferred = false,
|
||||
}: {
|
||||
isPaying: boolean
|
||||
configured: boolean
|
||||
plan?: BillingPlan
|
||||
firstChargeDeferred?: boolean
|
||||
}) {
|
||||
const t = useTranslations('settings_billing')
|
||||
const { toast } = useToast()
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
async function go(endpoint: string, payload?: Record<string, unknown>) {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload ?? {}),
|
||||
})
|
||||
const data = (await res.json().catch(() => ({}))) as {
|
||||
url?: string
|
||||
error?: string | { message?: string }
|
||||
}
|
||||
const errorMessage = typeof data.error === 'string' ? data.error : data.error?.message
|
||||
if (!res.ok || !data.url) throw new Error(errorMessage || t('checkout_failed'))
|
||||
window.location.href = data.url
|
||||
} catch (e) {
|
||||
toast({
|
||||
title: t('checkout_failed'),
|
||||
description: e instanceof Error ? getUserErrorMessage(e) : undefined,
|
||||
variant: 'destructive',
|
||||
})
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (isPaying) {
|
||||
return (
|
||||
<Button variant="outline" size="sm" onClick={() => go('/api/billing/portal')} disabled={loading}>
|
||||
{t('manage_cta')}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
if (!configured) {
|
||||
return (
|
||||
<Button size="lg" disabled className="w-full sm:w-auto">
|
||||
{t('cta_coming_soon')}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
const label = loading
|
||||
? t('cta_opening')
|
||||
: firstChargeDeferred
|
||||
? t('cta_start_deferred')
|
||||
: t('cta_start_now', { price: formatCurrency(PLAN_PRICES[plan].exVat), period: t(`period_${plan}`) })
|
||||
|
||||
return (
|
||||
<Button
|
||||
size="lg"
|
||||
onClick={() => go('/api/billing/checkout', { plan })}
|
||||
disabled={loading}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
{label}
|
||||
{!loading && <ChevronRight className="h-4 w-4" />}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,306 @@
|
||||
'use client'
|
||||
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { formatDateLong } from '@/lib/utils'
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Calendar, Copy, RefreshCw, Loader2, Check } from 'lucide-react'
|
||||
import { DestructiveConfirmDialog, useDestructiveConfirm } from '@/components/ui/destructive-confirm-dialog'
|
||||
import {
|
||||
SettingsGroup,
|
||||
SettingsInput,
|
||||
SettingsRow,
|
||||
SettingsRowEnd,
|
||||
SettingsRowNote,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import type { CalendarFeed } from '@/types'
|
||||
|
||||
interface CalendarFeedWithUrls extends CalendarFeed {
|
||||
webcalUrl: string
|
||||
httpsUrl: string
|
||||
}
|
||||
|
||||
export function CalendarFeedSettings() {
|
||||
const t = useTranslations('settings_calendar_feed')
|
||||
const locale = useLocale()
|
||||
const { toast } = useToast()
|
||||
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
const [isRegenerating, setIsRegenerating] = useState(false)
|
||||
const [feed, setFeed] = useState<CalendarFeedWithUrls | null>(null)
|
||||
const [copied, setCopied] = useState(false)
|
||||
const { dialogProps: confirmDialogProps, confirm: confirmAction } = useDestructiveConfirm()
|
||||
|
||||
useEffect(() => {
|
||||
fetchFeed()
|
||||
}, [])
|
||||
|
||||
const fetchFeed = async () => {
|
||||
setIsLoading(true)
|
||||
|
||||
const response = await fetch('/api/calendar/feed')
|
||||
const { data } = await response.json()
|
||||
|
||||
setFeed(data)
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
const createFeed = async () => {
|
||||
setIsSaving(true)
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/calendar/feed', {
|
||||
method: 'POST',
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to create feed')
|
||||
}
|
||||
|
||||
const { data } = await response.json()
|
||||
setFeed(data)
|
||||
|
||||
toast({
|
||||
title: t('toast_feed_created_title'),
|
||||
description: t('toast_feed_created_description'),
|
||||
})
|
||||
} catch {
|
||||
toast({
|
||||
title: t('toast_create_failed'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const updateFeed = async (key: keyof CalendarFeed, value: boolean) => {
|
||||
if (!feed) return
|
||||
|
||||
setIsSaving(true)
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/calendar/feed', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ [key]: value }),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to update feed')
|
||||
}
|
||||
|
||||
const { data } = await response.json()
|
||||
setFeed(data)
|
||||
} catch {
|
||||
toast({
|
||||
title: t('toast_update_failed'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const regenerateToken = async () => {
|
||||
const ok = await confirmAction({
|
||||
title: t('regen_dialog_title'),
|
||||
description: t('regen_dialog_description'),
|
||||
confirmLabel: t('regen_confirm'),
|
||||
variant: 'warning',
|
||||
})
|
||||
if (!ok) return
|
||||
|
||||
setIsRegenerating(true)
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/calendar/feed', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to regenerate token')
|
||||
}
|
||||
|
||||
const { data } = await response.json()
|
||||
setFeed(data)
|
||||
|
||||
toast({
|
||||
title: t('toast_new_link_title'),
|
||||
description: t('toast_new_link_description'),
|
||||
})
|
||||
} catch {
|
||||
toast({
|
||||
title: t('toast_regen_failed'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsRegenerating(false)
|
||||
}
|
||||
}
|
||||
|
||||
const copyToClipboard = async (text: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 2000)
|
||||
toast({
|
||||
title: t('toast_copied_title'),
|
||||
description: t('toast_copied_description'),
|
||||
})
|
||||
} catch {
|
||||
toast({
|
||||
title: t('toast_copy_failed'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const openWebcal = () => {
|
||||
if (feed?.webcalUrl) {
|
||||
window.location.href = feed.webcalUrl
|
||||
}
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex h-32 items-center justify-center">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!feed) {
|
||||
return (
|
||||
<SettingsGroup label={t('title')} help={t('description')}>
|
||||
<SettingsRow label={t('activate_sync')} help={t('empty_intro')}>
|
||||
<SettingsRowEnd>
|
||||
<Button variant="outline" size="sm" onClick={createFeed} disabled={isSaving}>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
|
||||
{t('creating')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Calendar className="mr-2 h-3.5 w-3.5" />
|
||||
{t('activate_sync')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Feed URL */}
|
||||
<SettingsGroup label={t('title')} help={t('subscribe_description')}>
|
||||
<SettingsRow
|
||||
label={t('calendar_link_label')}
|
||||
htmlFor="calendar-feed-url"
|
||||
help={t('calendar_link_help')}
|
||||
align="baseline"
|
||||
>
|
||||
<SettingsInput
|
||||
id="calendar-feed-url"
|
||||
value={feed.httpsUrl}
|
||||
readOnly
|
||||
className="font-mono text-xs"
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => copyToClipboard(feed.httpsUrl)}
|
||||
aria-label={t('calendar_link_help')}
|
||||
className="shrink-0 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
|
||||
</Button>
|
||||
<SettingsRowEnd>
|
||||
<Button variant="outline" size="sm" onClick={openWebcal}>
|
||||
<Calendar className="mr-2 h-3.5 w-3.5" />
|
||||
{t('add_to_apple_calendar')}
|
||||
</Button>
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
|
||||
<p className="px-1 pt-2 text-xs text-muted-foreground">
|
||||
{t('google_reminders_note')}
|
||||
</p>
|
||||
|
||||
<SettingsRow label={t('create_new_link')} help={t('regen_help')}>
|
||||
{/* Live feed stats stay visible: they are state, not instructions */}
|
||||
{feed.last_accessed_at && (
|
||||
<SettingsRowNote className="tabular-nums">
|
||||
{t('last_fetched')}{' '}
|
||||
{formatDateLong(feed.last_accessed_at, locale)}
|
||||
{' · '}
|
||||
{t('times_count', { count: feed.access_count })}
|
||||
</SettingsRowNote>
|
||||
)}
|
||||
<SettingsRowEnd>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={regenerateToken}
|
||||
disabled={isRegenerating}
|
||||
>
|
||||
{isRegenerating ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
|
||||
{t('creating_new_link')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<RefreshCw className="mr-2 h-3.5 w-3.5" />
|
||||
{t('create_new_link')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
|
||||
{/* Content settings */}
|
||||
<SettingsGroup label={t('content_title')} help={t('content_description')}>
|
||||
<SettingsRow
|
||||
label={t('tax_deadlines_label')}
|
||||
htmlFor="include-tax"
|
||||
help={t('tax_deadlines_help')}
|
||||
>
|
||||
<Switch
|
||||
id="include-tax"
|
||||
checked={feed.include_tax_deadlines}
|
||||
onCheckedChange={(checked) =>
|
||||
updateFeed('include_tax_deadlines', checked)
|
||||
}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow
|
||||
label={t('invoices_label')}
|
||||
htmlFor="include-invoices"
|
||||
help={t('invoices_help')}
|
||||
>
|
||||
<Switch
|
||||
id="include-invoices"
|
||||
checked={feed.include_invoices}
|
||||
onCheckedChange={(checked) =>
|
||||
updateFeed('include_invoices', checked)
|
||||
}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
|
||||
<DestructiveConfirmDialog {...confirmDialogProps} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { RetentionNotice } from '@/components/ui/retention-notice'
|
||||
import {
|
||||
SettingsDangerZone,
|
||||
SettingsRow,
|
||||
SettingsRowEnd,
|
||||
SettingsRowNote,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { getBranding } from '@/lib/branding/service'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { CompanyMigrationResetDialog } from '@/components/settings/CompanyMigrationResetDialog'
|
||||
import { CompanyMigrationArchiveRow } from '@/components/settings/CompanyMigrationArchiveRow'
|
||||
|
||||
const branding = getBranding()
|
||||
|
||||
/**
|
||||
* Danger zone for the currently-active company. Only visible to owners.
|
||||
*
|
||||
* Archive = soft delete: companies.archived_at is stamped via
|
||||
* POST /api/company/[id]/delete. All bookkeeping data is retained per
|
||||
* BFL 7 kap. 2§; the row just disappears from the user's UI.
|
||||
*
|
||||
* TODO(bankid): once users have a linked BankID identity, wrap the
|
||||
* confirm step in a BankID signature gate. Guarded behind a
|
||||
* capabilities.bankIdLinked boolean fetched from the user profile.
|
||||
*/
|
||||
export function CompanyDangerZone() {
|
||||
const t = useTranslations('settings_company')
|
||||
const tRetention = useTranslations('retention_notice')
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
const { company, role } = useCompany()
|
||||
|
||||
const [showDialog, setShowDialog] = useState(false)
|
||||
const [showResetDialog, setShowResetDialog] = useState(false)
|
||||
const [confirmText, setConfirmText] = useState('')
|
||||
const [isDeleting, setIsDeleting] = useState(false)
|
||||
|
||||
if (!company || role !== 'owner') return null
|
||||
|
||||
async function handleDelete() {
|
||||
if (!company) return
|
||||
if (confirmText.trim() !== company.name.trim()) return
|
||||
|
||||
setIsDeleting(true)
|
||||
try {
|
||||
const res = await fetch(`/api/company/${company.id}/delete`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ confirm_name: confirmText }),
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}))
|
||||
throw new Error(body.error || t('danger_delete_failed_default'))
|
||||
}
|
||||
|
||||
toast({ title: t('danger_deleted_title'), description: company.name })
|
||||
// Stay inside settings. If the user had another company, the dashboard
|
||||
// layout will resolve it and /settings/account still renders as
|
||||
// normal. If this was their last company, the layout falls into the
|
||||
// no-company shell rooted at /settings/account.
|
||||
router.push('/settings/account')
|
||||
router.refresh()
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: t('danger_delete_failed_title'),
|
||||
description: err instanceof Error ? getUserErrorMessage(err) : t('danger_try_again'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
setIsDeleting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<CompanyMigrationArchiveRow companyId={company.id} />
|
||||
|
||||
<SettingsDangerZone label={t('danger_heading')}>
|
||||
<SettingsRow label={t('reset_row_label')}>
|
||||
{/* Both destructive rows say up front that a typed confirmation
|
||||
follows. A reader who does not dare press the link cannot find
|
||||
that out any other way, and on a phone the link sits where a
|
||||
stray tap while scrolling lands (issue #2214). */}
|
||||
<div className="flex min-w-0 flex-col gap-0.5">
|
||||
<SettingsRowNote>{t('reset_row_note')}</SettingsRowNote>
|
||||
<SettingsRowNote>{t('danger_confirm_hint')}</SettingsRowNote>
|
||||
</div>
|
||||
<SettingsRowEnd>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowResetDialog(true)}
|
||||
className="text-sm font-medium text-destructive underline underline-offset-2 transition-colors duration-150 hover:text-destructive/80"
|
||||
>
|
||||
{t('reset_row_action')}
|
||||
</button>
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
<SettingsRow
|
||||
label={t('danger_button')}
|
||||
borderless
|
||||
// The full BFL retention copy (incl. the backup link) lives behind
|
||||
// the "?": the visible row stays one quiet line.
|
||||
help={<RetentionNotice variant="company" className="border-0 bg-transparent p-0" />}
|
||||
>
|
||||
<div className="flex min-w-0 flex-col gap-0.5">
|
||||
<SettingsRowNote>{tRetention('company_title')}</SettingsRowNote>
|
||||
<SettingsRowNote>{t('danger_confirm_hint')}</SettingsRowNote>
|
||||
</div>
|
||||
<SettingsRowEnd>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowDialog(true)}
|
||||
className="text-sm font-medium text-destructive underline underline-offset-2 transition-colors duration-150 hover:text-destructive/80"
|
||||
>
|
||||
{t('danger_button')}
|
||||
</button>
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
</SettingsDangerZone>
|
||||
|
||||
<Dialog
|
||||
open={showDialog}
|
||||
onOpenChange={(open) => {
|
||||
if (isDeleting) return
|
||||
setShowDialog(open)
|
||||
if (!open) setConfirmText('')
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
{/* data-ph-mask: the title interpolates the company name */}
|
||||
<DialogTitle data-ph-mask="">{t('danger_dialog_title', { companyName: company.name })}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t('danger_dialog_description', { appName: branding.appName.toLowerCase() })}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-2">
|
||||
{/* data-ph-mask: the label interpolates the company name */}
|
||||
<Label data-ph-mask="" htmlFor="company-delete-confirm">
|
||||
{t.rich('danger_confirm_label', {
|
||||
companyName: company.name,
|
||||
strong: (chunks) => <strong>{chunks}</strong>,
|
||||
})}
|
||||
</Label>
|
||||
<Input
|
||||
id="company-delete-confirm"
|
||||
value={confirmText}
|
||||
onChange={(e) => setConfirmText(e.target.value)}
|
||||
placeholder={company.name}
|
||||
autoComplete="off"
|
||||
// ph-no-capture: the placeholder is the company name, and
|
||||
// replay masking covers values, not attributes.
|
||||
className="ph-no-capture"
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setShowDialog(false)
|
||||
setConfirmText('')
|
||||
}}
|
||||
disabled={isDeleting}
|
||||
>
|
||||
{t('danger_cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={handleDelete}
|
||||
disabled={confirmText.trim() !== company.name.trim() || isDeleting}
|
||||
>
|
||||
{isDeleting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t('danger_deleting')}
|
||||
</>
|
||||
) : (
|
||||
t('danger_button')
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<CompanyMigrationResetDialog
|
||||
companyId={company.id}
|
||||
companyName={company.name}
|
||||
open={showResetDialog}
|
||||
onOpenChange={setShowResetDialog}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import {
|
||||
SettingsGroup,
|
||||
SettingsInput,
|
||||
SettingsRow,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import type { CompanySettings } from '@/types'
|
||||
|
||||
interface CompanyInfoFormProps {
|
||||
settings: CompanySettings
|
||||
}
|
||||
|
||||
export function CompanyInfoForm({ settings }: CompanyInfoFormProps) {
|
||||
const t = useTranslations('settings_company')
|
||||
const orgLocked = settings.onboarding_complete === true
|
||||
return (
|
||||
<SettingsGroup label={t('company_info_heading')}>
|
||||
<SettingsRow
|
||||
label={t('company_name_label')}
|
||||
htmlFor="company_name"
|
||||
help={t('company_name_help')}
|
||||
align="baseline"
|
||||
>
|
||||
<SettingsInput
|
||||
id="company_name"
|
||||
name="company_name"
|
||||
defaultValue={settings.company_name || ''}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow
|
||||
label={t('org_number_label')}
|
||||
htmlFor="org_number"
|
||||
help={orgLocked ? t('org_number_locked') : undefined}
|
||||
align="baseline"
|
||||
>
|
||||
<SettingsInput
|
||||
id="org_number"
|
||||
name="org_number"
|
||||
defaultValue={settings.org_number || ''}
|
||||
disabled={orgLocked}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow label={t('address_label')} htmlFor="address_line1" align="baseline">
|
||||
<SettingsInput
|
||||
id="address_line1"
|
||||
name="address_line1"
|
||||
defaultValue={settings.address_line1 || ''}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow label={t('postal_code_label')} htmlFor="postal_code" align="baseline">
|
||||
<SettingsInput
|
||||
id="postal_code"
|
||||
name="postal_code"
|
||||
defaultValue={settings.postal_code || ''}
|
||||
className="max-w-24 flex-none"
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow label={t('city_label')} htmlFor="city" align="baseline">
|
||||
<SettingsInput id="city" name="city" defaultValue={settings.city || ''} />
|
||||
</SettingsRow>
|
||||
<SettingsRow label={t('phone_label')} htmlFor="phone" align="baseline">
|
||||
<SettingsInput
|
||||
id="phone"
|
||||
name="phone"
|
||||
type="tel"
|
||||
defaultValue={settings.phone || ''}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow label={t('email_label')} htmlFor="email" align="baseline">
|
||||
<SettingsInput
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
defaultValue={settings.email || ''}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow label={t('website_label')} htmlFor="website" align="baseline">
|
||||
<SettingsInput
|
||||
id="website"
|
||||
name="website"
|
||||
defaultValue={settings.website || ''}
|
||||
placeholder="https://"
|
||||
/>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { AttnLine } from '@/components/ui/attn-line'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import {
|
||||
SettingsGroup,
|
||||
SettingsInput,
|
||||
SettingsRowNote,
|
||||
SettingsSelect,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import { parseCompanyMembersPayload } from '@/components/settings/members-payload'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
import { formatDateLong } from '@/lib/utils'
|
||||
import { Loader2, Plus, Trash2, Mail } from 'lucide-react'
|
||||
|
||||
interface CompanyMemberItem {
|
||||
id: string
|
||||
user_id: string
|
||||
email: string
|
||||
role: string
|
||||
source: 'direct' | 'team'
|
||||
joined_at: string
|
||||
is_current_user: boolean
|
||||
}
|
||||
|
||||
interface CompanyInvitation {
|
||||
id: string
|
||||
email: string
|
||||
role: string
|
||||
status: string
|
||||
expires_at: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* The shareable accept link from the latest invite response. Raw tokens are
|
||||
* never stored server-side (only their hash), so the link exists exactly
|
||||
* once: here, until the next navigation. Kept visible so a failed or absent
|
||||
* mail send (self-hosted without a mail provider, #1710) never dead-ends the
|
||||
* inviter. There is no re-send for company invites: revoke and re-invite.
|
||||
* provisioned = GoTrue created the account and sent its own invite mail
|
||||
* (AUTH_SIGNUPS_DISABLED path), so email_sent=false is not a failure there.
|
||||
*/
|
||||
interface ShareableInvite {
|
||||
email: string
|
||||
url: string
|
||||
sent: boolean
|
||||
provisioned: boolean
|
||||
}
|
||||
|
||||
export function CompanyMembersSection() {
|
||||
const t = useTranslations('settings_company')
|
||||
const errorLocale = useLocale() as ErrorLocale
|
||||
const { toast } = useToast()
|
||||
const { company } = useCompany()
|
||||
|
||||
const roleLabels: Record<string, string> = {
|
||||
owner: t('members_role_owner'),
|
||||
admin: t('members_role_admin'),
|
||||
member: t('members_role_member'),
|
||||
viewer: t('members_role_viewer'),
|
||||
}
|
||||
// null = the roster is not known: still loading, or the read failed
|
||||
// (loadError). A failed read must never render an apparently member-less
|
||||
// company: a consultant looking at an empty list re-invites people who are
|
||||
// already members. EmptyState-like rendering is reserved for a confirmed
|
||||
// empty read.
|
||||
const [members, setMembers] = useState<CompanyMemberItem[] | null>(null)
|
||||
const [invitations, setInvitations] = useState<CompanyInvitation[] | null>(null)
|
||||
// detail === null: transient, so the line carries a retry. A detail sentence
|
||||
// means the user has to act (an expired session) and a retry cannot help.
|
||||
const [loadError, setLoadError] = useState<{ detail: string | null } | null>(null)
|
||||
const [reloadKey, setReloadKey] = useState(0)
|
||||
const [inviteEmail, setInviteEmail] = useState('')
|
||||
const [inviteRole, setInviteRole] = useState<string>('viewer')
|
||||
const [isSending, setIsSending] = useState(false)
|
||||
const [removingId, setRemovingId] = useState<string | null>(null)
|
||||
const [revokingId, setRevokingId] = useState<string | null>(null)
|
||||
const [canInvite, setCanInvite] = useState(false)
|
||||
// Multi-user seat gate: true when inviting requires the paid plan
|
||||
// (multi_user frozen). The form is swapped for the upsell line; the POST's
|
||||
// own 403 stays the real enforcement.
|
||||
const [inviteRequiresUpgrade, setInviteRequiresUpgrade] = useState(false)
|
||||
const [shareInvite, setShareInvite] = useState<ShareableInvite | null>(null)
|
||||
|
||||
const fetchMembers = useCallback(async () => {
|
||||
setLoadError(null)
|
||||
try {
|
||||
const res = await fetch('/api/company/members')
|
||||
if (!res.ok) {
|
||||
// Not-JSON bodies (an HTML error page, an empty 502) leave null, and
|
||||
// getErrorMessage falls back to the status map.
|
||||
const body = await res.json().catch(() => null)
|
||||
const sessionGone = res.status === 401 || res.status === 403
|
||||
setMembers(null)
|
||||
setInvitations(null)
|
||||
setCanInvite(false)
|
||||
setLoadError({
|
||||
detail: sessionGone
|
||||
? getErrorMessage(body, { statusCode: res.status, locale: errorLocale })
|
||||
: null,
|
||||
})
|
||||
return
|
||||
}
|
||||
// A 200 whose body will not parse throws into the catch below; a 200
|
||||
// without the roster lists is a failed read too. Neither may become a
|
||||
// fabricated empty member list.
|
||||
const parsed = parseCompanyMembersPayload<CompanyMemberItem, CompanyInvitation>(
|
||||
await res.json(),
|
||||
)
|
||||
if (parsed === null) {
|
||||
setMembers(null)
|
||||
setInvitations(null)
|
||||
setCanInvite(false)
|
||||
setLoadError({ detail: null })
|
||||
return
|
||||
}
|
||||
setMembers(parsed.members)
|
||||
setInvitations(parsed.invitations)
|
||||
setCanInvite(parsed.canInvite)
|
||||
setInviteRequiresUpgrade(parsed.inviteRequiresUpgrade)
|
||||
} catch {
|
||||
setMembers(null)
|
||||
setInvitations(null)
|
||||
setCanInvite(false)
|
||||
setLoadError({ detail: null })
|
||||
}
|
||||
}, [errorLocale])
|
||||
|
||||
useEffect(() => {
|
||||
void fetchMembers()
|
||||
}, [fetchMembers, reloadKey])
|
||||
|
||||
const handleInvite = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
const email = inviteEmail.trim().toLowerCase()
|
||||
if (!email) return
|
||||
|
||||
setIsSending(true)
|
||||
try {
|
||||
const res = await fetch('/api/company/members/invite', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, role: inviteRole }),
|
||||
})
|
||||
const data = await res.json()
|
||||
|
||||
if (!res.ok) {
|
||||
toast({ title: data.error, variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
|
||||
const payload = (
|
||||
data as {
|
||||
data?: { email_sent?: boolean; user_provisioned?: boolean; inviteUrl?: string }
|
||||
} | null
|
||||
)?.data
|
||||
const sent = payload?.email_sent !== false
|
||||
const provisioned = payload?.user_provisioned === true
|
||||
// Persist the shareable link next to the pending list: a failed or
|
||||
// skipped send leaves the invitation valid, and the toast alone is too
|
||||
// easy to miss, so the recovery path stays visible on the page.
|
||||
if (payload?.inviteUrl) {
|
||||
setShareInvite({ email, url: payload.inviteUrl, sent, provisioned })
|
||||
}
|
||||
// The title must not claim a send that never happened (self-hosted
|
||||
// without a mail provider): 'created' when nothing was mailed.
|
||||
toast({
|
||||
title: sent || provisioned ? t('members_invite_sent_title') : t('members_invite_created_title'),
|
||||
description:
|
||||
sent || provisioned
|
||||
? t('members_invite_sent_description', { email })
|
||||
: t('members_invite_mail_not_sent'),
|
||||
})
|
||||
setInviteEmail('')
|
||||
setInviteRole('viewer')
|
||||
fetchMembers()
|
||||
} catch {
|
||||
toast({ title: t('members_invite_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setIsSending(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCopyInviteLink = async (url: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(url)
|
||||
toast({ title: t('members_invite_link_copied_toast') })
|
||||
} catch {
|
||||
toast({ title: t('members_invite_link_copy_failed'), variant: 'destructive' })
|
||||
}
|
||||
}
|
||||
|
||||
const handleRemoveMember = async (memberId: string) => {
|
||||
setRemovingId(memberId)
|
||||
try {
|
||||
const res = await fetch(`/api/company/members/${memberId}`, { method: 'DELETE' })
|
||||
const data = await res.json()
|
||||
|
||||
if (!res.ok) {
|
||||
toast({ title: data.error, variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
|
||||
toast({ title: t('members_removed') })
|
||||
fetchMembers()
|
||||
} catch {
|
||||
toast({ title: t('members_remove_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setRemovingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRevokeInvite = async (invite: CompanyInvitation) => {
|
||||
setRevokingId(invite.id)
|
||||
try {
|
||||
const res = await fetch(`/api/company/members/invite/${invite.id}`, { method: 'DELETE' })
|
||||
const data = await res.json()
|
||||
|
||||
if (!res.ok) {
|
||||
toast({ title: data.error, variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
|
||||
// A revoked invitation's link is dead: never keep offering it.
|
||||
setShareInvite((current) => (current?.email === invite.email ? null : current))
|
||||
toast({ title: t('members_invite_revoked') })
|
||||
fetchMembers()
|
||||
} catch {
|
||||
toast({ title: t('members_invite_revoke_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setRevokingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
if (members === null || invitations === null) {
|
||||
return (
|
||||
<div>
|
||||
{/* Live region always mounted while the roster is unknown, so the
|
||||
failure is announced when it appears, not merely inserted. */}
|
||||
<div role="status" aria-live="polite" className="min-w-0 px-1">
|
||||
{loadError && (
|
||||
<AttnLine
|
||||
action={
|
||||
loadError.detail
|
||||
? undefined
|
||||
: { label: t('members_load_retry'), onClick: () => setReloadKey((k) => k + 1) }
|
||||
}
|
||||
>
|
||||
{loadError.detail
|
||||
? `${t('members_load_failed')} ${loadError.detail}`
|
||||
: t('members_load_failed')}
|
||||
</AttnLine>
|
||||
)}
|
||||
</div>
|
||||
{!loadError && (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsGroup label={t('members_title')} help={t('members_invite_description')}>
|
||||
{/* Member rows: flat hairline list, no cards. */}
|
||||
{members.map((member) => (
|
||||
<div
|
||||
key={member.id}
|
||||
className="flex items-center gap-3 border-b border-border px-1 py-3"
|
||||
>
|
||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-muted/60">
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
{member.email.charAt(0).toUpperCase()}
|
||||
</span>
|
||||
</div>
|
||||
<p className="min-w-0 flex-1 truncate text-sm">
|
||||
{member.email}
|
||||
{member.is_current_user && (
|
||||
<span className="ml-1 text-muted-foreground">{t('members_you')}</span>
|
||||
)}
|
||||
</p>
|
||||
<span className="shrink-0 text-xs text-muted-foreground">
|
||||
{roleLabels[member.role] || member.role}
|
||||
{member.source === 'team' && <> · {t('members_team_badge')}</>}
|
||||
</span>
|
||||
{canInvite && !member.is_current_user && member.role !== 'owner' && member.source !== 'team' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive"
|
||||
aria-label={t('members_remove_aria')}
|
||||
onClick={() => handleRemoveMember(member.id)}
|
||||
disabled={removingId === member.id}
|
||||
>
|
||||
{removingId === member.id ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Pending invitations continue the same list, visually quieter. */}
|
||||
{invitations.map((inv) => (
|
||||
<div
|
||||
key={inv.id}
|
||||
className="flex items-center gap-3 border-b border-border px-1 py-3"
|
||||
>
|
||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-dashed border-border">
|
||||
<Mail className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
</div>
|
||||
<p className="min-w-0 flex-1 truncate text-sm text-muted-foreground">
|
||||
{inv.email}
|
||||
<span className="ml-1 text-xs">
|
||||
· {t('invitations_expires', { date: formatDateLong(inv.expires_at) })}
|
||||
</span>
|
||||
</p>
|
||||
<span className="shrink-0 text-xs text-muted-foreground">
|
||||
{roleLabels[inv.role] || inv.role}
|
||||
</span>
|
||||
{canInvite && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive"
|
||||
aria-label={t('members_revoke_aria')}
|
||||
onClick={() => handleRevokeInvite(inv)}
|
||||
disabled={revokingId === inv.id}
|
||||
>
|
||||
{revokingId === inv.id ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Shareable accept link from the latest invite: one sentence, not a
|
||||
banner. A send that failed or was skipped (no mail provider) is the
|
||||
page's single attn line; a sent or GoTrue-provisioned invite is a
|
||||
quiet muted line with the same copy action, since the link is a
|
||||
legitimate share path either way. The live region stays mounted
|
||||
(empty until a link exists) so the line is announced when it
|
||||
appears, not merely inserted; same reason as the roster block. */}
|
||||
{canInvite && (
|
||||
<div className={shareInvite ? 'px-1 pt-3' : undefined} role="status" aria-live="polite">
|
||||
{shareInvite &&
|
||||
(shareInvite.sent || shareInvite.provisioned ? (
|
||||
<p className="text-[12.5px] leading-5 text-muted-foreground">
|
||||
{t('members_invite_link_sent', { email: shareInvite.email })}{' '}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void handleCopyInviteLink(shareInvite.url)}
|
||||
className="underline underline-offset-2 hover:text-foreground"
|
||||
>
|
||||
{t('members_invite_link_copy_action')}
|
||||
</button>
|
||||
</p>
|
||||
) : (
|
||||
<AttnLine
|
||||
action={{
|
||||
label: t('members_invite_link_copy_action'),
|
||||
onClick: () => void handleCopyInviteLink(shareInvite.url),
|
||||
}}
|
||||
>
|
||||
{t('members_invite_link_not_sent', { email: shareInvite.email })}
|
||||
</AttnLine>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Multi-user seat gate: no invite form without the paid plan. One
|
||||
muted sentence with the billing link, not a dead form. */}
|
||||
{canInvite && inviteRequiresUpgrade && (
|
||||
<p className="px-1 pt-3 text-[12.5px] leading-5 text-muted-foreground">
|
||||
{t('members_invite_upgrade')}{' '}
|
||||
<Link
|
||||
href="/settings/billing"
|
||||
className="underline underline-offset-2 hover:text-foreground"
|
||||
>
|
||||
{t('members_invite_upgrade_cta')}
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Inline invite: the list's own last row instead of a separate card. */}
|
||||
{canInvite && !inviteRequiresUpgrade && (
|
||||
<form onSubmit={handleInvite} className="flex flex-col gap-3 px-1 pt-3 sm:flex-row sm:items-center">
|
||||
<label htmlFor="company-invite-email" className="sr-only">
|
||||
{t('members_invite_email_label')}
|
||||
</label>
|
||||
<SettingsInput
|
||||
id="company-invite-email"
|
||||
type="email"
|
||||
placeholder={t('members_invite_email_placeholder')}
|
||||
value={inviteEmail}
|
||||
onChange={(e) => setInviteEmail(e.target.value)}
|
||||
disabled={isSending}
|
||||
required
|
||||
className="border-border sm:flex-1"
|
||||
/>
|
||||
<SettingsSelect
|
||||
value={inviteRole}
|
||||
onChange={(e) => setInviteRole(e.target.value)}
|
||||
aria-label={t('members_role_label')}
|
||||
>
|
||||
<option value="viewer">{t('members_role_viewer')}</option>
|
||||
<option value="member">{t('members_role_member')}</option>
|
||||
<option value="admin">{t('members_role_admin')}</option>
|
||||
</SettingsSelect>
|
||||
<Button type="submit" size="sm" disabled={isSending || !inviteEmail.trim()}>
|
||||
{isSending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
{t('members_invite_button')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<p className="px-1 pt-3">
|
||||
<SettingsRowNote>
|
||||
{t('members_count', { count: members.length, companyName: company?.name ?? '' })}
|
||||
</SettingsRowNote>
|
||||
</p>
|
||||
</SettingsGroup>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { FullArchiveDialog } from '@/components/import/FullArchiveDialog'
|
||||
import {
|
||||
SettingsGroup,
|
||||
SettingsRow,
|
||||
SettingsRowEnd,
|
||||
SettingsRowNote,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import type { ApiResponse, ArchiveEstimate } from '@/types'
|
||||
|
||||
const ESTIMATE_RETRY_DELAY_MS = 1_000
|
||||
const ESTIMATE_MAX_ATTEMPTS = 3
|
||||
|
||||
export function CompanyMigrationArchiveRow({ companyId }: { companyId: string }) {
|
||||
const t = useTranslations('settings_company')
|
||||
const [loadedEstimate, setLoadedEstimate] = useState<{
|
||||
companyId: string
|
||||
value: ArchiveEstimate
|
||||
} | null>(null)
|
||||
const [open, setOpen] = useState(false)
|
||||
const estimate = loadedEstimate?.companyId === companyId
|
||||
? loadedEstimate.value
|
||||
: null
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
let cancelled = false
|
||||
let retryTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const scheduleRetry = (attempt: number) => {
|
||||
if (cancelled || attempt >= ESTIMATE_MAX_ATTEMPTS) return
|
||||
retryTimer = setTimeout(() => {
|
||||
void loadEstimate(attempt + 1)
|
||||
}, ESTIMATE_RETRY_DELAY_MS)
|
||||
}
|
||||
|
||||
const loadEstimate = async (attempt: number) => {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/company/${companyId}/migration-reset/archive?estimate=1`,
|
||||
{ signal: controller.signal },
|
||||
)
|
||||
if (!response.ok) {
|
||||
if (response.status >= 500 || response.status === 429) scheduleRetry(attempt)
|
||||
return
|
||||
}
|
||||
const body = await response.json() as ApiResponse<ArchiveEstimate>
|
||||
if (!cancelled && body.data) {
|
||||
setLoadedEstimate({ companyId, value: body.data })
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof DOMException && error.name === 'AbortError') return
|
||||
scheduleRetry(attempt)
|
||||
}
|
||||
}
|
||||
|
||||
void loadEstimate(1)
|
||||
return () => {
|
||||
cancelled = true
|
||||
if (retryTimer) clearTimeout(retryTimer)
|
||||
controller.abort()
|
||||
}
|
||||
}, [companyId])
|
||||
|
||||
if (!estimate) return null
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsGroup label={t('reset_archive_group_label')}>
|
||||
<SettingsRow label={t('reset_archive_row_label')} borderless>
|
||||
<SettingsRowNote>
|
||||
{t('reset_archive_row_note', { count: estimate.document_count })}
|
||||
</SettingsRowNote>
|
||||
<SettingsRowEnd>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(true)}
|
||||
className="text-sm font-medium text-foreground underline underline-offset-2 transition-colors duration-150 hover:text-foreground/70"
|
||||
>
|
||||
{t('reset_archive_row_action')}
|
||||
</button>
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
|
||||
<FullArchiveDialog
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
mode="migration-reset-source"
|
||||
companyId={companyId}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { AlertTriangle, Archive, Loader2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { getBranding } from '@/lib/branding/service'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { useFormat } from '@/lib/hooks/use-format'
|
||||
import {
|
||||
COMPANY_MIGRATION_RESET_COUNT_KEYS,
|
||||
type CompanyMigrationResetBlocker,
|
||||
type CompanyMigrationResetEligibility,
|
||||
} from '@/types'
|
||||
|
||||
interface CompanyMigrationResetDialogProps {
|
||||
companyId: string
|
||||
companyName: string
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
const branding = getBranding()
|
||||
|
||||
function readApiError(body: unknown, fallback: string): string {
|
||||
if (!body || typeof body !== 'object') return fallback
|
||||
const error = (body as { error?: unknown }).error
|
||||
if (typeof error === 'string') return error
|
||||
if (error && typeof error === 'object') {
|
||||
const message = (error as { message?: unknown }).message
|
||||
if (typeof message === 'string') return message
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
export function CompanyMigrationResetDialog({
|
||||
companyId,
|
||||
companyName,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: CompanyMigrationResetDialogProps) {
|
||||
const t = useTranslations('settings_company')
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
const { formatDateLong } = useFormat()
|
||||
const loadFailedMessage = t('reset_load_failed')
|
||||
const [eligibility, setEligibility] = useState<CompanyMigrationResetEligibility | null>(null)
|
||||
const [loadError, setLoadError] = useState<string | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [isResetting, setIsResetting] = useState(false)
|
||||
const [reason, setReason] = useState('')
|
||||
const [confirmName, setConfirmName] = useState('')
|
||||
const [confirmedNoFilings, setConfirmedNoFilings] = useState(false)
|
||||
const [confirmedArchive, setConfirmedArchive] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
|
||||
let cancelled = false
|
||||
async function loadEligibility() {
|
||||
setIsLoading(true)
|
||||
setLoadError(null)
|
||||
setEligibility(null)
|
||||
try {
|
||||
const response = await fetch(`/api/company/${companyId}/migration-reset`, {
|
||||
cache: 'no-store',
|
||||
})
|
||||
const body = await response.json().catch(() => ({}))
|
||||
if (!response.ok) {
|
||||
throw new Error(readApiError(body, loadFailedMessage))
|
||||
}
|
||||
if (!cancelled) setEligibility(body.data as CompanyMigrationResetEligibility)
|
||||
} catch (error) {
|
||||
if (!cancelled) {
|
||||
setLoadError(
|
||||
error instanceof Error ? getUserErrorMessage(error) : loadFailedMessage,
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
void loadEligibility()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [companyId, loadFailedMessage, open])
|
||||
|
||||
function resetForm() {
|
||||
setEligibility(null)
|
||||
setLoadError(null)
|
||||
setReason('')
|
||||
setConfirmName('')
|
||||
setConfirmedNoFilings(false)
|
||||
setConfirmedArchive(false)
|
||||
}
|
||||
|
||||
function handleOpenChange(nextOpen: boolean) {
|
||||
if (isResetting) return
|
||||
onOpenChange(nextOpen)
|
||||
if (!nextOpen) resetForm()
|
||||
}
|
||||
|
||||
function blockerMessage(blocker: CompanyMigrationResetBlocker): string {
|
||||
switch (blocker.code) {
|
||||
case 'migration_window_expired':
|
||||
return t('reset_blocker_window', {
|
||||
date: eligibility ? formatDateLong(eligibility.window_ends_at) : '',
|
||||
})
|
||||
case 'sandbox_company':
|
||||
return t('reset_blocker_sandbox')
|
||||
case 'locked_or_closed_periods':
|
||||
return t('reset_blocker_periods', { count: blocker.count })
|
||||
case 'authority_submission_detected':
|
||||
return t('reset_blocker_filings', { count: blocker.count })
|
||||
case 'live_bank_connections':
|
||||
return t('reset_blocker_bank_connections', { count: blocker.count })
|
||||
case 'imports_in_progress':
|
||||
return t('reset_blocker_imports', { count: blocker.count })
|
||||
case 'active_integrations_or_schedules':
|
||||
return t('reset_blocker_automations', { count: blocker.count })
|
||||
case 'background_work_in_progress':
|
||||
return t('reset_blocker_background_work', { count: blocker.count })
|
||||
default:
|
||||
return t('reset_blocker_other')
|
||||
}
|
||||
}
|
||||
|
||||
function countLabel(key: (typeof COMPANY_MIGRATION_RESET_COUNT_KEYS)[number]): string {
|
||||
switch (key) {
|
||||
case 'journal_entries': return t('reset_count_journal_entries')
|
||||
case 'journal_entry_lines': return t('reset_count_journal_entry_lines')
|
||||
case 'committed_import_entries': return t('reset_count_committed_import_entries')
|
||||
case 'transactions': return t('reset_count_transactions')
|
||||
case 'fiscal_periods': return t('reset_count_fiscal_periods')
|
||||
case 'documents': return t('reset_count_documents')
|
||||
case 'voucher_sequences': return t('reset_count_voucher_sequences')
|
||||
case 'sie_imports': return t('reset_count_sie_imports')
|
||||
case 'bank_file_imports': return t('reset_count_bank_file_imports')
|
||||
case 'skattekonto_file_imports': return t('reset_count_skattekonto_file_imports')
|
||||
case 'bank_connections': return t('reset_count_bank_connections')
|
||||
case 'customers': return t('reset_count_customers')
|
||||
case 'suppliers': return t('reset_count_suppliers')
|
||||
case 'invoices': return t('reset_count_invoices')
|
||||
case 'supplier_invoices': return t('reset_count_supplier_invoices')
|
||||
}
|
||||
}
|
||||
|
||||
const confirmationName = eligibility?.display_name ?? companyName
|
||||
const canReset = eligibility?.eligible === true
|
||||
&& reason.trim().length >= 20
|
||||
&& confirmName.trim() === confirmationName.trim()
|
||||
&& confirmedNoFilings
|
||||
&& confirmedArchive
|
||||
&& !isResetting
|
||||
|
||||
async function handleReset() {
|
||||
if (!canReset) return
|
||||
setIsResetting(true)
|
||||
try {
|
||||
const response = await fetch(`/api/company/${companyId}/migration-reset`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
confirm_name: confirmName,
|
||||
reason,
|
||||
confirm_no_filed_declarations: confirmedNoFilings,
|
||||
confirm_retained_archive: confirmedArchive,
|
||||
}),
|
||||
})
|
||||
const body = await response.json().catch(() => ({}))
|
||||
if (!response.ok) {
|
||||
throw new Error(readApiError(body, t('reset_failed_default')))
|
||||
}
|
||||
|
||||
toast({
|
||||
title: t('reset_success_title'),
|
||||
description: t('reset_success_description'),
|
||||
})
|
||||
setIsResetting(false)
|
||||
onOpenChange(false)
|
||||
resetForm()
|
||||
router.push('/import')
|
||||
router.refresh()
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t('reset_failed_title'),
|
||||
description: error instanceof Error
|
||||
? getUserErrorMessage(error)
|
||||
: t('reset_failed_default'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
setIsResetting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle data-ph-mask="">
|
||||
{t('reset_dialog_title', { companyName })}
|
||||
</DialogTitle>
|
||||
<DialogDescription>{t('reset_dialog_description')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex min-h-40 items-center justify-center text-muted-foreground">
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t('reset_checking')}
|
||||
</div>
|
||||
) : loadError ? (
|
||||
<div className="rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive">
|
||||
{loadError}
|
||||
</div>
|
||||
) : eligibility ? (
|
||||
<div className="space-y-5">
|
||||
<div className="flex gap-3 rounded-lg border border-border bg-muted/40 p-4">
|
||||
<Archive className="mt-0.5 h-5 w-5 shrink-0 text-muted-foreground" />
|
||||
<div className="space-y-1 text-sm">
|
||||
<p className="font-medium text-foreground">{t('reset_archive_title')}</p>
|
||||
<p className="text-muted-foreground">{t('reset_archive_description')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{eligibility.blockers.length > 0 ? (
|
||||
<div className="space-y-2 rounded-lg border border-destructive/30 bg-destructive/5 p-4">
|
||||
<div className="flex items-center gap-2 text-sm font-medium text-destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
{t('reset_blocked_title')}
|
||||
</div>
|
||||
<ul className="list-disc space-y-1 pl-5 text-sm text-muted-foreground">
|
||||
{eligibility.blockers.map((blocker) => (
|
||||
<li key={blocker.code}>{blockerMessage(blocker)}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div>
|
||||
<h3 className="mb-2 text-sm font-medium">{t('reset_retained_heading')}</h3>
|
||||
<dl className="divide-y divide-border border-y border-border">
|
||||
{COMPANY_MIGRATION_RESET_COUNT_KEYS.map((key) => (
|
||||
<div key={key} className="flex items-center justify-between py-2 text-sm">
|
||||
<dt className="text-muted-foreground">{countLabel(key)}</dt>
|
||||
<dd className="tabular-nums font-medium">{eligibility.counts[key] ?? 0}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
{eligibility.eligible ? (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="migration-reset-reason">{t('reset_reason_label')}</Label>
|
||||
<Textarea
|
||||
id="migration-reset-reason"
|
||||
value={reason}
|
||||
onChange={(event) => setReason(event.target.value)}
|
||||
placeholder={t('reset_reason_placeholder')}
|
||||
maxLength={1000}
|
||||
data-ph-mask=""
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('reset_reason_help', { count: reason.trim().length })}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<Checkbox
|
||||
id="migration-reset-no-filings"
|
||||
checked={confirmedNoFilings}
|
||||
onCheckedChange={(checked) => setConfirmedNoFilings(checked === true)}
|
||||
/>
|
||||
<Label htmlFor="migration-reset-no-filings" className="font-normal leading-5">
|
||||
{t('reset_confirm_no_filings', { appName: branding.appName })}
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<Checkbox
|
||||
id="migration-reset-retained"
|
||||
checked={confirmedArchive}
|
||||
onCheckedChange={(checked) => setConfirmedArchive(checked === true)}
|
||||
/>
|
||||
<Label htmlFor="migration-reset-retained" className="font-normal leading-5">
|
||||
{t('reset_confirm_archive')}
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label data-ph-mask="" htmlFor="migration-reset-name">
|
||||
{t.rich('reset_confirm_name', {
|
||||
companyName: confirmationName,
|
||||
strong: (chunks) => <strong>{chunks}</strong>,
|
||||
})}
|
||||
</Label>
|
||||
<Input
|
||||
id="migration-reset-name"
|
||||
value={confirmName}
|
||||
onChange={(event) => setConfirmName(event.target.value)}
|
||||
placeholder={confirmationName}
|
||||
autoComplete="off"
|
||||
className="ph-no-capture"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => handleOpenChange(false)} disabled={isResetting}>
|
||||
{t('danger_cancel')}
|
||||
</Button>
|
||||
{eligibility?.eligible ? (
|
||||
<Button variant="destructive" onClick={handleReset} disabled={!canReset}>
|
||||
{isResetting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t('reset_resetting')}
|
||||
</>
|
||||
) : t('reset_submit')}
|
||||
</Button>
|
||||
) : null}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { CompanyProfileView } from '@/components/settings/CompanyProfileView'
|
||||
import { refreshCompanyProfileAction } from '@/lib/company/tic-refresh'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import {
|
||||
SettingsGroup,
|
||||
SettingsInput,
|
||||
SettingsRow,
|
||||
SettingsRowNote,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import { formatDateLong } from '@/lib/utils'
|
||||
|
||||
type Snapshot = Parameters<typeof CompanyProfileView>[0]['snapshot']
|
||||
|
||||
const ERROR_MESSAGES: Record<string, string> = {
|
||||
org_number_invalid: 'Ogiltigt organisations- eller personnummer.',
|
||||
not_found: 'Inga bolagsuppgifter hittades för det numret.',
|
||||
unauthorized: 'Du har inte behörighet att hämta uppgifter.',
|
||||
persist_failed: 'Något gick fel. Försök igen.',
|
||||
}
|
||||
|
||||
// Företagsprofil: the cached TIC company snapshot (Bolagsuppgifter), rendered
|
||||
// as a read-only section on the Företag tab. Fetched client-side (low-traffic
|
||||
// settings) so it sits alongside the client-rendered company form. RLS scopes
|
||||
// the read to the user's own company. The trailing "Hämta" row lets the user
|
||||
// (re)fetch live when the snapshot is missing or wrong: the recovery path for
|
||||
// an enskild firma whose personnummer previously resolved to the wrong entity.
|
||||
export function CompanyProfileSection() {
|
||||
const { company } = useCompany()
|
||||
const [snapshot, setSnapshot] = useState<Snapshot>(null)
|
||||
const [fetchedAt, setFetchedAt] = useState<string | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const [orgInput, setOrgInput] = useState('')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!company?.id) return
|
||||
const supabase = createClient()
|
||||
let cancelled = false
|
||||
supabase
|
||||
.from('companies')
|
||||
.select('tic_snapshot, tic_snapshot_fetched_at, org_number')
|
||||
.eq('id', company.id)
|
||||
.maybeSingle()
|
||||
.then(({ data }) => {
|
||||
if (cancelled) return
|
||||
setSnapshot((data?.tic_snapshot as Snapshot) ?? null)
|
||||
setFetchedAt((data?.tic_snapshot_fetched_at as string | null) ?? null)
|
||||
setOrgInput((data?.org_number as string | null) ?? '')
|
||||
setLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [company?.id])
|
||||
|
||||
async function handleFetch(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
if (!company?.id || submitting) return
|
||||
setSubmitting(true)
|
||||
setError(null)
|
||||
const result = await refreshCompanyProfileAction(company.id, orgInput)
|
||||
if (result.ok) {
|
||||
setSnapshot((result.snapshot as Snapshot) ?? null)
|
||||
setFetchedAt(result.fetchedAt ?? null)
|
||||
} else {
|
||||
setError(ERROR_MESSAGES[result.error ?? ''] ?? ERROR_MESSAGES.persist_failed)
|
||||
}
|
||||
setSubmitting(false)
|
||||
}
|
||||
|
||||
if (loading) return <Skeleton className="h-48 w-full rounded-lg" />
|
||||
|
||||
return (
|
||||
<SettingsGroup label="Bolagsuppgifter">
|
||||
<CompanyProfileView snapshot={snapshot} />
|
||||
|
||||
<SettingsRow
|
||||
label={snapshot ? 'Uppdatera bolagsuppgifter' : 'Hämta bolagsuppgifter'}
|
||||
help="Uppgifterna hämtas från Bolagsverket. För enskild firma anges personnumret."
|
||||
borderless
|
||||
>
|
||||
<form
|
||||
onSubmit={handleFetch}
|
||||
className="flex min-w-0 flex-1 flex-wrap items-center gap-x-3 gap-y-1"
|
||||
>
|
||||
<SettingsInput
|
||||
id="tic_org_number"
|
||||
aria-label="Organisationsnummer eller personnummer"
|
||||
value={orgInput}
|
||||
onChange={(e) => setOrgInput(e.target.value)}
|
||||
placeholder="XXXXXX-XXXX"
|
||||
inputMode="numeric"
|
||||
autoComplete="off"
|
||||
className="max-w-xs tabular-nums"
|
||||
/>
|
||||
<Button type="submit" size="sm" disabled={submitting || !orgInput.trim()}>
|
||||
{submitting ? (
|
||||
<>
|
||||
<Loader2 className="animate-spin" />
|
||||
Hämtar…
|
||||
</>
|
||||
) : (
|
||||
'Hämta'
|
||||
)}
|
||||
</Button>
|
||||
{fetchedAt && (
|
||||
<SettingsRowNote>Uppdaterad {formatDateLong(fetchedAt)}</SettingsRowNote>
|
||||
)}
|
||||
{error && <span className="basis-full text-xs text-destructive">{error}</span>}
|
||||
</form>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import { SettingsRow, SettingsRowNote } from '@/components/settings/SettingsRows'
|
||||
|
||||
// Read-only "Bolagsuppgifter" view of the cached TIC company profile
|
||||
// (companies.tic_snapshot), rendered as flat settings rows inside the
|
||||
// section's SettingsGroup. Lives in core: reads the snapshot as plain
|
||||
// JSON rather than importing the TIC extension's types, so the
|
||||
// core-build CI boundary (no core → @/extensions/) stays intact.
|
||||
//
|
||||
// The snapshot is written by the TIC /profile endpoint; shape mirrors
|
||||
// TICCompanyProfile. We type only the fields we render and treat
|
||||
// everything as optional/defensive since older snapshots predate some
|
||||
// sections.
|
||||
|
||||
interface SnapshotShape {
|
||||
companyName?: string | null
|
||||
orgNumber?: string | null
|
||||
legalEntityType?: string | null
|
||||
address?: { street?: string | null; postalCode?: string | null; city?: string | null } | null
|
||||
registration?: { fTax?: boolean; vat?: boolean; payroll?: boolean } | null
|
||||
sniCodes?: { code: string; name: string }[] | null
|
||||
bankAccounts?: { type: string; accountNumber: string; bic?: string | null }[] | null
|
||||
purpose?: string | null
|
||||
employeeRange?: string | null
|
||||
financials?: {
|
||||
periodStart?: number
|
||||
periodEnd?: number
|
||||
netSalesK?: number | null
|
||||
operatingProfitK?: number | null
|
||||
} | null
|
||||
statuses?: {
|
||||
code?: string | null
|
||||
description?: string | null
|
||||
color?: 'red' | 'yellow' | 'green' | 'neutral' | string | null
|
||||
statusDate?: string | null
|
||||
isCeased?: boolean | null
|
||||
}[] | null
|
||||
fiscalYear?: { startMonthDay?: string | null; endMonthDay?: string | null } | null
|
||||
signatory?: { description: string }[] | null
|
||||
board?: {
|
||||
numberOfBoardMembers?: number | null
|
||||
numberOfDeputyBoardMembers?: number | null
|
||||
} | null
|
||||
representatives?: {
|
||||
name?: string | null
|
||||
positionType?: string | null
|
||||
positionStart?: string | null
|
||||
}[] | null
|
||||
}
|
||||
|
||||
// Clean Bolagsverket signatory text: the source carries ">" list markers
|
||||
// and collapses several rules onto one line. Strip the markers, normalise
|
||||
// whitespace, and split run-on "Firman tecknas …" clauses onto their own
|
||||
// lines so each rule reads as a sentence.
|
||||
function cleanSignatory(raw: string | null | undefined): string[] {
|
||||
// The snapshot is unvalidated registry JSON: `description` is declared
|
||||
// required inside an interface whose every other field is optional, so a
|
||||
// signatory row without one would throw here and blank the settings panel.
|
||||
if (!raw) return []
|
||||
const normalised = raw
|
||||
.replace(/>/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
// Each firmateckningsregel starts with "Firman tecknas". Split on the
|
||||
// boundary before subsequent occurrences so they stack vertically.
|
||||
return normalised
|
||||
.split(/(?=Firman tecknas)/g)
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s.length > 0)
|
||||
}
|
||||
|
||||
export function CompanyProfileView({ snapshot }: { snapshot: SnapshotShape | null }) {
|
||||
if (!snapshot) {
|
||||
// Dynamic status (nothing fetched yet): stays visible as a quiet line.
|
||||
return (
|
||||
<p className="border-b border-border px-1 py-3 text-sm text-muted-foreground">
|
||||
Inga företagsuppgifter hämtade ännu. Uppgifterna hämtas automatiskt
|
||||
från Bolagsverket via organisationsnumret.
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
const entityLabel =
|
||||
snapshot.legalEntityType === 'AB'
|
||||
? 'Aktiebolag'
|
||||
: snapshot.legalEntityType === 'EF'
|
||||
? 'Enskild firma'
|
||||
: snapshot.legalEntityType ?? null
|
||||
|
||||
const reg = snapshot.registration
|
||||
const regBadges = [
|
||||
reg?.fTax ? 'F-skatt' : null,
|
||||
reg?.vat ? 'Moms' : null,
|
||||
reg?.payroll ? 'Arbetsgivare' : null,
|
||||
].filter(Boolean) as string[]
|
||||
|
||||
const fyLabel =
|
||||
snapshot.fiscalYear?.startMonthDay && snapshot.fiscalYear?.endMonthDay
|
||||
? `${snapshot.fiscalYear.startMonthDay} till ${snapshot.fiscalYear.endMonthDay}`
|
||||
: null
|
||||
|
||||
// Only show dated status entries: Bolagsverket emits informational
|
||||
// flags like "Har aldrig varit verksam" with no date that read as
|
||||
// noise next to the real ones. Plain text, no colour: per the
|
||||
// design system, semantic colour is data-only and never chrome.
|
||||
const datedStatuses = (snapshot.statuses ?? []).filter((s) => s.statusDate)
|
||||
|
||||
// Flatten every signatory row, clean ">" markers, split run-on
|
||||
// clauses, and dedupe: the source repeats "Firman tecknas av
|
||||
// styrelsen" across rows.
|
||||
const signatoryRules = Array.from(
|
||||
new Set(
|
||||
(snapshot.signatory ?? []).flatMap((s) => cleanSignatory(s.description)),
|
||||
),
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsRow label="Företag">
|
||||
<span className="text-foreground">{snapshot.companyName ?? 'Okänt företag'}</span>
|
||||
{(snapshot.orgNumber || entityLabel) && (
|
||||
<SettingsRowNote className="tabular-nums">
|
||||
{[snapshot.orgNumber, entityLabel].filter(Boolean).join(' · ')}
|
||||
</SettingsRowNote>
|
||||
)}
|
||||
</SettingsRow>
|
||||
|
||||
{snapshot.address && (
|
||||
<SettingsRow label="Adress">
|
||||
<span className="text-muted-foreground">
|
||||
{[
|
||||
snapshot.address.street,
|
||||
[snapshot.address.postalCode, snapshot.address.city].filter(Boolean).join(' '),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(', ')}
|
||||
</span>
|
||||
</SettingsRow>
|
||||
)}
|
||||
|
||||
{regBadges.length > 0 && (
|
||||
<SettingsRow label="Registrerat för">
|
||||
{regBadges.map((b) => (
|
||||
<Badge key={b} variant="secondary" className="font-normal">{b}</Badge>
|
||||
))}
|
||||
</SettingsRow>
|
||||
)}
|
||||
|
||||
{Array.isArray(snapshot.sniCodes) && snapshot.sniCodes.length > 0 && (
|
||||
<SettingsRow label="SNI-koder" align="baseline">
|
||||
<ul className="w-full space-y-1">
|
||||
{snapshot.sniCodes.map((s) => (
|
||||
<li key={s.code} className="text-sm tabular-nums">
|
||||
<span className="text-foreground">{s.code}</span>{' '}
|
||||
<span className="text-muted-foreground">{s.name}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</SettingsRow>
|
||||
)}
|
||||
|
||||
{Array.isArray(snapshot.bankAccounts) && snapshot.bankAccounts.length > 0 && (
|
||||
<SettingsRow label="Bankuppgifter" align="baseline">
|
||||
{/* Registry read-out, not a setting: without the note this row makes
|
||||
the bankgiro look configured while payment files and invoices
|
||||
read the editable fields under Fakturering. */}
|
||||
<div className="w-full space-y-1">
|
||||
<ul className="space-y-1">
|
||||
{snapshot.bankAccounts.map((b, i) => (
|
||||
<li key={`${b.type}-${b.accountNumber}-${i}`} className="text-sm tabular-nums">
|
||||
<span className="text-muted-foreground">{b.type}:</span>{' '}
|
||||
<span className="text-foreground">{b.accountNumber}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<SettingsRowNote className="block">
|
||||
Enligt Bolagsverket. Fakturor och betalfiler använder bankuppgifterna
|
||||
under Inställningar → Fakturering.
|
||||
</SettingsRowNote>
|
||||
</div>
|
||||
</SettingsRow>
|
||||
)}
|
||||
|
||||
{snapshot.purpose && (
|
||||
<SettingsRow label="Verksamhet" align="baseline">
|
||||
<p className="text-sm leading-6 text-muted-foreground">{snapshot.purpose}</p>
|
||||
</SettingsRow>
|
||||
)}
|
||||
|
||||
<SettingsRow label="Anställda">
|
||||
<span className="text-muted-foreground">
|
||||
{snapshot.employeeRange ?? 'Inga anställda'}
|
||||
</span>
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow label="Senaste bokslut">
|
||||
{snapshot.financials ? (
|
||||
<>
|
||||
<span>
|
||||
<span className="text-muted-foreground">Nettoomsättning </span>
|
||||
<span className="tabular-nums">
|
||||
{snapshot.financials.netSalesK != null
|
||||
? `${snapshot.financials.netSalesK.toLocaleString('sv-SE')} tkr`
|
||||
: '-'}
|
||||
</span>
|
||||
</span>
|
||||
<span>
|
||||
<span className="text-muted-foreground">Rörelseresultat </span>
|
||||
<span className="tabular-nums">
|
||||
{snapshot.financials.operatingProfitK != null
|
||||
? `${snapshot.financials.operatingProfitK.toLocaleString('sv-SE')} tkr`
|
||||
: '-'}
|
||||
</span>
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-muted-foreground">Inga finansiella uppgifter tillgängliga.</span>
|
||||
)}
|
||||
</SettingsRow>
|
||||
|
||||
{datedStatuses.length > 0 && (
|
||||
<SettingsRow label="Status" align="baseline">
|
||||
<dl className="w-full space-y-1">
|
||||
{datedStatuses.map((s, i) => (
|
||||
<div key={`${s.code}-${i}`} className="flex items-center justify-between gap-3 text-sm">
|
||||
<dt className={s.isCeased ? 'text-destructive' : 'text-foreground'}>
|
||||
{s.description ?? s.code ?? '-'}
|
||||
</dt>
|
||||
<dd className="text-xs text-muted-foreground tabular-nums">
|
||||
{formatDate(s.statusDate!)}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</SettingsRow>
|
||||
)}
|
||||
|
||||
{fyLabel && (
|
||||
<SettingsRow label="Räkenskapsår">
|
||||
<span className="tabular-nums text-muted-foreground">Nuvarande: {fyLabel}</span>
|
||||
</SettingsRow>
|
||||
)}
|
||||
|
||||
{signatoryRules.length > 0 && (
|
||||
<SettingsRow label="Firmateckning" align="baseline">
|
||||
<ul className="w-full space-y-1">
|
||||
{signatoryRules.map((rule, i) => (
|
||||
<li key={i} className="text-sm leading-6 text-muted-foreground">
|
||||
{rule}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</SettingsRow>
|
||||
)}
|
||||
|
||||
{Array.isArray(snapshot.representatives) && snapshot.representatives.length > 0 && (
|
||||
<SettingsRow label="Företrädare" align="baseline">
|
||||
<div className="w-full">
|
||||
{snapshot.board && (
|
||||
<p className="mb-2 text-xs text-muted-foreground">
|
||||
{[
|
||||
snapshot.board.numberOfBoardMembers != null
|
||||
? `${snapshot.board.numberOfBoardMembers} styrelseledamot/-ledamöter`
|
||||
: null,
|
||||
snapshot.board.numberOfDeputyBoardMembers != null
|
||||
? `${snapshot.board.numberOfDeputyBoardMembers} suppleant(er)`
|
||||
: null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ')}
|
||||
</p>
|
||||
)}
|
||||
<ul className="space-y-1">
|
||||
{snapshot.representatives.map((r, i) => (
|
||||
<li key={`${r.name}-${i}`} className="flex items-center justify-between gap-3 text-sm">
|
||||
<span className="text-foreground">{r.name ?? '-'}</span>
|
||||
<span className="text-right text-xs text-muted-foreground">
|
||||
{[r.positionType, r.positionStart ? formatDate(r.positionStart) : null]
|
||||
.filter(Boolean)
|
||||
.join(' · ')}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</SettingsRow>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { Loader2, RefreshCw } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import {
|
||||
SettingsGroup,
|
||||
SettingsRow,
|
||||
SettingsRowEnd,
|
||||
SettingsRowNote,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import { isSelfHosted } from '@/lib/env/public-flags'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
|
||||
type UpstreamMode = 'connector' | 'own_credentials' | 'unconfigured'
|
||||
|
||||
interface ConnectorStatus {
|
||||
configured: boolean
|
||||
key_prefix: string | null
|
||||
upstreams: { bank: UpstreamMode; skatteverket: UpstreamMode }
|
||||
granted_capabilities: string[]
|
||||
}
|
||||
|
||||
interface SyncResult {
|
||||
outcome: 'not_configured' | 'synced' | 'revoked' | 'network_error' | 'server_error'
|
||||
grantsUpserted: number
|
||||
scopes?: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings -> Abonnemang, self-host only: is the connector wired, per
|
||||
* upstream, and a "Synka nu" that runs the entitlement sync on demand
|
||||
* instead of waiting for the hourly cron (PR6b-3). Renders nothing on
|
||||
* hosted; the status endpoint's self_hosted:false answer is the backstop.
|
||||
*
|
||||
* The sync covers every company on the instance; the capability list shown
|
||||
* is the active company's (same as the status endpoint reports). That
|
||||
* asymmetry lives in the group help, not in the row copy.
|
||||
*/
|
||||
export function ConnectorSettingsSection() {
|
||||
const t = useTranslations('settings_billing')
|
||||
const errorLocale = useLocale() as ErrorLocale
|
||||
const { toast } = useToast()
|
||||
const [status, setStatus] = useState<ConnectorStatus | null>(null)
|
||||
const [loadFailed, setLoadFailed] = useState(false)
|
||||
const [syncing, setSyncing] = useState(false)
|
||||
const [reloadKey, setReloadKey] = useState(0)
|
||||
|
||||
const selfHosted = isSelfHosted()
|
||||
|
||||
useEffect(() => {
|
||||
if (!selfHosted) return
|
||||
let active = true
|
||||
setLoadFailed(false)
|
||||
fetch('/api/connector/status')
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw new Error(`status ${res.status}`)
|
||||
const body = (await res.json()) as { data?: { self_hosted?: boolean } & ConnectorStatus }
|
||||
if (!active) return
|
||||
if (!body.data || body.data.self_hosted !== true) {
|
||||
setStatus(null)
|
||||
return
|
||||
}
|
||||
setStatus(body.data)
|
||||
})
|
||||
.catch(() => {
|
||||
if (active) setLoadFailed(true)
|
||||
})
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [selfHosted, reloadKey])
|
||||
|
||||
const runSync = useCallback(async () => {
|
||||
setSyncing(true)
|
||||
try {
|
||||
const res = await fetch('/api/connector/sync', { method: 'POST' })
|
||||
const body = (await res.json().catch(() => null)) as
|
||||
| { data?: SyncResult; error?: unknown }
|
||||
| null
|
||||
if (!res.ok || !body?.data) {
|
||||
toast({
|
||||
title: t('connector_sync_failed'),
|
||||
description: getErrorMessage(body, { statusCode: res.status, locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
const result = body.data
|
||||
if (result.outcome === 'synced') {
|
||||
// Count capabilities, not grant rows: grantsUpserted is
|
||||
// companies x scopes and reads absurd on a multi-company instance.
|
||||
toast({
|
||||
title: t('connector_sync_done'),
|
||||
description:
|
||||
(result.scopes?.length ?? 0) > 0
|
||||
? t('connector_sync_done_desc', { count: result.scopes?.length ?? 0 })
|
||||
: t('connector_sync_done_empty'),
|
||||
})
|
||||
} else if (result.outcome === 'not_configured') {
|
||||
// The key vanished after the page loaded (operator reconfigured):
|
||||
// saying the hosted service was unreachable would be false.
|
||||
toast({
|
||||
title: t('connector_status_unconfigured'),
|
||||
description: t('connector_status_unconfigured_note'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} else if (result.outcome === 'revoked') {
|
||||
// The grants were just deleted: this must not read as a generic error.
|
||||
toast({
|
||||
title: t('connector_sync_failed'),
|
||||
description: t('connector_sync_revoked_desc'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} else {
|
||||
toast({
|
||||
title: t('connector_sync_failed'),
|
||||
description: t('connector_sync_unreachable_desc'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
setReloadKey((k) => k + 1)
|
||||
} catch {
|
||||
// fetch itself rejected (instance restarting, network drop): without
|
||||
// this the click is a silent no-op and the rejection goes unhandled.
|
||||
toast({
|
||||
title: t('connector_sync_failed'),
|
||||
description: t('connector_sync_request_failed_desc'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setSyncing(false)
|
||||
}
|
||||
}, [t, errorLocale, toast])
|
||||
|
||||
if (!selfHosted) return null
|
||||
if (!status && !loadFailed) return null
|
||||
|
||||
const modeLabel: Record<UpstreamMode, string> = {
|
||||
connector: t('connector_mode_connector'),
|
||||
own_credentials: t('connector_mode_own'),
|
||||
unconfigured: t('connector_mode_unconfigured'),
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsGroup label={t('connector_group')} help={t('connector_help')}>
|
||||
{loadFailed || !status ? (
|
||||
<SettingsRow label={t('connector_row_status')} borderless>
|
||||
<SettingsRowNote>{t('connector_load_failed')}</SettingsRowNote>
|
||||
<SettingsRowEnd>
|
||||
<Button variant="outline" size="sm" onClick={() => setReloadKey((k) => k + 1)}>
|
||||
{t('load_retry')}
|
||||
</Button>
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
) : (
|
||||
<>
|
||||
<SettingsRow label={t('connector_row_status')}>
|
||||
{status.configured ? (
|
||||
<>
|
||||
<span className="font-medium">{t('connector_status_configured')}</span>
|
||||
{status.key_prefix ? (
|
||||
<span className="font-mono text-xs text-muted-foreground">{status.key_prefix}…</span>
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span>{t('connector_status_unconfigured')}</span>
|
||||
<SettingsRowNote>{t('connector_status_unconfigured_note')}</SettingsRowNote>
|
||||
</>
|
||||
)}
|
||||
{status.configured ? (
|
||||
<SettingsRowEnd>
|
||||
<Button variant="outline" size="sm" disabled={syncing} onClick={runSync}>
|
||||
{syncing ? (
|
||||
<Loader2 aria-hidden="true" className="h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw aria-hidden="true" className="h-3.5 w-3.5" />
|
||||
)}
|
||||
<span>{syncing ? t('connector_sync_button_busy') : t('connector_sync_button')}</span>
|
||||
</Button>
|
||||
</SettingsRowEnd>
|
||||
) : null}
|
||||
</SettingsRow>
|
||||
<SettingsRow label={t('connector_row_bank')}>
|
||||
<span className={status.upstreams.bank === 'unconfigured' ? 'text-muted-foreground' : undefined}>
|
||||
{modeLabel[status.upstreams.bank]}
|
||||
</span>
|
||||
</SettingsRow>
|
||||
<SettingsRow label={t('connector_row_skv')}>
|
||||
<span className={status.upstreams.skatteverket === 'unconfigured' ? 'text-muted-foreground' : undefined}>
|
||||
{modeLabel[status.upstreams.skatteverket]}
|
||||
</span>
|
||||
</SettingsRow>
|
||||
<SettingsRow label={t('connector_row_capabilities')} borderless>
|
||||
{status.granted_capabilities.length > 0 ? (
|
||||
<span className="font-mono text-xs text-muted-foreground">
|
||||
{status.granted_capabilities.join(', ')}
|
||||
</span>
|
||||
) : (
|
||||
<SettingsRowNote>
|
||||
{status.configured ? t('connector_caps_none') : t('connector_caps_unconfigured')}
|
||||
</SettingsRowNote>
|
||||
)}
|
||||
</SettingsRow>
|
||||
</>
|
||||
)}
|
||||
</SettingsGroup>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { SettingsGroup } from '@/components/settings/SettingsRows'
|
||||
import { Loader2, Trash2, Users, ChevronDown, Pencil } from 'lucide-react'
|
||||
import { formatAccountWithName } from '@/lib/bookkeeping/client-account-names'
|
||||
import { formatCounterpartyName } from '@/lib/bookkeeping/counterparty-templates'
|
||||
import type { CategorizationTemplate } from '@/types'
|
||||
|
||||
function formatDate(iso: string | null) {
|
||||
if (!iso) return '-'
|
||||
return new Date(iso).toLocaleDateString('sv-SE', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
})
|
||||
}
|
||||
|
||||
function confidenceColor(c: number): string {
|
||||
if (c >= 0.8) return 'text-success'
|
||||
if (c >= 0.5) return 'text-warning'
|
||||
return 'text-muted-foreground'
|
||||
}
|
||||
|
||||
export function CounterpartyTemplatesPanel() {
|
||||
const t = useTranslations('settings_counterparty_templates')
|
||||
const { toast } = useToast()
|
||||
|
||||
const SOURCE_LABELS: Record<string, string> = {
|
||||
sie_import: t('source_sie_import'),
|
||||
user_approved: t('source_user_approved'),
|
||||
auto_learned: t('source_auto_learned'),
|
||||
sni_default: t('source_sni_default'),
|
||||
}
|
||||
|
||||
const VAT_LABELS: Record<string, string> = {
|
||||
standard_25: '25%',
|
||||
reduced_12: '12%',
|
||||
reduced_6: '6%',
|
||||
reverse_charge: t('vat_reverse_charge'),
|
||||
export: t('vat_export'),
|
||||
exempt: t('vat_exempt'),
|
||||
}
|
||||
|
||||
const [templates, setTemplates] = useState<CategorizationTemplate[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [deletingId, setDeletingId] = useState<string | null>(null)
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null)
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
const [editName, setEditName] = useState('')
|
||||
const [savingId, setSavingId] = useState<string | null>(null)
|
||||
|
||||
const fetchTemplates = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/settings/counterparty-templates')
|
||||
const json = await res.json()
|
||||
if (json.data) {
|
||||
setTemplates(json.data)
|
||||
}
|
||||
} catch {
|
||||
toast({ title: t('toast_fetch_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [toast, t])
|
||||
|
||||
useEffect(() => {
|
||||
fetchTemplates()
|
||||
}, [fetchTemplates])
|
||||
|
||||
async function handleDelete(id: string) {
|
||||
setDeletingId(id)
|
||||
try {
|
||||
const res = await fetch('/api/settings/counterparty-templates', {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ id }),
|
||||
})
|
||||
if (!res.ok) {
|
||||
toast({ title: t('toast_delete_failed'), variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
setTemplates((prev) => prev.filter((tt) => tt.id !== id))
|
||||
if (expandedId === id) setExpandedId(null)
|
||||
toast({ title: t('toast_deleted') })
|
||||
} catch {
|
||||
toast({ title: t('toast_delete_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setDeletingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
function startRename(tt: CategorizationTemplate) {
|
||||
setEditingId(tt.id)
|
||||
setEditName(formatCounterpartyName(tt.counterparty_name))
|
||||
}
|
||||
|
||||
function cancelRename() {
|
||||
setEditingId(null)
|
||||
setEditName('')
|
||||
}
|
||||
|
||||
async function handleRename(id: string) {
|
||||
const name = editName.trim()
|
||||
if (!name) return
|
||||
setSavingId(id)
|
||||
try {
|
||||
const res = await fetch('/api/settings/counterparty-templates', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ id, counterparty_name: name }),
|
||||
})
|
||||
if (res.status === 409) {
|
||||
toast({ title: t('toast_duplicate_name'), variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
if (!res.ok) {
|
||||
toast({ title: t('toast_rename_failed'), variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
const json = (await res.json()) as { data?: CategorizationTemplate }
|
||||
if (json.data) {
|
||||
const updated = json.data
|
||||
setTemplates((prev) => prev.map((tt) => (tt.id === id ? { ...tt, ...updated } : tt)))
|
||||
}
|
||||
cancelRename()
|
||||
toast({ title: t('toast_renamed') })
|
||||
} catch {
|
||||
toast({ title: t('toast_rename_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setSavingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsGroup label={t('title')} help={t('description')}>
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : templates.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={Users}
|
||||
title={t('empty_title')}
|
||||
description={t('empty_help')}
|
||||
/>
|
||||
) : (
|
||||
templates.map((tt) => {
|
||||
const isExpanded = expandedId === tt.id
|
||||
const isMultiLine = tt.line_pattern && tt.line_pattern.length > 0
|
||||
|
||||
return (
|
||||
<div key={tt.id} className="border-b border-border">
|
||||
{/* Clickable summary row: flat hairline, one line. */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpandedId(isExpanded ? null : tt.id)}
|
||||
aria-expanded={isExpanded}
|
||||
className="flex w-full items-center gap-3 px-1 py-3 text-left transition-colors duration-150 hover:bg-secondary/60"
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-3 gap-y-1">
|
||||
<span className="truncate text-sm">{formatCounterpartyName(tt.counterparty_name)}</span>
|
||||
<span className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
|
||||
{isMultiLine ? (
|
||||
<span className="font-mono">
|
||||
{tt.line_pattern!.filter(lp => lp.type === 'business').map(lp => lp.account).join(', ')}
|
||||
</span>
|
||||
) : (
|
||||
<span className="font-mono">
|
||||
{tt.debit_account}
|
||||
<span className="text-muted-foreground/50"> → </span>
|
||||
{tt.credit_account}
|
||||
</span>
|
||||
)}
|
||||
{tt.vat_treatment && (
|
||||
<span>· {VAT_LABELS[tt.vat_treatment] || tt.vat_treatment}</span>
|
||||
)}
|
||||
<span>· {t('times_count', { count: tt.occurrence_count })}</span>
|
||||
<span className={`tabular-nums ${confidenceColor(Number(tt.confidence))}`}>
|
||||
{Math.round(Number(tt.confidence) * 100)}%
|
||||
</span>
|
||||
<span>· {SOURCE_LABELS[tt.source] || tt.source}</span>
|
||||
</span>
|
||||
</div>
|
||||
<ChevronDown
|
||||
className={`h-4 w-4 shrink-0 text-muted-foreground transition-transform ${isExpanded ? 'rotate-180' : ''}`}
|
||||
/>
|
||||
</button>
|
||||
|
||||
{/* Expanded detail */}
|
||||
{isExpanded && (
|
||||
<div className="space-y-3 px-1 pb-3">
|
||||
{/* Account lines */}
|
||||
<div>
|
||||
<p className="mb-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">{t('booking_label')}</p>
|
||||
{isMultiLine ? (
|
||||
<div className="space-y-1">
|
||||
{tt.line_pattern!.map((lp, i) => (
|
||||
<div key={i} className="flex items-center gap-2 text-xs">
|
||||
<span className="w-14 shrink-0 text-[10px] uppercase tracking-wider text-muted-foreground">
|
||||
{lp.side === 'debit' ? t('debit_label') : t('credit_label')}
|
||||
</span>
|
||||
<span className="font-mono">{formatAccountWithName(lp.account)}</span>
|
||||
{lp.type === 'vat' && lp.vat_rate && (
|
||||
<span className="text-muted-foreground">{t('vat_paren', { rate: Math.round(lp.vat_rate * 100) })}</span>
|
||||
)}
|
||||
{lp.ratio !== undefined && (
|
||||
<span className="text-muted-foreground">({Math.round(lp.ratio * 100)}%)</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
<span className="w-14 shrink-0 text-[10px] uppercase tracking-wider text-muted-foreground">{t('debit_label')}</span>
|
||||
<span className="font-mono">{formatAccountWithName(tt.debit_account)}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
<span className="w-14 shrink-0 text-[10px] uppercase tracking-wider text-muted-foreground">{t('credit_label')}</span>
|
||||
<span className="font-mono">{formatAccountWithName(tt.credit_account)}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Metadata */}
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-1 text-xs">
|
||||
{tt.vat_treatment && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">{t('vat_label')}</span>
|
||||
<span>{VAT_LABELS[tt.vat_treatment] || tt.vat_treatment}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">{t('occurrence_count_label')}</span>
|
||||
<span className="tabular-nums">{tt.occurrence_count}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">{t('confidence_label')}</span>
|
||||
<span className={`tabular-nums ${confidenceColor(Number(tt.confidence))}`}>
|
||||
{Math.round(Number(tt.confidence) * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">{t('last_seen_label')}</span>
|
||||
<span>{formatDate(tt.last_seen_date)}</span>
|
||||
</div>
|
||||
{tt.counterparty_aliases && tt.counterparty_aliases.length > 1 && (
|
||||
<div className="col-span-2 flex justify-between">
|
||||
<span className="text-muted-foreground">{t('aliases_label')}</span>
|
||||
<span className="ml-4 truncate text-right">{tt.counterparty_aliases.slice(0, 3).join(', ')}{tt.counterparty_aliases.length > 3 ? ` +${tt.counterparty_aliases.length - 3}` : ''}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Rename + delete */}
|
||||
{editingId === tt.id ? (
|
||||
<form
|
||||
className="flex items-center gap-2 pt-1"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
handleRename(tt.id)
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
value={editName}
|
||||
onChange={(e) => setEditName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') cancelRename()
|
||||
}}
|
||||
maxLength={100}
|
||||
autoFocus
|
||||
aria-label={t('rename_label')}
|
||||
className="h-8 max-w-xs text-sm"
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
disabled={savingId === tt.id || editName.trim().length < 2}
|
||||
className="h-7 text-xs"
|
||||
>
|
||||
{savingId === tt.id ? <Loader2 className="mr-1.5 h-3 w-3 animate-spin" /> : null}
|
||||
{t('rename_save')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={cancelRename}
|
||||
disabled={savingId === tt.id}
|
||||
className="h-7 text-xs"
|
||||
>
|
||||
{t('rename_cancel')}
|
||||
</Button>
|
||||
</form>
|
||||
) : (
|
||||
<div className="flex justify-end gap-2 pt-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => startRename(tt)}
|
||||
disabled={deletingId === tt.id}
|
||||
className="h-7 text-xs"
|
||||
>
|
||||
<Pencil className="mr-1.5 h-3 w-3" />
|
||||
{t('rename_button')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleDelete(tt.id)}
|
||||
disabled={deletingId === tt.id}
|
||||
className="h-7 text-xs text-destructive hover:text-destructive"
|
||||
>
|
||||
{deletingId === tt.id ? (
|
||||
<Loader2 className="mr-1.5 h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="mr-1.5 h-3 w-3" />
|
||||
)}
|
||||
{t('delete_button')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</SettingsGroup>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { SettingsRow, SettingsRowNote } from '@/components/settings/SettingsRows'
|
||||
import { useSettings } from '@/components/settings/useSettings'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
|
||||
/**
|
||||
* Company-level consent toggle for data analysis (#1346). Persists
|
||||
* company_settings.data_analysis_opt_in through the standard settings PUT.
|
||||
* The flag is enforced server-side (lib/company/data-analysis.ts) on every
|
||||
* path that reads bookkeeping outcomes across companies; this component only
|
||||
* mirrors it and states plainly what is analysed. Off by default.
|
||||
*
|
||||
* Owner / admin only: the company_settings RLS update policy is admin-gated,
|
||||
* so a plain member's PUT would fail with a misleading error. Consent is an
|
||||
* admin decision anyway, so the switch renders disabled for everyone else.
|
||||
*/
|
||||
export function DataAnalysisToggle() {
|
||||
const t = useTranslations('data_analysis')
|
||||
const errorLocale = useLocale() as ErrorLocale
|
||||
const { settings, updateSettings } = useSettings()
|
||||
const { role } = useCompany()
|
||||
const canConsent = role === 'owner' || role === 'admin'
|
||||
const { toast } = useToast()
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
|
||||
const enabled = settings?.data_analysis_opt_in ?? false
|
||||
|
||||
async function handleChange(next: boolean) {
|
||||
setIsSaving(true)
|
||||
try {
|
||||
const res = await fetch('/api/settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ data_analysis_opt_in: next }),
|
||||
})
|
||||
const json = await res.json().catch(() => null)
|
||||
if (!res.ok) {
|
||||
toast({
|
||||
title: t('settings_save_failed_title'),
|
||||
description: getErrorMessage(json, { locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
updateSettings({ data_analysis_opt_in: next })
|
||||
} catch (err) {
|
||||
// A rejected fetch never reaches the !res.ok arm above, and the switch
|
||||
// is controlled by the settings context, so it stays where it was:
|
||||
// without this toast the click looks like a dead control.
|
||||
toast({
|
||||
title: t('settings_save_failed_title'),
|
||||
description: getErrorMessage(err, { locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const locked = isSaving || !canConsent
|
||||
|
||||
return (
|
||||
<SettingsRow label={t('settings_heading')} help={t('settings_toggle_help')}>
|
||||
<Switch
|
||||
id="data-analysis-opt-in"
|
||||
checked={enabled}
|
||||
onCheckedChange={(next) => void handleChange(next)}
|
||||
disabled={locked}
|
||||
/>
|
||||
<label
|
||||
htmlFor="data-analysis-opt-in"
|
||||
className={cn('text-sm', locked ? 'text-muted-foreground' : 'cursor-pointer')}
|
||||
>
|
||||
{t('settings_toggle_label')}
|
||||
</label>
|
||||
<SettingsRowNote className="basis-full">
|
||||
{t('settings_disclosure')}{' '}
|
||||
<Link
|
||||
href="/privacy"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="underline underline-offset-4 transition-colors hover:text-foreground"
|
||||
>
|
||||
{t('settings_privacy_link')}
|
||||
</Link>
|
||||
</SettingsRowNote>
|
||||
</SettingsRow>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { ExternalLink } from 'lucide-react'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import {
|
||||
SettingsRow,
|
||||
SettingsRowEnd,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import { useSettings } from '@/components/settings/useSettings'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
|
||||
/**
|
||||
* Company-level toggle for the dimensions register (kostnadsställen &
|
||||
* projekt). Persists company_settings.dimensions_enabled through the standard
|
||||
* settings PUT: the flag gates UI visibility only (nav row + register),
|
||||
* never correctness (dimensions plan §2).
|
||||
*
|
||||
* Toggling ON runs the "Importera befintliga koder" scan
|
||||
* (POST /api/dimensions/import-existing): codes already present on
|
||||
* journal_entry_lines.dimensions but missing from the registry are created as
|
||||
* archived placeholder values, and the user is told how many were found.
|
||||
*/
|
||||
export function DimensionsToggle() {
|
||||
const t = useTranslations('dimensions')
|
||||
const errorLocale = useLocale() as ErrorLocale
|
||||
const { settings, updateSettings } = useSettings()
|
||||
const { canWrite } = useCanWrite()
|
||||
const { toast } = useToast()
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
|
||||
const enabled = settings?.dimensions_enabled ?? false
|
||||
|
||||
async function handleChange(next: boolean) {
|
||||
setIsSaving(true)
|
||||
try {
|
||||
const res = await fetch('/api/settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ dimensions_enabled: next }),
|
||||
})
|
||||
const json = await res.json().catch(() => null)
|
||||
if (!res.ok) {
|
||||
toast({
|
||||
title: t('settings_save_failed_title'),
|
||||
description: getErrorMessage(json, { locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
updateSettings({ dimensions_enabled: next })
|
||||
|
||||
if (next) {
|
||||
// Import scan: registry rows for codes already used on lines. Failure
|
||||
// is non-fatal: the toggle stays on and the scan can be re-run by
|
||||
// toggling again.
|
||||
try {
|
||||
const importRes = await fetch('/api/dimensions/import-existing', {
|
||||
method: 'POST',
|
||||
})
|
||||
const importJson = await importRes.json().catch(() => null)
|
||||
if (importRes.ok) {
|
||||
const created: number =
|
||||
importJson?.created ?? importJson?.data?.created ?? 0
|
||||
if (created > 0) {
|
||||
toast({
|
||||
title: t('settings_imported_toast_title'),
|
||||
description: t('settings_imported_toast', { count: created }),
|
||||
})
|
||||
}
|
||||
} else {
|
||||
toast({
|
||||
title: t('settings_import_failed_title'),
|
||||
description: getErrorMessage(importJson, { locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
toast({
|
||||
title: t('settings_import_failed_title'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// A rejected fetch (offline, DNS failure, aborted request) never reaches
|
||||
// the !res.ok arm above, and the switch is controlled by the settings
|
||||
// context, so it simply stays where it was: without this toast the click
|
||||
// looks like a dead control rather than a save that did not happen.
|
||||
// One toast per failed click, never two: TOAST_LIMIT is 1
|
||||
// (components/ui/use-toast.tsx) and a second would evict the first.
|
||||
toast({
|
||||
title: t('settings_save_failed_title'),
|
||||
description: getErrorMessage(err, { locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const locked = isSaving || !canWrite
|
||||
|
||||
return (
|
||||
<SettingsRow label={t('settings_heading')} help={t('settings_toggle_help')}>
|
||||
<Switch
|
||||
id="dimensions-enabled"
|
||||
checked={enabled}
|
||||
onCheckedChange={(next) => void handleChange(next)}
|
||||
disabled={locked}
|
||||
/>
|
||||
<label
|
||||
htmlFor="dimensions-enabled"
|
||||
className={cn('text-sm', locked ? 'text-muted-foreground' : 'cursor-pointer')}
|
||||
>
|
||||
{t('settings_toggle_label')}
|
||||
</label>
|
||||
{enabled && (
|
||||
<SettingsRowEnd>
|
||||
<Link
|
||||
href="/dimensions"
|
||||
className="inline-flex items-center gap-1.5 text-xs text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
{t('settings_open_register')}
|
||||
</Link>
|
||||
</SettingsRowEnd>
|
||||
)}
|
||||
</SettingsRow>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { SettingsGroup, SettingsRow } from '@/components/settings/SettingsRows'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
|
||||
/**
|
||||
* Per-user opt-in for the daily "nytt att bokfora" email digest
|
||||
* (notification_settings.email_digest_enabled, default false; consumed by
|
||||
* the bookkeeping-digest cron). Lives on the core account tab: the
|
||||
* push-notifications extension has its own settings panel with the same
|
||||
* toggle, but that extension is not enabled on hosted, so this is the
|
||||
* reachable switch.
|
||||
*/
|
||||
export function EmailDigestToggle() {
|
||||
const t = useTranslations('settings')
|
||||
const { toast } = useToast()
|
||||
const supabase = createClient()
|
||||
const [enabled, setEnabled] = useState(false)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
;(async () => {
|
||||
try {
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) return
|
||||
const { data } = await supabase
|
||||
.from('notification_settings')
|
||||
.select('email_digest_enabled')
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (active) setEnabled(data?.email_digest_enabled === true)
|
||||
} catch (err) {
|
||||
// Leave the default (off); a failed read must not block the page.
|
||||
console.error('Could not read email digest setting:', err)
|
||||
} finally {
|
||||
if (active) setLoading(false)
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
async function handleChange(next: boolean) {
|
||||
setEnabled(next)
|
||||
setSaving(true)
|
||||
try {
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) throw new Error('Not signed in')
|
||||
// Upsert on user_id: most users have no notification_settings row
|
||||
// until they touch a notification preference for the first time.
|
||||
const { error } = await supabase
|
||||
.from('notification_settings')
|
||||
.upsert(
|
||||
{ user_id: user.id, email_digest_enabled: next },
|
||||
{ onConflict: 'user_id' },
|
||||
)
|
||||
if (error) throw new Error(error.message)
|
||||
toast({
|
||||
title: next
|
||||
? t('digest_enabled_toast')
|
||||
: t('digest_disabled_toast'),
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('Could not save email digest setting:', err)
|
||||
setEnabled(!next)
|
||||
toast({ title: t('digest_save_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsGroup label={t('digest_group')}>
|
||||
<SettingsRow label={t('digest_label')} help={t('digest_description')}>
|
||||
<Switch
|
||||
id="email-digest"
|
||||
checked={enabled}
|
||||
onCheckedChange={(value) => void handleChange(value)}
|
||||
disabled={loading || saving}
|
||||
/>
|
||||
<label htmlFor="email-digest" className="cursor-pointer text-sm">
|
||||
{t('digest_switch_label')}
|
||||
</label>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { useFiscalPeriods } from '@/lib/reference-data/hooks'
|
||||
import { invalidateReferenceData } from '@/lib/reference-data/invalidate'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import {
|
||||
DestructiveConfirmDialog,
|
||||
useDestructiveConfirm,
|
||||
} from '@/components/ui/destructive-confirm-dialog'
|
||||
import { Loader2, Lock } from 'lucide-react'
|
||||
import { parseDateParts } from '@/lib/bookkeeping/validate-period-duration'
|
||||
import { validateFirstPeriod } from '@/components/bookkeeping/FiscalPeriodDateFields'
|
||||
import {
|
||||
SettingsGroup,
|
||||
SettingsInput,
|
||||
SettingsRow,
|
||||
SettingsRowNote,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import type { FiscalPeriod } from '@/types'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
function formatSwedishDate(dateStr: string): string {
|
||||
const months = [
|
||||
'januari', 'februari', 'mars', 'april', 'maj', 'juni',
|
||||
'juli', 'augusti', 'september', 'oktober', 'november', 'december',
|
||||
]
|
||||
const { year, month, day } = parseDateParts(dateStr)
|
||||
return `${day} ${months[month - 1]} ${year}`
|
||||
}
|
||||
|
||||
function isCalendarYear(period: { period_start: string; period_end: string }): boolean {
|
||||
const s = parseDateParts(period.period_start)
|
||||
const e = parseDateParts(period.period_end)
|
||||
return s.month === 1 && s.day === 1 && e.month === 12 && e.day === 31
|
||||
}
|
||||
|
||||
export function FiscalPeriodEditor() {
|
||||
const t = useTranslations('settings_company')
|
||||
const { company, role } = useCompany()
|
||||
const { toast } = useToast()
|
||||
const { dialogProps, confirm } = useDestructiveConfirm()
|
||||
|
||||
const [period, setPeriod] = useState<FiscalPeriod | null>(null)
|
||||
const [postedCount, setPostedCount] = useState<number | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [loadError, setLoadError] = useState<string | null>(null)
|
||||
|
||||
const [startDate, setStartDate] = useState('')
|
||||
const [endDate, setEndDate] = useState('')
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
|
||||
const isEF = company?.entity_type === 'enskild_firma'
|
||||
const canEdit = role === 'owner' || role === 'admin'
|
||||
|
||||
// Periods come from the session cache (lib/reference-data). The editor
|
||||
// snapshots the FIRST period once per company (a background revalidation
|
||||
// must not reset the dates the user is editing), then loads that period's
|
||||
// posted-entry count, which is what gates editing.
|
||||
const { periods, isLoading: periodsLoading, error: periodsError } = useFiscalPeriods()
|
||||
const periodsRef = useRef(periods)
|
||||
useEffect(() => {
|
||||
periodsRef.current = periods
|
||||
}, [periods])
|
||||
const initialisedForRef = useRef<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!company || periodsLoading) return
|
||||
if (initialisedForRef.current === company.id) return
|
||||
initialisedForRef.current = company.id
|
||||
let cancelled = false
|
||||
|
||||
async function load() {
|
||||
setIsLoading(true)
|
||||
setLoadError(null)
|
||||
try {
|
||||
if (periodsError) throw new Error(t('fp_load_error_periods'))
|
||||
const data = periodsRef.current
|
||||
if (!data || data.length === 0) {
|
||||
if (!cancelled) {
|
||||
setPeriod(null)
|
||||
setIsLoading(false)
|
||||
}
|
||||
return
|
||||
}
|
||||
const sorted = [...data].sort((a, b) => a.period_start.localeCompare(b.period_start))
|
||||
const first = sorted[0]
|
||||
|
||||
const countRes = await fetch(`/api/bookkeeping/fiscal-periods/${first.id}/entry-count`)
|
||||
if (!countRes.ok) throw new Error(t('fp_load_error_entry_count'))
|
||||
const { data: countData } = (await countRes.json()) as { data: { posted_count: number } }
|
||||
|
||||
if (cancelled) return
|
||||
setPeriod(first)
|
||||
setPostedCount(countData.posted_count)
|
||||
setStartDate(first.period_start)
|
||||
setEndDate(first.period_end)
|
||||
} catch (err) {
|
||||
if (!cancelled) {
|
||||
setLoadError(err instanceof Error ? getUserErrorMessage(err) : t('fp_load_error_unknown'))
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
void load()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [company, periodsLoading, periodsError, t])
|
||||
|
||||
const validation = validateFirstPeriod(
|
||||
startDate,
|
||||
endDate,
|
||||
company?.entity_type,
|
||||
)
|
||||
|
||||
const isBlocked =
|
||||
!!period && (period.locked_at || period.is_closed || (postedCount ?? 0) > 0)
|
||||
|
||||
const isDirty =
|
||||
period !== null && (startDate !== period.period_start || endDate !== period.period_end)
|
||||
|
||||
if (!company || !canEdit) return null
|
||||
|
||||
async function handleSave() {
|
||||
if (!period || !company) return
|
||||
if (!isDirty) return
|
||||
|
||||
const ok = await confirm({
|
||||
title: t('fp_confirm_title'),
|
||||
description: t('fp_confirm_description', {
|
||||
oldStart: formatSwedishDate(period.period_start),
|
||||
oldEnd: formatSwedishDate(period.period_end),
|
||||
newStart: formatSwedishDate(startDate),
|
||||
newEnd: formatSwedishDate(endDate),
|
||||
}),
|
||||
confirmLabel: t('fp_confirm_yes'),
|
||||
cancelLabel: t('fp_confirm_cancel'),
|
||||
variant: 'warning',
|
||||
})
|
||||
if (!ok) return
|
||||
|
||||
setIsSaving(true)
|
||||
try {
|
||||
const startYear = parseDateParts(startDate).year
|
||||
const endYear = parseDateParts(endDate).year
|
||||
const newName =
|
||||
startYear === endYear
|
||||
? t('fp_year_label_single', { year: startYear })
|
||||
: t('fp_year_label_range', { startYear, endYear })
|
||||
const res = await fetch(`/api/bookkeeping/fiscal-periods/${period.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
period_start: startDate,
|
||||
period_end: endDate,
|
||||
name: newName,
|
||||
}),
|
||||
})
|
||||
const body = await res.json().catch(() => ({}))
|
||||
if (!res.ok) {
|
||||
throw new Error(body.error || t('fp_update_failed_title'))
|
||||
}
|
||||
setPeriod(body.data as FiscalPeriod)
|
||||
// Every picker reads the shared list: refresh it with the new dates.
|
||||
void invalidateReferenceData('ref:fiscal-periods')
|
||||
toast({
|
||||
title: t('fp_updated_title'),
|
||||
description: `${formatSwedishDate(body.data.period_start)}: ${formatSwedishDate(body.data.period_end)}`,
|
||||
})
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: t('fp_update_failed_title'),
|
||||
description: err instanceof Error ? getUserErrorMessage(err) : t('fp_try_again'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
function handleReset() {
|
||||
if (!period) return
|
||||
setStartDate(period.period_start)
|
||||
setEndDate(period.period_end)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsGroup label={t('fp_heading')} help={t('fp_intro')}>
|
||||
{isLoading ? (
|
||||
<div className="flex items-center gap-2 px-1 py-3 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
{t('fp_loading')}
|
||||
</div>
|
||||
) : loadError ? (
|
||||
<p className="px-1 py-3 text-sm text-destructive">{loadError}</p>
|
||||
) : !period ? (
|
||||
<p className="px-1 py-3 text-sm text-muted-foreground">{t('fp_none')}</p>
|
||||
) : isBlocked ? (
|
||||
<BlockedRow period={period} postedCount={postedCount ?? 0} />
|
||||
) : (
|
||||
<>
|
||||
{/* Consequential warning: stays visible as one quiet ochre sentence. */}
|
||||
<p className="px-1 py-3 text-[12.5px] text-attn">
|
||||
{t('fp_warning_title')} {t('fp_warning_body')}
|
||||
{isEF ? t('fp_warning_ef_suffix') : null}
|
||||
</p>
|
||||
|
||||
<SettingsRow
|
||||
label={t('fp_start_date_label')}
|
||||
htmlFor="fiscal-period-start"
|
||||
help={t('fp_start_date_help')}
|
||||
align="baseline"
|
||||
>
|
||||
<SettingsInput
|
||||
id="fiscal-period-start"
|
||||
type="date"
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
className="max-w-44 flex-none tabular-nums"
|
||||
/>
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow
|
||||
label={t('fp_end_date_label')}
|
||||
htmlFor="fp_end"
|
||||
help={t('fp_end_date_help')}
|
||||
align="baseline"
|
||||
>
|
||||
<SettingsInput
|
||||
id="fp_end"
|
||||
type="date"
|
||||
value={endDate}
|
||||
onChange={(e) => setEndDate(e.target.value)}
|
||||
className="max-w-44 flex-none tabular-nums"
|
||||
/>
|
||||
</SettingsRow>
|
||||
|
||||
{validation.canSummarise && (
|
||||
<p className="px-1 pt-3 text-xs text-muted-foreground">
|
||||
{t('fp_summary_title')}:{' '}
|
||||
<span className="tabular-nums">
|
||||
{t('fp_range', { start: formatSwedishDate(startDate), end: formatSwedishDate(endDate) })}
|
||||
</span>
|
||||
{validation.months !== null && <> · {t('fp_months', { count: validation.months })}</>}
|
||||
</p>
|
||||
)}
|
||||
{validation.error && (
|
||||
<p className="px-1 pt-1 text-xs text-destructive">{validation.error}</p>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2 px-1 pt-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleReset}
|
||||
disabled={!isDirty || isSaving}
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{t('fp_reset')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={handleSave}
|
||||
disabled={
|
||||
!isDirty ||
|
||||
isSaving ||
|
||||
!startDate ||
|
||||
!endDate ||
|
||||
validation.error !== null
|
||||
}
|
||||
>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t('fp_saving')}
|
||||
</>
|
||||
) : (
|
||||
t('fp_save')
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</SettingsGroup>
|
||||
<DestructiveConfirmDialog {...dialogProps} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function BlockedRow({
|
||||
period,
|
||||
postedCount,
|
||||
}: {
|
||||
period: FiscalPeriod
|
||||
postedCount: number
|
||||
}) {
|
||||
const t = useTranslations('settings_company')
|
||||
const reason = period.locked_at
|
||||
? t('fp_blocked_reason_locked')
|
||||
: period.is_closed
|
||||
? t('fp_blocked_reason_closed')
|
||||
: t('fp_blocked_reason_posted', { count: postedCount })
|
||||
|
||||
return (
|
||||
<SettingsRow
|
||||
// The key carries a trailing colon from its old inline usage; strip it
|
||||
// for the micro-label position.
|
||||
label={t('fp_blocked_first_year').replace(/:$/, '')}
|
||||
help={
|
||||
<>
|
||||
<p>
|
||||
{t('fp_blocked_title')}. {reason}
|
||||
</p>
|
||||
<p className="mt-2">{t('fp_blocked_explainer')}</p>
|
||||
</>
|
||||
}
|
||||
borderless
|
||||
>
|
||||
<Lock aria-hidden="true" className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
|
||||
<span className="tabular-nums">
|
||||
{t('fp_range', { start: formatSwedishDate(period.period_start), end: formatSwedishDate(period.period_end) })}
|
||||
</span>
|
||||
<SettingsRowNote>
|
||||
{(isCalendarYear(period) ? t('fp_blocked_calendar_year') : t('fp_blocked_broken_year')).trim()}
|
||||
</SettingsRowNote>
|
||||
</SettingsRow>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { fiscalYearName, isDerivedFiscalYearName } from '@/lib/bookkeeping/suggest-fiscal-period'
|
||||
import type { FiscalPeriod } from '@/types'
|
||||
|
||||
interface FiscalYearEditDialogProps {
|
||||
period: FiscalPeriod
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
/** Called after a successful save so the parent can refetch. */
|
||||
onSaved: () => void
|
||||
}
|
||||
|
||||
/** Read a user-facing message from either a legacy `{ error: string }` body
|
||||
* (what the fiscal-periods PATCH route returns) or the canonical
|
||||
* `{ error: { message } }` envelope. */
|
||||
function readApiError(body: unknown, fallback: string): string {
|
||||
if (!body || typeof body !== 'object') return fallback
|
||||
const error = (body as { error?: unknown }).error
|
||||
if (typeof error === 'string') return error
|
||||
if (error && typeof error === 'object') {
|
||||
const message = (error as { message?: unknown }).message
|
||||
if (typeof message === 'string') return message
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit the name and dates of one OPEN fiscal year (issue #2287). A thin
|
||||
* surface over PATCH /api/bookkeeping/fiscal-periods/[id], which already
|
||||
* allows a rename at any time on an open year and a re-date only while the
|
||||
* year has no posted vouchers. The dialog mirrors those two rules with the
|
||||
* route's own reasons: the posted count comes from the entry-count endpoint
|
||||
* on open (dates read-only above zero), and every refusal from the route is
|
||||
* shown verbatim so the user can correct and retry without leaving the
|
||||
* dialog. Only changed fields are sent, so a pure rename never trips the
|
||||
* voucher check. Every guard is re-enforced server-side.
|
||||
*/
|
||||
export function FiscalYearEditDialog({
|
||||
period,
|
||||
open,
|
||||
onOpenChange,
|
||||
onSaved,
|
||||
}: FiscalYearEditDialogProps) {
|
||||
const t = useTranslations('settings_bookkeeping')
|
||||
const { toast } = useToast()
|
||||
|
||||
const [name, setName] = useState(period.name)
|
||||
// The name follows the dates while it is still the app's own derived name
|
||||
// ("Räkenskapsår 2027"), the same rule as CreatePeriodDialog: a seed name
|
||||
// that never matched its dates is corrected together with them, and the
|
||||
// user watches it change. A hand-written name is never overwritten.
|
||||
const [nameFollowsDates, setNameFollowsDates] = useState(() =>
|
||||
isDerivedFiscalYearName(period.name),
|
||||
)
|
||||
const [periodStart, setPeriodStart] = useState(period.period_start)
|
||||
const [periodEnd, setPeriodEnd] = useState(period.period_end)
|
||||
const [postedCount, setPostedCount] = useState<number | null>(null)
|
||||
const [countFailed, setCountFailed] = useState(false)
|
||||
const [isChecking, setIsChecking] = useState(false)
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
const [submitError, setSubmitError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
|
||||
let cancelled = false
|
||||
async function loadPostedCount() {
|
||||
setIsChecking(true)
|
||||
setCountFailed(false)
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/bookkeeping/fiscal-periods/${period.id}/entry-count`,
|
||||
{ cache: 'no-store' },
|
||||
)
|
||||
if (!response.ok) throw new Error('entry-count failed')
|
||||
const body = (await response.json()) as { data?: { posted_count?: number } }
|
||||
if (!cancelled) setPostedCount(body.data?.posted_count ?? 0)
|
||||
} catch {
|
||||
if (!cancelled) setCountFailed(true)
|
||||
} finally {
|
||||
if (!cancelled) setIsChecking(false)
|
||||
}
|
||||
}
|
||||
|
||||
void loadPostedCount()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [open, period.id])
|
||||
|
||||
// Dates open up only once the check has come back with zero posted
|
||||
// vouchers; while checking, or if the check failed, they stay read-only
|
||||
// and the sentence below the fields says why. The name is always editable.
|
||||
const datesEditable = !isChecking && !countFailed && postedCount === 0
|
||||
|
||||
// A date input yields '' while incomplete and a full YYYY-MM-DD otherwise:
|
||||
// only derive a name once both ends are known.
|
||||
function updateDates(start: string, end: string) {
|
||||
setPeriodStart(start)
|
||||
setPeriodEnd(end)
|
||||
if (nameFollowsDates && start && end) setName(fiscalYearName(start, end))
|
||||
}
|
||||
|
||||
const trimmedName = name.trim()
|
||||
const payload: { name?: string; period_start?: string; period_end?: string } = {}
|
||||
// "Changed" compares the raw input with the stored name, so a stored name
|
||||
// with stray whitespace does not read as dirty on open; the trimmed value
|
||||
// is what gets sent once the user has actually edited it.
|
||||
const nameChanged = name !== period.name
|
||||
if (nameChanged && trimmedName) payload.name = trimmedName
|
||||
if (datesEditable) {
|
||||
if (periodStart && periodStart !== period.period_start) payload.period_start = periodStart
|
||||
if (periodEnd && periodEnd !== period.period_end) payload.period_end = periodEnd
|
||||
}
|
||||
const endBeforeStart = datesEditable && !!periodStart && !!periodEnd && periodEnd <= periodStart
|
||||
const datesIncomplete = datesEditable && (!periodStart || !periodEnd)
|
||||
const isDirty = Object.keys(payload).length > 0
|
||||
const canSave =
|
||||
isDirty && trimmedName.length > 0 && !endBeforeStart && !datesIncomplete && !isSaving
|
||||
|
||||
function handleOpenChange(nextOpen: boolean) {
|
||||
if (isSaving) return
|
||||
onOpenChange(nextOpen)
|
||||
}
|
||||
|
||||
async function handleSave() {
|
||||
if (!canSave) return
|
||||
setIsSaving(true)
|
||||
setSubmitError(null)
|
||||
try {
|
||||
const response = await fetch(`/api/bookkeeping/fiscal-periods/${period.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
const body = await response.json().catch(() => ({}))
|
||||
if (!response.ok) {
|
||||
// The route's refusals (BFL 3 kap. shapes, overlap, posted vouchers)
|
||||
// are Swedish domain copy and stay verbatim in both locales.
|
||||
setSubmitError(readApiError(body, t('fy_edit_failed_default')))
|
||||
return
|
||||
}
|
||||
toast({ title: t('fy_edit_success') })
|
||||
onOpenChange(false)
|
||||
onSaved()
|
||||
} catch (error) {
|
||||
setSubmitError(
|
||||
error instanceof Error ? getUserErrorMessage(error) : t('fy_edit_failed_default'),
|
||||
)
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('fy_edit_dialog_title')}</DialogTitle>
|
||||
<DialogDescription>{t('fy_edit_dialog_description')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="fy-edit-name">{t('fy_edit_name_label')}</Label>
|
||||
<Input
|
||||
id="fy-edit-name"
|
||||
value={name}
|
||||
onChange={(event) => {
|
||||
setName(event.target.value)
|
||||
setNameFollowsDates(false)
|
||||
}}
|
||||
autoComplete="off"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="fy-edit-start">{t('fy_edit_start_label')}</Label>
|
||||
<Input
|
||||
id="fy-edit-start"
|
||||
type="date"
|
||||
value={periodStart}
|
||||
disabled={!datesEditable}
|
||||
aria-describedby="fy-edit-dates-note"
|
||||
onChange={(event) => updateDates(event.target.value, periodEnd)}
|
||||
className="tabular-nums"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="fy-edit-end">{t('fy_edit_end_label')}</Label>
|
||||
<Input
|
||||
id="fy-edit-end"
|
||||
type="date"
|
||||
value={periodEnd}
|
||||
disabled={!datesEditable}
|
||||
aria-describedby="fy-edit-dates-note"
|
||||
onChange={(event) => updateDates(periodStart, event.target.value)}
|
||||
className="tabular-nums"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* One quiet sentence on why the dates are read-only, in the
|
||||
route's own terms (posted vouchers). */}
|
||||
<p id="fy-edit-dates-note" className="text-xs text-muted-foreground">
|
||||
{isChecking ? (
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
{t('fy_edit_dates_checking')}
|
||||
</span>
|
||||
) : countFailed ? (
|
||||
t('fy_edit_dates_check_failed')
|
||||
) : postedCount !== null && postedCount > 0 ? (
|
||||
t('fy_edit_dates_blocked_posted', { count: postedCount })
|
||||
) : null}
|
||||
</p>
|
||||
|
||||
{endBeforeStart ? (
|
||||
<p className="text-xs text-destructive">{t('fy_edit_end_before_start')}</p>
|
||||
) : null}
|
||||
{submitError ? <p className="text-xs text-destructive">{submitError}</p> : null}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => handleOpenChange(false)} disabled={isSaving}>
|
||||
{t('fy_confirm_cancel')}
|
||||
</Button>
|
||||
<Button onClick={handleSave} disabled={!canSave}>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t('fy_edit_saving')}
|
||||
</>
|
||||
) : (
|
||||
t('fy_edit_save')
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { AlertTriangle, Loader2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import type { FiscalYearResetBlocker, FiscalYearResetEligibility } from '@/types'
|
||||
|
||||
interface FiscalYearResetDialogProps {
|
||||
periodId: string
|
||||
periodName: string
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
/** Called after a successful reset so the parent can refetch. */
|
||||
onReset: () => void
|
||||
}
|
||||
|
||||
function readApiError(body: unknown, fallback: string): string {
|
||||
if (!body || typeof body !== 'object') return fallback
|
||||
const error = (body as { error?: unknown }).error
|
||||
if (typeof error === 'string') return error
|
||||
if (error && typeof error === 'object') {
|
||||
const message = (error as { message?: unknown }).message
|
||||
if (typeof message === 'string') return message
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
/**
|
||||
* Destructive fiscal-year reset (issue #1883): hard-deletes ALL vouchers in
|
||||
* one OPEN fiscal year after typed confirmation of the year's label. Mirrors
|
||||
* the CompanyMigrationResetDialog pattern: eligibility preview with blockers,
|
||||
* a clear statement of what is deleted (voucher count, year label) and what
|
||||
* is NOT (documents are detached, never deleted: BFL 7 kap), and a
|
||||
* type-the-name confirmation. Every guard is re-enforced server-side.
|
||||
*/
|
||||
export function FiscalYearResetDialog({
|
||||
periodId,
|
||||
periodName,
|
||||
open,
|
||||
onOpenChange,
|
||||
onReset,
|
||||
}: FiscalYearResetDialogProps) {
|
||||
const t = useTranslations('settings_bookkeeping')
|
||||
const { toast } = useToast()
|
||||
const loadFailedMessage = t('fy_reset_load_failed')
|
||||
const [eligibility, setEligibility] = useState<FiscalYearResetEligibility | null>(null)
|
||||
const [loadError, setLoadError] = useState<string | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [isResetting, setIsResetting] = useState(false)
|
||||
const [confirmName, setConfirmName] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
|
||||
let cancelled = false
|
||||
async function loadEligibility() {
|
||||
setIsLoading(true)
|
||||
setLoadError(null)
|
||||
setEligibility(null)
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/bookkeeping/fiscal-periods/${periodId}/reset`,
|
||||
{ cache: 'no-store' },
|
||||
)
|
||||
const body = await response.json().catch(() => ({}))
|
||||
if (!response.ok) {
|
||||
throw new Error(readApiError(body, loadFailedMessage))
|
||||
}
|
||||
if (!cancelled) setEligibility(body.data as FiscalYearResetEligibility)
|
||||
} catch (error) {
|
||||
if (!cancelled) {
|
||||
setLoadError(
|
||||
error instanceof Error ? getUserErrorMessage(error) : loadFailedMessage,
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
void loadEligibility()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [periodId, loadFailedMessage, open])
|
||||
|
||||
function resetForm() {
|
||||
setEligibility(null)
|
||||
setLoadError(null)
|
||||
setConfirmName('')
|
||||
}
|
||||
|
||||
function handleOpenChange(nextOpen: boolean) {
|
||||
if (isResetting) return
|
||||
onOpenChange(nextOpen)
|
||||
if (!nextOpen) resetForm()
|
||||
}
|
||||
|
||||
function blockerMessage(blocker: FiscalYearResetBlocker): string {
|
||||
switch (blocker.code) {
|
||||
case 'period_closed':
|
||||
return t('fy_reset_blocker_closed')
|
||||
case 'period_locked':
|
||||
return t('fy_reset_blocker_locked')
|
||||
case 'company_lock_date':
|
||||
return t('fy_reset_blocker_lock_date', { date: blocker.date ?? '' })
|
||||
case 'year_end_state':
|
||||
return t('fy_reset_blocker_year_end')
|
||||
case 'arsredovisning_state':
|
||||
return t('fy_reset_blocker_arsredovisning')
|
||||
case 'next_year_dependency':
|
||||
return t('fy_reset_blocker_next_year')
|
||||
case 'vat_declared':
|
||||
return t('fy_reset_blocker_vat')
|
||||
case 'agi_declared':
|
||||
return t('fy_reset_blocker_agi')
|
||||
case 'rot_rut_state':
|
||||
return t('fy_reset_blocker_rot_rut')
|
||||
case 'cross_year_reference':
|
||||
return t('fy_reset_blocker_cross_year')
|
||||
default:
|
||||
return t('fy_reset_blocker_other')
|
||||
}
|
||||
}
|
||||
|
||||
const confirmationName = eligibility?.period.name ?? periodName
|
||||
const canReset =
|
||||
eligibility?.eligible === true &&
|
||||
confirmName.trim() === confirmationName.trim() &&
|
||||
!isResetting
|
||||
|
||||
async function handleReset() {
|
||||
if (!canReset) return
|
||||
setIsResetting(true)
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/bookkeeping/fiscal-periods/${periodId}/reset`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ confirm_name: confirmName }),
|
||||
},
|
||||
)
|
||||
const body = await response.json().catch(() => ({}))
|
||||
if (!response.ok) {
|
||||
throw new Error(readApiError(body, t('fy_reset_failed_default')))
|
||||
}
|
||||
|
||||
const deleted = (body.data as { deleted?: number } | undefined)?.deleted ?? 0
|
||||
toast({
|
||||
title: t('fy_reset_success_title'),
|
||||
description: t('fy_reset_success_description', { count: deleted }),
|
||||
})
|
||||
setIsResetting(false)
|
||||
onOpenChange(false)
|
||||
resetForm()
|
||||
onReset()
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t('fy_reset_failed_title'),
|
||||
description:
|
||||
error instanceof Error
|
||||
? getUserErrorMessage(error)
|
||||
: t('fy_reset_failed_default'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
setIsResetting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('fy_reset_dialog_title', { name: periodName })}</DialogTitle>
|
||||
<DialogDescription>{t('fy_reset_dialog_description')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex min-h-40 items-center justify-center text-muted-foreground">
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t('fy_reset_checking')}
|
||||
</div>
|
||||
) : loadError ? (
|
||||
<div className="rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive">
|
||||
{loadError}
|
||||
</div>
|
||||
) : eligibility ? (
|
||||
<div className="space-y-5">
|
||||
{eligibility.blockers.length > 0 ? (
|
||||
<div className="space-y-2 rounded-lg border border-destructive/30 bg-destructive/5 p-4">
|
||||
<div className="flex items-center gap-2 text-sm font-medium text-destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
{t('fy_reset_blocked_title')}
|
||||
</div>
|
||||
<ul className="list-disc space-y-1 pl-5 text-sm text-muted-foreground">
|
||||
{eligibility.blockers.map((blocker) => (
|
||||
<li key={blocker.code}>{blockerMessage(blocker)}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div>
|
||||
<h3 className="mb-2 text-sm font-medium">{t('fy_reset_summary_heading')}</h3>
|
||||
<dl className="divide-y divide-border border-y border-border">
|
||||
<div className="flex items-center justify-between py-2 text-sm">
|
||||
<dt className="text-muted-foreground">{t('fy_reset_summary_year')}</dt>
|
||||
<dd className="font-medium">
|
||||
{eligibility.period.name}
|
||||
<span className="ml-2 text-muted-foreground tabular-nums">
|
||||
{formatDate(eligibility.period.period_start)} -{' '}
|
||||
{formatDate(eligibility.period.period_end)}
|
||||
</span>
|
||||
</dd>
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-2 text-sm">
|
||||
<dt className="text-muted-foreground">{t('fy_reset_summary_vouchers')}</dt>
|
||||
<dd className="tabular-nums font-medium">{eligibility.counts.vouchers}</dd>
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-2 text-sm">
|
||||
<dt className="text-muted-foreground">{t('fy_reset_summary_documents')}</dt>
|
||||
<dd className="tabular-nums font-medium">
|
||||
{eligibility.counts.documents_to_detach}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
{t('fy_reset_documents_note')}
|
||||
</p>
|
||||
{eligibility.next_period?.has_opening_balances ? (
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
{t('fy_reset_next_year_ib_note', { name: eligibility.next_period.name })}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{eligibility.eligible ? (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="fy-reset-name">
|
||||
{t.rich('fy_reset_confirm_name', {
|
||||
name: confirmationName,
|
||||
strong: (chunks) => <strong>{chunks}</strong>,
|
||||
})}
|
||||
</Label>
|
||||
<Input
|
||||
id="fy-reset-name"
|
||||
value={confirmName}
|
||||
onChange={(event) => setConfirmName(event.target.value)}
|
||||
placeholder={confirmationName}
|
||||
autoComplete="off"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={isResetting}
|
||||
>
|
||||
{t('fy_confirm_cancel')}
|
||||
</Button>
|
||||
{eligibility?.eligible ? (
|
||||
<Button variant="destructive" onClick={handleReset} disabled={!canReset}>
|
||||
{isResetting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t('fy_reset_resetting')}
|
||||
</>
|
||||
) : (
|
||||
t('fy_reset_submit')
|
||||
)}
|
||||
</Button>
|
||||
) : null}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useState, useCallback } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import {
|
||||
DestructiveConfirmDialog,
|
||||
useDestructiveConfirm,
|
||||
} from '@/components/ui/destructive-confirm-dialog'
|
||||
import { SettingsGroup } from '@/components/settings/SettingsRows'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { useFiscalPeriods } from '@/lib/reference-data/hooks'
|
||||
import { invalidateReferenceData } from '@/lib/reference-data/invalidate'
|
||||
import { Plus, Lock, Unlock, Loader2, Eraser, Pencil } from 'lucide-react'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import type { FiscalPeriod } from '@/types'
|
||||
import CreatePeriodDialog from '@/components/bookkeeping/CreatePeriodDialog'
|
||||
import { FiscalYearResetDialog } from '@/components/settings/FiscalYearResetDialog'
|
||||
import { FiscalYearEditDialog } from '@/components/settings/FiscalYearEditDialog'
|
||||
import { suggestSeedDate } from '@/lib/bookkeeping/suggest-fiscal-period'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
/** Status of a fiscal period, in legal precedence: closed > locked > open. */
|
||||
function periodStatus(p: FiscalPeriod): 'closed' | 'locked' | 'open' {
|
||||
if (p.is_closed) return 'closed'
|
||||
if (p.locked_at) return 'locked'
|
||||
return 'open'
|
||||
}
|
||||
|
||||
// Open is the normal state and renders as muted text; only the deviations
|
||||
// (locked/closed) get a chip (UI-migration convention 5).
|
||||
const STATUS_VARIANT: Record<'closed' | 'locked', 'secondary' | 'warning'> = {
|
||||
closed: 'secondary',
|
||||
locked: 'warning',
|
||||
}
|
||||
|
||||
export function FiscalYearsManager() {
|
||||
const t = useTranslations('settings_bookkeeping')
|
||||
const { toast } = useToast()
|
||||
const { role } = useCompany()
|
||||
const { dialogProps, confirm } = useDestructiveConfirm()
|
||||
// Session-cached registry (lib/reference-data): the same list every
|
||||
// picker renders, so a lock/unlock/reset here is visible everywhere the
|
||||
// moment the cache is invalidated below.
|
||||
const { periods, isLoading, error: periodsError } = useFiscalPeriods()
|
||||
const hasError = !!periodsError && periods.length === 0
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [mutatingId, setMutatingId] = useState<string | null>(null)
|
||||
const [resetTarget, setResetTarget] = useState<FiscalPeriod | null>(null)
|
||||
const [editTarget, setEditTarget] = useState<FiscalPeriod | null>(null)
|
||||
|
||||
// Only owners/admins may change a period's lock state. The API enforces this
|
||||
// too (requireWrite); this just hides controls a viewer/member can't use.
|
||||
const canManage = role === 'owner' || role === 'admin'
|
||||
|
||||
const refreshPeriods = useCallback(() => invalidateReferenceData('ref:fiscal-periods'), [])
|
||||
|
||||
// Newest first: matches the API's ordering and reads most-recent-at-top.
|
||||
const sorted = [...periods].sort((a, b) => b.period_start.localeCompare(a.period_start))
|
||||
|
||||
async function runLockAction(
|
||||
period: FiscalPeriod,
|
||||
action: 'lock' | 'unlock' | 'reopen-external',
|
||||
) {
|
||||
setMutatingId(period.id)
|
||||
try {
|
||||
const res = await fetch(`/api/bookkeeping/fiscal-periods/${period.id}/${action}`, {
|
||||
method: 'POST',
|
||||
})
|
||||
const body = await res.json().catch(() => ({}))
|
||||
if (!res.ok) {
|
||||
// Surface the backend's message verbatim: e.g. "X affärstransaktion(er)
|
||||
// saknar bokföring", which tells the user exactly what to fix first.
|
||||
throw new Error(body?.error?.message || t('fy_action_error'))
|
||||
}
|
||||
toast({
|
||||
title:
|
||||
action === 'lock'
|
||||
? t('fy_lock_success')
|
||||
: action === 'unlock'
|
||||
? t('fy_unlock_success')
|
||||
: t('fy_reopen_success'),
|
||||
})
|
||||
await refreshPeriods()
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: t('fy_action_error'),
|
||||
description: err instanceof Error ? getUserErrorMessage(err) : undefined,
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setMutatingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLock(period: FiscalPeriod) {
|
||||
const ok = await confirm({
|
||||
title: t('fy_lock_confirm_title'),
|
||||
description: t('fy_lock_confirm_body', { name: period.name }),
|
||||
confirmLabel: t('fy_action_lock'),
|
||||
cancelLabel: t('fy_confirm_cancel'),
|
||||
variant: 'warning',
|
||||
})
|
||||
if (ok) await runLockAction(period, 'lock')
|
||||
}
|
||||
|
||||
async function handleUnlock(period: FiscalPeriod) {
|
||||
const ok = await confirm({
|
||||
title: t('fy_unlock_confirm_title'),
|
||||
description: t('fy_unlock_confirm_body', { name: period.name }),
|
||||
confirmLabel: t('fy_action_unlock'),
|
||||
cancelLabel: t('fy_confirm_cancel'),
|
||||
variant: 'warning',
|
||||
})
|
||||
if (ok) await runLockAction(period, 'unlock')
|
||||
}
|
||||
|
||||
// Undo "klarmarkera" (year marked as closed in a previous bookkeeping
|
||||
// system). Only offered while the closed state still comes from that mark:
|
||||
// a year closed by a real year-end run keeps its closing entry and stays
|
||||
// closed here.
|
||||
async function handleReopen(period: FiscalPeriod) {
|
||||
const ok = await confirm({
|
||||
title: t('fy_reopen_confirm_title'),
|
||||
description: t('fy_reopen_confirm_body', { name: period.name }),
|
||||
confirmLabel: t('fy_action_reopen'),
|
||||
cancelLabel: t('fy_confirm_cancel'),
|
||||
variant: 'warning',
|
||||
})
|
||||
if (ok) await runLockAction(period, 'reopen-external')
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsGroup label={t('fy_heading')} help={t('fy_help')}>
|
||||
{isLoading ? (
|
||||
<div className="space-y-2 px-1 py-3">
|
||||
<Skeleton className="h-4 w-48" />
|
||||
<Skeleton className="h-4 w-40" />
|
||||
</div>
|
||||
) : hasError ? (
|
||||
<p className="px-1 py-3 text-sm text-muted-foreground">{t('fy_load_error')}</p>
|
||||
) : sorted.length === 0 ? (
|
||||
<p className="px-1 py-3 text-sm text-muted-foreground">{t('fy_empty')}</p>
|
||||
) : (
|
||||
// Period rows: flat hairline list, no cards.
|
||||
sorted.map((p) => {
|
||||
const status = periodStatus(p)
|
||||
const isMutating = mutatingId === p.id
|
||||
const closedExternally = status === 'closed' && p.closed_externally === true
|
||||
const canReopen = canManage && closedExternally && !p.closing_entry_id
|
||||
return (
|
||||
<div key={p.id} className="flex items-center gap-3 border-b border-border px-1 py-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="text-sm font-medium">{p.name}</span>
|
||||
<span className="ml-2 text-sm text-muted-foreground tabular-nums">
|
||||
{formatDate(p.period_start)} - {formatDate(p.period_end)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-3">
|
||||
{status === 'open' ? (
|
||||
<span className="text-xs text-muted-foreground">{t('fy_status_open')}</span>
|
||||
) : (
|
||||
<Badge variant={STATUS_VARIANT[status]}>
|
||||
{closedExternally ? t('fy_status_closed_external') : t(`fy_status_${status}`)}
|
||||
</Badge>
|
||||
)}
|
||||
{/* Ändra is offered on open years only, like Lås and
|
||||
Nollställ: the PATCH route refuses locked and closed years
|
||||
outright, and the row already carries that chip. */}
|
||||
{canManage && status === 'open' && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
disabled={isMutating}
|
||||
onClick={() => setEditTarget(p)}
|
||||
>
|
||||
<Pencil className="mr-1.5 h-4 w-4" />
|
||||
{t('fy_action_edit')}
|
||||
</Button>
|
||||
)}
|
||||
{canManage && status === 'open' && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
disabled={isMutating}
|
||||
onClick={() => handleLock(p)}
|
||||
>
|
||||
{isMutating ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<>
|
||||
<Lock className="mr-1.5 h-4 w-4" />
|
||||
{t('fy_action_lock')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
{canManage && status === 'open' && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-destructive hover:text-destructive"
|
||||
disabled={isMutating}
|
||||
onClick={() => setResetTarget(p)}
|
||||
>
|
||||
<Eraser className="mr-1.5 h-4 w-4" />
|
||||
{t('fy_action_reset')}
|
||||
</Button>
|
||||
)}
|
||||
{canManage && status === 'locked' && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
disabled={isMutating}
|
||||
onClick={() => handleUnlock(p)}
|
||||
>
|
||||
{isMutating ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<>
|
||||
<Unlock className="mr-1.5 h-4 w-4" />
|
||||
{t('fy_action_unlock')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
{canReopen && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
disabled={isMutating}
|
||||
onClick={() => handleReopen(p)}
|
||||
>
|
||||
{isMutating ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<>
|
||||
<Unlock className="mr-1.5 h-4 w-4" />
|
||||
{t('fy_action_reopen')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)}
|
||||
|
||||
{/* Trailing quiet action: create the next fiscal year. */}
|
||||
<div className="px-1 pt-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
onClick={() => setDialogOpen(true)}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<Plus className="mr-1.5 h-4 w-4" />
|
||||
{t('fy_create')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<CreatePeriodDialog
|
||||
open={dialogOpen}
|
||||
onOpenChange={setDialogOpen}
|
||||
entryDate={suggestSeedDate(periods, new Date().toISOString().split('T')[0])}
|
||||
periods={periods}
|
||||
onCreated={refreshPeriods}
|
||||
/>
|
||||
|
||||
{editTarget && (
|
||||
<FiscalYearEditDialog
|
||||
period={editTarget}
|
||||
open={editTarget !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setEditTarget(null)
|
||||
}}
|
||||
onSaved={refreshPeriods}
|
||||
/>
|
||||
)}
|
||||
|
||||
{resetTarget && (
|
||||
<FiscalYearResetDialog
|
||||
periodId={resetTarget.id}
|
||||
periodName={resetTarget.name}
|
||||
open={resetTarget !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setResetTarget(null)
|
||||
}}
|
||||
onReset={refreshPeriods}
|
||||
/>
|
||||
)}
|
||||
|
||||
<DestructiveConfirmDialog {...dialogProps} />
|
||||
</SettingsGroup>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState, useSyncExternalStore } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { MonitorDown } from 'lucide-react'
|
||||
import {
|
||||
SettingsRow,
|
||||
SettingsRowEnd,
|
||||
SettingsRowNote,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import { useBranding } from '@/lib/branding/brand-context'
|
||||
|
||||
type BeforeInstallPromptEvent = Event & {
|
||||
prompt: () => Promise<void>
|
||||
userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>
|
||||
}
|
||||
|
||||
function subscribeDisplayMode(onChange: () => void) {
|
||||
const mql = window.matchMedia('(display-mode: standalone)')
|
||||
mql.addEventListener('change', onChange)
|
||||
return () => mql.removeEventListener('change', onChange)
|
||||
}
|
||||
|
||||
function getIsStandalone() {
|
||||
return (
|
||||
window.matchMedia('(display-mode: standalone)').matches ||
|
||||
// iOS Safari reports installed mode via navigator.standalone instead
|
||||
(navigator as Navigator & { standalone?: boolean }).standalone === true
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* "Install as app" row for account settings. Chromium fires
|
||||
* beforeinstallprompt when the PWA is installable; we capture it and offer a
|
||||
* real install button. Other browsers get per-platform instructions as the
|
||||
* row's visible note (that text IS the action). Hidden entirely when already
|
||||
* running standalone (installed) or after installing.
|
||||
*/
|
||||
export function InstallAppSection() {
|
||||
const t = useTranslations('settings')
|
||||
const { appName } = useBranding()
|
||||
// Server snapshot says standalone so the row is absent from server HTML
|
||||
// and only appears client-side when actually running in a browser tab.
|
||||
const isStandalone = useSyncExternalStore(subscribeDisplayMode, getIsStandalone, () => true)
|
||||
const [installed, setInstalled] = useState(false)
|
||||
const [installPrompt, setInstallPrompt] = useState<BeforeInstallPromptEvent | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const onBeforeInstallPrompt = (e: Event) => {
|
||||
e.preventDefault()
|
||||
setInstallPrompt(e as BeforeInstallPromptEvent)
|
||||
}
|
||||
const onInstalled = () => {
|
||||
setInstallPrompt(null)
|
||||
setInstalled(true)
|
||||
}
|
||||
window.addEventListener('beforeinstallprompt', onBeforeInstallPrompt)
|
||||
window.addEventListener('appinstalled', onInstalled)
|
||||
return () => {
|
||||
window.removeEventListener('beforeinstallprompt', onBeforeInstallPrompt)
|
||||
window.removeEventListener('appinstalled', onInstalled)
|
||||
}
|
||||
}, [])
|
||||
|
||||
async function handleInstall() {
|
||||
if (!installPrompt) return
|
||||
await installPrompt.prompt()
|
||||
const choice = await installPrompt.userChoice
|
||||
if (choice.outcome === 'accepted') setInstallPrompt(null)
|
||||
}
|
||||
|
||||
if (isStandalone || installed) return null
|
||||
|
||||
const ua = navigator.userAgent
|
||||
const isIos = /iPad|iPhone|iPod/.test(ua)
|
||||
const isSafari = /Safari/.test(ua) && !/Chrome|Chromium|Edg|CriOS/.test(ua)
|
||||
const hint = isIos
|
||||
? t('install_app_hint_ios', { appName })
|
||||
: isSafari
|
||||
? t('install_app_hint_safari', { appName })
|
||||
: t('install_app_hint_generic', { appName })
|
||||
|
||||
return (
|
||||
<SettingsRow label={t('install_app_title')} help={t('install_app_description', { appName })}>
|
||||
{installPrompt ? (
|
||||
<SettingsRowEnd>
|
||||
<Button variant="outline" size="sm" onClick={handleInstall}>
|
||||
<MonitorDown className="mr-2 h-3.5 w-3.5" />
|
||||
{t('install_app_button')}
|
||||
</Button>
|
||||
</SettingsRowEnd>
|
||||
) : (
|
||||
// No captured prompt: the platform-specific instruction is the only
|
||||
// way to act, so it stays visible instead of hiding behind the "?".
|
||||
<SettingsRowNote>{hint}</SettingsRowNote>
|
||||
)}
|
||||
</SettingsRow>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import {
|
||||
SettingsGroup,
|
||||
SettingsRow,
|
||||
SettingsTextarea,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import {
|
||||
EMAIL_PATTERN,
|
||||
MAX_INVOICE_EMAIL_COPY_RECIPIENTS,
|
||||
parseInvoiceRecipientText,
|
||||
} from '@/lib/invoices/email-recipients'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import type { CompanySettings } from '@/types'
|
||||
|
||||
interface InvoiceEmailRecipientsSettingsProps {
|
||||
settings: CompanySettings
|
||||
onUpdate: (updates: Partial<CompanySettings>) => void
|
||||
}
|
||||
|
||||
function listText(addresses: readonly string[]): string {
|
||||
return addresses.join('\n')
|
||||
}
|
||||
|
||||
export function InvoiceEmailRecipientsSettings({
|
||||
settings,
|
||||
onUpdate,
|
||||
}: InvoiceEmailRecipientsSettingsProps) {
|
||||
const t = useTranslations('settings_invoice_email_recipients')
|
||||
const { toast } = useToast()
|
||||
const { role } = useCompany()
|
||||
const effectiveCc = settings.invoice_email_cc_addresses ?? (
|
||||
settings.email ? [settings.email] : []
|
||||
)
|
||||
const effectiveBcc = settings.invoice_email_bcc_addresses ?? []
|
||||
const serverCcText = listText(effectiveCc)
|
||||
const serverBccText = listText(effectiveBcc)
|
||||
const [ccText, setCcText] = useState(serverCcText)
|
||||
const [bccText, setBccText] = useState(serverBccText)
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
const previousServerText = useRef({ cc: serverCcText, bcc: serverBccText })
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousServerText.current
|
||||
setCcText((current) => current === previous.cc ? serverCcText : current)
|
||||
setBccText((current) => current === previous.bcc ? serverBccText : current)
|
||||
previousServerText.current = { cc: serverCcText, bcc: serverBccText }
|
||||
}, [serverBccText, serverCcText])
|
||||
|
||||
if (role !== 'owner' && role !== 'admin') return null
|
||||
|
||||
async function save() {
|
||||
const cc = parseInvoiceRecipientText(ccText)
|
||||
const bcc = parseInvoiceRecipientText(bccText)
|
||||
const invalid = [...cc, ...bcc].find((address) => !EMAIL_PATTERN.test(address))
|
||||
|
||||
if (invalid) {
|
||||
toast({
|
||||
title: t('invalid_title'),
|
||||
description: t('invalid_description', { address: invalid }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
if (cc.length + bcc.length > MAX_INVOICE_EMAIL_COPY_RECIPIENTS) {
|
||||
toast({
|
||||
title: t('too_many_title'),
|
||||
description: t('too_many_description', { count: MAX_INVOICE_EMAIL_COPY_RECIPIENTS }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
setIsSaving(true)
|
||||
try {
|
||||
const response = await fetch('/api/settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
invoice_email_cc_addresses: cc,
|
||||
invoice_email_bcc_addresses: bcc,
|
||||
}),
|
||||
})
|
||||
if (!response.ok) {
|
||||
const result = await response.json()
|
||||
throw new Error(typeof result.error === 'string' ? result.error : t('save_failed'))
|
||||
}
|
||||
|
||||
onUpdate({
|
||||
invoice_email_cc_addresses: cc,
|
||||
invoice_email_bcc_addresses: bcc,
|
||||
})
|
||||
setCcText(listText(cc))
|
||||
setBccText(listText(bcc))
|
||||
toast({ title: t('saved_title'), description: t('saved_description') })
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t('save_failed_title'),
|
||||
description: error instanceof Error ? getUserErrorMessage(error) : t('save_failed'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsGroup label={t('heading')} help={t('description')}>
|
||||
<SettingsRow
|
||||
label={t('cc_label')}
|
||||
htmlFor="invoice-email-cc"
|
||||
help={t('cc_hint')}
|
||||
align="baseline"
|
||||
>
|
||||
<SettingsTextarea
|
||||
id="invoice-email-cc"
|
||||
value={ccText}
|
||||
onChange={(event) => setCcText(event.target.value)}
|
||||
placeholder={t('cc_placeholder')}
|
||||
rows={3}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow
|
||||
label={t('bcc_label')}
|
||||
htmlFor="invoice-email-bcc"
|
||||
help={t('bcc_hint')}
|
||||
align="baseline"
|
||||
>
|
||||
<SettingsTextarea
|
||||
id="invoice-email-bcc"
|
||||
value={bccText}
|
||||
onChange={(event) => setBccText(event.target.value)}
|
||||
placeholder={t('bcc_placeholder')}
|
||||
rows={3}
|
||||
/>
|
||||
</SettingsRow>
|
||||
|
||||
<div className="flex justify-end px-1 pt-4">
|
||||
<Button type="button" size="sm" onClick={save} disabled={isSaving}>
|
||||
{isSaving ? t('saving') : t('save')}
|
||||
</Button>
|
||||
</div>
|
||||
</SettingsGroup>
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user