* feat: add sandbox infrastructure — migration, types, and middleware

Add database migration for sandbox support:
- Add `is_sandbox` boolean column to company_settings
- Update 4 enforcement trigger functions (journal entry immutability,
  journal entry line immutability, retention enforcement, document
  deletion blocking) to bypass checks for sandbox users
- Add `cleanup_sandbox_user()` SECURITY DEFINER function that handles
  FK-safe deletion order (document_attachments → journal_entry_lines →
  journal_entries → supplier_invoices → auth.users cascade)
- Add `cleanup_expired_sandbox_users()` function that loops over
  sandbox users older than N hours with per-user error handling

Update TypeScript types:
- Add `is_sandbox: boolean` to CompanySettings interface
- Add `is_sandbox: false` to makeCompanySettings() test factory

Update middleware:
- Add `/sandbox` to public routes so the landing page is accessible
  without authentication

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* feat: add sandbox landing page, seed API, cleanup cron, and banner

Sandbox landing page (app/sandbox/page.tsx):
- Client component matching the existing auth page aesthetic
- Auth check: if logged in as real user, shows message to use incognito
- Otherwise shows feature overview (invoices, transactions, bookkeeping,
  reports) with "Starta sandbox" button
- On click: signInAnonymously() → POST /api/sandbox/seed → redirect
- Uses window.location.href for full page load (ensures middleware
  picks up new session cookies)

Seed API (app/api/sandbox/seed/route.ts):
- POST handler gated to anonymous users only (403 for real users)
- Idempotent: returns { seeded: false } if company_settings exists
- Seeds ~40 rows: profile, company_settings (is_sandbox: true,
  onboarding_complete: true), chart of accounts (via RPC),
  fiscal period, 3 customers (Swedish business, EU business,
  individual), 4 invoices (paid/sent/overdue/draft), 4 invoice
  items, 2 posted journal entries with 5 lines, 8 transactions
  (3 categorized, 2 income, 3 uncategorized), 2 deadlines
- Journal entries inserted directly (not via engine) to avoid
  event emission, using next_voucher_number() RPC

Cleanup cron (app/api/sandbox/cleanup/cron/route.ts):
- GET handler with CRON_SECRET Bearer token auth
- Creates service role Supabase client
- Calls cleanup_expired_sandbox_users RPC (24h default)

Sandbox banner (components/dashboard/SandboxBanner.tsx):
- Amber bar with dismiss button (client state, reappears on reload)
- Text: "Sandlådemiljö — dina data raderas automatiskt efter 24 timmar"
- "Skapa konto" link to /register

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* feat: integrate sandbox into dashboard — banner, nav, settings safeguards

Dashboard layout (app/(dashboard)/layout.tsx):
- Fetch is_sandbox from company_settings
- Render SandboxBanner at top of page for sandbox users
- Pass isSandbox prop to DashboardNav
- Hide RecaptIdentify analytics for sandbox users

Root page (app/page.tsx):
- Same sandbox banner and isSandbox prop treatment as dashboard layout
  (root page has its own layout, not wrapped by (dashboard)/layout)

DashboardNav (components/dashboard/DashboardNav.tsx):
- Add optional isSandbox prop
- Change logout button text to "Avsluta sandbox" when isSandbox
- Redirect to /sandbox instead of /login on logout for sandbox users
- Applied to both desktop sidebar and mobile drawer logout buttons

Settings page (app/(dashboard)/settings/page.tsx):
- Hide "Bank (PSD2)" tab entirely for sandbox users — prevents
  connecting real bank accounts from a temporary anonymous session
- Hide "Radera konto" card for sandbox users — account auto-deletes
  via cron, and the delete flow requires email confirmation

Vercel config (vercel.json):
- Add sandbox cleanup cron at 04:00 UTC daily
  (/api/sandbox/cleanup/cron)

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: remove audit trigger for non-existent tax_codes table

Migration 018 referenced public.tax_codes which was never created
(migration 012 is a placeholder). This caused failures when running
migrations from scratch on a fresh database.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: remove ALTER FUNCTION for 3 non-existent functions

