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:
co-authored by
Claude Opus 4.8
parent
07ecb98389
commit
c0b006fcc1
@@ -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 },
|
||||
)
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -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 },
|
||||
)
|
||||
Reference in New Issue
Block a user