Files
accounted/.claude/skills/erp-api-route/SKILL.md
T
Jakob Wennberg ec27228a8e style: remove em/en dashes repo-wide, add CLAUDE.md rule against them (#890)
Em dashes (—) and en dashes (–) had spread across comments, docs, tests,
and a few UI strings, reading as AI-generated boilerplate rather than
house style. Replaced each with punctuation matching its context: colon
for explanatory clauses, comma for asides, plain hyphen for numeric/legal
ranges (e.g. "21-23§"), "to"/"till" for date ranges, parentheses for
paired-dash asides. messages/en.json and messages/sv.json were fixed by
hand together to keep sv/en in sync.

Left untouched where the dash is the functional subject rather than
decorative punctuation: date-range-parser.ts's separator regex,
charset-repair.ts's CP1252 byte-mapping table (and its test), the SIE
encoding mojibake docs, generic-csv.ts's minus-sign normalizer, the
agent system-prompt files that already instruct against em dashes, and
a golden iXBRL test fixture compared byte-for-byte.

Also fixes two bugs surfaced along the way: an off-by-one in
ApiKeysPanel's scope-label split (a leftover from an earlier partial
pass), and a charset-repair test that had lost the literal en-dash it
exists to verify.

Regenerated the agent atom seed migration (skills:generate) since 27
SKILL.md files changed. Added a CLAUDE.md rule against em/en dashes,
with an explicit carve-out for the functional-dash cases above.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-04 15:58:06 +02:00

3.8 KiB

name, description
name description
erp-api-route Generate Next.js 16 API routes for Accounted with correct auth guards, Supabase client usage, event emission, journal entry creation, and error handling. Use when creating new API endpoints in app/api/. Handles the Next.js 16 async params pattern, ensureInitialized() for events, non-blocking journal entry wrapping, and defense-in-depth user_id filtering.

ERP API Route Generator

Standard Route Template

import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'

export async function GET(request: Request) {
  const supabase = await createClient()
  const { data: { user } } = await supabase.auth.getUser()

  if (!user) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const { data, error } = await supabase
    .from('table')
    .select('*')
    .eq('user_id', user.id)  // Defense in depth alongside RLS
    .order('created_at', { ascending: false })

  if (error) {
    return NextResponse.json({ error: error.message }, { status: 500 })
  }

  return NextResponse.json({ data })
}

Route That Emits Events

Add at module level (outside the handler):

import { eventBus } from '@/lib/events/bus'
import { ensureInitialized } from '@/lib/init'

ensureInitialized()  // MUST be module-level: loads extensions

Then emit after successful operations:

await eventBus.emit('invoice.created', { invoice: result, userId: user.id })

Dynamic Route Params (Next.js 16)

Params are a Promise; must await:

export async function POST(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params  // MUST await
  // ...
}

Supplementary Journal Entry Creation (Non-Blocking)

When the journal entry is a side effect of the primary operation (e.g., categorizing a transaction), failures must not block:

try {
  const entry = await createXxxJournalEntry(user.id, ...)
  if (entry) {
    await supabase.from('table')
      .update({ journal_entry_id: entry.id })
      .eq('id', id)
  }
} catch (err) {
  console.error('Failed to create journal entry:', err)
  // Continue: don't fail the request
}

Payment Journal Entry Creation (Blocking)

When the journal entry IS the accounting record (mark-paid, mark-sent for cash method), GL failure must block the operation. Without the GL entry, AP/AR diverges from GL:

try {
  const journalEntry = await createPaymentJournalEntry(...)
  if (journalEntry) journalEntryId = journalEntry.id
} catch (err) {
  console.error('Failed to create payment journal entry:', err)
  return NextResponse.json(
    { error: 'Kunde inte bokföra betalningen' },
    { status: 500 }
  )
}

Response Conventions

  • Success: NextResponse.json({ data: result })
  • Success with count: NextResponse.json({ data, count })
  • Error: NextResponse.json({ error: 'message' }, { status: N })

DB Query Pattern

Every query re-filters by user_id as defense in depth:

const { data, error } = await supabase
  .from('table')
  .select('*')
  .eq('user_id', user.id)  // Always include
  .eq('id', id)

if (error) {
  return NextResponse.json({ error: error.message }, { status: 500 })
}
if (!data) {
  return NextResponse.json({ error: 'Not found' }, { status: 404 })
}

Common Mistakes

  1. Forgetting ensureInitialized() on routes that emit events: events silently won't fire
  2. Using params.id instead of (await params).id: Next.js 16 breaking change
  3. Missing user_id filter on queries: relies solely on RLS
  4. Blocking on supplementary journal entry failure: must wrap in try/catch (but payment entries MUST block, see above)
  5. Returning { message } instead of { error } on failure: inconsistent with codebase
  6. Forgetting await on createClient(): it's async in server context