* 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>
509 lines
15 KiB
TypeScript
509 lines
15 KiB
TypeScript
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 }
|
|
)
|
|
}
|
|
}
|