Files
accounted/app/api/pending-operations/expire/cron/route.ts
T
Jakob WennbergandClaude Fable 5 0521c385d2 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>
2026-06-11 11:13:51 +02:00

63 lines
2.6 KiB
TypeScript

import { createServiceClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { withCronContext } from '@/lib/api/with-cron-context'
import { errorResponse } from '@/lib/errors/get-structured-error'
/**
* GET /api/pending-operations/expire/cron — daily 02:30 UTC.
*
* Auto-rejects staged operations that have sat at status='pending' for more
* than 30 days. AI agents stage operations for human review; when the chat
* session is abandoned the proposal would otherwise linger in the worklist
* forever, asking the user to Godkänn/Avvisa something whose context they no
* longer remember. A 30-day-old proposal has lost its context regardless of
* risk level, so the sweep applies uniformly.
*
* Rows are flipped to 'rejected' (never deleted — the table is the audit
* trail) with the same result_data shape the commit dispatcher uses for its
* own auto-rejects (lib/pending-operations/commit.ts). The strict
* reason: 'expired' marker is what the /pending UI keys its
* "Utgick automatiskt" badge on. rejection_category/rejection_reason stay
* NULL — those carry user feedback semantics, and an expiry is not feedback.
*
* If you change EXPIRY_DAYS, update the user-facing copy that states the
* window: pending.auto_expiry_note + pending.auto_expired_detail in
* messages/{sv,en}.json and the static note in components/agent/ApprovalCard.tsx.
*/
const EXPIRY_DAYS = 30
export const GET = withCronContext('cron.pending_operations_expire', async (_request, ctx) => {
const supabase = createServiceClient()
const cutoff = new Date()
cutoff.setDate(cutoff.getDate() - EXPIRY_DAYS)
// CAS on status='pending': rows a concurrent commit has claimed (status
// 'committing') or already resolved are skipped; the status-immutability
// trigger never fires because OLD.status is always 'pending' here.
// result_data is NULL on pending rows, so plain assignment is the merge.
const { data, error } = await supabase
.from('pending_operations')
.update({
status: 'rejected',
resolved_at: new Date().toISOString(),
result_data: { auto_rejected: true, reason: 'expired' },
})
.eq('status', 'pending')
.lt('created_at', cutoff.toISOString())
.select('id, company_id')
if (error) {
ctx.log.error('pending operations expiry failed', error)
return errorResponse(error, ctx.log, { requestId: ctx.requestId })
}
const expired = data?.length ?? 0
ctx.log.info('pending operations expiry summary', {
expired,
cutoff: cutoff.toISOString(),
})
return NextResponse.json({ success: true, expired, cutoff: cutoff.toISOString() })
})