feat(billing): paywall conversion pass (deferred first charge, trial touchpoint, sell-view upgrade) (#991)

* feat(billing): paywall conversion pass: deferred first charge, trial touchpoint, sell-view upgrade

- checkout passes subscription_data.trial_end (trial grant expiry, 49h floor)
  so a mid-trial upgrade costs 0 kr today instead of double-billing days the
  company already has free; billing/status counts 'trialing' as paying
- trial countdown pill in the sidebar (CompanyContext.trialEndsAt via
  getCompanyEntitlements); hidden for sandbox, dev bypass, and once any
  non-trial grant is active
- sell view: what-happens-when timeline, free-vs-paid comparison table,
  risk-reversal copy + chevron CTA, post-checkout confirmation state

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(billing): review triage: fail-closed trial lookup, hourly countdown refresh, BFL retention note

- checkout returns 500 (no Stripe session) when the trial-grant lookup errors,
  instead of silently charging immediately after the UI promised 0 kr idag
- sidebar trial countdown recomputes hourly so a long-lived tab stays honest
- sell-view retention copy states BFL 7-year retention explicitly
  (compliance-bot suggestion)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: retrigger CI (pull_request event delivery stuck)

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-07-11 22:29:48 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 9d91ee0168
commit 3a2c57a167
14 changed files with 532 additions and 52 deletions
@@ -4,8 +4,9 @@ import {
hasCapability,
requireCapability,
capabilityBlockedResponse,
getCompanyEntitlements,
} from '../has-capability'
import { CAPABILITY } from '../keys'
import { CAPABILITY, PAID_CAPABILITIES } from '../keys'
/**
* Per-table mock: each table resolves to its own configured result, so a
@@ -157,6 +158,64 @@ describe('requireCapability', () => {
})
})
describe('getCompanyEntitlements', () => {
const companyId = '11111111-1111-4111-8111-111111111111'
it('reports the trial expiry while the trial is the only source of access', async () => {
const expiry = iso(10 * 24 * 3600 * 1000)
const supabase = makeSupabase({
companies: { data: { team_id: null } },
capability_grants: {
data: [
{ capability_key: CAPABILITY.ai, expires_at: expiry, source: 'trial' },
{ capability_key: CAPABILITY.bank_sync, expires_at: expiry, source: 'trial' },
],
},
company_capability_config: { data: [] },
})
const result = await getCompanyEntitlements(supabase, companyId)
expect(result.trialEndsAt).toBe(expiry)
expect(result.capabilities).toContain(CAPABILITY.ai)
expect(result.capabilities).toContain(CAPABILITY.bank_sync)
})
it('hides the trial once a non-trial grant is active (converted customer)', async () => {
const supabase = makeSupabase({
companies: { data: { team_id: null } },
capability_grants: {
data: [
{ capability_key: CAPABILITY.ai, expires_at: iso(10 * 24 * 3600 * 1000), source: 'trial' },
{ capability_key: CAPABILITY.ai, expires_at: null, source: 'stripe' },
],
},
company_capability_config: { data: [] },
})
const result = await getCompanyEntitlements(supabase, companyId)
expect(result.trialEndsAt).toBeNull()
expect(result.capabilities).toContain(CAPABILITY.ai)
})
it('returns no trial and no capabilities after the trial lapsed', async () => {
const supabase = makeSupabase({
companies: { data: { team_id: null } },
capability_grants: {
data: [{ capability_key: CAPABILITY.ai, expires_at: iso(-60_000), source: 'trial' }],
},
})
const result = await getCompanyEntitlements(supabase, companyId)
expect(result.trialEndsAt).toBeNull()
expect(result.capabilities).toEqual([])
})
it('bypass (self-hosted) holds everything with no trial countdown', async () => {
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'true')
const supabase = makeSupabase({})
const result = await getCompanyEntitlements(supabase, companyId)
expect(result.trialEndsAt).toBeNull()
expect(result.capabilities).toEqual([...PAID_CAPABILITIES])
})
})
describe('capabilityBlockedResponse', () => {
it('returns a bilingual 403 carrying the capability key', async () => {
const res = capabilityBlockedResponse(CAPABILITY.bank_sync)
+45 -12
View File
@@ -167,17 +167,29 @@ export async function requireCapability(
return capabilityBlockedResponse(key)
}
export interface CompanyEntitlements {
capabilities: CapabilityKey[]
/**
* Expiry of the company's trial, present only while the trial is the SOLE
* source of paid access: null once any non-trial grant (stripe/comp/team)
* is active, and null after the trial has lapsed. Drives the trial
* countdown touchpoint in the dashboard chrome.
*/
trialEndsAt: string | null
}
/**
* Resolve which PAID capabilities a company currently holds (entitled AND
* enabled), in two queries. Used to seed the client CompanyContext so the UI
* can hide/disable/upsell gated features. Self-hosted holds everything.
* enabled) plus its trial state, in two queries. Used to seed the client
* CompanyContext so the UI can hide/disable/upsell gated features.
* Self-hosted holds everything.
*/
export async function getCompanyCapabilities(
export async function getCompanyEntitlements(
supabase: SupabaseClient,
companyId: string,
): Promise<CapabilityKey[]> {
if (isPaywallBypassed()) return [...PAID_CAPABILITIES]
if (!isUuid(companyId)) return [] // fail-closed: never interpolate a non-UUID
): Promise<CompanyEntitlements> {
if (isPaywallBypassed()) return { capabilities: [...PAID_CAPABILITIES], trialEndsAt: null }
if (!isUuid(companyId)) return { capabilities: [], trialEndsAt: null } // fail-closed: never interpolate a non-UUID
// The disabled-config subtraction only needs companyId, so it runs in
// parallel with the team lookup — this function sits on the dashboard
@@ -198,24 +210,45 @@ export async function getCompanyCapabilities(
: `company_id.eq.${companyId}`
const { data: grants } = await supabase
.from('capability_grants')
.select('capability_key, expires_at')
.select('capability_key, expires_at, source')
.in('capability_key', PAID_CAPABILITIES as unknown as string[])
.or(scopeFilter)
const now = Date.now()
const entitled = new Set<string>()
let trialEndsAt: string | null = null
let hasActiveNonTrialGrant = false
for (const g of grants ?? []) {
const row = g as { capability_key: string; expires_at: string | null }
if (row.expires_at === null || new Date(row.expires_at).getTime() > now) {
entitled.add(row.capability_key)
const row = g as { capability_key: string; expires_at: string | null; source: string | null }
const active = row.expires_at === null || new Date(row.expires_at).getTime() > now
if (!active) continue
entitled.add(row.capability_key)
if (row.source === 'trial') {
// Latest trial expiry (ISO strings from the same column compare lexically).
if (row.expires_at && (!trialEndsAt || row.expires_at > trialEndsAt)) {
trialEndsAt = row.expires_at
}
} else {
hasActiveNonTrialGrant = true
}
}
if (entitled.size === 0) return []
// Paying/comped companies are not "on trial" even if the seeded trial rows
// haven't expired yet: the countdown would nag someone who already converted.
if (hasActiveNonTrialGrant) trialEndsAt = null
if (entitled.size === 0) return { capabilities: [], trialEndsAt: null }
// Subtract any explicitly-disabled (enablement axis).
for (const c of configs ?? []) {
entitled.delete((c as { capability_key: string }).capability_key)
}
return PAID_CAPABILITIES.filter((k) => entitled.has(k))
return { capabilities: PAID_CAPABILITIES.filter((k) => entitled.has(k)), trialEndsAt }
}
/** Capability list only; see getCompanyEntitlements for the full shape. */
export async function getCompanyCapabilities(
supabase: SupabaseClient,
companyId: string,
): Promise<CapabilityKey[]> {
return (await getCompanyEntitlements(supabase, companyId)).capabilities
}