Delete features (#218)
* Implement company and account deletion features - Add event types for company and account deletion to CoreEvent. - Enhance Supabase middleware to handle company context resolution and cookie management for archived companies. - Create API routes for deleting accounts and companies, including necessary validations and event emissions. - Implement tests for account and company deletion endpoints to ensure proper functionality and error handling. - Add retention notice component to inform users about bookkeeping data retention during destructive actions. - Create database migrations to support soft deletion of companies and anonymization of user accounts, ensuring compliance with retention laws. * feat: enhance account deletion process and update user notifications * Add service client for onboarding completion check and update escape hatch visibility * Enhance invite flow and email handling for company members * Refactor company context and RLS policies for active company isolation - Update `switchCompany` to remove unnecessary revalidation as client handles navigation. - Revise `getActiveCompanyId` to prioritize `user_preferences` and validate against non-archived memberships. - Modify `setActiveCompany` to ensure `user_preferences` is the authoritative source while maintaining cookie compatibility. - Enhance middleware to resolve active company using `user_preferences` and fallback to first non-archived membership. - Introduce new API route `/api/company/current` to fetch the active company ID for cross-tab synchronization. - Implement `CompanyTabSync` component for real-time active company enforcement across tabs. - Create migration for RLS policies to enforce single-active-company isolation using `current_active_company_id()`. * feat: implement viewer role enforcement for write permissions - Added `useCanWrite` hook to determine if the current user has write permissions based on their role in the active company. - Updated various components (JournalEntryForm, CustomerForm, DeadlineForm, etc.) to disable write actions and show a lock icon with a tooltip for users without write permissions. - Introduced `requireWritePermission` function to enforce write permissions at the API level, returning a 403 response for viewers. - Created tests to verify the behavior of the viewer role and write permissions. - Added database migration to enforce read-only access for viewers at the database level.
This commit is contained in:
@@ -5,7 +5,8 @@ import Link from 'next/link'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { AccountNumber } from '@/components/ui/account-number'
|
||||
import { Loader2, ArrowLeft, Paperclip, AlertTriangle } from 'lucide-react'
|
||||
import { Loader2, ArrowLeft, Paperclip, AlertTriangle, Lock } from 'lucide-react'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import JournalEntryAttachments from '@/components/bookkeeping/JournalEntryAttachments'
|
||||
import JournalEntryStatusBadge, { sourceTypeLabels } from '@/components/bookkeeping/JournalEntryStatusBadge'
|
||||
import CorrectionEntryDialog from '@/components/bookkeeping/CorrectionEntryDialog'
|
||||
@@ -14,6 +15,7 @@ import type { JournalEntry, JournalEntryLine } from '@/types'
|
||||
|
||||
export default function JournalEntryDetailPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = use(params)
|
||||
const { canWrite } = useCanWrite()
|
||||
const [entry, setEntry] = useState<JournalEntry | null>(null)
|
||||
const [chain, setChain] = useState<JournalEntry[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
@@ -124,7 +126,10 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
size="sm"
|
||||
className="w-full sm:w-auto"
|
||||
onClick={() => setShowCorrection(true)}
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{!canWrite && <Lock className="mr-2 h-4 w-4" />}
|
||||
Skapa ändringsverifikation
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@@ -23,7 +23,9 @@ import {
|
||||
Trash2,
|
||||
Loader2,
|
||||
Receipt,
|
||||
Lock,
|
||||
} from 'lucide-react'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import type { Customer, CustomerType, CreateCustomerInput } from '@/types'
|
||||
|
||||
const customerTypeLabels: Record<CustomerType, string> = {
|
||||
@@ -63,6 +65,7 @@ export default function CustomerDetailPage({
|
||||
const { id } = use(params)
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
const { canWrite } = useCanWrite()
|
||||
const [customer, setCustomer] = useState<CustomerWithRelations | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isEditOpen, setIsEditOpen] = useState(false)
|
||||
@@ -203,8 +206,14 @@ export default function CustomerDetailPage({
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => setIsEditOpen(true)}>
|
||||
<Edit2 className="h-4 w-4 mr-1" />
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setIsEditOpen(true)}
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{canWrite ? <Edit2 className="h-4 w-4 mr-1" /> : <Lock className="h-4 w-4 mr-1" />}
|
||||
Redigera
|
||||
</Button>
|
||||
<Button
|
||||
@@ -212,8 +221,10 @@ export default function CustomerDetailPage({
|
||||
size="sm"
|
||||
onClick={handleDelete}
|
||||
className="text-destructive hover:text-destructive"
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-1" />
|
||||
{canWrite ? <Trash2 className="h-4 w-4 mr-1" /> : <Lock className="h-4 w-4 mr-1" />}
|
||||
Ta bort
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -8,11 +8,12 @@ import { Badge } from '@/components/ui/badge'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Plus, Search, Users } from 'lucide-react'
|
||||
import { Plus, Search, Users, Lock } from 'lucide-react'
|
||||
import CustomerForm from '@/components/customers/CustomerForm'
|
||||
import { EmptyCustomers } from '@/components/ui/empty-state'
|
||||
import Link from 'next/link'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import type { Customer, CustomerType, CreateCustomerInput } from '@/types'
|
||||
|
||||
const customerTypeLabels: Record<CustomerType, string> = {
|
||||
@@ -33,6 +34,7 @@ function getInitials(name: string): string {
|
||||
|
||||
export default function CustomersPage() {
|
||||
const { company } = useCompany()
|
||||
const { canWrite } = useCanWrite()
|
||||
const [customers, setCustomers] = useState<Customer[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
@@ -112,8 +114,15 @@ export default function CustomersPage() {
|
||||
</div>
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
<Button
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{canWrite ? (
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
) : (
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Ny kund
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
|
||||
@@ -18,7 +18,8 @@ import AccountCombobox from '@/components/bookkeeping/AccountCombobox'
|
||||
import { getAccountDescription } from '@/lib/bookkeeping/account-descriptions'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { useUnsavedChanges } from '@/lib/hooks/use-unsaved-changes'
|
||||
import { ArrowLeft, Plus, Trash2, ChevronDown, Loader2 } from 'lucide-react'
|
||||
import { ArrowLeft, Plus, Trash2, ChevronDown, Loader2, Lock } from 'lucide-react'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import type { Supplier, BASAccount, VatTreatment, EntityType } from '@/types'
|
||||
|
||||
interface LineItem {
|
||||
@@ -72,6 +73,7 @@ function inferVatTreatment(items: LineItem[], reverseCharge: boolean): VatTreatm
|
||||
|
||||
export default function NewExpensePage() {
|
||||
const router = useRouter()
|
||||
const { canWrite } = useCanWrite()
|
||||
const { toast } = useToast()
|
||||
const [suppliers, setSuppliers] = useState<Supplier[]>([])
|
||||
const [accounts, setAccounts] = useState<BASAccount[]>([])
|
||||
@@ -704,12 +706,22 @@ export default function NewExpensePage() {
|
||||
<Button type="button" variant="outline" className="w-full sm:w-auto" onClick={() => router.push('/expenses')}>
|
||||
Avbryt
|
||||
</Button>
|
||||
<Button type="submit" disabled={isSubmitting} className="w-full sm:w-auto">
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={isSubmitting || !canWrite}
|
||||
className="w-full sm:w-auto"
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Registrerar...
|
||||
</>
|
||||
) : !canWrite ? (
|
||||
<>
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
{isEF ? 'Registrera utgift' : 'Granska & registrera'}
|
||||
</>
|
||||
) : isEF ? (
|
||||
'Registrera utgift'
|
||||
) : (
|
||||
|
||||
@@ -12,8 +12,9 @@ import { PageHeader } from '@/components/ui/page-header'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { Plus, Search, Wallet, Clock, AlertCircle } from 'lucide-react'
|
||||
import { Plus, Search, Wallet, Clock, AlertCircle, Lock } from 'lucide-react'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import type { SupplierInvoice } from '@/types'
|
||||
|
||||
type ExpenseInvoice = SupplierInvoice & { supplier?: { id: string; name: string } }
|
||||
@@ -62,6 +63,7 @@ function getRelativeTimeLabel(dueDateStr: string, status: string): { text: strin
|
||||
|
||||
export default function ExpensesPage() {
|
||||
const { company } = useCompany()
|
||||
const { canWrite } = useCanWrite()
|
||||
const [invoices, setInvoices] = useState<ExpenseInvoice[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
@@ -119,12 +121,22 @@ export default function ExpensesPage() {
|
||||
title="Utgifter"
|
||||
description="Registrera och hantera dina utgifter"
|
||||
action={
|
||||
<Link href="/expenses/new">
|
||||
<Button>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
canWrite ? (
|
||||
<Link href="/expenses/new">
|
||||
<Button>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Ny utgift
|
||||
</Button>
|
||||
</Link>
|
||||
) : (
|
||||
<Button
|
||||
disabled
|
||||
title="Du har endast läsbehörighet i detta företag"
|
||||
>
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
Ny utgift
|
||||
</Button>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
/>
|
||||
|
||||
|
||||
@@ -12,7 +12,8 @@ import { Separator } from '@/components/ui/separator'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { cn, formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { getVatTreatmentLabel } from '@/lib/invoices/vat-rules'
|
||||
import { Loader2, ArrowLeft, AlertTriangle } from 'lucide-react'
|
||||
import { Loader2, ArrowLeft, AlertTriangle, Lock } from 'lucide-react'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import type { Invoice, InvoiceItem, Customer } from '@/types'
|
||||
|
||||
interface InvoiceWithRelations extends Invoice {
|
||||
@@ -21,6 +22,7 @@ interface InvoiceWithRelations extends Invoice {
|
||||
}
|
||||
|
||||
export default function CreateCreditNotePage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { canWrite } = useCanWrite()
|
||||
const { id } = use(params)
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
@@ -325,13 +327,19 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting || confirmText !== invoice.invoice_number}
|
||||
disabled={isSubmitting || confirmText !== invoice.invoice_number || !canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Skapar...
|
||||
</>
|
||||
) : !canWrite ? (
|
||||
<>
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
Skapa kreditfaktura
|
||||
</>
|
||||
) : (
|
||||
'Skapa kreditfaktura'
|
||||
)}
|
||||
|
||||
@@ -26,7 +26,9 @@ import {
|
||||
AlertTriangle,
|
||||
MessageSquare,
|
||||
Trash2,
|
||||
Lock,
|
||||
} from 'lucide-react'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import PaymentBookingDialog from '@/components/invoices/PaymentBookingDialog'
|
||||
import SendInvoiceDialog from '@/components/invoices/SendInvoiceDialog'
|
||||
import {
|
||||
@@ -62,6 +64,7 @@ interface InvoiceWithRelations extends Invoice {
|
||||
}
|
||||
|
||||
export default function InvoiceDetailPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { canWrite } = useCanWrite()
|
||||
const { id } = use(params)
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
@@ -379,9 +382,15 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
|
||||
{/* Actions */}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{isProforma && invoice.status !== 'cancelled' && (
|
||||
<Button onClick={convertToInvoice} disabled={isConverting}>
|
||||
<Button
|
||||
onClick={convertToInvoice}
|
||||
disabled={isConverting || !canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{isConverting ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : !canWrite ? (
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
) : (
|
||||
<FileText className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
@@ -390,26 +399,44 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
|
||||
)}
|
||||
{invoice.status === 'draft' && !isDeliveryNote && (
|
||||
customerHasEmail ? (
|
||||
<Button onClick={() => openSendDialog('email')}>
|
||||
<Mail className="mr-2 h-4 w-4" />
|
||||
<Button
|
||||
onClick={() => openSendDialog('email')}
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{canWrite ? <Mail className="mr-2 h-4 w-4" /> : <Lock className="mr-2 h-4 w-4" />}
|
||||
Skicka via e-post
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="secondary" onClick={() => openSendDialog('manual')}>
|
||||
<Send className="mr-2 h-4 w-4" />
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => openSendDialog('manual')}
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{canWrite ? <Send className="mr-2 h-4 w-4" /> : <Lock className="mr-2 h-4 w-4" />}
|
||||
Skickad manuellt
|
||||
</Button>
|
||||
)
|
||||
)}
|
||||
{isDeliveryNote && invoice.status === 'draft' && (
|
||||
<Button variant="secondary" onClick={() => updateStatus('sent')} disabled={isUpdating}>
|
||||
<Send className="mr-2 h-4 w-4" />
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => updateStatus('sent')}
|
||||
disabled={isUpdating || !canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{canWrite ? <Send className="mr-2 h-4 w-4" /> : <Lock className="mr-2 h-4 w-4" />}
|
||||
Markera som skickad
|
||||
</Button>
|
||||
)}
|
||||
{(invoice.status === 'sent' || invoice.status === 'overdue') && isRealInvoice && (
|
||||
<Button onClick={() => setShowPaymentDialog(true)} disabled={isUpdating}>
|
||||
<CheckCircle className="mr-2 h-4 w-4" />
|
||||
<Button
|
||||
onClick={() => setShowPaymentDialog(true)}
|
||||
disabled={isUpdating || !canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{canWrite ? <CheckCircle className="mr-2 h-4 w-4" /> : <Lock className="mr-2 h-4 w-4" />}
|
||||
Markera som betald
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@@ -19,7 +19,8 @@ import { useToast } from '@/components/ui/use-toast'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { getVatRules, getAvailableVatRates } from '@/lib/invoices/vat-rules'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog'
|
||||
import { Loader2, Plus, Trash2, ArrowLeft, Send, Eye, Landmark } from 'lucide-react'
|
||||
import { Loader2, Plus, Trash2, ArrowLeft, Send, Eye, Landmark, Lock } from 'lucide-react'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { ConfirmationDialog } from '@/components/ui/confirmation-dialog'
|
||||
import { InvoiceReviewContent } from '@/components/invoices/InvoiceReviewContent'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
@@ -57,6 +58,7 @@ const units = ['st', 'tim', 'dag', 'månad', 'km', 'kg']
|
||||
export default function NewInvoicePage() {
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
const { canWrite } = useCanWrite()
|
||||
const supabase = createClient()
|
||||
|
||||
const [customers, setCustomers] = useState<Customer[]>([])
|
||||
@@ -763,7 +765,14 @@ export default function NewInvoicePage() {
|
||||
</Card>
|
||||
|
||||
{/* Actions — desktop only */}
|
||||
<Button type="submit" className="w-full hidden lg:block" size="lg" disabled={isSubmitting}>
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full hidden lg:block"
|
||||
size="lg"
|
||||
disabled={isSubmitting || !canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{!canWrite && <Lock className="mr-2 h-4 w-4 inline" />}
|
||||
Granska & skapa
|
||||
</Button>
|
||||
</div>
|
||||
@@ -776,7 +785,12 @@ export default function NewInvoicePage() {
|
||||
<p className="text-xs text-muted-foreground">Totalt</p>
|
||||
<p className="text-lg font-bold tabular-nums">{formatCurrency(total, watchCurrency)}</p>
|
||||
</div>
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={isSubmitting || !canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{!canWrite && <Lock className="mr-2 h-4 w-4 inline" />}
|
||||
Granska & skapa
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -13,9 +13,10 @@ import { PageHeader } from '@/components/ui/page-header'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { Plus, Search, Receipt } from 'lucide-react'
|
||||
import { Plus, Search, Receipt, Lock } from 'lucide-react'
|
||||
import { EmptyInvoices } from '@/components/ui/empty-state'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import type { Invoice, InvoiceStatus } from '@/types'
|
||||
|
||||
const statusConfig: Record<InvoiceStatus, { label: string; variant: 'default' | 'secondary' | 'success' | 'warning' | 'destructive'; borderColor: string }> = {
|
||||
@@ -51,6 +52,7 @@ function getRelativeTimeLabel(dueDateStr: string, status: InvoiceStatus): { text
|
||||
|
||||
export default function InvoicesPage() {
|
||||
const { company } = useCompany()
|
||||
const { canWrite } = useCanWrite()
|
||||
const [invoices, setInvoices] = useState<Invoice[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
@@ -115,12 +117,22 @@ export default function InvoicesPage() {
|
||||
title="Fakturor"
|
||||
description="Skicka fakturor, följ betalningar och skapa kreditnotor"
|
||||
action={
|
||||
<Link href="/invoices/new">
|
||||
<Button>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
canWrite ? (
|
||||
<Link href="/invoices/new">
|
||||
<Button>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Ny faktura
|
||||
</Button>
|
||||
</Link>
|
||||
) : (
|
||||
<Button
|
||||
disabled
|
||||
title="Du har endast läsbehörighet i detta företag"
|
||||
>
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
Ny faktura
|
||||
</Button>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
/>
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { redirect } from 'next/navigation'
|
||||
import { cookies } from 'next/headers'
|
||||
import { headers } from 'next/headers'
|
||||
import DashboardNav from '@/components/dashboard/DashboardNav'
|
||||
import CompanyTabSync from '@/components/dashboard/CompanyTabSync'
|
||||
import { RecaptIdentify } from '@/components/RecaptIdentify'
|
||||
import { SentryIdentify } from '@/components/SentryIdentify'
|
||||
import { SandboxBanner } from '@/components/dashboard/SandboxBanner'
|
||||
@@ -10,6 +11,13 @@ import { CompanyProvider } from '@/contexts/CompanyContext'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import type { EntityType, CompanyRole, Team } from '@/types'
|
||||
|
||||
/**
|
||||
* Routes inside the dashboard group that must remain reachable when the
|
||||
* user has no active company. Keep in sync with the middleware's
|
||||
* no-company allowlist.
|
||||
*/
|
||||
const NO_COMPANY_ALLOWED_PATHS = ['/settings/account']
|
||||
|
||||
export default async function DashboardLayout({
|
||||
children,
|
||||
}: {
|
||||
@@ -23,9 +31,19 @@ export default async function DashboardLayout({
|
||||
redirect('/login')
|
||||
}
|
||||
|
||||
const cookieStore = await cookies()
|
||||
const companyId = cookieStore.get('gnubok-company-id')?.value
|
||||
?? await getActiveCompanyId(supabase, user.id)
|
||||
// Resolve active company from user_preferences (authoritative). The
|
||||
// `gnubok-company-id` cookie is intentionally no longer consulted here —
|
||||
// `getActiveCompanyId` reads from user_preferences, matching what RLS
|
||||
// sees via `current_active_company_id()`. Keeping both sides on the same
|
||||
// source avoids cross-tab / cookie divergence.
|
||||
const companyId = await getActiveCompanyId(supabase, user.id)
|
||||
|
||||
// Read the pathname forwarded by middleware so we can branch on it.
|
||||
const headerStore = await headers()
|
||||
const pathname = headerStore.get('x-pathname') ?? ''
|
||||
const isNoCompanyAllowed = NO_COMPANY_ALLOWED_PATHS.some((p) =>
|
||||
pathname.startsWith(p)
|
||||
)
|
||||
|
||||
// Fetch team membership + team info
|
||||
const { data: teamMembership } = await supabase
|
||||
@@ -47,9 +65,47 @@ export default async function DashboardLayout({
|
||||
|
||||
const isTeamMember = !!teamMembership
|
||||
|
||||
// No companies — redirect to onboarding
|
||||
// No companies — redirect to onboarding, except for allowed escape-hatch
|
||||
// routes (so the user can still reach /settings/account to delete their
|
||||
// account after archiving their last company).
|
||||
if (!companyId) {
|
||||
redirect('/onboarding')
|
||||
if (!isNoCompanyAllowed) {
|
||||
redirect('/onboarding')
|
||||
}
|
||||
|
||||
return (
|
||||
<CompanyProvider
|
||||
value={{
|
||||
company: null,
|
||||
role: null,
|
||||
companies: [],
|
||||
isTeamMember,
|
||||
team,
|
||||
}}
|
||||
>
|
||||
<CompanyTabSync />
|
||||
<div className="min-h-screen bg-background">
|
||||
<DashboardNav
|
||||
companyName="gnubok"
|
||||
entityType="enskild_firma"
|
||||
uncategorizedTransactionCount={0}
|
||||
pendingOperationsCount={0}
|
||||
isSandbox={false}
|
||||
extensionNavItems={getExtensionNavItems()}
|
||||
/>
|
||||
<main
|
||||
id="main-content"
|
||||
className="safe-area-main-padding 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>
|
||||
<SentryIdentify userId={user.id} email={user.email} />
|
||||
</div>
|
||||
</CompanyProvider>
|
||||
)
|
||||
}
|
||||
|
||||
// Fetch company + membership for context provider
|
||||
@@ -79,6 +135,7 @@ export default async function DashboardLayout({
|
||||
|
||||
return (
|
||||
<CompanyProvider value={companyContextValue}>
|
||||
<CompanyTabSync />
|
||||
<div className="min-h-screen bg-background">
|
||||
<DashboardNav
|
||||
companyName="gnubok"
|
||||
@@ -145,6 +202,7 @@ export default async function DashboardLayout({
|
||||
|
||||
return (
|
||||
<CompanyProvider value={companyContextValue}>
|
||||
<CompanyTabSync />
|
||||
<div className="min-h-screen bg-background">
|
||||
{/* Skip to content link for keyboard/screen reader users */}
|
||||
<a
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { CompanyDangerZone } from '@/components/settings/CompanyDangerZone'
|
||||
import { CompanyInfoForm } from '@/components/settings/CompanyInfoForm'
|
||||
import { CompanyMembersSection } from '@/components/settings/CompanyMembersSection'
|
||||
import { LogoUpload } from '@/components/settings/LogoUpload'
|
||||
@@ -49,6 +50,8 @@ export default function CompanySettingsPage() {
|
||||
<div className="border-t border-border/8 pt-8">
|
||||
<CompanyMembersSection />
|
||||
</div>
|
||||
|
||||
<CompanyDangerZone />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -9,7 +9,8 @@ import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { ArrowLeft, CheckCircle, CreditCard, FileText, Trash2 } from 'lucide-react'
|
||||
import { ArrowLeft, CheckCircle, CreditCard, FileText, Trash2, Lock } from 'lucide-react'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import Link from 'next/link'
|
||||
import { AccountNumber } from '@/components/ui/account-number'
|
||||
import { DestructiveConfirmDialog, useDestructiveConfirm } from '@/components/ui/destructive-confirm-dialog'
|
||||
@@ -40,6 +41,7 @@ const statusLabels: Record<string, string> = {
|
||||
}
|
||||
|
||||
export default function SupplierInvoiceDetailPage() {
|
||||
const { canWrite } = useCanWrite()
|
||||
const params = useParams()
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
@@ -189,24 +191,43 @@ export default function SupplierInvoiceDetailPage() {
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{invoice.status === 'registered' && (
|
||||
<>
|
||||
<Button onClick={handleApprove} disabled={isProcessing}>
|
||||
<CheckCircle className="mr-2 h-4 w-4" />
|
||||
<Button
|
||||
onClick={handleApprove}
|
||||
disabled={isProcessing || !canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{canWrite ? <CheckCircle className="mr-2 h-4 w-4" /> : <Lock className="mr-2 h-4 w-4" />}
|
||||
Godkänn
|
||||
</Button>
|
||||
<Button variant="destructive" size="icon" onClick={handleDelete} disabled={isProcessing}>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="icon"
|
||||
onClick={handleDelete}
|
||||
disabled={isProcessing || !canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{canWrite ? <Trash2 className="h-4 w-4" /> : <Lock className="h-4 w-4" />}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{['approved', 'overdue', 'partially_paid'].includes(invoice.status) && (
|
||||
<>
|
||||
<Button onClick={() => setIsPayDialogOpen(true)} disabled={isProcessing}>
|
||||
<CreditCard className="mr-2 h-4 w-4" />
|
||||
<Button
|
||||
onClick={() => setIsPayDialogOpen(true)}
|
||||
disabled={isProcessing || !canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{canWrite ? <CreditCard className="mr-2 h-4 w-4" /> : <Lock className="mr-2 h-4 w-4" />}
|
||||
Markera betald
|
||||
</Button>
|
||||
{invoice.status !== 'partially_paid' && (
|
||||
<Button variant="outline" onClick={handleCredit} disabled={isProcessing}>
|
||||
<FileText className="mr-2 h-4 w-4" />
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleCredit}
|
||||
disabled={isProcessing || !canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{canWrite ? <FileText className="mr-2 h-4 w-4" /> : <Lock className="mr-2 h-4 w-4" />}
|
||||
Kreditfaktura
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@@ -11,7 +11,8 @@ import { Textarea } from '@/components/ui/textarea'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { ArrowLeft, Plus, Trash2 } from 'lucide-react'
|
||||
import { ArrowLeft, Plus, Trash2, Lock } from 'lucide-react'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { ConfirmationDialog } from '@/components/ui/confirmation-dialog'
|
||||
import { SupplierInvoiceReviewContent } from '@/components/suppliers/SupplierInvoiceReviewContent'
|
||||
import AccountCombobox from '@/components/bookkeeping/AccountCombobox'
|
||||
@@ -62,6 +63,7 @@ function inferVatTreatment(items: LineItem[], reverseCharge: boolean): VatTreatm
|
||||
|
||||
export default function NewSupplierInvoicePage() {
|
||||
const router = useRouter()
|
||||
const { canWrite } = useCanWrite()
|
||||
const { toast } = useToast()
|
||||
const [suppliers, setSuppliers] = useState<Supplier[]>([])
|
||||
const [accounts, setAccounts] = useState<BASAccount[]>([])
|
||||
@@ -579,7 +581,12 @@ export default function NewSupplierInvoicePage() {
|
||||
<Button type="button" variant="outline" onClick={() => router.push('/supplier-invoices')}>
|
||||
Avbryt
|
||||
</Button>
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={isSubmitting || !canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{!canWrite && <Lock className="mr-2 h-4 w-4 inline" />}
|
||||
Granska & registrera
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -5,8 +5,9 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
||||
import { Plus, FileInput } from 'lucide-react'
|
||||
import { Plus, FileInput, Lock } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import type { SupplierInvoice } from '@/types'
|
||||
|
||||
function formatAmount(amount: number): string {
|
||||
@@ -34,6 +35,7 @@ const statusLabels: Record<string, string> = {
|
||||
}
|
||||
|
||||
export default function SupplierInvoicesPage() {
|
||||
const { canWrite } = useCanWrite()
|
||||
const [invoices, setInvoices] = useState<(SupplierInvoice & { supplier?: { id: string; name: string } })[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [activeTab, setActiveTab] = useState('all')
|
||||
@@ -78,12 +80,22 @@ export default function SupplierInvoicesPage() {
|
||||
Registrera och hantera inkommande fakturor
|
||||
</p>
|
||||
</div>
|
||||
<Link href="/supplier-invoices/new">
|
||||
<Button>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
{canWrite ? (
|
||||
<Link href="/supplier-invoices/new">
|
||||
<Button>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Registrera faktura
|
||||
</Button>
|
||||
</Link>
|
||||
) : (
|
||||
<Button
|
||||
disabled
|
||||
title="Du har endast läsbehörighet i detta företag"
|
||||
>
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
Registrera faktura
|
||||
</Button>
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Summary cards */}
|
||||
@@ -182,7 +194,7 @@ export default function SupplierInvoicesPage() {
|
||||
? 'Registrera din första leverantörsfaktura'
|
||||
: 'Inga fakturor i denna kategori'}
|
||||
</p>
|
||||
{activeTab === 'all' && (
|
||||
{activeTab === 'all' && canWrite && (
|
||||
<Link href="/supplier-invoices/new">
|
||||
<Button className="mt-4">
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
|
||||
@@ -7,7 +7,8 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { ArrowLeft, Edit, Trash2, FileText } from 'lucide-react'
|
||||
import { ArrowLeft, Edit, Trash2, FileText, Lock } from 'lucide-react'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import SupplierForm from '@/components/suppliers/SupplierForm'
|
||||
import Link from 'next/link'
|
||||
import { DestructiveConfirmDialog, useDestructiveConfirm } from '@/components/ui/destructive-confirm-dialog'
|
||||
@@ -24,6 +25,7 @@ function formatAmount(amount: number): string {
|
||||
}
|
||||
|
||||
export default function SupplierDetailPage() {
|
||||
const { canWrite } = useCanWrite()
|
||||
const params = useParams()
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
@@ -153,12 +155,23 @@ export default function SupplierDetailPage() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" onClick={() => setIsEditOpen(true)}>
|
||||
<Edit className="mr-2 h-4 w-4" />
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setIsEditOpen(true)}
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{canWrite ? <Edit className="mr-2 h-4 w-4" /> : <Lock className="mr-2 h-4 w-4" />}
|
||||
Redigera
|
||||
</Button>
|
||||
<Button variant="destructive" size="icon" onClick={handleDelete}>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="icon"
|
||||
onClick={handleDelete}
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{canWrite ? <Trash2 className="h-4 w-4" /> : <Lock className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -8,10 +8,11 @@ import { Badge } from '@/components/ui/badge'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Plus, Search, Building2, Globe } from 'lucide-react'
|
||||
import { Plus, Search, Building2, Globe, Lock } from 'lucide-react'
|
||||
import SupplierForm from '@/components/suppliers/SupplierForm'
|
||||
import Link from 'next/link'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import type { Supplier, SupplierType, CreateSupplierInput } from '@/types'
|
||||
|
||||
const supplierTypeLabels: Record<SupplierType, string> = {
|
||||
@@ -28,6 +29,7 @@ const supplierTypeIcons: Record<SupplierType, React.ElementType> = {
|
||||
|
||||
export default function SuppliersPage() {
|
||||
const { company } = useCompany()
|
||||
const { canWrite } = useCanWrite()
|
||||
const [suppliers, setSuppliers] = useState<Supplier[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
@@ -108,8 +110,15 @@ export default function SuppliersPage() {
|
||||
</div>
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
<Button
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{canWrite ? (
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
) : (
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Ny leverantör
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
@@ -169,8 +178,17 @@ export default function SuppliersPage() {
|
||||
<p className="text-muted-foreground text-center mt-1">
|
||||
Lägg till din första leverantör för att börja registrera inköpsfakturor
|
||||
</p>
|
||||
<Button className="mt-4" onClick={() => setIsDialogOpen(true)}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
<Button
|
||||
className="mt-4"
|
||||
onClick={() => setIsDialogOpen(true)}
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
>
|
||||
{canWrite ? (
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
) : (
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Ny leverantör
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import Link from 'next/link'
|
||||
import { Settings } from 'lucide-react'
|
||||
import { createClient, createServiceClient } from '@/lib/supabase/server'
|
||||
import { SentryIdentify } from '@/components/SentryIdentify'
|
||||
|
||||
export default async function OnboardingLayout({
|
||||
@@ -9,11 +11,48 @@ export default async function OnboardingLayout({
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
// Only show the settings escape hatch for users who have completed
|
||||
// onboarding at least once — i.e. they have a company_members row, even if
|
||||
// it points to an archived company. Absolute first-time users don't need
|
||||
// it and it clutters the welcome screen.
|
||||
//
|
||||
// Must use the service client: RLS on company_members goes through
|
||||
// user_company_ids(), which filters out archived companies, so an
|
||||
// authenticated query would return nothing for a user who archived their
|
||||
// last company and make the escape hatch disappear exactly when it's
|
||||
// needed most. Scoped to user_id = user.id, so no cross-user exposure.
|
||||
let hasCompletedOnboarding = false
|
||||
if (user) {
|
||||
const service = createServiceClient()
|
||||
const { data } = await service
|
||||
.from('company_members')
|
||||
.select('company_id')
|
||||
.eq('user_id', user.id)
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
hasCompletedOnboarding = !!data
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex items-center justify-center">
|
||||
<div className="w-full max-w-lg px-5">
|
||||
{children}
|
||||
</div>
|
||||
|
||||
{/* Escape hatch: a user who archived their last company can still
|
||||
reach account settings (and the delete-account flow) from here.
|
||||
Hidden for absolute first-time users (no memberships ever). */}
|
||||
{user && hasCompletedOnboarding && (
|
||||
<Link
|
||||
href="/settings/account"
|
||||
aria-label="Kontoinställningar"
|
||||
title="Kontoinställningar"
|
||||
className="fixed bottom-5 right-5 z-50 flex h-10 w-10 items-center justify-center rounded-full border border-border bg-background/80 text-muted-foreground shadow-sm backdrop-blur transition-colors hover:border-foreground/40 hover:text-foreground"
|
||||
>
|
||||
<Settings className="h-4 w-4" />
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{user && <SentryIdentify userId={user.id} email={user.email} />}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
|
||||
vi.mock('@/lib/init', () => ({
|
||||
ensureInitialized: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
createServiceClient: vi.fn(),
|
||||
}))
|
||||
|
||||
import { createClient, createServiceClient } from '@/lib/supabase/server'
|
||||
import { POST } from '../route'
|
||||
|
||||
const mockCreateClient = vi.mocked(createClient)
|
||||
const mockCreateServiceClient = vi.mocked(createServiceClient)
|
||||
|
||||
function mockAuth(
|
||||
user: { id: string; email: string | null } | null,
|
||||
rpcResult: { data?: unknown; error?: unknown } = { data: null, error: null }
|
||||
) {
|
||||
const signOut = vi.fn().mockResolvedValue({ error: null })
|
||||
const rpc = vi.fn().mockResolvedValue(rpcResult)
|
||||
|
||||
mockCreateClient.mockResolvedValue({
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user } }),
|
||||
signOut,
|
||||
},
|
||||
rpc,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
return { rpc, signOut }
|
||||
}
|
||||
|
||||
function mockServiceClient(blockers: { id: string; name: string }[] = []) {
|
||||
const updateUserById = vi.fn().mockResolvedValue({ data: {}, error: null })
|
||||
const adminSignOut = vi.fn().mockResolvedValue({ data: null, error: null })
|
||||
|
||||
const chain = {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
is: vi.fn().mockResolvedValue({
|
||||
data: blockers.map((b) => ({ companies: { id: b.id, name: b.name } })),
|
||||
error: null,
|
||||
}),
|
||||
}
|
||||
|
||||
mockCreateServiceClient.mockReturnValue({
|
||||
from: vi.fn().mockReturnValue(chain),
|
||||
auth: {
|
||||
admin: {
|
||||
updateUserById,
|
||||
signOut: adminSignOut,
|
||||
},
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
return { updateUserById, adminSignOut }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
})
|
||||
|
||||
describe('POST /api/account/delete', () => {
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
mockAuth(null)
|
||||
|
||||
const req = createMockRequest('/api/account/delete', {
|
||||
method: 'POST',
|
||||
body: { confirm_email: '[email protected]' },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 when confirm_email does not match', async () => {
|
||||
mockAuth({ id: 'user-1', email: '[email protected]' })
|
||||
|
||||
const req = createMockRequest('/api/account/delete', {
|
||||
method: 'POST',
|
||||
body: { confirm_email: '[email protected]' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse(await POST(req))
|
||||
expect(status).toBe(400)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
|
||||
it('returns 409 with blockers when RPC raises P0001', async () => {
|
||||
mockAuth(
|
||||
{ id: 'user-1', email: '[email protected]' },
|
||||
{ data: null, error: { code: 'P0001', message: 'blocked' } }
|
||||
)
|
||||
mockServiceClient([{ id: 'c1', name: 'Acme AB' }])
|
||||
|
||||
const req = createMockRequest('/api/account/delete', {
|
||||
method: 'POST',
|
||||
body: { confirm_email: '[email protected]' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
error: string
|
||||
blockers: { id: string; name: string }[]
|
||||
}>(await POST(req))
|
||||
|
||||
expect(status).toBe(409)
|
||||
expect(body.blockers).toEqual([{ id: 'c1', name: 'Acme AB' }])
|
||||
})
|
||||
|
||||
it('anonymizes, bans, signs out, and emits event on happy path', async () => {
|
||||
const { rpc } = mockAuth({ id: 'user-1', email: '[email protected]' })
|
||||
const { updateUserById, adminSignOut } = mockServiceClient()
|
||||
|
||||
const emitted: unknown[] = []
|
||||
eventBus.on('account.deleted', (payload) => {
|
||||
emitted.push(payload)
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/delete', {
|
||||
method: 'POST',
|
||||
body: { confirm_email: '[email protected]' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ success: boolean }>(
|
||||
await POST(req)
|
||||
)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.success).toBe(true)
|
||||
|
||||
expect(rpc).toHaveBeenCalledWith('anonymize_user_account', {
|
||||
target_user_id: 'user-1',
|
||||
})
|
||||
expect(updateUserById).toHaveBeenCalledWith(
|
||||
'user-1',
|
||||
expect.objectContaining({
|
||||
user_metadata: {},
|
||||
app_metadata: {},
|
||||
ban_duration: expect.any(String),
|
||||
})
|
||||
)
|
||||
// Email must NOT be scrubbed — retaining it is what blocks re-signup
|
||||
// with the same address. Recovery goes through support instead.
|
||||
const updatePayload = updateUserById.mock.calls[0][1]
|
||||
expect(updatePayload).not.toHaveProperty('email')
|
||||
expect(adminSignOut).toHaveBeenCalledWith('user-1', 'global')
|
||||
expect(emitted).toHaveLength(1)
|
||||
expect(emitted[0]).toMatchObject({ userId: 'user-1' })
|
||||
})
|
||||
})
|
||||
+106
-25
@@ -1,56 +1,137 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { createClient, createServiceClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
|
||||
const log = createLogger('api/account/delete')
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
const DeleteAccountSchema = z.object({
|
||||
confirm: z.literal('RADERA'),
|
||||
confirm_email: z.string().email(),
|
||||
})
|
||||
|
||||
/**
|
||||
* POST /api/account/delete
|
||||
*
|
||||
* Anonymizes the calling user's account. The auth.users row is retained
|
||||
* (banned for ~100 years) as a tombstone so FKs into BFL-retained
|
||||
* bookkeeping data (companies.created_by, audit_log.user_id, etc.) stay
|
||||
* valid. Memberships are removed, profile PII is stripped, and a global
|
||||
* signout forces all sessions to end.
|
||||
*
|
||||
* Precondition: the user must own zero non-archived companies. The RPC
|
||||
* enforces this at the DB level and raises SQLSTATE P0001 with a message
|
||||
* if the precondition fails — we return 409 in that case.
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
const supabase = await createClient()
|
||||
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
let body: unknown
|
||||
try {
|
||||
body = await request.json()
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
|
||||
}
|
||||
const result = await validateBody(request, DeleteAccountSchema)
|
||||
if (!result.success) return result.response
|
||||
const { confirm_email } = result.data
|
||||
|
||||
const parsed = DeleteAccountSchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
if (!user.email || confirm_email.trim().toLowerCase() !== user.email.toLowerCase()) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Skriv RADERA för att bekräfta kontoborttagning' },
|
||||
{ error: 'E-postadressen stämmer inte överens med ditt konto.' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
// RPC disables protective triggers, deletes from auth.users (CASCADE
|
||||
// cleans up all public tables), then re-enables triggers — all in one tx.
|
||||
const { error } = await supabase.rpc('delete_user_account', {
|
||||
target_user_id: user.id,
|
||||
})
|
||||
// Anonymize in the DB. Runs as SECURITY DEFINER and checks auth.uid()
|
||||
// internally, so we don't need service role here.
|
||||
const { error: rpcError } = await supabase.rpc('anonymize_user_account', {
|
||||
target_user_id: user.id,
|
||||
})
|
||||
|
||||
if (rpcError) {
|
||||
// P0001 = precondition violation from our RPC: user still owns active
|
||||
// companies. Re-fetch the blockers and return 409 so the UI can show
|
||||
// the list inline.
|
||||
if (rpcError.code === 'P0001') {
|
||||
const service = createServiceClient()
|
||||
const { data: blockers } = await service
|
||||
.from('company_members')
|
||||
.select('company_id, companies!inner(id, name, archived_at)')
|
||||
.eq('user_id', user.id)
|
||||
.eq('role', 'owner')
|
||||
.is('companies.archived_at', null)
|
||||
|
||||
const list = (blockers ?? []).map((b) => {
|
||||
const company = (b.companies as unknown) as { id: string; name: string }
|
||||
return { id: company.id, name: company.name }
|
||||
})
|
||||
|
||||
if (error) {
|
||||
console.error('Failed to delete user:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Kunde inte radera kontot. Försök igen.' },
|
||||
{ status: 500 }
|
||||
{
|
||||
error: 'Du måste radera eller överlåta dina företag innan du kan radera kontot.',
|
||||
blockers: list,
|
||||
},
|
||||
{ status: 409 }
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (error) {
|
||||
console.error('Account deletion error:', error)
|
||||
log.error('anonymize_user_account failed', { userId: user.id, error: rpcError.message })
|
||||
return NextResponse.json(
|
||||
{ error: 'Kunde inte radera kontot. Försök igen.' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
// Wipe PII in auth.users metadata and ban the tombstone row ~100 years.
|
||||
// DB functions can't reach supabase.auth.admin, so we do it here.
|
||||
//
|
||||
// Note: auth.users.email is intentionally NOT scrubbed. The original
|
||||
// address is retained as a legitimate-interest tombstone so that:
|
||||
// (1) re-signup with the same email is blocked by Supabase's unique
|
||||
// constraint — deletion must feel permanent, not trivially
|
||||
// reversible by re-registering
|
||||
// (2) support can verify identity when a former user asks to recover
|
||||
// BFL-retained räkenskapsinformation
|
||||
// This must be documented in the privacy policy under legitimate
|
||||
// interest (GDPR Art. 6(1)(f)). The email is never read by the app
|
||||
// after this point — login is impossible (row is banned) and the
|
||||
// profile is anonymized, so no UI ever surfaces it.
|
||||
//
|
||||
// user_metadata / app_metadata ARE wiped — they may contain display
|
||||
// name, avatar, or provider info that isn't needed for recovery.
|
||||
// The admin API replaces (not merges) these, so passing {} clears them.
|
||||
const service = createServiceClient()
|
||||
try {
|
||||
await service.auth.admin.updateUserById(user.id, {
|
||||
user_metadata: {},
|
||||
app_metadata: {},
|
||||
ban_duration: '876000h',
|
||||
})
|
||||
} catch (err) {
|
||||
log.error('Failed to wipe metadata and ban anonymized user', { userId: user.id, err })
|
||||
}
|
||||
|
||||
try {
|
||||
await service.auth.admin.signOut(user.id, 'global')
|
||||
} catch (err) {
|
||||
log.error('Failed to global sign out anonymized user', { userId: user.id, err })
|
||||
}
|
||||
|
||||
const deletedAt = new Date().toISOString()
|
||||
await eventBus.emit({
|
||||
type: 'account.deleted',
|
||||
payload: { userId: user.id, deletedAt },
|
||||
})
|
||||
|
||||
// Best-effort: clear the caller's session cookie too.
|
||||
await supabase.auth.signOut().catch(() => {})
|
||||
|
||||
// Request body is consumed; avoid unused-var lint.
|
||||
void request
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { NextResponse } from 'next/server'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { UpdateAccountSchema } from '@/lib/api/schemas'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
|
||||
export async function DELETE(
|
||||
request: Request,
|
||||
@@ -16,6 +17,9 @@ export async function DELETE(
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
// Fetch the account to check if it's a system account
|
||||
@@ -75,6 +79,9 @@ export async function PUT(
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const validation = await validateBody(request, UpdateAccountSchema)
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getBASReference } from '@/lib/bookkeeping/bas-reference'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
|
||||
/**
|
||||
* POST /api/bookkeeping/accounts/activate
|
||||
@@ -18,6 +19,9 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const body = await request.json()
|
||||
|
||||
@@ -4,6 +4,7 @@ import { NextResponse } from 'next/server'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CreateAccountSchema } from '@/lib/api/schemas'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
@@ -52,6 +53,9 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const validation = await validateBody(request, CreateAccountSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { closePeriod } from '@/lib/core/bookkeeping/period-service'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
|
||||
export async function POST(
|
||||
request: Request,
|
||||
@@ -15,6 +16,9 @@ export async function POST(
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
try {
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
executeCurrencyRevaluation,
|
||||
} from '@/lib/bookkeeping/currency-revaluation'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
|
||||
/**
|
||||
* GET: Preview currency revaluation for a fiscal period
|
||||
@@ -61,6 +62,9 @@ export async function POST(
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
try {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { lockPeriod } from '@/lib/core/bookkeeping/period-service'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
|
||||
export async function POST(
|
||||
request: Request,
|
||||
@@ -15,6 +16,9 @@ export async function POST(
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
try {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { NextResponse } from 'next/server'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { validatePeriodDuration } from '@/lib/bookkeeping/validate-period-duration'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
import { z } from 'zod'
|
||||
|
||||
const UpdateFiscalPeriodSchema = z.object({
|
||||
@@ -23,6 +24,9 @@ export async function PATCH(
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const validation = await validateBody(request, UpdateFiscalPeriodSchema)
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
executeYearEndClosing,
|
||||
} from '@/lib/core/bookkeeping/year-end-service'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
|
||||
/**
|
||||
* GET: Validate readiness and preview year-end closing
|
||||
@@ -54,6 +55,9 @@ export async function POST(
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
try {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { validatePeriodDuration } from '@/lib/bookkeeping/validate-period-durati
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CreateFiscalPeriodSchema } from '@/lib/api/schemas'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
|
||||
export async function GET() {
|
||||
const supabase = await createClient()
|
||||
@@ -36,6 +37,9 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const validation = await validateBody(request, CreateFiscalPeriodSchema)
|
||||
|
||||
@@ -17,6 +17,11 @@ vi.mock('@/lib/init', () => ({
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
const mockCorrectEntry = vi.fn()
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ensureInitialized } from '@/lib/init'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CorrectJournalEntrySchema } from '@/lib/api/schemas'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
@@ -20,6 +21,9 @@ export async function POST(
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const validation = await validateBody(request, CorrectJournalEntrySchema)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user