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
@@ -12,7 +12,7 @@ const PAGE_SIZE = 1000
|
||||
* supabase
|
||||
* .from('chart_of_accounts')
|
||||
* .select('account_number, account_name')
|
||||
* .eq('user_id', userId)
|
||||
* .eq('company_id', companyId)
|
||||
* .range(from, to)
|
||||
* )
|
||||
* ```
|
||||
|
||||
+108
-7
@@ -55,14 +55,20 @@ export async function updateSession(request: NextRequest) {
|
||||
pathname.startsWith('/register') ||
|
||||
pathname.startsWith('/auth') ||
|
||||
pathname.startsWith('/reset-password') ||
|
||||
pathname.startsWith('/sandbox')
|
||||
pathname.startsWith('/sandbox') ||
|
||||
pathname.startsWith('/invite')
|
||||
) {
|
||||
// If user is logged in and trying to access auth pages, redirect to dashboard or onboarding
|
||||
if (user) {
|
||||
const companyId = await resolveCompanyForMiddleware(supabase, user.id, request)
|
||||
if (!companyId) {
|
||||
return NextResponse.redirect(new URL('/onboarding', request.url))
|
||||
}
|
||||
|
||||
const { data: settings } = await supabase
|
||||
.from('company_settings')
|
||||
.select('onboarding_complete')
|
||||
.eq('user_id', user.id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (!settings?.onboarding_complete) {
|
||||
@@ -107,15 +113,58 @@ export async function updateSession(request: NextRequest) {
|
||||
}
|
||||
}
|
||||
|
||||
// Company context resolution
|
||||
const companyId = await resolveCompanyForMiddleware(supabase, user.id, request)
|
||||
|
||||
// No companies at all
|
||||
if (!companyId) {
|
||||
// Check if user is in a team (consultant without companies yet).
|
||||
// Team members should reach the dashboard (which shows an empty state)
|
||||
// rather than being forced through company onboarding.
|
||||
const { data: teamMember } = await supabase
|
||||
.from('team_members')
|
||||
.select('id')
|
||||
.eq('user_id', user.id)
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
|
||||
if (teamMember) {
|
||||
// Consultant with a team but no companies — allow dashboard access
|
||||
if (pathname.startsWith('/onboarding')) {
|
||||
return NextResponse.redirect(new URL('/', request.url))
|
||||
}
|
||||
return supabaseResponse
|
||||
}
|
||||
|
||||
// No team, no companies → redirect to onboarding
|
||||
if (pathname.startsWith('/onboarding')) {
|
||||
return supabaseResponse
|
||||
}
|
||||
return NextResponse.redirect(new URL('/onboarding', request.url))
|
||||
}
|
||||
|
||||
// Set company cookie on the response so downstream requests have it
|
||||
supabaseResponse.cookies.set('gnubok-company-id', companyId, {
|
||||
path: '/',
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
maxAge: 60 * 60 * 24 * 365,
|
||||
})
|
||||
|
||||
// Select-company page — allow access (for switching companies)
|
||||
if (pathname.startsWith('/select-company') || pathname.startsWith('/companies/new')) {
|
||||
return supabaseResponse
|
||||
}
|
||||
|
||||
// Onboarding route - only accessible if not complete
|
||||
if (pathname.startsWith('/onboarding')) {
|
||||
const { data: settings } = await supabase
|
||||
.from('company_settings')
|
||||
.select('onboarding_complete')
|
||||
.eq('user_id', user.id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
// If onboarding is complete, redirect to dashboard
|
||||
if (settings?.onboarding_complete) {
|
||||
return NextResponse.redirect(new URL('/', request.url))
|
||||
}
|
||||
@@ -123,17 +172,69 @@ export async function updateSession(request: NextRequest) {
|
||||
return supabaseResponse
|
||||
}
|
||||
|
||||
// Dashboard routes - require completed onboarding
|
||||
// Dashboard routes - require completed onboarding for active company
|
||||
const { data: settings } = await supabase
|
||||
.from('company_settings')
|
||||
.select('onboarding_complete')
|
||||
.eq('user_id', user.id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
// If no settings or onboarding not complete, redirect to onboarding
|
||||
if (!settings?.onboarding_complete) {
|
||||
return NextResponse.redirect(new URL('/onboarding', request.url))
|
||||
}
|
||||
|
||||
return supabaseResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the active company for the authenticated user.
|
||||
* Uses cookie → user_preferences → first membership as fallback.
|
||||
* Cannot use lib/company/context.ts because middleware runs on Edge.
|
||||
*/
|
||||
async function resolveCompanyForMiddleware(
|
||||
supabase: ReturnType<typeof createServerClient>,
|
||||
userId: string,
|
||||
request: NextRequest
|
||||
): Promise<string | null> {
|
||||
// 1. Try cookie
|
||||
const cookieCompanyId = request.cookies.get('gnubok-company-id')?.value
|
||||
if (cookieCompanyId) {
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('company_id')
|
||||
.eq('company_id', cookieCompanyId)
|
||||
.eq('user_id', userId)
|
||||
.single()
|
||||
|
||||
if (membership) return membership.company_id
|
||||
}
|
||||
|
||||
// 2. Try user_preferences
|
||||
const { data: prefs } = await supabase
|
||||
.from('user_preferences')
|
||||
.select('active_company_id')
|
||||
.eq('user_id', userId)
|
||||
.single()
|
||||
|
||||
if (prefs?.active_company_id) {
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('company_id')
|
||||
.eq('company_id', prefs.active_company_id)
|
||||
.eq('user_id', userId)
|
||||
.single()
|
||||
|
||||
if (membership) return membership.company_id
|
||||
}
|
||||
|
||||
// 3. Fallback: first company membership
|
||||
const { data: firstCompany } = await supabase
|
||||
.from('company_members')
|
||||
.select('company_id')
|
||||
.eq('user_id', userId)
|
||||
.order('created_at', { ascending: true })
|
||||
.limit(1)
|
||||
.single()
|
||||
|
||||
return firstCompany?.company_id ?? null
|
||||
}
|
||||
|
||||
+8
-19
@@ -36,27 +36,16 @@ export async function createClient() {
|
||||
)
|
||||
}
|
||||
|
||||
export async function createServiceClient() {
|
||||
const cookieStore = await cookies()
|
||||
|
||||
export function createServiceClient() {
|
||||
// Stateless service-role client — no cookies.
|
||||
// Passing user session cookies causes @supabase/ssr to send the
|
||||
// user's JWT as the Authorization header, which overrides the
|
||||
// service role key and re-enables RLS. A cookie-less client
|
||||
// ensures the service role key is used for authorization,
|
||||
// properly bypassing RLS on every query.
|
||||
return createServerClient(
|
||||
safeUrl,
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY!,
|
||||
{
|
||||
cookies: {
|
||||
getAll() {
|
||||
return cookieStore.getAll()
|
||||
},
|
||||
setAll(cookiesToSet) {
|
||||
try {
|
||||
cookiesToSet.forEach(({ name, value, options }) =>
|
||||
cookieStore.set(name, value, options)
|
||||
)
|
||||
} catch {
|
||||
// Ignore in Server Components
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
{ cookies: { getAll: () => [], setAll: () => {} } }
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user