Files
accounted/app/invite/[token]/page.tsx
T
Jakob WennbergandClaude Opus 4.7 20989379bb feat(sandbox,branding): prod-parity demo with AI gating + accounted rebrand (#585)
* feat(sandbox,branding): prod-parity demo with AI gating + accounted rebrand

Sandbox now ships with seeded suppliers, supplier invoices, an asset,
a verified agent_profile, and pending operations so the demo company
exercises every prod surface. Server-side `guardSandbox()` short-
circuits any AI or paid-external API call (Bedrock chat/composer,
Resend invoice send, Riksbanken FX, VIES, etc.) and the AgentSheet
swaps in a SandboxAgentPreview that explains what's gated and offers
a register CTA. DashboardContent no longer mounts the
NewUserChecklist when the agent is already built, fixing the path
that let sandbox users still trigger /onboarding/agent.

Visible branding flips from Gnubok to Accounted: new BrandWordmark
component (Hedvig Letters Serif 700), new app/icon.png + PWA icons
generated from the accounted icon, default appName updated. URLs,
header names, API key prefixes, hostnames, and event/cookie/
localStorage keys keep `gnubok` — the rebrand is visual only.

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

* fix(sandbox): hardcode supplier-invoice arrival numbers in seed

get_next_arrival_number is MAX(arrival_number) + 1 against the same
table we're about to insert into. Calling it twice before either row
lands made both calls return 1, which then violated the
(company_id, arrival_number) unique index — POST /api/sandbox/seed
500'd on first sandbox start.

The seeded company is brand new in this branch so 1 and 2 are
guaranteed unused; hardcoding side-steps the race entirely.

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

* fix(sandbox): set paid_amount=0 on unpaid supplier invoice

PostgREST normalizes the column set across rows in a bulk insert, so
the second supplier invoice (Espresso House, status=registered) was
being sent with paid_amount=null because the first row (Telia, paid)
set it. supplier_invoices.paid_amount is NOT NULL DEFAULT 0; the
default only kicks in when the column is *absent* from the payload,
not when it's explicitly null. Set it inline to side-step the
normalization.

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

* fix(sandbox): set actor_type=agent_chat on seeded pending_operations

pending_operations only allows user-scoped INSERTs via the
`pending_operations_chat_insert` policy, which requires
actor_type='agent_chat' alongside auth.uid()=user_id +
company membership. The seed was inserting with the default
actor_type='user', tripping the RLS check.

Also lift risk_level from preview_data (where it was unused) onto
the row itself, matching the column added in
20260430120000_pending_operations_actor_and_risk.

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

* fix(pr-review): address PR #585 review feedback

Fixes called out by the core-only CI check, Greptile, and the
compliance + Swedish-accounting bots:

- AGI Programnamn pinned back to 'gnubok' (CI blocker). The XML
  Skatteverket receives must keep the stable software identifier
  regardless of the visual rebrand — same rule as the v1 health
  endpoint's `service: 'gnubok'` literal.
- handleCreateAccount in SandboxAgentPreview + ChatEmptyState now
  wraps signOut() in try/catch so a transient Supabase failure
  doesn't strand the user on a dead button (greptile P2 × 2).
- /api/currency/rate hard-fails on missing companyId instead of
  conditionally skipping the sandbox guard (greptile P2 / compliance
  V8.2.1).
- topUpSandboxAdditions now delegates to ensureSandboxAgentProfile;
  the assistant persona lives in exactly one place across the seed,
  layout backfills, and top-up path (greptile P2 outside-diff /
  compliance SOC2 CC6.1).
- ensureSandboxAgentProfile drops the userId param and sets
  verified_by_user_id to NULL — synthetic seed data should not
  attribute verification to a real user (compliance V8.2.1 /
  GDPR Art. 25(2)). Errors now logged via the structured logger
  instead of being silently swallowed (V16).
- Sandbox seed swaps real-world company names (Telia, Espresso
  House) for clearly-synthetic Demo-prefixed brands using the
  5559... documentation org-number range (compliance A.8.33).
  Asset cost bumped 24 000 → 35 000 SEK so the demo clears the
  förbrukningsinventarier threshold and illustrates capitalization
  unambiguously (swedish-asset-accounting).
- Representation pending-operation preview corrected: VAT label
  fixed from 6% → 12%, and input VAT split between the avdragsgill
  (2641) and ej-avdragsgill (5811) portions to match
  swedish-vat / ML 8 kap rules (swedish-vat).

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

* fix(pr-review): seed preview consistency + AGI Programnamn constant

Two last review-bot items before merge:

- Sandbox seed: the representation pending-operation preview was
  splitting the 240 SEK café meal 60/180 between 5810 and 5811,
  which is wrong for a single attendee under the 300 SEK / person
  avdragsgill cap (ML 8 kap) — the entire amount is fully
  avdragsgill in that case. Collapse the preview to a single 5810
  + 2641 + 2440 entry so it matches the supplier_invoice_items row
  1:1 and stops teaching demo users an incorrect bookkeeping
  pattern.
- Hoist the AGI Programnamn 'gnubok' literal into a named constant
  with a comment pointing to potential future Skatteverket vendor
  registration (per the swedish-compliance bot's nit).

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

* fix(sandbox): avoid BFL duplicate-verification on pending op + fix VAT cap comment

Swedish-compliance bot caught two final nits:

- The pending operation for the Demokafé representation was using the
  same supplier_invoice_number as the already-seeded supplier_invoices
  row (88245). If the sandbox user approved the staged operation, the
  insert would have created (or attempted) a duplicate verification —
  BFL 5 kap. requires each affärshändelse be recorded exactly once.
  Swap the staged operation's invoice number to a distinct value
  (INKOMMANDE-2026-001) so approval cleanly creates a new row.
- The preview comment described the 300 SEK threshold as an
  "avdragsgill cap". The actual rule (ML 8 kap. 9 §) caps the
  deductible VAT at 25 % × 300 SEK × antal_personer = 75 SEK per
  person — the 300 SEK is the tax base, not the total. Math here is
  correct either way, but the comment now states the correct formula
  so future seed edits don't propagate the wrong understanding.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 13:19:41 +02:00

345 lines
13 KiB
TypeScript

'use client'
import { useState, useEffect } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { useTranslations } from 'next-intl'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Loader2, Building2, AlertCircle } from 'lucide-react'
import { createClient } from '@/lib/supabase/client'
import { useToast } from '@/components/ui/use-toast'
import { getBranding } from '@/lib/branding/service'
const branding = getBranding()
interface InviteInfo {
type: 'company'
companyName?: string
email: string
expired: boolean
alreadyHasAccount: boolean
}
export default function InvitePage() {
const params = useParams()
const router = useRouter()
const { toast } = useToast()
const t = useTranslations('invite')
const token = params.token as string
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [invite, setInvite] = useState<InviteInfo | null>(null)
// Email of the currently signed-in user (if any). Used to short-circuit
// the login redirect for users who are already authenticated.
const [currentUserEmail, setCurrentUserEmail] = useState<string | null>(null)
const [isJoining, setIsJoining] = useState(false)
useEffect(() => {
async function loadInvite() {
try {
// Load invite info and current session in parallel — the page needs
// both to decide which CTA to render.
const supabase = createClient()
const [inviteRes, sessionRes] = await Promise.all([
fetch(`/api/team/accept?token=${encodeURIComponent(token)}`),
supabase.auth.getUser(),
])
const data = await inviteRes.json()
if (!inviteRes.ok) {
setError(data.error || t('invalid_invite'))
return
}
setInvite(data.data)
setCurrentUserEmail(sessionRes.data.user?.email ?? null)
} catch {
setError(t('load_failed'))
} finally {
setIsLoading(false)
}
}
loadInvite()
}, [token, t])
const secureCookieFlag = typeof window !== 'undefined' && window.location.protocol === 'https:' ? '; secure' : ''
// True when the signed-in user's email matches the invite — in that case
// we can accept the invite with a single click, no re-login required.
const isLoggedInAsInvitee =
!!currentUserEmail &&
!!invite &&
currentUserEmail.toLowerCase() === invite.email.toLowerCase()
// True when someone is signed in but with a different email than the
// invite is for. They need to sign out first.
const isLoggedInAsOther =
!!currentUserEmail && !!invite && !isLoggedInAsInvitee
const handleAccept = () => {
// Store invite token in cookie before redirecting to register
document.cookie = `gnubok-invite-token=${token}; path=/; max-age=3600; samesite=lax${secureCookieFlag}`
router.push(`/register?invite=${encodeURIComponent(token)}`)
}
const handleAcceptExistingUser = () => {
// Store invite token in cookie before redirecting to login
document.cookie = `gnubok-invite-token=${token}; path=/; max-age=3600; samesite=lax${secureCookieFlag}`
router.push('/login')
}
// Already signed in as the invitee — accept directly, no login detour.
// POST /api/team/accept handles the membership insert + sets the active
// company; we then full-reload to '/' so middleware picks up the new
// company context and the switcher shows it.
const handleJoinNow = async () => {
setIsJoining(true)
try {
const res = await fetch('/api/team/accept', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token }),
})
const body = await res.json().catch(() => ({}))
if (!res.ok) {
toast({
title: t('join_failed_title'),
description: body.error || t('unexpected_error'),
variant: 'destructive',
})
setIsJoining(false)
return
}
toast({
title: t('welcome_title'),
description: invite?.companyName
? t('joined_named', { companyName: invite.companyName })
: t('joined_generic'),
})
// Full reload so the middleware re-resolves company context from the
// updated user_preferences.active_company_id.
window.location.href = '/'
} catch (err) {
console.error('[invite] join failed:', err)
toast({
title: t('join_failed_title'),
description: t('unexpected_error'),
variant: 'destructive',
})
setIsJoining(false)
}
}
const handleSignOutAndRetry = async () => {
const supabase = createClient()
await supabase.auth.signOut()
// Keep the invite cookie alive so the next login/register picks it up.
document.cookie = `gnubok-invite-token=${token}; path=/; max-age=3600; samesite=lax${secureCookieFlag}`
if (invite?.alreadyHasAccount) {
router.push('/login')
} else {
router.push(`/register?invite=${encodeURIComponent(token)}`)
}
}
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center bg-background">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
return (
<div className="min-h-screen flex flex-col bg-background">
<header className="relative bg-[#141414] text-white overflow-hidden">
<div className="absolute inset-0 pointer-events-none" aria-hidden>
<div
className="absolute inset-0"
style={{
background: 'radial-gradient(ellipse at 30% -20%, rgba(255,255,255,0.04) 0%, transparent 50%)',
}}
/>
</div>
<div className="relative z-10 max-w-2xl mx-auto w-full px-6 md:px-10 pt-5 pb-6 md:pt-6 md:pb-8">
<div className="flex items-center gap-2.5 mb-5 md:mb-6">
<span className="font-display text-base tracking-tight" style={{ fontWeight: 700 }}>
{branding.appName.toLowerCase()}
</span>
</div>
<div className="animate-fade-in">
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight leading-[1.1]">
{error ? t('header_invalid') : t('header_invited')}
</h1>
</div>
</div>
</header>
<main className="flex-1">
<div className="max-w-lg mx-auto px-6 md:px-10 py-6 md:py-8">
<div className="animate-slide-up">
{error ? (
<Card className="p-6">
<div className="flex items-start gap-3">
<AlertCircle className="h-5 w-5 text-destructive flex-shrink-0 mt-0.5" />
<div>
<p className="font-medium">{error}</p>
<p className="text-sm text-muted-foreground mt-1">
{t('contact_inviter')}
</p>
<Link
href="/login"
className="text-sm text-primary hover:underline mt-3 inline-block"
>
{t('go_to_login')}
</Link>
</div>
</div>
</Card>
) : invite?.expired ? (
<Card className="p-6">
<div className="flex items-start gap-3">
<AlertCircle className="h-5 w-5 text-muted-foreground flex-shrink-0 mt-0.5" />
<div>
<p className="font-medium">{t('expired_title')}</p>
<p className="text-sm text-muted-foreground mt-1">
{t('expired_description')}
</p>
</div>
</div>
</Card>
) : isLoggedInAsInvitee ? (
// Already signed in as the invitee — one-click join.
// Prioritized over alreadyHasAccount to avoid the broken flow
// where a false-negative from the email check would send a
// logged-in user to /register, which middleware bounces to /.
<div className="space-y-6">
<Card className="p-6">
<div className="flex items-start gap-4">
<div className="p-2.5 rounded-lg bg-muted/50">
<Building2 className="h-5 w-5 text-muted-foreground" />
</div>
<div>
<p className="font-medium">{invite.companyName}</p>
<p className="text-sm text-muted-foreground mt-0.5">
{t('invited_to_company')}
</p>
<p className="text-sm text-muted-foreground mt-1">
{t.rich('logged_in_as', {
email: currentUserEmail ?? '',
strong: (chunks) => <strong>{chunks}</strong>,
})}
</p>
</div>
</div>
</Card>
<Button
size="lg"
className="w-full"
onClick={handleJoinNow}
disabled={isJoining}
>
{isJoining ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t('joining')}
</>
) : (
<>{t('join_named', { companyName: invite.companyName ?? '' })}</>
)}
</Button>
</div>
) : isLoggedInAsOther ? (
// Signed in as a different user — ask them to sign out first.
<div className="space-y-6">
<Card className="p-6">
<div className="flex items-start gap-4">
<div className="p-2.5 rounded-lg bg-muted/50">
<Building2 className="h-5 w-5 text-muted-foreground" />
</div>
<div>
<p className="font-medium">{invite.companyName}</p>
<p className="text-sm text-muted-foreground mt-0.5">
{t.rich('wrong_account', {
invitedEmail: invite.email,
currentEmail: currentUserEmail ?? '',
strong: (chunks) => <strong>{chunks}</strong>,
})}
</p>
<p className="text-sm text-muted-foreground mt-1">
{t('signout_then_login')}
</p>
</div>
</div>
</Card>
<Button size="lg" className="w-full" onClick={handleSignOutAndRetry}>
{t('signout_and_switch')}
</Button>
</div>
) : invite?.alreadyHasAccount ? (
// Not signed in — email has an existing account, bounce to login.
<div className="space-y-6">
<Card className="p-6">
<div className="flex items-start gap-4">
<div className="p-2.5 rounded-lg bg-muted/50">
<Building2 className="h-5 w-5 text-muted-foreground" />
</div>
<div>
<p className="font-medium">{invite.companyName}</p>
<p className="text-sm text-muted-foreground mt-0.5">
{t('invited_to_company')}
</p>
<p className="text-sm text-muted-foreground mt-1">
{t.rich('existing_account', {
email: invite.email,
appName: branding.appName.toLowerCase(),
strong: (chunks) => <strong>{chunks}</strong>,
})}
</p>
</div>
</div>
</Card>
<Button size="lg" className="w-full" onClick={handleAcceptExistingUser}>
{t('login_and_join')}
</Button>
</div>
) : invite ? (
// Not signed in, no existing account — register.
<div className="space-y-6">
<Card className="p-6">
<div className="flex items-start gap-4">
<div className="p-2.5 rounded-lg bg-muted/50">
<Building2 className="h-5 w-5 text-muted-foreground" />
</div>
<div>
<p className="font-medium">{invite.companyName}</p>
<p className="text-sm text-muted-foreground mt-0.5">
{t('invited_to_company')}
</p>
</div>
</div>
</Card>
<Button size="lg" className="w-full" onClick={handleAccept}>
{t('create_account_and_join')}
</Button>
<p className="text-center text-xs text-muted-foreground">
{t('terms_notice')}
</p>
</div>
) : null}
</div>
</div>
</main>
</div>
)
}