f24b26a139
* fix(security): gate replace_sie_import behind owner/admin membership The RPC was SECURITY DEFINER with EXECUTE granted to PUBLIC and anon, no company_members lookup, no auth.uid() reference and no unauthorized raise, while setting gnubok.allow_delete to disarm the BFL immutability and retention triggers. Any caller holding a company_id and an import id could hard delete another tenant's verifikationer. Confirmed live in production. Applies the same fail closed owner/admin guard that undo_sie_import already carries (migration 20260624120000), resolving the actor from COALESCE(p_user_id, auth.uid()) so it denies when the role is NULL, then revokes EXECUTE from PUBLIC and anon. search_path and the raised statement_timeout are restated, since CREATE OR REPLACE drops settings that are not repeated. userId is a required parameter on replaceSIEImport: the service client has a NULL auth.uid(), so a caller without an explicit actor now fails to compile rather than hitting the closed gate at runtime. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): validate arcim OAuth callback state server side The callback route is skipAuth and decoded the state parameter as plain base64url JSON, trusting consentId and provider from it. A one time code was minted at flow start and never read. An unauthenticated attacker who learned a consent id could run an OAuth flow on their own provider account and post the callback with a forged state, landing their tokens on another tenant's consent, so the victim's next migration imported the attacker's ledger. State is now an opaque randomBytes(32) pointer to a provider_otc row, consumed by a single atomic UPDATE guarded on used_at IS NULL and expires_at, so a replay loses the row lock race and updates nothing. provider is read from provider_consents rather than trusted from the client. provider_otc already existed for exactly this purpose and was never wired up. Also scopes getConsent to an owning company, closing a cross tenant status oracle where the preview and migrate paths echoed a consent's status before the scoped check ran. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): scope documents storage to company_id (phase A) The documents bucket policies matched on auth.uid(), and upload keys were documents/{userId}/..., so company membership was never consulted. Removing a member revoked nothing: their session still authenticated and they kept direct Storage read access to every receipt, supplier invoice and bank statement they had uploaded. The same bug was fixed for sie-files in 20260416120000; this bucket was left behind. Phase A is additive. Company scoped policies are added alongside the uploader scoped ones, uploads move to documents/{companyId}/{userId}/..., and reads accept either layout so nothing breaks mid migration. Phase C, which drops the old policies, is gated on the backfill reporting zero remaining legacy prefix objects. The policy compares the company segment as text rather than casting to uuid the way sie-files does: this bucket holds keys whose second segment is not a uuid (MCP audit packages), and Postgres does not guarantee the bucket prefix qual runs before the cast, so a planner reordering would raise 22P02 and fail the whole query instead of filtering the row out. deleteDocument now removes both candidate keys. Removing only the stored pointer would leave a readable orphan copy of a document the user asked to erase. The backfill script is included but has never been run. It defaults to dry run, refuses .env.local by name, and verifies each copy is readable and SHA-256 identical before repointing the row. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): enforce events:read scope and membership on /api/events This was the only one of the three validateApiKey call sites with no downstream guard: v1 and the MCP server both check scope and re-verify company membership, this route did neither. An events:read scope existed and was documented as gating the endpoint but was never called, so a legacy key falling back to DEFAULT_SCOPES read the full log. The bound company id went straight from the api_keys row into a service role query, so a key whose user had been removed from the company kept reading. Adds the scope check before any database access, re-verifies company_members with archived_at IS NULL, honours test mode by stamping X-Gnubok-Mode instead of ignoring it, applies minimisePayload so the pull surface can never return a wider payload than the push surface, and replaces the three flat error strings with the canonical envelope. Test key reads are served rather than blocked: TEST_KEY_WRITE_BLOCKED is gated on mutations in with-api-v1, so a read gets the same treatment as every other v1 read endpoint. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * perf(bookkeeping): sweep remaining journal_entries!inner embeds A previous refactor removed this pattern from lib/reports and introduced fetchEntryLines, but the class was never swept. Seventeen sites remained and had become the top application consumer of production database time: measured across the resulting query shapes, 32,694 calls and 25,848 seconds of execution, mean 790ms, with shapes averaging 2.6s and 3.0s and maxing at 7,962ms against the 8s statement_timeout, which surfaced to users as 500s on the booking path. PostgREST compiles an embed with filters on the embedded side into a correlated INNER JOIN LATERAL with a parameterized LIMIT, which stops Postgres reordering the join, so each query walked the whole journal_entry_lines table across all tenants. Driving from the entries side instead turns that into two indexed round trips. Converted sites keep their existing shape: the helper reattaches the parent entry under the same key the embed produced. Several conversions also remove a latent silent truncation where an unpaginated query was capped at PostgREST's 1000 row ceiling. Two deliberate exceptions. The free text ilike legs of the MCP display query stay on the embed, because each is capped at legLimit and that cap drives the truncation contract the tool reports, while the helper is unbounded. The accounts route moves to the existing get_account_usage_counts RPC instead, since its embed was a head count and the helper returns rows. commitEntry's write path is untouched: the change there is confined to the read query of the pre-commit dimension rule check. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): anchor v1 list cursors on created_at Page two returned page one, forever, while still advertising a fresh next_cursor. The three routes sorted by and encoded a Postgres date column, which serializes as YYYY-MM-DD, but decodeDefaultCursor validates the cursor timestamp as full ISO-8601 and returned null, so the keyset filter was never applied and has_more never went false. An integrator syncing verifikat looped on the newest rows indefinitely. The transactions route already solved this and its comment names the trap; the fix was never ported. All three now order and encode on created_at with an id tie break, matching the transactions keyset predicate exactly. ISO_TIMESTAMP is deliberately left alone: relaxing it would silently change sort semantics on the route that currently works. Default ordering therefore moves from business date to insert order. Every business date is still on the row, and the invoices list gains date_from and date_to filters so a date range is still reachable; the other two already had them. The tests use an in-memory PostgREST that actually evaluates the filters, because the repo's pass-through mock cannot catch this class of bug: the bug is that the filter is never sent. They walk to exhaustion with a hard iteration cap, so an unterminated walk fails instead of hanging. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): separate dry run from commit in the idempotency hash The request hash was built from url.pathname, which excludes the query string, so a dry run and its commit hashed identically. Following the flow documented in dry-run.ts, re-issuing the request with the same Idempotency-Key returned the cached preview with Idempotent-Replayed set and wrote nothing, while reporting 200. An agent or integrator saw success for a write that never happened. dry_run is folded into the hash only when true, not as an unconditional boolean. Including it as false would change the hash of every ordinary write, and with a 24h idempotency TTL any key in flight across the deploy would fail the request_hash comparison and 409 on a legitimate retry. Both hash call sites now go through one shared helper so they cannot drift into a permanent cache miss, and dry run responses are no longer stored at all. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * ci: install the Bedrock SDK out of tree in the compliance review The Swedish accounting compliance gate had failed ten consecutive runs and so was posting nothing. With --no-package-lock npm discarded the lockfile and re-resolved the whole tree from package.json, floating @hookform/resolvers to 5.4.3, whose valibot ^1 peer conflicts with the pinned valibot 0.39.0. Installing into the parent of the checkout resolves only that one package, so an unrelated peer conflict can never take the gate down again. Node still finds it because ESM bare specifiers walk up parent node_modules; NODE_PATH would not have worked, as it is CommonJS only. --legacy-peer-deps was rejected because it masks future genuine peer conflicts and still reifies the full tree. The same step's SDK version is aligned from 0.31.0 back to the 0.29.1 that package.json and check:guards enforce after the streaming outage. That drift went unnoticed because the pin guard only inspects package.json and the lockfile, never workflow files. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * build(docker): generate crontabs from vercel.json vercel.json defines 16 cron jobs; both Docker crontabs carried 9, and were byte identical to each other. Self hosted deployments therefore never sent recurring invoices, never dispatched webhooks and never cleaned up idempotency keys. tax-deadlines also ran once a year on 2 January instead of daily, and documents/verify weekly instead of daily. Extension crons are included rather than excluded. The Dockerfile copies the whole tree before building, so every extension cron route is compiled into the image regardless of the enabled preset, and each returns 200 when its extension is unconfigured, so curl -sf logs no failure. Two such entries were already present in the crontab for extensions absent from the preset, which settles the intent. documents/verify is treated as drift rather than a self hosted concession: the weekly cadence was present in the hosted crontab too, and the run is capped at 200 documents walking a nulls-first queue, so weekly drains the integrity queue seven times slower on a check that exists for BFL retention. webhooks/dispatch keeps its per minute cadence, adding 1,440 requests a day on self hosted. A gentler tick would silently stretch the first retry, since the retry ladder opens at 60 seconds. SCHEDULE_OVERRIDES is the one line place to change that. A parity test asserts the path sets match minus a documented exclusion list, and ratchets three cron routes that are currently scheduled nowhere so they are named rather than silently rotting. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * chore(observability): add a provider agnostic error sink There is no error tracking in this codebase: logs go to console and Vercel retention and nowhere else, nothing alerts on the 16 cron jobs, and seven code comments across lib, app, components and extensions asserted that Sentry captures errors when Sentry is not a dependency. The two most recent bug fixes on this repo were both discovered by customer email. This adds the sink, not a vendor. No dependency is taken: the interface has a no-op default and a registration point, so behaviour is unchanged until an adapter is registered. Releases are tagged from the build id already inlined by next.config.ts. Redaction moved out of lib/logger.ts into a leaf module that both the logger and the sink import, so there is one denylist and no path from application data to a third party can skip the personnummer regex, including direct sink calls that bypass the logger. That matters here because these logs carry personnummer and financial data. verifyCronSecret now reports its own 401s, which covers all 16 jobs without touching a route file and catches the case where CRON_SECRET is rotated without updating the scheduler and every job silently 401s forever. The threshold is one failure rather than the backup alert's three: suppressing the first occurrence is precisely how an outage stays invisible. The seven misleading comments are corrected to describe what the code actually does, including the two cases that still are not covered: the client side one, since the sink is server side, and a warn level call that is not forwarded. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix: remediate the 2026-07-26 similar-sweep findings across all surfaces Resolves the ~150-finding sweep (dev_docs/similar-sweep-2026-07-26.md) with one agent per finding; every behavioural fix carries a regression test proven to fail at HEAD. Full status, corrections to the sweep, refusals and open decisions in dev_docs/similar-sweep-2026-07-26-remediation-status.md. Structural roots closed: - resolveSekAmountOrNull(): honest SEK resolution refuses instead of booking 1:1; four duplicated toSek closures now refuse via INVOICE_FX_RATE_MISSING - ledger-line-amount.ts: journal_entry_lines.currency labels the document, not the amount; SQL pre-filter decoy proven and fixed - sparse-patch.ts: .partial() does not strip .default() in Zod 4.4.3; the exploitable salary payslip-line PATCH and KPI preferences sinks fixed - tests/schema: migration-replay phantom-column guard (13k+ refs, closed CHECK sets, onConflict targets); found 28 real defects, all fixed, all four baselines now empty - three new ratchet guards: sek-labelled-amount, cross-extension-import, ungated-extension-route Highlights: lawful VAT-rate set on all seven invoice surfaces (ML 6 kap), RC input VAT mismatch wired on web + both MCP callers, missing-underlag resource delegates to the shared RPC predicate, push-notifications consent polarity fail-closed, deadlines undo honours requested state, silent-failure and read-side-fabrication classes fixed across settings/KPI/inbox/Stripe/ Arcim/kassaflodesanalys, error-envelope stringification fixed at 10+ sites with isSwedishUserMessage extended. Also includes the parallel session's MCP invoice tools (update_invoice, recurring schedules, invoice deliveries) which share files with the sweep work and are verified green together. 13 new migrations are NOT applied anywhere; they apply via branch merge. 20260726120000 backfills 1247 supplier-invoice rows. pg tests for new DDL are written but unrun (no local Postgres). Verified: 11088 tests / 881 files green, tsc 0 non-test errors, lint 0 errors, check:guards passing, MCP payload 57475/57500. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(migrations): rename replace_sie_import migration off main's 20260726090000 version origin/main shipped 20260726090000_agent_quota_rpc_caller_guard.sql; keeping our replace_sie_import migration on the same version would abort the Supabase apply with a schema_migrations_pkey duplicate at merge time. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): remediate pre-publish deep-review findings across all slices A 13-agent review of the full branch diff surfaced 1 critical, 5 high and ~45 further findings; this commit resolves them in one pass: - replace_sie_import / undo_sie_import: p_user_id honored only for service_role callers; any other caller is pinned to auth.uid() (impersonation gate bypass), authz raise errcode 42501 mapped to a Swedish 403 in the route, new caller-guard migration for undo - bulk_book_transactions refuses homogeneous non-SEK batches instead of writing foreign magnitudes into SEK ledger columns - credit-note cap trigger: company-match on credited_invoice_id, no cross-tenant figures in exception text - link_voucher RPCs resolve NULL invoice currency as SEK end to end - personal-number ciphertext CHECK split into NOT VALID + VALIDATE - same-currency foreign settlements clear 1510 at booking rate and book realized diff to 3960/7960; rate-less foreign write paths refuse - receivables revaluation covers partially_paid and outstanding amounts - period lock guard paginates candidates past the PostgREST 1000 cap - documents: service-client storage removals after authz, dual-layout reads in integrity cron and archive export, backfill delete-source sweep actually deletes with hash verification and shared-key grouping - invoice matching normalizes NULL/lowercase currencies (regression), duplicate candidates stop claiming amount matches they never ran - match-invoice aborts on any booking failure (no paid-without-verifikat) - refresh-exchange-rate reverts on concurrent booking (TOCTOU window) - KPI preferences upsert arbiter aligned to the company-scoped constraint - personnummer_last4 stripped from all salary responses incl. MCP tools - worked-hours batch restores destroyed rows on conflict and error paths - MCP: shared duplicate-claim builder (no more 'null kr'), short-circuit on tag_journal_lines overflow, auto_send schedules stage as high risk - observability sink redacts emails/IBANs/API keys and keeps redacted stacks in prod; assorted small guards (safe-return-to /@, dry_run=True, cursor helper off-by-one, OAuth state TTL 10 min, arcim saveMappings call removed) Full dispositions, deferred items and hand-verified accounting numbers are documented in the PR body and DECISIONS.md. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(personnummer): implement masking and encryption for personal numbers with tests * fix(review): address CI and compliance-bot findings for PR #1215 pg-real: the CI image's auth shim reads the legacy request.jwt.claim.role GUC, so both service-role simulations (runAsServiceRole and the invoice-delivery test's local helper) never satisfied auth.role() = 'service_role' and every legitimate p_user_id path failed closed; the shared helper now sets both GUC shapes plus SET LOCAL ROLE with a fail-loud sanity check, and the delivery test reuses it. The link-voucher migration had recreated both RPCs from pre-rewrite file text, reintroducing the NULL-unsafe membership pattern the null-safe-tenant-guards ratchet bans; both guards now use public.caller_is_company_member() with all currency changes preserved. Compliance bots: the customers export now emits the standard masked form instead of raw AES-256-GCM ciphertext in the Org-/personnummer column, and maskCustomerRow returns a non-round-trippable placeholder on decrypt failure instead of 500ing the list. MCP parity: gnubok_lock_period's staging pre-check now runs the exact countUnbookedInPeriod the commit path enforces (exported from period-service; local mirror deleted), and gnubok_agi_status resolves AGI state run-scoped so a correction run no longer renders as already filed. Declined with evidence: PR-Agent's opening-balances null-zeroing concern (all mergeable columns are NOT NULL with defaults per 20260713101000). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): address codex review findings on PR #1215 - restore 20260726140000 to its preview-recorded content and restate the NULL-safe tenant guard under 20260727130000: a recorded migration version never re-runs, so the in-place edit could not reach the preview branch - replace toFixed() with sv-SE two-decimal formatting in the ROT/RUT cap warning texts and update the pinned test expectations - drop the em dash in the fiscal-periods route comment - strip trailing whitespace in import-existing.test.ts Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(reports): raise timeout on real PDF render tests renderToBuffer does real @react-pdf layout work and exceeds the 5s default when the full suite saturates the CPU; tests pass in isolation. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
651 lines
24 KiB
TypeScript
651 lines
24 KiB
TypeScript
'use client'
|
|
|
|
import { useState } from 'react'
|
|
import { Pencil, X, Loader2, ArrowLeft, ArrowRight } from 'lucide-react'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Card, CardContent } from '@/components/ui/card'
|
|
import { Input } from '@/components/ui/input'
|
|
import { Badge } from '@/components/ui/badge'
|
|
import { cn } from '@/lib/utils'
|
|
import { AVATAR_OPTIONS } from '@/components/agent/avatars'
|
|
import AgentAvatar from '@/components/agent/AgentAvatar'
|
|
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
|
|
|
interface InitialFields {
|
|
entity_type_label: string
|
|
sni_codes: { code: string; name: string }[]
|
|
purpose: string | null
|
|
city: string | null
|
|
fiscal_period: string | null
|
|
vat_period: string | null
|
|
f_skatt: string | null
|
|
employees: string | null
|
|
}
|
|
|
|
interface ProfilePayload {
|
|
company_id: string
|
|
horizontal_atoms: string[]
|
|
vertical_atoms: string[]
|
|
modifier_atoms: string[]
|
|
is_multi_vertical: boolean
|
|
profile_summary: string
|
|
// Still carried from the composer + stored on the profile row, but no
|
|
// longer surfaced as a form step here: the Phase C chat intake owns the
|
|
// questions now (reads them server-side). Kept on the type so the payload
|
|
// shape stays aligned with the stream event.
|
|
verification_questions: string[]
|
|
uncertainty_notes: string[]
|
|
composer_model: string
|
|
composed_at: string
|
|
}
|
|
|
|
interface Props {
|
|
companyId: string
|
|
companyName: string
|
|
initialFields: InitialFields
|
|
// Pre-fetched atom titles from agent_atom_registry: used to render chips
|
|
// with the authored title instead of a naive slug-derived label. Missing
|
|
// ids fall through to deriveSlugTitle which is intentionally minimal.
|
|
atomTitles: Record<string, string>
|
|
profile: ProfilePayload | null
|
|
onVerified: () => void
|
|
}
|
|
|
|
// Maps an atom id to a chip label. Prefers the registry title when known.
|
|
function atomLabel(id: string, atomTitles: Record<string, string>): string {
|
|
if (atomTitles[id]) return atomTitles[id]
|
|
const slug = id.split('/').slice(-1)[0] ?? id
|
|
return slug
|
|
.split('-')
|
|
.map((w) => {
|
|
const upper = w.toUpperCase()
|
|
if (upper === 'VAT' || upper === 'SRU' || upper === 'SIE' || upper === 'IT') return upper
|
|
return w.length > 0 ? w[0].toUpperCase() + w.slice(1) : w
|
|
})
|
|
.join(' ')
|
|
}
|
|
|
|
export default function ReviewCard({
|
|
companyId,
|
|
companyName,
|
|
initialFields,
|
|
atomTitles,
|
|
profile,
|
|
onVerified,
|
|
}: Props) {
|
|
// Field-edit state. The pencil affordances let the user override anything
|
|
// the composer inferred. Each override is sent to PATCH /api/agent/profile,
|
|
// which stamps an overridden_at timestamp.
|
|
const [fields, setFields] = useState<InitialFields>(initialFields)
|
|
const [editing, setEditing] = useState<keyof InitialFields | null>(null)
|
|
const [summary, setSummary] = useState<string>(profile?.profile_summary ?? '')
|
|
const [editingSummary, setEditingSummary] = useState(false)
|
|
const [horizontal, setHorizontal] = useState<string[]>(profile?.horizontal_atoms ?? [])
|
|
const [vertical, setVertical] = useState<string[]>(profile?.vertical_atoms ?? [])
|
|
const [modifier, setModifier] = useState<string[]>(profile?.modifier_atoms ?? [])
|
|
// Agent identity: name shown on the FAB, avatar shown alongside.
|
|
const [displayName, setDisplayName] = useState('')
|
|
const [avatarId, setAvatarId] = useState<string>(AVATAR_OPTIONS[0].id)
|
|
const [seedMemory, setSeedMemory] = useState('')
|
|
const [verifying, setVerifying] = useState(false)
|
|
const [verifyError, setVerifyError] = useState<string | null>(null)
|
|
|
|
// Two steps now:
|
|
// 1: meet your assistant (name + avatar)
|
|
// 2: agree on the facts (profile + specialties + form fields + optional
|
|
// seed note), then "kör" which hands off to the Phase C chat intake.
|
|
// The verification-question interview that used to live here as a form
|
|
// stepper is gone: the chat conducts the real interview instead.
|
|
type Step = 1 | 2
|
|
const [step, setStep] = useState<Step>(1)
|
|
const totalPositions = 2
|
|
const currentPosition = step - 1
|
|
|
|
const agentName = displayName.trim() || 'din assistent'
|
|
|
|
async function handleVerify() {
|
|
setVerifying(true)
|
|
setVerifyError(null)
|
|
try {
|
|
// Persist edits before verifying. Skipped if nothing changed.
|
|
const changedFields: Record<string, unknown> = {}
|
|
for (const key of Object.keys(initialFields) as (keyof InitialFields)[]) {
|
|
if (fields[key] !== initialFields[key]) {
|
|
changedFields[key] = fields[key]
|
|
}
|
|
}
|
|
const atomsChanged =
|
|
!arrEq(horizontal, profile?.horizontal_atoms ?? []) ||
|
|
!arrEq(vertical, profile?.vertical_atoms ?? []) ||
|
|
!arrEq(modifier, profile?.modifier_atoms ?? [])
|
|
const summaryChanged = summary !== (profile?.profile_summary ?? '')
|
|
const trimmedName = displayName.trim()
|
|
// Identity is always persisted on first verify so the FAB picks it up
|
|
// immediately. If the user typed nothing, we leave display_name null
|
|
// (UI falls back to "min revisor").
|
|
const identityChanged = trimmedName.length > 0 || avatarId !== AVATAR_OPTIONS[0].id
|
|
|
|
if (Object.keys(changedFields).length > 0 || atomsChanged || summaryChanged || identityChanged) {
|
|
const patchBody: Record<string, unknown> = { company_id: companyId }
|
|
if (Object.keys(changedFields).length > 0) patchBody.field_overrides = changedFields
|
|
if (atomsChanged) {
|
|
patchBody.atoms = {
|
|
horizontal_atoms: horizontal,
|
|
vertical_atoms: vertical,
|
|
modifier_atoms: modifier,
|
|
}
|
|
}
|
|
if (summaryChanged) patchBody.profile_summary = summary
|
|
if (identityChanged) {
|
|
patchBody.display_name = trimmedName.length > 0 ? trimmedName : null
|
|
patchBody.avatar_id = avatarId
|
|
}
|
|
const res = await fetch('/api/agent/profile', {
|
|
method: 'PATCH',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(patchBody),
|
|
})
|
|
if (!res.ok) {
|
|
// Map the parsed body plus the status, never the raw response text:
|
|
// the route answers thrown errors with the canonical envelope
|
|
// `{ error: { code, message } }`, and throwing the raw JSON text
|
|
// (or "[object Object]") discards the route's own Swedish reason.
|
|
const body = await res.json().catch(() => null)
|
|
setVerifyError(getUserErrorMessage(body, { statusCode: res.status }))
|
|
return
|
|
}
|
|
}
|
|
|
|
if (seedMemory.trim().length > 1) {
|
|
await fetch('/api/agent/memory', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
company_id: companyId,
|
|
content: seedMemory.trim(),
|
|
kind: 'fact',
|
|
source: 'user_taught',
|
|
source_ref: 'onboarding_seed',
|
|
relevance_score: 1.0,
|
|
}),
|
|
})
|
|
}
|
|
|
|
const verifyRes = await fetch('/api/agent/profile/verify', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ company_id: companyId }),
|
|
})
|
|
if (!verifyRes.ok) {
|
|
const body = await verifyRes.json().catch(() => null)
|
|
setVerifyError(getUserErrorMessage(body, { statusCode: verifyRes.status }))
|
|
return
|
|
}
|
|
|
|
onVerified()
|
|
} catch (err) {
|
|
setVerifyError(err instanceof Error ? getUserErrorMessage(err) : 'Kunde inte verifiera.')
|
|
} finally {
|
|
setVerifying(false)
|
|
}
|
|
}
|
|
|
|
const stepTitle = step === 1 ? 'Träffa din assistent' : 'Stäm av detaljerna'
|
|
const stepSubtitle =
|
|
step === 1
|
|
? 'Ge din assistent ett namn och välj en avatar.'
|
|
: 'Bekräfta att uppgifterna stämmer, eller ändra det som blivit fel. Sen lär din assistent känna dig i en kort intervju.'
|
|
|
|
return (
|
|
<div className="w-full">
|
|
<header className="mb-6">
|
|
<p className="text-xs uppercase tracking-wider text-muted-foreground mb-1">
|
|
{companyName}
|
|
</p>
|
|
<h1 className="font-display text-3xl md:text-4xl tracking-tight">{stepTitle}</h1>
|
|
<p className="text-muted-foreground mt-2">{stepSubtitle}</p>
|
|
</header>
|
|
|
|
{/* Progress: one segment per step. Back navigation lives on the
|
|
"Tillbaka" button below. */}
|
|
<div className="flex items-center gap-1.5 mb-6" aria-hidden="true">
|
|
{Array.from({ length: totalPositions }, (_, i) => i).map((pos) => (
|
|
<div
|
|
key={pos}
|
|
className={cn(
|
|
'h-1.5 flex-1 rounded-full transition-colors',
|
|
pos <= currentPosition ? 'bg-foreground' : 'bg-border',
|
|
)}
|
|
/>
|
|
))}
|
|
</div>
|
|
|
|
<Card className="border-border">
|
|
<CardContent className="p-6 md:p-8 space-y-6">
|
|
{step === 1 && (
|
|
<section className="space-y-6">
|
|
<div className="flex flex-col items-center text-center gap-3 py-4">
|
|
<AgentAvatar avatarId={avatarId} size="lg" className="h-20 w-20" />
|
|
<div>
|
|
<p className="font-display text-xl tracking-tight">
|
|
{displayName.trim() || 'Din assistent'}
|
|
</p>
|
|
<p className="text-xs text-muted-foreground mt-1">
|
|
Visas som <span className="font-medium">Fråga {displayName.trim() || 'min assistent'}</span> i appen.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
<div>
|
|
<label htmlFor="agent-display-name" className="block text-sm font-medium mb-2">
|
|
Vad ska den heta?
|
|
</label>
|
|
<Input
|
|
id="agent-display-name"
|
|
value={displayName}
|
|
onChange={(e) => setDisplayName(e.target.value)}
|
|
placeholder="t.ex. Anna, Lars, Karin. Eller hoppa över."
|
|
maxLength={60}
|
|
autoFocus
|
|
/>
|
|
</div>
|
|
<div>
|
|
<p className="block text-sm font-medium mb-2">Välj en avatar</p>
|
|
<div className="grid grid-cols-4 gap-3 sm:grid-cols-8">
|
|
{AVATAR_OPTIONS.map((opt) => (
|
|
<button
|
|
key={opt.id}
|
|
type="button"
|
|
onClick={() => setAvatarId(opt.id)}
|
|
aria-label={`Välj avatar ${opt.label}`}
|
|
className={cn(
|
|
'aspect-square rounded-full overflow-hidden transition-all',
|
|
avatarId === opt.id
|
|
? 'ring-2 ring-foreground ring-offset-2 ring-offset-background'
|
|
: 'opacity-70 hover:opacity-100 hover:ring-1 hover:ring-border',
|
|
)}
|
|
>
|
|
<AgentAvatar avatarId={opt.id} size="md" className="h-full w-full" />
|
|
</button>
|
|
))}
|
|
</div>
|
|
</div>
|
|
</section>
|
|
)}
|
|
|
|
{step === 2 && (
|
|
<>
|
|
{/* Value first: the prose summary the composer wrote, so the
|
|
user sees the assistant understood them before being asked to
|
|
check dry registry facts. */}
|
|
<section>
|
|
<div className="flex items-center justify-between mb-3">
|
|
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
|
Så här har jag förstått dig
|
|
</h2>
|
|
{!editingSummary && summary && (
|
|
<button
|
|
onClick={() => setEditingSummary(true)}
|
|
className="text-muted-foreground hover:text-foreground transition-colors"
|
|
aria-label="Redigera profil"
|
|
>
|
|
<Pencil className="h-4 w-4" />
|
|
</button>
|
|
)}
|
|
</div>
|
|
{editingSummary ? (
|
|
<textarea
|
|
value={summary}
|
|
onChange={(e) => setSummary(e.target.value)}
|
|
onBlur={() => setEditingSummary(false)}
|
|
autoFocus
|
|
rows={5}
|
|
className="w-full rounded-lg border border-border bg-background px-4 py-3 text-sm leading-6 resize-none focus:outline-none focus:ring-2 focus:ring-ring"
|
|
/>
|
|
) : (
|
|
<p className="text-sm leading-6 italic text-muted-foreground">
|
|
{summary || 'Ingen sammanfattning ännu.'}
|
|
</p>
|
|
)}
|
|
</section>
|
|
|
|
{/* What the assistant can actually do: the differentiated
|
|
output of the build. Plain-language heading, not the internal
|
|
"atoms/specialiteter" framing. */}
|
|
{(horizontal.length > 0 || vertical.length > 0 || modifier.length > 0) && (
|
|
<section>
|
|
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground mb-1">
|
|
Vad jag kan hjälpa dig med
|
|
</h2>
|
|
<p className="text-xs text-muted-foreground mb-3">
|
|
Kunskapsområden jag läst in för din verksamhet. Ta bort det som inte passar, så slipper du förslag som inte är relevanta.
|
|
</p>
|
|
<ChipGroup
|
|
primaryLabel="Bransch"
|
|
secondaryLabel="Övrigt"
|
|
primary={vertical.map((id) => ({ id, label: atomLabel(id, atomTitles) }))}
|
|
secondary={[
|
|
...modifier.map((id) => ({ id, label: atomLabel(id, atomTitles), group: 'modifier' as const })),
|
|
...horizontal.map((id) => ({ id, label: atomLabel(id, atomTitles), group: 'horizontal' as const })),
|
|
]}
|
|
onRemove={(id, group) => {
|
|
if (group === 'horizontal') setHorizontal((arr) => arr.filter((x) => x !== id))
|
|
else if (group === 'vertical') setVertical((arr) => arr.filter((x) => x !== id))
|
|
else setModifier((arr) => arr.filter((x) => x !== id))
|
|
}}
|
|
/>
|
|
</section>
|
|
)}
|
|
|
|
{/* Inferred facts to confirm */}
|
|
<section>
|
|
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground mb-4">
|
|
Uppgifter
|
|
</h2>
|
|
<dl className="divide-y divide-border">
|
|
<FieldRow
|
|
label="Form"
|
|
value={fields.entity_type_label}
|
|
editing={editing === 'entity_type_label'}
|
|
onEdit={() => setEditing('entity_type_label')}
|
|
onChange={(v) => setFields((f) => ({ ...f, entity_type_label: v }))}
|
|
onCommit={() => setEditing(null)}
|
|
/>
|
|
<SniRow sniCodes={fields.sni_codes} />
|
|
<FieldRow
|
|
label="Säte"
|
|
value={fields.city ?? ''}
|
|
placeholder="-"
|
|
editing={editing === 'city'}
|
|
onEdit={() => setEditing('city')}
|
|
onChange={(v) => setFields((f) => ({ ...f, city: v }))}
|
|
onCommit={() => setEditing(null)}
|
|
/>
|
|
<FieldRow
|
|
label="Räkenskapsår"
|
|
value={fields.fiscal_period ?? ''}
|
|
placeholder="januari-december"
|
|
editing={editing === 'fiscal_period'}
|
|
onEdit={() => setEditing('fiscal_period')}
|
|
onChange={(v) => setFields((f) => ({ ...f, fiscal_period: v }))}
|
|
onCommit={() => setEditing(null)}
|
|
/>
|
|
<FieldRow
|
|
label="Moms"
|
|
value={fields.vat_period ?? ''}
|
|
placeholder="Kvartal / månad / år"
|
|
editing={editing === 'vat_period'}
|
|
onEdit={() => setEditing('vat_period')}
|
|
onChange={(v) => setFields((f) => ({ ...f, vat_period: v }))}
|
|
onCommit={() => setEditing(null)}
|
|
/>
|
|
<FieldRow
|
|
label="F-skatt"
|
|
value={fields.f_skatt ?? ''}
|
|
placeholder="Aktivt / saknas"
|
|
editing={editing === 'f_skatt'}
|
|
onEdit={() => setEditing('f_skatt')}
|
|
onChange={(v) => setFields((f) => ({ ...f, f_skatt: v }))}
|
|
onCommit={() => setEditing(null)}
|
|
/>
|
|
<FieldRow
|
|
label="Anställda"
|
|
value={fields.employees ?? ''}
|
|
placeholder="0"
|
|
editing={editing === 'employees'}
|
|
onEdit={() => setEditing('employees')}
|
|
onChange={(v) => setFields((f) => ({ ...f, employees: v }))}
|
|
onCommit={() => setEditing(null)}
|
|
/>
|
|
</dl>
|
|
</section>
|
|
|
|
{/* Verksamhetsbeskrivning from Bolagsverket: verbatim, since
|
|
authoritative legal text. Hidden when TIC didn't return one. */}
|
|
{fields.purpose && (
|
|
<section>
|
|
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground mb-3">
|
|
Verksamhet
|
|
</h2>
|
|
<p className="text-sm leading-6 text-muted-foreground italic">
|
|
{fields.purpose}
|
|
</p>
|
|
</section>
|
|
)}
|
|
|
|
{/* Optional seed note: the fast path for users who'd rather jot
|
|
one thing than chat. The Phase C intake will draw the rest
|
|
out conversationally. */}
|
|
<section>
|
|
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground mb-1">
|
|
Bra att veta
|
|
</h2>
|
|
<p className="text-xs text-muted-foreground mb-3">
|
|
Valfritt: du kan också berätta i chatten strax. T.ex. återkommande kunder, en hyresfaktura som kommer den 25:e, eller att kunderna mest finns i Tyskland.
|
|
</p>
|
|
<textarea
|
|
id="seed-memory"
|
|
value={seedMemory}
|
|
onChange={(e) => setSeedMemory(e.target.value)}
|
|
rows={3}
|
|
placeholder="Skriv något, eller lämna tomt"
|
|
className="w-full rounded-lg border border-border bg-background px-4 py-3 text-sm leading-6 resize-none focus:outline-none focus:ring-2 focus:ring-ring"
|
|
/>
|
|
</section>
|
|
</>
|
|
)}
|
|
|
|
{verifyError && (
|
|
<p className="text-sm text-destructive">{verifyError}</p>
|
|
)}
|
|
|
|
{/* Step nav. Step 1 → forward to review. Step 2 → back to meet, or
|
|
run the verify pipeline and hand off to the chat intake. */}
|
|
<div className="flex items-center justify-between gap-3 pt-2">
|
|
<Button
|
|
variant="ghost"
|
|
onClick={() => setStep(1)}
|
|
disabled={step === 1}
|
|
>
|
|
<ArrowLeft className="h-4 w-4 mr-2" />
|
|
Tillbaka
|
|
</Button>
|
|
|
|
{step === 1 && (
|
|
<Button onClick={() => setStep(2)}>
|
|
Nästa
|
|
<ArrowRight className="h-4 w-4 ml-2" />
|
|
</Button>
|
|
)}
|
|
{step === 2 && (
|
|
<Button size="lg" onClick={handleVerify} disabled={verifying}>
|
|
{verifying ? (
|
|
<>
|
|
<Loader2 className="h-4 w-4 animate-spin mr-2" />
|
|
Sparar…
|
|
</>
|
|
) : (
|
|
<>
|
|
Möt {agentName}
|
|
<ArrowRight className="h-4 w-4 ml-2" />
|
|
</>
|
|
)}
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
// Renders one or more SNI codes alongside their human-readable industry
|
|
// labels. Read-only for the POC: TIC is authoritative for SNI and we don't
|
|
// surface a UI to add codes that Bolagsverket doesn't have.
|
|
//
|
|
// TIC occasionally returns the same SNI code twice (e.g. as both primary and
|
|
// secondary on the company record). Dedupe by code so the same line doesn't
|
|
// render twice in a row.
|
|
function SniRow({ sniCodes }: { sniCodes: { code: string; name: string }[] }) {
|
|
const seen = new Set<string>()
|
|
const uniqueCodes = sniCodes.filter((s) => {
|
|
if (seen.has(s.code)) return false
|
|
seen.add(s.code)
|
|
return true
|
|
})
|
|
|
|
return (
|
|
<div className="flex items-start gap-4 py-3">
|
|
<dt className="w-32 text-sm text-muted-foreground shrink-0">SNI</dt>
|
|
<dd className="flex-1 min-w-0">
|
|
{uniqueCodes.length === 0 ? (
|
|
<span className="text-sm italic text-muted-foreground/60">Saknas</span>
|
|
) : (
|
|
<ul className="space-y-1">
|
|
{uniqueCodes.map((s) => (
|
|
<li key={s.code} className="flex gap-3 text-sm">
|
|
<span className="tabular-nums text-muted-foreground shrink-0">{s.code}</span>
|
|
<span className="min-w-0">{s.name}</span>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
)}
|
|
</dd>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
function FieldRow({
|
|
label,
|
|
value,
|
|
placeholder,
|
|
editing,
|
|
onEdit,
|
|
onChange,
|
|
onCommit,
|
|
}: {
|
|
label: string
|
|
value: string
|
|
placeholder?: string
|
|
editing: boolean
|
|
onEdit: () => void
|
|
onChange: (v: string) => void
|
|
onCommit: () => void
|
|
}) {
|
|
return (
|
|
<div className="flex items-center gap-4 py-3">
|
|
<dt className="w-32 text-sm text-muted-foreground shrink-0">{label}</dt>
|
|
<dd className="flex-1 min-w-0">
|
|
{editing ? (
|
|
<Input
|
|
value={value}
|
|
onChange={(e) => onChange(e.target.value)}
|
|
onBlur={onCommit}
|
|
onKeyDown={(e) => {
|
|
if (e.key === 'Enter') {
|
|
e.preventDefault()
|
|
onCommit()
|
|
}
|
|
}}
|
|
autoFocus
|
|
className="h-9"
|
|
/>
|
|
) : (
|
|
<span
|
|
className={cn(
|
|
'text-sm',
|
|
!value && 'text-muted-foreground/60 italic',
|
|
)}
|
|
>
|
|
{value || placeholder || '-'}
|
|
</span>
|
|
)}
|
|
</dd>
|
|
{!editing && (
|
|
<button
|
|
onClick={onEdit}
|
|
className="text-muted-foreground hover:text-foreground transition-colors shrink-0"
|
|
aria-label={`Redigera ${label}`}
|
|
>
|
|
<Pencil className="h-4 w-4" />
|
|
</button>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
function ChipGroup({
|
|
primaryLabel,
|
|
secondaryLabel,
|
|
primary,
|
|
secondary,
|
|
onRemove,
|
|
}: {
|
|
primaryLabel: string
|
|
secondaryLabel: string
|
|
primary: { id: string; label: string }[]
|
|
secondary: { id: string; label: string; group: 'horizontal' | 'modifier' }[]
|
|
onRemove: (id: string, group: 'horizontal' | 'vertical' | 'modifier') => void
|
|
}) {
|
|
return (
|
|
<div className="space-y-3">
|
|
{primary.length > 0 && (
|
|
<div>
|
|
<p className="text-xs text-muted-foreground mb-2">{primaryLabel}</p>
|
|
<div className="flex flex-wrap gap-2">
|
|
{primary.map((c) => (
|
|
<Chip key={c.id} label={c.label} onRemove={() => onRemove(c.id, 'vertical')} />
|
|
))}
|
|
</div>
|
|
</div>
|
|
)}
|
|
{secondary.length > 0 && (
|
|
<div>
|
|
<p className="text-xs text-muted-foreground mb-2">{secondaryLabel}</p>
|
|
<div className="flex flex-wrap gap-2">
|
|
{secondary.map((c) => (
|
|
<Chip
|
|
key={c.id}
|
|
label={c.label}
|
|
onRemove={() => onRemove(c.id, c.group)}
|
|
muted
|
|
/>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
function Chip({
|
|
label,
|
|
onRemove,
|
|
muted,
|
|
}: {
|
|
label: string
|
|
onRemove: () => void
|
|
muted?: boolean
|
|
}) {
|
|
return (
|
|
<Badge
|
|
variant={muted ? 'outline' : 'secondary'}
|
|
className="pl-3 pr-1.5 py-1 text-xs gap-1 inline-flex items-center"
|
|
>
|
|
{label}
|
|
<button
|
|
onClick={onRemove}
|
|
className="ml-1 rounded-full hover:bg-foreground/10 p-0.5 transition-colors"
|
|
aria-label={`Ta bort ${label}`}
|
|
>
|
|
<X className="h-3 w-3" />
|
|
</button>
|
|
</Badge>
|
|
)
|
|
}
|
|
|
|
function arrEq(a: string[], b: string[]): boolean {
|
|
if (a.length !== b.length) return false
|
|
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false
|
|
return true
|
|
}
|