Files
accounted/lib/company/onboarding-input.ts
T
31e0cd6e05 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>
2026-08-25 12:41:02 +02:00

163 lines
6.6 KiB
TypeScript

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
}