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:
Mattsson
2026-03-31 16:41:52 +02:00
committed by GitHub
co-authored by Claude Opus 4.6
parent 1756af6c5e
commit 0dd1f5ebc1
290 changed files with 7690 additions and 1339 deletions
+253
View File
@@ -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>
)
}
+4 -1
View File
@@ -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(() => {
+7 -6
View File
@@ -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"
+1 -1
View File
@@ -25,7 +25,7 @@ import { formatDateISO, DEADLINE_TYPE_LABELS, PRIORITY_LABELS } from '@/lib/cale
interface DeadlineFormProps {
open: boolean
onOpenChange: (open: boolean) => void
onSubmit: (data: Omit<Deadline, 'id' | 'user_id' | 'created_at' | 'updated_at'>) => Promise<void>
onSubmit: (data: Omit<Deadline, 'id' | 'user_id' | 'company_id' | 'created_at' | 'updated_at'>) => Promise<void>
onDelete?: (deadline: Partial<Deadline>) => void
initialData?: Partial<Deadline>
initialDate?: Date | null
+2 -2
View File
@@ -12,7 +12,7 @@ import { Plus } from 'lucide-react'
interface DeadlineListProps {
deadlines: Deadline[]
customers: { id: string; name: string }[]
onDeadlineCreate: (data: Omit<Deadline, 'id' | 'user_id' | 'created_at' | 'updated_at'>) => Promise<void>
onDeadlineCreate: (data: Omit<Deadline, 'id' | 'user_id' | 'company_id' | 'created_at' | 'updated_at'>) => Promise<void>
onDeadlineToggle: (deadline: Deadline) => Promise<void>
onDeadlineEdit: (deadline: Deadline) => Promise<void>
onDeadlineDelete: (deadline: Deadline) => Promise<void>
@@ -67,7 +67,7 @@ export function DeadlineList({
setTypeFilter('all')
}
const handleFormSubmit = async (data: Omit<Deadline, 'id' | 'user_id' | 'created_at' | 'updated_at'>) => {
const handleFormSubmit = async (data: Omit<Deadline, 'id' | 'user_id' | 'company_id' | 'created_at' | 'updated_at'>) => {
if (editingDeadline) {
await onDeadlineEdit({ ...editingDeadline, ...data })
} else {
@@ -59,7 +59,7 @@ export default function CalendarWorkspace({ userId }: WorkspaceComponentProps) {
}, [fetchData])
const handleDeadlineCreate = async (
data: Omit<Deadline, 'id' | 'user_id' | 'created_at' | 'updated_at'>
data: Omit<Deadline, 'id' | 'user_id' | 'company_id' | 'created_at' | 'updated_at'>
) => {
try {
const { error } = await supabase.from('deadlines').insert([data])
+28 -2
View File
@@ -104,6 +104,7 @@ export default function TicWorkspace({ userId }: WorkspaceComponentProps) {
const [profile, setProfile] = useState<TICCompanyProfile | null>(null)
const [isFetching, setIsFetching] = useState(false)
const [noOrgNumber, setNoOrgNumber] = useState(false)
const [fetchFailed, setFetchFailed] = useState(false)
const [initialLoad, setInitialLoad] = useState(true)
// Load cached profile from extension data
@@ -119,6 +120,7 @@ export default function TicWorkspace({ userId }: WorkspaceComponentProps) {
const fetchProfile = useCallback(async () => {
setIsFetching(true)
setNoOrgNumber(false)
setFetchFailed(false)
try {
// Get org_number from company settings
@@ -142,6 +144,7 @@ export default function TicWorkspace({ userId }: WorkspaceComponentProps) {
if (!res.ok) {
const { error } = await res.json()
toast({ title: error ?? 'Kunde inte hämta företagsprofil', variant: 'destructive' })
setFetchFailed(true)
return
}
@@ -150,6 +153,7 @@ export default function TicWorkspace({ userId }: WorkspaceComponentProps) {
await save('company_profile', data)
} catch {
toast({ title: 'Ett oväntat fel inträffade', variant: 'destructive' })
setFetchFailed(true)
} finally {
setIsFetching(false)
}
@@ -157,10 +161,10 @@ export default function TicWorkspace({ userId }: WorkspaceComponentProps) {
// Auto-fetch on first visit when no cached data
useEffect(() => {
if (!initialLoad && !profile && !noOrgNumber && !isFetching) {
if (!initialLoad && !profile && !noOrgNumber && !isFetching && !fetchFailed) {
fetchProfile()
}
}, [initialLoad, profile, noOrgNumber, isFetching, fetchProfile])
}, [initialLoad, profile, noOrgNumber, isFetching, fetchFailed, fetchProfile])
if (initialLoad || isDataLoading) {
return <ProfileSkeleton />
@@ -187,6 +191,28 @@ export default function TicWorkspace({ userId }: WorkspaceComponentProps) {
return <ProfileSkeleton />
}
if (fetchFailed && !profile) {
return (
<div className="flex flex-col items-center justify-center py-16 text-center">
<XCircle className="h-12 w-12 text-muted-foreground/40 mb-4" />
<h3 className="text-lg font-medium text-foreground">
Kunde inte hämta företagsprofil
</h3>
<p className="text-sm text-muted-foreground mt-1 max-w-md">
Kontrollera att organisationsnumret i inställningarna är korrekt och försök igen.
</p>
<div className="flex gap-3 mt-4">
<Button variant="outline" asChild>
<Link href="/settings">Inställningar</Link>
</Button>
<Button variant="outline" onClick={fetchProfile} disabled={isFetching}>
Försök igen
</Button>
</div>
</div>
)
}
if (!profile) return null
const isActive = profile.activityStatus !== 'ceased'
+65
View File
@@ -0,0 +1,65 @@
'use client'
import { Card } from '@/components/ui/card'
import { User, Users } from 'lucide-react'
import { cn } from '@/lib/utils'
interface Step0Props {
onChooseSelf: () => void
onChooseConsultant: () => void
}
const options = [
{
key: 'self',
label: 'Jag bokför själv',
description: 'Du driver ditt eget företag och vill hantera bokföringen.',
icon: User,
},
{
key: 'consultant',
label: 'Jag bokför åt någon annan',
description: 'Du är konsult eller byrå och bokför åt dina kunder.',
icon: Users,
},
] as const
export default function Step0RoleChoice({ onChooseSelf, onChooseConsultant }: Step0Props) {
return (
<div className="space-y-8">
<div className="grid gap-3">
{options.map((option) => {
const Icon = option.icon
const handler = option.key === 'self' ? onChooseSelf : onChooseConsultant
return (
<button
key={option.key}
type="button"
onClick={handler}
className="text-left w-full"
>
<Card
className={cn(
'relative p-5 transition-all cursor-pointer',
'hover:border-primary/50 hover:shadow-sm',
)}
>
<div className="flex items-start gap-4">
<div className="p-2.5 rounded-lg bg-muted/50">
<Icon className="h-5 w-5 text-muted-foreground" />
</div>
<div className="flex-1">
<span className="font-medium">{option.label}</span>
<p className="text-sm text-muted-foreground mt-0.5">
{option.description}
</p>
</div>
</div>
</Card>
</button>
)
})}
</div>
</div>
)
}
@@ -0,0 +1,308 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { useToast } from '@/components/ui/use-toast'
import { useCompany } from '@/contexts/CompanyContext'
import { Loader2, Plus, Trash2, Mail, Clock, Users } from 'lucide-react'
interface CompanyMemberItem {
id: string
user_id: string
email: string
role: string
source: 'direct' | 'team'
joined_at: string
is_current_user: boolean
}
interface CompanyInvitation {
id: string
email: string
role: string
status: string
expires_at: string
created_at: string
}
const ROLE_LABELS: Record<string, string> = {
owner: 'Ägare',
admin: 'Admin',
member: 'Medlem',
viewer: 'Läsbehörighet',
}
export function CompanyMembersSection() {
const { toast } = useToast()
const { company } = useCompany()
const [isLoading, setIsLoading] = useState(true)
const [members, setMembers] = useState<CompanyMemberItem[]>([])
const [invitations, setInvitations] = useState<CompanyInvitation[]>([])
const [inviteEmail, setInviteEmail] = useState('')
const [inviteRole, setInviteRole] = useState<string>('viewer')
const [isSending, setIsSending] = useState(false)
const [removingId, setRemovingId] = useState<string | null>(null)
const [revokingId, setRevokingId] = useState<string | null>(null)
const [canInvite, setCanInvite] = useState(false)
const fetchMembers = useCallback(async () => {
try {
const res = await fetch('/api/company/members')
const data = await res.json()
if (res.ok) {
setMembers(data.data.members)
setInvitations(data.data.invitations)
setCanInvite(data.data.canInvite)
}
} catch {
// Silently fail
} finally {
setIsLoading(false)
}
}, [])
useEffect(() => {
fetchMembers()
}, [fetchMembers])
const handleInvite = async (e: React.FormEvent) => {
e.preventDefault()
const email = inviteEmail.trim().toLowerCase()
if (!email) return
setIsSending(true)
try {
const res = await fetch('/api/company/members/invite', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, role: inviteRole }),
})
const data = await res.json()
if (!res.ok) {
toast({ title: 'Fel', description: data.error, variant: 'destructive' })
return
}
if (data.data.inviteUrl) {
console.log('[DEV] Company invite URL:', data.data.inviteUrl)
}
toast({
title: 'Inbjudan skickad',
description: data.data.inviteUrl
? 'Länk loggad i konsolen (F12)'
: `E-post skickad till ${email}.`,
})
setInviteEmail('')
setInviteRole('viewer')
fetchMembers()
} catch {
toast({ title: 'Fel', description: 'Kunde inte skicka inbjudan.', variant: 'destructive' })
} finally {
setIsSending(false)
}
}
const handleRemoveMember = async (memberId: string) => {
setRemovingId(memberId)
try {
const res = await fetch(`/api/company/members/${memberId}`, { method: 'DELETE' })
const data = await res.json()
if (!res.ok) {
toast({ title: 'Fel', description: data.error, variant: 'destructive' })
return
}
toast({ title: 'Medlem borttagen' })
fetchMembers()
} catch {
toast({ title: 'Fel', description: 'Kunde inte ta bort medlem.', variant: 'destructive' })
} finally {
setRemovingId(null)
}
}
const handleRevokeInvite = async (inviteId: string) => {
setRevokingId(inviteId)
try {
const res = await fetch(`/api/company/members/invite/${inviteId}`, { method: 'DELETE' })
const data = await res.json()
if (!res.ok) {
toast({ title: 'Fel', description: data.error, variant: 'destructive' })
return
}
toast({ title: 'Inbjudan återkallad' })
fetchMembers()
} catch {
toast({ title: 'Fel', description: 'Kunde inte återkalla inbjudan.', variant: 'destructive' })
} finally {
setRevokingId(null)
}
}
if (isLoading) {
return (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
)
}
return (
<div className="space-y-6">
{/* Invite form — disabled, coming soon */}
{canInvite && (
<Card className="relative overflow-hidden">
<div className="absolute inset-0 bg-background/60 backdrop-blur-[1px] z-10 flex items-center justify-center">
<Badge variant="secondary" className="text-xs font-medium">
Kommer snart
</Badge>
</div>
<CardHeader>
<CardTitle className="text-base">Bjud in till {company?.name}</CardTitle>
<CardDescription>
Personen får tillgång till enbart detta företag.
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex gap-3 pointer-events-none">
<div className="flex-1">
<Label htmlFor="company-invite-email" className="sr-only">E-postadress</Label>
<Input
id="company-invite-email"
type="email"
placeholder="namn@example.com"
disabled
/>
</div>
<Button disabled>
<Plus className="h-4 w-4 mr-1.5" />
Bjud in
</Button>
</div>
</CardContent>
</Card>
)}
{/* Members list */}
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Users className="h-4 w-4" />
Medlemmar
</CardTitle>
<CardDescription>
{members.length} {members.length === 1 ? 'medlem' : 'medlemmar'} i {company?.name}
</CardDescription>
</CardHeader>
<CardContent>
<div className="divide-y divide-border/40">
{members.map((member) => (
<div key={member.id} className="flex items-center justify-between py-3 first:pt-0 last:pb-0">
<div className="flex items-center gap-3 min-w-0">
<div className="h-8 w-8 rounded-full bg-muted/60 flex items-center justify-center flex-shrink-0">
<span className="text-xs font-medium text-muted-foreground">
{member.email.charAt(0).toUpperCase()}
</span>
</div>
<div className="min-w-0">
<p className="text-sm font-medium truncate">
{member.email}
{member.is_current_user && (
<span className="text-muted-foreground font-normal ml-1">(du)</span>
)}
</p>
<div className="flex items-center gap-1.5">
<span className="text-xs text-muted-foreground">
{ROLE_LABELS[member.role] || member.role}
</span>
{member.source === 'team' && (
<Badge variant="outline" className="text-[10px] px-1.5 py-0">
Team
</Badge>
)}
</div>
</div>
</div>
{canInvite && !member.is_current_user && member.role !== 'owner' && member.source !== 'team' && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-muted-foreground hover:text-destructive"
onClick={() => handleRemoveMember(member.id)}
disabled={removingId === member.id}
>
{removingId === member.id ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Trash2 className="h-3.5 w-3.5" />
)}
</Button>
)}
</div>
))}
</div>
</CardContent>
</Card>
{/* Pending invitations — hidden while invites are disabled */}
{false && invitations.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="text-base">Väntande inbjudningar</CardTitle>
</CardHeader>
<CardContent>
<div className="divide-y divide-border/40">
{invitations.map((inv) => (
<div key={inv.id} className="flex items-center justify-between py-3 first:pt-0 last:pb-0">
<div className="flex items-center gap-3 min-w-0">
<div className="h-8 w-8 rounded-full bg-muted/60 flex items-center justify-center flex-shrink-0">
<Mail className="h-3.5 w-3.5 text-muted-foreground" />
</div>
<div className="min-w-0">
<p className="text-sm font-medium truncate">{inv.email}</p>
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
<Clock className="h-3 w-3" />
<span>
Går ut {new Date(inv.expires_at).toLocaleDateString('sv-SE')}
</span>
</div>
</div>
</div>
<div className="flex items-center gap-2">
<Badge variant="secondary" className="text-xs">
{ROLE_LABELS[inv.role] || inv.role}
</Badge>
{canInvite && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-muted-foreground hover:text-destructive"
onClick={() => handleRevokeInvite(inv.id)}
disabled={revokingId === inv.id}
>
{revokingId === inv.id ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Trash2 className="h-3.5 w-3.5" />
)}
</Button>
)}
</div>
</div>
))}
</div>
</CardContent>
</Card>
)}
</div>
)
}
+95
View File
@@ -0,0 +1,95 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Loader2, Users } from 'lucide-react'
interface TeamMember {
id: string
user_id: string
email: string
role: 'owner' | 'admin' | 'member'
joined_at: string | null
is_current_user: boolean
}
const ROLE_LABELS: Record<string, string> = {
owner: 'Ägare',
admin: 'Admin',
member: 'Medlem',
}
export function TeamPanel() {
const [isLoading, setIsLoading] = useState(true)
const [members, setMembers] = useState<TeamMember[]>([])
const [teamName, setTeamName] = useState('')
const fetchMembers = useCallback(async () => {
try {
const res = await fetch('/api/team/members')
const data = await res.json()
if (res.ok) {
setMembers(data.data.members)
if (data.data.teamName) setTeamName(data.data.teamName)
}
} catch {
// Silently fail
} finally {
setIsLoading(false)
}
}, [])
useEffect(() => {
fetchMembers()
}, [fetchMembers])
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
)
}
return (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Users className="h-4 w-4" />
{teamName || 'Team'}
</CardTitle>
<CardDescription>
Ditt team har en ägare. Bjud in medarbetare via enskilda företag.
</CardDescription>
</CardHeader>
<CardContent>
<div className="divide-y divide-border/40">
{members.map((member) => (
<div key={member.id} className="flex items-center justify-between py-3 first:pt-0 last:pb-0">
<div className="flex items-center gap-3 min-w-0">
<div className="h-8 w-8 rounded-full bg-muted/60 flex items-center justify-center flex-shrink-0">
<span className="text-xs font-medium text-muted-foreground">
{member.email.charAt(0).toUpperCase()}
</span>
</div>
<div className="min-w-0">
<p className="text-sm font-medium truncate">
{member.email}
{member.is_current_user && (
<span className="text-muted-foreground font-normal ml-1">(du)</span>
)}
</p>
<p className="text-xs text-muted-foreground">
{ROLE_LABELS[member.role] || member.role}
</p>
</div>
</div>
</div>
))}
</div>
</CardContent>
</Card>
</div>
)
}