feat: multi-tenant company refactor (GNU-19) (#153)
* feat: multi-tenant company refactor (GNU-19) Introduce companies table, company_members, and user_preferences to support multiple companies per user. All data scoping changes from user_id to company_id across the entire codebase. Key changes: - Database migration: new tables, company_id on 40+ tables, backfill, RLS rewrite from user_id to company-member-based, updated RPCs - Types: Company, CompanyMember, CompanyRole, UserPreferences types; company_id added to all entity interfaces; companyId on all events - Engine: all 7 core functions take companyId; storno, period, year-end services updated; 16 report generators updated - Middleware: company context resolution (cookie → prefs → first company) - API routes: ~120 routes updated with requireCompanyId() - Frontend: CompanyProvider context, layout/dashboard/onboarding updated - Extensions: context factory, 9 extensions, all lib files updated - Tests: 1880 tests passing, all helpers updated with company_id defaults Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add database migrations for multi-tenant company and team system (GNU-19) Adds company_invitations, company creation RPC, team_members, account deletion RPC, and teams table refactor migrations. Updates base multi-tenant migration with cascading FKs and onboarding_step column. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add team types and update core infrastructure for multi-tenancy (GNU-19) Adds TeamRole, MemberSource, and Team types. Refactors Supabase service client to be stateless, updates middleware for team-aware routing, extends CompanyContext with team/role fields, and updates extension service types to accept companyId. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: thread company_id through business logic functions (GNU-19) Replaces user_id scoping with company_id across all lib modules: bookkeeping, documents, transactions, invoices, reconciliation, tax, deadlines, and import. Updates corresponding tests. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: thread company_id through API routes and extensions (GNU-19) Updates all existing API routes to extract and pass companyId. Updates enable-banking and arcim-migration extensions for company-scoped transaction ingestion and sync. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add company and team management API routes (GNU-19) Adds CRUD endpoints for company members, company invitations, team members, and team invitations. Includes invite token utilities, email templates, and company switch server action. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add team/company UI components, pages, and dashboard updates (GNU-19) Adds CompanySwitcher, ConsultantEmptyState, Step0RoleChoice, company members and team management panels. Updates dashboard layout for team-aware routing, onboarding for multi-step role choice, and auth callback for team invite acceptance. Ignores supabase/.branches/. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add null guards for company in import page (GNU-19) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: move appUrl declaration to outer scope in invite route (GNU-19) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add optional chaining for company.name in members section (GNU-19) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add optional chaining for second company.name in members section (GNU-19) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add null guards for company in extension components (GNU-19) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: pass companyId to executeSIEImport in arcim-migration extension (GNU-19) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: update tests to use companyId instead of userId and improve type handling --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
1756af6c5e
commit
0dd1f5ebc1
@@ -0,0 +1,253 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useRef, useEffect, useTransition, useCallback } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { switchCompany } from '@/lib/company/actions'
|
||||
import { Check, ChevronsUpDown, Plus, Loader2 } from 'lucide-react'
|
||||
|
||||
export default function CompanySwitcher() {
|
||||
const { company, companies, isTeamMember, team } = useCompany()
|
||||
const router = useRouter()
|
||||
const [open, setOpen] = useState(false)
|
||||
const [isPending, startTransition] = useTransition()
|
||||
const triggerRef = useRef<HTMLButtonElement>(null)
|
||||
const dropdownRef = useRef<HTMLDivElement>(null)
|
||||
const [dropdownPos, setDropdownPos] = useState({ top: 0, left: 0 })
|
||||
|
||||
const updatePosition = useCallback(() => {
|
||||
if (!triggerRef.current || !dropdownRef.current) return
|
||||
const triggerRect = triggerRef.current.getBoundingClientRect()
|
||||
const dropdownRect = dropdownRef.current.getBoundingClientRect()
|
||||
const margin = 8
|
||||
|
||||
let top = triggerRect.bottom + 4
|
||||
let left = triggerRect.left
|
||||
|
||||
// Clamp right edge to viewport
|
||||
if (left + dropdownRect.width > window.innerWidth - margin) {
|
||||
left = Math.max(margin, window.innerWidth - dropdownRect.width - margin)
|
||||
}
|
||||
|
||||
// If dropdown would go below viewport, show above trigger
|
||||
if (top + dropdownRect.height > window.innerHeight - margin) {
|
||||
top = Math.max(margin, triggerRect.top - dropdownRect.height - 4)
|
||||
}
|
||||
|
||||
setDropdownPos({ top, left })
|
||||
}, [])
|
||||
|
||||
// Update position when opening (run twice: once to render, once to measure)
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
// First frame: portal mounts, second frame: we can measure it
|
||||
const raf = requestAnimationFrame(() => updatePosition())
|
||||
return () => cancelAnimationFrame(raf)
|
||||
}, [open, updatePosition])
|
||||
|
||||
// Close on outside click
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
function handleClick(e: MouseEvent) {
|
||||
const target = e.target as Node
|
||||
if (
|
||||
(!triggerRef.current || !triggerRef.current.contains(target)) &&
|
||||
(!dropdownRef.current || !dropdownRef.current.contains(target))
|
||||
) {
|
||||
setOpen(false)
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', handleClick)
|
||||
return () => document.removeEventListener('mousedown', handleClick)
|
||||
}, [open])
|
||||
|
||||
// Close on Escape
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
function handleKey(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') setOpen(false)
|
||||
}
|
||||
document.addEventListener('keydown', handleKey)
|
||||
return () => document.removeEventListener('keydown', handleKey)
|
||||
}, [open])
|
||||
|
||||
const handleSwitch = (companyId: string) => {
|
||||
if (company && companyId === company.id) {
|
||||
setOpen(false)
|
||||
return
|
||||
}
|
||||
startTransition(async () => {
|
||||
const result = await switchCompany(companyId)
|
||||
if (!result.error) {
|
||||
setOpen(false)
|
||||
router.refresh()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const canOpen = companies.length > 0 || isTeamMember
|
||||
|
||||
// For team members: show team name as header, active company below
|
||||
// For self-service: just show company name
|
||||
if (team) {
|
||||
return (
|
||||
<div>
|
||||
<button
|
||||
ref={triggerRef}
|
||||
onClick={() => canOpen && setOpen(!open)}
|
||||
className={cn(
|
||||
'flex flex-col w-full text-left rounded-lg transition-colors',
|
||||
canOpen && 'hover:bg-muted/40 -mx-1 px-1 py-0.5',
|
||||
)}
|
||||
aria-expanded={open}
|
||||
aria-haspopup="listbox"
|
||||
>
|
||||
<div className="flex items-center gap-1.5 w-full">
|
||||
<p className="text-[13px] font-semibold text-foreground truncate tracking-[-0.01em] flex-1">
|
||||
{team.name}
|
||||
</p>
|
||||
{canOpen && (
|
||||
<ChevronsUpDown className="h-3 w-3 text-muted-foreground flex-shrink-0" />
|
||||
)}
|
||||
</div>
|
||||
{company && (
|
||||
<p className="text-[11px] text-muted-foreground truncate">
|
||||
{company.name}
|
||||
</p>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{open && createPortal(
|
||||
<div
|
||||
ref={dropdownRef}
|
||||
className="fixed min-w-56 w-max max-w-[calc(100vw-1rem)] bg-card border border-border/60 rounded-lg shadow-lg z-[60] py-1 animate-in fade-in slide-in-from-top-1 duration-150"
|
||||
style={{ top: dropdownPos.top, left: dropdownPos.left }}
|
||||
>
|
||||
{companies.length > 0 && (
|
||||
<>
|
||||
<div className="px-2 py-1.5">
|
||||
<p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-[0.08em] px-1.5">
|
||||
Företag
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="max-h-48 overflow-y-auto px-1">
|
||||
{companies.map(({ company: c, role }) => (
|
||||
<button
|
||||
key={c.id}
|
||||
onClick={() => handleSwitch(c.id)}
|
||||
disabled={isPending}
|
||||
className={cn(
|
||||
'flex items-center gap-2 w-full px-2.5 py-2 text-left text-[13px] leading-snug transition-colors rounded-md md:whitespace-nowrap',
|
||||
c.id === company?.id
|
||||
? 'text-foreground bg-muted/40'
|
||||
: 'text-muted-foreground hover:text-foreground hover:bg-muted/40',
|
||||
isPending && 'opacity-50',
|
||||
)}
|
||||
role="option"
|
||||
aria-selected={c.id === company?.id}
|
||||
>
|
||||
<span className="flex-1 min-w-0">{c.name}</span>
|
||||
{role !== 'owner' && (
|
||||
<span className="text-[10px] text-muted-foreground/60 flex-shrink-0">
|
||||
{role}
|
||||
</span>
|
||||
)}
|
||||
{c.id === company?.id && (
|
||||
<Check className="h-3.5 w-3.5 text-primary flex-shrink-0" />
|
||||
)}
|
||||
{isPending && c.id !== company?.id && (
|
||||
<Loader2 className="h-3 w-3 animate-spin text-muted-foreground flex-shrink-0" />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className={cn(companies.length > 0 && 'border-t border-border/40 mt-1 pt-1', 'px-1')}>
|
||||
<Link
|
||||
href="/companies/new"
|
||||
onClick={() => setOpen(false)}
|
||||
className="flex items-center gap-2 px-2.5 py-2 text-[13px] text-muted-foreground hover:text-foreground hover:bg-muted/40 rounded-md transition-colors md:whitespace-nowrap"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
Lägg till företag
|
||||
</Link>
|
||||
</div>
|
||||
</div>,
|
||||
document.body
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Self-service user (no team) — simple company display
|
||||
const hasMultiple = companies.length > 1
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button
|
||||
ref={triggerRef}
|
||||
onClick={() => hasMultiple && setOpen(!open)}
|
||||
className={cn(
|
||||
'flex items-center gap-1.5 w-full text-left rounded-lg transition-colors',
|
||||
hasMultiple && 'hover:bg-muted/40 -mx-1 px-1 py-0.5',
|
||||
)}
|
||||
aria-expanded={open}
|
||||
aria-haspopup="listbox"
|
||||
>
|
||||
<p className="text-[13px] font-semibold text-foreground truncate tracking-[-0.01em] flex-1">
|
||||
{company?.name || 'Min verksamhet'}
|
||||
</p>
|
||||
{hasMultiple && (
|
||||
<ChevronsUpDown className="h-3 w-3 text-muted-foreground flex-shrink-0" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{open && createPortal(
|
||||
<div
|
||||
ref={dropdownRef}
|
||||
className="fixed min-w-56 w-max max-w-[calc(100vw-1rem)] bg-card border border-border/60 rounded-lg shadow-lg z-[60] py-1 animate-in fade-in slide-in-from-top-1 duration-150"
|
||||
style={{ top: dropdownPos.top, left: dropdownPos.left }}
|
||||
>
|
||||
<div className="max-h-48 overflow-y-auto px-1">
|
||||
{companies.map(({ company: c, role }) => (
|
||||
<button
|
||||
key={c.id}
|
||||
onClick={() => handleSwitch(c.id)}
|
||||
disabled={isPending}
|
||||
className={cn(
|
||||
'flex items-center gap-2 w-full px-2.5 py-2 text-left text-[13px] leading-snug transition-colors rounded-md md:whitespace-nowrap',
|
||||
c.id === company?.id
|
||||
? 'text-foreground bg-muted/40'
|
||||
: 'text-muted-foreground hover:text-foreground hover:bg-muted/40',
|
||||
isPending && 'opacity-50',
|
||||
)}
|
||||
role="option"
|
||||
aria-selected={c.id === company?.id}
|
||||
>
|
||||
<span className="flex-1 min-w-0">{c.name}</span>
|
||||
{role !== 'owner' && (
|
||||
<span className="text-[10px] text-muted-foreground/60 flex-shrink-0">
|
||||
{role}
|
||||
</span>
|
||||
)}
|
||||
{c.id === company?.id && (
|
||||
<Check className="h-3.5 w-3.5 text-primary flex-shrink-0" />
|
||||
)}
|
||||
{isPending && c.id !== company?.id && (
|
||||
<Loader2 className="h-3 w-3 animate-spin text-muted-foreground flex-shrink-0" />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>,
|
||||
document.body
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
'use client'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { Building2, Plus } from 'lucide-react'
|
||||
|
||||
interface ConsultantEmptyStateProps {
|
||||
firstName?: string | null
|
||||
}
|
||||
|
||||
export default function ConsultantEmptyState({ firstName }: ConsultantEmptyStateProps) {
|
||||
const hour = new Date().getHours()
|
||||
const greeting = hour < 5 ? 'God natt' : hour < 10 ? 'Godmorgon' : hour < 14 ? 'Hej' : hour < 18 ? 'God eftermiddag' : 'God kväll'
|
||||
|
||||
return (
|
||||
<div className="stagger-enter">
|
||||
<header className="mb-16">
|
||||
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">
|
||||
{greeting}{firstName ? `, ${firstName}` : ''}
|
||||
</h1>
|
||||
</header>
|
||||
|
||||
<div className="flex flex-col items-center text-center max-w-md mx-auto">
|
||||
<div className="w-12 h-12 rounded-xl bg-muted/60 flex items-center justify-center mb-5">
|
||||
<Building2 className="h-5 w-5 text-muted-foreground" />
|
||||
</div>
|
||||
|
||||
<h2 className="font-display text-lg font-medium mb-2">
|
||||
Inga företag ännu
|
||||
</h2>
|
||||
<p className="text-sm text-muted-foreground mb-8">
|
||||
Lägg till ditt första kundföretag för att komma igång med bokföringen.
|
||||
</p>
|
||||
|
||||
<Link
|
||||
href="/companies/new"
|
||||
className="inline-flex items-center gap-2 px-5 py-2.5 rounded-lg bg-primary text-primary-foreground text-sm font-medium hover:bg-primary/90 transition-colors active:scale-[0.98]"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
Lägg till företag
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
} from 'lucide-react'
|
||||
import { getAllExtensions } from '@/lib/extensions/sectors'
|
||||
import { resolveIcon } from '@/lib/extensions/icon-resolver'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import type { QuickActionDefinition } from '@/lib/extensions/types'
|
||||
import type { CompanySettings, Deadline, ReceiptQueueSummary, OnboardingProgress } from '@/types'
|
||||
|
||||
@@ -50,11 +51,13 @@ interface DashboardContentProps {
|
||||
}
|
||||
|
||||
export default function DashboardContent({ firstName, settings, summary, onboardingProgress }: DashboardContentProps) {
|
||||
const { isTeamMember } = useCompany()
|
||||
const [showAllAlerts, setShowAllAlerts] = useState(false)
|
||||
const [showMore, setShowMore] = useState(false)
|
||||
|
||||
// Setup gate — blocks dashboard until user imports data or chooses fresh start
|
||||
const needsSetup = onboardingProgress && !onboardingProgress.hasBankConnected && !onboardingProgress.hasSIEImport
|
||||
// Consultants (team members) skip this — they go straight to the dashboard
|
||||
const needsSetup = !isTeamMember && onboardingProgress && !onboardingProgress.hasBankConnected && !onboardingProgress.hasSIEImport
|
||||
const [setupGateActive, setSetupGateActive] = useState(!!needsSetup)
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
} from 'lucide-react'
|
||||
import { resolveIcon } from '@/lib/extensions/icon-resolver'
|
||||
import { SupportLink } from '@/components/ui/support-link'
|
||||
import CompanySwitcher from '@/components/dashboard/CompanySwitcher'
|
||||
import type { EntityType } from '@/types'
|
||||
|
||||
interface ExtensionNavItem {
|
||||
@@ -158,15 +159,13 @@ export default function DashboardNav({ companyName, entityType, uncategorizedTra
|
||||
<aside className="hidden md:fixed md:inset-y-0 md:flex md:w-[232px] md:flex-col">
|
||||
<div className="flex min-h-0 flex-1 flex-col border-r border-border/30 bg-card/90">
|
||||
<div className="flex flex-1 flex-col overflow-y-auto pt-7 pb-4">
|
||||
{/* Company name */}
|
||||
{/* Company switcher */}
|
||||
<div className="px-5 mb-8">
|
||||
<p className="text-[13px] font-semibold text-foreground truncate tracking-[-0.01em]">
|
||||
{companyName}
|
||||
</p>
|
||||
<CompanySwitcher />
|
||||
</div>
|
||||
|
||||
{/* Navigation with group headers */}
|
||||
<nav className="flex-1 px-3" aria-label="Huvudnavigation">
|
||||
<nav className="px-3" aria-label="Huvudnavigation">
|
||||
{/* Huvudmeny group */}
|
||||
<div className="mb-6">
|
||||
<p className="px-3 mb-1.5 text-[10px] font-semibold text-muted-foreground uppercase tracking-[0.08em]">
|
||||
@@ -404,7 +403,9 @@ export default function DashboardNav({ companyName, entityType, uncategorizedTra
|
||||
|
||||
{/* Header */}
|
||||
<div className="px-4 pb-2 flex items-center justify-between">
|
||||
<p className="font-medium text-sm truncate">{companyName}</p>
|
||||
<div className="flex-1 min-w-0 mr-2">
|
||||
<CompanySwitcher />
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
|
||||
Reference in New Issue
Block a user