Files
accounted/components/agent/ChatEmptyState.tsx
T
Jakob Wennberg 4f0a7b1db0 feat(entitlements): per-company capability paywall — gate, trial seeding, UI upsells, Stripe checkout (#815)
* 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>
2026-06-29 15:56:19 +02:00

133 lines
5.8 KiB
TypeScript

'use client'
import { ArrowUpRight, Sparkles } from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { useAgentSheet } from './AgentSheetProvider'
import AgentAvatar from './AgentAvatar'
import { useCompanyOptional, useCapability } from '@/contexts/CompanyContext'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { createClient } from '@/lib/supabase/client'
// Tiny client component for /chat empty state. Reads the agent identity from
// the provider so it can show the user's chosen avatar + name above the
// "starta en konversation" CTA.
//
// The three suggestion chips below the headline give users a one-click way
// in. They navigate to /chat/new?intent=…&prompt=… which mounts AgentChat
// inline and swaps to /chat/[id] once the conversation is created — so the
// flow stays full-screen instead of opening a slide-in sheet.
const SUGGESTIONS: { label: string; prompt: string }[] = [
{
label: 'Vad är min största utgiftspost den här månaden?',
prompt: 'Vad är min största utgiftspost den här månaden? Visa de fem största kategorierna.',
},
{
label: 'Hur ser min momsrapport ut för senaste perioden?',
prompt: 'Hur ser min momsrapport ut för den senaste perioden? Vad blir moms att betala eller få tillbaka, och ser något ovanligt ut?',
},
{
label: 'När är min nästa skatte- eller momsdeadline?',
prompt: 'När är min nästa skatte- eller momsdeadline, och vad behöver jag göra inför den?',
},
]
export default function ChatEmptyState() {
const { identity } = useAgentSheet()
const companyCtx = useCompanyOptional()
const router = useRouter()
const isSandbox = companyCtx?.isSandbox ?? false
const hasAi = useCapability(CAPABILITY.ai)
const name = identity.displayName?.trim() || 'din assistent'
if (isSandbox) {
const handleCreateAccount = async () => {
const supabase = createClient()
// Sign-out is best-effort — navigate even if Supabase is unreachable
// so the button never looks dead.
try {
await supabase.auth.signOut()
} catch {
// Intentionally swallowed.
}
router.push('/register')
}
return (
<div className="hidden md:flex flex-1 flex-col items-center justify-center px-6 py-12 text-center">
<AgentAvatar avatarId={identity.avatarId} size="lg" alt={name} className="mb-5" />
<h1 className="font-display text-2xl tracking-tight mb-2">Fråga {name}</h1>
<div className="rounded-lg border border-border bg-secondary/40 px-5 py-4 max-w-md mb-6 text-left">
<div className="flex items-center gap-2 text-sm font-medium">
<Sparkles className="h-4 w-4" />
Avstängd i sandlådan
</div>
<p className="text-sm text-muted-foreground mt-2 leading-relaxed">
AI-assistenten använder en betald molntjänst och är därför
inaktiverad här. I den fullständiga produkten kan {name} kategorisera
transaktioner, granska leverantörsfakturor och svara frågor om
din bokföring.
</p>
</div>
<Button size="lg" onClick={handleCreateAccount}>
Skapa konto för att använda {name}
</Button>
</div>
)
}
if (!hasAi) {
return (
<div className="hidden md:flex flex-1 flex-col items-center justify-center px-6 py-12 text-center">
<AgentAvatar avatarId={identity.avatarId} size="lg" alt={name} className="mb-5" />
<h1 className="font-display text-2xl tracking-tight mb-2">Fråga {name}</h1>
<div className="rounded-lg border border-border bg-secondary/40 px-5 py-4 max-w-md mb-6 text-left">
<div className="flex items-center gap-2 text-sm font-medium">
<Sparkles className="h-4 w-4" />
Ingår i abonnemanget
</div>
<p className="text-sm text-muted-foreground mt-2 leading-relaxed">
AI-assistenten använder en betald molntjänst. Uppgradera för att låta
{' '}{name} kategorisera transaktioner, granska leverantörsfakturor
och svara frågor om din bokföring.
</p>
</div>
<Button size="lg" asChild>
<Link href="/settings/billing">Uppgradera för att använda {name}</Link>
</Button>
</div>
)
}
// Hidden on mobile — the sidebar IS the page when no conversation is open.
// On desktop, fills the right pane with a centered prompt.
return (
<div className="hidden md:flex flex-1 flex-col items-center justify-center px-6 py-12 text-center">
<AgentAvatar avatarId={identity.avatarId} size="lg" alt={name} className="mb-5" />
<h1 className="font-display text-2xl tracking-tight mb-2">Fråga {name}</h1>
<p className="text-muted-foreground max-w-md mb-6">
Välj en konversation till vänster, eller starta en ny om något har dykt upp.
</p>
<div className="flex flex-col gap-2 w-full max-w-md mb-6">
{SUGGESTIONS.map((s) => (
<Link
key={s.label}
href={`/chat/new?intent=general.help&prompt=${encodeURIComponent(s.prompt)}`}
className="group flex items-center gap-3 rounded-lg border border-border bg-card px-4 py-3 text-left text-sm transition-colors hover:border-foreground/30 hover:bg-secondary/30"
>
<span className="flex-1 text-muted-foreground group-hover:text-foreground transition-colors">
{s.label}
</span>
<ArrowUpRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground/60 group-hover:text-foreground transition-colors" />
</Link>
))}
</div>
<Button size="lg" variant="outline" asChild>
<Link href="/chat/new?intent=general.help">Eller skriv din egen fråga</Link>
</Button>
</div>
)
}