feat(invoicing): artikelregister (product/article catalog) with per-article revenue account (#703)

* feat(invoicing): artikelregister (product/article catalog) with per-article revenue account

Add a lean, non-inventory article catalog (artikelregister) so users can define
reusable invoice-line presets (name, unit, price excl VAT, VAT rate) with an
optional per-article BAS class-3 revenue-account override.

- DB: articles table (RLS via user_company_ids(), audit + updated_at triggers,
  unique-per-company article_number), generate_article_number RPC (atomic +
  idempotent), company_settings counter, nullable invoice_items.revenue_account
  + article_id, pending_operations CHECK expansion.
- Engine: generatePerRateLines groups revenue by (vat_rate, account) —
  byte-identical with no override, balance-safe when split (last account absorbs
  the rounding remainder), reverse_charge/export still force 3308/3305.
- API: /api/articles CRUD (soft-deactivate); override validated against
  chart_of_accounts (active class-3) and frozen onto invoice lines at create.
- Propagation: override carried through send/mark-sent/credit/convert/cash and
  the staged commit paths (recurring deferred — documented inline).
- MCP: gnubok_list/create/update_article (staged, scoped, risk-tiered).
- UI: articles register (list/detail/form) + nav + bilingual i18n + invoice-line
  article picker & "Spara som artikel" quick-create.
- Tests: engine regression, route, and pg-real (RPC/RLS/triggers).

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

* fix(mcp): strip ILIKE _ wildcard from gnubok_list_articles search

Underscore is a single-character ILIKE wildcard; stripping it (alongside the
existing %,()\* set) keeps a stray char in the article search from matching
every row. Read-only + RLS-scoped, so no security impact — addresses PR #703
reviewer + compliance-swarm CC6.3 notes.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-06-09 21:05:37 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent 07ecb98389
commit c0b006fcc1
32 changed files with 3047 additions and 16 deletions
+146
View File
@@ -0,0 +1,146 @@
import { NextResponse } from 'next/server'
import { eventBus } from '@/lib/events'
import { ensureInitialized } from '@/lib/init'
import { validateBody } from '@/lib/api/validate'
import { UpdateArticleSchema } from '@/lib/api/schemas'
import { withRouteContext } from '@/lib/api/with-route-context'
import { isValidRevenueAccount } from '@/lib/articles/validate-revenue-account'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { Article } from '@/types'
ensureInitialized()
export const GET = withRouteContext(
'article.get',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { supabase, companyId, log, requestId } = ctx
const opLog = log.child({ articleId: id })
const { data, error } = await supabase
.from('articles')
.select('*')
.eq('id', id)
.eq('company_id', companyId)
.single()
if (error) {
if (error.code === 'PGRST116') {
return errorResponseFromCode('ARTICLE_NOT_FOUND', opLog, { requestId })
}
opLog.error('article fetch failed', error)
return errorResponseFromCode('INTERNAL_ERROR', opLog, {
requestId,
details: { reason: error.message },
})
}
return NextResponse.json({ data })
},
)
export const PATCH = withRouteContext(
'article.update',
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { user, supabase, companyId, log, requestId } = ctx
const opLog = log.child({ articleId: id })
const result = await validateBody(request, UpdateArticleSchema, {
log: opLog,
operation: 'article.update',
})
if (!result.success) return result.response
const body = result.data
if (body.revenue_account) {
const ok = await isValidRevenueAccount(supabase, companyId!, body.revenue_account)
if (!ok) {
return errorResponseFromCode('ARTICLE_REVENUE_ACCOUNT_INVALID', opLog, { requestId })
}
}
// Sparse update — only the fields the caller actually sent.
const updateData: Record<string, unknown> = {}
for (const key of [
'name', 'name_en', 'type', 'unit', 'price_excl_vat', 'vat_rate',
'revenue_account', 'cost_price', 'ean', 'housework_type', 'notes',
'article_number', 'active',
] as const) {
if (body[key] !== undefined) updateData[key] = body[key]
}
const { data, error } = await supabase
.from('articles')
.update(updateData)
.eq('id', id)
.eq('company_id', companyId)
.select()
.single()
if (error) {
if (error.code === 'PGRST116') {
return errorResponseFromCode('ARTICLE_NOT_FOUND', opLog, { requestId })
}
if (error.code === '23505') {
return errorResponseFromCode('ARTICLE_DUPLICATE_NUMBER', opLog, {
requestId,
details: { articleNumber: body.article_number },
})
}
opLog.error('article update failed', error)
return errorResponseFromCode('ARTICLE_UPDATE_FAILED', opLog, {
requestId,
details: { reason: error.message },
})
}
await eventBus.emit({
type: 'article.updated',
payload: { article: data as Article, companyId: companyId!, userId: user.id },
})
return NextResponse.json({ data })
},
{ requireWrite: true },
)
// DELETE soft-deactivates (active = false) rather than hard-deleting. Articles
// are master data referenced by historical invoice lines via a (frozen) copy;
// keeping the row preserves the register's audit trail and the article number.
// Re-activate by PATCHing { active: true }.
export const DELETE = withRouteContext(
'article.delete',
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
const { id } = await params
const { user, supabase, companyId, log, requestId } = ctx
const opLog = log.child({ articleId: id })
const { data, error } = await supabase
.from('articles')
.update({ active: false })
.eq('id', id)
.eq('company_id', companyId)
.select()
.single()
if (error) {
if (error.code === 'PGRST116') {
return errorResponseFromCode('ARTICLE_NOT_FOUND', opLog, { requestId })
}
opLog.error('article deactivate failed', error)
return errorResponseFromCode('ARTICLE_UPDATE_FAILED', opLog, {
requestId,
details: { reason: error.message },
})
}
await eventBus.emit({
type: 'article.updated',
payload: { article: data as Article, companyId: companyId!, userId: user.id },
})
return NextResponse.json({ success: true })
},
{ requireWrite: true },
)
+73
View File
@@ -0,0 +1,73 @@
/**
* Tests for GET/PATCH/DELETE /api/articles/[id] (artikelregister).
*
* DELETE soft-deactivates (active = false) rather than hard-deleting, so the
* article and its number survive for history. PATCH is a sparse update.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createQueuedMockSupabase, createMockRequest, createMockRouteParams, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
import { GET, PATCH, DELETE } from '../[id]/route'
describe('GET/PATCH/DELETE /api/articles/[id]', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
requireWriteMock.mockResolvedValue({ ok: true })
})
it('GET returns 404 when the article is not found', async () => {
enqueue({ data: null, error: { code: 'PGRST116', message: 'not found' } })
const response = await GET(createMockRequest('/api/articles/a1'), createMockRouteParams({ id: 'a1' }))
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
expect(status).toBe(404)
expect(body.error.code).toBe('ARTICLE_NOT_FOUND')
})
it('PATCH updates a field and returns the row', async () => {
enqueue({ data: { id: 'a1', name: 'Konsulttimme', price_excl_vat: 1500 } })
const request = createMockRequest('/api/articles/a1', {
method: 'PATCH',
body: { price_excl_vat: 1500 },
})
const response = await PATCH(request, createMockRouteParams({ id: 'a1' }))
const { status, body } = await parseJsonResponse<{ data: { price_excl_vat: number } }>(response)
expect(status).toBe(200)
expect(body.data.price_excl_vat).toBe(1500)
})
it('DELETE soft-deactivates and returns success', async () => {
enqueue({ data: { id: 'a1', active: false } })
const response = await DELETE(createMockRequest('/api/articles/a1', { method: 'DELETE' }), createMockRouteParams({ id: 'a1' }))
const { status, body } = await parseJsonResponse<{ success: boolean }>(response)
expect(status).toBe(200)
expect(body.success).toBe(true)
})
})
+97
View File
@@ -0,0 +1,97 @@
/**
* Tests for GET/POST /api/articles (artikelregister).
*
* Exercises the route through the real withRouteContext wrapper, mocking only
* its auth/company/write dependencies and injecting a queued Supabase mock via
* requireAuth. Covers: list, validation (400), revenue-account guard (400),
* and the happy-path create with auto-numbering.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
import { GET, POST } from '../route'
describe('GET/POST /api/articles', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
requireWriteMock.mockResolvedValue({ ok: true })
})
it('GET lists the company articles', async () => {
enqueue({ data: [{ id: 'a1', name: 'Konsulttimme' }, { id: 'a2', name: 'Licens' }] })
const response = await GET(createMockRequest('/api/articles'), { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(response)
expect(status).toBe(200)
expect(body.data).toHaveLength(2)
})
it('POST rejects an invalid body (missing name) with 400', async () => {
const request = createMockRequest('/api/articles', {
method: 'POST',
body: { price_excl_vat: 100 },
})
const response = await POST(request, { params: Promise.resolve({}) })
const { status } = await parseJsonResponse(response)
expect(status).toBe(400)
})
it('POST rejects a revenue_account that is not an active class-3 account', async () => {
// chart_of_accounts lookup returns no row → override is invalid.
enqueue({ data: null })
const request = createMockRequest('/api/articles', {
method: 'POST',
body: { name: 'Frakt', price_excl_vat: 100, revenue_account: '3999' },
})
const response = await POST(request, { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
expect(status).toBe(400)
expect(body.error.code).toBe('ARTICLE_REVENUE_ACCOUNT_INVALID')
})
it('POST creates an article and auto-assigns a number', async () => {
// 1st DB hit: insert ... returning the row (article_number still null).
enqueue({ data: { id: 'a1', name: 'Konsulttimme', article_number: null, type: 'tjanst', vat_rate: 25 } })
// 2nd DB hit: generate_article_number RPC returns the assigned number.
enqueue({ data: '7' })
const request = createMockRequest('/api/articles', {
method: 'POST',
body: { name: 'Konsulttimme', price_excl_vat: 1200, vat_rate: 25 },
})
const response = await POST(request, { params: Promise.resolve({}) })
const { status, body } = await parseJsonResponse<{ data: { id: string; article_number: string } }>(response)
expect(status).toBe(200)
expect(body.data.id).toBe('a1')
expect(body.data.article_number).toBe('7')
})
})
+113
View File
@@ -0,0 +1,113 @@
import { NextResponse } from 'next/server'
import { eventBus } from '@/lib/events'
import { ensureInitialized } from '@/lib/init'
import { validateBody } from '@/lib/api/validate'
import { CreateArticleSchema } from '@/lib/api/schemas'
import { withRouteContext } from '@/lib/api/with-route-context'
import { ensureArticleNumber } from '@/lib/articles/ensure-article-number'
import { isValidRevenueAccount } from '@/lib/articles/validate-revenue-account'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { Article } from '@/types'
ensureInitialized()
// GET /api/articles — list the active company's articles. `?include_inactive=1`
// returns soft-deactivated ones too (the register page can show an archive view).
export const GET = withRouteContext(
'article.list',
async (request, ctx) => {
const { supabase, companyId, log, requestId } = ctx
const includeInactive = new URL(request.url).searchParams.get('include_inactive') === '1'
let query = supabase
.from('articles')
.select('*')
.eq('company_id', companyId)
if (!includeInactive) query = query.eq('active', true)
const { data, error } = await query.order('name', { ascending: true })
if (error) {
log.error('article list failed', error)
return errorResponse(error, log, { requestId })
}
return NextResponse.json({ data })
},
)
export const POST = withRouteContext(
'article.create',
async (request, ctx) => {
const { user, supabase, companyId, log, requestId } = ctx
const result = await validateBody(request, CreateArticleSchema, {
log,
operation: 'article.create',
})
if (!result.success) return result.response
const body = result.data
// Guard the optional revenue-account override against the chart of accounts.
if (body.revenue_account) {
const ok = await isValidRevenueAccount(supabase, companyId!, body.revenue_account)
if (!ok) {
return errorResponseFromCode('ARTICLE_REVENUE_ACCOUNT_INVALID', log, { requestId })
}
}
const { data, error } = await supabase
.from('articles')
.insert({
user_id: user.id,
company_id: companyId,
name: body.name,
name_en: body.name_en ?? null,
type: body.type ?? 'tjanst',
unit: body.unit ?? 'st',
price_excl_vat: body.price_excl_vat,
vat_rate: body.vat_rate ?? 25,
revenue_account: body.revenue_account ?? null,
cost_price: body.cost_price ?? null,
ean: body.ean ?? null,
housework_type: body.housework_type ?? null,
notes: body.notes ?? null,
article_number: body.article_number ?? null,
})
.select()
.single()
if (error) {
if (error.code === '23505') {
return errorResponseFromCode('ARTICLE_DUPLICATE_NUMBER', log, {
requestId,
details: { articleNumber: body.article_number },
})
}
log.error('article insert failed', error)
return errorResponseFromCode('ARTICLE_CREATE_FAILED', log, {
requestId,
details: { reason: error.message },
})
}
// Auto-number when the caller didn't supply one. Non-fatal: an unnumbered
// article is still usable and can be numbered later.
if (!data.article_number) {
try {
data.article_number = await ensureArticleNumber(supabase, companyId!, data.id)
} catch (err) {
log.warn('article number assignment failed', err as Error, { articleId: data.id })
}
}
await eventBus.emit({
type: 'article.created',
payload: { article: data as Article, companyId: companyId!, userId: user.id },
})
return NextResponse.json({ data })
},
{ requireWrite: true },
)
+47 -1
View File
@@ -145,6 +145,41 @@ export const POST = withRouteContext(
}
const total = documentType === 'delivery_note' ? 0 : subtotal + vatAmount
// Validate any per-line revenue-account override against the company's chart
// of accounts. Zod already constrains the shape to a 3xxx string; here we
// confirm each is a real, active class-3 account so a typo or a non-revenue
// account can never be booked. Never trust the client — same posture as the
// server-recomputed ROT/RUT amounts.
const overrideAccounts = Array.from(
new Set(
invoiceInput.items
.map((item) => item.revenue_account)
.filter((a): a is string => !!a),
),
)
if (overrideAccounts.length > 0) {
const { data: validAccounts, error: accountsError } = await supabase
.from('chart_of_accounts')
.select('account_number')
.eq('company_id', companyId!)
.eq('account_class', 3)
.eq('is_active', true)
.in('account_number', overrideAccounts)
if (accountsError) {
log.error('revenue account validation query failed', accountsError)
return errorResponse(accountsError, log, { requestId })
}
const validSet = new Set((validAccounts ?? []).map((a) => a.account_number))
const invalid = overrideAccounts.filter((a) => !validSet.has(a))
if (invalid.length > 0) {
return errorResponseFromCode('INVOICE_CREATE_REVENUE_ACCOUNT_INVALID', log, {
requestId,
details: { invalidAccounts: invalid },
})
}
}
// ROT/RUT-avdrag: validate prerequisites and compute the per-item +
// invoice-level deduction. Computed server-side (never trusted from
// the client) so a tampered request can't expand the 1513 receivable.
@@ -294,6 +329,11 @@ export const POST = withRouteContext(
line_total: lineTotal,
vat_rate: itemRate,
vat_amount: itemVat,
// Article linkage. revenue_account is frozen-copied here so a later
// article edit never re-books this line; null falls through to the
// VAT-treatment-derived account in generatePerRateLines().
article_id: item.article_id ?? null,
revenue_account: item.revenue_account ?? null,
deduction_type: deductionType,
deduction_amount: deductionAmount,
labor_hours: documentType === 'invoice' ? (item.labor_hours ?? null) : null,
@@ -469,7 +509,7 @@ async function createCreditNote(
})
}
const creditNoteItems = (originalInvoice.items || []).map((item: { sort_order: number; description: string; quantity: number; unit: string; unit_price: number; line_total: number; vat_rate?: number; vat_amount?: number }) => ({
const creditNoteItems = (originalInvoice.items || []).map((item: { sort_order: number; description: string; quantity: number; unit: string; unit_price: number; line_total: number; vat_rate?: number; vat_amount?: number; revenue_account?: string | null; article_id?: string | null }) => ({
invoice_id: creditNote.id,
sort_order: item.sort_order,
description: item.description,
@@ -479,6 +519,12 @@ async function createCreditNote(
line_total: -Math.abs(item.line_total),
vat_rate: item.vat_rate ?? 0,
vat_amount: -(item.vat_amount ? Math.abs(item.vat_amount) : 0),
// Carry the original's per-line revenue-account override so the reversal
// hits the SAME account it originally credited (e.g. 3041, not the
// VAT-derived 3001) — otherwise the override account keeps a dangling
// balance. article_id is preserved for the usage history.
revenue_account: item.revenue_account ?? null,
article_id: item.article_id ?? null,
}))
const { error: itemsError } = await supabase.from('invoice_items').insert(creditNoteItems)
@@ -126,7 +126,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
const { data: invoice, error: fetchErr } = await ctx.supabase
.from('invoices')
.select(
`${INVOICE_MARK_SENT_RESPONSE_COLUMNS}, customer:customers(id, name, customer_type, country), items:invoice_items(id, sort_order, description, quantity, unit, unit_price, line_total, vat_rate, vat_amount)`,
`${INVOICE_MARK_SENT_RESPONSE_COLUMNS}, customer:customers(id, name, customer_type, country), items:invoice_items(id, sort_order, description, quantity, unit, unit_price, line_total, vat_rate, vat_amount, revenue_account)`,
)
.eq('company_id', ctx.companyId!)
.eq('id', invoiceId)
@@ -154,7 +154,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
const { data: invoice, error: fetchErr } = await ctx.supabase
.from('invoices')
.select(
`${INVOICE_SEND_RESPONSE_COLUMNS}, customer:customers(id, name, email, customer_type, country, address_line1, address_line2, postal_code, city, vat_number), items:invoice_items(id, sort_order, description, quantity, unit, unit_price, line_total, vat_rate, vat_amount)`,
`${INVOICE_SEND_RESPONSE_COLUMNS}, customer:customers(id, name, email, customer_type, country, address_line1, address_line2, postal_code, city, vat_number), items:invoice_items(id, sort_order, description, quantity, unit, unit_price, line_total, vat_rate, vat_amount, revenue_account)`,
)
.eq('company_id', ctx.companyId!)
.eq('id', invoiceId)