* 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>
254 lines
9.3 KiB
TypeScript
254 lines
9.3 KiB
TypeScript
'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>
|
|
)
|
|
}
|