Removed search_path pinning for create_invoice_with_items,
seed_asset_categories, and update_reconciliation_session_counts —
none of these functions were ever created in any migration.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: remove ALTER for generate_invoice_number (created in later migration)

The function is created in migration 20260306 with search_path already
set, but migration 20260304 tried to ALTER it before it existed.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* Fixed redirect issue

* Update app/api/sandbox/seed/route.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Update app/api/sandbox/seed/route.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Update app/sandbox/page.tsx

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Fixed catch block issue

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
This commit is contained in:
Mattsson
2026-03-11 14:54:53 +01:00
committed by GitHub
co-authored by Claude Opus 4.6 greptile-apps[bot]
parent d696e0282b
commit 109f860e22
15 changed files with 1136 additions and 47 deletions
+13 -6
View File
@@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'
import DashboardNav from '@/components/dashboard/DashboardNav'
import { RecaptIdentify } from '@/components/RecaptIdentify'
import { SandboxBanner } from '@/components/dashboard/SandboxBanner'
import type { EntityType } from '@/types'
export default async function DashboardLayout({
@@ -19,7 +20,7 @@ export default async function DashboardLayout({
const { data: settings } = await supabase
.from('company_settings')
.select('company_name, onboarding_complete, entity_type')
.select('company_name, onboarding_complete, entity_type, is_sandbox')
.eq('user_id', user.id)
.single()
@@ -35,6 +36,8 @@ export default async function DashboardLayout({
.eq('user_id', user.id)
.is('is_business', null)
const isSandbox = settings.is_sandbox === true
return (
<div className="min-h-screen bg-background">
{/* Skip to content link for keyboard/screen reader users */}
@@ -44,21 +47,25 @@ export default async function DashboardLayout({
>
Hoppa till innehåll
</a>
{isSandbox && <SandboxBanner />}
<DashboardNav
companyName={settings.company_name || 'Min verksamhet'}
entityType={entityType}
uncategorizedTransactionCount={uncategorizedCount ?? 0}
isSandbox={isSandbox}
/>
<main id="main-content" className="pb-20 md:pb-0 md:pl-[232px]" role="main">
<div className="max-w-5xl mx-auto px-5 py-8 md:px-8 md:py-10">
{children}
</div>
</main>
<RecaptIdentify
userId={user.id}
email={user.email}
displayName={settings.company_name || undefined}
/>
{!isSandbox && (
<RecaptIdentify
userId={user.id}
email={user.email}
displayName={settings.company_name || undefined}
/>
)}
</div>
)
}
+31 -27
View File
@@ -261,9 +261,11 @@ export default function SettingsPage() {
<TabsTrigger value="company">
Företag
</TabsTrigger>
<TabsTrigger value="banking">
Bank (PSD2)
</TabsTrigger>
{!settings?.is_sandbox && (
<TabsTrigger value="banking">
Bank (PSD2)
</TabsTrigger>
)}
{hasCalendarExtension && (
<TabsTrigger value="calendar">
Kalender
@@ -500,28 +502,30 @@ export default function SettingsPage() {
</form>
</TabsContent>
{/* Banking settings — loaded dynamically from extension */}
<TabsContent value="banking" className="space-y-6">
{hasBankingExtension && BankingPanel ? (
<BankingPanel />
) : (
<Card>
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
<CreditCard className="h-10 w-10 text-muted-foreground/40 mb-4" />
<p className="font-medium mb-1">Bankintegration (PSD2) är inte aktiverad</p>
<p className="text-sm text-muted-foreground mb-4 max-w-md">
Aktivera tillägget Enable Banking för att koppla ditt bankkonto och automatiskt hämta transaktioner.
</p>
<Button variant="outline" asChild>
<Link href="/extensions">
<ExternalLink className="mr-2 h-4 w-4" />
Gå till Tillägg
</Link>
</Button>
</CardContent>
</Card>
)}
</TabsContent>
{/* Banking settings — loaded dynamically from extension, hidden for sandbox */}
{!settings?.is_sandbox && (
<TabsContent value="banking" className="space-y-6">
{hasBankingExtension && BankingPanel ? (
<BankingPanel />
) : (
<Card>
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
<CreditCard className="h-10 w-10 text-muted-foreground/40 mb-4" />
<p className="font-medium mb-1">Bankintegration (PSD2) är inte aktiverad</p>
<p className="text-sm text-muted-foreground mb-4 max-w-md">
Aktivera tillägget Enable Banking för att koppla ditt bankkonto och automatiskt hämta transaktioner.
</p>
<Button variant="outline" asChild>
<Link href="/extensions">
<ExternalLink className="mr-2 h-4 w-4" />
Gå till Tillägg
</Link>
</Button>
</CardContent>
</Card>
)}
</TabsContent>
)}
{/* Calendar feed settings */}
{hasCalendarExtension && (
@@ -654,7 +658,7 @@ export default function SettingsPage() {
</CardContent>
</Card>
<Card className="border-destructive/50">
{!settings?.is_sandbox && <Card className="border-destructive/50">
<CardHeader>
<CardTitle className="text-destructive">Radera konto</CardTitle>
<CardDescription>
@@ -692,7 +696,7 @@ export default function SettingsPage() {
</Button>
</div>
</CardContent>
</Card>
</Card>}
</TabsContent>
</Tabs>
+47
View File
@@ -0,0 +1,47 @@
import { createClient } from '@supabase/supabase-js'
import { NextResponse } from 'next/server'
/**
* GET /api/sandbox/cleanup/cron
* Daily cron job to clean up expired sandbox users (>24h old).
* Runs at 04:00 UTC every day.
*/
export async function GET(request: Request) {
const authHeader = request.headers.get('authorization')
const cronSecret = process.env.CRON_SECRET
if (!cronSecret || authHeader !== `Bearer ${cronSecret}`) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return NextResponse.json(
{ error: 'Missing Supabase configuration' },
{ status: 500 }
)
}
const supabase = createClient(supabaseUrl, supabaseServiceKey)
try {
const { data, error } = await supabase.rpc('cleanup_expired_sandbox_users', {
p_max_age_hours: 24,
})
if (error) throw error
const cleaned = data ?? 0
console.log(`Sandbox cleanup cron completed: ${cleaned} users removed`)
return NextResponse.json({ success: true, cleaned })
} catch (error) {
console.error('Error in sandbox cleanup cron:', error)
return NextResponse.json(
{ error: 'Failed to clean up sandbox users' },
{ status: 500 }
)
}
}
File diff suppressed because it is too large Load Diff
+5 -1
View File
@@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'
import DashboardNav from '@/components/dashboard/DashboardNav'
import DashboardContent from '@/components/dashboard/DashboardContent'
import { SandboxBanner } from '@/components/dashboard/SandboxBanner'
import type { Deadline, ReceiptQueueSummary } from '@/types'
export default async function RootPage() {
@@ -204,9 +205,12 @@ export default async function RootPage() {
.eq('user_id', user.id)
.eq('enabled', true)
const isSandbox = settings.is_sandbox === true
return (
<div className="min-h-screen bg-background">
<DashboardNav companyName={settings.company_name || 'Min verksamhet'} entityType={settings.entity_type || 'enskild_firma'} />
{isSandbox && <SandboxBanner />}
<DashboardNav companyName={settings.company_name || 'Min verksamhet'} entityType={settings.entity_type || 'enskild_firma'} isSandbox={isSandbox} />
<main className="pb-20 md:pb-0 md:pl-64">
<div className="container max-w-6xl mx-auto px-4 py-6">
<DashboardContent
+183
View File
@@ -0,0 +1,183 @@
'use client'
import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import Image from 'next/image'
import { createClient } from '@/lib/supabase/client'
import { Button } from '@/components/ui/button'
import { useToast } from '@/components/ui/use-toast'
import { Loader2, Receipt, ArrowLeftRight, BookOpen, BarChart3 } from 'lucide-react'
export default function SandboxPage() {
const [isLoading, setIsLoading] = useState(false)
const [isLoggedIn, setIsLoggedIn] = useState<boolean | null>(null)
const { toast } = useToast()
const router = useRouter()
const supabase = createClient()
useEffect(() => {
supabase.auth.getUser().then(({ data: { user } }) => {
setIsLoggedIn(user !== null && !user.is_anonymous)
})
}, [supabase.auth])
const handleStartSandbox = async () => {
setIsLoading(true)
try {
const { error } = await supabase.auth.signInAnonymously()
if (error) {
toast({
title: 'Kunde inte starta sandlådan',
description: error.message,
variant: 'destructive',
})
setIsLoading(false)
return
}
const res = await fetch('/api/sandbox/seed', { method: 'POST' })
if (!res.ok) {
const body = await res.json().catch(() => ({}))
// Clean up the orphaned anonymous session so the user can retry cleanly
await supabase.auth.signOut()
toast({
title: 'Kunde inte skapa demodata',
description: 'Försök igen om en stund.',
variant: 'destructive',
})
setIsLoading(false)
return
}
// Full page load to ensure middleware picks up the new session cookies
window.location.href = '/'
} catch {
toast({
title: 'Något gick fel',
description: 'Försök igen om en stund.',
variant: 'destructive',
})
setIsLoading(false)
}
}
// Loading state while checking auth
if (isLoggedIn === null) {
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-b from-background to-primary/[0.03]">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
)
}
// Already logged in as a real user
if (isLoggedIn) {
return (
<div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-b from-background to-primary/[0.03] p-4">
<div className="w-full max-w-sm animate-slide-up">
<div className="text-center mb-10">
<Image
src="/gnubokiceon-removebg-preview.png"
alt="Gnubok"
width={240}
height={240}
className="mx-auto mb-2"
priority
/>
</div>
<div className="rounded-xl border bg-card p-6" style={{ boxShadow: 'var(--shadow-md)' }}>
<h1 className="text-lg font-medium tracking-tight text-center mb-2">
Du är redan inloggad
</h1>
<p className="text-sm text-muted-foreground text-center leading-relaxed">
Sandlådan kräver att du inte är inloggad. Öppna ett inkognitofönster
eller logga ut först.
</p>
</div>
<div className="mt-6 flex flex-col items-center gap-3">
<Button asChild className="w-full h-11">
<Link href="/">Gå till dashboard</Link>
</Button>
</div>
</div>
</div>
)
}
// Sandbox landing
return (
<div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-b from-background to-primary/[0.03] p-4">
<div className="w-full max-w-sm animate-slide-up">
<div className="text-center mb-10">
<Image
src="/gnubokiceon-removebg-preview.png"
alt="Gnubok"
width={240}
height={240}
className="mx-auto mb-2"
priority
/>
<h1 className="text-xl font-medium tracking-tight mt-3">
Testa gnubok utan att registrera dig
</h1>
<p className="text-muted-foreground text-sm mt-2 leading-relaxed">
Utforska ett fullt demoföretag med riktig data — helt gratis.
</p>
</div>
<div className="rounded-xl border bg-card p-6" style={{ boxShadow: 'var(--shadow-md)' }}>
{/* Feature highlights */}
<div className="grid grid-cols-2 gap-3 mb-6">
{[
{ icon: Receipt, label: 'Fakturor' },
{ icon: ArrowLeftRight, label: 'Transaktioner' },
{ icon: BookOpen, label: 'Bokföring' },
{ icon: BarChart3, label: 'Rapporter' },
].map(({ icon: Icon, label }) => (
<div
key={label}
className="flex items-center gap-2.5 rounded-lg bg-muted/40 px-3 py-2.5"
>
<Icon className="h-4 w-4 text-primary/70 flex-shrink-0" />
<span className="text-sm text-foreground/80">{label}</span>
</div>
))}
</div>
<Button
className="w-full h-11"
onClick={handleStartSandbox}
disabled={isLoading}
>
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Startar...
</>
) : (
'Starta sandbox'
)}
</Button>
<p className="text-xs text-muted-foreground/70 text-center mt-3">
Dina data raderas automatiskt efter 24 timmar
</p>
</div>
<p className="mt-6 text-center text-sm text-muted-foreground">
Har du redan ett konto?{' '}
<Link
href="/login"
className="font-medium text-foreground underline underline-offset-2 hover:text-primary transition-colors"
>
Logga in
</Link>
</p>
</div>
</div>
)
}