Files
accounted/components/onboarding/NewUserChecklist.tsx
T
d41ef2a909 feat(sandbox): seed payroll, articles and a year of ledger history; calm the connect CTAs (#1437)
* feat(sandbox): seed payroll, articles and a year of ledger history; calm the connect CTAs

The sandbox showed neither Löner nor a usable set of reports, and the
"connect X" surfaces were oversized boxed cards.

Sandbox seed:
- pays_salaries + employer_registered, so Löner and Anställda appear at all
  (an enskild firma is not an employer by default). Both seeded employees are
  employment_type 'employee': an EF may employ staff, just not its own owner.
- Two employees, one booked and one open lönekörning, and the three verifikat
  the booked run must have posted (7210/2710/1930, 7510/2731, 7290+7519/
  2920+2940). Skatteavdrag comes from the real Skatteverket 2026 tables.
- Year-to-date ledger history, January through last month, with the quarterly
  momsredovisning cleared to 2650 and paid on the SFL deadline. Without the
  settlement the demo collected VAT all year and never remitted it, which left
  an implausible bank balance and 155 813 kr of moms "att betala".
- The history is exempted through journal_entry_no_doc_required, the same way
  the SIE-import opt-in treats imported books: its kvitton live in the previous
  system, and unflagged it put 39 "verifikat utan underlag" on the home screen.
- Artikelregister, and the BAS accounts the K1 chart omits for an enskild firma.
- History is numbered before the invoice and payroll vouchers so the series runs
  forwards through the year, and its writes are batched.

Connect CTAs:
- Bank picker: a two-column grid of 95px bordered logo cards becomes flat
  hairline rows, Lucide icons, and a quiet inline connecting state.
- Cloud backup: each provider collapses to one row; the BFL note is shown once
  for the section and names only configured destinations.
- Hem first-run: only the active step argues its case, but every not-done step
  keeps a reachable action. The Skatteverket nudge becomes one quiet sentence.

Mobile assistant FAB: a fresh open is desktop-only, since the bottom nav already
has an Assistent tab. A collapsed session keeps its handle everywhere except
/chat, which is itself the way back to the conversation.

Also closes a real hole: /api/salary/runs/[id]/payslips/send had no sandbox
guard, and a seeded booked run put "Skicka lönebesked" one click from an
anonymous visitor with live Resend behind it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(sandbox): check the two unchecked Supabase errors and tighten review nits

CodeRabbit review on #1437.

Major: two calls discarded their error and continued with null data. A failed
chart_of_accounts re-select would have written account_id: null onto every
ledger-history and salary voucher line, and a failed next_voucher_number would
have inserted a posted verifikat with no number, which is a hole in the
verifikationsserie (BFNAR 2013:2). Both now throw, and a null voucher number is
rejected explicitly.

Minor: the A-004 note claimed a 10 % markup on numbers that are 11.1 %; the
salary breakdown test's name said the opposite of its assertions after the
switch to the real tax table; the ledger-history doc still said 4 to 6 verifikat
per month before the quarterly momsredovisning added a seventh in March, May and
June.

Bank picker: the spinner is aria-hidden, so loading and connecting had no text
equivalent and a failed bank fetch was never announced. Added role="status" with
an sr-only label, and role="alert" on the error line.

Declined: confirm-before-disconnect on the cloud-backup row. Disconnect was
unconfirmed before this PR too, so adding a dialog is a behaviour change beyond
the redesign rather than a fix to it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-06 15:30:04 +02:00

346 lines
12 KiB
TypeScript

'use client'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { useTranslations } from 'next-intl'
import { Check } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { useErrorToast } from '@/lib/hooks/use-error-toast'
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
import { useCapability } from '@/contexts/CompanyContext'
import { CAPABILITY } from '@/lib/entitlements/keys'
import type { InitialSetupPath, InitialSetupState } from '@/types'
interface NewUserChecklistProps {
initialState: InitialSetupState
className?: string
hasBookkeepingImported?: boolean
hasBankConnected?: boolean
hasSkatteverketConnected?: boolean
hasAgentBuilt?: boolean
}
/**
* First-run getting-started block on Hem, in the founder-picked stepped
* shape: a numbered thread (get the books in, connect the bank, connect
* Skatteverket, build the assistant) on a hairline spine.
* Only the step you are on argues its case: it carries the description and
* the partner marks next to a filled action. Steps you have not reached yet
* drop the pitch but keep a quiet outline action, so any step stays one
* click away (connect Skatteverket before the bank, if that is your order).
* Done steps collapse to their title.
* The persisted state machine is unchanged (path / completedAt /
* dismissedAt via /api/onboarding/state); "Starta från början" records the
* fresh path and simply checks off step one.
*/
export default function NewUserChecklist({
initialState,
className,
hasBookkeepingImported = false,
hasBankConnected = false,
hasSkatteverketConnected = false,
hasAgentBuilt = false,
}: NewUserChecklistProps) {
const t = useTranslations('initial_setup')
const router = useRouter()
const showError = useErrorToast()
const hasAi = useCapability(CAPABILITY.ai)
const [state, setState] = useState(initialState)
const [saving, setSaving] = useState<InitialSetupPath | 'dismiss' | 'complete' | null>(null)
const hasMigration = ENABLED_EXTENSION_IDS.has('arcim-migration')
const hasBanking = ENABLED_EXTENSION_IDS.has('enable-banking')
const hasSkatteverket = ENABLED_EXTENSION_IDS.has('skatteverket')
const persist = async (
body: Record<string, unknown>,
pending: InitialSetupPath | 'dismiss' | 'complete',
): Promise<InitialSetupState | null> => {
setSaving(pending)
try {
const response = await fetch('/api/onboarding/state', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (!response.ok) {
await showError(response, { context: 'settings' })
return null
}
const payload = await response.json() as { data: InitialSetupState }
setState(payload.data)
return payload.data
} catch (error) {
await showError(error, { context: 'settings' })
return null
} finally {
setSaving(null)
}
}
const step1Done = hasBookkeepingImported || state.path === 'fresh'
const step2Done = hasBankConnected
// Companies built without the skatteverket extension skip that step.
const step3Done = !hasSkatteverket || hasSkatteverketConnected
const step4Done = hasAgentBuilt
useEffect(() => {
// The block retires itself once every step is done; Dölj remains the
// manual way out.
if (!state.completedAt && step1Done && step2Done && step3Done && step4Done && saving === null) {
void persist({ completed: true }, 'complete')
}
// persist intentionally stays out: its identity follows the toast hook and
// would retrigger this completion sync after every render.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [step1Done, step2Done, step3Done, step4Done, saving, state.completedAt])
if (state.dismissedAt || state.completedAt) return null
const goMigration = async () => {
const updated = await persist({ path: 'migration' }, 'migration')
if (updated) router.push(hasMigration ? '/import?mode=migration' : '/import?mode=sie')
}
const goFresh = () => void persist({ path: 'fresh' }, 'fresh')
const goBank = async () => {
const updated = await persist({ path: state.path ?? 'bank' }, 'bank')
if (updated) router.push(hasBanking ? '/import?mode=psd2' : '/import?mode=bank')
}
const activeStep = !step1Done ? 1 : !step2Done ? 2 : !step3Done ? 3 : 4
const stepCount = hasSkatteverket ? 4 : 3
return (
<section className={className} aria-label={t('title', { count: stepCount })}>
<div className="flex items-center justify-between gap-3">
<h2 className="text-sm font-medium">{t('title', { count: stepCount })}</h2>
<button
type="button"
disabled={saving !== null}
onClick={() => void persist({ dismissed: true }, 'dismiss')}
className="shrink-0 text-xs text-muted-foreground underline decoration-border underline-offset-4 transition-colors hover:text-foreground"
>
{t('dismiss')}
</button>
</div>
<ol className="mt-3" role="list">
<Step
number={1}
done={step1Done}
active={activeStep === 1}
title={t('step_books_title')}
action={(variant) => (
<Button
size="sm"
variant={variant}
disabled={saving !== null}
onClick={() => void goMigration()}
>
{t('step_books_action')}
</Button>
)}
marks={
<>
<LogoMark src="/logos/fortnox.svg" name="Fortnox" />
<LogoMark src="/logos/visma.jpeg" name="Visma" />
<LogoMark src="/logos/bokio.png" name="Bokio" />
<span className="text-[11px] text-muted-foreground">{t('step_books_sie')}</span>
</>
}
>
{t('step_books_description')}{' '}
<button
type="button"
disabled={saving !== null}
onClick={goFresh}
className="underline decoration-border underline-offset-4 transition-colors hover:text-foreground"
>
{t('step_books_fresh_link')}
</button>{' '}
{t('step_books_fresh_suffix')}
</Step>
<Step
number={2}
done={step2Done}
active={activeStep === 2}
title={t('step_bank_title')}
action={(variant) => (
<Button
size="sm"
variant={variant}
disabled={saving !== null}
onClick={() => void goBank()}
>
{t('step_bank_action')}
</Button>
)}
marks={
hasBanking ? (
<LogoMark src="/logos/enable-banking-icon.png" name="Enable Banking" mono />
) : undefined
}
>
{t('step_bank_description')}
</Step>
{hasSkatteverket && (
<Step
number={3}
done={step3Done}
active={activeStep === 3}
title={t('step_skv_title')}
action={(variant) => (
<Button size="sm" variant={variant} asChild>
{/* The authorize endpoint redirects off-site to Skatteverket. */}
{/* eslint-disable-next-line @next/next/no-html-link-for-pages */}
<a href="/api/extensions/ext/skatteverket/authorize?return_to=/">
{t('step_skv_action')}
</a>
</Button>
)}
marks={<LogoMark src="/logos/skatteverket_color.svg" name="Skatteverket" />}
>
{t('step_skv_description')}
</Step>
)}
<Step
number={hasSkatteverket ? 4 : 3}
done={step4Done}
active={activeStep === 4 || (!hasSkatteverket && activeStep === 3)}
title={t('step_assistant_title')}
badge={t('step_assistant_beta')}
last
action={(variant) => (
<Button
size="sm"
variant={variant}
onClick={() => router.push(hasAi ? '/onboarding/agent' : '/settings/billing')}
>
{t('step_assistant_action')}
</Button>
)}
>
{t('step_assistant_description')}
</Step>
</ol>
</section>
)
}
/**
* One numbered step on the thread: dot + hairline down to the next step.
* `children` (the pitch) and `marks` (partner logos) render only while this
* is the step the user is on. `action` renders on every step that is not
* done: filled on the active step, outline on the ones further down, so no
* step is ever unreachable just because it is not next in line.
* The title row is a constant 36px so it matches the h-9 action button and
* the dot (mt-1) centres in it; the spine then runs dot-bottom to dot-top
* (top-8 to -bottom-1) without visible breaks.
*/
function Step({
number,
done,
active,
title,
badge,
action,
marks,
last = false,
children,
}: {
number: number
done: boolean
active: boolean
title: string
badge?: string
action?: (variant: 'default' | 'outline') => React.ReactNode
marks?: React.ReactNode
last?: boolean
children: React.ReactNode
}) {
const open = active && !done
return (
<li
className="relative flex gap-3 pb-3 last:pb-0"
aria-current={open ? 'step' : undefined}
>
{!last && (
<span
className="absolute -bottom-1 left-[13px] top-8 w-px bg-border"
aria-hidden="true"
/>
)}
<span
className={cn(
'relative z-10 mt-1 flex h-7 w-7 shrink-0 items-center justify-center rounded-full border text-xs tabular-nums',
done
? 'border-success/40 text-success'
: open
? 'border-foreground bg-foreground text-background'
: 'border-border text-muted-foreground',
)}
>
{done ? <Check className="h-3.5 w-3.5" aria-hidden="true" /> : number}
</span>
<div className="min-w-0 flex-1">
<div className="flex min-h-9 flex-wrap items-center gap-x-3 gap-y-2">
<div
className={cn(
'flex items-center gap-2 text-sm',
open ? 'font-medium' : 'text-muted-foreground',
)}
>
<span>{title}</span>
{badge && (
<Badge
variant="secondary"
className={cn('shrink-0 uppercase tracking-wider', !open && 'font-normal')}
>
{badge}
</Badge>
)}
</div>
{!done && action?.(open ? 'default' : 'outline')}
</div>
{open && (
<div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-2">
<p className="text-xs leading-5 text-muted-foreground">{children}</p>
{marks && <span className="flex items-center gap-2">{marks}</span>}
</div>
)}
</div>
</li>
)
}
/** Tiny partner mark: real logo on a white chip; `mono` darkens a white
* source logo in light mode and lifts it in dark (Enable Banking). */
function LogoMark({ src, name, mono = false }: { src: string; name: string; mono?: boolean }) {
return (
<span
className={cn(
'flex h-6 w-6 items-center justify-center overflow-hidden rounded-md border border-border',
!mono && 'bg-white',
)}
title={name}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={src}
alt={name}
className={cn(
'h-4 w-4 object-contain',
mono &&
'opacity-90 [filter:grayscale(100%)_brightness(0.18)] dark:[filter:grayscale(100%)_brightness(1.5)]',
)}
/>
</span>
)
}