Files
accounted/tests/pg/articles.pg.test.ts
T
Jakob Wennberg c0b006fcc1 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>
2026-06-09 21:05:37 +02:00

151 lines
5.4 KiB
TypeScript

import { randomUUID } from 'node:crypto'
import { describe, it, expect } from 'vitest'
import { getPool, withUserContext } from './setup'
import { seedCompany, insertAuthUser } from './fixtures'
// pg-real coverage for the artikelregister migration: the generate_article_number
// RPC (atomic + idempotent), the per-company unique article_number index, RLS
// isolation, and the updated_at + audit triggers.
async function seedSettings(companyId: string, userId: string): Promise<void> {
// seedCompany() inserts companies/members/period but not company_settings
// (the real flow creates it via create_company_with_owner). The RPC reads the
// per-company next_article_number counter, so seed a row (defaults to 1).
await getPool().query(
`INSERT INTO public.company_settings (user_id, company_id) VALUES ($1, $2)`,
[userId, companyId],
)
}
async function insertArticle(
companyId: string,
userId: string,
overrides: { name?: string; articleNumber?: string | null; revenueAccount?: string | null } = {},
): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.articles (id, company_id, user_id, name, article_number, revenue_account)
VALUES ($1, $2, $3, $4, $5, $6)`,
[
id,
companyId,
userId,
overrides.name ?? 'Konsulttimme',
overrides.articleNumber ?? null,
overrides.revenueAccount ?? null,
],
)
return id
}
describe('generate_article_number RPC', () => {
it('assigns sequential numbers, is idempotent, and advances the counter exactly once', async () => {
const { userId, companyId } = await seedCompany()
await seedSettings(companyId, userId)
const a1 = await insertArticle(companyId, userId, { name: 'A' })
const a2 = await insertArticle(companyId, userId, { name: 'B' })
const first = await getPool().query<{ n: string }>(
`SELECT public.generate_article_number($1, $2) AS n`,
[companyId, a1],
)
expect(first.rows[0].n).toBe('1')
// Idempotent: second call on the same article returns the same number and
// does NOT consume another sequence value.
const firstAgain = await getPool().query<{ n: string }>(
`SELECT public.generate_article_number($1, $2) AS n`,
[companyId, a1],
)
expect(firstAgain.rows[0].n).toBe('1')
const second = await getPool().query<{ n: string }>(
`SELECT public.generate_article_number($1, $2) AS n`,
[companyId, a2],
)
expect(second.rows[0].n).toBe('2')
const settings = await getPool().query<{ next_article_number: number }>(
`SELECT next_article_number FROM public.company_settings WHERE company_id = $1`,
[companyId],
)
// Started at 1, consumed by a1 and a2 → next free is 3.
expect(settings.rows[0].next_article_number).toBe(3)
})
it('raises when the article does not belong to the company', async () => {
const { userId, companyId } = await seedCompany()
await seedSettings(companyId, userId)
const other = await seedCompany()
const article = await insertArticle(companyId, userId)
await expect(
getPool().query(`SELECT public.generate_article_number($1, $2)`, [other.companyId, article]),
).rejects.toThrow()
})
})
describe('articles constraints + RLS', () => {
it('enforces a per-company unique article_number', async () => {
const { userId, companyId } = await seedCompany()
await insertArticle(companyId, userId, { name: 'A', articleNumber: '5' })
await expect(
insertArticle(companyId, userId, { name: 'B', articleNumber: '5' }),
).rejects.toThrow(/duplicate|unique/i)
})
it('isolates articles by company via RLS', async () => {
const { userId, companyId } = await seedCompany()
const articleId = await insertArticle(companyId, userId, { name: 'Secret' })
const stranger = await insertAuthUser()
const ownerView = await withUserContext(userId, (client) =>
client.query<{ id: string }>(`SELECT id FROM public.articles WHERE id = $1`, [articleId]),
)
expect(ownerView.rows).toHaveLength(1)
const strangerView = await withUserContext(stranger, (client) =>
client.query<{ id: string }>(`SELECT id FROM public.articles WHERE id = $1`, [articleId]),
)
expect(strangerView.rows).toHaveLength(0)
})
})
describe('articles triggers', () => {
it('bumps updated_at on update', async () => {
const { userId, companyId } = await seedCompany()
const articleId = await insertArticle(companyId, userId)
const before = await getPool().query<{ updated_at: string }>(
`SELECT updated_at FROM public.articles WHERE id = $1`,
[articleId],
)
await getPool().query(
`UPDATE public.articles SET name = 'Renamed', updated_at = now() - interval '0 seconds' WHERE id = $1`,
[articleId],
)
const after = await getPool().query<{ updated_at: string }>(
`SELECT updated_at FROM public.articles WHERE id = $1`,
[articleId],
)
expect(new Date(after.rows[0].updated_at).getTime()).toBeGreaterThanOrEqual(
new Date(before.rows[0].updated_at).getTime(),
)
})
it('writes an audit row on insert', async () => {
const { userId, companyId } = await seedCompany()
const articleId = await insertArticle(companyId, userId)
const audit = await getPool().query<{ count: string }>(
`SELECT count(*)::text AS count FROM public.audit_log
WHERE table_name = 'articles' AND record_id = $1`,
[articleId],
)
expect(Number(audit.rows[0].count)).toBeGreaterThanOrEqual(1)
})
})