Files
accounted/components/agent/AgentTrigger.tsx
T
Jakob Wennberg 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

183 lines
9.5 KiB
TypeScript

'use client'
import { useAgentSheet } from './AgentSheetProvider'
import { usePathname, useRouter } from 'next/navigation'
import { Loader2 } from 'lucide-react'
import AgentAvatar from './AgentAvatar'
import { collapsedStatusLabel } from './agent-status'
import { routeToIntent } from '@/lib/agent/intents/route-mapping'
import { useCapability } from '@/contexts/CompanyContext'
import { CAPABILITY } from '@/lib/entitlements/keys'
// Floating trigger sits above the page bottom-right, opens the AgentSheet when
// clicked. Hidden when the sheet is already open so the icon doesn't double up.
//
// Desktop-only for a FRESH open (founder call 2026-08-06). On mobile the pill
// landed on top of the bottom nav and covered page content, and the bottom nav
// already carries an "Assistent" tab to /chat behind the very same
// identity.isVerified gate used here, so the pill was pure redundancy. A
// COLLAPSED session keeps its handle on every viewport and on every page except
// /chat: see the page-suppression block and the visibility class below.
//
// Route-aware: routeToIntent(pathname) picks the right intent + intentArgs so
// clicking the FAB on /invoices/abc-123 opens invoice.draft with that invoice
// id (rather than the page-agnostic general.help with just the URL). The
// label suffix renders "Fråga Anna om denna faktura" so the user can tell at
// a glance that the agent is going to know which entity they're on.
//
// Reads the agent's display_name + avatar_id from the AgentSheet context so
// the button reads "Fråga Anna" (with Anna's face) rather than the generic
// "Fråga min assistent".
//
// Page-specific triggers (e.g. "Granska med assistent" on a supplier invoice)
// still call useAgentSheet() directly from their own buttons because they
// know exactly which entity to pass. (Per-transaction help has its own
// row-level "Fråga [namn]" button in TransactionInboxCard, and the matching
// "Fråga assistenten" in Dokumentinkorgen: both passing a transaction_id the
// pathname-only FAB can't know.)
export default function AgentTrigger({ hidden = false }: { hidden?: boolean }) {
const { openAgentSheet, expandAgentSheet, isOpen, collapsed, status, identity } = useAgentSheet()
const pathname = usePathname()
const router = useRouter()
const hasAi = useCapability(CAPABILITY.ai)
// User opt-out (Inställningar → Assistenten): the sidebar entry stays, the
// floating button goes. A collapsed session keeps its reopen handle even
// when hidden: it's the only way back to a minimized conversation, and its
// existence implies the user is actively using the assistant right now.
if (hidden && !collapsed) return null
// Sheet open AND visible → hide the FAB so the icon doesn't double up. When
// the session is merely collapsed we KEEP the FAB: it's the handle that
// brings the minimized conversation back.
if (isOpen && !collapsed) return null
// Page suppression, split by WHY the page suppresses. The split is the point:
// one rule is about redundancy (the page already IS the conversation), the
// other is about crowding (the page is dense and the pill would sit on top of
// it). Only the redundancy rule survives into the collapsed state, because
// only it leaves the user another route back to the conversation.
//
// /chat*: suppressed in BOTH states. Fresh open: the surface IS the chat, so
// a floating "Fråga …" pill is redundant and overlaps the input. Collapsed:
// the /chat layout lists every conversation in its sidebar and renders the
// selected one in the main pane, so navigating here IS the way back; a handle
// that re-expands the panel on top of it would put two chats on one screen.
// Safe because the session lives in AgentSheetProvider in the dashboard
// layout, one level above the page: it stays mounted (messages, streaming,
// pending approval cards intact) the whole time the user is on /chat, and the
// handle reappears the moment they navigate anywhere else, bottom nav
// included. Nothing is discarded, the handle is just hidden while the user is
// standing inside the surface it would lead to.
if (pathname?.startsWith('/chat')) return null
// /bookkeeping/[id]: FRESH open only. The verifikation editor is a dense
// regulatory surface (debits/credits, BAS codes, period locks) and a floating
// "Fråga … om denna verifikation" pill on top of it adds noise without
// earning its place. A COLLAPSED session keeps its handle here, and on every
// other page in the app: this page offers no other route back to a minimized
// conversation, and stranding a half-finished booking is a worse outcome than
// a pill over the editor. (/bookkeeping list, /bookkeeping/new and
// /bookkeeping/year-end are not the editor and keep the fresh-open FAB.)
if (!collapsed) {
const segs = pathname?.split('/').filter(Boolean) ?? []
if (segs[0] === 'bookkeeping' && segs[1] && segs[1] !== 'year-end' && segs[1] !== 'new') {
return null
}
}
// Pre-onboarding: no agent_profile.verified_at yet. The FAB would lead
// into a generic chat with no specialization. Better to hide it until
// the user has finished /onboarding/agent. (A collapsed session implies the
// agent is already in use, so this only gates fresh opens in practice.)
if (!identity.isVerified) return null
const name = identity.displayName?.trim() || 'min assistent'
const dispatch = routeToIntent(pathname)
// AI assistant runs on a paid cloud service. Without the capability, opening
// the sheet would land the user in a chat whose send is dead. Keep the FAB
// visible (it's the conversion surface) but route it to billing instead.
// A minimized session used to be silent: the agent could be three tool calls
// into a booking, or finished ten minutes ago, and the pill said "Fortsätt
// med Anna" either way. While hidden, the status channel does the talking.
const statusText = collapsed ? collapsedStatusLabel(status, name) : null
const working = status.activity === 'working' || status.activity === 'detached'
const finished = collapsed && status.activity === 'done'
const labelText =
statusText ??
(collapsed
? `Fortsätt med ${name}`
: !hasAi
? `Uppgradera för att använda ${name}`
: dispatch.labelSuffix
? `Fråga ${name} ${dispatch.labelSuffix}`
: `Fråga ${name}`)
const handleClick = () => {
// Collapsed → bring the existing session back, don't start a new one.
if (collapsed) {
expandAgentSheet()
return
}
if (!hasAi) {
router.push('/settings/billing')
return
}
openAgentSheet({
intentId: dispatch.intentId,
intentArgs: dispatch.intentArgs,
contextRef: dispatch.contextRef,
})
}
// Mobile visibility, decided per state rather than per viewport alone:
//
// fresh open -> 'hidden md:flex'. `display: none` (not opacity/visibility)
// so the button is genuinely non-interactive on mobile: not
// clickable, not tabbable, out of the accessibility tree.
// Losing it costs nothing, the bottom nav's "Assistent" tab
// reaches the same agent.
// collapsed -> 'flex' on every viewport. Off /chat this is the ONLY route
// back to a minimized conversation: the bottom-nav tab opens
// the /chat surface instead of restoring the in-progress
// sheet, so hiding the handle on mobile would strand a
// session mid-booking with no way to reopen it. On /chat the
// handle is suppressed outright (see above), which is exactly
// the case where the nav tab does lead somewhere useful.
//
// A pure CSS switch on purpose: no useMediaQuery, so no hydration mismatch,
// no resize listener, no layout shift on first paint.
const visibilityClass = collapsed ? 'flex' : 'hidden md:flex'
return (
<button
onClick={handleClick}
// Mobile: sit above the bottom nav (h-16 = 64px) AND the iOS home
// indicator (env(safe-area-inset-bottom)). Still needed after the FAB
// went desktop-only: the collapsed handle above renders on mobile too.
// Desktop: standard 20px lift, no mobile nav to worry about.
className={`fixed right-4 z-30 ${visibilityClass} h-12 max-w-[calc(100vw-2rem)] items-center gap-2 rounded-full bg-foreground pl-2 pr-4 text-background shadow-lg hover:bg-foreground/90 transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 bottom-[calc(env(safe-area-inset-bottom,0px)+5rem)] md:bottom-4`}
aria-label={labelText}
// The label changes on its own while the panel is hidden, so it has to be
// announced rather than only redrawn. Polite: it never interrupts.
aria-live="polite"
>
<span className="relative shrink-0">
<AgentAvatar
avatarId={identity.avatarId}
size="sm"
className="ring-2 ring-background/20"
alt={name}
/>
{/* An answer waiting behind a hidden panel is the one thing worth a
dot: it is unread, not in progress. */}
{finished && (
<span className="absolute -right-1 -top-1 h-2 w-2 rounded-full bg-success ring-2 ring-foreground" />
)}
</span>
{working && collapsed && (
<Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin motion-reduce:animate-none" />
)}
<span className="text-sm font-medium truncate">{labelText}</span>
</button>
)
}