0dd1f5ebc1
* 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>
160 lines
5.2 KiB
TypeScript
160 lines
5.2 KiB
TypeScript
import { createClient } from '@/lib/supabase/server'
|
|
import { NextResponse } from 'next/server'
|
|
import { ensureInitialized } from '@/lib/init'
|
|
import { extensionRegistry } from '@/lib/extensions/registry'
|
|
import { createExtensionContext } from '@/lib/extensions/context-factory'
|
|
import { hasAiConsent, isAiExtension } from '@/lib/extensions/ai-consent'
|
|
import { requireCompanyId } from '@/lib/company/context'
|
|
import type { ApiRouteDefinition } from '@/lib/extensions/types'
|
|
|
|
ensureInitialized()
|
|
|
|
// Heavy extension routes (SIE import, migration) need up to 5 minutes
|
|
export const maxDuration = 300
|
|
|
|
/**
|
|
* Match a request path against a route pattern.
|
|
* Supports :param wildcards (e.g., /:id/confirm).
|
|
* Returns extracted params on match, null on mismatch.
|
|
*/
|
|
function matchPath(
|
|
pattern: string,
|
|
requestPath: string
|
|
): Record<string, string> | null {
|
|
const patternParts = pattern.split('/').filter(Boolean)
|
|
const requestParts = requestPath.split('/').filter(Boolean)
|
|
|
|
if (patternParts.length !== requestParts.length) return null
|
|
|
|
const params: Record<string, string> = {}
|
|
|
|
for (let i = 0; i < patternParts.length; i++) {
|
|
if (patternParts[i].startsWith(':')) {
|
|
params[patternParts[i].slice(1)] = requestParts[i]
|
|
} else if (patternParts[i] !== requestParts[i]) {
|
|
return null
|
|
}
|
|
}
|
|
|
|
return params
|
|
}
|
|
|
|
/**
|
|
* Catch-all route for extension-declared API routes.
|
|
*
|
|
* URL scheme: /api/extensions/ext/{extensionId}/{...routePath}
|
|
* Example: /api/extensions/ext/receipt-ocr/abc123/confirm → POST /:id/confirm
|
|
*
|
|
* - Looks up the extension in the registry
|
|
* - Checks the extension toggle (disabled → 403)
|
|
* - Matches method + path pattern to registered apiRoutes
|
|
* - Extracts path params and appends them as URL search params
|
|
* - Builds an ExtensionContext and passes it to the handler
|
|
*/
|
|
async function handleRequest(
|
|
request: Request,
|
|
{ params }: { params: Promise<{ path: string[] }> }
|
|
): Promise<Response> {
|
|
const segments = await params
|
|
|
|
if (!segments.path || segments.path.length < 1) {
|
|
return NextResponse.json({ error: 'Invalid extension route' }, { status: 400 })
|
|
}
|
|
|
|
const [extensionId, ...rest] = segments.path
|
|
const routePath = '/' + rest.join('/')
|
|
const method = request.method as 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
|
|
|
|
// Look up extension
|
|
const extension = extensionRegistry.get(extensionId)
|
|
if (!extension || !extension.apiRoutes || extension.apiRoutes.length === 0) {
|
|
return NextResponse.json({ error: 'Extension not found' }, { status: 404 })
|
|
}
|
|
|
|
// Match route BEFORE auth so we can check skipAuth (e.g. OAuth callbacks)
|
|
let matchedRoute: ApiRouteDefinition | null = null
|
|
let extractedParams: Record<string, string> = {}
|
|
|
|
for (const route of extension.apiRoutes) {
|
|
if (route.method !== method) continue
|
|
|
|
const routeParams = matchPath(route.path, routePath)
|
|
if (routeParams !== null) {
|
|
matchedRoute = route
|
|
extractedParams = routeParams
|
|
break
|
|
}
|
|
}
|
|
|
|
if (!matchedRoute) {
|
|
return NextResponse.json({ error: 'Route not found' }, { status: 404 })
|
|
}
|
|
|
|
// For skipAuth routes (e.g. OAuth callbacks from external providers),
|
|
// skip user auth, toggle check, and AI consent — dispatch immediately
|
|
if (matchedRoute.skipAuth) {
|
|
let handlerRequest = request
|
|
if (Object.keys(extractedParams).length > 0) {
|
|
const url = new URL(request.url)
|
|
for (const [key, value] of Object.entries(extractedParams)) {
|
|
url.searchParams.set(`_${key}`, value)
|
|
}
|
|
handlerRequest = new Request(url.toString(), {
|
|
method: request.method,
|
|
headers: request.headers,
|
|
body: request.body,
|
|
// @ts-expect-error -- duplex needed for streaming body
|
|
duplex: 'half',
|
|
})
|
|
}
|
|
return matchedRoute.handler(handlerRequest)
|
|
}
|
|
|
|
// Auth check
|
|
const supabase = await createClient()
|
|
const { data: { user } } = await supabase.auth.getUser()
|
|
|
|
if (!user) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
}
|
|
|
|
const companyId = await requireCompanyId(supabase, user.id)
|
|
|
|
// AI consent check
|
|
if (isAiExtension(extensionId)) {
|
|
const consented = await hasAiConsent(supabase, companyId, extensionId)
|
|
if (!consented) {
|
|
return NextResponse.json(
|
|
{ error: 'AI consent required', code: 'AI_CONSENT_REQUIRED' },
|
|
{ status: 403 }
|
|
)
|
|
}
|
|
}
|
|
|
|
// If path params were extracted, create a new Request with them as search params
|
|
let handlerRequest = request
|
|
if (Object.keys(extractedParams).length > 0) {
|
|
const url = new URL(request.url)
|
|
for (const [key, value] of Object.entries(extractedParams)) {
|
|
url.searchParams.set(`_${key}`, value)
|
|
}
|
|
handlerRequest = new Request(url.toString(), {
|
|
method: request.method,
|
|
headers: request.headers,
|
|
body: request.body,
|
|
// @ts-expect-error -- duplex needed for streaming body
|
|
duplex: 'half',
|
|
})
|
|
}
|
|
|
|
// Build context and dispatch
|
|
const ctx = createExtensionContext(supabase, user.id, companyId, extensionId)
|
|
return matchedRoute.handler(handlerRequest, ctx)
|
|
}
|
|
|
|
export const GET = handleRequest
|
|
export const POST = handleRequest
|
|
export const PUT = handleRequest
|
|
export const DELETE = handleRequest
|
|
export const PATCH = handleRequest
|