docs(production): standardiserad produktionsberedskap och gap-analys
Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
@@ -1,385 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Sun, Moon, Monitor, LogOut, ExternalLink } from 'lucide-react'
|
||||
import { useTheme } from 'next-themes'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { SecuritySettings } from '@/components/settings/SecuritySettings'
|
||||
import { EmailDigestToggle } from '@/components/settings/EmailDigestToggle'
|
||||
import { InstallAppSection } from '@/components/settings/InstallAppSection'
|
||||
import { CalendarFeedSettings } from '@/components/settings/CalendarFeedSettings'
|
||||
import { AccountDangerZone } from '@/components/settings/AccountDangerZone'
|
||||
import {
|
||||
SettingsGroup,
|
||||
SettingsInput,
|
||||
SettingsRow,
|
||||
SettingsRowEnd,
|
||||
SettingsSectionHeader,
|
||||
SettingsSeg,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
|
||||
import { useSettings } from '@/components/settings/useSettings'
|
||||
import { resetAnalyticsIdentity } from '@/lib/analytics/reset'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { SUPPORTED_LOCALES, type Locale } from '@/i18n/config'
|
||||
import { PalettePicker } from '@/components/settings/PalettePicker'
|
||||
import { usePalette } from '@/components/providers/PaletteProvider'
|
||||
import type { Palette } from '@/lib/theme/palettes'
|
||||
|
||||
export function AccountSettingsContent() {
|
||||
const router = useRouter()
|
||||
const supabase = createClient()
|
||||
const { theme, setTheme } = useTheme()
|
||||
const { palette, setPalette } = usePalette()
|
||||
const [mounted, setMounted] = useState(false)
|
||||
const hasCalendarExtension = ENABLED_EXTENSION_IDS.has('calendar')
|
||||
const { settings } = useSettings()
|
||||
const { toast } = useToast()
|
||||
const activeLocale = useLocale() as Locale
|
||||
const tCommon = useTranslations('common')
|
||||
const tSettings = useTranslations('settings')
|
||||
const tNav = useTranslations('settings_nav')
|
||||
const tIntro = useTranslations('settings_intro')
|
||||
const [savingLocale, setSavingLocale] = useState(false)
|
||||
const [fullName, setFullName] = useState('')
|
||||
const [initialName, setInitialName] = useState('')
|
||||
const [nameLoading, setNameLoading] = useState(true)
|
||||
const [savingName, setSavingName] = useState(false)
|
||||
const [email, setEmail] = useState('')
|
||||
const [currentEmail, setCurrentEmail] = useState('')
|
||||
const [savingEmail, setSavingEmail] = useState(false)
|
||||
const [pendingEmail, setPendingEmail] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => { setMounted(true) }, [])
|
||||
|
||||
// Pre-fill the name field from profiles.full_name. Self-contained client
|
||||
// fetch: mirrors BankIdSettings.
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
;(async () => {
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) { if (active) setNameLoading(false); return }
|
||||
if (active && user.email) {
|
||||
setEmail(user.email)
|
||||
setCurrentEmail(user.email)
|
||||
}
|
||||
// A change already awaiting confirmation survives a page reload.
|
||||
if (active && user.new_email) setPendingEmail(user.new_email.toLowerCase())
|
||||
const { data } = await supabase
|
||||
.from('profiles')
|
||||
.select('full_name')
|
||||
.eq('id', user.id)
|
||||
.maybeSingle()
|
||||
if (!active) return
|
||||
setFullName(data?.full_name ?? '')
|
||||
setInitialName(data?.full_name ?? '')
|
||||
setNameLoading(false)
|
||||
})()
|
||||
return () => { active = false }
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
async function handleSaveName() {
|
||||
const trimmed = fullName.trim()
|
||||
if (!trimmed || trimmed === initialName || savingName) return
|
||||
setSavingName(true)
|
||||
try {
|
||||
const res = await fetch('/api/user/profile', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ full_name: trimmed }),
|
||||
})
|
||||
if (!res.ok) throw new Error('Could not save')
|
||||
setFullName(trimmed)
|
||||
setInitialName(trimmed)
|
||||
toast({ title: tSettings('name_saved') })
|
||||
router.refresh()
|
||||
} catch {
|
||||
toast({ title: tSettings('name_save_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setSavingName(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSaveEmail() {
|
||||
const trimmed = email.trim().toLowerCase()
|
||||
if (!trimmed || trimmed === currentEmail.toLowerCase() || savingEmail) return
|
||||
setSavingEmail(true)
|
||||
try {
|
||||
const res = await fetch('/api/account/email', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email: trimmed }),
|
||||
})
|
||||
const json = await res.json().catch(() => null)
|
||||
if (!res.ok) {
|
||||
toast({
|
||||
title: tSettings('email_change_failed'),
|
||||
description: getErrorMessage(json, {
|
||||
statusCode: res.status,
|
||||
locale: activeLocale,
|
||||
}),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
setPendingEmail(trimmed)
|
||||
const resent = (json as { data?: { resent?: boolean } } | null)?.data?.resent
|
||||
toast({
|
||||
title:
|
||||
resent === false
|
||||
? tSettings('email_change_already_pending')
|
||||
: tSettings('email_change_requested'),
|
||||
description: tSettings('email_change_requested_help'),
|
||||
})
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: tSettings('email_change_failed'),
|
||||
description: getErrorMessage(err, { locale: activeLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setSavingEmail(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLogout() {
|
||||
resetAnalyticsIdentity()
|
||||
await supabase.auth.signOut()
|
||||
router.push('/login')
|
||||
}
|
||||
|
||||
async function handleLocaleChange(next: Locale) {
|
||||
if (next === activeLocale || savingLocale) return
|
||||
setSavingLocale(true)
|
||||
try {
|
||||
const res = await fetch('/api/user/locale', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ locale: next }),
|
||||
})
|
||||
if (!res.ok) throw new Error('Could not save')
|
||||
toast({ title: tSettings('language_saved') })
|
||||
router.refresh()
|
||||
} catch {
|
||||
toast({
|
||||
title: tSettings('language_save_failed'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setSavingLocale(false)
|
||||
}
|
||||
}
|
||||
|
||||
const localeLabels: Record<Locale, string> = {
|
||||
sv: tCommon('language_swedish'),
|
||||
en: tCommon('language_english'),
|
||||
}
|
||||
|
||||
const paletteLabels: Record<Palette, string> = {
|
||||
neutral: tSettings('palette_neutral'),
|
||||
indigo: tSettings('palette_indigo'),
|
||||
forest: tSettings('palette_forest'),
|
||||
sand: tSettings('palette_sand'),
|
||||
}
|
||||
|
||||
const nameUnchanged = !fullName.trim() || fullName.trim() === initialName
|
||||
|
||||
return (
|
||||
<div>
|
||||
<SettingsSectionHeader title={tNav('account')} intro={tIntro('account')} />
|
||||
|
||||
{/* Profile: name, appearance, language, install-as-app */}
|
||||
<SettingsGroup label={tSettings('group_profile')}>
|
||||
<SettingsRow
|
||||
label={tSettings('name_label')}
|
||||
htmlFor="full_name"
|
||||
help={tSettings('name_description')}
|
||||
align="baseline"
|
||||
>
|
||||
<SettingsInput
|
||||
id="full_name"
|
||||
value={fullName}
|
||||
onChange={(e) => setFullName(e.target.value)}
|
||||
placeholder={tSettings('name_placeholder')}
|
||||
disabled={nameLoading || savingName}
|
||||
maxLength={100}
|
||||
/>
|
||||
<SettingsRowEnd>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleSaveName}
|
||||
disabled={nameLoading || savingName || nameUnchanged}
|
||||
>
|
||||
{savingName ? tCommon('saving') : tCommon('save')}
|
||||
</Button>
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow
|
||||
label={tSettings('email_label')}
|
||||
htmlFor="account_email"
|
||||
help={
|
||||
pendingEmail
|
||||
? tSettings('email_change_pending', { email: pendingEmail })
|
||||
: tSettings('email_description')
|
||||
}
|
||||
align="baseline"
|
||||
>
|
||||
<SettingsInput
|
||||
id="account_email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
disabled={!currentEmail || savingEmail}
|
||||
maxLength={320}
|
||||
/>
|
||||
<SettingsRowEnd>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleSaveEmail}
|
||||
disabled={
|
||||
!currentEmail ||
|
||||
savingEmail ||
|
||||
!email.trim() ||
|
||||
email.trim().toLowerCase() === currentEmail.toLowerCase()
|
||||
}
|
||||
>
|
||||
{savingEmail
|
||||
? tCommon('saving')
|
||||
: email.trim().toLowerCase() === pendingEmail
|
||||
? tSettings('email_resend')
|
||||
: tCommon('save')}
|
||||
</Button>
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow label={tSettings('section_appearance')}>
|
||||
{mounted && (
|
||||
<SettingsSeg
|
||||
value={theme ?? 'system'}
|
||||
onChange={setTheme}
|
||||
aria-label={tSettings('section_appearance')}
|
||||
options={[
|
||||
{
|
||||
value: 'light',
|
||||
label: (
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<Sun className="h-3.5 w-3.5" />
|
||||
{tCommon('theme_light')}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
value: 'dark',
|
||||
label: (
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<Moon className="h-3.5 w-3.5" />
|
||||
{tCommon('theme_dark')}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
value: 'system',
|
||||
label: (
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<Monitor className="h-3.5 w-3.5" />
|
||||
{tCommon('theme_system')}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow
|
||||
label={tSettings('palette_label')}
|
||||
help={tSettings('palette_description')}
|
||||
align="baseline"
|
||||
>
|
||||
{mounted && (
|
||||
<PalettePicker
|
||||
value={palette}
|
||||
onChange={setPalette}
|
||||
labels={paletteLabels}
|
||||
aria-label={tSettings('palette_label')}
|
||||
/>
|
||||
)}
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow
|
||||
label={tSettings('section_language')}
|
||||
help={tSettings('language_description')}
|
||||
>
|
||||
<SettingsSeg
|
||||
value={activeLocale}
|
||||
onChange={(next) => void handleLocaleChange(next)}
|
||||
disabled={savingLocale}
|
||||
aria-label={tSettings('section_language')}
|
||||
options={SUPPORTED_LOCALES.map((value) => ({
|
||||
value,
|
||||
label: localeLabels[value],
|
||||
}))}
|
||||
/>
|
||||
</SettingsRow>
|
||||
|
||||
{/* Install as app: renders nothing when already running installed */}
|
||||
<InstallAppSection />
|
||||
</SettingsGroup>
|
||||
|
||||
{/* Security: BankID, password, 2FA (renders its own group) */}
|
||||
<SecuritySettings />
|
||||
|
||||
{/* Notifications: daily "nytt att bokfora" email digest opt-in */}
|
||||
<EmailDigestToggle />
|
||||
|
||||
{/* Calendar feed (extension-gated) */}
|
||||
{hasCalendarExtension && <CalendarFeedSettings />}
|
||||
|
||||
{/* Privacy & agreements: surface the otherwise-unlinked DPA + privacy policy */}
|
||||
<SettingsGroup label={tSettings('legal_title')}>
|
||||
<SettingsRow label={tSettings('legal_privacy')}>
|
||||
<SettingsRowEnd>
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<Link href="/privacy" target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="mr-2 h-3.5 w-3.5" />
|
||||
{tCommon('open')}
|
||||
</Link>
|
||||
</Button>
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
<SettingsRow label={tSettings('legal_dpa')}>
|
||||
<SettingsRowEnd>
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<Link href="/dpa" target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="mr-2 h-3.5 w-3.5" />
|
||||
{tCommon('open')}
|
||||
</Link>
|
||||
</Button>
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
|
||||
{/* Sign out */}
|
||||
<SettingsGroup>
|
||||
<SettingsRow label={tCommon('logout')} help={tCommon('logout_description')}>
|
||||
<SettingsRowEnd>
|
||||
<Button variant="outline" size="sm" onClick={handleLogout}>
|
||||
<LogOut className="mr-2 h-3.5 w-3.5" />
|
||||
{tCommon('logout')}
|
||||
</Button>
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
|
||||
{/* Delete account: only for non-sandbox */}
|
||||
{!settings?.is_sandbox && <AccountDangerZone />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { ApiKeysPanel } from '@/components/settings/ApiKeysPanel'
|
||||
import { OAuthClientsPanel } from '@/components/settings/OAuthClientsPanel'
|
||||
import { SettingsSectionHeader } from '@/components/settings/SettingsRows'
|
||||
|
||||
export function ApiSettingsContent() {
|
||||
const tNav = useTranslations('settings_nav')
|
||||
const tIntro = useTranslations('settings_intro')
|
||||
|
||||
return (
|
||||
<div>
|
||||
<SettingsSectionHeader title={tNav('api')} intro={tIntro('api')} />
|
||||
<ApiKeysPanel />
|
||||
<OAuthClientsPanel />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,226 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useId, useState } from 'react'
|
||||
import { useSearchParams, useRouter } from 'next/navigation'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { AttnLine } from '@/components/ui/attn-line'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
import { AgentMemoryPanel } from '@/components/settings/AgentMemoryPanel'
|
||||
import { AgentSkillsPanel } from '@/components/settings/AgentSkillsPanel'
|
||||
import { AgentKnowledgePanel } from '@/components/agent-knowledge/AgentKnowledgePanel'
|
||||
import {
|
||||
SettingsGroup,
|
||||
SettingsRow,
|
||||
SettingsRowEnd,
|
||||
SettingsSectionHeader,
|
||||
SettingsSeg,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
|
||||
// "Assistenten": the ledger profile the agent reads before booking (Kunskap =
|
||||
// "Vad din agent vet", opens on the konteringskarta and is the default view),
|
||||
// what the assistant remembers about this company (Minne, editable), and the
|
||||
// domain knowledge it ships with (Kompetens, read-only). The segmented control
|
||||
// keeps all three one click away instead of stacked.
|
||||
type View = 'knowledge' | 'memory' | 'skills'
|
||||
|
||||
const VIEW_ROUTE: Record<View, string> = {
|
||||
knowledge: '/settings/assistant',
|
||||
memory: '/settings/assistant?view=memory',
|
||||
skills: '/settings/assistant?view=skills',
|
||||
}
|
||||
|
||||
const VIEW_OPTIONS: Array<{ value: View; label: string }> = [
|
||||
{ value: 'knowledge', label: 'Kunskap' },
|
||||
{ value: 'memory', label: 'Minne' },
|
||||
{ value: 'skills', label: 'Kompetens' },
|
||||
]
|
||||
|
||||
export function AssistantSettingsContent() {
|
||||
const tNav = useTranslations('settings_nav')
|
||||
const tIntro = useTranslations('settings_intro')
|
||||
const searchParams = useSearchParams()
|
||||
const router = useRouter()
|
||||
const raw = searchParams.get('view')
|
||||
const view: View = raw === 'skills' ? 'skills' : raw === 'memory' ? 'memory' : 'knowledge'
|
||||
|
||||
function setView(next: View) {
|
||||
// 'knowledge' is the default: keep its URL clean (no query string).
|
||||
router.replace(VIEW_ROUTE[next] ?? VIEW_ROUTE.knowledge, { scroll: false })
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<SettingsSectionHeader title={tNav('assistant')} intro={tIntro('assistant')} />
|
||||
|
||||
<div className="mt-6">
|
||||
<SettingsSeg value={view} onChange={setView} options={VIEW_OPTIONS} aria-label="Välj vy" />
|
||||
</div>
|
||||
|
||||
{/* Only the active view mounts, so each panel's data is fetched lazily
|
||||
the first time its view is opened (same behavior as when Radix Tabs
|
||||
unmounted the inactive panels). */}
|
||||
<div className="mt-6">
|
||||
{view === 'knowledge' && <AgentKnowledgePanel />}
|
||||
{view === 'memory' && <AgentMemoryPanel />}
|
||||
{view === 'skills' && <AgentSkillsPanel />}
|
||||
</div>
|
||||
|
||||
<FabVisibilityRow />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Per-user toggle for the floating assistant button bottom-right. The value
|
||||
// lives on user_preferences (server-rendered into the dashboard layout), so
|
||||
// a successful save triggers router.refresh() to make the button react
|
||||
// immediately instead of on next navigation.
|
||||
function FabVisibilityRow() {
|
||||
const t = useTranslations('settings_assistant')
|
||||
const errorLocale = useLocale() as ErrorLocale
|
||||
const { toast } = useToast()
|
||||
const router = useRouter()
|
||||
// null = the value is not known: still loading, or the read failed (loadError).
|
||||
const [hideFab, setHideFab] = useState<boolean | 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 [saving, setSaving] = useState(false)
|
||||
const errorId = useId()
|
||||
|
||||
// A settings row that cannot read its own value must not render one.
|
||||
// Defaulting to false on a failed GET drew a loaded-looking, interactive
|
||||
// switch in the "assistant button visible" position whatever the stored
|
||||
// preference was, and here that claim is contradicted on screen: the button
|
||||
// is server-rendered from the same column in the dashboard layout, so an
|
||||
// empty corner sat next to a switch insisting it was on.
|
||||
//
|
||||
// So the unknown value stays unknown: the switch keeps its disabled state and
|
||||
// one line says the value could not be read. 401/403 is the only case where
|
||||
// the reason changes what the user must do, so that message (from the same
|
||||
// status map the save path uses) replaces the retry instead of sitting next
|
||||
// to it; everything else is transient and the retry is the whole answer.
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
async function load() {
|
||||
setLoadError(null)
|
||||
try {
|
||||
const res = await fetch('/api/user/preferences')
|
||||
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
|
||||
setHideFab(null)
|
||||
setLoadError({
|
||||
detail: sessionGone
|
||||
? getErrorMessage(body, { statusCode: res.status, locale: errorLocale })
|
||||
: null,
|
||||
})
|
||||
return
|
||||
}
|
||||
// A 200 whose body will not parse is a failed read too: let it land in
|
||||
// the catch below rather than become a fabricated `false`.
|
||||
const body = await res.json()
|
||||
if (!cancelled) setHideFab(Boolean(body?.data?.hide_assistant_fab))
|
||||
} catch {
|
||||
if (!cancelled) {
|
||||
setHideFab(null)
|
||||
setLoadError({ detail: null })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void load()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [reloadKey, errorLocale])
|
||||
|
||||
// Rolling the switch back is necessary but not sufficient: a switch that
|
||||
// flips and flips again reads as a broken control, not as a refused save, so
|
||||
// the user retries the same click instead of signing in again (401 on an
|
||||
// expired session is by far the likeliest refusal here, and the status map
|
||||
// says exactly that). One toast per failed click, never two: TOAST_LIMIT is
|
||||
// 1 (components/ui/use-toast.tsx) and a second would evict the first.
|
||||
//
|
||||
// Only the fetch sits inside the try. A router.refresh() that threw must not
|
||||
// roll the switch back and claim the save failed, because by then the write
|
||||
// has landed.
|
||||
async function handleToggle(showFab: boolean) {
|
||||
const nextHide = !showFab
|
||||
const previous = hideFab
|
||||
setHideFab(nextHide)
|
||||
setSaving(true)
|
||||
try {
|
||||
const res = await fetch('/api/user/preferences', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ hide_assistant_fab: nextHide }),
|
||||
})
|
||||
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)
|
||||
setHideFab(previous)
|
||||
toast({
|
||||
title: t('fab_save_failed'),
|
||||
description: getErrorMessage(body, {
|
||||
statusCode: res.status,
|
||||
locale: errorLocale,
|
||||
}),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
} catch (err) {
|
||||
setHideFab(previous)
|
||||
toast({
|
||||
title: t('fab_save_failed'),
|
||||
description: getErrorMessage(err, { locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
router.refresh()
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsGroup>
|
||||
<SettingsRow label={t('fab_title')} help={t('fab_description')}>
|
||||
{/* 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">
|
||||
{loadError && (
|
||||
<AttnLine
|
||||
action={
|
||||
loadError.detail
|
||||
? undefined
|
||||
: { label: t('fab_load_retry'), onClick: () => setReloadKey((k) => k + 1) }
|
||||
}
|
||||
>
|
||||
{loadError.detail
|
||||
? `${t('fab_load_failed')} ${loadError.detail}`
|
||||
: t('fab_load_failed')}
|
||||
</AttnLine>
|
||||
)}
|
||||
</div>
|
||||
<SettingsRowEnd>
|
||||
<Switch
|
||||
checked={hideFab === null ? true : !hideFab}
|
||||
onCheckedChange={handleToggle}
|
||||
disabled={hideFab === null || saving}
|
||||
aria-label={t('fab_title')}
|
||||
aria-describedby={loadError ? errorId : undefined}
|
||||
/>
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
)
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useSearchParams, useRouter } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { AlertTriangle, CreditCard, ExternalLink } from 'lucide-react'
|
||||
import { getSettingsPanel } from '@/lib/extensions/settings-panel-registry'
|
||||
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
|
||||
import { SettingsSectionHeader } from '@/components/settings/SettingsRows'
|
||||
import { useBranding } from '@/lib/branding/brand-context'
|
||||
|
||||
const BankingPanel = getSettingsPanel('enable-banking')
|
||||
|
||||
export function BankingSettingsContent() {
|
||||
const t = useTranslations('settings_banking')
|
||||
const tNav = useTranslations('settings_nav')
|
||||
const tIntro = useTranslations('settings_intro')
|
||||
const { appName } = useBranding()
|
||||
const searchParams = useSearchParams()
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
const [bankConnectionError, setBankConnectionError] = useState<string | null>(null)
|
||||
const [failedBankName, setFailedBankName] = useState<string | null>(null)
|
||||
const [isAccessDenied, setIsAccessDenied] = useState(false)
|
||||
const [showHbPoaHint, setShowHbPoaHint] = useState(false)
|
||||
const hasBankingExtension = ENABLED_EXTENSION_IDS.has('enable-banking')
|
||||
|
||||
// Surface a bank connection/authorization failure that the OAuth callback
|
||||
// bounced back as `?bank_error=...`. The success path is handled by the
|
||||
// callback redirecting to `?select_accounts=<id>`, which the banking panel
|
||||
// picks up to open account selection: there is no `bank_connected` param.
|
||||
useEffect(() => {
|
||||
const bankError = searchParams.get('bank_error')
|
||||
if (!bankError) return
|
||||
|
||||
let errorMsg: string
|
||||
try { errorMsg = decodeURIComponent(bankError) } catch { errorMsg = bankError }
|
||||
const bankName = searchParams.get('bank_name')
|
||||
const errorCode = searchParams.get('bank_error_code')
|
||||
const psuType = searchParams.get('psu_type')
|
||||
// The bank often returns a bare "server_error" with no description: show a
|
||||
// human message instead of the raw OAuth error code.
|
||||
if (errorCode === 'server_error' && errorMsg === 'server_error') {
|
||||
errorMsg = t('bank_server_error')
|
||||
}
|
||||
|
||||
// Consume the one-shot ?bank_error= param off the render path: a microtask
|
||||
// defers these updates out of the effect body (react-hooks/set-state-in-
|
||||
// effect) without a user-visible delay, since the param appears at most
|
||||
// once per OAuth bounce-back. The cancellation flag drops the deferred work
|
||||
// if the effect re-runs or the component unmounts before it flushes (also
|
||||
// suppresses a duplicate toast under StrictMode's dev double-invoke).
|
||||
let cancelled = false
|
||||
queueMicrotask(() => {
|
||||
if (cancelled) return
|
||||
toast({
|
||||
title: t('connect_failed_title'),
|
||||
description: errorMsg,
|
||||
variant: 'destructive',
|
||||
})
|
||||
setBankConnectionError(errorMsg)
|
||||
if (bankName) setFailedBankName(bankName)
|
||||
if (errorCode === 'access_denied') setIsAccessDenied(true)
|
||||
// Handelsbanken rejects business connects with server_error when the
|
||||
// company hasn't registered the open banking fullmakt ("Internet
|
||||
// Företag – tilläggstjänst API Företag"): surface the fix steps.
|
||||
if (bankName === 'Handelsbanken' && psuType === 'business' && errorCode === 'server_error') {
|
||||
setShowHbPoaHint(true)
|
||||
}
|
||||
router.replace('/settings/banking')
|
||||
})
|
||||
return () => { cancelled = true }
|
||||
}, [searchParams, router, toast, t])
|
||||
|
||||
return (
|
||||
<div>
|
||||
<SettingsSectionHeader title={tNav('banking')} intro={tIntro('banking', { appName })} />
|
||||
|
||||
{/* OAuth bounce-back failure: a live warning, so it stays visible in the
|
||||
page flow, as compact warning-tone lines instead of a bordered box. */}
|
||||
{bankConnectionError && (
|
||||
<div role="alert" className="mt-6 flex items-start gap-2 px-1">
|
||||
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-attn" />
|
||||
<div className="min-w-0 flex-1 space-y-1 text-[12.5px] leading-relaxed">
|
||||
<p className="text-attn">{bankConnectionError}</p>
|
||||
{isAccessDenied && failedBankName && (
|
||||
<p className="text-muted-foreground">
|
||||
{t('access_denied_hint', { bankName: failedBankName })}
|
||||
</p>
|
||||
)}
|
||||
{showHbPoaHint && (
|
||||
<p className="text-muted-foreground">
|
||||
{t('hb_business_poa_hint')}{' '}
|
||||
<a
|
||||
href="https://tilisy.enablebanking.com/guides/SE/Handelsbanken/"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="underline underline-offset-2 hover:text-foreground"
|
||||
>
|
||||
{t('hb_business_poa_link')}
|
||||
</a>
|
||||
</p>
|
||||
)}
|
||||
<p className="text-muted-foreground">
|
||||
{t('import_fallback_text')}<Link href="/import?mode=bank" className="underline underline-offset-2 hover:text-foreground">{t('import_fallback_link')}</Link>{t('import_fallback_suffix')}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => {
|
||||
setBankConnectionError(null)
|
||||
setFailedBankName(null)
|
||||
setIsAccessDenied(false)
|
||||
setShowHbPoaHint(false)
|
||||
}}
|
||||
className="shrink-0 rounded-sm p-1 text-muted-foreground transition-colors duration-150 hover:text-foreground"
|
||||
aria-label={t('dismiss_aria')}
|
||||
>
|
||||
<span className="text-lg leading-none">×</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hasBankingExtension && BankingPanel ? (
|
||||
// No BankSyncStatusChip here: on this page the chip links to itself,
|
||||
// and the panel now carries its own single attention sentence. The
|
||||
// chip stays on /transactions.
|
||||
<BankingPanel />
|
||||
) : (
|
||||
<div className="pt-8">
|
||||
<EmptyState
|
||||
icon={CreditCard}
|
||||
title={t('not_enabled_title')}
|
||||
description={t('not_enabled_description')}
|
||||
>
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/extensions">
|
||||
<ExternalLink className="mr-2 h-4 w-4" />
|
||||
{t('go_to_extensions')}
|
||||
</Link>
|
||||
</Button>
|
||||
</EmptyState>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,360 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { Check } from 'lucide-react'
|
||||
import { AttnLine } from '@/components/ui/attn-line'
|
||||
import { HelpPopover } from '@/components/ui/help-popover'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
import {
|
||||
SettingsGroup,
|
||||
SettingsRow,
|
||||
SettingsRowEnd,
|
||||
SettingsRowNote,
|
||||
SettingsSectionHeader,
|
||||
SettingsSeg,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import { cn, formatCurrency } from '@/lib/utils'
|
||||
import { useFormat } from '@/lib/hooks/use-format'
|
||||
import { BillingActions } from '@/components/settings/BillingActions'
|
||||
import { ConnectorSettingsSection } from '@/components/settings/ConnectorSettingsSection'
|
||||
import { PLAN_PRICES } from '@/components/settings/billing-plans'
|
||||
import type { BillingPlan } from '@/lib/stripe/client'
|
||||
import { useBranding } from '@/lib/branding/brand-context'
|
||||
|
||||
// What the paid tier unlocks: the external connections. One item per PAID
|
||||
// capability in lib/entitlements/keys.ts (ai, bank_sync, skatteverket,
|
||||
// email_send, stripe_payments, woocommerce_sync + shopify_sync as one
|
||||
// "webshop" item). Keep in step with PAID_CAPABILITIES when a key is added.
|
||||
const UNLOCK_KEYS = ['unlock_ai', 'unlock_bank', 'unlock_skv', 'unlock_email', 'unlock_payments', 'unlock_webshop', 'unlock_users'] as const
|
||||
|
||||
// Mirrors the checkout route's deferred-first-charge condition (Stripe's 48h
|
||||
// trial_end floor plus clock margin). Above this, checkout collects the card
|
||||
// but the first charge lands when the trial ends.
|
||||
const DEFER_THRESHOLD_MS = 49 * 3600 * 1000
|
||||
|
||||
interface BillingView {
|
||||
isPaying: boolean
|
||||
configured: boolean
|
||||
trialEndsAt: string | null
|
||||
daysLeft: number | null
|
||||
chargeDeferred: boolean
|
||||
paidJustNow: boolean
|
||||
isDemo: boolean
|
||||
/**
|
||||
* WL-10: present when the company is covered by its byrå team's agreement
|
||||
* (active team-scoped manual grant). Replaces the upgrade pitch with a
|
||||
* read-only "Ingår i <teamName>s avtal" state.
|
||||
*/
|
||||
teamAgreement: { teamName: string } | null
|
||||
}
|
||||
|
||||
function UnlockList({ className }: { className?: string }) {
|
||||
const t = useTranslations('settings_billing')
|
||||
return (
|
||||
<ul className={cn('grid gap-x-6 gap-y-3 px-1 sm:grid-cols-2', className)}>
|
||||
{UNLOCK_KEYS.map((key) => (
|
||||
<li key={key} className="text-sm">
|
||||
<span className="font-medium">{t(key)}</span>
|
||||
<span className="block text-xs text-muted-foreground">{t(`${key}_gloss`)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings → Abonnemang. Rendered both as the full page (thin wrapper) and
|
||||
* inside the settings modal (via SETTINGS_SECTIONS), so it's a client component
|
||||
* that reads its state from GET /api/billing/status.
|
||||
*
|
||||
* The sell view is deliberately an order summary in the Fönster row grammar:
|
||||
* what you unlock, then price / first charge / how to cancel as flat rows,
|
||||
* then one CTA. The money terms are stated once each, where the decision is
|
||||
* made, instead of repeated as reassurance copy around the page.
|
||||
*/
|
||||
export function BillingSettingsContent() {
|
||||
return (
|
||||
<>
|
||||
<BillingCoreContent />
|
||||
{/* Self-host only (renders null on hosted): connector status + manual
|
||||
entitlement sync. Sits below the billing states, which is why the
|
||||
core content is split out: it has several early returns. */}
|
||||
<ConnectorSettingsSection />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function BillingCoreContent() {
|
||||
const tNav = useTranslations('settings_nav')
|
||||
const tIntro = useTranslations('settings_intro')
|
||||
const t = useTranslations('settings_billing')
|
||||
const { appName } = useBranding()
|
||||
const errorLocale = useLocale() as ErrorLocale
|
||||
const { formatDateLong } = useFormat()
|
||||
// null = the billing state is not known: still loading, or the read failed
|
||||
// (loadError). A failed GET must never render a fabricated non-paying,
|
||||
// unconfigured panel to a paying customer.
|
||||
const [view, setView] = useState<BillingView | 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 [plan, setPlan] = useState<BillingPlan>('yearly')
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
|
||||
async function load() {
|
||||
setLoadError(null)
|
||||
try {
|
||||
const res = await fetch('/api/billing/status')
|
||||
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 (!active) return
|
||||
const sessionGone = res.status === 401 || res.status === 403
|
||||
setView(null)
|
||||
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 expected booleans is a failed read too. Neither may
|
||||
// become a fabricated view.
|
||||
const d = (await res.json()) as {
|
||||
isPaying?: unknown
|
||||
configured?: unknown
|
||||
trialEndsAt?: unknown
|
||||
isDemo?: unknown
|
||||
teamAgreement?: unknown
|
||||
}
|
||||
if (!active) return
|
||||
if (typeof d?.isPaying !== 'boolean' || typeof d?.configured !== 'boolean') {
|
||||
setView(null)
|
||||
setLoadError({ detail: null })
|
||||
return
|
||||
}
|
||||
const trialEndsAt = typeof d.trialEndsAt === 'string' ? d.trialEndsAt : null
|
||||
// Compute time-derived state here (effect), not during render, to keep render pure.
|
||||
const msLeft = trialEndsAt ? new Date(trialEndsAt).getTime() - Date.now() : null
|
||||
const daysLeft = msLeft !== null ? Math.max(0, Math.ceil(msLeft / 86_400_000)) : null
|
||||
const chargeDeferred = msLeft !== null && msLeft > DEFER_THRESHOLD_MS
|
||||
// Set by the checkout success redirect. Provisioning happens via the
|
||||
// Stripe webhook, so isPaying can lag the redirect by a few seconds.
|
||||
const paidJustNow = new URLSearchParams(window.location.search).get('success') === '1'
|
||||
// Only a well-formed teamAgreement (non-empty team name) activates the
|
||||
// read-only agreement state: anything else falls back to the normal view.
|
||||
const rawAgreement = d.teamAgreement as { teamName?: unknown } | null | undefined
|
||||
const teamAgreement =
|
||||
rawAgreement && typeof rawAgreement.teamName === 'string' && rawAgreement.teamName.length > 0
|
||||
? { teamName: rawAgreement.teamName }
|
||||
: null
|
||||
setView({
|
||||
isPaying: d.isPaying,
|
||||
configured: d.configured,
|
||||
trialEndsAt,
|
||||
daysLeft,
|
||||
chargeDeferred,
|
||||
paidJustNow,
|
||||
isDemo: d.isDemo === true,
|
||||
teamAgreement,
|
||||
})
|
||||
} catch {
|
||||
if (active) {
|
||||
setView(null)
|
||||
setLoadError({ detail: null })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void load()
|
||||
return () => { active = false }
|
||||
}, [reloadKey, errorLocale])
|
||||
|
||||
const header = <SettingsSectionHeader title={tNav('billing')} intro={tIntro('billing')} />
|
||||
|
||||
if (!view) {
|
||||
return (
|
||||
<div>
|
||||
{header}
|
||||
{/* Live region always mounted so the failure is announced when it
|
||||
appears, not merely inserted. */}
|
||||
<div role="status" aria-live="polite" className="mt-3">
|
||||
{loadError && (
|
||||
<AttnLine
|
||||
action={
|
||||
loadError.detail
|
||||
? undefined
|
||||
: { label: t('load_retry'), onClick: () => setReloadKey((k) => k + 1) }
|
||||
}
|
||||
>
|
||||
{loadError.detail ? `${t('load_failed')} ${loadError.detail}` : t('load_failed')}
|
||||
</AttnLine>
|
||||
)}
|
||||
</div>
|
||||
{!loadError && (
|
||||
<div className="mt-6 space-y-4">
|
||||
<Skeleton className="h-12 w-full" />
|
||||
<Skeleton className="h-64 w-full" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Demo / sandbox account → can't check out. Show the value prop but point
|
||||
// them to creating a real account instead of a pay button that would 403.
|
||||
if (view.isDemo) {
|
||||
return (
|
||||
<div>
|
||||
{header}
|
||||
<SettingsGroup label={t('group_yours')}>
|
||||
<SettingsRow label={t('row_status')} borderless>
|
||||
<span>{t('status_demo')}</span>
|
||||
<SettingsRowNote>{t('status_demo_note', { appName })}</SettingsRowNote>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
<SettingsGroup label={t('group_included')}>
|
||||
<UnlockList className="pt-3" />
|
||||
</SettingsGroup>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Paying company → manage view.
|
||||
if (view.isPaying) {
|
||||
return (
|
||||
<div>
|
||||
{header}
|
||||
<SettingsGroup label={t('group_yours')}>
|
||||
<SettingsRow label={t('row_status')}>
|
||||
<span className="font-medium">{t('status_active')}</span>
|
||||
<SettingsRowNote>{t('status_active_note')}</SettingsRowNote>
|
||||
</SettingsRow>
|
||||
<SettingsRow label={t('row_manage')} borderless>
|
||||
<SettingsRowNote>{t('manage_note')}</SettingsRowNote>
|
||||
<SettingsRowEnd>
|
||||
<BillingActions isPaying configured={view.configured} />
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
<SettingsGroup label={t('group_included')}>
|
||||
<UnlockList className="pt-3" />
|
||||
</SettingsGroup>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Just returned from checkout but the webhook hasn't flipped isPaying yet →
|
||||
// confirm instead of re-showing the sell pitch to someone who already paid.
|
||||
if (view.paidJustNow) {
|
||||
return (
|
||||
<div>
|
||||
{header}
|
||||
<SettingsGroup label={t('group_yours')}>
|
||||
<SettingsRow label={t('row_status')} borderless>
|
||||
<span className="flex items-start gap-2">
|
||||
<Check aria-hidden="true" className="mt-1 h-3.5 w-3.5 shrink-0 text-foreground" />
|
||||
<span>{t('paid_just_now')}</span>
|
||||
</span>
|
||||
<SettingsRowNote>{t('paid_just_now_note')}</SettingsRowNote>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Covered by the byrå team's agreement (WL-10) → read-only state instead
|
||||
// of the upgrade pitch and Stripe checkout. The page stays visible for
|
||||
// transparency; billing is the byrå's, so there is nothing to manage here.
|
||||
if (view.teamAgreement) {
|
||||
return (
|
||||
<div>
|
||||
{header}
|
||||
<SettingsGroup label={t('group_yours')}>
|
||||
<SettingsRow label={t('row_status')} borderless>
|
||||
<span className="font-medium">
|
||||
{t('team_agreement_status', { teamName: view.teamAgreement.teamName })}
|
||||
</span>
|
||||
<SettingsRowNote>{t('team_agreement_note')}</SettingsRowNote>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
<SettingsGroup label={t('group_included')}>
|
||||
<UnlockList className="pt-3" />
|
||||
</SettingsGroup>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Trialing / expired → sell view: one number, four short lines, one
|
||||
// button, two quiet sentences. Everything else lives behind the "?".
|
||||
const { trialEndsAt, daysLeft, chargeDeferred } = view
|
||||
const price = PLAN_PRICES[plan]
|
||||
const priceNote =
|
||||
plan === 'yearly'
|
||||
? t('price_note_yearly', { inc: formatCurrency(price.incVat), perMonth: formatCurrency(price.perMonthEquivalent) })
|
||||
: t('price_note_monthly', { inc: formatCurrency(price.incVat) })
|
||||
const termsLine =
|
||||
chargeDeferred && trialEndsAt
|
||||
? t('terms_deferred', { date: formatDateLong(trialEndsAt) })
|
||||
: t('terms_now')
|
||||
|
||||
return (
|
||||
<div>
|
||||
{header}
|
||||
|
||||
{/* Consequential trial countdown: one attn-tone sentence, not a banner. */}
|
||||
{daysLeft !== null && (
|
||||
<AttnLine className="mt-3">
|
||||
{daysLeft > 0
|
||||
? t('trial_ends_in', { days: daysLeft, date: trialEndsAt ? formatDateLong(trialEndsAt) : '' })
|
||||
: t('trial_ended')}
|
||||
</AttnLine>
|
||||
)}
|
||||
|
||||
<div className="mt-8 flex flex-wrap items-start justify-between gap-x-6 gap-y-3 px-1">
|
||||
<div>
|
||||
<p className="font-display text-xl tabular-nums leading-8">
|
||||
{formatCurrency(price.exVat)}
|
||||
<span className="text-muted-foreground"> / {t(`period_${plan}`)}</span>
|
||||
</p>
|
||||
<p className="text-xs tabular-nums text-muted-foreground">{priceNote}</p>
|
||||
</div>
|
||||
<SettingsSeg
|
||||
value={plan}
|
||||
onChange={setPlan}
|
||||
aria-label={t('row_interval')}
|
||||
options={[
|
||||
{ value: 'monthly', label: t('interval_monthly') },
|
||||
{
|
||||
value: 'yearly',
|
||||
label: (
|
||||
<>
|
||||
{t('interval_yearly')}
|
||||
<span className="ml-2 text-muted-foreground">{t('interval_yearly_save')}</span>
|
||||
</>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<UnlockList className="mt-6 border-t border-border pt-6" />
|
||||
|
||||
<div className="mt-8 border-t border-border px-1 pt-6">
|
||||
<BillingActions isPaying={false} configured={view.configured} plan={plan} firstChargeDeferred={chargeDeferred} />
|
||||
<p className="pt-3 text-xs text-muted-foreground">{termsLine}</p>
|
||||
<p className="pt-1 text-xs text-muted-foreground">
|
||||
{t('without_note')}{' '}
|
||||
<HelpPopover className="ml-1 align-middle">{t('unlock_help')}</HelpPopover>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,213 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { SettingsFormWrapper } from '@/components/settings/SettingsFormWrapper'
|
||||
import { SettingsLoadError } from '@/components/settings/SettingsLoadError'
|
||||
import { SettingsLoadingSkeleton } from '@/components/settings/SettingsLoadingSkeleton'
|
||||
import { PeriodLockingSettings } from '@/components/settings/PeriodLockingSettings'
|
||||
import { FiscalYearsManager } from '@/components/settings/FiscalYearsManager'
|
||||
import { VoucherSeriesManager } from '@/components/settings/VoucherSeriesManager'
|
||||
import { VoucherSeriesPerSourceTypeForm } from '@/components/settings/VoucherSeriesPerSourceTypeForm'
|
||||
import { VoucherSeriesPerCashAccountForm } from '@/components/settings/VoucherSeriesPerCashAccountForm'
|
||||
import { applyDefaultSeriesToMap, voucherSeriesLabel } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import { DimensionsToggle } from '@/components/settings/DimensionsToggle'
|
||||
import { MileageToggle } from '@/components/settings/MileageToggle'
|
||||
import { SalesOrdersToggle } from '@/components/settings/SalesOrdersToggle'
|
||||
import { AccountingFrameworkForm } from '@/components/settings/AccountingFrameworkForm'
|
||||
import {
|
||||
SettingsGroup,
|
||||
SettingsRow,
|
||||
SettingsSectionHeader,
|
||||
SettingsSelect,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import { useSettings } from '@/components/settings/useSettings'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { ExternalLink } from 'lucide-react'
|
||||
import type { AccountingFramework, CompanySettings } from '@/types'
|
||||
|
||||
const SERIES_OPTIONS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
|
||||
|
||||
export function BookkeepingSettingsContent() {
|
||||
const t = useTranslations('settings_bookkeeping')
|
||||
const tNav = useTranslations('settings_nav')
|
||||
const tIntro = useTranslations('settings_intro')
|
||||
const { settings, isLoading, updateSettings, refetch } = useSettings()
|
||||
const { company } = useCompany()
|
||||
// Local mirror of the company-level accounting_framework so the K2/K3
|
||||
// selector can reflect its own saves without waiting for the layout to
|
||||
// re-render through the server. Falls back to k2 (matches the column
|
||||
// default) until the company row is loaded.
|
||||
const [framework, setFramework] = useState<AccountingFramework>(
|
||||
company?.accounting_framework ?? 'k2',
|
||||
)
|
||||
|
||||
if (isLoading) return <SettingsLoadingSkeleton />
|
||||
if (!settings) return <SettingsLoadError onRetry={refetch} />
|
||||
|
||||
function handleSave(formData: FormData) {
|
||||
const autoLockValue = formData.get('auto_lock_period_days') as string
|
||||
const lockedThrough = (formData.get('bookkeeping_locked_through') as string) || null
|
||||
const accountingMethod = (formData.get('accounting_method') as string) || 'accrual'
|
||||
const defaultVoucherSeries = (formData.get('default_voucher_series') as string) || 'A'
|
||||
// Deferred booking is an accrual-only concept (#967): normalize to false
|
||||
// under kontantmetoden so switching back to accrual can never re-activate
|
||||
// a stale flag the user set in a mode where it had no effect.
|
||||
const deferInvoiceBooking =
|
||||
accountingMethod === 'accrual' && formData.get('defer_invoice_booking') === 'true'
|
||||
|
||||
const updates: Record<string, unknown> = {
|
||||
bookkeeping_locked_through: lockedThrough,
|
||||
auto_lock_period_days: autoLockValue === 'none' ? null : parseInt(autoLockValue),
|
||||
accounting_method: accountingMethod,
|
||||
default_voucher_series: defaultVoucherSeries,
|
||||
defer_invoice_booking: deferInvoiceBooking,
|
||||
}
|
||||
|
||||
// Write-through: the booking engine resolves the series from the
|
||||
// per-source-type map, NOT from default_voucher_series. So when the user
|
||||
// changes the global default, propagate it across the map, but only for
|
||||
// types that were still following the previous default, leaving explicit
|
||||
// per-type overrides (set via VoucherSeriesPerSourceTypeForm) untouched.
|
||||
// Without this the "Standardserie" dropdown is a no-op for bookkeeping.
|
||||
// Only runs when the series actually changed, so saving the form for an
|
||||
// unrelated reason (e.g. the lock date) never rewrites the map.
|
||||
const prevDefault = settings?.default_voucher_series || 'A'
|
||||
const currentMap = settings?.default_voucher_series_per_source_type
|
||||
if (currentMap && defaultVoucherSeries !== prevDefault) {
|
||||
updates.default_voucher_series_per_source_type = applyDefaultSeriesToMap(
|
||||
currentMap,
|
||||
prevDefault,
|
||||
defaultVoucherSeries,
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
updates,
|
||||
onSuccess: (data: Record<string, unknown>) => {
|
||||
updateSettings(data as Partial<CompanySettings>)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// K2/K3 selector is only meaningful for AB. EF stays on EF rules and never
|
||||
// picks a framework. Use the company row (source of truth) since
|
||||
// company_settings.entity_type can be stale on legacy data.
|
||||
const isAktiebolag = company?.entity_type === 'aktiebolag'
|
||||
|
||||
return (
|
||||
<div>
|
||||
<SettingsSectionHeader title={tNav('bookkeeping')} intro={tIntro('bookkeeping')} />
|
||||
|
||||
<SettingsFormWrapper onSave={handleSave}>
|
||||
{/* Grunder: framework (AB only), method, deferred booking, default
|
||||
series. The framework row saves through its own PATCH and opts out
|
||||
of this wrapper's dirty tracking; the rest read via FormData. */}
|
||||
<SettingsGroup label={t('group_basics')}>
|
||||
{isAktiebolag && (
|
||||
<AccountingFrameworkForm
|
||||
current={framework}
|
||||
onSaved={(next) => setFramework(next)}
|
||||
/>
|
||||
)}
|
||||
<SettingsRow
|
||||
label={t('method_label')}
|
||||
htmlFor="accounting_method"
|
||||
help={t('method_help')}
|
||||
>
|
||||
<SettingsSelect
|
||||
id="accounting_method"
|
||||
name="accounting_method"
|
||||
defaultValue={settings.accounting_method || 'accrual'}
|
||||
>
|
||||
<option value="accrual">{t('method_accrual')}</option>
|
||||
<option value="cash">{t('method_cash')}</option>
|
||||
</SettingsSelect>
|
||||
</SettingsRow>
|
||||
{/* #967: register/send without booking; ekonomi books in a separate
|
||||
explicit step. Only meaningful under faktureringsmetoden. */}
|
||||
<SettingsRow
|
||||
label={t('defer_booking_label')}
|
||||
htmlFor="defer_invoice_booking"
|
||||
help={t('defer_booking_help')}
|
||||
>
|
||||
<SettingsSelect
|
||||
id="defer_invoice_booking"
|
||||
name="defer_invoice_booking"
|
||||
defaultValue={settings.defer_invoice_booking ? 'true' : 'false'}
|
||||
>
|
||||
<option value="false">{t('defer_booking_off')}</option>
|
||||
<option value="true">{t('defer_booking_on')}</option>
|
||||
</SettingsSelect>
|
||||
</SettingsRow>
|
||||
<SettingsRow
|
||||
label={t('series_label')}
|
||||
htmlFor="default_voucher_series"
|
||||
help={t('series_help')}
|
||||
>
|
||||
<SettingsSelect
|
||||
id="default_voucher_series"
|
||||
name="default_voucher_series"
|
||||
defaultValue={settings.default_voucher_series || 'A'}
|
||||
className="font-mono"
|
||||
>
|
||||
{SERIES_OPTIONS.map((letter) => {
|
||||
// Same name the pickers show: the company's own, else the preset.
|
||||
const label = voucherSeriesLabel(letter, settings.voucher_series_labels)
|
||||
return (
|
||||
<option key={letter} value={letter}>
|
||||
{label ? `${letter} ${label}` : letter}
|
||||
</option>
|
||||
)
|
||||
})}
|
||||
</SettingsSelect>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
|
||||
<PeriodLockingSettings settings={settings} />
|
||||
</SettingsFormWrapper>
|
||||
|
||||
<FiscalYearsManager />
|
||||
|
||||
<VoucherSeriesPerSourceTypeForm
|
||||
settings={settings}
|
||||
onSettingsUpdated={updateSettings}
|
||||
/>
|
||||
|
||||
<VoucherSeriesPerCashAccountForm settings={settings} />
|
||||
|
||||
<VoucherSeriesManager settings={settings} onSettingsUpdated={updateSettings} />
|
||||
|
||||
<SettingsGroup label={t('group_automation')}>
|
||||
{/* Periodisering is a review-gated wizard step, not an automation
|
||||
that can be switched on or off, so this row is a plain link. The
|
||||
old toggle here wrote a localStorage preference nothing read. */}
|
||||
<SettingsRow label={t('periodisering_label')} help={t('periodisering_help')}>
|
||||
<Link
|
||||
href="/bookkeeping/year-end/periodisering"
|
||||
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
{t('periodisering_open_wizard')}
|
||||
</Link>
|
||||
</SettingsRow>
|
||||
<DimensionsToggle />
|
||||
<MileageToggle />
|
||||
<SalesOrdersToggle />
|
||||
</SettingsGroup>
|
||||
|
||||
<SettingsGroup>
|
||||
<SettingsRow label={t('related_heading')} borderless>
|
||||
<Link
|
||||
href="/chart-of-accounts"
|
||||
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
{t('related_chart_of_accounts')}
|
||||
</Link>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,284 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Loader2, Palette, Trash2, Upload } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { SettingsGroup, SettingsInput, SettingsRow } from '@/components/settings/SettingsRows'
|
||||
import { SettingsLoadingSkeleton } from '@/components/settings/SettingsLoadingSkeleton'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { LOGO_UPLOAD_MAX_BYTES } from '@/lib/invoices/branding-constants'
|
||||
|
||||
const ALLOWED_TYPES = ['image/png', 'image/jpeg', 'image/webp']
|
||||
|
||||
interface ByraBrand {
|
||||
hasBrand: boolean
|
||||
domain: string | null
|
||||
appName: string | null
|
||||
logoUrl: string | null
|
||||
canEdit: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Byrå settings: Varumärke (WL-17). Byråer edit the logo and the app name
|
||||
* themselves; domain and colors render read-only (ops-managed, the
|
||||
* white-glove decision). Upload interaction mirrors the company invoice
|
||||
* logo (components/settings/LogoUpload.tsx) against the byrå brand route.
|
||||
* The logo saves on upload; the app name has an inline save that appears
|
||||
* when the field is dirty (SettingsFormWrapper is wired to /api/settings,
|
||||
* so this single team-scoped field saves itself).
|
||||
*/
|
||||
export function BrandSettingsContent() {
|
||||
const t = useTranslations('settings_brand')
|
||||
const { toast } = useToast()
|
||||
const [brand, setBrand] = useState<ByraBrand | null>(null)
|
||||
const [loadFailed, setLoadFailed] = useState(false)
|
||||
const [isUploading, setIsUploading] = useState(false)
|
||||
const [isDeleting, setIsDeleting] = useState(false)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const [appNameDraft, setAppNameDraft] = useState('')
|
||||
const [isSavingName, setIsSavingName] = useState(false)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
fetch('/api/byra/brand')
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw new Error()
|
||||
const body = (await res.json()) as { data: ByraBrand }
|
||||
if (!cancelled) {
|
||||
setBrand(body.data)
|
||||
setAppNameDraft(body.data.appName ?? '')
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setLoadFailed(true)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
const appNameDirty =
|
||||
!!brand?.hasBrand &&
|
||||
brand.canEdit &&
|
||||
appNameDraft.trim().length > 0 &&
|
||||
appNameDraft.trim() !== brand.appName
|
||||
|
||||
async function handleSaveAppName() {
|
||||
if (!appNameDirty || isSavingName) return
|
||||
setIsSavingName(true)
|
||||
try {
|
||||
const response = await fetch('/api/byra/brand', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ appName: appNameDraft.trim() }),
|
||||
})
|
||||
const result = await response.json()
|
||||
if (!response.ok) {
|
||||
throw new Error(result.error || t('app_name_save_failed'))
|
||||
}
|
||||
setBrand((prev) => (prev ? { ...prev, appName: result.data.app_name } : prev))
|
||||
setAppNameDraft(result.data.app_name)
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t('app_name_save_failed'),
|
||||
description: error instanceof Error ? getUserErrorMessage(error) : undefined,
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
setIsSavingName(false)
|
||||
}
|
||||
|
||||
function validateAndUpload(file: File) {
|
||||
if (!ALLOWED_TYPES.includes(file.type)) {
|
||||
toast({ title: t('logo_disallowed_type'), variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
if (file.size > LOGO_UPLOAD_MAX_BYTES) {
|
||||
toast({ title: t('logo_too_large'), variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
void handleUpload(file)
|
||||
}
|
||||
|
||||
async function handleUpload(file: File) {
|
||||
setIsUploading(true)
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
try {
|
||||
const response = await fetch('/api/byra/brand/logo', { method: 'POST', body: formData })
|
||||
const result = await response.json()
|
||||
if (!response.ok) {
|
||||
throw new Error(result.error || t('logo_upload_failed'))
|
||||
}
|
||||
setBrand((prev) => (prev ? { ...prev, logoUrl: result.data.logo_url } : prev))
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t('logo_upload_failed'),
|
||||
description: error instanceof Error ? getUserErrorMessage(error) : undefined,
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
setIsUploading(false)
|
||||
}
|
||||
|
||||
async function handleDelete() {
|
||||
setIsDeleting(true)
|
||||
try {
|
||||
const response = await fetch('/api/byra/brand/logo', { method: 'DELETE' })
|
||||
if (!response.ok) throw new Error()
|
||||
setBrand((prev) => (prev ? { ...prev, logoUrl: null } : prev))
|
||||
if (inputRef.current) inputRef.current.value = ''
|
||||
} catch {
|
||||
toast({ title: t('logo_delete_failed'), variant: 'destructive' })
|
||||
}
|
||||
setIsDeleting(false)
|
||||
}
|
||||
|
||||
function handleDrop(e: React.DragEvent<HTMLButtonElement>) {
|
||||
e.preventDefault()
|
||||
setIsDragging(false)
|
||||
const file = e.dataTransfer.files?.[0]
|
||||
if (file) validateAndUpload(file)
|
||||
}
|
||||
|
||||
function handleDragOver(e: React.DragEvent<HTMLButtonElement>) {
|
||||
e.preventDefault()
|
||||
setIsDragging(true)
|
||||
}
|
||||
|
||||
function handleDragLeave(e: React.DragEvent<HTMLButtonElement>) {
|
||||
e.preventDefault()
|
||||
setIsDragging(false)
|
||||
}
|
||||
|
||||
if (loadFailed) {
|
||||
return <p className="text-sm text-muted-foreground">{t('load_failed')}</p>
|
||||
}
|
||||
if (!brand) {
|
||||
return <SettingsLoadingSkeleton />
|
||||
}
|
||||
if (!brand.hasBrand) {
|
||||
return (
|
||||
<EmptyState
|
||||
icon={Palette}
|
||||
title={t('empty_title')}
|
||||
description={t('empty_description')}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsGroup>
|
||||
<SettingsRow label={t('logo_label')} help={t('logo_help')}>
|
||||
{brand.logoUrl ? (
|
||||
<>
|
||||
<span className="inline-flex rounded-lg border border-border bg-muted/30 p-2">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={brand.logoUrl}
|
||||
alt={t('logo_alt')}
|
||||
className="max-h-10 max-w-32 object-contain"
|
||||
/>
|
||||
</span>
|
||||
{brand.canEdit && (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => inputRef.current?.click()}
|
||||
disabled={isUploading}
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{isUploading ? <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" /> : null}
|
||||
{t('logo_change')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleDelete}
|
||||
disabled={isDeleting}
|
||||
className="text-muted-foreground hover:text-destructive"
|
||||
>
|
||||
{isDeleting ? (
|
||||
<Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="mr-2 h-3.5 w-3.5" />
|
||||
)}
|
||||
{t('logo_remove')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
) : brand.canEdit ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => inputRef.current?.click()}
|
||||
onDrop={handleDrop}
|
||||
onDragOver={handleDragOver}
|
||||
onDragEnter={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
disabled={isUploading}
|
||||
className={`inline-flex min-h-10 items-center gap-2 rounded-lg border border-dashed px-4 py-2 text-sm text-muted-foreground transition-colors duration-150 disabled:opacity-50 ${
|
||||
isDragging ? 'border-foreground bg-muted/40' : 'border-border hover:bg-muted/20'
|
||||
}`}
|
||||
>
|
||||
{isUploading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Upload className="h-4 w-4 text-muted-foreground/60" />
|
||||
)}
|
||||
{isUploading ? t('logo_uploading') : t('logo_pick_or_drop')}
|
||||
</button>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">{t('logo_none')}</span>
|
||||
)}
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow label={t('domain_label')} help={t('domain_help')}>
|
||||
<span className="text-sm tabular-nums">{brand.domain}</span>
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow label={t('app_name_label')} help={t('app_name_help')} htmlFor="byra-app-name">
|
||||
{brand.canEdit ? (
|
||||
<>
|
||||
<SettingsInput
|
||||
id="byra-app-name"
|
||||
value={appNameDraft}
|
||||
maxLength={60}
|
||||
onChange={(e) => setAppNameDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
void handleSaveAppName()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{appNameDirty && (
|
||||
<Button size="sm" onClick={handleSaveAppName} disabled={isSavingName}>
|
||||
{isSavingName ? <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" /> : null}
|
||||
{t('app_name_save')}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<span className="text-sm">{brand.appName}</span>
|
||||
)}
|
||||
</SettingsRow>
|
||||
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/webp"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) validateAndUpload(file)
|
||||
}}
|
||||
/>
|
||||
</SettingsGroup>
|
||||
)
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { CompanyDangerZone } from '@/components/settings/CompanyDangerZone'
|
||||
import { CompanyInfoForm } from '@/components/settings/CompanyInfoForm'
|
||||
import { CompanyMembersSection } from '@/components/settings/CompanyMembersSection'
|
||||
import { CompanyProfileSection } from '@/components/settings/CompanyProfileSection'
|
||||
import { DataAnalysisToggle } from '@/components/settings/DataAnalysisToggle'
|
||||
import { FiscalPeriodEditor } from '@/components/settings/FiscalPeriodEditor'
|
||||
import { LogoUpload } from '@/components/settings/LogoUpload'
|
||||
import { SettingsFormWrapper } from '@/components/settings/SettingsFormWrapper'
|
||||
import { SettingsLoadError } from '@/components/settings/SettingsLoadError'
|
||||
import { SettingsLoadingSkeleton } from '@/components/settings/SettingsLoadingSkeleton'
|
||||
import { SettingsGroup, SettingsSectionHeader } from '@/components/settings/SettingsRows'
|
||||
import { ShareCapitalForm } from '@/components/settings/ShareCapitalForm'
|
||||
import { useSettings } from '@/components/settings/useSettings'
|
||||
import type { CompanySettings } from '@/types'
|
||||
|
||||
export function CompanySettingsContent() {
|
||||
const router = useRouter()
|
||||
const tNav = useTranslations('settings_nav')
|
||||
const tIntro = useTranslations('settings_intro')
|
||||
const tData = useTranslations('data_analysis')
|
||||
const { settings, isLoading, updateSettings, refetch } = useSettings()
|
||||
|
||||
// Deep-link target for "Medlemmar och roller" (/settings/company#members):
|
||||
// a ref callback rather than an effect because this content mounts late
|
||||
// (settings fetch + dynamic import); the callback fires exactly when the
|
||||
// section exists. The hash is cleared after scrolling so switching tabs
|
||||
// and returning to Företag doesn't scroll again.
|
||||
const scrollToMembers = useCallback((node: HTMLDivElement | null) => {
|
||||
if (!node || window.location.hash !== '#members') return
|
||||
node.scrollIntoView({ block: 'start' })
|
||||
history.replaceState(null, '', window.location.pathname + window.location.search)
|
||||
}, [])
|
||||
|
||||
if (isLoading) return <SettingsLoadingSkeleton />
|
||||
if (!settings) return <SettingsLoadError onRetry={refetch} />
|
||||
|
||||
function handleSave(formData: FormData) {
|
||||
// Empty string clears the value (schema accepts null, not '').
|
||||
const numberOrNull = (name: string) => {
|
||||
const raw = String(formData.get(name) ?? '').trim()
|
||||
if (raw === '') return null
|
||||
const parsed = Number(raw)
|
||||
// NaN would serialize to null in JSON and silently clear the value.
|
||||
return Number.isFinite(parsed) ? parsed : null
|
||||
}
|
||||
const updates: Record<string, unknown> = {
|
||||
...(formData.has('company_name') && { company_name: formData.get('company_name') as string }),
|
||||
...(formData.has('org_number') && { org_number: formData.get('org_number') as string }),
|
||||
address_line1: formData.get('address_line1') as string,
|
||||
postal_code: formData.get('postal_code') as string,
|
||||
city: formData.get('city') as string,
|
||||
phone: (formData.get('phone') as string) || '',
|
||||
email: (formData.get('email') as string) || '',
|
||||
website: (formData.get('website') as string) || '',
|
||||
...(formData.has('aktiekapital') && { aktiekapital: numberOrNull('aktiekapital') }),
|
||||
...(formData.has('antal_aktier') && { antal_aktier: numberOrNull('antal_aktier') }),
|
||||
}
|
||||
return {
|
||||
updates,
|
||||
onSuccess: (data: Record<string, unknown>) => {
|
||||
updateSettings(data as Partial<CompanySettings>)
|
||||
// Refresh server components so the company switcher and DashboardNav
|
||||
// pick up the new company_name (rendered from server in the dashboard layout).
|
||||
if ('company_name' in updates) {
|
||||
router.refresh()
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<SettingsSectionHeader title={tNav('company')} intro={tIntro('company')} />
|
||||
|
||||
<SettingsFormWrapper onSave={handleSave}>
|
||||
<CompanyInfoForm settings={settings} />
|
||||
{settings.entity_type === 'aktiebolag' && (
|
||||
<ShareCapitalForm
|
||||
settings={{ aktiekapital: settings.aktiekapital, antal_aktier: settings.antal_aktier }}
|
||||
/>
|
||||
)}
|
||||
</SettingsFormWrapper>
|
||||
|
||||
<LogoUpload
|
||||
logoUrl={settings.logo_url}
|
||||
onUpdate={(url) => updateSettings({ logo_url: url })}
|
||||
/>
|
||||
|
||||
<div id="members" ref={scrollToMembers} className="scroll-mt-6">
|
||||
<CompanyMembersSection />
|
||||
</div>
|
||||
|
||||
<FiscalPeriodEditor />
|
||||
|
||||
<CompanyProfileSection />
|
||||
|
||||
<SettingsGroup label={tData('group_label')}>
|
||||
<DataAnalysisToggle />
|
||||
</SettingsGroup>
|
||||
|
||||
<CompanyDangerZone />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { InvoiceSettingsForm } from '@/components/settings/InvoiceSettingsForm'
|
||||
import { InvoicePaymentLinkSettings } from '@/components/settings/InvoicePaymentLinkSettings'
|
||||
import { PeppolReceiveSettings } from '@/components/settings/PeppolReceiveSettings'
|
||||
import { InvoicePaymentAccountsSettings } from '@/components/settings/InvoicePaymentAccountsSettings'
|
||||
import { InvoiceEmailTextsSettings } from '@/components/settings/InvoiceEmailTextsSettings'
|
||||
import { ReminderEmailTextsSettings } from '@/components/settings/ReminderEmailTextsSettings'
|
||||
import { InvoiceEmailRecipientsSettings } from '@/components/settings/InvoiceEmailRecipientsSettings'
|
||||
import { InvoiceSenderDomainSettings } from '@/components/settings/InvoiceSenderDomainSettings'
|
||||
import { InvoicePreviewCard } from '@/components/settings/InvoicePreviewCard'
|
||||
import { PdfPrintSettings } from '@/components/settings/PdfPrintSettings'
|
||||
import { SettingsFormWrapper } from '@/components/settings/SettingsFormWrapper'
|
||||
import { SettingsLoadError } from '@/components/settings/SettingsLoadError'
|
||||
import { SettingsLoadingSkeleton } from '@/components/settings/SettingsLoadingSkeleton'
|
||||
import { SettingsSectionHeader } from '@/components/settings/SettingsRows'
|
||||
import { useSettings } from '@/components/settings/useSettings'
|
||||
import type { CompanySettings } from '@/types'
|
||||
|
||||
export function InvoicingSettingsContent() {
|
||||
const tNav = useTranslations('settings_nav')
|
||||
const tIntro = useTranslations('settings_intro')
|
||||
const { settings, isLoading, updateSettings, refetch } = useSettings()
|
||||
|
||||
if (isLoading) return <SettingsLoadingSkeleton />
|
||||
if (!settings) return <SettingsLoadError onRetry={refetch} />
|
||||
|
||||
function handleSave(formData: FormData) {
|
||||
const updates: Record<string, unknown> = {
|
||||
invoice_prefix: (formData.get('invoice_prefix') as string) || null,
|
||||
next_invoice_number: parseInt(formData.get('next_invoice_number') as string) || 1,
|
||||
next_arrival_number: parseInt(formData.get('next_arrival_number') as string) || 1,
|
||||
invoice_default_days: parseInt(formData.get('invoice_default_days') as string) || 30,
|
||||
invoice_default_notes: (formData.get('invoice_default_notes') as string) || null,
|
||||
default_our_reference: (formData.get('default_our_reference') as string) || null,
|
||||
reminder_days_level_1:
|
||||
Number.parseInt(formData.get('reminder_days_level_1') as string) || 15,
|
||||
reminder_days_level_2:
|
||||
Number.parseInt(formData.get('reminder_days_level_2') as string) || 30,
|
||||
reminder_days_level_3:
|
||||
Number.parseInt(formData.get('reminder_days_level_3') as string) || 45,
|
||||
send_invoice_reminders: formData.get('send_invoice_reminders') === 'true',
|
||||
}
|
||||
return {
|
||||
updates,
|
||||
onSuccess: (data: Record<string, unknown>) => {
|
||||
updateSettings(data as Partial<CompanySettings>)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<SettingsSectionHeader
|
||||
title={tNav('invoicing')}
|
||||
intro={tIntro('invoicing')}
|
||||
action={<InvoicePreviewCard settings={settings} />}
|
||||
/>
|
||||
|
||||
{/* Owner/admin only: the component gates itself on role. */}
|
||||
<InvoicePaymentAccountsSettings settings={settings} onUpdate={updateSettings} />
|
||||
|
||||
<SettingsFormWrapper onSave={handleSave}>
|
||||
<InvoiceSettingsForm settings={settings} />
|
||||
</SettingsFormWrapper>
|
||||
|
||||
{/* Payment link opt-in: saves individually via toggle switch */}
|
||||
<InvoicePaymentLinkSettings settings={settings} onUpdate={updateSettings} />
|
||||
|
||||
{/* Peppol receiving: one switch that publishes the company's Peppol id */}
|
||||
<PeppolReceiveSettings />
|
||||
|
||||
{/* PDF settings: saves individually via toggle switches */}
|
||||
<PdfPrintSettings settings={settings} onUpdate={updateSettings} />
|
||||
|
||||
{/* Fixed invoice email recipients: explicit save (owner/admin only) */}
|
||||
<InvoiceEmailRecipientsSettings settings={settings} onUpdate={updateSettings} />
|
||||
|
||||
<InvoiceSenderDomainSettings companyName={settings.company_name ?? null} />
|
||||
|
||||
{/* Invoice email texts: autosaves on blur */}
|
||||
<InvoiceEmailTextsSettings settings={settings} onUpdate={updateSettings} />
|
||||
|
||||
{/* Reminder email texts per level: autosaves on blur */}
|
||||
<ReminderEmailTextsSettings settings={settings} onUpdate={updateSettings} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { MailConnectionsPanel } from '@/components/extensions/general/MailConnectionsPanel'
|
||||
import { SettingsSectionHeader } from '@/components/settings/SettingsRows'
|
||||
|
||||
export function MailSettingsContent() {
|
||||
const tNav = useTranslations('settings_nav')
|
||||
const tIntro = useTranslations('settings_intro')
|
||||
|
||||
return (
|
||||
<div>
|
||||
<SettingsSectionHeader title={tNav('mail')} intro={tIntro('mail')} />
|
||||
<MailConnectionsPanel />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,199 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { SettingsFormWrapper } from '@/components/settings/SettingsFormWrapper'
|
||||
import { SettingsLoadError } from '@/components/settings/SettingsLoadError'
|
||||
import { SettingsLoadingSkeleton } from '@/components/settings/SettingsLoadingSkeleton'
|
||||
import {
|
||||
SettingsGroup,
|
||||
SettingsInput,
|
||||
SettingsRow,
|
||||
SettingsSectionHeader,
|
||||
SettingsSelect,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import { TaxTableStatus } from '@/components/salary/TaxTableStatus'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { useSettings } from '@/components/settings/useSettings'
|
||||
import { resolveDefaultSeriesForSource } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import type { CompanySettings } from '@/types'
|
||||
|
||||
const SERIES_OPTIONS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
|
||||
const BANK_OPTIONS = ['swedbank', 'seb', 'handelsbanken', 'nordea'] as const
|
||||
|
||||
const BANK_LABEL: Record<(typeof BANK_OPTIONS)[number], string> = {
|
||||
swedbank: 'Swedbank',
|
||||
seb: 'SEB',
|
||||
handelsbanken: 'Handelsbanken',
|
||||
nordea: 'Nordea',
|
||||
}
|
||||
|
||||
export function SalarySettingsContent() {
|
||||
const t = useTranslations('settings_salary')
|
||||
const tNav = useTranslations('settings_nav')
|
||||
const tIntro = useTranslations('settings_intro')
|
||||
const tSalary = useTranslations('salary')
|
||||
const { settings, isLoading, updateSettings, refetch } = useSettings()
|
||||
// Controlled so the LB sunset note reacts to the selection before save.
|
||||
const [format, setFormat] = useState<'bg_lb' | 'pain001' | null>(null)
|
||||
// Controlled: the Radix Switch is not a form element, so its value rides
|
||||
// along in handleSave instead of FormData.
|
||||
const [netRounding, setNetRounding] = useState<boolean | null>(null)
|
||||
|
||||
if (isLoading) return <SettingsLoadingSkeleton />
|
||||
if (!settings) return <SettingsLoadError onRetry={refetch} />
|
||||
|
||||
const effectiveFormat = format ?? settings.preferred_payment_format ?? 'pain001'
|
||||
const effectiveNetRounding = netRounding ?? settings.salary_net_rounding ?? false
|
||||
const currentSeries = resolveDefaultSeriesForSource(settings, 'salary_payment')
|
||||
|
||||
function handleSave(formData: FormData) {
|
||||
const payDayRaw = parseInt((formData.get('salary_pay_day') as string) || '25', 10)
|
||||
const payDay = Number.isFinite(payDayRaw) ? Math.min(28, Math.max(1, payDayRaw)) : 25
|
||||
const paymentFormat = (formData.get('preferred_payment_format') as string) || 'pain001'
|
||||
const bank = (formData.get('salary_default_bank') as string) || 'none'
|
||||
const series = (formData.get('salary_voucher_series') as string) || 'A'
|
||||
|
||||
const updates: Record<string, unknown> = {
|
||||
salary_pay_day: payDay,
|
||||
preferred_payment_format: paymentFormat,
|
||||
salary_default_bank: bank === 'none' ? null : bank,
|
||||
salary_net_rounding: effectiveNetRounding,
|
||||
}
|
||||
|
||||
// The booking engine resolves the series from the per-source-type map;
|
||||
// salary entries pass run.voucher_series explicitly, seeded from this
|
||||
// entry at run creation. Merge, never replace, the map so other
|
||||
// source-type overrides survive.
|
||||
if (series !== currentSeries) {
|
||||
updates.default_voucher_series_per_source_type = {
|
||||
...(settings?.default_voucher_series_per_source_type || {}),
|
||||
salary_payment: series,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
updates,
|
||||
onSuccess: (data: Record<string, unknown>) => {
|
||||
updateSettings(data as Partial<CompanySettings>)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<SettingsSectionHeader title={tNav('salary')} intro={tIntro('salary')} />
|
||||
|
||||
<SettingsFormWrapper onSave={handleSave}>
|
||||
<SettingsGroup label={t('payments_heading')} help={t('info_payroll_scope')}>
|
||||
<SettingsRow
|
||||
label={t('pay_day_label')}
|
||||
htmlFor="salary_pay_day"
|
||||
help={t('pay_day_help')}
|
||||
align="baseline"
|
||||
>
|
||||
<SettingsInput
|
||||
id="salary_pay_day"
|
||||
name="salary_pay_day"
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={1}
|
||||
max={28}
|
||||
defaultValue={settings.salary_pay_day ?? 25}
|
||||
className="max-w-24 flex-none tabular-nums"
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow
|
||||
label={t('format_label')}
|
||||
htmlFor="preferred_payment_format"
|
||||
help={t('format_help')}
|
||||
borderless={effectiveFormat === 'bg_lb'}
|
||||
>
|
||||
<SettingsSelect
|
||||
id="preferred_payment_format"
|
||||
name="preferred_payment_format"
|
||||
value={effectiveFormat}
|
||||
onChange={(e) => setFormat(e.target.value as 'bg_lb' | 'pain001')}
|
||||
>
|
||||
<option value="pain001">{t('format_pain001')}</option>
|
||||
<option value="bg_lb">{t('format_bg_lb')}</option>
|
||||
</SettingsSelect>
|
||||
</SettingsRow>
|
||||
{effectiveFormat === 'bg_lb' && (
|
||||
<p className="border-b border-border px-1 pb-3 text-[12.5px] leading-relaxed text-attn">
|
||||
{t('sunset_warning')}
|
||||
</p>
|
||||
)}
|
||||
<SettingsRow label={t('bank_label')} htmlFor="salary_default_bank" help={t('bank_help')}>
|
||||
<SettingsSelect
|
||||
id="salary_default_bank"
|
||||
name="salary_default_bank"
|
||||
defaultValue={settings.salary_default_bank ?? 'none'}
|
||||
>
|
||||
<option value="none">{t('bank_none')}</option>
|
||||
{BANK_OPTIONS.map((key) => (
|
||||
<option key={key} value={key}>{BANK_LABEL[key]}</option>
|
||||
))}
|
||||
<option value="other">{t('bank_other')}</option>
|
||||
</SettingsSelect>
|
||||
</SettingsRow>
|
||||
<SettingsRow label={t('net_rounding_label')} help={t('net_rounding_help')}>
|
||||
<Switch
|
||||
id="salary_net_rounding"
|
||||
checked={effectiveNetRounding}
|
||||
onCheckedChange={(next) => setNetRounding(next)}
|
||||
/>
|
||||
<label htmlFor="salary_net_rounding" className="cursor-pointer text-sm">
|
||||
{t('net_rounding_toggle')}
|
||||
</label>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
|
||||
<SettingsGroup label={t('accounting_heading')}>
|
||||
<SettingsRow
|
||||
label={t('voucher_series_label')}
|
||||
htmlFor="salary_voucher_series"
|
||||
help={t('voucher_series_help')}
|
||||
>
|
||||
<SettingsSelect
|
||||
id="salary_voucher_series"
|
||||
name="salary_voucher_series"
|
||||
defaultValue={currentSeries}
|
||||
className="font-mono"
|
||||
>
|
||||
{SERIES_OPTIONS.map((letter) => (
|
||||
<option key={letter} value={letter}>{letter}</option>
|
||||
))}
|
||||
</SettingsSelect>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
</SettingsFormWrapper>
|
||||
|
||||
{/* Tax tables: automatic, read-only status. Lives outside the form so
|
||||
the recheck action never interacts with the save flow. */}
|
||||
<SettingsGroup
|
||||
label={t('tax_tables_heading')}
|
||||
help={t.rich('info_current_year', {
|
||||
strong: (chunks) => <strong>{chunks}</strong>,
|
||||
})}
|
||||
>
|
||||
<SettingsRow label={tSalary('th_status')} help={t('tax_tables_help')}>
|
||||
<TaxTableStatus />
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
|
||||
{/* Vacation is configured per employee; this row only points there. */}
|
||||
<SettingsGroup label={t('vacation_heading')}>
|
||||
<SettingsRow label={t('vacation_rule_label')} help={t('vacation_info')}>
|
||||
<Link
|
||||
href="/salary/employees"
|
||||
className="text-sm text-muted-foreground underline underline-offset-2 transition-colors duration-150 hover:text-foreground"
|
||||
>
|
||||
{t('vacation_info_link')}
|
||||
</Link>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useSearchParams, useRouter } from 'next/navigation'
|
||||
import { TaxSettingsForm } from '@/components/settings/TaxSettingsForm'
|
||||
import { TaxAssessmentNoticesPanel } from '@/components/settings/TaxAssessmentNoticesPanel'
|
||||
import { SettingsFormWrapper } from '@/components/settings/SettingsFormWrapper'
|
||||
import { SettingsLoadError } from '@/components/settings/SettingsLoadError'
|
||||
import { SettingsLoadingSkeleton } from '@/components/settings/SettingsLoadingSkeleton'
|
||||
import { SettingsSectionHeader } from '@/components/settings/SettingsRows'
|
||||
import { SkatteverketConnectPanel } from '@/components/settings/SkatteverketConnectPanel'
|
||||
import { useSettings } from '@/components/settings/useSettings'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
|
||||
import type { CompanySettings } from '@/types'
|
||||
|
||||
export function TaxSettingsContent() {
|
||||
const { settings, isLoading, updateSettings, refetch } = useSettings()
|
||||
const t = useTranslations('settings_skatteverket')
|
||||
const tNav = useTranslations('settings_nav')
|
||||
const tIntro = useTranslations('settings_intro')
|
||||
const searchParams = useSearchParams()
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
|
||||
const hasSkatteverketExtension = ENABLED_EXTENSION_IDS.has('skatteverket')
|
||||
|
||||
// Derived EU-sales signal: postings on 3108/3308/3107 imply a periodisk
|
||||
// sammanställning obligation the opt-in flags may not reflect. Suggestion
|
||||
// only; the user confirms via the ordinary checkboxes.
|
||||
const [euSalesDetected, setEuSalesDetected] = useState(false)
|
||||
// Same pattern for kontrolluppgifter: postings on 2898 (utdelning) or
|
||||
// 2393/2893 (ägarlån) imply a KU obligation on 31 January that AGI never
|
||||
// covers. Suggestion only; the user confirms via the checkbox.
|
||||
const [kuSignalDetected, setKuSignalDetected] = useState(false)
|
||||
// And for ROT/RUT: invoices with deductions mean a begäran om utbetalning
|
||||
// must reach Skatteverket by 31 January after the payment year.
|
||||
const [rotRutSignalDetected, setRotRutSignalDetected] = useState(false)
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
fetch('/api/settings/eu-trade-signal')
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((json) => {
|
||||
if (!cancelled && json?.data?.has_eu_sales) setEuSalesDetected(true)
|
||||
})
|
||||
.catch(() => {
|
||||
// Best-effort signal: a failed fetch just hides the suggestion.
|
||||
})
|
||||
fetch('/api/settings/ku-signal')
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((json) => {
|
||||
if (!cancelled && json?.data?.has_ku_signal) setKuSignalDetected(true)
|
||||
})
|
||||
.catch(() => {
|
||||
// Best-effort signal: a failed fetch just hides the suggestion.
|
||||
})
|
||||
fetch('/api/settings/rot-rut-signal')
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((json) => {
|
||||
if (!cancelled && json?.data?.has_rot_rut) setRotRutSignalDetected(true)
|
||||
})
|
||||
.catch(() => {
|
||||
// Best-effort signal: a failed fetch just hides the suggestion.
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Skatteverket OAuth callback: the connect flow returns to /settings/tax with
|
||||
// a status query param (returnTo set in SkatteverketConnectPanel).
|
||||
useEffect(() => {
|
||||
const connected = searchParams.get('skv_connected')
|
||||
const error = searchParams.get('skv_error')
|
||||
if (connected === 'true') {
|
||||
toast({ title: t('connected_title'), description: t('connected_description') })
|
||||
router.replace('/settings/tax')
|
||||
} else if (error) {
|
||||
let msg: string
|
||||
try {
|
||||
msg = decodeURIComponent(error)
|
||||
} catch {
|
||||
msg = error
|
||||
}
|
||||
toast({ title: t('connect_failed_title'), description: msg, variant: 'destructive' })
|
||||
router.replace('/settings/tax')
|
||||
}
|
||||
}, [searchParams, router, toast, t])
|
||||
|
||||
if (isLoading) return <SettingsLoadingSkeleton />
|
||||
if (!settings) return <SettingsLoadError onRetry={refetch} />
|
||||
|
||||
function handleSave(formData: FormData) {
|
||||
const vatRegistered = formData.get('vat_registered') === 'true'
|
||||
const paysSalaries = formData.get('pays_salaries') === 'true'
|
||||
const employerRegistered = formData.get('employer_registered') === 'true'
|
||||
|
||||
const updates: Record<string, unknown> = {
|
||||
f_skatt: formData.get('f_skatt') === 'true',
|
||||
vat_registered: vatRegistered,
|
||||
vat_number: vatRegistered ? ((formData.get('vat_number') as string) || null) : null,
|
||||
moms_period: vatRegistered ? ((formData.get('moms_period') as string) || null) : null,
|
||||
vat_taxable_base_over_40m:
|
||||
vatRegistered && formData.get('vat_taxable_base_over_40m') === 'true',
|
||||
vat_has_eu_trade: vatRegistered && formData.get('vat_has_eu_trade') === 'true',
|
||||
// The filing-method and PS selects are conditionally rendered: when a
|
||||
// control is unmounted its FormData key is absent, and defaulting would
|
||||
// silently overwrite the saved preference. Fall back to the stored
|
||||
// value first, then the default.
|
||||
vat_filing_method:
|
||||
(formData.get('vat_filing_method') as string) ||
|
||||
settings?.vat_filing_method ||
|
||||
'electronic',
|
||||
periodisk_sammanstallning_enabled:
|
||||
vatRegistered && formData.get('periodisk_sammanstallning_enabled') === 'true',
|
||||
periodisk_sammanstallning_period:
|
||||
(formData.get('periodisk_sammanstallning_period') as string) ||
|
||||
settings?.periodisk_sammanstallning_period ||
|
||||
'monthly',
|
||||
periodisk_sammanstallning_filing_method:
|
||||
(formData.get('periodisk_sammanstallning_filing_method') as string) ||
|
||||
settings?.periodisk_sammanstallning_filing_method ||
|
||||
'electronic',
|
||||
tax_contact_name: (formData.get('tax_contact_name') as string) || null,
|
||||
tax_contact_phone: (formData.get('tax_contact_phone') as string) || null,
|
||||
tax_contact_email: (formData.get('tax_contact_email') as string) || null,
|
||||
fiscal_year_start_month: parseInt(formData.get('fiscal_year_start_month') as string) || 1,
|
||||
pays_salaries: paysSalaries,
|
||||
employer_registered: employerRegistered,
|
||||
// The seasonal switch stays mounted inside its reveal, but the
|
||||
// employer_registered gate still forces false when not registered.
|
||||
employer_seasonal: employerRegistered && formData.get('employer_seasonal') === 'true',
|
||||
preliminary_tax_monthly: parseFloat(formData.get('preliminary_tax_monthly') as string) || null,
|
||||
kontrolluppgifter_enabled: formData.get('kontrolluppgifter_enabled') === 'true',
|
||||
rot_rut_enabled: formData.get('rot_rut_enabled') === 'true',
|
||||
// OSS/IOSS/Intrastat presuppose VAT registration; retire them with it.
|
||||
oss_enabled: vatRegistered && formData.get('oss_enabled') === 'true',
|
||||
ioss_enabled: vatRegistered && formData.get('ioss_enabled') === 'true',
|
||||
intrastat_enabled: vatRegistered && formData.get('intrastat_enabled') === 'true',
|
||||
punktskatt_enabled: formData.get('punktskatt_enabled') === 'true',
|
||||
fyllnadsinbetalning_enabled: formData.get('fyllnadsinbetalning_enabled') === 'true',
|
||||
}
|
||||
return {
|
||||
updates,
|
||||
onSuccess: (data: Record<string, unknown>) => {
|
||||
updateSettings(data as Partial<CompanySettings>)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Sandbox companies don't connect to the real Skatteverket: hide the panel,
|
||||
// matching the old Skatteverket tab's visibility gate. Read straight off the
|
||||
// already-loaded settings row (no separate query needed).
|
||||
const showSkatteverket = hasSkatteverketExtension && !settings.is_sandbox
|
||||
|
||||
return (
|
||||
<div>
|
||||
<SettingsSectionHeader title={tNav('tax')} intro={tIntro('tax')} />
|
||||
|
||||
{/* Connection panel first: the skattekonto and momsdeklaration pages
|
||||
send users here specifically to (re)connect; below the long tax
|
||||
form it sat out of view. */}
|
||||
{showSkatteverket && <SkatteverketConnectPanel />}
|
||||
|
||||
<SettingsFormWrapper onSave={handleSave} className="space-y-0">
|
||||
<TaxSettingsForm
|
||||
settings={settings}
|
||||
euSalesDetected={euSalesDetected}
|
||||
kuSignalDetected={kuSignalDetected}
|
||||
rotRutSignalDetected={rotRutSignalDetected}
|
||||
/>
|
||||
</SettingsFormWrapper>
|
||||
|
||||
<TaxAssessmentNoticesPanel />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { BookingTemplatesPanel } from '@/components/settings/BookingTemplatesPanel'
|
||||
import { CounterpartyTemplatesPanel } from '@/components/settings/CounterpartyTemplatesPanel'
|
||||
import { SettingsSectionHeader } from '@/components/settings/SettingsRows'
|
||||
|
||||
export function TemplatesSettingsContent() {
|
||||
const tNav = useTranslations('settings_nav')
|
||||
const tIntro = useTranslations('settings_intro')
|
||||
return (
|
||||
<div>
|
||||
<SettingsSectionHeader title={tNav('templates')} intro={tIntro('templates')} />
|
||||
<BookingTemplatesPanel />
|
||||
<CounterpartyTemplatesPanel />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { WhatsAppLinkPanel } from '@/components/extensions/general/WhatsAppLinkPanel'
|
||||
import { WhatsAppMark } from '@/components/extensions/general/WhatsAppMark'
|
||||
import { SettingsSectionHeader } from '@/components/settings/SettingsRows'
|
||||
|
||||
export function WhatsAppSettingsContent() {
|
||||
const tNav = useTranslations('settings_nav')
|
||||
const tIntro = useTranslations('settings_intro')
|
||||
|
||||
return (
|
||||
<div>
|
||||
<SettingsSectionHeader
|
||||
title={tNav('whatsapp')}
|
||||
intro={tIntro('whatsapp')}
|
||||
mark={<WhatsAppMark size={26} />}
|
||||
/>
|
||||
<WhatsAppLinkPanel />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
import type { ComponentType } from 'react'
|
||||
import dynamic from 'next/dynamic'
|
||||
import { SettingsLoadingSkeleton } from '../SettingsLoadingSkeleton'
|
||||
|
||||
const AccountSettingsContent = dynamic(() =>
|
||||
import('./AccountSettingsContent').then((module) => ({ default: module.AccountSettingsContent })),
|
||||
{ loading: SettingsLoadingSkeleton },
|
||||
)
|
||||
const CompanySettingsContent = dynamic(() =>
|
||||
import('./CompanySettingsContent').then((module) => ({ default: module.CompanySettingsContent })),
|
||||
{ loading: SettingsLoadingSkeleton },
|
||||
)
|
||||
const BookkeepingSettingsContent = dynamic(() =>
|
||||
import('./BookkeepingSettingsContent').then((module) => ({ default: module.BookkeepingSettingsContent })),
|
||||
{ loading: SettingsLoadingSkeleton },
|
||||
)
|
||||
const TaxSettingsContent = dynamic(() =>
|
||||
import('./TaxSettingsContent').then((module) => ({ default: module.TaxSettingsContent })),
|
||||
{ loading: SettingsLoadingSkeleton },
|
||||
)
|
||||
const SalarySettingsContent = dynamic(() =>
|
||||
import('./SalarySettingsContent').then((module) => ({ default: module.SalarySettingsContent })),
|
||||
{ loading: SettingsLoadingSkeleton },
|
||||
)
|
||||
const InvoicingSettingsContent = dynamic(() =>
|
||||
import('./InvoicingSettingsContent').then((module) => ({ default: module.InvoicingSettingsContent })),
|
||||
{ loading: SettingsLoadingSkeleton },
|
||||
)
|
||||
const TemplatesSettingsContent = dynamic(() =>
|
||||
import('./TemplatesSettingsContent').then((module) => ({ default: module.TemplatesSettingsContent })),
|
||||
{ loading: SettingsLoadingSkeleton },
|
||||
)
|
||||
const BankingSettingsContent = dynamic(() =>
|
||||
import('./BankingSettingsContent').then((module) => ({ default: module.BankingSettingsContent })),
|
||||
{ loading: SettingsLoadingSkeleton },
|
||||
)
|
||||
const AssistantSettingsContent = dynamic(() =>
|
||||
import('./AssistantSettingsContent').then((module) => ({ default: module.AssistantSettingsContent })),
|
||||
{ loading: SettingsLoadingSkeleton },
|
||||
)
|
||||
const ApiSettingsContent = dynamic(() =>
|
||||
import('./ApiSettingsContent').then((module) => ({ default: module.ApiSettingsContent })),
|
||||
{ loading: SettingsLoadingSkeleton },
|
||||
)
|
||||
const BillingSettingsContent = dynamic(() =>
|
||||
import('./BillingSettingsContent').then((module) => ({ default: module.BillingSettingsContent })),
|
||||
{ loading: SettingsLoadingSkeleton },
|
||||
)
|
||||
const TeamSettingsContent = dynamic(() =>
|
||||
import('../TeamPanel').then((module) => ({ default: module.TeamPanel })),
|
||||
{ loading: SettingsLoadingSkeleton },
|
||||
)
|
||||
const BrandSettingsContent = dynamic(() =>
|
||||
import('./BrandSettingsContent').then((module) => ({ default: module.BrandSettingsContent })),
|
||||
{ loading: SettingsLoadingSkeleton },
|
||||
)
|
||||
const WhatsAppSettingsContent = dynamic(() =>
|
||||
import('./WhatsAppSettingsContent').then((module) => ({ default: module.WhatsAppSettingsContent })),
|
||||
{ loading: SettingsLoadingSkeleton },
|
||||
)
|
||||
const MailSettingsContent = dynamic(() =>
|
||||
import('./MailSettingsContent').then((module) => ({ default: module.MailSettingsContent })),
|
||||
{ loading: SettingsLoadingSkeleton },
|
||||
)
|
||||
|
||||
/**
|
||||
* Single source of truth mapping a settings section id to the component that
|
||||
* renders its content. Both the per-section route (`settings/<section>/page.tsx`,
|
||||
* a thin wrapper) and the routed settings modal (`SettingsModal` → `SettingsShell`)
|
||||
* resolve content through this map, so there is exactly one place a section's
|
||||
* composition lives.
|
||||
*/
|
||||
export const SETTINGS_SECTIONS: Record<string, ComponentType> = {
|
||||
account: AccountSettingsContent,
|
||||
company: CompanySettingsContent,
|
||||
bookkeeping: BookkeepingSettingsContent,
|
||||
tax: TaxSettingsContent,
|
||||
salary: SalarySettingsContent,
|
||||
invoicing: InvoicingSettingsContent,
|
||||
templates: TemplatesSettingsContent,
|
||||
banking: BankingSettingsContent,
|
||||
assistant: AssistantSettingsContent,
|
||||
api: ApiSettingsContent,
|
||||
billing: BillingSettingsContent,
|
||||
team: TeamSettingsContent,
|
||||
brand: BrandSettingsContent,
|
||||
whatsapp: WhatsAppSettingsContent,
|
||||
mail: MailSettingsContent,
|
||||
}
|
||||
Reference in New Issue
Block a user