* feat(reconciliation): close the bank-feed loop on voucher links and re-tag mis-typed opening balances
Two related fixes to bank reconciliation correctness:
1. Auto-reconcile on voucher link. Linking an invoice or supplier invoice to
an existing voucher previously advanced only the invoice — the bank
transaction that paid it kept sitting in the Transactions inbox with a null
journal_entry_id. linkInvoiceToVoucher / linkSupplierInvoiceToVoucher now
call autoReconcileTransactionForLinkedVoucher (lib/reconciliation), which
links the bank transaction to the same verifikat when exactly one unbooked
line matches it. Best-effort and post-commit: a failure here never fails the
link. The result surfaces reconciledTransactionId; the inbox row leaves the
list and the UI shows link_success_tx_reconciled.
2. Re-tag mis-typed opening balances. getReconciliationStatus and the GL-line
matching RPCs identify a cash account's ingående balans solely by
journal_entries.source_type='opening_balance'. Companies migrated from other
systems often booked the bank IB as an ordinary voucher (source_type
'import' or 'manual'), so it was never excluded and surfaced as a phantom
reconciliation difference equal to the opening balance. Adds:
- migration mark_entry_as_opening_balance: a GUC-gated carve-out in the
immutability trigger plus a SECURITY DEFINER RPC that validates the entry
(balance-sheet lines only, dated on a fiscal-period boundary), flips the
source_type, and writes an audit row — no blanket data sweep.
- POST /api/reconciliation/bank/mark-opening-balance + MarkOpeningBalanceSchema.
- BankReconciliationView action to trigger it from the IB diff.
The gnubok_create_voucher executor now accepts a typed is_opening_balance flag
and derives source_type='opening_balance' only after validating class 1/2 lines
on the period start, so new IBs land correctly typed.
Covered by lib/reconciliation auto-reconcile tests, voucher-executors tests,
and a mark-entry-as-opening-balance pg-real test.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* chore: rebrand gnubok → Accounted and prune swarm agent skills
Product rebrand and skills housekeeping. No runtime behaviour change.
Rebrand: replace user-visible "gnubok" with "Accounted" across docs, READMEs,
in-code comments, doc-site content, MCP skill/resource prose, and the
gnubok-mcp package description. The MCP resource URI scheme is moved gnubok://
→ Accounted:// consistently across resource registrations, the event-type
comment, and the resource/skill tests. Deliberately preserved as stable
identifiers (NOT rebranded): the gnubok-company-id cookie, gnubok_sk_ / gnubok_inv_
token prefixes, the gnubok-mcp npm bridge name, and the AGI <gem:Programnamn>
value (kept 'gnubok' per its source comment — it is the software identifier sent
to Skatteverket and must not churn across visual rebrands).
Skills: remove the 27 swarm-* agent SKILL.md atoms (no longer used; already
absent from the agent_atom_registry in prod), refresh the remaining skill docs,
add the .claude/rules/ path-scoped rule set, and regenerate the
seed_agent_atom_bodies migration + .skill-body-manifest.json via
`npm run skills:generate` so the DB-backed skill bodies match the trimmed set.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
175 lines
5.8 KiB
TypeScript
175 lines
5.8 KiB
TypeScript
import { redirect } from 'next/navigation'
|
|
import { createClient, createServiceClient } from '@/lib/supabase/server'
|
|
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() {
|
|
const supabase = await createClient()
|
|
|
|
const { data: { user } } = await supabase.auth.getUser()
|
|
if (!user) {
|
|
redirect('/login')
|
|
}
|
|
|
|
// Existing Accounted memberships.
|
|
const { data: memberships } = await 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 })
|
|
|
|
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).
|
|
const { data: teamMembership } = await supabase
|
|
.from('team_members')
|
|
.select('team_id')
|
|
.eq('user_id', user.id)
|
|
.limit(1)
|
|
.maybeSingle()
|
|
|
|
let teamId = teamMembership?.team_id
|
|
if (!teamId) {
|
|
const { data: ensured } = await supabase.rpc('ensure_user_team')
|
|
teamId = ensured ?? null
|
|
}
|
|
if (!teamId) {
|
|
redirect('/login')
|
|
}
|
|
|
|
// Greeting name.
|
|
const { data: profile } = await supabase
|
|
.from('profiles')
|
|
.select('full_name')
|
|
.eq('id', user.id)
|
|
.single()
|
|
const firstName = profile?.full_name?.split(' ')[0] ?? null
|
|
|
|
// 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.
|
|
const { data: enrichmentRow } = await supabase
|
|
.from('bankid_enrichment')
|
|
.select('company_roles, created_at, updated_at')
|
|
.eq('user_id', user.id)
|
|
.maybeSingle()
|
|
|
|
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
|
|
|
|
return (
|
|
<BankIdCompanyPicker
|
|
firstName={firstName}
|
|
teamId={teamId}
|
|
memberCompanies={memberCompanies}
|
|
ticCompanies={ticCompanies}
|
|
enrichmentStale={enrichmentStale}
|
|
/>
|
|
)
|
|
}
|