docs(production): standardiserad produktionsberedskap och gap-analys

Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
2026-11-10 09:15:21 +01:00
parent 0fda8cae48
commit 2bee8eb778
6135 changed files with 4 additions and 1718997 deletions
-315
View File
@@ -1,315 +0,0 @@
/**
* Tests for POST /api/billing/checkout.
*
* Exercises the route through the real withRouteContext wrapper, mocking
* auth/company, the Stripe client, and the service-role Supabase client.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase: serviceSupabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => serviceSupabase,
}))
// Keep sandboxBlockedResponse real; stub only the DB-backed guardSandbox so the
// route's company_settings read doesn't need a live supabase mock.
const guardSandboxMock = vi.fn()
vi.mock('@/lib/sandbox/guard', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/sandbox/guard')>()
return { ...actual, guardSandbox: (...args: unknown[]) => guardSandboxMock(...args) }
})
const customersCreate = vi.fn()
const sessionsCreate = vi.fn()
vi.mock('@/lib/stripe/client', () => ({
getStripe: () => ({
customers: { create: customersCreate },
checkout: { sessions: { create: sessionsCreate } },
}),
priceIdForPlan: vi.fn().mockReturnValue('price_123'),
}))
import { POST } from '../checkout/route'
const routeParams = { params: Promise.resolve({}) }
// The trusted-origin resolver reads the brands table; pin one registered
// brand host so the return-URL tests exercise the real resolver logic.
const resolveBrandResultByHostMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/branding/resolve', () => ({
resolveBrandResultByHost: (...args: unknown[]) => resolveBrandResultByHostMock(...args),
}))
const originalAppUrl = process.env.NEXT_PUBLIC_APP_URL
beforeEach(() => {
vi.clearAllMocks()
reset()
process.env.NEXT_PUBLIC_APP_URL = 'https://app.accounted.test'
resolveBrandResultByHostMock.mockImplementation(async (host: string) => ({
brand: host === 'portal.brand.test' ? { domain: host } : null,
lookupFailed: false,
}))
guardSandboxMock.mockResolvedValue(null)
requireAuthMock.mockResolvedValue({
user: { id: 'user-1', email: '[email protected]', is_anonymous: false },
supabase: {},
error: null,
})
})
afterEach(() => {
if (originalAppUrl === undefined) delete process.env.NEXT_PUBLIC_APP_URL
else process.env.NEXT_PUBLIC_APP_URL = originalAppUrl
})
describe('POST /api/billing/checkout', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const req = createMockRequest('/api/billing/checkout', { method: 'POST', body: {} })
const res = await POST(req, routeParams)
expect(res.status).toBe(401)
})
it('blocks an anonymous (demo) user with 403 and never touches Stripe', async () => {
requireAuthMock.mockResolvedValue({
user: { id: 'anon-1', email: null, is_anonymous: true },
supabase: {},
error: null,
})
const req = createMockRequest('/api/billing/checkout', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ sandbox_blocked?: boolean }>(
await POST(req, routeParams),
)
expect(status).toBe(403)
expect(body.sandbox_blocked).toBe(true)
expect(customersCreate).not.toHaveBeenCalled()
expect(sessionsCreate).not.toHaveBeenCalled()
// The cheap identity check short-circuits before the DB-backed guard.
expect(guardSandboxMock).not.toHaveBeenCalled()
})
it('blocks a sandbox company with 403 and never touches Stripe', async () => {
const { sandboxBlockedResponse } = await import('@/lib/sandbox/guard')
guardSandboxMock.mockResolvedValue(sandboxBlockedResponse())
const req = createMockRequest('/api/billing/checkout', { method: 'POST', body: { plan: 'monthly' } })
const { status, body } = await parseJsonResponse<{ sandbox_blocked?: boolean }>(
await POST(req, routeParams),
)
expect(status).toBe(403)
expect(body.sandbox_blocked).toBe(true)
expect(guardSandboxMock).toHaveBeenCalledWith(expect.anything(), 'company-1')
expect(customersCreate).not.toHaveBeenCalled()
expect(sessionsCreate).not.toHaveBeenCalled()
})
it('rejects an unknown plan with 400', async () => {
const req = createMockRequest('/api/billing/checkout', {
method: 'POST',
body: { plan: 'weekly' },
})
const { status } = await parseJsonResponse(await POST(req, routeParams))
expect(status).toBe(400)
expect(sessionsCreate).not.toHaveBeenCalled()
})
it('reuses an existing Stripe customer and returns the checkout URL', async () => {
enqueue({ data: { stripe_customer_id: 'cus_existing' } }) // subscription row
enqueue({ data: null }) // no trial grant
sessionsCreate.mockResolvedValue({ url: 'https://stripe.test/session' })
const req = createMockRequest('/api/billing/checkout', {
method: 'POST',
body: { plan: 'yearly' },
})
const { status, body } = await parseJsonResponse<{ url: string }>(await POST(req, routeParams))
expect(status).toBe(200)
expect(body.url).toBe('https://stripe.test/session')
expect(customersCreate).not.toHaveBeenCalled()
expect(sessionsCreate).toHaveBeenCalledWith(
expect.objectContaining({
customer: 'cus_existing',
client_reference_id: 'company-1',
})
)
// No trial grant → billing starts immediately, no Stripe trial.
expect(sessionsCreate.mock.calls[0][0].subscription_data.trial_end).toBeUndefined()
})
it('enables automatic VAT, tax-id collection and address capture on the session', async () => {
enqueue({ data: { stripe_customer_id: 'cus_existing' } }) // subscription row
enqueue({ data: null }) // no trial grant
sessionsCreate.mockResolvedValue({ url: 'https://stripe.test/session' })
const req = createMockRequest('/api/billing/checkout', { method: 'POST', body: { plan: 'monthly' } })
await POST(req, routeParams)
expect(sessionsCreate).toHaveBeenCalledWith(
expect.objectContaining({
automatic_tax: { enabled: true },
tax_id_collection: { enabled: true },
billing_address_collection: 'required',
customer_update: { name: 'auto', address: 'auto' },
}),
)
})
it('creates a Stripe customer when none exists yet', async () => {
enqueue({ data: null }) // no existing subscription row
enqueue({ data: null }) // no trial grant
enqueue({ data: null }) // upsert result
customersCreate.mockResolvedValue({ id: 'cus_new' })
sessionsCreate.mockResolvedValue({ url: 'https://stripe.test/session' })
const req = createMockRequest('/api/billing/checkout', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ url: string }>(await POST(req, routeParams))
expect(status).toBe(200)
expect(body.url).toBe('https://stripe.test/session')
expect(customersCreate).toHaveBeenCalledWith(
expect.objectContaining({ metadata: { company_id: 'company-1' } })
)
expect(sessionsCreate).toHaveBeenCalledWith(
expect.objectContaining({ customer: 'cus_new' })
)
})
it('defers the first charge to the trial end when the trial has >48h left', async () => {
const trialEnd = new Date(Date.now() + 10 * 24 * 3600 * 1000).toISOString()
enqueue({ data: { stripe_customer_id: 'cus_existing' } }) // subscription row
enqueue({ data: { expires_at: trialEnd } }) // active trial grant
sessionsCreate.mockResolvedValue({ url: 'https://stripe.test/session' })
const req = createMockRequest('/api/billing/checkout', { method: 'POST', body: {} })
const { status } = await parseJsonResponse(await POST(req, routeParams))
expect(status).toBe(200)
expect(sessionsCreate).toHaveBeenCalledWith(
expect.objectContaining({
subscription_data: expect.objectContaining({
metadata: { company_id: 'company-1' },
trial_end: Math.floor(new Date(trialEnd).getTime() / 1000),
}),
})
)
})
it('bills immediately when the trial is inside the 48h Stripe floor', async () => {
const trialEnd = new Date(Date.now() + 24 * 3600 * 1000).toISOString()
enqueue({ data: { stripe_customer_id: 'cus_existing' } }) // subscription row
enqueue({ data: { expires_at: trialEnd } }) // trial ends tomorrow
sessionsCreate.mockResolvedValue({ url: 'https://stripe.test/session' })
const req = createMockRequest('/api/billing/checkout', { method: 'POST', body: {} })
const { status } = await parseJsonResponse(await POST(req, routeParams))
expect(status).toBe(200)
expect(sessionsCreate.mock.calls[0][0].subscription_data.trial_end).toBeUndefined()
})
it('bills immediately when the trial has already expired', async () => {
const trialEnd = new Date(Date.now() - 24 * 3600 * 1000).toISOString()
enqueue({ data: { stripe_customer_id: 'cus_existing' } }) // subscription row
enqueue({ data: { expires_at: trialEnd } }) // lapsed trial
sessionsCreate.mockResolvedValue({ url: 'https://stripe.test/session' })
const req = createMockRequest('/api/billing/checkout', { method: 'POST', body: {} })
const { status } = await parseJsonResponse(await POST(req, routeParams))
expect(status).toBe(200)
expect(sessionsCreate.mock.calls[0][0].subscription_data.trial_end).toBeUndefined()
})
it('fails closed (500, no Stripe session) when the trial lookup errors', async () => {
enqueue({ data: { stripe_customer_id: 'cus_existing' } }) // subscription row
enqueue({ data: null, error: { message: 'boom' } }) // trial lookup fails
const req = createMockRequest('/api/billing/checkout', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await POST(req, routeParams),
)
expect(status).toBe(500)
expect(body.error.code).toBe('TRIAL_LOOKUP_FAILED')
expect(sessionsCreate).not.toHaveBeenCalled()
})
describe('return URLs', () => {
function checkoutFrom(url: string) {
enqueue({ data: { stripe_customer_id: 'cus_existing' } }) // subscription row
enqueue({ data: null }) // no trial grant
sessionsCreate.mockResolvedValue({ url: 'https://stripe.test/session' })
return POST(createMockRequest(url, { method: 'POST', body: {} }), routeParams)
}
it('returns to the canonical app when checkout starts there', async () => {
const { status } = await parseJsonResponse(
await checkoutFrom('https://app.accounted.test/api/billing/checkout'),
)
expect(status).toBe(200)
expect(sessionsCreate).toHaveBeenCalledWith(
expect.objectContaining({
success_url: 'https://app.accounted.test/settings/billing?success=1',
cancel_url: 'https://app.accounted.test/settings/billing?canceled=1',
}),
)
})
it('returns to a registered white-label host when checkout starts there', async () => {
const { status } = await parseJsonResponse(
await checkoutFrom('https://portal.brand.test/api/billing/checkout'),
)
expect(status).toBe(200)
expect(sessionsCreate).toHaveBeenCalledWith(
expect.objectContaining({
success_url: 'https://portal.brand.test/settings/billing?success=1',
cancel_url: 'https://portal.brand.test/settings/billing?canceled=1',
}),
)
})
it('falls back to the canonical app for an unregistered or spoofed host', async () => {
const { status } = await parseJsonResponse(
await checkoutFrom('https://portal.brand.test.attacker.test/api/billing/checkout'),
)
expect(status).toBe(200)
expect(sessionsCreate).toHaveBeenCalledWith(
expect.objectContaining({
success_url: 'https://app.accounted.test/settings/billing?success=1',
cancel_url: 'https://app.accounted.test/settings/billing?canceled=1',
}),
)
})
})
})
-184
View File
@@ -1,184 +0,0 @@
/**
* Tests for POST /api/billing/portal.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase: serviceSupabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => serviceSupabase,
}))
// Keep sandboxBlockedResponse real; stub only the DB-backed guardSandbox.
const guardSandboxMock = vi.fn()
vi.mock('@/lib/sandbox/guard', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/sandbox/guard')>()
return { ...actual, guardSandbox: (...args: unknown[]) => guardSandboxMock(...args) }
})
const portalCreate = vi.fn()
vi.mock('@/lib/stripe/client', () => ({
getStripe: () => ({
billingPortal: { sessions: { create: portalCreate } },
}),
}))
import { POST } from '../portal/route'
const routeParams = { params: Promise.resolve({}) }
// The trusted-origin resolver reads the brands table; pin one registered
// brand host so the return-URL tests exercise the real resolver logic.
const resolveBrandResultByHostMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/branding/resolve', () => ({
resolveBrandResultByHost: (...args: unknown[]) => resolveBrandResultByHostMock(...args),
}))
const originalAppUrl = process.env.NEXT_PUBLIC_APP_URL
beforeEach(() => {
vi.clearAllMocks()
reset()
process.env.NEXT_PUBLIC_APP_URL = 'https://app.accounted.test'
resolveBrandResultByHostMock.mockImplementation(async (host: string) => ({
brand: host === 'portal.brand.test' ? { domain: host } : null,
lookupFailed: false,
}))
guardSandboxMock.mockResolvedValue(null)
requireAuthMock.mockResolvedValue({ user: { id: 'user-1', is_anonymous: false }, supabase: {}, error: null })
})
afterEach(() => {
if (originalAppUrl === undefined) delete process.env.NEXT_PUBLIC_APP_URL
else process.env.NEXT_PUBLIC_APP_URL = originalAppUrl
})
describe('POST /api/billing/portal', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const req = createMockRequest('/api/billing/portal', { method: 'POST', body: {} })
const res = await POST(req, routeParams)
expect(res.status).toBe(401)
})
it('blocks an anonymous (demo) user with 403 and never touches Stripe', async () => {
requireAuthMock.mockResolvedValue({
user: { id: 'anon-1', is_anonymous: true },
supabase: {},
error: null,
})
const req = createMockRequest('/api/billing/portal', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ sandbox_blocked?: boolean }>(
await POST(req, routeParams),
)
expect(status).toBe(403)
expect(body.sandbox_blocked).toBe(true)
expect(portalCreate).not.toHaveBeenCalled()
expect(guardSandboxMock).not.toHaveBeenCalled()
})
it('blocks a sandbox company with 403 and never touches Stripe', async () => {
const { sandboxBlockedResponse } = await import('@/lib/sandbox/guard')
guardSandboxMock.mockResolvedValue(sandboxBlockedResponse())
const req = createMockRequest('/api/billing/portal', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ sandbox_blocked?: boolean }>(
await POST(req, routeParams),
)
expect(status).toBe(403)
expect(body.sandbox_blocked).toBe(true)
expect(guardSandboxMock).toHaveBeenCalledWith(expect.anything(), 'company-1')
expect(portalCreate).not.toHaveBeenCalled()
})
it('returns 400 with NO_SUBSCRIPTION when the company has no Stripe customer', async () => {
enqueue({ data: null })
const req = createMockRequest('/api/billing/portal', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await POST(req, routeParams)
)
expect(status).toBe(400)
expect(body.error.code).toBe('NO_SUBSCRIPTION')
expect(portalCreate).not.toHaveBeenCalled()
})
it('returns the portal URL for a company with a Stripe customer', async () => {
enqueue({ data: { stripe_customer_id: 'cus_1' } })
portalCreate.mockResolvedValue({ url: 'https://stripe.test/portal' })
const req = createMockRequest('/api/billing/portal', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ url: string }>(await POST(req, routeParams))
expect(status).toBe(200)
expect(body.url).toBe('https://stripe.test/portal')
expect(portalCreate).toHaveBeenCalledWith(
expect.objectContaining({ customer: 'cus_1' })
)
})
describe('return URL', () => {
function portalFrom(url: string) {
enqueue({ data: { stripe_customer_id: 'cus_1' } })
portalCreate.mockResolvedValue({ url: 'https://stripe.test/portal' })
return POST(createMockRequest(url, { method: 'POST' }), routeParams)
}
it('comes back to the canonical app when opened there', async () => {
const { status } = await parseJsonResponse(
await portalFrom('https://app.accounted.test/api/billing/portal'),
)
expect(status).toBe(200)
expect(portalCreate).toHaveBeenCalledWith({
customer: 'cus_1',
return_url: 'https://app.accounted.test/settings/billing',
})
})
it('comes back to a registered white-label host when opened there', async () => {
const { status } = await parseJsonResponse(
await portalFrom('https://portal.brand.test/api/billing/portal'),
)
expect(status).toBe(200)
expect(portalCreate).toHaveBeenCalledWith(
expect.objectContaining({ return_url: 'https://portal.brand.test/settings/billing' }),
)
})
it('falls back to the canonical app for an unregistered or spoofed host', async () => {
const { status } = await parseJsonResponse(
await portalFrom('https://portal.brand.test.attacker.test/api/billing/portal'),
)
expect(status).toBe(200)
expect(portalCreate).toHaveBeenCalledWith(
expect.objectContaining({ return_url: 'https://app.accounted.test/settings/billing' }),
)
})
})
})
-216
View File
@@ -1,216 +0,0 @@
/**
* Tests for GET /api/billing/status.
*
* Focus: the isPaying classification. 'trialing' must count as paying since
* checkout defers the first charge to the trial end (the card is committed),
* while a company with no subscription stays on the upgrade path.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { parseJsonResponse } from '@/tests/helpers'
type TableResult = { data: unknown; error?: unknown }
function makeSupabase(byTable: Record<string, TableResult>) {
const chainFor = (table: string) => {
const result = byTable[table] ?? { data: null, error: null }
const chain: unknown = new Proxy(
{},
{
get(_t, prop) {
if (prop === 'then') {
return (resolve: (v: unknown) => void) =>
resolve({ data: result.data ?? null, error: result.error ?? null })
}
return () => chain
},
},
)
return chain
}
return { from: (t: string) => chainFor(t) }
}
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/sandbox/guard', () => ({
isSandboxCompany: vi.fn().mockResolvedValue(false),
}))
// Service client for the WL-10 team-agreement lookup (end clients cannot read
// the byrå team or its grants under RLS, so the route uses the service role).
let serviceByTable: Record<string, TableResult> = {}
const createServiceClientMock = vi.fn(() => makeSupabase(serviceByTable))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => createServiceClientMock(),
createClient: vi.fn(),
}))
import { GET } from '../status/route'
interface StatusBody {
isPaying: boolean
trialEndsAt: string | null
isDemo: boolean
teamAgreement?: { teamName: string }
}
function authAs(byTable: Record<string, TableResult>) {
requireAuthMock.mockResolvedValue({
user: { id: 'user-1', is_anonymous: false },
supabase: makeSupabase(byTable),
error: null,
})
}
beforeEach(() => {
vi.clearAllMocks()
serviceByTable = {}
})
describe('GET /api/billing/status', () => {
it('treats a trialing subscription as paying (card committed via deferred checkout)', async () => {
authAs({
company_subscriptions: { data: { status: 'trialing' } },
capability_grants: { data: { expires_at: '2099-01-01T00:00:00Z' } },
})
const { status, body } = await parseJsonResponse<StatusBody>(await GET())
expect(status).toBe(200)
expect(body.isPaying).toBe(true)
})
it('keeps a card-less product trial on the upgrade path with its expiry', async () => {
authAs({
company_subscriptions: { data: null },
capability_grants: { data: { expires_at: '2099-01-01T00:00:00Z' } },
})
const { status, body } = await parseJsonResponse<StatusBody>(await GET())
expect(status).toBe(200)
expect(body.isPaying).toBe(false)
expect(body.trialEndsAt).toBe('2099-01-01T00:00:00Z')
})
it('treats an active subscription as paying', async () => {
authAs({
company_subscriptions: { data: { status: 'active' } },
capability_grants: { data: null },
})
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.isPaying).toBe(true)
})
it('treats a canceled subscription as not paying', async () => {
authAs({
company_subscriptions: { data: { status: 'canceled' } },
capability_grants: { data: null },
})
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.isPaying).toBe(false)
})
})
// WL-10 billing honesty: a non-paying company under a byrå team with an
// active team-scoped manual grant gets the additive teamAgreement field.
describe('GET /api/billing/status team agreement', () => {
it('returns teamAgreement for a byrå-covered non-paying company', async () => {
authAs({
company_subscriptions: { data: null },
capability_grants: { data: null },
})
serviceByTable = {
companies: { data: { team_id: 'team-1' } },
teams: { data: { name: 'Siffran AB', kind: 'byra' } },
capability_grants: { data: [{ expires_at: null }] },
}
const { status, body } = await parseJsonResponse<StatusBody>(await GET())
expect(status).toBe(200)
expect(body.isPaying).toBe(false)
expect(body.teamAgreement).toEqual({ teamName: 'Siffran AB' })
})
it('accepts a future-dated grant expiry', async () => {
authAs({
company_subscriptions: { data: null },
capability_grants: { data: null },
})
serviceByTable = {
companies: { data: { team_id: 'team-1' } },
teams: { data: { name: 'Siffran AB', kind: 'byra' } },
capability_grants: { data: [{ expires_at: '2099-01-01T00:00:00Z' }] },
}
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.teamAgreement).toEqual({ teamName: 'Siffran AB' })
})
it('ignores an expired team grant (grace lapsed: standard paywall)', async () => {
authAs({
company_subscriptions: { data: null },
capability_grants: { data: null },
})
serviceByTable = {
companies: { data: { team_id: 'team-1' } },
teams: { data: { name: 'Siffran AB', kind: 'byra' } },
capability_grants: { data: [{ expires_at: '2020-01-01T00:00:00Z' }] },
}
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.isPaying).toBe(false)
expect(body.teamAgreement).toBeUndefined()
})
it('ignores a personal team even with a manual grant', async () => {
authAs({
company_subscriptions: { data: null },
capability_grants: { data: null },
})
serviceByTable = {
companies: { data: { team_id: 'team-1' } },
teams: { data: { name: 'Personal', kind: 'personal' } },
capability_grants: { data: [{ expires_at: null }] },
}
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.teamAgreement).toBeUndefined()
})
it('leaves a teamless company unchanged', async () => {
authAs({
company_subscriptions: { data: null },
capability_grants: { data: { expires_at: '2099-01-01T00:00:00Z' } },
})
serviceByTable = {
companies: { data: { team_id: null } },
}
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.isPaying).toBe(false)
expect(body.trialEndsAt).toBe('2099-01-01T00:00:00Z')
expect(body.teamAgreement).toBeUndefined()
expect('teamAgreement' in (body as object)).toBe(false)
})
it('never consults the team path for a paying company', async () => {
authAs({
company_subscriptions: { data: { status: 'active' } },
capability_grants: { data: null },
})
const { body } = await parseJsonResponse<StatusBody>(await GET())
expect(body.isPaying).toBe(true)
expect(body.teamAgreement).toBeUndefined()
expect(createServiceClientMock).not.toHaveBeenCalled()
})
})
-154
View File
@@ -1,154 +0,0 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { createServiceClient } from '@/lib/supabase/server'
import { getStripe, priceIdForPlan } from '@/lib/stripe/client'
import { guardSandbox, sandboxBlockedResponse } from '@/lib/sandbox/guard'
import { resolveRequestAppOrigin } from '@/lib/domains/trusted-app-origin'
const CheckoutSchema = z.object({
plan: z.enum(['monthly', 'yearly']).default('monthly'),
})
/**
* Create a Stripe subscription Checkout Session and return its hosted URL.
* The client redirects to it; provisioning happens via the webhook on
* checkout.session.completed (never trust the success redirect for fulfilment).
*
* company_subscriptions is read/written via the service client on purpose —
* the row is webhook-owned and not member-readable under RLS; every query
* still filters by the membership-validated companyId.
*/
export const POST = withRouteContext('billing.checkout', async (request, ctx) => {
const { user, supabase, companyId, log } = ctx
// Demo accounts must never reach Stripe. An anonymous user has no real
// identity to bill, and a sandbox company must never charge a token (same
// doctrine as lib/sandbox/guard.ts: no real external side effects). Both
// checks run before any Stripe call: this is the gap that let an anonymous
// demo user create a live Stripe customer.
if (user.is_anonymous) return sandboxBlockedResponse()
const blocked = await guardSandbox(supabase, companyId)
if (blocked) return blocked
const validation = await validateBody(request, CheckoutSchema, {
log,
operation: 'billing.checkout',
})
if (!validation.success) return validation.response
const { plan } = validation.data
const priceId = priceIdForPlan(plan)
if (!priceId) {
return NextResponse.json(
{
error: {
code: 'STRIPE_NOT_CONFIGURED',
message: 'Betalning är inte konfigurerad. Kontakta supporten.',
message_en: 'Stripe price not configured.',
},
},
{ status: 500 },
)
}
const stripe = getStripe()
const service = createServiceClient()
// Reuse the company's Stripe customer if we already created one, and read
// the trial expiry for the deferred-first-charge decision below. Independent
// reads, so one round-trip batch.
const [{ data: existing }, { data: trialGrant, error: trialGrantError }] = await Promise.all([
service
.from('company_subscriptions')
.select('stripe_customer_id')
.eq('company_id', companyId)
.maybeSingle(),
service
.from('capability_grants')
.select('expires_at')
.eq('company_id', companyId)
.eq('source', 'trial')
.order('expires_at', { ascending: false })
.limit(1)
.maybeSingle(),
])
// Fail closed on an uncertain trial state: proceeding on a lookup error
// would silently charge immediately after the UI promised "0 kr idag".
if (trialGrantError) {
return NextResponse.json(
{
error: {
code: 'TRIAL_LOOKUP_FAILED',
message: 'Kunde inte läsa din provperiod. Försök igen om en stund.',
message_en: 'Could not resolve the trial state. Try again shortly.',
},
},
{ status: 500 },
)
}
// Defer the first charge to the end of an active trial. The company already
// holds the paid capabilities free until then, so charging at checkout would
// bill for days it already has; instead the subscription starts as
// 'trialing' (which grants access via the webhook, see subscription-sync)
// and the first charge lands when the product trial ends. Stripe Checkout
// requires trial_end to be at least 48h in the future; closer than that, or
// with no active trial, billing starts immediately.
const trialExpiry = (trialGrant as { expires_at: string | null } | null)?.expires_at ?? null
const trialExpiryMs = trialExpiry ? new Date(trialExpiry).getTime() : null
const STRIPE_MIN_TRIAL_END_MS = 49 * 3600 * 1000 // Stripe's 48h floor + 1h clock margin
const trialEnd =
trialExpiryMs && trialExpiryMs - Date.now() > STRIPE_MIN_TRIAL_END_MS
? Math.floor(trialExpiryMs / 1000)
: undefined
let customerId = (existing as { stripe_customer_id: string | null } | null)?.stripe_customer_id ?? null
if (!customerId) {
const customer = await stripe.customers.create({
email: user.email ?? undefined,
metadata: { company_id: companyId },
})
customerId = customer.id
await service
.from('company_subscriptions')
.upsert({ company_id: companyId, stripe_customer_id: customerId }, { onConflict: 'company_id' })
}
// Return the user to the host they started on. Sessions are per domain, so
// sending a white-label user back to the canonical app would land them on a
// foreign-branded login with no session. The origin is resolved against the
// brands table; an unknown or spoofed host falls back to the
// canonical app URL. The paths stay fixed: never accept a caller-supplied
// return URL here.
const appOrigin = await resolveRequestAppOrigin(request)
const session = await stripe.checkout.sessions.create({
mode: 'subscription',
customer: customerId,
line_items: [{ price: priceId, quantity: 1 }],
// Swedish VAT: the Price is net (tax_behavior=exclusive in Stripe), so Stripe
// Tax adds 25% moms for SE customers and applies reverse charge for EU-B2B with
// a valid VAT number. automatic_tax carries onto the created subscription, so
// renewals (and the first charge after a deferred trial) stay taxed. The rate
// can only compute with a customer address, and a compliant momsfaktura needs
// it too; customer_update persists the address + tax id onto the pre-created
// customer for future invoices.
automatic_tax: { enabled: true },
tax_id_collection: { enabled: true },
billing_address_collection: 'required',
customer_update: { name: 'auto', address: 'auto' },
client_reference_id: companyId,
metadata: { company_id: companyId },
subscription_data: {
metadata: { company_id: companyId },
...(trialEnd ? { trial_end: trialEnd } : {}),
},
allow_promotion_codes: true,
success_url: `${appOrigin}/settings/billing?success=1`,
cancel_url: `${appOrigin}/settings/billing?canceled=1`,
})
return NextResponse.json({ url: session.url })
})
-58
View File
@@ -1,58 +0,0 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { createServiceClient } from '@/lib/supabase/server'
import { getStripe } from '@/lib/stripe/client'
import { guardSandbox, sandboxBlockedResponse } from '@/lib/sandbox/guard'
import { resolveRequestAppOrigin } from '@/lib/domains/trusted-app-origin'
/**
* Create a Stripe Billing Customer Portal session so the user can manage,
* upgrade/downgrade, or cancel their subscription. Stripe handles all the
* compliance/PCI surface: we never build those flows ourselves.
*
* company_subscriptions is read via the service client on purpose: the row
* is webhook-owned and not member-readable under RLS; the query still filters
* by the membership-validated companyId.
*/
export const POST = withRouteContext('billing.portal', async (request, ctx) => {
const { user, supabase, companyId } = ctx
// Demo accounts must never reach Stripe (see billing/checkout for the full
// rationale). Defense in depth: a demo tenant should never own a portal
// session even if a stray customer row exists.
if (user.is_anonymous) return sandboxBlockedResponse()
const blocked = await guardSandbox(supabase, companyId)
if (blocked) return blocked
const service = createServiceClient()
const { data: sub } = await service
.from('company_subscriptions')
.select('stripe_customer_id')
.eq('company_id', companyId)
.maybeSingle()
const customerId = (sub as { stripe_customer_id: string | null } | null)?.stripe_customer_id
if (!customerId) {
return NextResponse.json(
{
error: {
code: 'NO_SUBSCRIPTION',
message: 'Det finns inget abonnemang att hantera.',
message_en: 'No subscription to manage.',
},
},
{ status: 400 },
)
}
// Same host the user started on (see billing/checkout): a registered
// white-label host stays on its brand, anything else returns to the
// canonical app. The path is fixed.
const appOrigin = await resolveRequestAppOrigin(request)
const portal = await getStripe().billingPortal.sessions.create({
customer: customerId,
return_url: `${appOrigin}/settings/billing`,
})
return NextResponse.json({ url: portal.url })
})
-81
View File
@@ -1,81 +0,0 @@
import { NextResponse } from 'next/server'
import { requireAuth } from '@/lib/auth/require-auth'
import { createServiceClient } from '@/lib/supabase/server'
import { requireCompanyId } from '@/lib/company/context'
import { isStripeConfigured } from '@/lib/stripe/client'
import { isSandboxCompany } from '@/lib/sandbox/guard'
import { getTeamAgreement, type TeamAgreement } from '@/lib/entitlements/team-agreement'
/**
* Billing status for the client-rendered billing section (which lives inside the
* settings modal Dialog and can't read the DB server-side). Returns whether the
* company is paying, whether Stripe checkout is configured, and the trial expiry
* (for the days-left urgency banner). Read-only.
*
* WL-10: a non-paying company covered by its byrå team's agreement (active
* team-scoped manual grant) additionally gets `teamAgreement: { teamName }`,
* which the settings surface renders as "Ingår i <byråns namn>s avtal"
* instead of the upgrade pitch. Additive field: absent for everyone else.
*/
export async function GET() {
const { user, supabase, error } = await requireAuth()
if (error) return error
let companyId: string | null = null
try {
companyId = await requireCompanyId(supabase, user.id)
} catch {
companyId = null
}
// Demo accounts (anonymous user or sandbox company) can't check out, so the
// client hides the upgrade CTA rather than showing a button that only errors.
let isDemo = user.is_anonymous === true
if (companyId && !isDemo) {
isDemo = await isSandboxCompany(supabase, companyId)
}
let isPaying = false
let trialEndsAt: string | null = null
let teamAgreement: TeamAgreement | null = null
if (companyId) {
const { data: sub } = await supabase
.from('company_subscriptions')
.select('status')
.eq('company_id', companyId)
.maybeSingle()
const status = (sub as { status: string | null } | null)?.status ?? null
// Paying = a real subscription. Includes 'trialing': checkout defers the
// first charge to the product-trial end, so a Stripe-trialing subscription
// means the card is already committed and the user should see the manage
// view, not the upgrade pitch. Companies without a subscription (product
// trial only, no card) stay on the upgrade path.
isPaying = status === 'active' || status === 'past_due' || status === 'trialing'
const { data: trial } = await supabase
.from('capability_grants')
.select('expires_at')
.eq('company_id', companyId)
.eq('source', 'trial')
.order('expires_at', { ascending: false })
.limit(1)
.maybeSingle()
trialEndsAt = (trial as { expires_at: string | null } | null)?.expires_at ?? null
// Team entitlement (WL-10): only consulted when the company isn't paying
// on its own subscription. Service client by necessity: end clients are
// not members of the byrå team, so RLS hides the team and its grants
// from the user's session.
if (!isPaying) {
teamAgreement = await getTeamAgreement(createServiceClient(), companyId)
}
}
return NextResponse.json({
isPaying,
configured: isStripeConfigured(),
trialEndsAt,
isDemo,
...(teamAgreement ? { teamAgreement } : {}),
})
}