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:
co-authored by
Claude Fable 5
Jakob Wennberg
parent
c121d27996
commit
31e0cd6e05
@@ -1,6 +1,6 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`v1 spec snapshot > matches the recorded endpoint count > endpoint-count 1`] = `135`;
|
||||
exports[`v1 spec snapshot > matches the recorded endpoint count > endpoint-count 1`] = `136`;
|
||||
|
||||
exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-keys 1`] = `
|
||||
[
|
||||
@@ -79,6 +79,7 @@ exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-key
|
||||
"PATCH /api/v1/companies/:companyId/supplier-invoices/:id",
|
||||
"PATCH /api/v1/companies/:companyId/suppliers/:id",
|
||||
"PATCH /api/v1/companies/:companyId/webhooks/:id",
|
||||
"POST /api/v1/companies",
|
||||
"POST /api/v1/companies/:companyId/customers",
|
||||
"POST /api/v1/companies/:companyId/customers/bulk-create",
|
||||
"POST /api/v1/companies/:companyId/dimensions/:id/values",
|
||||
|
||||
@@ -28,7 +28,7 @@ export const API_KEY_SCOPES = {
|
||||
'payroll:write': { label: 'Löner: skriv', description: 'Skapa lönekörning, beräkna, generera AGI, logga körjournalresor' },
|
||||
// v1 REST API: added Phase 1
|
||||
'companies:read': { label: 'Företag: läs', description: 'Lista och visa företagsprofiler som API-nyckeln har tillgång till' },
|
||||
'companies:write': { label: 'Företag: skriv', description: 'Uppdatera företagsinställningar via stagade verktyg eller REST-endpointen PATCH /api/v1/companies/{companyId}/settings' },
|
||||
'companies:write': { label: 'Företag: skriv', description: 'Skapa nya företag och uppdatera företagsinställningar (gnubok_create_company, stagade verktyg, REST POST /api/v1/companies och PATCH /api/v1/companies/{companyId}/settings)' },
|
||||
'events:read': { label: 'Händelser: läs', description: 'Polla händelseloggen (event_log) som webhook-fallback' },
|
||||
'webhooks:manage': { label: 'Webhooks: hantera', description: 'Skapa, lista, uppdatera och radera webhook-prenumerationer' },
|
||||
'operations:read': { label: 'Operationer: läs', description: 'Hämta status för långkörande operationer (importer, bokslut, omvärdering)' },
|
||||
@@ -179,6 +179,9 @@ export const SCOPE_GROUPS = [
|
||||
export const TOOL_SCOPE_MAP: Record<string, ApiKeyScope> = {
|
||||
// Companies
|
||||
gnubok_list_companies: 'companies:read',
|
||||
gnubok_create_company: 'companies:write',
|
||||
gnubok_connect_bank: 'companies:read',
|
||||
gnubok_connect_skatteverket: 'companies:read',
|
||||
gnubok_get_company_settings: 'companies:read',
|
||||
gnubok_update_company_settings: 'companies:write',
|
||||
// Transactions
|
||||
|
||||
@@ -38,6 +38,8 @@ export const V1_PUBLIC_ENDPOINTS: ReadonlyArray<string> = [
|
||||
export const V1_ENDPOINT_SCOPES: Record<string, ApiKeyScope> = {
|
||||
// Companies
|
||||
'GET /api/v1/companies': 'companies:read',
|
||||
// Issue #1814: programmatic company creation (partner provisioning, agents).
|
||||
'POST /api/v1/companies': 'companies:write',
|
||||
'GET /api/v1/companies/:companyId': 'companies:read',
|
||||
// Issue #1348: company-settings write (same field set as the MCP tool
|
||||
// gnubok_update_company_settings; direct write, no staging).
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { CompanySetupSchema, planCompanySetup } from '../onboarding-input'
|
||||
|
||||
const base = {
|
||||
name: 'Testbolaget AB',
|
||||
entity_type: 'aktiebolag' as const,
|
||||
org_number: '5560000001',
|
||||
vat_registered: true,
|
||||
moms_period: 'quarterly' as const,
|
||||
accounting_method: 'accrual' as const,
|
||||
f_skatt: true,
|
||||
}
|
||||
|
||||
describe('CompanySetupSchema', () => {
|
||||
it('accepts a complete aktiebolag setup', () => {
|
||||
expect(CompanySetupSchema.safeParse(base).success).toBe(true)
|
||||
})
|
||||
|
||||
it('refuses a VAT-registered company without a moms_period (silent zero-deadline trap)', () => {
|
||||
const result = CompanySetupSchema.safeParse({ ...base, moms_period: undefined })
|
||||
expect(result.success).toBe(false)
|
||||
if (!result.success) {
|
||||
expect(result.error.issues.some((i) => i.path.join('.') === 'moms_period')).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('refuses a moms_period on a company that is not VAT-registered', () => {
|
||||
const result = CompanySetupSchema.safeParse({ ...base, vat_registered: false })
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
it('accepts a non-VAT company with no moms_period', () => {
|
||||
const result = CompanySetupSchema.safeParse({ ...base, vat_registered: false, moms_period: undefined })
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
|
||||
it('refuses a VAT-registered company without an org number (invoice momsregistreringsnummer)', () => {
|
||||
const result = CompanySetupSchema.safeParse({ ...base, org_number: undefined })
|
||||
expect(result.success).toBe(false)
|
||||
if (!result.success) {
|
||||
expect(result.error.issues.some((i) => i.path.join('.') === 'org_number')).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('accepts a non-VAT company without an org number', () => {
|
||||
const result = CompanySetupSchema.safeParse({
|
||||
...base,
|
||||
org_number: undefined,
|
||||
vat_registered: false,
|
||||
moms_period: undefined,
|
||||
})
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
|
||||
it('refuses an omitted f_skatt: F-skatt approval is never assumed', () => {
|
||||
const result = CompanySetupSchema.safeParse({ ...base, f_skatt: undefined })
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
it('refuses an enskild firma first fiscal year that does not end on 31 December', () => {
|
||||
const result = CompanySetupSchema.safeParse({
|
||||
...base,
|
||||
entity_type: 'enskild_firma',
|
||||
first_fiscal_year: { start: '2026-03-15', end: '2027-06-30' },
|
||||
})
|
||||
expect(result.success).toBe(false)
|
||||
if (!result.success) {
|
||||
expect(result.error.issues.some((i) => i.path.join('.') === 'first_fiscal_year.end')).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('refuses a malformed organisationsnummer', () => {
|
||||
const result = CompanySetupSchema.safeParse({ ...base, org_number: '1234' })
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('planCompanySetup', () => {
|
||||
it('produces the wizard-shaped settings and a calendar-year period by default', () => {
|
||||
const plan = planCompanySetup(CompanySetupSchema.parse(base))
|
||||
expect(plan.ok).toBe(true)
|
||||
if (!plan.ok) return
|
||||
const year = new Date().getFullYear()
|
||||
expect(plan.fiscalPeriod.startDate).toBe(`${year}-01-01`)
|
||||
expect(plan.fiscalPeriod.endDate).toBe(`${year}-12-31`)
|
||||
expect(plan.input.settings).toMatchObject({
|
||||
entity_type: 'aktiebolag',
|
||||
company_name: 'Testbolaget AB',
|
||||
org_number: '5560000001',
|
||||
vat_registered: true,
|
||||
vat_number: 'SE556000000101',
|
||||
moms_period: 'quarterly',
|
||||
accounting_method: 'accrual',
|
||||
f_skatt: true,
|
||||
fiscal_year_start_month: 1,
|
||||
is_first_fiscal_year: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('forces enskild firma onto the calendar year regardless of the requested start month', () => {
|
||||
const plan = planCompanySetup(
|
||||
CompanySetupSchema.parse({ ...base, entity_type: 'enskild_firma', fiscal_year_start_month: 7 })
|
||||
)
|
||||
expect(plan.ok).toBe(true)
|
||||
if (!plan.ok) return
|
||||
expect(plan.input.settings.fiscal_year_start_month).toBe(1)
|
||||
expect(plan.fiscalPeriod.startDate.endsWith('-01-01')).toBe(true)
|
||||
})
|
||||
|
||||
it('uses the first fiscal year dates and derives the start month from its end', () => {
|
||||
const plan = planCompanySetup(
|
||||
CompanySetupSchema.parse({
|
||||
...base,
|
||||
first_fiscal_year: { start: '2026-03-15', end: '2027-06-30' },
|
||||
})
|
||||
)
|
||||
expect(plan.ok).toBe(true)
|
||||
if (!plan.ok) return
|
||||
expect(plan.fiscalPeriod).toMatchObject({ startDate: '2026-03-15', endDate: '2027-06-30' })
|
||||
expect(plan.fiscalPeriod.name).toContain('Första räkenskapsåret')
|
||||
expect(plan.input.settings.fiscal_year_start_month).toBe(7)
|
||||
expect(plan.input.settings.is_first_fiscal_year).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps an enskild firma on the calendar year through a first fiscal year ending 31 December', () => {
|
||||
const plan = planCompanySetup(
|
||||
CompanySetupSchema.parse({
|
||||
...base,
|
||||
entity_type: 'enskild_firma',
|
||||
first_fiscal_year: { start: '2026-03-15', end: '2026-12-31' },
|
||||
})
|
||||
)
|
||||
expect(plan.ok).toBe(true)
|
||||
if (!plan.ok) return
|
||||
expect(plan.fiscalPeriod).toMatchObject({ startDate: '2026-03-15', endDate: '2026-12-31' })
|
||||
expect(plan.input.settings.fiscal_year_start_month).toBe(1)
|
||||
})
|
||||
|
||||
it('carries f_skatt=false through instead of defaulting to approved', () => {
|
||||
const plan = planCompanySetup(CompanySetupSchema.parse({ ...base, f_skatt: false }))
|
||||
expect(plan.ok).toBe(true)
|
||||
if (!plan.ok) return
|
||||
expect(plan.input.settings.f_skatt).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects a first fiscal year longer than 18 months', () => {
|
||||
const plan = planCompanySetup(
|
||||
CompanySetupSchema.parse({
|
||||
...base,
|
||||
first_fiscal_year: { start: '2026-01-01', end: '2027-12-31' },
|
||||
})
|
||||
)
|
||||
expect(plan.ok).toBe(false)
|
||||
})
|
||||
|
||||
it('leaves vat_number null and moms_period null for a non-VAT company', () => {
|
||||
const plan = planCompanySetup(
|
||||
CompanySetupSchema.parse({ ...base, vat_registered: false, moms_period: undefined })
|
||||
)
|
||||
expect(plan.ok).toBe(true)
|
||||
if (!plan.ok) return
|
||||
expect(plan.input.settings.vat_number).toBeNull()
|
||||
expect(plan.input.settings.moms_period).toBeNull()
|
||||
})
|
||||
})
|
||||
+21
-171
@@ -3,13 +3,7 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { setActiveCompany, CompanyContextError } from '@/lib/company/context'
|
||||
import { revalidatePath } from 'next/cache'
|
||||
import { normalizeOrgNumber } from '@/lib/company-lookup/normalize-org-number'
|
||||
import { normalizeVatNumber, isValidSwedishVatNumber, deriveSwedishVatNumber } from '@/lib/vat/vat-number'
|
||||
import {
|
||||
regenerateTaxDeadlinesForUser,
|
||||
toDeadlineSettings,
|
||||
} from '@/lib/tax/deadline-generator'
|
||||
import type { CompanySettingsForDeadlines } from '@/lib/tax/deadline-config'
|
||||
import { createCompanyCore } from '@/lib/company/create-company'
|
||||
import type { CompanyLookupResult } from '@/lib/company-lookup/types'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
@@ -101,174 +95,30 @@ async function createCompanyFromOnboardingImpl(params: {
|
||||
|
||||
const companyName = (params.settings.company_name as string | undefined) || 'Mitt företag'
|
||||
|
||||
// Org-number format validation. We intentionally do NOT enforce
|
||||
// uniqueness: the same org number may legitimately appear on multiple
|
||||
// companies (a separate test copy of your real company, or a consultant
|
||||
// and the owner each tracking the same entity). Tenant isolation
|
||||
// (RLS + company_id) is the real boundary, not org-number uniqueness.
|
||||
//
|
||||
// normalizeOrgNumber returns null for malformed input: we refuse rather
|
||||
// than storing a value that would break SIE/SRU exports later.
|
||||
const rawOrgNumber = params.settings.org_number as string | undefined
|
||||
const cleanedOrgNumber = normalizeOrgNumber(rawOrgNumber)
|
||||
if (rawOrgNumber && rawOrgNumber.trim() && !cleanedOrgNumber) {
|
||||
return { error: 'org_number_invalid' }
|
||||
}
|
||||
|
||||
// 1. Create company + owner membership atomically via RPC
|
||||
const { data: newCompanyId, error: companyError } = await supabase.rpc('create_company_with_owner', {
|
||||
p_name: companyName,
|
||||
p_entity_type: entityType,
|
||||
p_team_id: params.teamId,
|
||||
})
|
||||
|
||||
if (companyError || !newCompanyId) {
|
||||
console.error('[createCompanyFromOnboarding] company creation failed', companyError)
|
||||
return { error: 'Kunde inte skapa företag. Försök igen.' }
|
||||
}
|
||||
|
||||
// Helper: roll back the company if a subsequent step fails. Deletes in FK
|
||||
// order. Each delete is error-checked so a failed cleanup leaves a trace
|
||||
// instead of silently stranding partial company data behind a generic
|
||||
// "try again" message.
|
||||
const rollback = async (reason: string, err: unknown) => {
|
||||
console.error(`[createCompanyFromOnboarding] rolling back ${newCompanyId}: ${reason}`, err)
|
||||
const deletions: Array<[table: string, run: () => PromiseLike<{ error: unknown }>]> = [
|
||||
['company_settings', () => supabase.from('company_settings').delete().eq('company_id', newCompanyId)],
|
||||
['fiscal_periods', () => supabase.from('fiscal_periods').delete().eq('company_id', newCompanyId)],
|
||||
['chart_of_accounts', () => supabase.from('chart_of_accounts').delete().eq('company_id', newCompanyId)],
|
||||
['company_members', () => supabase.from('company_members').delete().eq('company_id', newCompanyId)],
|
||||
['companies', () => supabase.from('companies').delete().eq('id', newCompanyId)],
|
||||
]
|
||||
for (const [table, run] of deletions) {
|
||||
const { error: deleteError } = await run()
|
||||
if (deleteError) {
|
||||
console.error(
|
||||
`[createCompanyFromOnboarding] rollback delete failed for ${table} (company ${newCompanyId})`,
|
||||
deleteError,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mirror the normalized org_number onto the companies row so future
|
||||
// duplicate checks and cross-references are reliable. MUST be error-checked
|
||||
// and rolled back on failure: otherwise the freshly-created company would
|
||||
// exist without an org_number and the duplicate guard would never match it
|
||||
// for any future user (the very guard this code is enforcing).
|
||||
if (cleanedOrgNumber) {
|
||||
const { error: orgUpdateError } = await supabase
|
||||
.from('companies')
|
||||
.update({ org_number: cleanedOrgNumber })
|
||||
.eq('id', newCompanyId)
|
||||
if (orgUpdateError) {
|
||||
await rollback('org_number update failed', orgUpdateError)
|
||||
return { error: 'Kunde inte spara organisationsnummer. Försök igen.' }
|
||||
}
|
||||
}
|
||||
|
||||
// Persist whatever lookup data the wizard already gathered. Do NOT call
|
||||
// /profile here: that handler fans out to 13 Lens calls and the 5 s
|
||||
// timeout in tic-fetch.ts ate ~530 wasted calls in May before yielding
|
||||
// zero snapshots (every signup's /profile timed out, but the in-flight
|
||||
// upstream fetches still counted against quota). The agent build path
|
||||
// (app/(onboarding)/onboarding/agent/page.tsx) calls ensureTicSnapshot
|
||||
// with upgradeV1: true lazily, which is the right place: only companies
|
||||
// that actually reach agent onboarding spend the budget.
|
||||
if (params.ticLookup) {
|
||||
const { error: ticErr } = await supabase
|
||||
.from('companies')
|
||||
.update({
|
||||
tic_snapshot: params.ticLookup,
|
||||
tic_snapshot_fetched_at: new Date().toISOString(),
|
||||
})
|
||||
.eq('id', newCompanyId)
|
||||
if (ticErr) {
|
||||
console.warn('[createCompanyFromOnboarding] tic snapshot persist failed', ticErr)
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Seed chart of accounts
|
||||
const { error: coaError } = await supabase.rpc('seed_chart_of_accounts', {
|
||||
p_company_id: newCompanyId,
|
||||
p_entity_type: entityType,
|
||||
})
|
||||
if (coaError) {
|
||||
await rollback('COA seeding failed', coaError)
|
||||
return { error: 'Kunde inte skapa kontoplan. Försök igen.' }
|
||||
}
|
||||
|
||||
// 3. Save settings (strip UI-only and managed fields)
|
||||
const {
|
||||
id: _id,
|
||||
user_id: _uid,
|
||||
company_id: _cid,
|
||||
created_at: _ca,
|
||||
updated_at: _ua,
|
||||
is_first_fiscal_year: _ify,
|
||||
first_year_start: _fys,
|
||||
first_year_end: _fye,
|
||||
...settingsToSave
|
||||
} = params.settings
|
||||
|
||||
// Defence in depth: this upsert bypasses UpdateSettingsSchema, so never persist
|
||||
// a VAT number blind. Normalise to the canonical SE+12 form; if it isn't
|
||||
// structurally valid (e.g. the legacy SE+14 personnummer derivation), re-derive
|
||||
// it from the org number, falling back to null rather than storing a malformed
|
||||
// momsregistreringsnummer.
|
||||
if (typeof settingsToSave.vat_number === 'string' && settingsToSave.vat_number) {
|
||||
const normalized = normalizeVatNumber(settingsToSave.vat_number)
|
||||
settingsToSave.vat_number = isValidSwedishVatNumber(normalized)
|
||||
? normalized
|
||||
: deriveSwedishVatNumber(settingsToSave.org_number as string | null | undefined)
|
||||
}
|
||||
|
||||
const { error: settingsError } = await supabase
|
||||
.from('company_settings')
|
||||
.upsert(
|
||||
{
|
||||
...settingsToSave,
|
||||
company_id: newCompanyId,
|
||||
onboarding_complete: true,
|
||||
onboarding_step: 4,
|
||||
},
|
||||
{ onConflict: 'company_id' },
|
||||
)
|
||||
|
||||
if (settingsError) {
|
||||
await rollback('settings upsert failed', settingsError)
|
||||
return { error: 'Kunde inte spara inställningar. Försök igen.' }
|
||||
}
|
||||
|
||||
// 4. Create fiscal period
|
||||
const { error: periodError } = await supabase.from('fiscal_periods').upsert(
|
||||
// Steps 1-5 (company + owner via RPC, org number, TIC snapshot, chart,
|
||||
// settings, fiscal period, tax deadlines, with rollback) are shared with
|
||||
// the MCP and v1 creation paths: lib/company/create-company.ts.
|
||||
const created = await createCompanyCore(
|
||||
supabase,
|
||||
{
|
||||
company_id: newCompanyId,
|
||||
name: params.fiscalPeriod.name,
|
||||
period_start: params.fiscalPeriod.startDate,
|
||||
period_end: params.fiscalPeriod.endDate,
|
||||
entityType,
|
||||
companyName,
|
||||
orgNumber: params.settings.org_number as string | undefined,
|
||||
settings: params.settings,
|
||||
fiscalPeriod: params.fiscalPeriod,
|
||||
ticLookup: params.ticLookup,
|
||||
},
|
||||
{ onConflict: 'company_id,period_start,period_end' },
|
||||
() =>
|
||||
supabase.rpc('create_company_with_owner', {
|
||||
p_name: companyName,
|
||||
p_entity_type: entityType,
|
||||
p_team_id: params.teamId,
|
||||
}),
|
||||
)
|
||||
|
||||
if (periodError) {
|
||||
await rollback('fiscal period upsert failed', periodError)
|
||||
return { error: 'Kunde inte skapa räkenskapsår. Försök igen.' }
|
||||
}
|
||||
|
||||
// 5. Create the automatic tax deadlines while the onboarding data is still
|
||||
// available. Treat this as part of company creation so a new company never
|
||||
// starts in the broken state where valid settings exist without deadlines.
|
||||
try {
|
||||
await regenerateTaxDeadlinesForUser(
|
||||
supabase,
|
||||
newCompanyId,
|
||||
toDeadlineSettings(settingsToSave as Partial<CompanySettingsForDeadlines>),
|
||||
)
|
||||
} catch (deadlineError) {
|
||||
await rollback('tax deadline generation failed', deadlineError)
|
||||
return { error: 'Kunde inte skapa skattedeadlines. Försök igen.' }
|
||||
if (created.error !== undefined) {
|
||||
return { error: created.error }
|
||||
}
|
||||
const newCompanyId = created.companyId
|
||||
|
||||
// 6. Set as active company
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { normalizeOrgNumber } from '@/lib/company-lookup/normalize-org-number'
|
||||
import { normalizeVatNumber, isValidSwedishVatNumber, deriveSwedishVatNumber } from '@/lib/vat/vat-number'
|
||||
import { regenerateTaxDeadlinesForUser, toDeadlineSettings } from '@/lib/tax/deadline-generator'
|
||||
import type { CompanySettingsForDeadlines } from '@/lib/tax/deadline-config'
|
||||
import type { CompanyLookupResult } from '@/lib/company-lookup/types'
|
||||
import type { EntityType } from '@/types'
|
||||
|
||||
/**
|
||||
* The one company-creation sequence, shared by the web wizard (Server
|
||||
* Action, cookie session, create_company_with_owner), the MCP tool
|
||||
* gnubok_create_company and POST /api/v1/companies (service client,
|
||||
* create_company_for_user). Issue #1814 PR 3.
|
||||
*
|
||||
* All steps after the company row exists roll back on failure so a company
|
||||
* never survives half-configured: bookkeeping duty under BFL starts the
|
||||
* moment the tenant is real, and a company without a chart, a fiscal period
|
||||
* or its tax deadlines is worse than no company.
|
||||
*
|
||||
* The caller supplies `createCompanyRow`, the RPC call that inserts the
|
||||
* company + owner membership: which RPC is right depends on whether the
|
||||
* caller has an auth.uid() (cookie session) or an explicit owner (service
|
||||
* role). Everything else is identical.
|
||||
*/
|
||||
export interface CreateCompanyInput {
|
||||
entityType: EntityType
|
||||
companyName: string
|
||||
/** Raw org number as typed; normalised here, refused when malformed. */
|
||||
orgNumber?: string | null
|
||||
/**
|
||||
* company_settings partial to persist. UI-only and managed fields are
|
||||
* stripped here (id, user_id, company_id, timestamps, first-fiscal-year
|
||||
* helpers), so callers may pass the wizard state as-is.
|
||||
*/
|
||||
settings: Record<string, unknown>
|
||||
fiscalPeriod: { startDate: string; endDate: string; name: string }
|
||||
ticLookup?: CompanyLookupResult | null
|
||||
}
|
||||
|
||||
export type CreateCompanyResult = { companyId: string; error?: undefined } | { companyId?: undefined; error: string }
|
||||
|
||||
export const COMPANY_CREATION_ERRORS = {
|
||||
org_number_invalid: 'org_number_invalid',
|
||||
create_failed: 'Kunde inte skapa företag. Försök igen.',
|
||||
org_number_save_failed: 'Kunde inte spara organisationsnummer. Försök igen.',
|
||||
chart_failed: 'Kunde inte skapa kontoplan. Försök igen.',
|
||||
settings_failed: 'Kunde inte spara inställningar. Försök igen.',
|
||||
period_failed: 'Kunde inte skapa räkenskapsår. Försök igen.',
|
||||
deadlines_failed: 'Kunde inte skapa skattedeadlines. Försök igen.',
|
||||
} as const
|
||||
|
||||
export async function createCompanyCore(
|
||||
supabase: SupabaseClient,
|
||||
input: CreateCompanyInput,
|
||||
createCompanyRow: () => PromiseLike<{ data: unknown; error: unknown }>,
|
||||
): Promise<CreateCompanyResult> {
|
||||
// Org-number format validation. We intentionally do NOT enforce
|
||||
// uniqueness: the same org number may legitimately appear on multiple
|
||||
// companies (a separate test copy of your real company, or a consultant
|
||||
// and the owner each tracking the same entity). Tenant isolation
|
||||
// (RLS + company_id) is the real boundary, not org-number uniqueness.
|
||||
//
|
||||
// normalizeOrgNumber returns null for malformed input: we refuse rather
|
||||
// than storing a value that would break SIE/SRU exports later.
|
||||
const rawOrgNumber = input.orgNumber ?? undefined
|
||||
const cleanedOrgNumber = normalizeOrgNumber(rawOrgNumber)
|
||||
if (rawOrgNumber && rawOrgNumber.trim() && !cleanedOrgNumber) {
|
||||
return { error: COMPANY_CREATION_ERRORS.org_number_invalid }
|
||||
}
|
||||
|
||||
// 1. Create company + owner membership atomically via RPC
|
||||
const { data: newCompanyIdRaw, error: companyError } = await createCompanyRow()
|
||||
const newCompanyId = typeof newCompanyIdRaw === 'string' ? newCompanyIdRaw : null
|
||||
|
||||
if (companyError || !newCompanyId) {
|
||||
console.error('[createCompany] company creation failed', companyError)
|
||||
return { error: COMPANY_CREATION_ERRORS.create_failed }
|
||||
}
|
||||
|
||||
// Helper: roll back the company if a subsequent step fails. Deletes in FK
|
||||
// order. Each delete is error-checked so a failed cleanup leaves a trace
|
||||
// instead of silently stranding partial company data behind a generic
|
||||
// "try again" message.
|
||||
const rollback = async (reason: string, err: unknown) => {
|
||||
console.error(`[createCompany] rolling back ${newCompanyId}: ${reason}`, err)
|
||||
const deletions: Array<[table: string, run: () => PromiseLike<{ error: unknown }>]> = [
|
||||
['company_settings', () => supabase.from('company_settings').delete().eq('company_id', newCompanyId)],
|
||||
['fiscal_periods', () => supabase.from('fiscal_periods').delete().eq('company_id', newCompanyId)],
|
||||
['chart_of_accounts', () => supabase.from('chart_of_accounts').delete().eq('company_id', newCompanyId)],
|
||||
['company_members', () => supabase.from('company_members').delete().eq('company_id', newCompanyId)],
|
||||
['companies', () => supabase.from('companies').delete().eq('id', newCompanyId)],
|
||||
]
|
||||
for (const [table, run] of deletions) {
|
||||
const { error: deleteError } = await run()
|
||||
if (deleteError) {
|
||||
console.error(
|
||||
`[createCompany] rollback delete failed for ${table} (company ${newCompanyId})`,
|
||||
deleteError,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mirror the normalized org_number onto the companies row so future
|
||||
// duplicate checks and cross-references are reliable. MUST be error-checked
|
||||
// and rolled back on failure: otherwise the freshly-created company would
|
||||
// exist without an org_number and the duplicate guard would never match it
|
||||
// for any future user (the very guard this code is enforcing).
|
||||
if (cleanedOrgNumber) {
|
||||
const { error: orgUpdateError } = await supabase
|
||||
.from('companies')
|
||||
.update({ org_number: cleanedOrgNumber })
|
||||
.eq('id', newCompanyId)
|
||||
if (orgUpdateError) {
|
||||
await rollback('org_number update failed', orgUpdateError)
|
||||
return { error: COMPANY_CREATION_ERRORS.org_number_save_failed }
|
||||
}
|
||||
}
|
||||
|
||||
// Persist whatever lookup data the caller already gathered. Do NOT call
|
||||
// /profile here: that handler fans out to 13 Lens calls and the 5 s
|
||||
// timeout in tic-fetch.ts ate ~530 wasted calls in May before yielding
|
||||
// zero snapshots (every signup's /profile timed out, but the in-flight
|
||||
// upstream fetches still counted against quota). The agent build path
|
||||
// (app/(onboarding)/onboarding/agent/page.tsx) calls ensureTicSnapshot
|
||||
// with upgradeV1: true lazily, which is the right place: only companies
|
||||
// that actually reach agent onboarding spend the budget.
|
||||
if (input.ticLookup) {
|
||||
const { error: ticErr } = await supabase
|
||||
.from('companies')
|
||||
.update({
|
||||
tic_snapshot: input.ticLookup,
|
||||
tic_snapshot_fetched_at: new Date().toISOString(),
|
||||
})
|
||||
.eq('id', newCompanyId)
|
||||
if (ticErr) {
|
||||
console.warn('[createCompany] tic snapshot persist failed', ticErr)
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Seed chart of accounts
|
||||
const { error: coaError } = await supabase.rpc('seed_chart_of_accounts', {
|
||||
p_company_id: newCompanyId,
|
||||
p_entity_type: input.entityType,
|
||||
})
|
||||
if (coaError) {
|
||||
await rollback('COA seeding failed', coaError)
|
||||
return { error: COMPANY_CREATION_ERRORS.chart_failed }
|
||||
}
|
||||
|
||||
// 3. Save settings (strip UI-only and managed fields)
|
||||
const {
|
||||
id: _id,
|
||||
user_id: _uid,
|
||||
company_id: _cid,
|
||||
created_at: _ca,
|
||||
updated_at: _ua,
|
||||
is_first_fiscal_year: _ify,
|
||||
first_year_start: _fys,
|
||||
first_year_end: _fye,
|
||||
...settingsToSave
|
||||
} = input.settings
|
||||
|
||||
// Defence in depth: this upsert bypasses UpdateSettingsSchema, so never persist
|
||||
// a VAT number blind. Normalise to the canonical SE+12 form; if it isn't
|
||||
// structurally valid (e.g. the legacy SE+14 personnummer derivation), re-derive
|
||||
// it from the org number, falling back to null rather than storing a malformed
|
||||
// momsregistreringsnummer.
|
||||
if (typeof settingsToSave.vat_number === 'string' && settingsToSave.vat_number) {
|
||||
const normalized = normalizeVatNumber(settingsToSave.vat_number)
|
||||
settingsToSave.vat_number = isValidSwedishVatNumber(normalized)
|
||||
? normalized
|
||||
: deriveSwedishVatNumber(settingsToSave.org_number as string | null | undefined)
|
||||
}
|
||||
|
||||
const { error: settingsError } = await supabase
|
||||
.from('company_settings')
|
||||
.upsert(
|
||||
{
|
||||
...settingsToSave,
|
||||
company_id: newCompanyId,
|
||||
onboarding_complete: true,
|
||||
onboarding_step: 4,
|
||||
},
|
||||
{ onConflict: 'company_id' },
|
||||
)
|
||||
|
||||
if (settingsError) {
|
||||
await rollback('settings upsert failed', settingsError)
|
||||
return { error: COMPANY_CREATION_ERRORS.settings_failed }
|
||||
}
|
||||
|
||||
// 4. Create fiscal period
|
||||
const { error: periodError } = await supabase.from('fiscal_periods').upsert(
|
||||
{
|
||||
company_id: newCompanyId,
|
||||
name: input.fiscalPeriod.name,
|
||||
period_start: input.fiscalPeriod.startDate,
|
||||
period_end: input.fiscalPeriod.endDate,
|
||||
},
|
||||
{ onConflict: 'company_id,period_start,period_end' },
|
||||
)
|
||||
|
||||
if (periodError) {
|
||||
await rollback('fiscal period upsert failed', periodError)
|
||||
return { error: COMPANY_CREATION_ERRORS.period_failed }
|
||||
}
|
||||
|
||||
// 5. Create the automatic tax deadlines while the onboarding data is still
|
||||
// available. Treat this as part of company creation so a new company never
|
||||
// starts in the broken state where valid settings exist without deadlines.
|
||||
try {
|
||||
await regenerateTaxDeadlinesForUser(
|
||||
supabase,
|
||||
newCompanyId,
|
||||
toDeadlineSettings(settingsToSave as Partial<CompanySettingsForDeadlines>),
|
||||
)
|
||||
} catch (deadlineError) {
|
||||
await rollback('tax deadline generation failed', deadlineError)
|
||||
return { error: COMPANY_CREATION_ERRORS.deadlines_failed }
|
||||
}
|
||||
|
||||
return { companyId: newCompanyId }
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import { z } from 'zod'
|
||||
import { saneIsoDateSchema } from '@/lib/invariants/zod'
|
||||
import { computeFiscalPeriod } from '@/lib/company/compute-fiscal-period'
|
||||
import { normalizeOrgNumber } from '@/lib/company-lookup/normalize-org-number'
|
||||
import { deriveSwedishVatNumber } from '@/lib/vat/vat-number'
|
||||
import type { CreateCompanyInput } from '@/lib/company/create-company'
|
||||
|
||||
/**
|
||||
* Typed company-setup input for the agent and API creation paths (the MCP
|
||||
* tool gnubok_create_company and POST /api/v1/companies, issue #1814 PR 3),
|
||||
* turned into the same `settings` + `fiscalPeriod` shape the web wizard
|
||||
* hands to createCompanyCore. One schema, one builder, so the two
|
||||
* programmatic paths cannot drift from each other or from the wizard.
|
||||
*
|
||||
* Compliance rules that must never be skipped: a VAT-registered company
|
||||
* needs a moms_period and an org_number (the invoice momsregistreringsnummer
|
||||
* derives from it), F-skatt is stated explicitly rather than assumed, and an
|
||||
* enskild firma stays on the calendar year even in its first year. Chief
|
||||
* among them, the moms_period: a VAT-registered company
|
||||
* needs a moms_period. Without it the deadline engine silently generates
|
||||
* ZERO VAT deadlines (lib/tax/deadline-config.ts conditions all require a
|
||||
* concrete period), which reads as "no VAT duty" to everyone downstream.
|
||||
* The schema refuses the combination instead of warning.
|
||||
*/
|
||||
export const CompanySetupSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1).max(200),
|
||||
entity_type: z.enum(['enskild_firma', 'aktiebolag']),
|
||||
org_number: z.string().trim().min(1).max(20).optional(),
|
||||
vat_registered: z.boolean(),
|
||||
moms_period: z.enum(['monthly', 'quarterly', 'yearly']).nullable().optional(),
|
||||
accounting_method: z.enum(['accrual', 'cash']),
|
||||
/** Godkänd för F-skatt. Explicit on purpose: never assumed (SE-R-005 risk). */
|
||||
f_skatt: z.boolean(),
|
||||
/** 1-12. Ignored for enskild firma (always calendar year). */
|
||||
fiscal_year_start_month: z.number().int().min(1).max(12).optional(),
|
||||
/**
|
||||
* First fiscal year of a newly formed company (BFL 3 kap.): may be
|
||||
* shorter or longer than 12 months. Both dates YYYY-MM-DD.
|
||||
*/
|
||||
first_fiscal_year: z
|
||||
.object({
|
||||
start: saneIsoDateSchema,
|
||||
end: saneIsoDateSchema,
|
||||
})
|
||||
.optional(),
|
||||
address_line1: z.string().trim().max(200).optional(),
|
||||
postal_code: z.string().trim().max(20).optional(),
|
||||
city: z.string().trim().max(100).optional(),
|
||||
/** Team (byrå) to attach the company to. Defaults to the caller's own team. */
|
||||
team_id: z.string().uuid().optional(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (value.vat_registered && !value.moms_period) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['moms_period'],
|
||||
message:
|
||||
'moms_period is required when vat_registered is true: without it no VAT deadlines are generated (silent misconfiguration).',
|
||||
})
|
||||
}
|
||||
if (!value.vat_registered && value.moms_period) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['moms_period'],
|
||||
message: 'moms_period must be omitted when the company is not VAT-registered.',
|
||||
})
|
||||
}
|
||||
if (value.vat_registered && !value.org_number) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['org_number'],
|
||||
message:
|
||||
'org_number is required for a VAT-registered company: the momsregistreringsnummer on every invoice is derived from it (ML 17 kap 24 §).',
|
||||
})
|
||||
}
|
||||
if (
|
||||
value.entity_type === 'enskild_firma' &&
|
||||
value.first_fiscal_year &&
|
||||
!value.first_fiscal_year.end.endsWith('-12-31')
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['first_fiscal_year', 'end'],
|
||||
message:
|
||||
'An enskild firma always closes its fiscal year on 31 December (BFL 3 kap. 1 §): the first year may be shorter or up to 18 months, but must end on 12-31.',
|
||||
})
|
||||
}
|
||||
if (value.org_number && normalizeOrgNumber(value.org_number) === null) {
|
||||
ctx.addIssue({
|
||||
code: 'custom',
|
||||
path: ['org_number'],
|
||||
message: 'org_number is not a valid Swedish organisationsnummer.',
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
export type CompanySetup = z.infer<typeof CompanySetupSchema>
|
||||
|
||||
export type CompanySetupPlan =
|
||||
| {
|
||||
ok: true
|
||||
input: Omit<CreateCompanyInput, 'ticLookup'>
|
||||
/** What the fiscal period resolved to, for previews. */
|
||||
fiscalPeriod: { startDate: string; endDate: string; name: string }
|
||||
}
|
||||
| { ok: false; error: string }
|
||||
|
||||
/**
|
||||
* Resolve validated setup input into the creation payload. The only failure
|
||||
* left at this point is an invalid fiscal period (validatePeriodDuration).
|
||||
*/
|
||||
export function planCompanySetup(setup: CompanySetup): CompanySetupPlan {
|
||||
const isEf = setup.entity_type === 'enskild_firma'
|
||||
const firstYear = setup.first_fiscal_year
|
||||
const startMonth = isEf ? 1 : (setup.fiscal_year_start_month ?? 1)
|
||||
|
||||
const settings: Record<string, unknown> = {
|
||||
entity_type: setup.entity_type,
|
||||
company_name: setup.name,
|
||||
org_number: setup.org_number ? normalizeOrgNumber(setup.org_number) : null,
|
||||
vat_registered: setup.vat_registered,
|
||||
vat_number: setup.vat_registered ? deriveSwedishVatNumber(setup.org_number ?? null) : null,
|
||||
moms_period: setup.vat_registered ? setup.moms_period ?? null : null,
|
||||
accounting_method: setup.accounting_method,
|
||||
f_skatt: setup.f_skatt,
|
||||
// Enskild firma is calendar-year by law, with or without a first year.
|
||||
fiscal_year_start_month: isEf ? 1 : firstYear ? nextMonthAfter(firstYear.end) : startMonth,
|
||||
...(setup.address_line1 ? { address_line1: setup.address_line1 } : {}),
|
||||
...(setup.postal_code ? { postal_code: setup.postal_code } : {}),
|
||||
...(setup.city ? { city: setup.city } : {}),
|
||||
// Wizard helpers consumed by computeFiscalPeriod and stripped by
|
||||
// createCompanyCore before the settings upsert.
|
||||
is_first_fiscal_year: Boolean(firstYear),
|
||||
first_year_start: firstYear?.start,
|
||||
first_year_end: firstYear?.end,
|
||||
}
|
||||
|
||||
const period = computeFiscalPeriod(settings)
|
||||
if (period.error) {
|
||||
return { ok: false, error: period.error }
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
input: {
|
||||
entityType: setup.entity_type,
|
||||
companyName: setup.name,
|
||||
orgNumber: setup.org_number,
|
||||
settings,
|
||||
fiscalPeriod: { startDate: period.startStr, endDate: period.endStr, name: period.periodName },
|
||||
},
|
||||
fiscalPeriod: { startDate: period.startStr, endDate: period.endStr, name: period.periodName },
|
||||
}
|
||||
}
|
||||
|
||||
/** The fiscal_year_start_month implied by a first fiscal year ending in `end`. */
|
||||
function nextMonthAfter(end: string): number {
|
||||
const endMonth = Number(end.split('-')[1])
|
||||
if (!Number.isInteger(endMonth) || endMonth < 1 || endMonth > 12) return 1
|
||||
return endMonth === 12 ? 1 : endMonth + 1
|
||||
}
|
||||
@@ -22,6 +22,9 @@ const DISPATCH_ONLY_MCP_TOOLS = new Set<string>([
|
||||
'gnubok_upload_document',
|
||||
'gnubok_create_document_upload',
|
||||
'gnubok_complete_document_upload',
|
||||
// Onboarding connect-link tools: read status + hand out a browser link; no commit counterpart.
|
||||
'gnubok_connect_bank',
|
||||
'gnubok_connect_skatteverket',
|
||||
])
|
||||
|
||||
describe('MCP_TOOL_CAPABILITY_MAP', () => {
|
||||
@@ -30,6 +33,8 @@ describe('MCP_TOOL_CAPABILITY_MAP', () => {
|
||||
gnubok_send_invoice: CAPABILITY.email_send,
|
||||
gnubok_vat_declaration_submit: CAPABILITY.skatteverket,
|
||||
gnubok_agi_submit: CAPABILITY.skatteverket,
|
||||
gnubok_connect_bank: CAPABILITY.bank_sync,
|
||||
gnubok_connect_skatteverket: CAPABILITY.skatteverket,
|
||||
// Dispatch-only AI tools: inline Bedrock OCR, no staged operation. The
|
||||
// signed-URL pair is gated at create AND complete so a free-tier key can
|
||||
// neither reserve nor finalize a paid extraction.
|
||||
|
||||
@@ -89,6 +89,9 @@ export const MCP_TOOL_CAPABILITY_MAP: Readonly<Partial<Record<string, Capability
|
||||
gnubok_send_invoice: CAPABILITY.email_send,
|
||||
gnubok_vat_declaration_submit: CAPABILITY.skatteverket,
|
||||
gnubok_agi_submit: CAPABILITY.skatteverket,
|
||||
// Onboarding connect-link tools (issue #1814): gated like the links' targets.
|
||||
gnubok_connect_bank: CAPABILITY.bank_sync,
|
||||
gnubok_connect_skatteverket: CAPABILITY.skatteverket,
|
||||
// AI document OCR (Bedrock): the inbox's paid extraction, reachable via MCP.
|
||||
gnubok_create_document_upload: CAPABILITY.ai,
|
||||
gnubok_complete_document_upload: CAPABILITY.ai,
|
||||
|
||||
Reference in New Issue
Block a user