Files
accounted/app/(onboarding)/select-company/page.tsx
T
c0a106e591 feat(ux): Bucket A defaults pass: remove choices the system already knows the answer to (#1443)
* feat(booking): batch VAT seeds from category default, period derives from entry date

BatchCategorySelector and BulkBookInboxDialog hardcoded standard_25 as the
initial VAT treatment, overriding the server's per-category derivation and
claiming 25% moms on VAT-exempt bank fees. Both now default to an explicit
'Enligt kategori' option that omits vat_treatment so the server derives it
(exempt bank/card fees, 12% representation). Reverse charge is never derived.

The embedded JournalEntryForm period Select is replaced by the same derived
read-only text the standalone variant already uses: the period is a total
function of the entry date, and the Select allowed picking a period that
disagreed with it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(booking): prefill cost account from counterparty history; period text in Bokfor direkt

BookDirectlyDialog and the supplier-invoice form left the cost account
deliberately blank even when the company's own confirmed history for the
counterparty (categorization_templates) or supplier.default_expense_account
knew the answer. Both now prefill from a counterparty-template hit (new
?counterparty= single-match mode on the settings route, same tiered matcher
as the booking flows), only into still-empty fields, only from expense-shaped
templates, with a provenance line. No generic fallback: a miss leaves the
field blank exactly as before.

Bokfor direkt's period Select is replaced by text derived from the entry
date; the silent periods[0] fallback becomes a blocking explanation, since
borrowing an arbitrary period could book into the wrong one.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(ux): single-company login skips the picker; filing surfaces default to filable periods

/select-company auto-forwards when the user is a member of exactly one
company with nothing else to decide (no new TIC engagements, no pending
invite, enrichment fresh); the in-app 'Lagg till foretag' links pass
?choose=1 to keep the picker deliberately reachable. Byra/multi-company
users are untouched.

The VAT declaration now opens on the most recently ENDED month/quarter
(lib/vat/period-defaults, tested) instead of the current one, which can
never be filed and forced a step-back click on every filing visit; the
periodicity switch resets the same way. Helarsmoms FyPicker gains
preferLatestEnded and opens on the latest ended rakenskapsar instead of
the newest started one.

The 'momsperiod saknas' dead end now collects the answer inline through
the same PUT /api/settings validation instead of bouncing to settings:
until the period exists the deadline engine generates zero VAT deadlines,
silently, so every extra hop kept a compliance hole open.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(granskning): approve pill commits directly for low and medium risk

The Godkann pill on /pending only opened a ConfirmationDialog demanding a
second Godkann, regardless of tier. The review row already states source,
title and risk and offers Detaljer, so for low/medium the pill now commits
directly; high risk keeps the dialog, whose warning sentence carries
information the row does not. Chat-side bulk approve is deferred: it needs
ApprovalCard's state lifted (assistant-redesign seam 8.8), see DECISIONS.md.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(reports): map inline momsperiod save errors through getErrorMessage

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(review): repair the dead login auto-forward and nine review findings

The big one: setActiveCompany ends with a cookie write that throws during
Server Component render (sealed cookie store), so the /select-company
auto-forward silently never fired; the write is now best-effort since the
cookie is write-only compat and the DB write is already verified.

Also: supplier-switch un-plants history-prefilled accounts so the new
supplier's own default applies; prefill routes through handleAccountChange
so konto default moms rides along; batch 'Ingen moms' books exempt instead
of the derived 25%; monthly VAT default tracks the actual 12th/17th filing
deadline (over-40M stays M-1); inline momsperiod setup uses EmptyState,
gates on vat_number (the PUT would 400 without it), keeps keyboard focus
and announces errors; cost-account shape guard tightened to P&L accounts;
attn tone on the new warning lines.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* ci: retrigger workflows; the Actions outage swallowed the rebase push event

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* ci: retrigger after outage (events dropped, not delayed)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* ci: retrigger after GitHub Actions recovery

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(review): address CodeRabbit and compliance-bot findings

Direct commit now prunes the op from the bulk selection (a stale id kept
inflating the bulk bar and rode into bulk-commit) and the detail-panel
Godkann gets the same risk gate as the row pill. The automatic account
fill in the supplier-invoice form is requested, not applied inline: the
applying effect waits for both the BAS chart and the request with fresh
closures, so a fill can no longer land before the chart and leave a
VAT-free konto on the 25% row default. Test dates use local-time
constructors (ISO strings parse as UTC midnight and shift a day in
negative-offset timezones). Stale ML 11 kap citation dropped from a
comment.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* ci: retrigger; push event dropped again

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 10:16:23 +02:00

225 lines
7.8 KiB
TypeScript

import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
import { createClient, createServiceClient } from '@/lib/supabase/server'
import { setActiveCompany } from '@/lib/company/context'
import {
acceptPendingInviteByToken,
hasPendingInviteForEmail,
} from '@/lib/company/pending-invites'
import type { EnrichmentCompanyRole } from '@/lib/company-lookup/types'
import BankIdCompanyPicker, {
type MemberCompany,
type TicPickerCompany,
} from '@/components/onboarding/BankIdCompanyPicker'
export const dynamic = 'force-dynamic'
const ENRICHMENT_TTL_DAYS = 7
export default async function SelectCompanyPage({
searchParams,
}: {
searchParams: Promise<{ choose?: string }>
}) {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
redirect('/login')
}
// Invite recovery, same as /onboarding: BankID users land here, so a missed
// invite acceptance (e.g. a register flow that dropped the cookie handling)
// gets retried before the picker funnels the invitee into creating a company.
const inviteToken = (await cookies()).get('gnubok-invite-token')?.value
if (inviteToken && (await acceptPendingInviteByToken(user, inviteToken))) {
redirect('/')
}
// All lookups key only on user.id/email, one parallel batch instead of
// serial round-trips on the post-BankID-login landing page.
const [
// Existing Accounted memberships.
{ data: memberships },
{ data: teamMembership },
// Greeting name.
{ data: profile },
// BankID enrichment (CompanyRoles from Bolagsverket via TIC). Stored
// user-keyed in `bankid_enrichment` because it lands before company
// selection, see fetchAndStoreEnrichment in the tic extension.
{ data: enrichmentRow },
// Pending invitation for this email with no cookie to accept it from:
// rendered as a "check your invite email" hint in the picker.
hasPendingInvite,
] = await Promise.all([
supabase
.from('company_members')
.select(`
role,
company:company_id (
id,
name,
org_number,
entity_type,
archived_at
)
`)
.eq('user_id', user.id)
.order('joined_at', { ascending: true }),
supabase
.from('team_members')
.select('team_id')
.eq('user_id', user.id)
.limit(1)
.maybeSingle(),
supabase.from('profiles').select('full_name').eq('id', user.id).single(),
supabase
.from('bankid_enrichment')
.select('company_roles, created_at, updated_at')
.eq('user_id', user.id)
.maybeSingle(),
user.email ? hasPendingInviteForEmail(user.email) : Promise.resolve(false),
])
type CompanyRow = {
id: string
name: string
org_number: string | null
entity_type: string | null
archived_at: string | null
}
const memberCompanies: MemberCompany[] = ((memberships ?? []) as unknown as Array<{
role: string
// Supabase's generated types can express this as either a single object
// or an array depending on the relationship graph; handle both shapes.
company: CompanyRow | CompanyRow[] | null
}>)
.map((m) => ({
role: m.role,
company: Array.isArray(m.company) ? m.company[0] ?? null : m.company,
}))
.filter((m): m is { role: string; company: CompanyRow } => !!m.company && !m.company.archived_at)
.map((m) => ({
id: m.company.id,
name: m.company.name,
orgNumber: m.company.org_number,
entityType: m.company.entity_type,
role: m.role,
}))
const memberOrgNumbers = new Set(
memberCompanies
.map((c) => (c.orgNumber ? c.orgNumber.replace(/[\s-]/g, '') : null))
.filter((n): n is string => !!n),
)
// Ensure the user has a team (same pattern as /onboarding).
let teamId = teamMembership?.team_id
if (!teamId) {
const { data: ensured } = await supabase.rpc('ensure_user_team')
teamId = ensured ?? null
}
if (!teamId) {
redirect('/login')
}
const firstName = profile?.full_name?.split(' ')[0] ?? null
const enrichmentValue = enrichmentRow
? { companyRoles: enrichmentRow.company_roles as EnrichmentCompanyRole[] }
: null
// "Currently a director" = no position end date. We deliberately do NOT
// also require companyStatus === 'Aktivt': real TIC payloads have been
// observed with other values (locale/tenant variants), and filtering too
// strictly silently hides the user's real directorships.
//
// Ceased/struck-off companies would still render here, but two later
// guards block provisioning:
// 1. BankIdCompanyPicker calls TIC /lookup before provisioning and
// short-circuits with a toast when isCeased=true.
// 2. createCompanyFromTicRole refuses to provision when lookup.isCeased.
// Both guards are required: don't remove one without removing both.
//
// Loose `== null` on purpose: TIC payloads have been observed returning
// `undefined` for open-ended positions, which `=== null` would miss.
const activeRoles = (enrichmentValue?.companyRoles ?? []).filter(
(r) => r.positionEnd == null,
)
// Drop TIC roles that already appear in the user's Accounted memberships:
// those render via the "Your Accounted companies" section above instead.
const rolesNotAlreadyMine = activeRoles.filter(
(r) => !memberOrgNumbers.has(r.companyRegistrationNumber.replace(/[\s-]/g, '')),
)
// Cross-reference remaining TIC org numbers against the global companies
// table to detect "exists in Accounted, user not a member" cases. Use the
// service client: RLS filters out companies the user isn't a member of,
// which is exactly the data we need. Scoped to the specific org numbers.
let externallyOwnedOrgs = new Set<string>()
if (rolesNotAlreadyMine.length > 0) {
const service = createServiceClient()
const orgNumbers = rolesNotAlreadyMine.map((r) =>
r.companyRegistrationNumber.replace(/[\s-]/g, ''),
)
const { data: rows } = await service
.from('companies')
.select('org_number')
.in('org_number', orgNumbers)
.is('archived_at', null)
externallyOwnedOrgs = new Set(
(rows ?? []).map((r: { org_number: string | null }) => r.org_number ?? '').filter(Boolean),
)
}
const ticCompanies: TicPickerCompany[] = rolesNotAlreadyMine.map((role) => {
const cleaned = role.companyRegistrationNumber.replace(/[\s-]/g, '')
return {
role,
status: externallyOwnedOrgs.has(cleaned) ? 'exists' : 'new',
}
})
const enrichmentTimestamp = enrichmentRow?.updated_at ?? enrichmentRow?.created_at ?? null
const enrichmentStale = enrichmentTimestamp
? Date.now() - new Date(enrichmentTimestamp).getTime() > ENRICHMENT_TTL_DAYS * 24 * 60 * 60 * 1000
: false
// A member of exactly one company with nothing else to decide (no new TIC
// engagements, no pending invite, enrichment not stale enough to hide one)
// gets sent straight in instead of clicking the only row on every login.
// `?choose=1` (the in-app switcher links) always renders the picker, and
// multi-company/byra users are untouched.
const { choose } = await searchParams
if (
!choose &&
memberCompanies.length === 1 &&
ticCompanies.length === 0 &&
!hasPendingInvite &&
!enrichmentStale
) {
// redirect() throws NEXT_REDIRECT, so it must stay outside the try.
let switched = false
try {
await setActiveCompany(supabase, user.id, memberCompanies[0].id)
switched = true
} catch {
// Fall through to the picker: rendering it is always safe.
}
if (switched) redirect('/')
}
return (
<BankIdCompanyPicker
firstName={firstName}
teamId={teamId}
memberCompanies={memberCompanies}
ticCompanies={ticCompanies}
enrichmentStale={enrichmentStale}
hasPendingInvite={hasPendingInvite}
/>
)
}