* feat(entitlements): capability-grant gate substrate (paywall + modularity) Two-axis capability primitive behind the SaaS paywall and the per-tenant modularity/marketplace vision: - migration: capability_grants (entitlement axis, polymorphic company/firm scope), company_capability_config (enablement axis), metered_events (append-only), company_has_capability() RPC reusing the 20260619130100 tenant guard; SELECT-only RLS (writes service-role only, no self-grant). - lib/entitlements: hasCapability/requireCapability gate (mirrors guardSandbox, fail-closed, NEXT_PUBLIC_SELF_HOSTED bypass), capability key namespace, metering helper. - unit (11) + pg-real tests (RPC/RLS/tenant-guard incl. no-self-grant). Gate not yet wired into call sites (follow-up commit). Paid keys: ai, bank_sync, skatteverket, email_send. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(entitlements): enforce capability gate at paid external-service chokepoints Wire the gate into the paid surfaces (keys: ai, email_send, bank_sync, skatteverket): - AI routes (agent invoke/composer/onboarding stream): requireCapability(ai) - Invoice send (web + v1): requireCapability(email_send) - document-extraction event handler: skip Bedrock extract if ai not entitled - enable-banking + skatteverket crons: per-company hasCapability skip in loop - colocated send-route test mocks updated (requireCapability -> null) Free per founder decision: TIC org lookup, VIES VAT validation, FX auto-fetch, cloud backup, BankID login, all internal bookkeeping. DEPLOY ORDER: fail-closed by design — do NOT deploy before trial/comp grant seeding lands, or companies without grants lose these features. Seeding + Stripe checkout/webhook are the next steps. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(entitlements): seed trial + comp capability grants Makes the fail-closed gate safely deployable — nobody is locked out at cutover: - AFTER INSERT trigger on companies grants every NEW company a 30-day trial on the PAID keys (ai, bank_sync, skatteverket, email_send), on ALL creation paths (RPC/MCP/direct) — so a new signup can use onboarding AI immediately. - one-time backfill for EXISTING companies: created <=2026-06-07 -> trial ends 2026-07-07; created later -> created_at + 30 days. - permanent comp grants for Arcim/Mattsson (matched by name, no hardcoded UUIDs). - pg tests: clearGrants() for controlled resolver tests + trigger coverage. Trigger fn is SECURITY DEFINER so it writes grants regardless of caller RLS (table has no INSERT policy for authenticated — no self-grant). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(entitlements): client capability visibility + billing page Non-payers get a clean upsell instead of broken/empty features: - CompanyContext gains capabilities[] + useCapability(key); resolved once server-side in the dashboard layout via getCompanyCapabilities (batched, 2 queries), all three provider branches wired. - /settings/billing upgrade page — the destination upsells point to (Stripe Payment Link via NEXT_PUBLIC_STRIPE_PAYMENT_LINK; degrades to 'coming soon' until automated checkout lands). - ChatEmptyState: non-payer sees an Uppgradera CTA (mirrors the sandbox state). - SendInvoiceDialog: email send disabled + upsell note when email_send missing (extends the existing sandbox-disable pattern). Fast-follow: chat input/FAB + document-inbox empty state + bank/skatteverket/ AI-suggest buttons + a shared capability_blocked->toast backstop. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(entitlements): gate remaining paid UI surfaces with upsell (fast-follow) disable-with-upsell across the rest of the paid surfaces (keys: bank_sync, skatteverket, ai): - BankSyncNowButton: sync/reconnect disabled + note when !bank_sync (CSV/SIE stays free) - AGIPanel: AGI submit-to-Skatteverket disabled + note when !skatteverket - SkatteverketConnectPanel: BankID connect/reconnect disabled + upsell - ApprovalCard: AI re-propose (correction) gated; manual approve/reject stay free - InvoiceInboxWorkspace: upsell when extraction empty AND !ai (deterministic parse + manual entry unaffected) - AgentTrigger FAB: routes to /settings/billing when !ai (no dead chat) - settings nav: 'Abonnemang'/'Subscription' link to /settings/billing (sv/en) TaxPaymentPanel + TransactionInboxCard intentionally untouched — only local/ deterministic actions there, nothing paid+external to gate. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(entitlements): automated Stripe subscription checkout + webhook Self-serve revenue wired to the same capability-grant primitive: - migration: company_subscriptions (company<->Stripe link/status) + stripe_webhook_events (idempotency) - lib/stripe: getStripe singleton, plan->price mapping, subscription-sync (statusGrantsAccess / subscriptionToState / applySubscriptionState / handleStripeEvent). Active sub -> upsert source='stripe' grants for PAID keys (expiry = period_end + 3d grace); canceled/unpaid -> remove ONLY stripe grants (freeze-and-retain). - routes: POST /api/billing/checkout (hosted subscription Checkout, company_id metadata), POST /api/billing/portal (Customer Portal), POST /api/stripe/webhook (raw-body signature verify, event-id dedup; handles checkout.session.completed + customer.subscription.*) - billing page: real plan-toggle Checkout CTA / manage-subscription portal, gated on isStripeConfigured() - adds stripe@22; unit tests for sync logic Provisioning is webhook-driven (never trusts the success redirect). Needs env: STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET, STRIPE_PRICE_MONTHLY, STRIPE_PRICE_YEARLY. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(entitlements): validate UUIDs in capability filter + log webhook errors Addresses PR review (Superagent Security / PR Agent): - has-capability.ts: validate companyId/teamId as UUIDs before interpolating into the PostgREST .or() filter (fail-closed) — removes the latent injection vector flagged in the entitlement gate. Unit tests updated to use UUIDs. - stripe/webhook: log processing failures with event id + type before the generic 500, so a failing webhook is visible to operators. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(salary): always-free AGI XML download for manual filing; only direct API submit is paid Per founder decision on the swedish-compliance-review finding: AGI is a mandatory statutory filing, so producing/downloading the AGI XML must never be paywalled. Adds a free 'Ladda ner AGI-fil' button (generates + downloads the XML for manual upload to Skatteverket's e-service) on all tiers; the gated 'Skicka in underlag' stays the paid convenience (direct API submission — which also requires the paid BankID connection). Upsell reworded to point to the manual path. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(entitlements): harden comp-grant match after prod verification Verified Arcim/Mattsson in prod (pwxtzglxptnnvjrpixpg): the name match was case-sensitive (missed the active 'Arcim technology AB' lowercase variant) and would have granted 3 archived dupes. Now match by org_number (5595386219 / 5595719864) OR case-insensitive name, active companies only — hits exactly the 3 active comp companies, excludes archived dupes and the unrelated 'Amnäs Mattsson, Emil' enskild firma. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
321 lines
12 KiB
TypeScript
321 lines
12 KiB
TypeScript
import { createClient } from '@/lib/supabase/server'
|
|
import { redirect } from 'next/navigation'
|
|
import { headers } from 'next/headers'
|
|
import DashboardNav from '@/components/dashboard/DashboardNav'
|
|
import { MainContainer } from '@/components/dashboard/MainContainer'
|
|
import CompanyTabSync from '@/components/dashboard/CompanyTabSync'
|
|
import { RecaptIdentify } from '@/components/RecaptIdentify'
|
|
import { AgentSheetProvider } from '@/components/agent/AgentSheetProvider'
|
|
import AgentTrigger from '@/components/agent/AgentTrigger'
|
|
import CommandPalette from '@/components/common/CommandPalette'
|
|
import { SettingsHotkey } from '@/components/settings/SettingsHotkey'
|
|
import { SandboxBanner } from '@/components/dashboard/SandboxBanner'
|
|
import { getExtensionNavItems } from '@/lib/extensions/sectors'
|
|
import { CompanyProvider } from '@/contexts/CompanyContext'
|
|
import { getActiveCompanyId } from '@/lib/company/context'
|
|
import { getCompanyCapabilities } from '@/lib/entitlements/has-capability'
|
|
import { getBranding } from '@/lib/branding/service'
|
|
import { ensureSandboxAgentProfile } from '@/lib/sandbox/ensure-agent'
|
|
import { countPendingOperations, countUnbookedTransactions } from '@/lib/worklist'
|
|
import type { EntityType, CompanyRole, Team } from '@/types'
|
|
|
|
/**
|
|
* Routes inside the dashboard group that must remain reachable when the
|
|
* user has no active company. Keep in sync with the middleware's
|
|
* no-company allowlist.
|
|
*/
|
|
const NO_COMPANY_ALLOWED_PATHS = ['/settings/account']
|
|
|
|
export default async function DashboardLayout({
|
|
children,
|
|
settingsModal,
|
|
}: {
|
|
children: React.ReactNode
|
|
// `@settingsModal` parallel slot — renders the routed settings modal over the
|
|
// current page on in-app navigation to /settings/*; null otherwise.
|
|
settingsModal: React.ReactNode
|
|
}) {
|
|
const supabase = await createClient()
|
|
|
|
const { data: { user } } = await supabase.auth.getUser()
|
|
|
|
if (!user) {
|
|
redirect('/login')
|
|
}
|
|
|
|
// Resolve active company from user_preferences (authoritative). The
|
|
// `gnubok-company-id` cookie is intentionally no longer consulted here —
|
|
// `getActiveCompanyId` reads from user_preferences, matching what RLS
|
|
// sees via `current_active_company_id()`. Keeping both sides on the same
|
|
// source avoids cross-tab / cookie divergence.
|
|
const companyId = await getActiveCompanyId(supabase, user.id)
|
|
|
|
// Read the pathname forwarded by middleware so we can branch on it.
|
|
const headerStore = await headers()
|
|
const pathname = headerStore.get('x-pathname') ?? ''
|
|
const isNoCompanyAllowed = NO_COMPANY_ALLOWED_PATHS.some((p) =>
|
|
pathname.startsWith(p)
|
|
)
|
|
|
|
// Fetch team membership + team info
|
|
const { data: teamMembership } = await supabase
|
|
.from('team_members')
|
|
.select('team_id, role')
|
|
.eq('user_id', user.id)
|
|
.limit(1)
|
|
.maybeSingle()
|
|
|
|
let team: Team | null = null
|
|
if (teamMembership?.team_id) {
|
|
const { data: teamRow } = await supabase
|
|
.from('teams')
|
|
.select('*')
|
|
.eq('id', teamMembership.team_id)
|
|
.single()
|
|
team = teamRow
|
|
}
|
|
|
|
const isTeamMember = !!teamMembership
|
|
|
|
// No companies — redirect to onboarding, except for allowed escape-hatch
|
|
// routes (so the user can still reach /settings/account to delete their
|
|
// account after archiving their last company).
|
|
if (!companyId) {
|
|
if (!isNoCompanyAllowed) {
|
|
redirect('/onboarding')
|
|
}
|
|
|
|
return (
|
|
<CompanyProvider
|
|
value={{
|
|
company: null,
|
|
role: null,
|
|
companies: [],
|
|
isTeamMember,
|
|
team,
|
|
isSandbox: false,
|
|
capabilities: [],
|
|
}}
|
|
>
|
|
<AgentSheetProvider>
|
|
<CompanyTabSync />
|
|
<div className="min-h-screen bg-background">
|
|
<DashboardNav
|
|
companyName={getBranding().appName.toLowerCase()}
|
|
entityType="enskild_firma"
|
|
uncategorizedTransactionCount={0}
|
|
pendingOperationsCount={0}
|
|
isSandbox={false}
|
|
extensionNavItems={getExtensionNavItems()}
|
|
/>
|
|
<main
|
|
id="main-content"
|
|
className="safe-area-main-padding md:!pb-0 md:pl-64"
|
|
role="main"
|
|
>
|
|
<div className="max-w-5xl mx-auto px-5 py-8 md:px-8 md:py-10">
|
|
{children}
|
|
</div>
|
|
</main>
|
|
{settingsModal}
|
|
<SettingsHotkey />
|
|
</div>
|
|
</AgentSheetProvider>
|
|
</CompanyProvider>
|
|
)
|
|
}
|
|
|
|
// Fetch company + membership for context provider
|
|
const [
|
|
{ data: companyRow },
|
|
{ data: memberRow },
|
|
{ data: allMemberships },
|
|
] = await Promise.all([
|
|
supabase.from('companies').select('*').eq('id', companyId).single(),
|
|
supabase.from('company_members').select('role').eq('company_id', companyId).eq('user_id', user.id).single(),
|
|
supabase.from('company_members').select('company_id, role, companies:company_id(id, name, org_number, entity_type, accounting_framework, created_by, team_id, archived_at, created_at, updated_at)').eq('user_id', user.id),
|
|
])
|
|
|
|
if (!companyRow || !memberRow) {
|
|
// Stale cookie pointing to a deleted/inaccessible company.
|
|
// Render the empty-state dashboard so user can switch or create a company.
|
|
const companyContextValue = {
|
|
company: null,
|
|
role: null,
|
|
companies: (allMemberships || []).filter(m => m.companies).map((m) => ({
|
|
company: m.companies as unknown as import('@/types').Company,
|
|
role: m.role as CompanyRole,
|
|
})),
|
|
isTeamMember,
|
|
team,
|
|
isSandbox: false,
|
|
capabilities: [],
|
|
}
|
|
|
|
return (
|
|
<CompanyProvider value={companyContextValue}>
|
|
<AgentSheetProvider>
|
|
<CompanyTabSync />
|
|
<div className="min-h-screen bg-background">
|
|
<DashboardNav
|
|
companyName={getBranding().appName.toLowerCase()}
|
|
entityType="enskild_firma"
|
|
uncategorizedTransactionCount={0}
|
|
pendingOperationsCount={0}
|
|
isSandbox={false}
|
|
extensionNavItems={getExtensionNavItems()}
|
|
/>
|
|
<main id="main-content" className="safe-area-main-padding md:!pb-0 md:pl-64" role="main">
|
|
<div className="max-w-5xl mx-auto px-5 py-8 md:px-8 md:py-10">
|
|
{children}
|
|
</div>
|
|
</main>
|
|
{settingsModal}
|
|
<SettingsHotkey />
|
|
</div>
|
|
</AgentSheetProvider>
|
|
</CompanyProvider>
|
|
)
|
|
}
|
|
|
|
const [
|
|
{ data: settings },
|
|
uncategorizedCount,
|
|
pendingOpsCount,
|
|
{ data: agentProfileIdentity },
|
|
{ data: userProfile },
|
|
capabilities,
|
|
] = await Promise.all([
|
|
supabase
|
|
.from('company_settings')
|
|
.select('company_name, onboarding_complete, entity_type, pays_salaries, is_sandbox')
|
|
.eq('company_id', companyId)
|
|
.single(),
|
|
// Shared worklist predicates (lib/worklist) — the badge must show the
|
|
// same number as every other "att göra" surface. Notably this excludes
|
|
// is_ignored rows, which the old inline query here did not.
|
|
countUnbookedTransactions(supabase, companyId),
|
|
countPendingOperations(supabase, companyId),
|
|
// Agent identity — name + avatar — surfaced on the FAB and chat
|
|
// surfaces. Null when no agent_profile exists yet (banner CTA path).
|
|
supabase
|
|
.from('agent_profiles')
|
|
.select('display_name, avatar_id, verified_at')
|
|
.eq('company_id', companyId)
|
|
.maybeSingle(),
|
|
// The signed-in user's profile — shown in the bottom-left account
|
|
// popover (full_name + initial) so it's clear which user is logged
|
|
// in, distinct from the active company shown at the top.
|
|
supabase.from('profiles').select('full_name').eq('id', user.id).maybeSingle(),
|
|
getCompanyCapabilities(supabase, companyId),
|
|
])
|
|
|
|
// If onboarding incomplete, still render the dashboard — the page component
|
|
// will show the inline onboarding card instead of the normal dashboard content.
|
|
|
|
// Use company_name from settings as the display name (companies.name may be stale)
|
|
const displayName = settings?.company_name || companyRow.name
|
|
|
|
// Resolve entity type the same way the report engines and
|
|
// getCompanyEntityType do: company_settings is read-primary, companies is the
|
|
// canonical fallback, then default to enskild_firma. Mirroring it onto the
|
|
// active company keeps the settings rail (useSettingsNavItems, which reads
|
|
// context) and the sidebar in agreement on who is an employer. #782
|
|
const entityType =
|
|
(settings?.entity_type as EntityType) ||
|
|
(companyRow.entity_type as EntityType) ||
|
|
'enskild_firma'
|
|
const paysSalaries = settings?.pays_salaries ?? false
|
|
const companyWithName = {
|
|
...companyRow,
|
|
name: displayName,
|
|
entity_type: entityType,
|
|
pays_salaries: paysSalaries,
|
|
}
|
|
|
|
const isSandbox = settings?.is_sandbox === true
|
|
|
|
// Backfill a verified agent_profile for sandbox sessions that pre-date the
|
|
// seed change. Without this an old anonymous session shows the "Bygg din
|
|
// bokföringsassistent" CTA in three places (dashboard hero, NewUserChecklist
|
|
// step 4, /chat layout redirect) and the user can still kick off a build
|
|
// flow that the server now 403s. Best-effort; doesn't block the layout
|
|
// even if the insert fails.
|
|
let resolvedAgentIdentity = agentProfileIdentity
|
|
if (isSandbox && !agentProfileIdentity?.verified_at) {
|
|
await ensureSandboxAgentProfile(supabase, companyId)
|
|
const { data: refreshed } = await supabase
|
|
.from('agent_profiles')
|
|
.select('display_name, avatar_id, verified_at')
|
|
.eq('company_id', companyId)
|
|
.maybeSingle()
|
|
resolvedAgentIdentity = refreshed ?? agentProfileIdentity
|
|
}
|
|
|
|
const companyContextValue = {
|
|
company: companyWithName,
|
|
role: memberRow.role as CompanyRole,
|
|
companies: (allMemberships || []).map((m) => {
|
|
const c = m.companies as unknown as import('@/types').Company
|
|
// Override active company's name with settings name
|
|
if (c.id === companyId) {
|
|
return { company: { ...c, name: displayName }, role: m.role as CompanyRole }
|
|
}
|
|
return { company: c, role: m.role as CompanyRole }
|
|
}),
|
|
isTeamMember,
|
|
team,
|
|
isSandbox,
|
|
capabilities,
|
|
}
|
|
|
|
return (
|
|
<CompanyProvider value={companyContextValue}>
|
|
<AgentSheetProvider
|
|
identity={{
|
|
displayName: resolvedAgentIdentity?.display_name ?? null,
|
|
avatarId: resolvedAgentIdentity?.avatar_id ?? null,
|
|
isVerified: Boolean(resolvedAgentIdentity?.verified_at),
|
|
}}
|
|
>
|
|
<CompanyTabSync />
|
|
<div className="min-h-screen bg-background">
|
|
{/* Skip to content link for keyboard/screen reader users */}
|
|
<a
|
|
href="#main-content"
|
|
className="sr-only focus:not-sr-only focus:fixed focus:top-4 focus:left-4 focus:z-[100] focus:px-4 focus:py-2 focus:bg-primary focus:text-primary-foreground focus:rounded-lg focus:text-sm focus:font-medium"
|
|
>
|
|
Hoppa till innehåll
|
|
</a>
|
|
{isSandbox && <SandboxBanner />}
|
|
<DashboardNav
|
|
companyName={settings?.company_name || 'Min verksamhet'}
|
|
entityType={entityType}
|
|
paysSalaries={paysSalaries}
|
|
uncategorizedTransactionCount={uncategorizedCount}
|
|
pendingOperationsCount={pendingOpsCount}
|
|
isSandbox={isSandbox}
|
|
extensionNavItems={getExtensionNavItems()}
|
|
userName={userProfile?.full_name ?? null}
|
|
userEmail={user.email ?? null}
|
|
/>
|
|
<main id="main-content" className="safe-area-main-padding md:!pb-0 md:pl-64" role="main">
|
|
<MainContainer companyId={companyId}>{children}</MainContainer>
|
|
</main>
|
|
<AgentTrigger />
|
|
<CommandPalette />
|
|
<SettingsHotkey />
|
|
{settingsModal}
|
|
</div>
|
|
{!isSandbox && (
|
|
<RecaptIdentify
|
|
userId={user.id}
|
|
email={user.email}
|
|
displayName={settings?.company_name || undefined}
|
|
/>
|
|
)}
|
|
</AgentSheetProvider>
|
|
</CompanyProvider>
|
|
)
|
|
}
|