Files
accounted/lib/stripe/subscription-sync.ts
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

165 lines
6.0 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import type Stripe from 'stripe'
import { PAID_CAPABILITIES } from '@/lib/entitlements/keys'
import type { BillingPlan } from './client'
/**
* Stripe → DB reconciliation for subscriptions. The single source of truth for
* paid access is capability_grants(source='stripe'); this module writes those
* grants from subscription state and removes them on cancellation
* (freeze-and-retain — only the stripe grants are touched, never bank tokens or
* AI data).
*/
// Statuses that should keep paid access on. past_due stays on as a grace window
// (Stripe's dunning retries the charge); access is revoked only once the
// subscription is genuinely canceled/unpaid.
const ACCESS_STATUSES = new Set(['active', 'trialing', 'past_due'])
export function statusGrantsAccess(status: string | null | undefined): boolean {
return !!status && ACCESS_STATUSES.has(status)
}
export interface SubscriptionState {
companyId: string
stripeCustomerId: string | null
stripeSubscriptionId: string | null
status: string | null
plan: BillingPlan | null
currentPeriodEnd: string | null // ISO
}
function planFromSubscription(sub: Stripe.Subscription): BillingPlan | null {
const price = sub.items.data[0]?.price
const priceId = price?.id
if (priceId && priceId === process.env.STRIPE_PRICE_YEARLY) return 'yearly'
if (priceId && priceId === process.env.STRIPE_PRICE_MONTHLY) return 'monthly'
// Fallback by recurring interval if env price ids aren't wired up.
const interval = price?.recurring?.interval
if (interval === 'year') return 'yearly'
if (interval === 'month') return 'monthly'
return null
}
// current_period_end lives on the Subscription in older API versions and on the
// subscription item in newer ones — read defensively so SDK/API drift can't
// break the build or the expiry calc.
function periodEndIso(sub: Stripe.Subscription): string | null {
const s = sub as unknown as {
current_period_end?: number
items?: { data?: Array<{ current_period_end?: number }> }
}
const unix = s.current_period_end ?? s.items?.data?.[0]?.current_period_end ?? null
return unix ? new Date(unix * 1000).toISOString() : null
}
export function subscriptionToState(sub: Stripe.Subscription, companyId: string): SubscriptionState {
return {
companyId,
stripeCustomerId: typeof sub.customer === 'string' ? sub.customer : (sub.customer?.id ?? null),
stripeSubscriptionId: sub.id,
status: sub.status,
plan: planFromSubscription(sub),
currentPeriodEnd: periodEndIso(sub),
}
}
/**
* Reconcile a company's subscription state into the DB: upsert
* company_subscriptions, then either grant or remove the stripe capability
* grants. Idempotent — safe to run on duplicate/retried events.
*/
export async function applySubscriptionState(
supabase: SupabaseClient,
state: SubscriptionState,
): Promise<void> {
await supabase.from('company_subscriptions').upsert(
{
company_id: state.companyId,
stripe_customer_id: state.stripeCustomerId,
stripe_subscription_id: state.stripeSubscriptionId,
status: state.status,
plan: state.plan,
current_period_end: state.currentPeriodEnd,
updated_at: new Date().toISOString(),
},
{ onConflict: 'company_id' },
)
if (statusGrantsAccess(state.status)) {
// Grant a few days past the period end so a brief renewal-webhook delay
// never flips a paying customer to blocked.
const expiresAt = state.currentPeriodEnd
? new Date(new Date(state.currentPeriodEnd).getTime() + 3 * 24 * 3600 * 1000).toISOString()
: null
const rows = PAID_CAPABILITIES.map((key) => ({
company_id: state.companyId,
capability_key: key,
source: 'stripe',
expires_at: expiresAt,
}))
await supabase
.from('capability_grants')
.upsert(rows, { onConflict: 'company_id,team_id,capability_key,source' })
} else {
// Freeze-and-retain: drop only the stripe grants. Trial/comp grants (if any)
// are untouched; data and tokens are never deleted.
await supabase
.from('capability_grants')
.delete()
.eq('company_id', state.companyId)
.eq('source', 'stripe')
}
}
async function companyIdForCustomer(
supabase: SupabaseClient,
customerId: string,
): Promise<string | null> {
const { data } = await supabase
.from('company_subscriptions')
.select('company_id')
.eq('stripe_customer_id', customerId)
.maybeSingle()
return (data as { company_id: string } | null)?.company_id ?? null
}
/**
* Route a verified Stripe event to a state reconciliation. Only subscription
* lifecycle events matter; everything else is a no-op (already ack'd 200).
*/
export async function handleStripeEvent(
supabase: SupabaseClient,
stripe: Stripe,
event: Stripe.Event,
): Promise<void> {
switch (event.type) {
case 'checkout.session.completed': {
const session = event.data.object as Stripe.Checkout.Session
if (session.mode !== 'subscription' || !session.subscription) return
const sub = await stripe.subscriptions.retrieve(session.subscription as string)
const companyId =
session.metadata?.company_id ??
session.client_reference_id ??
sub.metadata?.company_id ??
null
if (companyId) await applySubscriptionState(supabase, subscriptionToState(sub, companyId))
return
}
case 'customer.subscription.created':
case 'customer.subscription.updated':
case 'customer.subscription.deleted': {
const sub = event.data.object as Stripe.Subscription
const companyId =
sub.metadata?.company_id ??
(await companyIdForCustomer(supabase, typeof sub.customer === 'string' ? sub.customer : sub.customer.id))
if (companyId) await applySubscriptionState(supabase, subscriptionToState(sub, companyId))
return
}
default:
// invoice.payment_failed etc. — Stripe also emits subscription.updated
// (-> past_due / canceled), which the cases above handle. No-op here.
return
}
}