feat(transactions): underlag status badges + attach dialog; auto-expire stale pending ops (#712)
* feat(transactions): per-row underlag status + attach-document dialog
- New "Matcha mot underlag" dialog on /transactions (inbox pick or fresh
upload), the tx→doc mirror of the Documents view's matcher
- Per-row Underlag/Underlag saknas badges on booked history rows, driven
by computeJeUnderlagStatus — same posted-only, exemption-aware scope as
the worklist count so badge and count never disagree
- attach-document route + commit dispatcher now propagate the doc onto
the verifikation when the tx is already booked (BFL 5 kap 6 §), with a
409 guard for docs consumed by a different verifikation, idempotent
re-attach (no same-value rewrite under period lock), and an honest 409
when the period-lock trigger blocks the propagation
- Booking-dialog doc links also pin the doc to the transaction row
(first linked doc wins) via the link route's new transaction_id param
messages/{sv,en}.json also carries the strings for the pending-ops
expiry UI that lands in the next commit.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(pending-operations): auto-expire stale staged operations after 30 days
- New daily cron (02:30 UTC, vercel.json + both docker crontabs) flips
>30-day-old pending ops to rejected with the dispatcher's
{ auto_rejected: true, reason: 'expired' } result_data shape — rows are
never deleted, the table is the audit trail
- /pending renders an "Utgick automatiskt" badge + detail line for these,
orders terminal tabs by resolved_at so a fresh expiry sweep isn't
buried, and adds a first-time-reviewer explainer
- Origin labels spell out where a proposal came from (AI chat, MCP key,
API, cron) instead of the raw actor_label
- agent_chat actor type added to PendingOperationActorType/AuditLogEntry
(DB CHECK already widened in 20260519090000) and to the agent filter
- ApprovalCard notes that ignoring a proposal is safe
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs(mcp): surface the client telemetry marker in connect instructions
Tag the connector URLs shown in ApiKeysPanel, the connect-claude doc and
the gnubok-mcp README with ?client=<surface> (claude-connector /
claude-code) and GNUBOK_CLIENT=claude-desktop for the npm bridge.
Telemetry-only — the server already reads the param/header; this just
lets us measure which Claude surface connected.
The claude mcp add copy blocks quote the URL: an unquoted ? in the query
string trips zsh globbing ("no matches found").
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* review: fix stale-closure badge flip + zod-validate link route body (PR #712)
- handleDocumentAttached read journal_entry_id off the render-time
transactions snapshot; if the list changed while the attach dialog was
open the optimistic badge flip was silently skipped. Read it off the
dialog's own subject (attachDocTx) instead.
- POST /api/documents/[id]/link now validates the body against the new
LinkDocumentSchema (uuid-strict, all four fields) instead of a bare
presence check on journal_entry_id — same canonical VALIDATION_ERROR
envelope. Test fixtures switched to real UUIDs accordingly.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
e978136210
commit
0521c385d2
@@ -1730,6 +1730,13 @@ export const AttachDocumentSchema = z.object({
|
||||
document_id: uuid,
|
||||
})
|
||||
|
||||
export const LinkDocumentSchema = z.object({
|
||||
journal_entry_id: uuid,
|
||||
journal_entry_line_id: uuid.optional(),
|
||||
inbox_item_id: uuid.optional(),
|
||||
transaction_id: uuid.optional(),
|
||||
})
|
||||
|
||||
// ============================================================
|
||||
// Shift-premium rules (OB-tillägg och övertid)
|
||||
// ============================================================
|
||||
|
||||
@@ -17,8 +17,9 @@ Best for most users. No API key to manage — you authorise Accounted the same w
|
||||
1. In **claude.ai** (Settings → Connectors) or **Claude Desktop** (Settings → Connectors → Add custom connector), choose **Add custom connector**.
|
||||
2. Paste the connector URL:
|
||||
\`\`\`
|
||||
https://app.gnubok.se/api/extensions/ext/mcp-server/mcp
|
||||
https://app.gnubok.se/api/extensions/ext/mcp-server/mcp?client=claude-connector
|
||||
\`\`\`
|
||||
_(The "?client=claude-connector" suffix is telemetry-only — it lets Accounted see you connected via claude.ai/Desktop. It changes nothing about behaviour or scopes; drop the query string if you prefer.)_
|
||||
3. Claude opens the Accounted OAuth 2.1 consent screen. Sign in and pick the company you want Claude to act on.
|
||||
4. On the consent screen you grant **read-only scopes by default** (list invoices, read reports, compute VAT). Write scopes (create invoice, categorise, book vouchers, run year-end) are **listed separately and must be ticked explicitly** — leave them unchecked for a read-only review session.
|
||||
5. Approve. Claude now lists the Accounted tools and you can start asking questions.
|
||||
@@ -38,7 +39,8 @@ Best for Claude Desktop on a machine where you'd rather use a long-lived API key
|
||||
"command": "npx",
|
||||
"args": ["gnubok-mcp"],
|
||||
"env": {
|
||||
"GNUBOK_API_KEY": "gnubok_sk_test_..."
|
||||
"GNUBOK_API_KEY": "gnubok_sk_test_...",
|
||||
"GNUBOK_CLIENT": "claude-desktop"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -694,4 +694,75 @@ describe('commitPendingOperation: attach_document_to_transaction', () => {
|
||||
const tablesTouched = (supabase.from as ReturnType<typeof vi.fn>).mock.calls.map(c => c[0])
|
||||
expect(tablesTouched).toContain('invoice_inbox_items')
|
||||
})
|
||||
|
||||
it('auto-rejects 409 when the document already belongs to a different verifikation', async () => {
|
||||
// Without this guard the attach would pin a consumed doc (undetachable
|
||||
// per the transactions immutability trigger) and the later propagation
|
||||
// would corrupt or be blocked by the doc-metadata immutability trigger.
|
||||
// Mirrors the REST route's guard.
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null }) // CAS claim
|
||||
enqueue({ data: { id: 'tx-1', document_id: null, journal_entry_id: 'je-1' }, error: null })
|
||||
enqueue({ data: { id: 'doc-1', journal_entry_id: 'je-OTHER' }, error: null }) // doc fetch
|
||||
enqueue({ data: null, error: null }) // dispatcher reject update
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never,
|
||||
'user-1',
|
||||
'company-1',
|
||||
makePendingOp(baseOp),
|
||||
)
|
||||
expect(result.status).toBe('rejected')
|
||||
expect(result.http_status).toBe(409)
|
||||
})
|
||||
|
||||
it('skips the propagation write on an idempotent re-attach (doc already on the same verifikation)', async () => {
|
||||
// The period-lock trigger raises on ANY journal_entry_id write — even a
|
||||
// same-value rewrite — so an unconditional re-run would fail an otherwise
|
||||
// idempotent re-attach once the period locks.
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null }) // CAS claim
|
||||
enqueue({ data: { id: 'tx-1', document_id: 'doc-1', journal_entry_id: 'je-1' }, error: null })
|
||||
enqueue({ data: { id: 'doc-1', journal_entry_id: 'je-1' }, error: null }) // doc fetch — same JE
|
||||
enqueue({ data: { journal_entry_id: 'je-1' }, error: null }) // tx UPDATE returning
|
||||
enqueue({ data: null, error: null }) // invoice_inbox_items link
|
||||
enqueue({ data: null, error: null }) // dispatcher commit update
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never,
|
||||
'user-1',
|
||||
'company-1',
|
||||
makePendingOp(baseOp),
|
||||
)
|
||||
expect(result.status).toBe('committed')
|
||||
// document_attachments touched once (the doc fetch) — no propagation write.
|
||||
const tablesTouched = (supabase.from as ReturnType<typeof vi.fn>).mock.calls.map(c => c[0])
|
||||
expect(tablesTouched.filter((t) => t === 'document_attachments')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('maps a period-lock propagation failure to auto-reject 409', async () => {
|
||||
// A retry could never succeed until the period is unlocked, so the
|
||||
// generic 500 "försök igen" would be a false promise. Mirrors the REST
|
||||
// route's mapping.
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' }, error: null }) // CAS claim
|
||||
enqueue({ data: { id: 'tx-1', document_id: null, journal_entry_id: null }, error: null })
|
||||
enqueue({ data: { id: 'doc-1', journal_entry_id: null }, error: null }) // doc fetch
|
||||
enqueue({ data: { journal_entry_id: 'je-7' }, error: null }) // tx UPDATE returning — booked meanwhile
|
||||
enqueue({ data: null, error: null }) // invoice_inbox_items link
|
||||
enqueue({
|
||||
data: null,
|
||||
error: { message: 'cannot link document in a locked/closed fiscal period' },
|
||||
}) // propagation blocked by enforce_period_lock
|
||||
enqueue({ data: null, error: null }) // dispatcher reject update
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never,
|
||||
'user-1',
|
||||
'company-1',
|
||||
makePendingOp(baseOp),
|
||||
)
|
||||
expect(result.status).toBe('rejected')
|
||||
expect(result.http_status).toBe(409)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1453,12 +1453,25 @@ async function commitAttachDocumentToTransaction(
|
||||
|
||||
const { data: doc, error: docError } = await supabase
|
||||
.from('document_attachments')
|
||||
.select('id')
|
||||
.select('id, journal_entry_id')
|
||||
.eq('id', documentId)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
if (docError || !doc) return { error: 'Document not found', status: 404 }
|
||||
|
||||
// A document that already serves as underlag for a DIFFERENT verifikation
|
||||
// cannot be pinned here — propagating would either corrupt that link or be
|
||||
// blocked by the document-metadata immutability trigger. Same verifikation
|
||||
// is fine (idempotent re-attach; propagation below becomes a no-op).
|
||||
// Mirrors the REST route in app/api/transactions/[id]/attach-document.
|
||||
const docJournalEntryId = (doc.journal_entry_id as string | null) ?? null
|
||||
if (docJournalEntryId && docJournalEntryId !== tx.journal_entry_id) {
|
||||
return {
|
||||
error: 'Underlaget är redan kopplat till en annan verifikation.',
|
||||
status: 409,
|
||||
}
|
||||
}
|
||||
|
||||
// Race-free read of journal_entry_id: use UPDATE ... RETURNING so the value
|
||||
// we propagate against reflects any concurrent categorize that committed
|
||||
// before our UPDATE acquired the row lock. Reading the post-update state
|
||||
@@ -1511,13 +1524,29 @@ async function commitAttachDocumentToTransaction(
|
||||
}
|
||||
|
||||
const journalEntryId = postUpdate.journal_entry_id as string | null
|
||||
if (journalEntryId) {
|
||||
// Skip when the doc already points at this verifikation: the period-lock
|
||||
// trigger raises on ANY journal_entry_id write (even a same-value rewrite),
|
||||
// so an unconditional re-run would 500 an otherwise idempotent re-attach
|
||||
// once the period locks.
|
||||
if (journalEntryId && docJournalEntryId !== journalEntryId) {
|
||||
const { error: linkErr } = await supabase
|
||||
.from('document_attachments')
|
||||
.update({ journal_entry_id: journalEntryId })
|
||||
.eq('id', documentId)
|
||||
.eq('company_id', companyId)
|
||||
if (linkErr) {
|
||||
// The enforce_period_lock trigger blocks journal_entry_id writes when
|
||||
// the target entry sits in a closed/locked period. Map to 409 — the
|
||||
// dispatcher auto-rejects it, and a retry could never succeed until the
|
||||
// period is unlocked, so "försök igen" would be a false promise.
|
||||
const linkMsg = (linkErr as { message?: string }).message ?? ''
|
||||
if (/locked\/closed fiscal period|Bokföringen är låst/i.test(linkMsg)) {
|
||||
return {
|
||||
error:
|
||||
'Bilagan kopplades till transaktionen men verifikationens period är låst — den kunde inte länkas till verifikationen.',
|
||||
status: 409,
|
||||
}
|
||||
}
|
||||
// Surface the propagation failure rather than logging-and-continuing.
|
||||
// BFL 5 kap 6 § requires the verifikation to reference its underlag, so
|
||||
// a "succeeded" attach that left document_attachments.journal_entry_id
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { computeJeUnderlagStatus } from '../underlag-status'
|
||||
|
||||
describe('computeJeUnderlagStatus', () => {
|
||||
it('marks entries with a current-version document as has', () => {
|
||||
const result = computeJeUnderlagStatus(
|
||||
[{ id: 'je-1', source_type: 'bank_transaction' }],
|
||||
new Set(['je-1']),
|
||||
new Set(),
|
||||
)
|
||||
expect(result['je-1']).toBe('has')
|
||||
})
|
||||
|
||||
it('marks doc-requiring entries without documents as missing', () => {
|
||||
const result = computeJeUnderlagStatus(
|
||||
[
|
||||
{ id: 'je-1', source_type: 'bank_transaction' },
|
||||
{ id: 'je-2', source_type: 'manual' },
|
||||
{ id: 'je-3', source_type: 'import' },
|
||||
],
|
||||
new Set(),
|
||||
new Set(),
|
||||
)
|
||||
expect(result).toEqual({ 'je-1': 'missing', 'je-2': 'missing', 'je-3': 'missing' })
|
||||
})
|
||||
|
||||
it('respects journal_entry_no_doc_required exemptions', () => {
|
||||
const result = computeJeUnderlagStatus(
|
||||
[{ id: 'je-1', source_type: 'manual' }],
|
||||
new Set(),
|
||||
new Set(['je-1']),
|
||||
)
|
||||
expect(result['je-1']).toBe('none')
|
||||
})
|
||||
|
||||
it('never flags system-generated source types (exempt by omission)', () => {
|
||||
const result = computeJeUnderlagStatus(
|
||||
[
|
||||
{ id: 'je-1', source_type: 'vat_settlement' },
|
||||
{ id: 'je-2', source_type: 'invoice_payment' },
|
||||
{ id: 'je-3', source_type: 'year_end' },
|
||||
],
|
||||
new Set(),
|
||||
new Set(),
|
||||
)
|
||||
expect(result).toEqual({ 'je-1': 'none', 'je-2': 'none', 'je-3': 'none' })
|
||||
})
|
||||
|
||||
it('treats null source_type as no statement', () => {
|
||||
const result = computeJeUnderlagStatus(
|
||||
[{ id: 'je-1', source_type: null }],
|
||||
new Set(),
|
||||
new Set(),
|
||||
)
|
||||
expect(result['je-1']).toBe('none')
|
||||
})
|
||||
|
||||
it('has wins over missing when both a doc and a needs-doc source type are present', () => {
|
||||
const result = computeJeUnderlagStatus(
|
||||
[{ id: 'je-1', source_type: 'manual' }],
|
||||
new Set(['je-1']),
|
||||
new Set(['je-1']),
|
||||
)
|
||||
expect(result['je-1']).toBe('has')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
import { NEEDS_DOC_SOURCE_TYPES } from '@/lib/worklist/categories'
|
||||
|
||||
/**
|
||||
* Row-level underlag status for a booked transaction's journal entry.
|
||||
*
|
||||
* - 'has' — the verifikation has at least one current-version document
|
||||
* - 'missing' — the verifikation's source type requires underlag (BFL 5 kap
|
||||
* 7§), has none, and is not exempted via journal_entry_no_doc_required
|
||||
* - 'none' — no statement either way (system-generated source types,
|
||||
* exempted entries) — render no badge
|
||||
*
|
||||
* Mirrors countVerifikatMissingDocument in lib/worklist/categories.ts at row
|
||||
* granularity so the per-row "Underlag saknas" badge and the worklist count
|
||||
* never disagree on what counts as missing. Contract: callers must pass only
|
||||
* POSTED entries (filter journal_entries on status = 'posted', like the
|
||||
* worklist does) — reversed/corrected entries must render no badge at all,
|
||||
* never 'missing'.
|
||||
*/
|
||||
export type JeUnderlagStatus = 'has' | 'missing' | 'none'
|
||||
|
||||
const NEEDS_DOC = new Set<string>(NEEDS_DOC_SOURCE_TYPES)
|
||||
|
||||
export function computeJeUnderlagStatus(
|
||||
entries: Array<{ id: string; source_type: string | null }>,
|
||||
jeIdsWithDocs: ReadonlySet<string>,
|
||||
exemptJeIds: ReadonlySet<string>,
|
||||
): Record<string, JeUnderlagStatus> {
|
||||
const result: Record<string, JeUnderlagStatus> = {}
|
||||
for (const entry of entries) {
|
||||
if (jeIdsWithDocs.has(entry.id)) {
|
||||
result[entry.id] = 'has'
|
||||
} else if (
|
||||
entry.source_type != null &&
|
||||
NEEDS_DOC.has(entry.source_type) &&
|
||||
!exemptJeIds.has(entry.id)
|
||||
) {
|
||||
result[entry.id] = 'missing'
|
||||
} else {
|
||||
result[entry.id] = 'none'
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
Reference in New Issue
Block a user