Accounted rebrand + swarm-skill cleanup + bank-reconciliation fixes (#643)
* 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) <[email protected]>
* 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) <[email protected]>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
331ae11867
commit
c74b19df1b
@@ -272,14 +272,14 @@ export function buildIdentityBlock(args: BuildArgs): string {
|
||||
// MCP catalog, and then claims access to tools that aren't in this
|
||||
// intent's whitelist. The tools-parameter the model receives via the
|
||||
// Anthropic API is the canonical source of truth — anything outside it
|
||||
// is reachable from *other* gnubok surfaces, not from here.
|
||||
// is reachable from *other* Accounted surfaces, not from here.
|
||||
lines.push('# Verktyg')
|
||||
lines.push('')
|
||||
lines.push('Verktygen du kan anropa just nu är EXAKT de som ligger i din tools-parameter — varken fler eller färre. Om du har sett andra verktygsnamn via gnubok_search_tools eller gnubok_list_skills så finns de i systemet, men de är inte anropbara från denna ingång. Påstå aldrig att du har ett verktyg som inte ligger i tools-parametern.')
|
||||
lines.push('')
|
||||
lines.push('När användaren frågar "vad kan du?" / "vilka verktyg har du?": svara i förmågor (vad du faktiskt kan hjälpa till med här), inte i API-namn. Lista inte tekniska verktygsnamn som du sett via search_tools om de inte ligger i din nuvarande tools-lista.')
|
||||
lines.push('')
|
||||
lines.push('När en uppgift kräver ett verktyg du inte har: hänvisa användaren till rätt vy i gnubok där motsvarande knapp har rätt verktyg inkopplat (t.ex. en transaktionsrad, /invoices/new, /bookkeeping/year-end). Säg vart de ska gå — försök inte fejka åtgärden.')
|
||||
lines.push('När en uppgift kräver ett verktyg du inte har: hänvisa användaren till rätt vy i Accounted där motsvarande knapp har rätt verktyg inkopplat (t.ex. en transaktionsrad, /invoices/new, /bookkeeping/year-end). Säg vart de ska gå — försök inte fejka åtgärden.')
|
||||
lines.push('')
|
||||
lines.push('När du HAR rätt verktyg — använd dem. Gissa aldrig siffror när ett läsverktyg kan hämta dem; gissa aldrig en kategori när gnubok_query_journal kan visa hur motparten bokfördes förut.')
|
||||
lines.push('')
|
||||
|
||||
@@ -214,7 +214,7 @@ function buildUserPrompt(inputs: ComposerInputs): string {
|
||||
const lines: string[] = []
|
||||
lines.push(`# Företag`)
|
||||
lines.push(`Namn: ${inputs.companyName}`)
|
||||
lines.push(`Juridisk form (gnubok): ${inputs.entityType}`)
|
||||
lines.push(`Juridisk form (Accounted): ${inputs.entityType}`)
|
||||
lines.push('')
|
||||
|
||||
const known = buildKnownFacts(inputs)
|
||||
|
||||
@@ -84,7 +84,7 @@ export async function loadCompanySettings(
|
||||
// ownership in the user's mouth.
|
||||
//
|
||||
// We match the user's enrichment row against this company's org_number.
|
||||
// `companyId` is the gnubok UUID — we need to read the orgnr from
|
||||
// `companyId` is the Accounted UUID — we need to read the orgnr from
|
||||
// `companies` to do the match. Cheap (single SELECT each) and only runs once
|
||||
// per agent build.
|
||||
//
|
||||
@@ -108,7 +108,7 @@ export async function loadUserDirectorship(
|
||||
companyId: string,
|
||||
): Promise<{ confirmedDirector: boolean }> {
|
||||
// Read this company's org_number — the BankID CompanyRoles row keys on
|
||||
// companyRegistrationNumber, not the gnubok company UUID.
|
||||
// companyRegistrationNumber, not the Accounted company UUID.
|
||||
const { data: companyRow } = await supabase
|
||||
.from('companies')
|
||||
.select('org_number')
|
||||
|
||||
@@ -975,6 +975,16 @@ export const BankUnlinkSchema = z.object({
|
||||
transaction_id: uuid,
|
||||
})
|
||||
|
||||
/**
|
||||
* Re-tag a mis-typed bank-account opening balance (a manual/import voucher that
|
||||
* is really an ingående balans) as source_type='opening_balance' so bank
|
||||
* reconciliation excludes it from the period movement. Routed to the
|
||||
* mark_entry_as_opening_balance SECURITY DEFINER RPC, which enforces the rest.
|
||||
*/
|
||||
export const MarkOpeningBalanceSchema = z.object({
|
||||
journal_entry_id: uuid,
|
||||
})
|
||||
|
||||
export const RunReconciliationSchema = z.object({
|
||||
date_from: isoDate.optional(),
|
||||
date_to: isoDate.optional(),
|
||||
|
||||
@@ -27,7 +27,7 @@ import '@/app/api/v1/companies/[companyId]/journal-entries/[id]/correct/route'
|
||||
import '@/app/api/v1/companies/[companyId]/journal-entries/batch-create/route'
|
||||
import '@/app/api/v1/companies/[companyId]/voucher-gap-explanations/route'
|
||||
|
||||
// Phase 4 PR-2 — compliance-check (gnubok's defensible edge).
|
||||
// Phase 4 PR-2 — compliance-check (Accounted's defensible edge).
|
||||
import '@/app/api/v1/companies/[companyId]/compliance/check/route'
|
||||
|
||||
// Phase 4 PR-2 — fiscal-periods async ops (lock/close/year-end/opening-balances/currency-revaluation).
|
||||
|
||||
@@ -297,10 +297,10 @@ export function generateOpenApiSpec(serverUrl: string): OpenApiSpec {
|
||||
return {
|
||||
openapi: '3.1.0',
|
||||
info: {
|
||||
title: 'gnubok API',
|
||||
title: 'Accounted API',
|
||||
version: API_V1_VERSION,
|
||||
description:
|
||||
'Public REST API for gnubok — Swedish double-entry bookkeeping. ' +
|
||||
'Public REST API for Accounted — Swedish double-entry bookkeeping. ' +
|
||||
'Every write supports dry-run via `?dry_run=true`. Every request must include ' +
|
||||
'`Authorization: Bearer gnubok_sk_...`. See /docs/api for the cookbook.',
|
||||
},
|
||||
|
||||
@@ -30,7 +30,7 @@ export const PUBLIC_SECURITY_HEADERS: Record<string, string> = {
|
||||
// form contexts. `default-src 'none'` is the strictest possible CSP and
|
||||
// costs nothing here.
|
||||
'Content-Security-Policy': "default-src 'none'; frame-ancestors 'none'",
|
||||
// HSTS — every gnubok deployment is HTTPS-only. 1 year is the standard
|
||||
// HSTS — every Accounted deployment is HTTPS-only. 1 year is the standard
|
||||
// production value; includeSubDomains because the apex serves everything.
|
||||
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
|
||||
}
|
||||
|
||||
+1
-1
@@ -103,7 +103,7 @@ export const V1_ENDPOINT_SCOPES: Record<string, ApiKeyScope> = {
|
||||
'POST /api/v1/companies/:companyId/fiscal-periods/:id/year-end': 'bookkeeping:write',
|
||||
'POST /api/v1/companies/:companyId/fiscal-periods/:id/opening-balances': 'bookkeeping:write',
|
||||
'POST /api/v1/companies/:companyId/fiscal-periods/:id/currency-revaluation': 'bookkeeping:write',
|
||||
// Compliance check (gnubok's defensible edge).
|
||||
// Compliance check (Accounted's defensible edge).
|
||||
'GET /api/v1/companies/:companyId/compliance/check': 'compliance:read',
|
||||
// Phase 4 PR-3 — Documents (multipart).
|
||||
'POST /api/v1/companies/:companyId/documents': 'documents:write',
|
||||
|
||||
@@ -43,7 +43,7 @@ describe('branding service', () => {
|
||||
const b = getBranding()
|
||||
expect(b.appName).toBe('Accounted')
|
||||
expect(b.appDescription).toBe('Ekonomihantering')
|
||||
expect(b.legalEntity).toBe('Arcim')
|
||||
expect(b.legalEntity).toBe('Arcim Technology AB')
|
||||
expect(b.supportEmail).toBe('[email protected]')
|
||||
expect(b.privacyEmail).toBe('[email protected]')
|
||||
expect(b.securityEmail).toBe('[email protected]')
|
||||
@@ -128,7 +128,7 @@ describe('branding service', () => {
|
||||
registerBrandingService({ appName: 'Holdio' })
|
||||
const b = getBranding()
|
||||
expect(b.appName).toBe('Holdio')
|
||||
expect(b.legalEntity).toBe('Arcim')
|
||||
expect(b.legalEntity).toBe('Arcim Technology AB')
|
||||
expect(b.supportEmail).toBe('[email protected]')
|
||||
})
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* defaults < env vars < extension override
|
||||
*
|
||||
* If nothing is set, gnubok defaults are returned — production behaviour
|
||||
* If nothing is set, Accounted defaults are returned — production behaviour
|
||||
* is unchanged. A whitelabel sets env vars (NEXT_PUBLIC_BRANDING_* for
|
||||
* client-readable, BRANDING_* for server-only) or registers a branding
|
||||
* extension via registerBrandingService().
|
||||
@@ -60,8 +60,8 @@ export interface BrandingConfig {
|
||||
const DEFAULT_BRANDING: BrandingConfig = {
|
||||
appName: 'Accounted',
|
||||
appDescription: 'Ekonomihantering',
|
||||
legalEntity: 'Arcim',
|
||||
// Emails and URLs intentionally keep the gnubok hostname — the rebrand is
|
||||
legalEntity: 'Arcim Technology AB',
|
||||
// Emails and URLs intentionally keep the gnubok.se hostname — the rebrand is
|
||||
// visual only; we don't churn the support inbox or app domain alongside it.
|
||||
supportEmail: '[email protected]',
|
||||
privacyEmail: '[email protected]',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { EntityType } from '@/types'
|
||||
|
||||
/**
|
||||
* Explicit allow-lists for TIC/Bolagsverket `legalEntityType` → gnubok
|
||||
* Explicit allow-lists for TIC/Bolagsverket `legalEntityType` → Accounted
|
||||
* EntityType. Strict (not substring) matching avoids misclassifications like
|
||||
* "Enskild stiftelse" → enskild_firma, which would provision with K1/
|
||||
* kontantmetoden defaults — an ML/BFL correctness risk.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { luhnValidate } from '@/lib/bankgiro/luhn'
|
||||
|
||||
/**
|
||||
* Normalize an org number to gnubok's canonical 10-digit storage form.
|
||||
* Normalize an org number to Accounted's canonical 10-digit storage form.
|
||||
*
|
||||
* Accepts hyphen/space-formatted input in either of the two shapes Swedish
|
||||
* users commonly type:
|
||||
@@ -12,7 +12,7 @@ import { luhnValidate } from '@/lib/bankgiro/luhn'
|
||||
* check digit (the structural rule Bolagsverket and personnummer share).
|
||||
* Storing a structurally invalid org number would later be caught by
|
||||
* Skatteverket SRU and any receiving SIE4 system — refusing at the boundary
|
||||
* keeps gnubok's bookkeeping from accumulating under an unusable identifier.
|
||||
* keeps Accounted's bookkeeping from accumulating under an unusable identifier.
|
||||
*
|
||||
* 10-digit storage matches the rest of the codebase — see
|
||||
* `lib/skatteverket/format.ts`, which converts 10→12 at export time by
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { CompanyLookupResult } from '@/lib/company-lookup/types'
|
||||
|
||||
/**
|
||||
* Check whether an org number is already registered in any non-archived
|
||||
* gnubok company. Uses the service role because RLS hides rows the caller
|
||||
* Accounted company. Uses the service role because RLS hides rows the caller
|
||||
* isn't a member of — and "other users' duplicates" is exactly what we
|
||||
* need to detect. Returns null when `orgNumber` is empty/malformed. Throws
|
||||
* if the underlying query fails — callers must not silently treat that as
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,6 +1,6 @@
|
||||
export const COOKBOOK_INGEST_BANK_MD = `# Cookbook — ingest and categorise bank transactions
|
||||
|
||||
> Push a bank statement file into gnubok, get AI-assisted category suggestions, commit the categorisations, and match payments against open invoices. End-to-end transaction-to-booking pipeline.
|
||||
> Push a bank statement file into Accounted, get AI-assisted category suggestions, commit the categorisations, and match payments against open invoices. End-to-end transaction-to-booking pipeline.
|
||||
|
||||
This is the operational companion to the [Transactions reference](/docs/api/reference/transactions) and the [Imports reference](/docs/api/reference/imports). Use it for the first integration where transactions enter the system from a bank source.
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ export const QUICKSTART_MD = `# Quickstart — send your first invoice
|
||||
|
||||
## What you'll need
|
||||
|
||||
- A test API key (\`gnubok_sk_test_*\`) from the gnubok dashboard at **/settings/api**. Test keys are bound to a deterministic sandbox company seeded with realistic data — safe for evals.
|
||||
- A test API key (\`gnubok_sk_test_*\`) from the Accounted dashboard at **/settings/api**. Test keys are bound to a deterministic sandbox company seeded with realistic data — safe for evals.
|
||||
- \`curl\` or any HTTP client.
|
||||
|
||||
## 1. List the companies the key can access
|
||||
|
||||
@@ -109,7 +109,7 @@ Failures return \`SALARY_RUN_APPROVE_VALIDATION_FAILED\` with a per-employee bre
|
||||
|
||||
## 4. Mark paid (approved → paid)
|
||||
|
||||
After the bank transfer settles (or you mark it on the same day for cash-method shops), tell gnubok:
|
||||
After the bank transfer settles (or you mark it on the same day for cash-method shops), tell Accounted:
|
||||
|
||||
\`\`\`bash
|
||||
curl -X POST "https://gnubok.app/api/v1/companies/$COMPANY_ID/salary-runs/$SR_ID/mark-paid" \\
|
||||
|
||||
@@ -7,7 +7,7 @@ This is the operational companion to the [Webhooks concept page](/docs/api/webho
|
||||
## What you'll need
|
||||
|
||||
- A test API key with \`webhooks:manage\` scope (and \`payroll:read\` if you intend to subscribe to payroll events).
|
||||
- A receiver URL that gnubok can POST to. For local development use [smee.io](https://smee.io) or \`ngrok\` — gnubok refuses webhook URLs that resolve to private IPs (SSRF protection), so localhost won't work directly.
|
||||
- A receiver URL that Accounted can POST to. For local development use [smee.io](https://smee.io) or \`ngrok\` — Accounted refuses webhook URLs that resolve to private IPs (SSRF protection), so localhost won't work directly.
|
||||
- HTTPS only — \`http://\` URLs are rejected at registration.
|
||||
|
||||
## 1. Register the webhook
|
||||
@@ -82,7 +82,7 @@ X-Gnubok-Event: webhook.test
|
||||
X-Gnubok-Delivery: wh_dlv_...
|
||||
X-Gnubok-Api-Version: 2026-05-12
|
||||
|
||||
{"id":"wh_dlv_...","type":"webhook.test","api_version":"2026-05-12","created":1715797800,"data":{"object":{"hello":"from gnubok","tested_at":"2026-05-15T12:00:00Z"}},"previous_attributes":null}
|
||||
{"id":"wh_dlv_...","type":"webhook.test","api_version":"2026-05-12","created":1715797800,"data":{"object":{"hello":"from Accounted","tested_at":"2026-05-15T12:00:00Z"}},"previous_attributes":null}
|
||||
\`\`\`
|
||||
|
||||
If your receiver returns 2xx, the delivery moves to \`delivered\`. If it returns 4xx (other than 410) or 5xx, it goes to \`failed\` and retries on the schedule \`1m / 5m / 30m / 2h / 12h / 24h / 48h\`.
|
||||
@@ -148,7 +148,7 @@ async function handleEvent(event) {
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
This pattern: a unique constraint on \`delivery_id\`, an INSERT-on-conflict-do-nothing, and short-circuit when nothing was inserted. Every gnubok delivery passes through that gate at most once even if the dispatcher retries.
|
||||
This pattern: a unique constraint on \`delivery_id\`, an INSERT-on-conflict-do-nothing, and short-circuit when nothing was inserted. Every Accounted delivery passes through that gate at most once even if the dispatcher retries.
|
||||
|
||||
## Replaying a dead delivery
|
||||
|
||||
@@ -181,7 +181,7 @@ This clears \`disabled_at\` and \`disabled_reason\` but does NOT replay the deli
|
||||
|
||||
## Common pitfalls
|
||||
|
||||
- **Re-serialising the body.** \`JSON.parse(rawBody); JSON.stringify(parsed)\` produces different bytes than gnubok sent. Always sign-check against the raw bytes.
|
||||
- **Re-serialising the body.** \`JSON.parse(rawBody); JSON.stringify(parsed)\` produces different bytes than Accounted sent. Always sign-check against the raw bytes.
|
||||
- **Forgetting the timestamp window.** Without a \`t\` check, an attacker who captured one signed payload can replay it forever. 5 minutes is the recommended tolerance.
|
||||
- **Returning 5xx for application errors.** A 5xx triggers full retries (~72h). If a payload is malformed-but-stable, return 200 and queue for internal investigation.
|
||||
- **Treating \`failed\` as terminal.** \`failed\` rows will retry; only \`delivered\` and \`dead\` are terminal. Don't alert on \`failed\` — alert when retries exhaust to \`dead\`.
|
||||
|
||||
@@ -73,7 +73,7 @@ export function buildErrorReferenceMd(): string {
|
||||
const lines: string[] = []
|
||||
lines.push('# Errors')
|
||||
lines.push('')
|
||||
lines.push(`> Every error returned by the gnubok REST API uses a stable code from this catalogue. Codes never change once shipped — agents can pattern-match on them safely. The \`docs_url\` field on every error envelope points at the anchor for that specific code.`)
|
||||
lines.push(`> Every error returned by the Accounted REST API uses a stable code from this catalogue. Codes never change once shipped — agents can pattern-match on them safely. The \`docs_url\` field on every error envelope points at the anchor for that specific code.`)
|
||||
lines.push('')
|
||||
lines.push('## Envelope shape')
|
||||
lines.push('')
|
||||
|
||||
@@ -188,7 +188,7 @@ export function buildReferenceOverviewMd(): string {
|
||||
const lines: string[] = []
|
||||
lines.push('# API reference')
|
||||
lines.push('')
|
||||
lines.push(`> Every endpoint exposed by the gnubok REST API, grouped by resource. Auto-generated from the same Zod registry that powers the [OpenAPI 3.1 spec](/api/v1/openapi.json), the MCP tool surface, and runtime validators — there is no separate doc-source to keep in sync.`)
|
||||
lines.push(`> Every endpoint exposed by the Accounted REST API, grouped by resource. Auto-generated from the same Zod registry that powers the [OpenAPI 3.1 spec](/api/v1/openapi.json), the MCP tool surface, and runtime validators — there is no separate doc-source to keep in sync.`)
|
||||
lines.push('')
|
||||
lines.push('## Resources')
|
||||
lines.push('')
|
||||
|
||||
File diff suppressed because one or more lines are too long
+1
-1
@@ -24,7 +24,7 @@ export const DOCS_NAV: DocsNavSection[] = [
|
||||
{
|
||||
label: 'Getting started',
|
||||
links: [
|
||||
{ label: 'Introduction', href: '/docs/api', summary: 'What the gnubok REST API is and how to authenticate.' },
|
||||
{ label: 'Introduction', href: '/docs/api', summary: 'What the Accounted REST API is and how to authenticate.' },
|
||||
{ label: 'Quickstart', href: '/docs/api/cookbook/quickstart', summary: 'Send your first invoice in five minutes.' },
|
||||
{ label: 'Authentication', href: '/docs/api#authentication', summary: 'API keys, scopes, test mode.' },
|
||||
],
|
||||
|
||||
@@ -26,7 +26,7 @@ describe('getStructuredError', () => {
|
||||
}
|
||||
const result = getStructuredError(new FakeBookkeepingError())
|
||||
expect(result.code).toBe('ACCOUNTS_NOT_IN_CHART')
|
||||
expect(result.remediation?.resource).toBe('gnubok://chart-of-accounts')
|
||||
expect(result.remediation?.resource).toBe('Accounted://chart-of-accounts')
|
||||
})
|
||||
|
||||
it('infers PERIOD_NOT_LOCKED from message text', () => {
|
||||
@@ -50,7 +50,7 @@ describe('getStructuredError', () => {
|
||||
)
|
||||
expect(result.code).toBe('INSUFFICIENT_SCOPE')
|
||||
expect(result.remediation?.description).toContain('"bookkeeping:write"')
|
||||
expect(result.remediation?.resource).toBe('gnubok://capabilities')
|
||||
expect(result.remediation?.resource).toBe('Accounted://capabilities')
|
||||
})
|
||||
|
||||
it('infers TRANSACTION_ALREADY_CATEGORIZED', () => {
|
||||
|
||||
@@ -114,7 +114,7 @@ const GENERIC: Record<string, StructuredErrorEntry> = {
|
||||
remediation: {
|
||||
description:
|
||||
'Mint a new key with the missing scope or grant it through the API key settings.',
|
||||
resource: 'gnubok://capabilities',
|
||||
resource: 'Accounted://capabilities',
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -131,7 +131,7 @@ const BOOKKEEPING: Record<string, StructuredErrorEntry> = {
|
||||
remediation: {
|
||||
description:
|
||||
'Activate the missing accounts via bookkeeping settings, or use a different category.',
|
||||
resource: 'gnubok://chart-of-accounts',
|
||||
resource: 'Accounted://chart-of-accounts',
|
||||
},
|
||||
},
|
||||
JOURNAL_ENTRY_NOT_BALANCED: {
|
||||
@@ -148,7 +148,7 @@ const BOOKKEEPING: Record<string, StructuredErrorEntry> = {
|
||||
message_en: 'No fiscal period covers the entry date.',
|
||||
remediation: {
|
||||
description: 'Create or extend the relevant fiscal period before retrying.',
|
||||
resource: 'gnubok://period/active',
|
||||
resource: 'Accounted://period/active',
|
||||
},
|
||||
},
|
||||
ENTRY_DATE_OUTSIDE_FISCAL_PERIOD: {
|
||||
@@ -157,7 +157,7 @@ const BOOKKEEPING: Record<string, StructuredErrorEntry> = {
|
||||
message_en: 'Entry date is outside the active fiscal period.',
|
||||
remediation: {
|
||||
description: 'Use a date inside an open period or create one that covers it.',
|
||||
resource: 'gnubok://period/active',
|
||||
resource: 'Accounted://period/active',
|
||||
},
|
||||
},
|
||||
JOURNAL_ENTRY_NOT_FOUND: {
|
||||
@@ -272,7 +272,7 @@ const TRANSACTIONS: Record<string, StructuredErrorEntry> = {
|
||||
message_en: 'The supplied account does not exist in the chart of accounts.',
|
||||
remediation: {
|
||||
description: 'Activate the account in the chart of accounts or pick a different one.',
|
||||
resource: 'gnubok://chart-of-accounts',
|
||||
resource: 'Accounted://chart-of-accounts',
|
||||
},
|
||||
},
|
||||
TX_CATEGORIZE_INVALID_TEMPLATE: {
|
||||
|
||||
+1
-1
@@ -174,7 +174,7 @@ export type CoreEvent =
|
||||
// get loaded by agents. `kind` discriminates by URI scheme so we can
|
||||
// GROUP BY skill vs widget vs data without parsing URIs.
|
||||
| { type: 'mcp.resource_read'; payload: {
|
||||
uri: string // e.g. 'gnubok://skill/month-end-close'
|
||||
uri: string // e.g. 'Accounted://skill/month-end-close'
|
||||
kind: 'widget' | 'skill' | 'data' | 'unknown'
|
||||
success: boolean
|
||||
errorCode: string | null
|
||||
|
||||
@@ -1024,7 +1024,7 @@ describe('importVouchers — per-voucher series preservation', () => {
|
||||
it('preserves original source series/number on each imported entry, even across skipped vouchers', async () => {
|
||||
const { supabase, journalEntryInserts } = buildCapturingSupabase()
|
||||
// A2 is an empty voucher (no lines) — will be skipped. A1 and A3 survive.
|
||||
// Gnubok assigns target numbers 1 and 2 (contiguous), but source_voucher_number
|
||||
// Accounted assigns target numbers 1 and 2 (contiguous), but source_voucher_number
|
||||
// must preserve the SIE originals (1 and 3) so traceability is not lost.
|
||||
const parsed = makeParsedFile({
|
||||
vouchers: [
|
||||
|
||||
@@ -355,7 +355,7 @@ export async function ensureFiscalPeriod(
|
||||
|
||||
if (!replaceableGateOpen || hasEntries) {
|
||||
throw new Error(
|
||||
`SIE-filens räkenskapsår (${startDate} – ${endDate}) överlappar men matchar inte ett befintligt räkenskapsår i gnubok ` +
|
||||
`SIE-filens räkenskapsår (${startDate} – ${endDate}) överlappar men matchar inte ett befintligt räkenskapsår i Accounted ` +
|
||||
`(${existing.name}: ${existing.period_start} – ${existing.period_end}). ` +
|
||||
`Justera räkenskapsåret i Inställningar → Företag så att det matchar SIE-filen exakt, eller importera en SIE-fil som täcker exakt samma period.`
|
||||
)
|
||||
@@ -902,11 +902,28 @@ export async function importVouchers(
|
||||
// traceability alongside the aggregate sie_imports.migration_documentation.
|
||||
sourceSeries: string | null
|
||||
sourceNumber: number | null
|
||||
// 'import' for ordinary migrated vouchers; 'opening_balance' for a #VER that
|
||||
// is really the year's ingående balans (see isLikelyOpeningBalance below).
|
||||
sourceType: 'import' | 'opening_balance'
|
||||
lines: { account_number: string; debit_amount: number; credit_amount: number; line_description: string | null }[]
|
||||
}
|
||||
|
||||
const preparedVouchers: PreparedVoucher[] = []
|
||||
|
||||
// A SIE file represents the opening balance either as #IB records (handled
|
||||
// separately by createOpeningBalanceEntry → source_type='opening_balance') or,
|
||||
// in some source systems, as an ordinary #VER dated on the fiscal-year start.
|
||||
// When there are NO current-year #IB records, detect a clearly-labelled IB
|
||||
// voucher and tag it opening_balance so bank reconciliation excludes it from
|
||||
// the period movement (otherwise it lands as 'import' and surfaces as a phantom
|
||||
// difference equal to the IB). Deliberately conservative — requires the IB
|
||||
// wording AND a balance-sheet-only voucher on FY start, and never a
|
||||
// share-capital deposit. A missed IB still falls back to the manual "Märk som
|
||||
// ingående balans" action in Bankavstämning, so we never risk hiding a real
|
||||
// bank movement by over-classifying.
|
||||
const hasCurrentYearIb = parsed.openingBalances.some((b) => b.yearIndex === 0)
|
||||
const fyStart = parsed.stats.fiscalYearStart
|
||||
|
||||
for (const voucher of parsed.vouchers) {
|
||||
const lines: PreparedVoucher['lines'] = []
|
||||
let hasUnmappedAccount = false
|
||||
@@ -1038,13 +1055,23 @@ export async function importVouchers(
|
||||
const rawSourceSeries = voucher.series && voucher.series.trim() ? voucher.series.trim() : null
|
||||
const rawSourceNumber = Number.isFinite(voucher.number) ? voucher.number : null
|
||||
|
||||
const voucherDateStr = formatDate(voucher.date)
|
||||
const isLikelyOpeningBalance =
|
||||
!hasCurrentYearIb &&
|
||||
!!fyStart && fyStart.slice(0, 10) === voucherDateStr &&
|
||||
lines.length > 0 &&
|
||||
lines.every((l) => isBalanceSheetAccount(l.account_number)) &&
|
||||
/ing[åa]ende balans|ing[åa]ende saldo|opening balance/i.test(voucher.description || '') &&
|
||||
!/aktiekapital/i.test(voucher.description || '')
|
||||
|
||||
preparedVouchers.push({
|
||||
sourceId: voucherId,
|
||||
series: resolvedSeries,
|
||||
date: formatDate(voucher.date),
|
||||
date: voucherDateStr,
|
||||
description: voucher.description || `Import: ${voucher.series}${voucher.number}`,
|
||||
sourceSeries: rawSourceSeries,
|
||||
sourceNumber: rawSourceNumber,
|
||||
sourceType: isLikelyOpeningBalance ? 'opening_balance' : 'import',
|
||||
lines,
|
||||
})
|
||||
}
|
||||
@@ -1141,7 +1168,7 @@ export async function importVouchers(
|
||||
voucher_series: series,
|
||||
entry_date: v.date,
|
||||
description: v.description,
|
||||
source_type: 'import',
|
||||
source_type: v.sourceType,
|
||||
source_voucher_series: v.sourceSeries,
|
||||
source_voucher_number: v.sourceNumber,
|
||||
status: 'posted',
|
||||
@@ -1778,7 +1805,7 @@ export async function loadMappings(supabase: SupabaseClient, companyId: string):
|
||||
* updated data from Fortnox without manual cleanup.
|
||||
*
|
||||
* Replace only cancels journal entries with source_type='import' — entries
|
||||
* the user created natively in gnubok (categorized transactions, invoices,
|
||||
* the user created natively in Accounted (categorized transactions, invoices,
|
||||
* etc.) are left alone. See the replace_sie_import RPC.
|
||||
*/
|
||||
export async function executeSIEImport(
|
||||
|
||||
@@ -60,21 +60,21 @@ describe('isWcagAACompliant', () => {
|
||||
expect(isWcagAACompliant('#ffff00', '#ffffff')).toBe(false)
|
||||
})
|
||||
|
||||
// gnubok brand semantic colors. All three are used as DATA-ONLY indicators
|
||||
// Accounted brand semantic colors. All three are used as DATA-ONLY indicators
|
||||
// (charts, positive/negative deltas), never as chrome text on white. These
|
||||
// tests document where they sit relative to AA — terracotta/destructive is
|
||||
// the only one that comfortably passes AA on white.
|
||||
it('gnubok terracotta (#c2410c equivalent dark red) passes AA on white', () => {
|
||||
it('Accounted terracotta (#c2410c equivalent dark red) passes AA on white', () => {
|
||||
// 5.91:1 — passes AA for normal text.
|
||||
expect(isWcagAACompliant('#c2410c', '#ffffff')).toBe(true)
|
||||
})
|
||||
|
||||
it('gnubok sage (#84a98c lighter green) fails AA on white', () => {
|
||||
it('Accounted sage (#84a98c lighter green) fails AA on white', () => {
|
||||
// ~2.4:1 — fails AA, as expected for a soft pastel sage.
|
||||
expect(isWcagAACompliant('#84a98c', '#ffffff')).toBe(false)
|
||||
})
|
||||
|
||||
it('gnubok ochre (#d4a373 warm yellow) fails AA on white', () => {
|
||||
it('Accounted ochre (#d4a373 warm yellow) fails AA on white', () => {
|
||||
// ~2.3:1 — fails AA, as expected for a warm soft ochre.
|
||||
expect(isWcagAACompliant('#d4a373', '#ffffff')).toBe(false)
|
||||
})
|
||||
|
||||
@@ -54,7 +54,7 @@ const LATE_PAYMENT_PREMIUM = 0.08 // 8 procentenheter per Räntelagen §6
|
||||
*
|
||||
* If the requested date is before the earliest entry in the table we fall
|
||||
* back to the earliest entry (this is a defensive measure — should never
|
||||
* happen in practice since gnubok was launched after 2022).
|
||||
* happen in practice since Accounted was launched after 2022).
|
||||
*/
|
||||
export function getReferensrantaAt(date: string): number {
|
||||
// Walk newest-first so the first match wins.
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
amountsMatchFuzzy,
|
||||
customerNameMatches,
|
||||
} from './invoice-matching'
|
||||
import { autoReconcileTransactionForLinkedVoucher } from '@/lib/reconciliation/bank-reconciliation'
|
||||
import type { SupplierInvoice, Supplier } from '@/types'
|
||||
|
||||
const log = createLogger('supplier-voucher-matching')
|
||||
@@ -480,6 +481,9 @@ export interface LinkSupplierInvoiceToVoucherResult {
|
||||
remainingAmount: number
|
||||
paymentAmount: number
|
||||
journalEntryId: string
|
||||
/** Bank transaction auto-reconciled to the linked voucher, if exactly one
|
||||
* unbooked line matched it; null when nothing was safely linkable. */
|
||||
reconciledTransactionId: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -594,6 +598,29 @@ export async function linkSupplierInvoiceToVoucher(
|
||||
}
|
||||
}
|
||||
|
||||
// Close the loop on the bank feed: the link above only advanced the supplier
|
||||
// invoice, leaving the bank transaction that paid it in the Transactions
|
||||
// inbox. Reconcile it to the same verifikat when unambiguous. Best-effort —
|
||||
// the link RPC has already committed.
|
||||
let reconciledTransactionId: string | null = null
|
||||
try {
|
||||
const recon = await autoReconcileTransactionForLinkedVoucher(
|
||||
supabase,
|
||||
companyId,
|
||||
userId,
|
||||
params.journalEntryId,
|
||||
{ supplierInvoiceId: params.supplierInvoiceId },
|
||||
)
|
||||
reconciledTransactionId = recon?.linkedTransactionId ?? null
|
||||
} catch (err) {
|
||||
log.warn('auto-reconcile of bank transaction after supplier voucher link failed (non-blocking)', {
|
||||
companyId,
|
||||
supplierInvoiceId: params.supplierInvoiceId,
|
||||
journalEntryId: params.journalEntryId,
|
||||
reason: err instanceof Error ? err.message : String(err),
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
result: {
|
||||
@@ -603,6 +630,7 @@ export async function linkSupplierInvoiceToVoucher(
|
||||
remainingAmount: result.remaining_amount,
|
||||
paymentAmount: result.payment_amount,
|
||||
journalEntryId: result.journal_entry_id,
|
||||
reconciledTransactionId,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user