* 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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>
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
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" />
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" />
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 }
)
}
}
+508
View File
@@ -0,0 +1,508 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
/**
* POST /api/sandbox/seed
* Seeds demo data for an anonymous sandbox user.
* Only callable by anonymous users (is_anonymous === true).
*/
export async function POST() {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
if (!user.is_anonymous) {
return NextResponse.json({ error: 'Sandbox is only available for anonymous users' }, { status: 403 })
}
// Idempotency: if already seeded, return early
const { data: existing } = await supabase
.from('company_settings')
.select('id')
.eq('user_id', user.id)
.maybeSingle()
if (existing) {
return NextResponse.json({ seeded: false })
}
try {
const userId = user.id
// 1. Update profile (auto-created by auth trigger)
await supabase
.from('profiles')
.update({ full_name: 'Demo Användare' })
.eq('id', userId)
// 2. Create company settings
const { error: settingsError } = await supabase
.from('company_settings')
.insert({
user_id: userId,
entity_type: 'enskild_firma',
company_name: 'Sandlådan Konsult',
org_number: '199001011234',
address_line1: 'Demovägen 1',
postal_code: '111 22',
city: 'Stockholm',
country: 'SE',
f_skatt: true,
vat_registered: true,
vat_number: 'SE199001011234',
moms_period: 'quarterly',
fiscal_year_start_month: 1,
accounting_method: 'accrual',
invoice_prefix: 'F',
next_invoice_number: 5,
next_delivery_note_number: 1,
invoice_default_days: 30,
onboarding_step: 6,
onboarding_complete: true,
is_sandbox: true,
})
if (settingsError) throw settingsError
// 3. Seed chart of accounts via RPC
const { error: coaError } = await supabase.rpc('seed_chart_of_accounts', {
p_user_id: userId,
p_entity_type: 'enskild_firma',
})
if (coaError) throw coaError
// 4. Create fiscal period (current year)
const currentYear = new Date().getFullYear()
const { data: fiscalPeriod, error: fpError } = await supabase
.from('fiscal_periods')
.insert({
user_id: userId,
name: `Räkenskapsår ${currentYear}`,
period_start: `${currentYear}-01-01`,
period_end: `${currentYear}-12-31`,
})
.select('id')
.single()
if (fpError) throw fpError
// 5. Create customers
const { data: customers, error: custError } = await supabase
.from('customers')
.insert([
{
user_id: userId,
name: 'Björk & Partner AB',
customer_type: 'swedish_business',
email: 'faktura@bjorkpartner.se',
org_number: '5566778899',
vat_number: 'SE556677889901',
vat_number_validated: true,
address_line1: 'Storgatan 10',
postal_code: '111 44',
city: 'Stockholm',
country: 'SE',
default_payment_terms: 30,
},
{
user_id: userId,
name: 'Schmidt GmbH',
customer_type: 'eu_business',
email: 'billing@schmidt.de',
org_number: 'HRB 12345',
vat_number: 'DE123456789',
vat_number_validated: true,
address_line1: 'Hauptstraße 5',
postal_code: '10115',
city: 'Berlin',
country: 'DE',
default_payment_terms: 30,
},
{
user_id: userId,
name: 'Anna Lindström',
customer_type: 'individual',
email: 'anna.lindstrom@example.com',
address_line1: 'Lillgatan 3',
postal_code: '222 33',
city: 'Malmö',
country: 'SE',
default_payment_terms: 30,
},
])
.select('id, name')
if (custError) throw custError
const customerMap = Object.fromEntries(customers.map(c => [c.name, c.id]))
// 6. Create invoices
const today = new Date()
const pad = (n: number) => String(n).padStart(2, '0')
const toDateStr = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
const thirtyDaysAgo = new Date(today)
thirtyDaysAgo.setDate(today.getDate() - 30)
const fifteenDaysAgo = new Date(today)
fifteenDaysAgo.setDate(today.getDate() - 15)
const thirtyDaysFromNow = new Date(today)
thirtyDaysFromNow.setDate(today.getDate() + 30)
const fiveDaysAgo = new Date(today)
fiveDaysAgo.setDate(today.getDate() - 5)
const { data: invoices, error: invError } = await supabase
.from('invoices')
.insert([
{
user_id: userId,
customer_id: customerMap['Björk & Partner AB'],
invoice_number: 'F-2026001',
invoice_date: toDateStr(thirtyDaysAgo),
due_date: toDateStr(today),
status: 'paid',
subtotal: 15000,
vat_amount: 3750,
total: 18750,
vat_treatment: 'standard_25',
vat_rate: 25,
moms_ruta: '10',
document_type: 'invoice',
paid_at: toDateStr(fifteenDaysAgo),
paid_amount: 18750,
},
{
user_id: userId,
customer_id: customerMap['Schmidt GmbH'],
invoice_number: 'F-2026002',
invoice_date: toDateStr(fifteenDaysAgo),
due_date: toDateStr(thirtyDaysFromNow),
status: 'sent',
subtotal: 20000,
vat_amount: 0,
total: 20000,
vat_treatment: 'reverse_charge',
vat_rate: 0,
reverse_charge_text: 'Reverse charge — buyer is liable for VAT',
document_type: 'invoice',
},
{
user_id: userId,
customer_id: customerMap['Anna Lindström'],
invoice_number: 'F-2026003',
invoice_date: toDateStr(thirtyDaysAgo),
due_date: toDateStr(fiveDaysAgo),
status: 'overdue',
subtotal: 5000,
vat_amount: 1250,
total: 6250,
vat_treatment: 'standard_25',
vat_rate: 25,
moms_ruta: '10',
document_type: 'invoice',
},
{
user_id: userId,
customer_id: customerMap['Björk & Partner AB'],
invoice_number: 'F-2026004',
invoice_date: toDateStr(today),
due_date: toDateStr(thirtyDaysFromNow),
status: 'draft',
subtotal: 8000,
vat_amount: 2000,
total: 10000,
vat_treatment: 'standard_25',
vat_rate: 25,
moms_ruta: '10',
document_type: 'invoice',
},
])
.select('id, invoice_number')
if (invError) throw invError
const invoiceMap = Object.fromEntries(invoices.map(i => [i.invoice_number, i.id]))
// 7. Create invoice items
const { error: itemsError } = await supabase
.from('invoice_items')
.insert([
{
invoice_id: invoiceMap['F-2026001'],
description: 'Webbutveckling — mars 2026',
quantity: 30,
unit: 'tim',
unit_price: 500,
line_total: 15000,
vat_rate: 25,
},
{
invoice_id: invoiceMap['F-2026002'],
description: 'IT-konsulting — internationellt projekt',
quantity: 40,
unit: 'tim',
unit_price: 500,
line_total: 20000,
vat_rate: 0,
},
{
invoice_id: invoiceMap['F-2026003'],
description: 'Hemsida & grafisk profil',
quantity: 1,
unit: 'st',
unit_price: 5000,
line_total: 5000,
vat_rate: 25,
},
{
invoice_id: invoiceMap['F-2026004'],
description: 'Systemunderhåll april 2026',
quantity: 16,
unit: 'tim',
unit_price: 500,
line_total: 8000,
vat_rate: 25,
},
])
if (itemsError) throw itemsError
// 8. Resolve account IDs for journal entries
const { data: accounts } = await supabase
.from('chart_of_accounts')
.select('id, account_number')
.eq('user_id', userId)
.in('account_number', ['1510', '1930', '2611', '3001'])
const accountMap = Object.fromEntries(
(accounts ?? []).map(a => [a.account_number, a.id])
)
// 9. Create journal entries (inserted directly, not via engine, to avoid event emission)
const { data: voucherNum1 } = await supabase.rpc('next_voucher_number', {
p_user_id: userId,
p_fiscal_period_id: fiscalPeriod.id,
p_series: 'A',
})
const { data: je1, error: je1Error } = await supabase
.from('journal_entries')
.insert({
user_id: userId,
fiscal_period_id: fiscalPeriod.id,
voucher_number: voucherNum1 ?? 1,
voucher_series: 'A',
entry_date: toDateStr(thirtyDaysAgo),
description: 'Faktura F-2026001 — Björk & Partner AB',
source_type: 'invoice_created',
source_id: invoiceMap['F-2026001'],
status: 'posted',
committed_at: toDateStr(thirtyDaysAgo),
})
.select('id')
.single()
if (je1Error) throw je1Error
const { data: voucherNum2 } = await supabase.rpc('next_voucher_number', {
p_user_id: userId,
p_fiscal_period_id: fiscalPeriod.id,
p_series: 'A',
})
const { data: je2, error: je2Error } = await supabase
.from('journal_entries')
.insert({
user_id: userId,
fiscal_period_id: fiscalPeriod.id,
voucher_number: voucherNum2 ?? 2,
voucher_series: 'A',
entry_date: toDateStr(fifteenDaysAgo),
description: 'Betalning faktura F-2026001 — Björk & Partner AB',
source_type: 'invoice_paid',
source_id: invoiceMap['F-2026001'],
status: 'posted',
committed_at: toDateStr(fifteenDaysAgo),
})
.select('id')
.single()
if (je2Error) throw je2Error
// 10. Create journal entry lines
const { error: jelError } = await supabase
.from('journal_entry_lines')
.insert([
// JE1: Invoice creation — Debit AR, Credit Revenue + VAT
{
journal_entry_id: je1.id,
account_number: '1510',
account_id: accountMap['1510'] ?? null,
debit_amount: 18750,
credit_amount: 0,
sort_order: 0,
},
{
journal_entry_id: je1.id,
account_number: '3001',
account_id: accountMap['3001'] ?? null,
debit_amount: 0,
credit_amount: 15000,
sort_order: 1,
},
{
journal_entry_id: je1.id,
account_number: '2611',
account_id: accountMap['2611'] ?? null,
debit_amount: 0,
credit_amount: 3750,
sort_order: 2,
},
// JE2: Invoice payment — Debit Bank, Credit AR
{
journal_entry_id: je2.id,
account_number: '1930',
account_id: accountMap['1930'] ?? null,
debit_amount: 18750,
credit_amount: 0,
sort_order: 0,
},
{
journal_entry_id: je2.id,
account_number: '1510',
account_id: accountMap['1510'] ?? null,
debit_amount: 0,
credit_amount: 18750,
sort_order: 1,
},
])
if (jelError) throw jelError
// 11. Create transactions
const { error: txError } = await supabase
.from('transactions')
.insert([
// Categorized expenses
{
user_id: userId,
date: toDateStr(thirtyDaysAgo),
description: 'CLAS OHLSON STOCKHOLM',
amount: -450,
category: 'expense_office',
is_business: true,
merchant_name: 'Clas Ohlson',
},
{
user_id: userId,
date: toDateStr(fifteenDaysAgo),
description: 'GITHUB INC',
amount: -999,
category: 'expense_software',
is_business: true,
merchant_name: 'GitHub',
},
{
user_id: userId,
date: toDateStr(fiveDaysAgo),
description: 'SJ BILJETT',
amount: -2500,
category: 'expense_travel',
is_business: true,
merchant_name: 'SJ',
},
// Income matched to paid invoice
{
user_id: userId,
date: toDateStr(fifteenDaysAgo),
description: 'BJÖRK & PARTNER AB BETALNING F-2026001',
amount: 18750,
category: 'income_services',
is_business: true,
invoice_id: invoiceMap['F-2026001'],
journal_entry_id: je2.id,
merchant_name: 'Björk & Partner AB',
},
// Private transaction
{
user_id: userId,
date: toDateStr(fiveDaysAgo),
description: 'PRIVAT INSÄTTNING',
amount: 5000,
category: 'private',
is_business: false,
},
// Uncategorized transactions
{
user_id: userId,
date: toDateStr(fiveDaysAgo),
description: 'SWISH BETALNING 0701234567',
amount: -350,
category: 'uncategorized',
is_business: null,
},
{
user_id: userId,
date: toDateStr(today),
description: 'INSÄTTNING BANKGIRO',
amount: 1200,
category: 'uncategorized',
is_business: null,
},
{
user_id: userId,
date: toDateStr(today),
description: 'KORTBETALNING RESTAURANG',
amount: -680,
category: 'uncategorized',
is_business: null,
},
])
if (txError) throw txError
// 12. Create deadlines
const momsDeadline = new Date(today)
momsDeadline.setMonth(momsDeadline.getMonth() + 2)
momsDeadline.setDate(12)
const { error: dlError } = await supabase
.from('deadlines')
.insert([
{
user_id: userId,
title: 'Momsdeklaration Q1 2026',
due_date: toDateStr(momsDeadline),
deadline_type: 'tax',
priority: 'important',
tax_deadline_type: 'moms',
tax_period: `${currentYear}-Q1`,
source: 'system',
status: 'upcoming',
linked_report_type: 'vat',
},
{
user_id: userId,
title: 'Inkomstdeklaration 2025',
due_date: `${currentYear}-05-02`,
deadline_type: 'tax',
priority: 'critical',
tax_deadline_type: 'inkomstdeklaration',
tax_period: `${currentYear - 1}`,
source: 'system',
status: 'upcoming',
},
])
if (dlError) throw dlError
return NextResponse.json({ seeded: true })
} catch {
return NextResponse.json(
{ error: 'Failed to seed sandbox data' },
{ status: 500 }
)
}
}
+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="/"> 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>
)
}
+5 -4
View File
@@ -31,6 +31,7 @@ interface DashboardNavProps {
companyName: string
entityType: EntityType
uncategorizedTransactionCount?: number
isSandbox?: boolean
}
interface NavItem {
@@ -66,7 +67,7 @@ const groupLabels: Record<string, string> = {
övrigt: 'Övrigt',
}
export default function DashboardNav({ companyName, entityType, uncategorizedTransactionCount = 0 }: DashboardNavProps) {
export default function DashboardNav({ companyName, entityType, uncategorizedTransactionCount = 0, isSandbox = false }: DashboardNavProps) {
const pathname = usePathname()
const router = useRouter()
const supabase = createClient()
@@ -81,7 +82,7 @@ export default function DashboardNav({ companyName, entityType, uncategorizedTra
const handleLogout = async () => {
await supabase.auth.signOut()
router.push('/login')
router.push(isSandbox ? '/sandbox' : '/login')
}
const isActive = (href: string) => {
@@ -243,7 +244,7 @@ export default function DashboardNav({ companyName, entityType, uncategorizedTra
onClick={handleLogout}
>
<LogOut className="mr-2.5 h-[15px] w-[15px]" />
Logga ut
{isSandbox ? 'Avsluta sandbox' : 'Logga ut'}
</Button>
</div>
</div>
@@ -424,7 +425,7 @@ export default function DashboardNav({ companyName, entityType, uncategorizedTra
}}
>
<LogOut className="mr-3 h-5 w-5" />
Logga ut
{isSandbox ? 'Avsluta sandbox' : 'Logga ut'}
</Button>
</div>
</div>
+40
View File
@@ -0,0 +1,40 @@
'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { X } from 'lucide-react'
import { createClient } from '@/lib/supabase/client'
export function SandboxBanner() {
const [dismissed, setDismissed] = useState(false)
const router = useRouter()
if (dismissed) return null
async function handleCreateAccount() {
const supabase = createClient()
await supabase.auth.signOut()
router.push('/register')
}
return (
<div className="relative z-50 flex items-center justify-center gap-3 bg-amber-500/90 px-4 py-2 text-sm text-amber-950">
<span className="font-medium">
Sandlådemiljö dina data raderas automatiskt efter 24 timmar
</span>
<button
onClick={handleCreateAccount}
className="rounded-md bg-amber-950/15 px-3 py-0.5 text-xs font-semibold hover:bg-amber-950/25 transition-colors"
>
Skapa konto
</button>
<button
onClick={() => setDismissed(true)}
className="absolute right-3 top-1/2 -translate-y-1/2 rounded p-0.5 hover:bg-amber-950/15 transition-colors"
aria-label="Stäng"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
)
}
+2 -1
View File
@@ -54,7 +54,8 @@ export async function updateSession(request: NextRequest) {
pathname.startsWith('/login') ||
pathname.startsWith('/register') ||
pathname.startsWith('/auth') ||
pathname.startsWith('/reset-password')
pathname.startsWith('/reset-password') ||
pathname.startsWith('/sandbox')
) {
// If user is logged in and trying to access auth pages, redirect to dashboard or onboarding
if (user) {
@@ -110,7 +110,4 @@ CREATE TRIGGER audit_company_settings
AFTER INSERT OR UPDATE OR DELETE ON public.company_settings
FOR EACH ROW EXECUTE FUNCTION public.write_audit_log();
-- tax_codes
CREATE TRIGGER audit_tax_codes
AFTER INSERT OR UPDATE OR DELETE ON public.tax_codes
FOR EACH ROW EXECUTE FUNCTION public.write_audit_log();
-- tax_codes trigger removed: table never created (migration 012 is a placeholder)
@@ -6,7 +6,7 @@ ALTER FUNCTION public.audit_log_immutable() SET search_path = public;
ALTER FUNCTION public.block_document_deletion() SET search_path = public;
ALTER FUNCTION public.calculate_retention_expiry() SET search_path = public;
ALTER FUNCTION public.check_journal_entry_balance() SET search_path = public;
ALTER FUNCTION public.create_invoice_with_items(p_invoice jsonb, p_items jsonb) SET search_path = public;
-- create_invoice_with_items removed: function was never created
ALTER FUNCTION public.detect_voucher_gaps(p_user_id uuid, p_fiscal_period_id uuid, p_series text) SET search_path = public;
ALTER FUNCTION public.enforce_journal_entry_immutability() SET search_path = public;
ALTER FUNCTION public.enforce_journal_entry_line_immutability() SET search_path = public;
@@ -14,15 +14,15 @@ ALTER FUNCTION public.enforce_opening_balance_immutability() SET search_path = p
ALTER FUNCTION public.enforce_period_lock() SET search_path = public;
ALTER FUNCTION public.enforce_period_lock_documents() SET search_path = public;
ALTER FUNCTION public.enforce_retention_journal_entries() SET search_path = public;
ALTER FUNCTION public.generate_invoice_number(p_user_id uuid) SET search_path = public;
-- generate_invoice_number removed: created in later migration (20260306) with search_path already set
ALTER FUNCTION public.get_next_arrival_number(p_user_id uuid) SET search_path = public;
ALTER FUNCTION public.get_unlinked_1930_lines(p_user_id uuid, p_date_from date, p_date_to date) SET search_path = public;
ALTER FUNCTION public.handle_new_user() SET search_path = public;
ALTER FUNCTION public.next_voucher_number(p_user_id uuid, p_fiscal_period_id uuid, p_series text) SET search_path = public;
ALTER FUNCTION public.seed_asset_categories(p_user_id uuid) SET search_path = public;
-- seed_asset_categories removed: function was never created
ALTER FUNCTION public.seed_chart_of_accounts(p_user_id uuid, p_entity_type text) SET search_path = public;
ALTER FUNCTION public.set_committed_at() SET search_path = public;
ALTER FUNCTION public.update_overdue_supplier_invoices() SET search_path = public;
ALTER FUNCTION public.update_reconciliation_session_counts() SET search_path = public;
-- update_reconciliation_session_counts removed: function was never created
ALTER FUNCTION public.update_updated_at_column() SET search_path = public;
ALTER FUNCTION public.write_audit_log() SET search_path = public;
@@ -0,0 +1,289 @@
-- Sandbox support: is_sandbox column, enforcement trigger bypasses, cleanup functions
-- =============================================================================
-- 1a. Add is_sandbox column to company_settings
-- =============================================================================
ALTER TABLE public.company_settings
ADD COLUMN is_sandbox boolean NOT NULL DEFAULT false;
CREATE INDEX idx_company_settings_sandbox
ON public.company_settings (is_sandbox)
WHERE is_sandbox = true;
-- =============================================================================
-- 1b. Update enforcement triggers to skip for sandbox users
-- =============================================================================
-- enforce_journal_entry_immutability — add sandbox bypass
CREATE OR REPLACE FUNCTION public.enforce_journal_entry_immutability()
RETURNS trigger
LANGUAGE plpgsql
SET search_path = public
AS $$
BEGIN
-- Skip enforcement for sandbox users
IF EXISTS (
SELECT 1 FROM public.company_settings
WHERE user_id = COALESCE(OLD.user_id, NEW.user_id) AND is_sandbox = true
) THEN
IF TG_OP = 'DELETE' THEN
RETURN OLD;
END IF;
RETURN NEW;
END IF;
IF TG_OP = 'DELETE' THEN
-- Allow deleting drafts
IF OLD.status = 'draft' THEN
RETURN OLD;
END IF;
RAISE EXCEPTION 'Cannot delete a % journal entry (id: %)', OLD.status, OLD.id;
END IF;
-- TG_OP = 'UPDATE'
-- Allow: draft → draft (editing a draft)
IF OLD.status = 'draft' AND NEW.status = 'draft' THEN
RETURN NEW;
END IF;
-- Allow: draft → posted (committing)
IF OLD.status = 'draft' AND NEW.status = 'posted' THEN
RETURN NEW;
END IF;
-- Allow: posted → reversed (storno reversal)
IF OLD.status = 'posted' AND NEW.status = 'reversed' THEN
-- Only allow setting reversed_by_id during this transition
IF NEW.description != OLD.description
OR NEW.entry_date != OLD.entry_date
OR NEW.fiscal_period_id != OLD.fiscal_period_id
OR NEW.voucher_number != OLD.voucher_number THEN
RAISE EXCEPTION 'Cannot modify fields of a posted entry during reversal (id: %)', OLD.id;
END IF;
RETURN NEW;
END IF;
-- Block all other transitions
RAISE EXCEPTION 'Cannot modify a % journal entry (id: %). Committed entries are immutable per Bokföringslagen.',
OLD.status, OLD.id;
END;
$$;
-- enforce_journal_entry_line_immutability — add sandbox bypass
CREATE OR REPLACE FUNCTION public.enforce_journal_entry_line_immutability()
RETURNS trigger
LANGUAGE plpgsql
SET search_path = public
AS $$
DECLARE
v_status text;
v_user_id uuid;
BEGIN
-- Get the parent entry status and user_id
SELECT status, user_id INTO v_status, v_user_id
FROM public.journal_entries
WHERE id = COALESCE(OLD.journal_entry_id, NEW.journal_entry_id);
-- Skip enforcement for sandbox users
IF EXISTS (
SELECT 1 FROM public.company_settings
WHERE user_id = v_user_id AND is_sandbox = true
) THEN
IF TG_OP = 'DELETE' THEN
RETURN OLD;
END IF;
RETURN NEW;
END IF;
-- Allow modifications to lines of draft entries
IF v_status = 'draft' THEN
IF TG_OP = 'DELETE' THEN
RETURN OLD;
END IF;
RETURN NEW;
END IF;
-- Block modifications to lines of posted/reversed entries
RAISE EXCEPTION 'Cannot % lines of a % journal entry. Committed entries are immutable per Bokföringslagen.',
TG_OP, v_status;
END;
$$;
-- enforce_retention_journal_entries — add sandbox bypass (SECURITY DEFINER)
CREATE OR REPLACE FUNCTION public.enforce_retention_journal_entries()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
v_retention_expires date;
BEGIN
-- Skip enforcement for sandbox users
IF EXISTS (
SELECT 1 FROM public.company_settings
WHERE user_id = OLD.user_id AND is_sandbox = true
) THEN
RETURN OLD;
END IF;
SELECT fp.retention_expires_at INTO v_retention_expires
FROM public.fiscal_periods fp
WHERE fp.id = OLD.fiscal_period_id;
IF v_retention_expires IS NOT NULL AND v_retention_expires > CURRENT_DATE THEN
INSERT INTO public.audit_log (user_id, action, table_name, record_id, description)
VALUES (OLD.user_id, 'RETENTION_BLOCK', 'journal_entries', OLD.id,
'Attempted deletion within retention period (expires ' || v_retention_expires || ')');
RAISE EXCEPTION 'Cannot delete journal entry within 7-year retention period (expires %)',
v_retention_expires;
END IF;
RETURN OLD;
END;
$$;
-- block_document_deletion — add sandbox bypass (SECURITY DEFINER)
CREATE OR REPLACE FUNCTION public.block_document_deletion()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
v_entry_status text;
v_retention_expires date;
BEGIN
-- Skip enforcement for sandbox users
IF EXISTS (
SELECT 1 FROM public.company_settings
WHERE user_id = OLD.user_id AND is_sandbox = true
) THEN
RETURN OLD;
END IF;
-- Check if linked to a committed journal entry
IF OLD.journal_entry_id IS NOT NULL THEN
SELECT je.status INTO v_entry_status
FROM public.journal_entries je
WHERE je.id = OLD.journal_entry_id;
IF v_entry_status IN ('posted', 'reversed') THEN
-- Log the blocked attempt
INSERT INTO public.audit_log (user_id, action, table_name, record_id, description)
VALUES (OLD.user_id, 'DOCUMENT_DELETE_BLOCKED', 'document_attachments', OLD.id,
'Attempted deletion of document linked to ' || v_entry_status || ' journal entry ' || OLD.journal_entry_id);
RAISE EXCEPTION 'Cannot delete document linked to a % journal entry (Bokföringslagen)',
v_entry_status;
END IF;
END IF;
-- Check retention window
IF OLD.journal_entry_id IS NOT NULL THEN
SELECT fp.retention_expires_at INTO v_retention_expires
FROM public.journal_entries je
JOIN public.fiscal_periods fp ON fp.id = je.fiscal_period_id
WHERE je.id = OLD.journal_entry_id;
IF v_retention_expires IS NOT NULL AND v_retention_expires > CURRENT_DATE THEN
INSERT INTO public.audit_log (user_id, action, table_name, record_id, description)
VALUES (OLD.user_id, 'RETENTION_BLOCK', 'document_attachments', OLD.id,
'Attempted deletion within retention period (expires ' || v_retention_expires || ')');
RAISE EXCEPTION 'Cannot delete document within 7-year retention period (expires %)',
v_retention_expires;
END IF;
END IF;
RETURN OLD;
END;
$$;
-- =============================================================================
-- 1c. cleanup_sandbox_user(p_user_id uuid)
-- =============================================================================
CREATE OR REPLACE FUNCTION public.cleanup_sandbox_user(p_user_id uuid)
RETURNS integer
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
v_is_sandbox boolean;
v_deleted integer := 0;
BEGIN
-- Verify this is a sandbox user
SELECT is_sandbox INTO v_is_sandbox
FROM public.company_settings
WHERE user_id = p_user_id;
IF v_is_sandbox IS NOT TRUE THEN
RAISE EXCEPTION 'User % is not a sandbox user', p_user_id;
END IF;
-- Clear RESTRICT FKs on document_attachments
UPDATE public.document_attachments
SET journal_entry_id = NULL, journal_entry_line_id = NULL
WHERE user_id = p_user_id;
DELETE FROM public.document_attachments WHERE user_id = p_user_id;
-- Delete journal entry lines (child of journal_entries)
DELETE FROM public.journal_entry_lines
WHERE journal_entry_id IN (
SELECT id FROM public.journal_entries WHERE user_id = p_user_id
);
-- Delete journal entries (triggers bypass for sandbox)
DELETE FROM public.journal_entries WHERE user_id = p_user_id;
-- Delete supplier invoices before suppliers cascade
DELETE FROM public.supplier_invoices WHERE user_id = p_user_id;
-- Delete from auth.users — cascades everything else
DELETE FROM auth.users WHERE id = p_user_id;
GET DIAGNOSTICS v_deleted = ROW_COUNT;
RETURN v_deleted;
END;
$$;
-- =============================================================================
-- 1d. cleanup_expired_sandbox_users(p_max_age_hours int)
-- =============================================================================
CREATE OR REPLACE FUNCTION public.cleanup_expired_sandbox_users(p_max_age_hours int DEFAULT 24)
RETURNS integer
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
v_user_id uuid;
v_total integer := 0;
BEGIN
FOR v_user_id IN
SELECT cs.user_id
FROM public.company_settings cs
WHERE cs.is_sandbox = true
AND cs.created_at < now() - interval '1 hour' * p_max_age_hours
LOOP
BEGIN
PERFORM public.cleanup_sandbox_user(v_user_id);
v_total := v_total + 1;
EXCEPTION WHEN OTHERS THEN
RAISE WARNING 'Failed to clean up sandbox user %: %', v_user_id, SQLERRM;
END;
END LOOP;
RETURN v_total;
END;
$$;
-- Grant execute to service_role
GRANT EXECUTE ON FUNCTION public.cleanup_sandbox_user(uuid) TO service_role;
GRANT EXECUTE ON FUNCTION public.cleanup_expired_sandbox_users(int) TO service_role;
+1
View File
@@ -449,6 +449,7 @@ export function makeCompanySettings(
onboarding_step: 6,
onboarding_complete: true,
sector_slug: null,
is_sandbox: false,
created_at: '2024-01-01T00:00:00Z',
updated_at: '2024-01-01T00:00:00Z',
...overrides,
+3
View File
@@ -138,6 +138,9 @@ export interface CompanySettings {
// Sector
sector_slug: string | null
// Sandbox
is_sandbox: boolean
// Timestamps
created_at: string
updated_at: string
+4
View File
@@ -19,6 +19,10 @@
{
"path": "/api/documents/verify/cron",
"schedule": "0 3 * * 0"
},
{
"path": "/api/sandbox/cleanup/cron",
"schedule": "0 4 * * *"
}
]
}