feat(onboarding): company setup from the conversation and POST /api/v1/companies (#1814 PR 3) (#1864)

* feat(onboarding): company setup from the conversation and POST /api/v1/companies

Third PR of agent-first onboarding (#1814). Once connected, the agent can
now set up a company end to end without the web wizard, and partner
platforms can provision companies over REST.

- create_company_for_user: service-role-only SECURITY DEFINER twin of
  create_company_with_owner taking the owner explicitly (service clients
  have no auth.uid()). pg-real test covers creation, role gating, unknown
  owner and foreign team.
- lib/company/create-company.ts: the wizard's creation sequence (org
  number, TIC snapshot, BAS chart, settings, first fiscal period, tax
  deadlines, rollback) extracted into createCompanyCore; the Server
  Action delegates to it, behaviour unchanged.
- lib/company/onboarding-input.ts: one Zod schema + planner for the
  agent/API paths; a VAT-registered company without moms_period is
  refused (a missing period silently yields zero VAT deadlines).
- MCP: gnubok_create_company (two-phase: preview, then confirm=true;
  companies:write, company-independent), gnubok_connect_bank and
  gnubok_connect_skatteverket (status + the browser link, gated on
  bank_sync / skatteverket, search-only in the catalog), the
  "onboarding" skill, and initialize instructions pointing at it.
- Consent page pre-ticks companies:write for an account with no company
  yet, so the setup does not dead-end on insufficient scope after signup.
- POST /api/v1/companies (companies:write, dry-run aware) on the same
  core; scope map, registry, spec snapshot and the generated API skill
  updated.
- tools/list payload ceiling raised 59.95K -> 60.4K for the one new
  default-catalog tool (documented in the guard).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018wCdzRTatKiDByKB8hCNT6

* fix(onboarding): explicit f_skatt, org number when VAT-registered, EF first year ends 31 Dec

Review findings on #1864 (Swedish compliance review):
- f_skatt is required, never defaulted to approved (SE-R-005 risk).
- org_number is required when vat_registered: the invoice
  momsregistreringsnummer derives from it (ML 17 kap 24 §).
- An enskild firma's first fiscal year must end on 31 December and its
  start month is forced to 1 even with first_fiscal_year set, mirroring
  the wizard's own rule text (BFL 3 kap. 1 §).
- POST /api/v1/companies no longer claims Idempotency-Key support (the
  wrapper only honours it on company-scoped routes).
- pg-real: createCompanyCore's chart seed runs under the real
  service_role, which the unit tests could not prove.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018wCdzRTatKiDByKB8hCNT6

* test(pg): starter chart has 41 accounts, assert non-empty

The service_role chart-seed proof passed the part that mattered (no
42501 from seed_chart_of_accounts) and failed on a wrong row-count
guess: the seeded chart is a curated starter set, not the full BAS list.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018wCdzRTatKiDByKB8hCNT6

* fix(migrations): move create_company_for_user to 20260825120000

main gained 20260824170000_bulk_book_transactions_service_actor.sql with
the same version while this branch was open; two files on one version
abort every Supabase branch apply and the prod auto-apply.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018wCdzRTatKiDByKB8hCNT6

* chore(api): refresh spec snapshot and generated skill after rebasing onto main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018wCdzRTatKiDByKB8hCNT6

* fix(mcp): flat create_company result, refuse localhost connect links, test hygiene

CodeRabbit on #1864: the confirmed-create result was wrapped in the
{ data, next } envelope while its outputSchema promised top-level
fields; it now returns the fields with next as a sibling. The two
connect-link tools refuse to build a link when NEXT_PUBLIC_APP_URL is
unset instead of handing a remote user a localhost URL. Tests clear
mocks and the event bus in beforeEach. Not changed: the rollback
already survives user_preferences.active_company_id (that FK is ON
DELETE SET NULL since 20260331010000), and v1 error details stay in the
surface's English developer convention.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018wCdzRTatKiDByKB8hCNT6

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-08-25 12:41:02 +02:00
committed by GitHub
co-authored by Claude Fable 5 Jakob Wennberg
parent c121d27996
commit 31e0cd6e05
25 changed files with 1920 additions and 183 deletions
@@ -435,6 +435,20 @@ describe('account with no company yet (issue #1814)', () => {
expect(supabase.from).not.toHaveBeenCalled()
})
it('pre-ticks companies:write so the agent can create the company, other writes stay unticked', async () => {
mocks.createClient.mockResolvedValue(buildSupabase({ id: 'user-1', email: 'ny@example.se' }))
const response = await GET(new Request(buildAuthorizeUrl(authorizeParams)))
const html = await response.text()
const companiesWrite = html.match(/<input[^>]*value="companies:write"[^>]*>/)?.[0]
expect(companiesWrite).toBeDefined()
expect(companiesWrite!).toContain('checked')
const transactionsWrite = html.match(/<input[^>]*value="transactions:write"[^>]*>/)?.[0]
expect(transactionsWrite).toBeDefined()
expect(transactionsWrite!).not.toContain('checked')
})
it('POST still issues an authorization code', async () => {
mocks.createClient.mockResolvedValue(buildSupabase({ id: 'user-1', email: 'ny@example.se' }))
+8
View File
@@ -283,6 +283,14 @@ export async function GET(request: Request) {
// instructions"), which is the whole point of the consent step.
const grantCeiling = new Set<ApiKeyScope>(parsed.scopes ?? ALL_SCOPES)
const preChecked = new Set<ApiKeyScope>(parsed.scopes ?? DEFAULT_OAUTH_SCOPES)
// An account with no company is connecting in order to create one
// (issue #1814): pre-tick the one write scope that gnubok_create_company
// needs, so the agent-driven setup does not dead-end on insufficient scope
// right after signup. Still a checkbox the user can untick, and still
// bounded by the client's ceiling.
if (!companyId && grantCeiling.has('companies:write')) {
preChecked.add('companies:write')
}
const scopeCheckboxesHtml = renderScopeCheckboxes(preChecked, grantCeiling)
// Render consent page
@@ -0,0 +1,189 @@
/**
* POST /api/v1/companies (issue #1814 PR 3): programmatic company creation
* for partner provisioning and agents. Same static-route context shape as the
* GET tests (Next.js 16 passes `{ params: undefined }`).
*/
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
beforeAll(() => {
process.env.NEXT_PUBLIC_SUPABASE_URL ||= 'http://localhost:54321'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||= 'test-anon-key'
})
const mocks = vi.hoisted(() => ({
createCompanyCore: vi.fn(),
}))
vi.mock('@/lib/auth/api-keys', async () => {
const actual = await vi.importActual<typeof import('@/lib/auth/api-keys')>('@/lib/auth/api-keys')
return {
...actual,
validateApiKey: vi.fn(),
createServiceClientNoCookies: vi.fn(),
}
})
vi.mock('@supabase/supabase-js', async () => {
const actual = await vi.importActual<typeof import('@supabase/supabase-js')>('@supabase/supabase-js')
return { ...actual, createClient: vi.fn().mockReturnValue({}) }
})
vi.mock('@/lib/company/create-company', () => ({
createCompanyCore: (...args: unknown[]) => mocks.createCompanyCore(...args),
}))
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
import { POST as createCompany } from '../route'
const mockValidate = validateApiKey as ReturnType<typeof vi.fn>
const mockServiceClient = createServiceClientNoCookies as ReturnType<typeof vi.fn>
const USER_ID = '930abb54-c5ef-4ae0-b274-30fb16e9a295'
const TEAM_ID = '44444444-4444-4444-8444-444444444444'
const COMPANY_ID = '55555555-5555-4555-8555-555555555555'
function makeSupabase(teamId: string | null) {
const chain: Record<string, ReturnType<typeof vi.fn>> = {
select: vi.fn(() => chain),
eq: vi.fn(() => chain),
order: vi.fn(() => chain),
limit: vi.fn(() => chain),
maybeSingle: vi.fn().mockResolvedValue({ data: teamId ? { team_id: teamId } : null, error: null }),
}
return {
from: vi.fn(() => chain),
rpc: vi.fn().mockResolvedValue({ data: COMPANY_ID, error: null }),
}
}
function makeRequest(body: unknown, headers: Record<string, string> = {}): Request {
return new Request('https://x.test/api/v1/companies', {
method: 'POST',
headers: {
Authorization: 'Bearer test-fixture-not-a-real-key',
'Content-Type': 'application/json',
'Idempotency-Key': 'idem-1',
...headers,
},
body: typeof body === 'string' ? body : JSON.stringify(body),
})
}
type PostCtx = Parameters<typeof createCompany>[1]
const staticRouteContext = () => ({ params: undefined } as unknown as PostCtx)
const validBody = {
name: 'Acme AB',
entity_type: 'aktiebolag',
org_number: '5560000001',
vat_registered: true,
moms_period: 'quarterly',
accounting_method: 'accrual',
f_skatt: true,
}
beforeEach(() => {
vi.clearAllMocks()
mockValidate.mockResolvedValue({
userId: USER_ID,
companyId: null,
apiKeyId: 'key-1',
apiKeyName: 'Partner key',
scopes: ['companies:write', 'companies:read'],
mode: 'live',
})
mockServiceClient.mockReturnValue(makeSupabase(TEAM_ID))
mocks.createCompanyCore.mockImplementation(
async (_client: unknown, _input: unknown, createRow: () => Promise<{ data: unknown; error: unknown }>) => {
const { data } = await createRow()
return { companyId: data as string }
}
)
})
describe('POST /api/v1/companies', () => {
it('returns 401 for a missing bearer token', async () => {
const request = new Request('https://x.test/api/v1/companies', {
method: 'POST',
body: JSON.stringify(validBody),
headers: { 'Content-Type': 'application/json' },
})
const res = await createCompany(request, staticRouteContext())
expect(res.status).toBe(401)
})
it('returns 403 without companies:write', async () => {
mockValidate.mockResolvedValue({
userId: USER_ID,
companyId: null,
apiKeyId: 'key-1',
apiKeyName: 'Read key',
scopes: ['companies:read'],
mode: 'live',
})
const res = await createCompany(makeRequest(validBody), staticRouteContext())
expect(res.status).toBe(403)
expect(mocks.createCompanyCore).not.toHaveBeenCalled()
})
it('returns 400 for a VAT-registered company without a moms period', async () => {
const res = await createCompany(makeRequest({ ...validBody, moms_period: undefined }), staticRouteContext())
expect(res.status).toBe(400)
const body = await res.json()
expect(JSON.stringify(body)).toContain('moms_period')
expect(mocks.createCompanyCore).not.toHaveBeenCalled()
})
it('returns 400 for a body that is not JSON', async () => {
const res = await createCompany(makeRequest('not json'), staticRouteContext())
expect(res.status).toBe(400)
})
it('creates the company through the service-role RPC for the key user and returns 201', async () => {
const supabase = makeSupabase(TEAM_ID)
mockServiceClient.mockReturnValue(supabase)
const res = await createCompany(makeRequest(validBody), staticRouteContext())
expect(res.status).toBe(201)
const body = await res.json()
expect(body.data).toMatchObject({
id: COMPANY_ID,
name: 'Acme AB',
entity_type: 'aktiebolag',
org_number: '5560000001',
vat_registered: true,
moms_period: 'quarterly',
team_id: TEAM_ID,
})
expect(body.data.fiscal_period.name).toContain('Räkenskapsår')
expect(supabase.rpc).toHaveBeenCalledWith('create_company_for_user', {
p_user_id: USER_ID,
p_name: 'Acme AB',
p_entity_type: 'aktiebolag',
p_team_id: TEAM_ID,
})
})
it('previews without creating for a test-mode key (dry run)', async () => {
mockValidate.mockResolvedValue({
userId: USER_ID,
companyId: null,
apiKeyId: 'key-1',
apiKeyName: 'Test key',
scopes: ['companies:write'],
mode: 'test',
})
const res = await createCompany(makeRequest(validBody), staticRouteContext())
expect(res.status).toBe(200)
const body = await res.json()
expect(body.data.dry_run).toBe(true)
expect(body.data.preview.name).toBe('Acme AB')
expect(mocks.createCompanyCore).not.toHaveBeenCalled()
})
it('maps a creation failure to INTERNAL_ERROR', async () => {
mocks.createCompanyCore.mockResolvedValue({ error: 'Kunde inte skapa kontoplan. Försök igen.' })
const res = await createCompany(makeRequest(validBody), staticRouteContext())
expect(res.status).toBe(500)
})
})
+165 -3
View File
@@ -10,15 +10,18 @@
*/
import { z } from 'zod'
import { paginated } from '@/lib/api/v1/response'
import { paginated, created } from '@/lib/api/v1/response'
import {
encodeDefaultCursor,
parsePaginationParams,
decodeDefaultCursor,
} from '@/lib/api/v1/pagination'
import { registerEndpoint, listEnvelope } from '@/lib/api/v1/registry'
import { registerEndpoint, listEnvelope, dataEnvelope } from '@/lib/api/v1/registry'
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
import { v1ErrorResponse } from '@/lib/api/v1/errors'
import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
import { dryRunPreview } from '@/lib/api/v1/dry-run'
import { createCompanyCore } from '@/lib/company/create-company'
import { CompanySetupSchema, planCompanySetup } from '@/lib/company/onboarding-input'
const Company = z.object({
id: z.string().uuid(),
@@ -70,6 +73,165 @@ registerEndpoint({
response: { success: CompaniesListResponse },
})
const CreatedCompany = z.object({
id: z.string().uuid(),
name: z.string(),
entity_type: z.enum(['enskild_firma', 'aktiebolag']),
org_number: z.string().nullable(),
vat_registered: z.boolean(),
moms_period: z.enum(['monthly', 'quarterly', 'yearly']).nullable(),
accounting_method: z.enum(['accrual', 'cash']),
fiscal_period: z.object({ start_date: z.string(), end_date: z.string(), name: z.string() }),
team_id: z.string().uuid().nullable(),
})
registerEndpoint({
operation: 'companies.create',
method: 'POST',
path: '/api/v1/companies',
summary: 'Create a company and set it up for bookkeeping.',
description:
'Creates a new company owned by the API key user (or attached to one of their teams) and sets it up in one call: ' +
'owner membership, BAS chart of accounts for the company form, compliance settings, the first fiscal period and the ' +
'automatic tax deadlines. A 30-day trial with every paid capability starts immediately. ' +
'Intended for partner platforms provisioning client companies (byrå/vertical SaaS) and for agents onboarding a user.',
useWhen:
'A platform or agent needs to provision a company that does not exist in Accounted yet. The caller becomes its owner; invite the end customer afterwards.',
doNotUseFor:
'Companies that already exist (list them with GET /api/v1/companies), or changing settings on an existing company (PATCH /api/v1/companies/{companyId}/settings).',
pitfalls: [
'A VAT-registered company MUST send moms_period (monthly / quarterly / yearly); the request is refused otherwise, because a missing period silently produces zero VAT deadlines.',
'Bookkeeping duty under BFL starts when the company exists with a fiscal period: do not create companies to try things out. Use a test-mode key (dry run) for that.',
'Enskild firma always runs on the calendar year; fiscal_year_start_month is ignored for it.',
'first_fiscal_year is only for a company in its first year (BFL 3 kap.: up to 18 months). Omit it for an established company.',
'Not idempotent, and Idempotency-Key is not honoured on this company-less route: a retry after a network failure creates a second company. List GET /api/v1/companies before retrying.',
'org_number is required for a VAT-registered company (the invoice momsregistreringsnummer derives from it), and f_skatt must be stated explicitly: F-skatt approval is never assumed.',
],
example: {
request: {
name: 'Acme AB',
entity_type: 'aktiebolag',
org_number: '5566778899',
vat_registered: true,
moms_period: 'quarterly',
accounting_method: 'accrual',
f_skatt: true,
},
response: {
data: {
id: '8fd5b1f4-…',
name: 'Acme AB',
entity_type: 'aktiebolag',
org_number: '5566778899',
vat_registered: true,
moms_period: 'quarterly',
accounting_method: 'accrual',
fiscal_period: { start_date: '2026-01-01', end_date: '2026-12-31', name: 'Räkenskapsår 2026' },
team_id: null,
},
meta: { request_id: 'req_…', api_version: '2026-05-12' },
},
},
scope: 'companies:write',
risk: 'medium',
idempotent: false,
reversible: false,
dryRunSupported: true,
request: { body: CompanySetupSchema },
response: { success: dataEnvelope(CreatedCompany), errorCodes: ['VALIDATION_ERROR', 'FORBIDDEN', 'INTERNAL_ERROR'] },
})
export const POST = withApiV1('companies.create', async (request, ctx) => {
let rawBody: unknown
try {
rawBody = await request.json()
} catch {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { field: 'body', message: 'Body is not valid JSON.' },
})
}
const parsed = CompanySetupSchema.safeParse(rawBody)
if (!parsed.success) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { issues: parsed.error.issues.map((i) => ({ field: i.path.join('.'), message: i.message })) },
})
}
const setup = parsed.data
const plan = planCompanySetup(setup)
if (!plan.ok) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { field: 'first_fiscal_year', message: plan.error },
})
}
// Team: explicit, else the caller's first (usually personal) team, same as
// the web wizard. create_company_for_user re-checks membership.
let teamId: string | null = setup.team_id ?? null
if (!teamId) {
const { data: membership } = await ctx.supabase
.from('team_members')
.select('team_id')
.eq('user_id', ctx.userId)
.order('created_at', { ascending: true })
.limit(1)
.maybeSingle()
teamId = (membership?.team_id as string | undefined) ?? null
}
const shape = (id: string) => ({
id,
name: setup.name,
entity_type: setup.entity_type,
org_number: (plan.input.settings.org_number as string | null) ?? null,
vat_registered: setup.vat_registered,
moms_period: setup.vat_registered ? setup.moms_period ?? null : null,
accounting_method: setup.accounting_method,
fiscal_period: {
start_date: plan.fiscalPeriod.startDate,
end_date: plan.fiscalPeriod.endDate,
name: plan.fiscalPeriod.name,
},
team_id: teamId,
})
if (ctx.dryRun) {
return dryRunPreview(shape('00000000-0000-4000-8000-000000000000'), {
requestId: ctx.requestId,
log: ctx.log,
})
}
const result = await createCompanyCore(ctx.supabase, plan.input, () =>
ctx.supabase.rpc('create_company_for_user', {
p_user_id: ctx.userId,
p_name: setup.name,
p_entity_type: setup.entity_type,
p_team_id: teamId,
}),
)
if (result.error !== undefined) {
if (result.error === 'org_number_invalid') {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { field: 'org_number', message: 'Invalid organisationsnummer.' },
})
}
ctx.log.error('companies.create failed', { reason: result.error })
return v1ErrorResponseFromCode('INTERNAL_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { message: result.error },
})
}
return created(shape(result.companyId), { requestId: ctx.requestId })
})
export const GET = withApiV1('companies.list', async (request, ctx) => {
const url = new URL(request.url)
const { limit, cursor } = parsePaginationParams(url)