26e29f47bc
* feat(company): ideell förening as a third legal form, behind a flag (#2072 step 1) Why the problem occurred: the legal form was modelled as a binary flag in ~300 files. `EntityType` was a two-member union, but nothing dispatched on it exhaustively: 28 sites defaulted `?? 'enskild_firma'` (invoice, categorize, match, stripe, invoice-inbox) or `?? 'aktiebolag'` (year-end, bokslut, MCP), and every form-dependent choice was an `=== 'aktiebolag' ? A : B` ternary. Widening the union compiled everywhere and changed nothing, so a förening would have booked as an enskild firma in the app and as an aktiebolag in bokslut and MCP, with no error anywhere. The lookup refused föreningar at the door (mapEntityType returned null), which is what the tester hit. What was removed or simplified: the silent defaults. One module, lib/company/entity-type.ts, now holds the list (ENTITY_TYPES), the parser (never defaults), the resolver (settings hint, then companies.entity_type, then throw) and `byEntityType`, whose Record arms make the compiler refuse the next widening until each site has an answer. The form-dependent facts (closing account, owner settlement account, calendar-year lock, default method, K1/K2 label, personnummer vs 16-prefix) live there once instead of in the ternaries. On the SQL side supported_entity_types() replaces four copies of the literal list in the create RPCs. Why this shape and not the proposed one: the tracker asked for the enum widening plus a chart; that alone was the dangerous version (compiles, books wrong). Bundling stiftelse was considered and dropped: identical plumbing but no chart block. Creation sits behind NEXT_PUBLIC_IDEELL_FORENING_ENABLED so the CHECK, RPCs and seed can ship now and the first partner is switched on without a migration; the flag goes when Phase 2 (packs, INK3, årsbokslut, Swish) lands on the tracker. Domain choices (DECISIONS.md 2026-09-08, verify with an accountant before Phase 2): result closes to 2069 with 2068 as prior-year carry; no owner accounts, member settlement on 2890; accrual default; brutet räkenskapsår allowed; K1 label for the 5 000 kr accrual threshold (BFNAR 2010:1); org number gets the 16 prefix. Migration 20260908110835 widens the three CHECK constraints, adds supported_entity_types(), re-creates the three create RPCs with the widened guard and adds the förening block to seed_chart_of_accounts. Applied to staging and covered by ideell-forening-entity-type.pg.test.ts. Part of #2072 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh * fix(company): close the förening paths the skeptic refuted (#2072) Five refutations from the /skeptic pass on 7a05c54d2, each fixed at the shared definition rather than the reported site: 1. Privately paid supplier invoices and the utlägg dialog resolved the owner account in lib/expenses/payer.ts with its own AB/EF ternary, so a förening member's invoice was built on 2893 and then refused by the expense-claim service (which already said 2890), burning an ankomstnummer. The helper now uses ownerSettlementAccount. 2. Booking templates substitute their `_ab` accounts only for an aktiebolag; the `private_expense` template kept its base 2013 for a förening. Template accounts now resolve through templateAccountForForm: EF base, AB override, förening base with owner accounts translated to 2890 (booking-templates.ts and proposal-lines.ts share it). 3. A VAT-registered förening with helårsmoms got no momsdeklaration deadline: the annual VAT rule bailed on anything but AB/EF. A förening is a juridisk person and follows the räkenskapsår schedule (SFL 26 kap 33 §), so the rule now keys on fiscalYearLockedToCalendar instead of the two literals; same in the MCP VAT report. 4. 2069 would have accumulated across years: the year-open omföring was AB-only with 2099/2098 hard-coded. planResultAppropriation now takes the pair from resultClosingAccounts (AB 2099 -> 2098, förening 2069 -> 2068) and skips forms with no carry (EF). 5. With the flag off, a registry lookup that returned "Ideell förening" was prefilled into the onboarding journey, the form picker was skipped and the create step answered "Ogiltig företagsform" with no way back. The journey, the BankID picker, the onboarding page and the MCP lookup now use mapSetupEntityType, which maps only creatable forms, so a flagged-off form falls through to the picker as before. Also: form picker keeps its AB-first order; tests for each fix. Part of #2072 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh * chore(migrations): move ideell förening migration after main's latest version (20260908143051) Two migrations landed on main after the branch forked; a lower version would be skipped by the merge-time apply. Staging history row renamed to match. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh * chore(skills): regenerate accounted-api reference for the widened entity_type enum Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
255 lines
8.9 KiB
TypeScript
255 lines
8.9 KiB
TypeScript
'use client'
|
|
|
|
import { useMemo, useState } from 'react'
|
|
import { useRouter } from 'next/navigation'
|
|
import { useTranslations } from 'next-intl'
|
|
import Link from 'next/link'
|
|
import { Loader2 } from 'lucide-react'
|
|
import { AttnLine } from '@/components/ui/attn-line'
|
|
import { useToast } from '@/components/ui/use-toast'
|
|
import { switchCompany } from '@/lib/company/actions'
|
|
import { mapEntityType, mapSetupEntityType } from '@/lib/company-lookup/entity-type-map'
|
|
import { ENTITY_TYPE_LABELS_SV, isEntityType } from '@/lib/company/entity-type'
|
|
import type { EnrichmentCompanyRole } from '@/lib/company-lookup/types'
|
|
import { getBranding } from '@/lib/branding/service'
|
|
import '@/components/onboarding/journey/journey.css'
|
|
|
|
const branding = getBranding()
|
|
|
|
/**
|
|
* BankID company picker, restyled to the journey's searchable list
|
|
* (founder decision 2026-07-24: the list is the standard at ANY count).
|
|
* The contract is unchanged: picking a CompanyRoles engagement routes to
|
|
* /onboarding?org_number=… (one Lens lookup happens there, on pick);
|
|
* member companies switch + open directly. The roster itself is free
|
|
* CompanyRoles data: this page never calls TIC.
|
|
*/
|
|
|
|
export interface MemberCompany {
|
|
id: string
|
|
name: string
|
|
orgNumber: string | null
|
|
entityType: string | null
|
|
role: string
|
|
}
|
|
|
|
export interface TicPickerCompany {
|
|
role: EnrichmentCompanyRole
|
|
/** 'new' = not in Accounted, can set up. 'exists' = in Accounted but user is not a member. */
|
|
status: 'new' | 'exists'
|
|
}
|
|
|
|
interface BankIdCompanyPickerProps {
|
|
firstName: string | null
|
|
teamId: string
|
|
memberCompanies: MemberCompany[]
|
|
ticCompanies: TicPickerCompany[]
|
|
enrichmentStale: boolean
|
|
/** A pending invitation exists for this email but no invite token is at
|
|
* hand: point the user back to the link in the invitation email. */
|
|
hasPendingInvite?: boolean
|
|
}
|
|
|
|
type SetupState = { kind: 'idle' } | { kind: 'opening'; companyId: string }
|
|
|
|
// Swedish legal entity names (Aktiebolag, Enskild firma, etc.) are statutory
|
|
// terms: kept in Swedish in both locales.
|
|
function humanEntityType(t: string | null | undefined): string {
|
|
if (!t) return ''
|
|
if (isEntityType(t)) return ENTITY_TYPE_LABELS_SV[t]
|
|
return t
|
|
}
|
|
|
|
function humanTicEntityType(t: string): string {
|
|
const mapped = mapEntityType(t)
|
|
if (mapped) return ENTITY_TYPE_LABELS_SV[mapped]
|
|
if (t.toLowerCase().includes('handelsbolag') || t.toLowerCase() === 'hb') return 'Handelsbolag'
|
|
if (t.toLowerCase().includes('kommanditbolag') || t.toLowerCase() === 'kb') return 'Kommanditbolag'
|
|
return t
|
|
}
|
|
|
|
function positionLabel(role: EnrichmentCompanyRole): string {
|
|
const descs = role.positionDescriptions?.filter(Boolean)
|
|
if (descs && descs.length > 0) return descs.join(' · ')
|
|
const types = role.positionTypes?.filter(Boolean)
|
|
if (types && types.length > 0) return types.join(' · ')
|
|
return ''
|
|
}
|
|
|
|
export default function BankIdCompanyPicker({
|
|
firstName,
|
|
memberCompanies,
|
|
ticCompanies,
|
|
enrichmentStale,
|
|
hasPendingInvite = false,
|
|
}: BankIdCompanyPickerProps) {
|
|
const router = useRouter()
|
|
const { toast } = useToast()
|
|
const t = useTranslations('select_company')
|
|
const [setup, setSetup] = useState<SetupState>({ kind: 'idle' })
|
|
const [query, setQuery] = useState('')
|
|
|
|
const hour = new Date().getHours()
|
|
const greeting = hour < 5 ? t('greeting_night') : hour < 10 ? t('greeting_morning') : hour < 14 ? t('greeting_hello') : hour < 18 ? t('greeting_afternoon') : t('greeting_evening')
|
|
|
|
const busy = setup.kind !== 'idle'
|
|
|
|
const q = query.trim().toLowerCase()
|
|
const filteredTic = useMemo(
|
|
() =>
|
|
ticCompanies.filter(
|
|
({ role }) =>
|
|
!q ||
|
|
role.legalName.toLowerCase().includes(q) ||
|
|
role.companyRegistrationNumber.replace(/[\s-]/g, '').includes(q.replace(/[\s-]/g, '')),
|
|
),
|
|
[ticCompanies, q],
|
|
)
|
|
const filteredMembers = useMemo(
|
|
() =>
|
|
memberCompanies.filter(
|
|
(c) =>
|
|
!q ||
|
|
c.name.toLowerCase().includes(q) ||
|
|
(c.orgNumber ?? '').replace(/[\s-]/g, '').includes(q.replace(/[\s-]/g, '')),
|
|
),
|
|
[memberCompanies, q],
|
|
)
|
|
|
|
async function handleOpenMember(companyId: string) {
|
|
if (busy) return
|
|
setSetup({ kind: 'opening', companyId })
|
|
const result = await switchCompany(companyId)
|
|
if (result.error) {
|
|
toast({
|
|
title: t(result.error === 'not_member' ? 'error_no_access' : 'error_switch_failed'),
|
|
variant: 'destructive',
|
|
})
|
|
setSetup({ kind: 'idle' })
|
|
return
|
|
}
|
|
window.location.assign('/')
|
|
}
|
|
|
|
// Every engagement pick routes to the journey with the orgnr; the journey
|
|
// runs ONE Lens lookup on arrival and prefills facts (plan addendum
|
|
// 2026-07-24). CompanyRoles itself is on the Identity API: separate quota.
|
|
function handleCreateFromTic(role: EnrichmentCompanyRole) {
|
|
if (busy) return
|
|
const orgNumber = role.companyRegistrationNumber.replace(/[\s-]/g, '')
|
|
router.push(`/onboarding?org_number=${encodeURIComponent(orgNumber)}`)
|
|
}
|
|
|
|
function onSearchEnter() {
|
|
if (filteredTic.length === 1) handleCreateFromTic(filteredTic[0].role)
|
|
}
|
|
|
|
return (
|
|
<div className="stagger-enter">
|
|
<header className="mb-8 text-center">
|
|
<h1 className="font-display text-2xl md:text-3xl tracking-tight">
|
|
{greeting}{firstName ? `, ${firstName}` : ''}
|
|
</h1>
|
|
<p className="text-muted-foreground text-sm mt-1.5">{t('subtitle')}</p>
|
|
</header>
|
|
|
|
{hasPendingInvite && (
|
|
<div className="mb-6 rounded-lg border bg-muted/30 p-3">
|
|
<p className="text-sm text-muted-foreground text-center">
|
|
{t('pending_invite_note')}
|
|
</p>
|
|
</div>
|
|
)}
|
|
|
|
{enrichmentStale && (
|
|
<AttnLine className="mb-6">{t('enrichment_stale')}</AttnLine>
|
|
)}
|
|
|
|
<div className="jny-biginput jny-filter" style={{ margin: '0 auto' }}>
|
|
<input
|
|
value={query}
|
|
placeholder={t('search_placeholder')}
|
|
aria-label={t('search_placeholder')}
|
|
autoComplete="off"
|
|
autoFocus
|
|
onChange={(e) => setQuery(e.target.value)}
|
|
onKeyDown={(e) => e.key === 'Enter' && onSearchEnter()}
|
|
/>
|
|
</div>
|
|
|
|
<div className="jny-rowlist" style={{ maxHeight: '52vh' }}>
|
|
{filteredTic.map(({ role, status }) => {
|
|
const cleaned = role.companyRegistrationNumber.replace(/[\s-]/g, '')
|
|
const position = positionLabel(role)
|
|
const entityLabel = humanTicEntityType(role.legalEntityType)
|
|
const mappable = mapSetupEntityType(role.legalEntityType) !== null
|
|
const metaParts = [entityLabel, position].filter(Boolean)
|
|
if (!mappable) metaParts.push(t('setup_manually'))
|
|
if (status === 'exists') {
|
|
metaParts.push(t('already_in_app', { appName: branding.appName.toLowerCase() }))
|
|
}
|
|
return (
|
|
<button
|
|
key={cleaned}
|
|
type="button"
|
|
className="jny-rowpick"
|
|
disabled={busy}
|
|
onClick={() => handleCreateFromTic(role)}
|
|
>
|
|
<span className="jny-rleft">
|
|
<span className="jny-rname">{role.legalName}</span>
|
|
<span className="jny-rmeta">{metaParts.join(' · ')}</span>
|
|
</span>
|
|
<span className="jny-rorg">{role.companyRegistrationNumber}</span>
|
|
</button>
|
|
)
|
|
})}
|
|
|
|
{filteredMembers.length > 0 && (
|
|
<div className="jny-rowsec">
|
|
{t('section_your_companies', { appName: branding.appName.toLowerCase() })}
|
|
</div>
|
|
)}
|
|
{filteredMembers.map((c) => {
|
|
const isOpening = setup.kind === 'opening' && setup.companyId === c.id
|
|
return (
|
|
<button
|
|
key={c.id}
|
|
type="button"
|
|
className="jny-rowpick is-existing"
|
|
disabled={busy}
|
|
onClick={() => handleOpenMember(c.id)}
|
|
>
|
|
<span className="jny-rleft">
|
|
<span className="jny-rname">{c.name}</span>
|
|
<span className="jny-rmeta">
|
|
{[humanEntityType(c.entityType), c.role !== 'owner' ? c.role : '']
|
|
.filter(Boolean)
|
|
.join(' · ') || t('opens_directly')}
|
|
</span>
|
|
</span>
|
|
<span className="jny-rorg">
|
|
{isOpening ? <Loader2 className="h-4 w-4 animate-spin" /> : c.orgNumber ?? ''}
|
|
</span>
|
|
</button>
|
|
)
|
|
})}
|
|
|
|
{filteredTic.length === 0 && filteredMembers.length === 0 && (
|
|
<div className="jny-rownote">
|
|
{ticCompanies.length + memberCompanies.length === 0
|
|
? t('no_companies_found')
|
|
: t('no_search_matches')}
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<div className="mt-6 text-center">
|
|
<Link href="/onboarding" className="jny-btn-quiet" style={{ textDecoration: 'none' }}>
|
|
{t('add_company_manually')} …
|
|
</Link>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|