Bug/invalid imports (#1146)

* feat: add Accounted MCP namespace

* fix(bookkeeping): stop flagging verifikat whose underlag lives on a referenced supplier invoice

The missing-underlag surfaces only accepted a document directly linked to
the entry, so payment verifikat for supplier invoices (doc on the
registration entry per design) and entries whose doc was pinned to the
bank transaction before matching were falsely flagged; opening the entry
showed the referenced doc and cleared the warning client-side, and it
came back on reload.

- verifikat_without_documents + transactions_without_documents now treat
  an entry as covered when a supplier invoice referencing it (registration
  or payment FK, or a supplier_invoice_payments row) carries a document
  anchored to a journal entry (BFL 5 kap 7 paragraf hänvisning till
  underlag; anchoring required because the WORM deletion guards key on
  document_attachments.journal_entry_id)
- match-supplier-invoice routes (dashboard + v1) propagate the
  transaction's pinned document onto the payment verifikat, mirroring the
  categorize route; migration backfills rows already written (open
  unlocked periods, company-guarded, never steals a linked doc)
- /api/documents/counts, the transactions-page badges, the bulk "Inget
  underlag krävs" count and the push-notification scheduler share the
  same reference-aware predicate, so every surface agrees with the RPC
- counts route validates journal_entry_ids as UUIDs (they are
  interpolated into a PostgREST or-filter)

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

* fix(transactions): align table columns flush with page edges

Collapse the checkbox gutter column to zero width and hang the
hover-revealed checkbox/expand chevron in the page margins, drop the
outer padding so DATUM sits flush left and STATUS flush right, and
tuck the overflow-menu dots under the middle of the STATUS header.
Applied to both the inbox and history tables so they stay identical.

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

* fix(arsredovisning): tie anlaggningstillgangar note to booked depreciation

The ARL 5:8 roll-forward note recomputed depreciation from its own
day-based linear formula (365.25/12 month length, non-inclusive day
count, linear only), drifting ~20 kr per year per asset from the
ledger-driven resultat- and balansrakning and misstating non-linear
methods entirely. Note figures now come from posted
depreciation_schedules rows (the same source disposeAsset reverses),
falling back to the engine's computeAnnualDepreciation when nothing is
posted; pre-onboarding opening balances iterate prior years through
the engine. Adds a note-vs-trial-balance tie-out warning (accounts
1000-1299, over 1 kr) surfaced before download.

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

* refactor(stripe): move connect and sync surface from settings to import page

Stripe's transaction feed is a continuous import source in the same
category as the PSD2 bank connection, so its connect/sync surface now
lives on the import page as a source card (mode=stripe), gated
"kommer snart" on hosted like before; self-hosted keeps the full panel.

- Import page: Stripe card after Koppla bank, renders the existing
  StripeSettingsPanel via the settings-panel registry
- OAuth callback and panel cleanup return to /import?mode=stripe
- Settings > Betalningar retired: nav item removed, route redirects,
  PaymentsSettingsContent deleted, legacy ?tab=payments mapped
- New import.stripe_* strings in sv+en; dead settings_nav.payments removed

Crons and sync logic unchanged; payment-link settings stay in the
invoicing section.

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

* fix(underlag): paginate missing-underlag cron and harden doc-surface queries

Resolve PR review findings on bug/invalid-imports:
- notification-scheduler: fetchAllRows on all 5 global reads; past 1000 rows
  the capped reads produced false "saknade underlag" notifications
- bulk-missing: LOOKUP_CHUNK 300->150 so the twice-embedded .or() id list
  stays under the PostgREST URL limit
- bulk-missing + transactions page: UUID-guard the .or()-interpolated id
  lists, matching documents/counts
- match-supplier-invoice (dashboard + v1): log documentId/journalEntryId on
  the non-fatal doc-link warning
- well-known/oauth-protected-resource: document the tool_namespace allow-list
- messages/en: reword stripe_description
- DECISIONS.md: record the asset ibAck tie-out and Tailwind !important calls

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(tic): convert registrationDate from Unix seconds to millisecond epoch in lookup and profile tests

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-07-24 15:03:50 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent 51ca574ca4
commit 53e343ee92
71 changed files with 3085 additions and 452 deletions
+57
View File
@@ -0,0 +1,57 @@
# accounted-mcp
Connect Claude Desktop, Claude Code, or another stdio MCP client to your
[Accounted](https://app.accounted.se) bookkeeping account.
This zero-dependency bridge forwards JSON-RPC over stdio to the hosted Accounted
MCP server. New connections receive the `accounted_*` tool namespace. Existing
`gnubok-mcp` configurations remain supported separately.
## Setup
1. Create an API key in Accounted under **Settings > API**.
2. Add the bridge to your MCP client:
```json
{
"mcpServers": {
"accounted": {
"command": "npx",
"args": ["-y", "accounted-mcp"],
"env": {
"ACCOUNTED_API_KEY": "gnubok_sk_test_...",
"ACCOUNTED_CLIENT": "claude-desktop"
}
}
}
}
```
The credential value retains the legacy `gnubok_sk_*` wire prefix for backward
compatibility. Only the MCP integration is being renamed in this release.
## Environment variables
| Variable | Required | Default | Description |
|---|---:|---|---|
| `ACCOUNTED_API_KEY` | yes | none | Your existing Accounted API key. |
| `ACCOUNTED_URL` | no | Accounted hosted MCP endpoint | Override for self-hosted Accounted. The bridge adds `tool_namespace=accounted` when omitted. |
| `ACCOUNTED_CLIENT` | no | none | Telemetry-only distribution marker such as `claude-desktop`. |
The API key scopes determine which tools are visible and callable. Write tools
stage pending operations for explicit approval before anything is booked.
## OAuth connector
Clients with OAuth custom-connector support can connect directly without this
bridge:
```text
https://app.accounted.se/api/extensions/ext/mcp-server/mcp?tool_namespace=accounted
```
## Compatibility
The legacy `gnubok-mcp` package, environment variables, endpoint behavior, and
`gnubok_*` tool aliases remain supported. Existing installations do not need to
change.
@@ -0,0 +1,35 @@
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { describe, expect, it } from 'vitest'
const packageDir = path.resolve(__dirname, '..')
const packageJson = JSON.parse(
readFileSync(path.join(packageDir, 'package.json'), 'utf8')
) as {
name: string
bin: Record<string, string>
dependencies?: Record<string, string>
}
const source = readFileSync(path.join(packageDir, 'index.mjs'), 'utf8')
describe('accounted-mcp package', () => {
it('publishes the Accounted command without runtime dependencies', () => {
expect(packageJson.name).toBe('accounted-mcp')
expect(packageJson.bin).toEqual({ 'accounted-mcp': './index.mjs' })
expect(packageJson.dependencies).toBeUndefined()
})
it('uses Accounted configuration names and preserves the API-key wire prefix', () => {
expect(source).toContain('ACCOUNTED_API_KEY')
expect(source).toContain('ACCOUNTED_URL')
expect(source).toContain('ACCOUNTED_CLIENT')
expect(source).toContain('X-Accounted-Client')
expect(source).toContain('tool_namespace')
expect(source).toContain('gnubok_sk_')
expect(source).not.toContain('GNUBOK_API_KEY')
expect(source).not.toContain('GNUBOK_URL')
expect(source).not.toContain('X-Gnubok-Client')
expect(source).not.toContain('app.gnubok.se')
})
})
+160
View File
@@ -0,0 +1,160 @@
#!/usr/bin/env node
/**
* accounted-mcp: Connect an MCP client to your Accounted bookkeeping account.
*
* Usage in claude_desktop_config.json:
* {
* "mcpServers": {
* "accounted": {
* "command": "npx",
* "args": ["-y", "accounted-mcp"],
* "env": {
* "ACCOUNTED_API_KEY": "gnubok_sk_..."
* }
* }
* }
* }
*/
const API_KEY = process.env.ACCOUNTED_API_KEY
const DEFAULT_MCP_URL =
'https://app.accounted.se/api/extensions/ext/mcp-server/mcp'
function resolveMcpUrl(rawUrl) {
try {
const url = new URL(rawUrl)
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
throw new Error('unsupported protocol')
}
if (!url.searchParams.has('tool_namespace')) {
url.searchParams.set('tool_namespace', 'accounted')
}
return url.toString()
} catch {
process.stderr.write('accounted-mcp: ACCOUNTED_URL must be a valid HTTP(S) URL\n')
process.exit(1)
}
}
const MCP_URL = resolveMcpUrl(process.env.ACCOUNTED_URL || DEFAULT_MCP_URL)
// Optional distribution-channel marker (for example, "claude-desktop").
// Forwarded for telemetry only and never used for authentication or behavior.
const rawClient = process.env.ACCOUNTED_CLIENT
const CLIENT =
rawClient && /^[A-Za-z0-9._-]{1,64}$/.test(rawClient) ? rawClient : undefined
if (rawClient && !CLIENT) {
process.stderr.write(
'accounted-mcp: ignoring ACCOUNTED_CLIENT: must match [A-Za-z0-9._-]{1,64}\n'
)
}
if (!API_KEY) {
process.stderr.write(
'Error: ACCOUNTED_API_KEY is required.\n' +
'Get your API key at: https://app.accounted.se/settings?tab=api\n' +
'\n' +
'Add it to your Claude Desktop config:\n' +
'{\n' +
' "mcpServers": {\n' +
' "accounted": {\n' +
' "command": "npx",\n' +
' "args": ["-y", "accounted-mcp"],\n' +
' "env": {\n' +
' "ACCOUNTED_API_KEY": "gnubok_sk_..."\n' +
' }\n' +
' }\n' +
' }\n' +
'}\n'
)
process.exit(1)
}
let buffer = ''
process.stdin.setEncoding('utf8')
process.stdin.on('data', (chunk) => {
buffer += chunk
let newlineIdx
while ((newlineIdx = buffer.indexOf('\n')) !== -1) {
const line = buffer.slice(0, newlineIdx).trim()
buffer = buffer.slice(newlineIdx + 1)
if (!line) continue
handleMessage(line).catch((err) => {
process.stderr.write(`accounted-mcp error: ${err.message}\n`)
})
}
})
process.stdin.on('end', () => {
process.exit(0)
})
async function handleMessage(line) {
let parsed
try {
parsed = JSON.parse(line)
} catch {
process.stderr.write('accounted-mcp: invalid JSON\n')
return
}
const isNotification = parsed.id === undefined || parsed.id === null
try {
const res = await fetch(MCP_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${API_KEY}`,
...(CLIENT ? { 'X-Accounted-Client': CLIENT } : {}),
},
body: line,
})
if (res.status === 202 || res.status === 204) {
return
}
const responseText = await res.text()
// Guard against non-JSON error responses such as CDN or proxy pages.
if (!res.ok && !isNotification) {
let message = `HTTP ${res.status}`
try {
const json = JSON.parse(responseText)
if (json.error) {
message =
typeof json.error === 'string'
? json.error
: JSON.stringify(json.error)
}
} catch {
// The body was not JSON: use the generic HTTP status message.
}
const errorResponse = JSON.stringify({
jsonrpc: '2.0',
id: parsed.id,
error: { code: -32000, message },
})
process.stdout.write(`${errorResponse}\n`)
return
}
if (responseText) {
process.stdout.write(`${responseText}\n`)
}
} catch (err) {
if (!isNotification) {
const errorResponse = JSON.stringify({
jsonrpc: '2.0',
id: parsed.id,
error: { code: -32000, message: `Connection error: ${err.message}` },
})
process.stdout.write(`${errorResponse}\n`)
}
}
}
+28
View File
@@ -0,0 +1,28 @@
{
"name": "accounted-mcp",
"version": "1.0.0",
"description": "Connect MCP clients to your Accounted bookkeeping account",
"bin": {
"accounted-mcp": "./index.mjs"
},
"type": "module",
"license": "MIT",
"keywords": [
"mcp",
"accounted",
"bookkeeping",
"claude",
"accounting"
],
"repository": {
"type": "git",
"url": "https://github.com/erp-mafia/accounted"
},
"engines": {
"node": ">=18"
},
"files": [
"index.mjs",
"README.md"
]
}
+5
View File
@@ -1,5 +1,10 @@
# gnubok-mcp
Legacy compatibility package for existing MCP configurations. New installations
should use [`accounted-mcp`](https://www.npmjs.com/package/accounted-mcp).
This package, its environment variables, and all existing API keys remain
supported.
Connect [Claude Desktop](https://claude.ai/download) (or any stdio MCP client) to your [Accounted](https://app.gnubok.se) bookkeeping account. This is a thin stdio → HTTPS bridge: it forwards JSON-RPC over stdio to the hosted Accounted MCP server, which exposes 90+ bookkeeping tools (invoices, transactions, VAT/momsdeklaration, payroll, reports, year-end).
Write tools stage a pending operation that you confirm before anything is booked: the bridge never books on its own.