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:
@@ -0,0 +1,329 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, use } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import ArticleForm from '@/components/articles/ArticleForm'
|
||||
import { DestructiveConfirmDialog, useDestructiveConfirm } from '@/components/ui/destructive-confirm-dialog'
|
||||
import {
|
||||
ArrowLeft,
|
||||
Package,
|
||||
Wrench,
|
||||
Edit2,
|
||||
Archive,
|
||||
Loader2,
|
||||
Lock,
|
||||
} from 'lucide-react'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import type { Article, ArticleType, CreateArticleInput } from '@/types'
|
||||
|
||||
const ARTICLE_TYPE_KEY: Record<ArticleType, string> = {
|
||||
vara: 'type_vara',
|
||||
tjanst: 'type_tjanst',
|
||||
}
|
||||
|
||||
const articleTypeIcons: Record<ArticleType, React.ElementType> = {
|
||||
vara: Package,
|
||||
tjanst: Wrench,
|
||||
}
|
||||
|
||||
export default function ArticleDetailPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>
|
||||
}) {
|
||||
const { id } = use(params)
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
const { canWrite } = useCanWrite()
|
||||
const t = useTranslations('article_detail')
|
||||
const [article, setArticle] = useState<Article | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isEditOpen, setIsEditOpen] = useState(false)
|
||||
const [isUpdating, setIsUpdating] = useState(false)
|
||||
const { dialogProps: confirmDialogProps, confirm: confirmAction } = useDestructiveConfirm()
|
||||
|
||||
useEffect(() => {
|
||||
fetchArticle()
|
||||
}, [id])
|
||||
|
||||
async function fetchArticle() {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const response = await fetch(`/api/articles/${id}`)
|
||||
if (!response.ok) {
|
||||
throw new Error('Not found')
|
||||
}
|
||||
const { data } = await response.json()
|
||||
setArticle(data)
|
||||
} catch {
|
||||
toast({
|
||||
title: t('load_failed_title'),
|
||||
description: t('load_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
router.push('/articles')
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleUpdate(data: CreateArticleInput) {
|
||||
setIsUpdating(true)
|
||||
try {
|
||||
const response = await fetch(`/api/articles/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Update failed')
|
||||
}
|
||||
|
||||
toast({
|
||||
title: t('updated_title'),
|
||||
description: data.name,
|
||||
})
|
||||
setIsEditOpen(false)
|
||||
fetchArticle()
|
||||
} catch {
|
||||
toast({
|
||||
title: t('update_failed_title'),
|
||||
description: t('retry'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsUpdating(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDeactivate() {
|
||||
if (!article) return
|
||||
const ok = await confirmAction({
|
||||
title: t('deactivate_confirm_title', { name: article.name }),
|
||||
description: t('deactivate_confirm_description'),
|
||||
confirmLabel: t('deactivate_confirm_label'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
if (!ok) return
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/articles/${id}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Deactivate failed')
|
||||
}
|
||||
|
||||
toast({
|
||||
title: t('deactivated_title'),
|
||||
description: article.name,
|
||||
})
|
||||
router.push('/articles')
|
||||
} catch {
|
||||
toast({
|
||||
title: t('deactivate_failed_title'),
|
||||
description: t('retry'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!article) return null
|
||||
|
||||
const Icon = articleTypeIcons[article.type]
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{/* Header */}
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<Link
|
||||
href="/articles"
|
||||
className="text-sm text-muted-foreground hover:text-foreground flex items-center gap-1 mb-2"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
{t('back')}
|
||||
</Link>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center">
|
||||
<Icon className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">{article.name}</h1>
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<Badge variant="secondary">{t(ARTICLE_TYPE_KEY[article.type])}</Badge>
|
||||
{article.article_number && (
|
||||
<span className="text-sm text-muted-foreground tabular-nums">
|
||||
{article.article_number}
|
||||
</span>
|
||||
)}
|
||||
<Badge variant={article.active ? 'success' : 'secondary'}>
|
||||
{article.active ? t('status_active') : t('status_inactive')}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setIsEditOpen(true)}
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
|
||||
>
|
||||
{canWrite ? <Edit2 className="h-4 w-4 mr-1" /> : <Lock className="h-4 w-4 mr-1" />}
|
||||
{t('edit')}
|
||||
</Button>
|
||||
{article.active && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleDeactivate}
|
||||
className="text-destructive hover:text-destructive"
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
|
||||
>
|
||||
{canWrite ? <Archive className="h-4 w-4 mr-1" /> : <Lock className="h-4 w-4 mr-1" />}
|
||||
{t('deactivate')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Info cards */}
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{/* Pricing */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">{t('section_pricing')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="text-sm flex items-center justify-between">
|
||||
<span className="text-muted-foreground">{t('label_price')}</span>
|
||||
<span className="tabular-nums">{formatCurrency(article.price_excl_vat)}</span>
|
||||
</div>
|
||||
<div className="text-sm flex items-center justify-between">
|
||||
<span className="text-muted-foreground">{t('label_vat')}</span>
|
||||
<span className="tabular-nums">{article.vat_rate} %</span>
|
||||
</div>
|
||||
<div className="text-sm flex items-center justify-between">
|
||||
<span className="text-muted-foreground">{t('label_unit')}</span>
|
||||
<span>{article.unit}</span>
|
||||
</div>
|
||||
{article.cost_price != null && (
|
||||
<div className="text-sm flex items-center justify-between">
|
||||
<span className="text-muted-foreground">{t('label_cost_price')}</span>
|
||||
<span className="tabular-nums">{formatCurrency(article.cost_price)}</span>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Accounting */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">{t('section_accounting')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="text-sm flex items-center justify-between">
|
||||
<span className="text-muted-foreground">{t('label_revenue_account')}</span>
|
||||
<span className="tabular-nums">
|
||||
{article.revenue_account || t('revenue_account_auto')}
|
||||
</span>
|
||||
</div>
|
||||
{article.type === 'tjanst' && article.housework_type && (
|
||||
<div className="text-sm flex items-center justify-between">
|
||||
<span className="text-muted-foreground">{t('label_housework')}</span>
|
||||
<Badge variant="secondary">{article.housework_type}</Badge>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Details */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">{t('section_details')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{article.name_en && (
|
||||
<div className="text-sm flex items-center justify-between">
|
||||
<span className="text-muted-foreground">{t('label_name_en')}</span>
|
||||
<span className="truncate ml-2">{article.name_en}</span>
|
||||
</div>
|
||||
)}
|
||||
{article.ean && (
|
||||
<div className="text-sm flex items-center justify-between">
|
||||
<span className="text-muted-foreground">{t('label_ean')}</span>
|
||||
<span className="tabular-nums">{article.ean}</span>
|
||||
</div>
|
||||
)}
|
||||
{!article.name_en && !article.ean && (
|
||||
<p className="text-sm text-muted-foreground">{t('no_details')}</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Notes */}
|
||||
{article.notes && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">{t('section_notes')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground whitespace-pre-wrap">{article.notes}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<DestructiveConfirmDialog {...confirmDialogProps} />
|
||||
|
||||
{/* Edit dialog */}
|
||||
<Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('edit_dialog_title')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ArticleForm
|
||||
onSubmit={handleUpdate}
|
||||
isLoading={isUpdating}
|
||||
initialData={{
|
||||
name: article.name,
|
||||
name_en: article.name_en || undefined,
|
||||
type: article.type,
|
||||
unit: article.unit,
|
||||
price_excl_vat: article.price_excl_vat,
|
||||
vat_rate: article.vat_rate,
|
||||
revenue_account: article.revenue_account || undefined,
|
||||
cost_price: article.cost_price ?? undefined,
|
||||
ean: article.ean || undefined,
|
||||
housework_type: article.housework_type || undefined,
|
||||
notes: article.notes || undefined,
|
||||
}}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useMemo, useCallback, Suspense } from 'react'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { useSearchParams, useRouter, usePathname } from 'next/navigation'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
import { Plus, Search, Package, Lock, ChevronUp, ChevronDown, ChevronsUpDown } from 'lucide-react'
|
||||
import ArticleForm from '@/components/articles/ArticleForm'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { PageHeader } from '@/components/ui/page-header'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import Link from 'next/link'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import type { Article, ArticleType, CreateArticleInput } from '@/types'
|
||||
|
||||
const ARTICLE_TYPE_LABEL_KEYS: Record<ArticleType, string> = {
|
||||
vara: 'type_vara',
|
||||
tjanst: 'type_tjanst',
|
||||
}
|
||||
|
||||
type SortColumn = 'name' | 'article_number' | 'type' | 'unit' | 'price_excl_vat' | 'vat_rate'
|
||||
type SortDir = 'asc' | 'desc'
|
||||
|
||||
const SORTABLE_COLUMNS: ReadonlyArray<SortColumn> = [
|
||||
'name',
|
||||
'article_number',
|
||||
'type',
|
||||
'unit',
|
||||
'price_excl_vat',
|
||||
'vat_rate',
|
||||
]
|
||||
|
||||
function compareStrings(a: string, b: string): number {
|
||||
return a.localeCompare(b, 'sv', { sensitivity: 'base' })
|
||||
}
|
||||
|
||||
function ArticlesPageInner() {
|
||||
const { company } = useCompany()
|
||||
const { canWrite } = useCanWrite()
|
||||
const [articles, setArticles] = useState<Article[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false)
|
||||
const [isCreating, setIsCreating] = useState(false)
|
||||
const { toast } = useToast()
|
||||
const supabase = createClient()
|
||||
const t = useTranslations('articles')
|
||||
const errorLocale = useLocale() as ErrorLocale
|
||||
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
const searchParams = useSearchParams()
|
||||
|
||||
const sortParam = searchParams.get('sort')
|
||||
const dirParam = searchParams.get('dir')
|
||||
const sortColumn: SortColumn = (SORTABLE_COLUMNS as ReadonlyArray<string>).includes(sortParam ?? '')
|
||||
? (sortParam as SortColumn)
|
||||
: 'name'
|
||||
const sortDir: SortDir = dirParam === 'desc' ? 'desc' : 'asc'
|
||||
|
||||
const updateSort = useCallback(
|
||||
(column: SortColumn) => {
|
||||
const params = new URLSearchParams(searchParams.toString())
|
||||
let nextDir: SortDir = 'asc'
|
||||
if (column === sortColumn) {
|
||||
nextDir = sortDir === 'asc' ? 'desc' : 'asc'
|
||||
}
|
||||
params.set('sort', column)
|
||||
params.set('dir', nextDir)
|
||||
router.replace(`${pathname}?${params.toString()}`, { scroll: false })
|
||||
},
|
||||
[searchParams, sortColumn, sortDir, router, pathname]
|
||||
)
|
||||
|
||||
async function fetchArticles() {
|
||||
if (!company) return
|
||||
setIsLoading(true)
|
||||
const { data, error } = await supabase
|
||||
.from('articles')
|
||||
.select('*')
|
||||
.eq('company_id', company.id)
|
||||
.eq('active', true)
|
||||
.order('name', { ascending: true })
|
||||
|
||||
if (error) {
|
||||
toast({
|
||||
title: t('load_failed_title'),
|
||||
description: t('load_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} else {
|
||||
setArticles(data || [])
|
||||
}
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetchArticles()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
async function handleCreateArticle(data: CreateArticleInput) {
|
||||
setIsCreating(true)
|
||||
|
||||
const response = await fetch('/api/articles', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
|
||||
const result = await response.json()
|
||||
|
||||
if (!response.ok) {
|
||||
toast({
|
||||
title: t('create_failed_title'),
|
||||
description: getErrorMessage(result, { context: 'article', locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} else {
|
||||
toast({
|
||||
title: t('created_title'),
|
||||
description: t('created_description', { name: data.name }),
|
||||
})
|
||||
setArticles([...articles, result.data])
|
||||
setIsDialogOpen(false)
|
||||
}
|
||||
|
||||
setIsCreating(false)
|
||||
}
|
||||
|
||||
const filteredArticles = useMemo(() => {
|
||||
const term = searchTerm.trim().toLowerCase()
|
||||
if (!term) return articles
|
||||
return articles.filter((a) => {
|
||||
return (
|
||||
a.name.toLowerCase().includes(term) ||
|
||||
a.name_en?.toLowerCase().includes(term) ||
|
||||
a.article_number?.toLowerCase().includes(term)
|
||||
)
|
||||
})
|
||||
}, [articles, searchTerm])
|
||||
|
||||
const sortedArticles = useMemo(() => {
|
||||
const arr = [...filteredArticles]
|
||||
arr.sort((a, b) => {
|
||||
let cmp = 0
|
||||
switch (sortColumn) {
|
||||
case 'price_excl_vat':
|
||||
cmp = a.price_excl_vat - b.price_excl_vat
|
||||
break
|
||||
case 'vat_rate':
|
||||
cmp = a.vat_rate - b.vat_rate
|
||||
break
|
||||
case 'name':
|
||||
cmp = compareStrings(a.name || '', b.name || '')
|
||||
break
|
||||
case 'article_number':
|
||||
cmp = compareStrings(a.article_number || '', b.article_number || '')
|
||||
break
|
||||
case 'type':
|
||||
cmp = compareStrings(a.type || '', b.type || '')
|
||||
break
|
||||
case 'unit':
|
||||
cmp = compareStrings(a.unit || '', b.unit || '')
|
||||
break
|
||||
}
|
||||
return sortDir === 'asc' ? cmp : -cmp
|
||||
})
|
||||
return arr
|
||||
}, [filteredArticles, sortColumn, sortDir])
|
||||
|
||||
function SortableHeader({
|
||||
column,
|
||||
label,
|
||||
className,
|
||||
}: {
|
||||
column: SortColumn
|
||||
label: string
|
||||
className?: string
|
||||
}) {
|
||||
const isActive = sortColumn === column
|
||||
const Icon = isActive ? (sortDir === 'asc' ? ChevronUp : ChevronDown) : ChevronsUpDown
|
||||
return (
|
||||
<TableHead className={className}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => updateSort(column)}
|
||||
className="inline-flex items-center gap-1 text-[11px] font-medium uppercase tracking-wider text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
{label}
|
||||
<Icon className="h-3 w-3 opacity-70" aria-hidden="true" />
|
||||
</button>
|
||||
</TableHead>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title={t('title')}
|
||||
action={
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
|
||||
>
|
||||
{canWrite ? (
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
) : (
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
{t('new_article')}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('add_article')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ArticleForm
|
||||
onSubmit={handleCreateArticle}
|
||||
isLoading={isCreating}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Search */}
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder={t('search_placeholder')}
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="pl-10"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Article list */}
|
||||
{isLoading ? (
|
||||
<>
|
||||
{/* Desktop skeleton */}
|
||||
<Card className="hidden md:block">
|
||||
<CardContent className="p-6 space-y-3">
|
||||
{[1, 2, 3, 4, 5].map((i) => (
|
||||
<Skeleton key={i} className="h-10 w-full" />
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
{/* Mobile skeleton */}
|
||||
<div className="grid gap-4 md:hidden">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<Card key={i}>
|
||||
<CardHeader>
|
||||
<Skeleton className="h-5 w-1/2" />
|
||||
<Skeleton className="h-4 w-1/3 mt-2" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Skeleton className="h-4 w-full" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
) : sortedArticles.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
{searchTerm ? (
|
||||
<EmptyState
|
||||
icon={Package}
|
||||
title={t('no_search_results_title')}
|
||||
description={t('no_search_results_description', { term: searchTerm })}
|
||||
/>
|
||||
) : (
|
||||
<EmptyState
|
||||
icon={Package}
|
||||
title={t('empty_title')}
|
||||
description={t('empty_description')}
|
||||
actionLabel={canWrite ? t('empty_action') : undefined}
|
||||
onAction={canWrite ? () => setIsDialogOpen(true) : undefined}
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<>
|
||||
{/* Desktop table */}
|
||||
<Card className="hidden md:block">
|
||||
<CardContent className="p-0">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<SortableHeader column="article_number" label={t('col_number')} />
|
||||
<SortableHeader column="name" label={t('col_name')} />
|
||||
<SortableHeader column="type" label={t('col_type')} />
|
||||
<SortableHeader column="unit" label={t('col_unit')} />
|
||||
<SortableHeader
|
||||
column="price_excl_vat"
|
||||
label={t('col_price')}
|
||||
className="text-right"
|
||||
/>
|
||||
<SortableHeader
|
||||
column="vat_rate"
|
||||
label={t('col_vat')}
|
||||
className="text-right"
|
||||
/>
|
||||
<TableHead className="text-right">{t('col_status')}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{sortedArticles.map((article) => (
|
||||
<TableRow
|
||||
key={article.id}
|
||||
className="cursor-pointer"
|
||||
onClick={() => router.push(`/articles/${article.id}`)}
|
||||
>
|
||||
<TableCell className="tabular-nums text-muted-foreground">
|
||||
{article.article_number || '—'}
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">
|
||||
<Link
|
||||
href={`/articles/${article.id}`}
|
||||
className="hover:text-primary transition-colors"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{article.name}
|
||||
</Link>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant="secondary">
|
||||
{t(ARTICLE_TYPE_LABEL_KEYS[article.type])}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground">{article.unit}</TableCell>
|
||||
<TableCell className="text-right tabular-nums">
|
||||
{formatCurrency(article.price_excl_vat)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums text-muted-foreground">
|
||||
{article.vat_rate} %
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<Badge variant={article.active ? 'success' : 'secondary'}>
|
||||
{article.active ? t('status_active') : t('status_inactive')}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Mobile card list */}
|
||||
<div className="grid gap-4 md:hidden">
|
||||
{sortedArticles.map((article) => (
|
||||
<Link key={article.id} href={`/articles/${article.id}`}>
|
||||
<Card className="cursor-pointer transition-colors duration-150 hover:bg-secondary/60 h-full group">
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<CardTitle className="text-base truncate group-hover:text-primary transition-colors">
|
||||
{article.name}
|
||||
</CardTitle>
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<Badge variant="secondary">
|
||||
{t(ARTICLE_TYPE_LABEL_KEYS[article.type])}
|
||||
</Badge>
|
||||
{article.article_number && (
|
||||
<span className="text-xs text-muted-foreground tabular-nums">
|
||||
{article.article_number}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<span className="font-display text-lg tabular-nums shrink-0">
|
||||
{formatCurrency(article.price_excl_vat)}
|
||||
</span>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground tabular-nums">
|
||||
<span>{t('per_unit', { unit: article.unit })}</span>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span>{t('vat_label_value', { rate: article.vat_rate })}</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function ArticlesPage() {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<ArticlesPageInner />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
@@ -39,11 +39,17 @@ import {
|
||||
RUT_MAX,
|
||||
computeDeduction,
|
||||
} from '@/lib/invoices/rot-rut-rules'
|
||||
import type { Customer, Currency, CreateInvoiceInput, CreateCustomerInput, InvoiceDocumentType } from '@/types'
|
||||
import type { Customer, Currency, CreateInvoiceInput, CreateCustomerInput, InvoiceDocumentType, Article } from '@/types'
|
||||
|
||||
const currencies: Currency[] = ['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK']
|
||||
const units = ['st', 'tim', 'dag', 'månad', 'km', 'kg']
|
||||
|
||||
// Subset of Article fields the line picker needs to pre-fill a row.
|
||||
type ArticleOption = Pick<
|
||||
Article,
|
||||
'id' | 'article_number' | 'name' | 'unit' | 'price_excl_vat' | 'vat_rate' | 'revenue_account'
|
||||
>
|
||||
|
||||
function RequiredMark() {
|
||||
return <span className="text-destructive ml-0.5" aria-hidden="true">*</span>
|
||||
}
|
||||
@@ -67,6 +73,9 @@ export default function NewInvoicePage() {
|
||||
unit: z.string().min(1, t('validation_unit_required')),
|
||||
unit_price: z.number().min(0, t('validation_price_positive')),
|
||||
vat_rate: z.number().min(0).max(25),
|
||||
// Article linkage (artikelregister). Optional — free-text lines omit them.
|
||||
article_id: z.string().nullable().optional(),
|
||||
revenue_account: z.string().nullable().optional(),
|
||||
// ROT/RUT-avdrag per line. Optional — null means "no deduction".
|
||||
deduction_type: z.enum(['rot', 'rut']).nullable().optional(),
|
||||
labor_hours: z.number().nonnegative().nullable().optional(),
|
||||
@@ -120,6 +129,9 @@ export default function NewInvoicePage() {
|
||||
const [vatRegistered, setVatRegistered] = useState<boolean>(true)
|
||||
const [numberPreview, setNumberPreview] = useState<string | null>(null)
|
||||
const [logoUrl, setLogoUrl] = useState<string | null>(null)
|
||||
// Artikelregister: active articles for the line picker + which line is mid quick-create.
|
||||
const [articles, setArticles] = useState<ArticleOption[]>([])
|
||||
const [savingArticleIndex, setSavingArticleIndex] = useState<number | null>(null)
|
||||
// True only when the user had zero invoices when this page loaded. The
|
||||
// post-create flow uses this to offer a one-shot "upload a logo?" prompt
|
||||
// — issue #520. Self-limits: once count > 0 it stays false.
|
||||
@@ -152,6 +164,8 @@ export default function NewInvoicePage() {
|
||||
unit: 'st',
|
||||
unit_price: 0,
|
||||
vat_rate: 25,
|
||||
article_id: null,
|
||||
revenue_account: null,
|
||||
deduction_type: null,
|
||||
labor_hours: null,
|
||||
work_type: null,
|
||||
@@ -194,8 +208,85 @@ export default function NewInvoicePage() {
|
||||
if (!company?.id) return
|
||||
fetchCustomers()
|
||||
fetchDefaultNotes()
|
||||
fetchArticles()
|
||||
}, [company?.id])
|
||||
|
||||
async function fetchArticles() {
|
||||
if (!company?.id) return
|
||||
const { data } = await supabase
|
||||
.from('articles')
|
||||
.select('id, article_number, name, unit, price_excl_vat, vat_rate, revenue_account')
|
||||
.eq('company_id', company.id)
|
||||
.eq('active', true)
|
||||
.order('name')
|
||||
setArticles((data ?? []) as ArticleOption[])
|
||||
}
|
||||
|
||||
// Apply a chosen article's defaults onto a line. Selecting "none" detaches the
|
||||
// article link (and its account override) but keeps the typed text/price so the
|
||||
// row becomes an editable free-text line.
|
||||
function applyArticle(index: number, articleId: string) {
|
||||
if (articleId === 'none') {
|
||||
setValue(`items.${index}.article_id`, null, { shouldDirty: true })
|
||||
setValue(`items.${index}.revenue_account`, null, { shouldDirty: true })
|
||||
return
|
||||
}
|
||||
const a = articles.find((x) => x.id === articleId)
|
||||
if (!a) return
|
||||
setValue(`items.${index}.article_id`, a.id, { shouldDirty: true })
|
||||
setValue(`items.${index}.description`, a.name, { shouldValidate: true, shouldDirty: true })
|
||||
if (a.unit) setValue(`items.${index}.unit`, a.unit, { shouldDirty: true })
|
||||
setValue(`items.${index}.unit_price`, Number(a.price_excl_vat) || 0, { shouldValidate: true, shouldDirty: true })
|
||||
// Only adopt the article's VAT rate when it's allowed for this customer
|
||||
// (and the rate isn't locked, e.g. reverse charge / export). Otherwise keep
|
||||
// the line's current rate so the API's per-customer VAT rule isn't violated.
|
||||
if (!isRateLocked && availableRates.some((r) => r.rate === a.vat_rate)) {
|
||||
setValue(`items.${index}.vat_rate`, a.vat_rate, { shouldValidate: true, shouldDirty: true })
|
||||
}
|
||||
// The account override rides along regardless of rate; the engine ignores it
|
||||
// for reverse-charge/export and validates it against the chart of accounts.
|
||||
setValue(`items.${index}.revenue_account`, a.revenue_account ?? null, { shouldDirty: true })
|
||||
}
|
||||
|
||||
// "Spara som artikel": persist the current free-text line into the register and
|
||||
// back-fill the article_id so the row is now catalog-linked.
|
||||
async function saveLineAsArticle(index: number) {
|
||||
const item = watchItems[index]
|
||||
if (!item?.description?.trim()) {
|
||||
toast({ title: t('save_article_need_description'), variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
setSavingArticleIndex(index)
|
||||
try {
|
||||
const response = await fetch('/api/articles', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: item.description.trim(),
|
||||
unit: item.unit || 'st',
|
||||
price_excl_vat: Number(item.unit_price) || 0,
|
||||
vat_rate: item.vat_rate ?? 25,
|
||||
}),
|
||||
})
|
||||
const result = await response.json()
|
||||
if (!response.ok) {
|
||||
throw new Error(getErrorMessage(result, { context: 'article', statusCode: response.status }))
|
||||
}
|
||||
const created = result.data as ArticleOption
|
||||
setArticles((prev) => [...prev, created].sort((a, b) => a.name.localeCompare(b.name, 'sv')))
|
||||
setValue(`items.${index}.article_id`, created.id, { shouldDirty: true })
|
||||
toast({ title: t('article_saved_title'), description: created.name })
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t('save_article_failed'),
|
||||
description: getErrorMessage(error, { context: 'article' }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setSavingArticleIndex(null)
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchDefaultNotes() {
|
||||
if (!company?.id) return
|
||||
const { data } = await supabase
|
||||
@@ -864,6 +955,55 @@ export default function NewInvoicePage() {
|
||||
key={field.id}
|
||||
className="rounded-lg border bg-card p-4 space-y-3 relative md:rounded-none md:border-0 md:bg-transparent md:p-0 md:space-y-0 md:grid md:grid-cols-12 md:gap-4 md:items-start"
|
||||
>
|
||||
{/* Article picker (artikelregister). Optional — leave on
|
||||
"Egen rad" to type a free-text line. Selecting an
|
||||
article pre-fills description, unit, price, VAT and any
|
||||
revenue-account override. */}
|
||||
<div className="md:col-span-12 flex flex-wrap items-end gap-2">
|
||||
<div className="flex-1 min-w-[180px] space-y-1 md:space-y-2">
|
||||
<Label className="text-xs text-muted-foreground md:text-sm md:text-foreground">{t('article_label')}</Label>
|
||||
<Controller
|
||||
name={`items.${index}.article_id`}
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
value={field.value ?? 'none'}
|
||||
onValueChange={(v) => applyArticle(index, v)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={t('article_placeholder')} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">{t('article_free_text')}</SelectItem>
|
||||
{articles.map((a) => (
|
||||
<SelectItem key={a.id} value={a.id}>
|
||||
{a.article_number ? `${a.article_number} — ${a.name}` : a.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
{canWrite && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-10 shrink-0"
|
||||
onClick={() => saveLineAsArticle(index)}
|
||||
disabled={savingArticleIndex === index}
|
||||
>
|
||||
{savingArticleIndex === index ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Plus className="h-4 w-4 md:mr-1" />
|
||||
)}
|
||||
<span className="hidden md:inline">{t('save_as_article')}</span>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Description + mobile delete button */}
|
||||
<div className="flex items-start gap-2 md:contents">
|
||||
<div className="flex-1 space-y-1 md:col-span-3 md:space-y-2">
|
||||
@@ -1106,6 +1246,8 @@ export default function NewInvoicePage() {
|
||||
unit: 'st',
|
||||
unit_price: 0,
|
||||
vat_rate: availableRates[0]?.rate ?? 25,
|
||||
article_id: null,
|
||||
revenue_account: null,
|
||||
deduction_type: null,
|
||||
labor_hours: null,
|
||||
work_type: null,
|
||||
|
||||
@@ -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 },
|
||||
)
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,337 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useForm, Controller } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { z } from 'zod'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { ChevronDown, Loader2, Lock } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import type { CreateArticleInput } from '@/types'
|
||||
|
||||
// Unit list mirrors the invoice line editor (app/(dashboard)/invoices/new/page.tsx).
|
||||
const UNITS = ['st', 'tim', 'dag', 'månad', 'km', 'kg'] as const
|
||||
|
||||
// Legal Swedish VAT rates as integer percent. Matches vatRatePercent in
|
||||
// lib/api/schemas.ts (25 | 12 | 6 | 0).
|
||||
const VAT_RATES = [25, 12, 6, 0] as const
|
||||
|
||||
interface ArticleFormProps {
|
||||
onSubmit: (data: CreateArticleInput) => Promise<void>
|
||||
isLoading: boolean
|
||||
initialData?: Partial<CreateArticleInput>
|
||||
}
|
||||
|
||||
export default function ArticleForm({
|
||||
onSubmit,
|
||||
isLoading,
|
||||
initialData,
|
||||
}: ArticleFormProps) {
|
||||
const { canWrite } = useCanWrite()
|
||||
const t = useTranslations('form_article')
|
||||
// Open the advanced section by default when it already holds data, so an
|
||||
// edit never hides a value the user previously set.
|
||||
const [advancedOpen, setAdvancedOpen] = useState(
|
||||
Boolean(
|
||||
initialData?.revenue_account ||
|
||||
initialData?.cost_price != null ||
|
||||
initialData?.ean ||
|
||||
initialData?.housework_type ||
|
||||
initialData?.notes,
|
||||
),
|
||||
)
|
||||
|
||||
// UI-local schema mirroring CreateArticleSchema (lib/api/schemas.ts).
|
||||
const schema = useMemo(
|
||||
() =>
|
||||
z.object({
|
||||
name: z.string().min(1, t('name_required')),
|
||||
name_en: z.string().optional(),
|
||||
type: z.enum(['vara', 'tjanst']),
|
||||
unit: z.string().min(1),
|
||||
price_excl_vat: z.number({ message: t('price_required') }).nonnegative(t('price_required')),
|
||||
vat_rate: z.union([z.literal(25), z.literal(12), z.literal(6), z.literal(0)]),
|
||||
revenue_account: z.string().optional(),
|
||||
cost_price: z.number().nonnegative().optional(),
|
||||
ean: z.string().optional(),
|
||||
housework_type: z.string().optional(),
|
||||
notes: z.string().optional(),
|
||||
}),
|
||||
[t],
|
||||
)
|
||||
|
||||
type FormData = z.infer<typeof schema>
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
watch,
|
||||
control,
|
||||
formState: { errors },
|
||||
} = useForm<FormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
name: initialData?.name || '',
|
||||
name_en: initialData?.name_en || '',
|
||||
type: initialData?.type || 'tjanst',
|
||||
unit: initialData?.unit || 'st',
|
||||
price_excl_vat: initialData?.price_excl_vat ?? 0,
|
||||
vat_rate: (initialData?.vat_rate as FormData['vat_rate']) ?? 25,
|
||||
revenue_account: initialData?.revenue_account || '',
|
||||
cost_price: initialData?.cost_price ?? undefined,
|
||||
ean: initialData?.ean || '',
|
||||
housework_type: initialData?.housework_type || '',
|
||||
notes: initialData?.notes || '',
|
||||
},
|
||||
})
|
||||
|
||||
const type = watch('type')
|
||||
|
||||
const onFormSubmit = (data: FormData) => {
|
||||
onSubmit({
|
||||
name: data.name,
|
||||
name_en: data.name_en || null,
|
||||
type: data.type,
|
||||
unit: data.unit,
|
||||
price_excl_vat: data.price_excl_vat,
|
||||
vat_rate: data.vat_rate,
|
||||
revenue_account: data.revenue_account || null,
|
||||
cost_price: data.cost_price ?? null,
|
||||
ean: data.ean || null,
|
||||
housework_type: type === 'tjanst' ? data.housework_type || null : null,
|
||||
notes: data.notes || null,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(onFormSubmit)} className="space-y-6">
|
||||
{/* Type */}
|
||||
<div className="space-y-2">
|
||||
<Label>{t('type_label')}</Label>
|
||||
<Controller
|
||||
name="type"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<Select value={field.value} onValueChange={(v) => { if (v) field.onChange(v) }}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={t('type_placeholder')} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="vara">{t('type_vara')}</SelectItem>
|
||||
<SelectItem value="tjanst">{t('type_tjanst')}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Name */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">{t('name_label')}</Label>
|
||||
<Input
|
||||
id="name"
|
||||
placeholder={t('name_placeholder')}
|
||||
{...register('name')}
|
||||
/>
|
||||
{errors.name && (
|
||||
<p className="text-sm text-destructive">{errors.name.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* English name */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name_en">{t('name_en_label')}</Label>
|
||||
<Input
|
||||
id="name_en"
|
||||
placeholder={t('name_en_placeholder')}
|
||||
{...register('name_en')}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">{t('name_en_hint')}</p>
|
||||
</div>
|
||||
|
||||
{/* Unit + price + VAT */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>{t('unit_label')}</Label>
|
||||
<Controller
|
||||
name="unit"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<Select value={field.value} onValueChange={(v) => { if (v) field.onChange(v) }}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{UNITS.map((u) => (
|
||||
<SelectItem key={u} value={u}>{u}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="price_excl_vat">{t('price_label')}</Label>
|
||||
<Input
|
||||
id="price_excl_vat"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
className="tabular-nums"
|
||||
{...register('price_excl_vat', { valueAsNumber: true })}
|
||||
/>
|
||||
{errors.price_excl_vat && (
|
||||
<p className="text-sm text-destructive">{errors.price_excl_vat.message}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>{t('vat_rate_label')}</Label>
|
||||
<Controller
|
||||
name="vat_rate"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
value={String(field.value)}
|
||||
onValueChange={(v) => { if (v) field.onChange(Number(v)) }}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{VAT_RATES.map((rate) => (
|
||||
<SelectItem key={rate} value={String(rate)}>{rate} %</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Advanced (collapsible) */}
|
||||
<div className="pt-4 border-t">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAdvancedOpen((o) => !o)}
|
||||
className="flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors"
|
||||
aria-expanded={advancedOpen}
|
||||
>
|
||||
<ChevronDown
|
||||
className={cn('h-4 w-4 transition-transform duration-200', advancedOpen && 'rotate-180')}
|
||||
/>
|
||||
{t('advanced_section')}
|
||||
</button>
|
||||
|
||||
{advancedOpen && (
|
||||
<div className="space-y-4 pt-4">
|
||||
{/* Revenue account */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="revenue_account">{t('revenue_account_label')}</Label>
|
||||
<Input
|
||||
id="revenue_account"
|
||||
inputMode="numeric"
|
||||
placeholder={t('revenue_account_placeholder')}
|
||||
className="tabular-nums"
|
||||
{...register('revenue_account')}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">{t('revenue_account_hint')}</p>
|
||||
</div>
|
||||
|
||||
{/* Cost price */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cost_price">{t('cost_price_label')}</Label>
|
||||
<Input
|
||||
id="cost_price"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
className="tabular-nums"
|
||||
{...register('cost_price', {
|
||||
setValueAs: (v) => (v === '' || v == null ? undefined : Number(v)),
|
||||
})}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">{t('cost_price_hint')}</p>
|
||||
</div>
|
||||
|
||||
{/* EAN */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="ean">{t('ean_label')}</Label>
|
||||
<Input
|
||||
id="ean"
|
||||
placeholder={t('ean_placeholder')}
|
||||
className="tabular-nums"
|
||||
{...register('ean')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Housework type (tjänst only) */}
|
||||
{type === 'tjanst' && (
|
||||
<div className="space-y-2">
|
||||
<Label>{t('housework_label')}</Label>
|
||||
<Controller
|
||||
name="housework_type"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
value={field.value || 'none'}
|
||||
onValueChange={(v) => field.onChange(v === 'none' ? '' : v)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder={t('housework_placeholder')} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">{t('housework_none')}</SelectItem>
|
||||
<SelectItem value="ROT">{t('housework_rot')}</SelectItem>
|
||||
<SelectItem value="RUT">{t('housework_rut')}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">{t('housework_hint')}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Notes */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="notes">{t('notes_label')}</Label>
|
||||
<Textarea
|
||||
id="notes"
|
||||
placeholder={t('notes_placeholder')}
|
||||
{...register('notes')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Submit */}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={isLoading || !canWrite}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t('submit_saving')}
|
||||
</>
|
||||
) : !canWrite ? (
|
||||
<>
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
{t('submit_save')}
|
||||
</>
|
||||
) : (
|
||||
t('submit_save')
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
ClipboardCheck,
|
||||
HandCoins,
|
||||
Package,
|
||||
Tag,
|
||||
ChevronsUpDown,
|
||||
Sparkles,
|
||||
} from 'lucide-react'
|
||||
@@ -81,6 +82,7 @@ type NavLabelKey =
|
||||
| 'invoice_inbox'
|
||||
| 'invoices'
|
||||
| 'customers'
|
||||
| 'articles'
|
||||
| 'supplier_invoices'
|
||||
| 'suppliers'
|
||||
| 'review'
|
||||
@@ -128,6 +130,7 @@ const navItems: NavItem[] = [
|
||||
// Försäljning dropdown
|
||||
{ href: '/invoices', labelKey: 'invoices', icon: Receipt, group: 'försäljning' },
|
||||
{ href: '/customers', labelKey: 'customers', icon: Users, group: 'försäljning' },
|
||||
{ href: '/articles', labelKey: 'articles', icon: Tag, group: 'försäljning' },
|
||||
// Inköp dropdown
|
||||
{ href: '/supplier-invoices', labelKey: 'supplier_invoices', icon: Wallet, group: 'inköp' },
|
||||
{ href: '/suppliers', labelKey: 'suppliers', icon: Building2, group: 'inköp' },
|
||||
|
||||
@@ -2789,6 +2789,187 @@ export const tools: McpTool[] = [
|
||||
},
|
||||
},
|
||||
|
||||
// ── Article tools (artikelregister) ──────────────────────────
|
||||
|
||||
{
|
||||
name: 'gnubok_list_articles',
|
||||
title: 'List Articles',
|
||||
description: "List the active company's catalog articles (artikelregister). Use to look up an article to add to an invoice line. Active articles only by default.",
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
query: { type: 'string', description: 'Optional case-insensitive filter on name or article_number.' },
|
||||
include_inactive: { type: 'boolean', description: 'Include deactivated articles (default false).' },
|
||||
},
|
||||
},
|
||||
outputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
articles: { type: 'array', items: { type: 'object' } },
|
||||
count: { type: 'number' },
|
||||
},
|
||||
required: ['articles', 'count'],
|
||||
},
|
||||
annotations: {
|
||||
readOnlyHint: true,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: false,
|
||||
},
|
||||
async execute(args, companyId, userId, supabase) {
|
||||
let q = supabase
|
||||
.from('articles')
|
||||
.select('id, article_number, name, name_en, type, unit, price_excl_vat, vat_rate, revenue_account, housework_type, active')
|
||||
.eq('company_id', companyId)
|
||||
if (!args.include_inactive) q = q.eq('active', true)
|
||||
|
||||
// Strip PostgREST filter metacharacters before interpolating into .or() —
|
||||
// commas/parens would otherwise let a query inject extra or-conditions, and
|
||||
// the ILIKE wildcards % and _ would turn a stray char into a match-all.
|
||||
const raw = typeof args.query === 'string' ? args.query : ''
|
||||
const safe = raw.replace(/[%_,()\\*]/g, ' ').trim()
|
||||
if (safe) {
|
||||
q = q.or(`name.ilike.%${safe}%,article_number.ilike.%${safe}%`)
|
||||
}
|
||||
|
||||
const { data, error } = await q.order('name')
|
||||
if (error) throw new Error(`Database error: ${error.message}`)
|
||||
return { articles: data, count: data?.length ?? 0 }
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: 'gnubok_create_article',
|
||||
title: 'Create Article',
|
||||
description: 'Stage a new catalog article (artikelregister). Stages for approval — not created until approved. Article number auto-assigned. Reuse on invoice lines via gnubok_create_invoice.',
|
||||
outputSchema: STAGED_OPERATION_SCHEMA,
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
name: { type: 'string', description: 'Article name (prints on the invoice line).' },
|
||||
type: { type: 'string', enum: ['vara', 'tjanst'], description: 'Good (vara) or service (tjanst). Default tjanst.' },
|
||||
unit: { type: 'string', description: 'Unit, e.g. st, tim, kg. Default st.' },
|
||||
price_excl_vat: { type: 'number', description: 'Unit price EXCLUDING VAT.' },
|
||||
vat_rate: { type: 'number', enum: [0, 6, 12, 25], description: 'VAT rate percent. Default 25.' },
|
||||
revenue_account: { type: 'string', description: 'Optional BAS class-3 revenue account (e.g. 3041). Omit to derive from VAT.' },
|
||||
cost_price: { type: 'number', description: 'Optional cost price (margin only; never booked).' },
|
||||
ean: { type: 'string', description: 'Barcode / EAN.' },
|
||||
housework_type: { type: 'string', description: 'ROT/RUT arbetstyp (services only).' },
|
||||
name_en: { type: 'string', description: 'English name for English-language invoices.' },
|
||||
notes: { type: 'string' },
|
||||
article_number: { type: 'string', description: 'Optional manual number; omit to auto-generate.' },
|
||||
dry_run: { type: 'boolean', description: 'Validate and preview without staging.' },
|
||||
idempotency_key: { type: 'string', description: 'Per-operation UUID for safe retries (24h TTL).' },
|
||||
},
|
||||
required: ['name', 'price_excl_vat'],
|
||||
},
|
||||
annotations: {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: false,
|
||||
},
|
||||
async execute(args, companyId, userId, supabase, actor) {
|
||||
const name = (args.name as string)?.trim()
|
||||
if (!name) throw new Error('Article name is required.')
|
||||
if (typeof args.price_excl_vat !== 'number') {
|
||||
throw new Error('price_excl_vat is required and must be a number.')
|
||||
}
|
||||
|
||||
const params: Record<string, unknown> = {
|
||||
name,
|
||||
type: (args.type as string) || 'tjanst',
|
||||
unit: (args.unit as string) || undefined,
|
||||
price_excl_vat: args.price_excl_vat,
|
||||
vat_rate: typeof args.vat_rate === 'number' ? args.vat_rate : 25,
|
||||
revenue_account: (args.revenue_account as string) || null,
|
||||
cost_price: typeof args.cost_price === 'number' ? args.cost_price : null,
|
||||
ean: (args.ean as string) || null,
|
||||
housework_type: (args.housework_type as string) || null,
|
||||
name_en: (args.name_en as string) || null,
|
||||
notes: (args.notes as string) || null,
|
||||
article_number: (args.article_number as string) || null,
|
||||
}
|
||||
|
||||
return stagePendingOperation(supabase, companyId, userId, 'create_article',
|
||||
`Ny artikel: ${name}`,
|
||||
params,
|
||||
params, // params ARE the preview
|
||||
actor,
|
||||
{
|
||||
description: 'Once approved, add it to an invoice with gnubok_create_invoice using the returned article fields.',
|
||||
tool: 'gnubok_create_invoice',
|
||||
},
|
||||
{
|
||||
dryRun: Boolean(args.dry_run),
|
||||
idempotencyKey: typeof args.idempotency_key === 'string' ? args.idempotency_key : undefined,
|
||||
}
|
||||
)
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: 'gnubok_update_article',
|
||||
title: 'Update Article',
|
||||
description: 'Stage an edit to a catalog article (price, name, account, etc.) or deactivate it via active:false. Stages for approval. Find article_id with gnubok_list_articles.',
|
||||
outputSchema: STAGED_OPERATION_SCHEMA,
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
article_id: { type: 'string', description: 'UUID of the article to update.' },
|
||||
name: { type: 'string' },
|
||||
type: { type: 'string', enum: ['vara', 'tjanst'] },
|
||||
unit: { type: 'string' },
|
||||
price_excl_vat: { type: 'number' },
|
||||
vat_rate: { type: 'number', enum: [0, 6, 12, 25] },
|
||||
revenue_account: { type: 'string', description: 'BAS class-3 revenue account, or omit to leave unchanged.' },
|
||||
cost_price: { type: 'number' },
|
||||
ean: { type: 'string' },
|
||||
housework_type: { type: 'string' },
|
||||
name_en: { type: 'string' },
|
||||
notes: { type: 'string' },
|
||||
active: { type: 'boolean', description: 'Set false to deactivate (hide from pickers, keep history).' },
|
||||
dry_run: { type: 'boolean' },
|
||||
idempotency_key: { type: 'string' },
|
||||
},
|
||||
required: ['article_id'],
|
||||
},
|
||||
annotations: {
|
||||
readOnlyHint: false,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: false,
|
||||
},
|
||||
async execute(args, companyId, userId, supabase, actor) {
|
||||
const articleId = args.article_id as string
|
||||
if (!articleId) throw new Error('article_id is required.')
|
||||
|
||||
const params: Record<string, unknown> = { article_id: articleId }
|
||||
for (const key of [
|
||||
'name', 'type', 'unit', 'price_excl_vat', 'vat_rate', 'revenue_account',
|
||||
'cost_price', 'ean', 'housework_type', 'name_en', 'notes', 'active',
|
||||
]) {
|
||||
if (args[key] !== undefined) params[key] = args[key]
|
||||
}
|
||||
|
||||
return stagePendingOperation(supabase, companyId, userId, 'update_article',
|
||||
`Uppdatera artikel ${(args.name as string)?.trim() || articleId}`,
|
||||
params,
|
||||
params,
|
||||
actor,
|
||||
undefined,
|
||||
{
|
||||
dryRun: Boolean(args.dry_run),
|
||||
idempotencyKey: typeof args.idempotency_key === 'string' ? args.idempotency_key : undefined,
|
||||
}
|
||||
)
|
||||
},
|
||||
},
|
||||
|
||||
// ── Invoice tools ────────────────────────────────────────────
|
||||
|
||||
{
|
||||
|
||||
@@ -28,6 +28,14 @@ const accountNumber = z.string().regex(/^\d{4}$/, 'Account number must be exactl
|
||||
/** Non-negative monetary amount (>= 0) */
|
||||
const nonNegativeAmount = z.number().nonnegative()
|
||||
|
||||
/** BAS class-3 revenue account — exactly 4 digits starting with 3 (försäljning/intäkt). */
|
||||
const revenueAccount = z
|
||||
.string()
|
||||
.regex(/^3\d{3}$/, 'Revenue account must be a 4-digit BAS class-3 account (3xxx)')
|
||||
|
||||
/** Swedish VAT rate as an integer percent. */
|
||||
const vatRatePercent = z.union([z.literal(0), z.literal(6), z.literal(12), z.literal(25)])
|
||||
|
||||
/** Time string (HH:MM or HH:MM:SS) */
|
||||
const timeString = z.string().regex(/^\d{2}:\d{2}(:\d{2})?$/, 'Expected HH:MM or HH:MM:SS time format')
|
||||
|
||||
@@ -190,6 +198,11 @@ export const CreateInvoiceItemSchema = z.object({
|
||||
unit: z.string().min(1, 'Unit is required'),
|
||||
unit_price: z.number(),
|
||||
vat_rate: z.number().min(0).max(100).optional(),
|
||||
// Article linkage. `article_id` ties the line to a catalog article (free-text
|
||||
// lines omit it). `revenue_account` is the optional BAS class-3 override the
|
||||
// engine books to; the API validates it against chart_of_accounts before use.
|
||||
article_id: uuid.nullable().optional(),
|
||||
revenue_account: revenueAccount.nullable().optional(),
|
||||
// ROT/RUT-avdrag fields. `deduction_amount` is intentionally omitted from
|
||||
// the client schema — the API computes it from rot-rut-rules.ts so a
|
||||
// tampered client can't expand the 1513 receivable beyond the line total.
|
||||
@@ -232,6 +245,37 @@ export const CreateCreditNoteSchema = z.object({
|
||||
reason: z.string().optional(),
|
||||
})
|
||||
|
||||
// ============================================================
|
||||
// Articles (artikelregister)
|
||||
// ============================================================
|
||||
|
||||
export const ArticleTypeSchema = z.enum(['vara', 'tjanst'])
|
||||
|
||||
export const CreateArticleSchema = z.object({
|
||||
name: z.string().min(1, 'Article name is required').max(200),
|
||||
type: ArticleTypeSchema.optional(),
|
||||
unit: z.string().min(1).max(32).optional(),
|
||||
price_excl_vat: nonNegativeAmount,
|
||||
vat_rate: vatRatePercent.optional(),
|
||||
// Optional BAS class-3 revenue-account override. Null/omitted = derive from
|
||||
// the invoice's VAT treatment (current behaviour).
|
||||
revenue_account: revenueAccount.nullable().optional(),
|
||||
// Margin/display only; never posted.
|
||||
cost_price: nonNegativeAmount.nullable().optional(),
|
||||
ean: z.string().max(32).nullable().optional(),
|
||||
// ROT/RUT arbetstyp; only meaningful for type === 'tjanst'.
|
||||
housework_type: z.string().max(64).nullable().optional(),
|
||||
name_en: z.string().max(200).nullable().optional(),
|
||||
notes: z.string().max(2000).nullable().optional(),
|
||||
// Manual article number; omit to auto-generate via generate_article_number.
|
||||
article_number: z.string().max(64).nullable().optional(),
|
||||
})
|
||||
|
||||
// PATCH allows every create field plus toggling the soft-delete flag.
|
||||
export const UpdateArticleSchema = CreateArticleSchema.partial().extend({
|
||||
active: z.boolean().optional(),
|
||||
})
|
||||
|
||||
// Self-billing received (mottagen självfaktura, ML 17 kap 15§). The customer
|
||||
// issued the invoice on our behalf; for us it is a sale. We store the
|
||||
// counterparty's number in external_invoice_number and never assign one from
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
/**
|
||||
* Assign an article number to an article row via the generate_article_number
|
||||
* RPC. Idempotent: if the row already has a number, the RPC returns it unchanged
|
||||
* without consuming a sequence number. Concurrency is handled inside the RPC via
|
||||
* a row lock on the article plus an atomic counter on company_settings — two
|
||||
* callers racing on the same article both return the same number and the counter
|
||||
* advances by exactly one.
|
||||
*
|
||||
* Mirrors lib/invoices/ensure-invoice-number.ts. Unlike invoice numbers, article
|
||||
* numbers are master data and carry no BFL sequence/immutability obligation, so
|
||||
* a gap is harmless.
|
||||
*/
|
||||
export async function ensureArticleNumber(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
articleId: string,
|
||||
): Promise<string> {
|
||||
const { data, error } = await supabase.rpc('generate_article_number', {
|
||||
p_company_id: companyId,
|
||||
p_article_id: articleId,
|
||||
})
|
||||
|
||||
if (error || !data) {
|
||||
throw new Error(`Failed to assign article number: ${error?.message ?? 'no value returned'}`)
|
||||
}
|
||||
|
||||
return data as string
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
/**
|
||||
* True when `account` exists in the company's chart of accounts as an ACTIVE
|
||||
* class-3 (revenue/intäkt) account. Used to guard the optional per-article
|
||||
* revenue-account override so a typo or a non-revenue account can never be
|
||||
* pinned to an article (and later booked). Never trust the client.
|
||||
*
|
||||
* Throws on an unexpected DB error so the route wrapper maps it to the canonical
|
||||
* envelope; a simple "account not found" resolves to `false`, not an error.
|
||||
*/
|
||||
export async function isValidRevenueAccount(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
account: string,
|
||||
): Promise<boolean> {
|
||||
const { data, error } = await supabase
|
||||
.from('chart_of_accounts')
|
||||
.select('account_number')
|
||||
.eq('company_id', companyId)
|
||||
.eq('account_class', 3)
|
||||
.eq('is_active', true)
|
||||
.eq('account_number', account)
|
||||
.maybeSingle()
|
||||
|
||||
if (error) throw error
|
||||
return !!data
|
||||
}
|
||||
@@ -11,6 +11,8 @@ export const API_KEY_SCOPES = {
|
||||
'transactions:write': { label: 'Transaktioner — skriv', description: 'Kategorisera, av-kategorisera, kvittomatchning, koppling mot faktura (4 verktyg)' },
|
||||
'customers:read': { label: 'Kunder — läs', description: 'Lista kunder (1 verktyg)' },
|
||||
'customers:write': { label: 'Kunder — skriv', description: 'Skapa kunder (1 verktyg)' },
|
||||
'articles:read': { label: 'Artiklar — läs', description: 'Lista artiklar i artikelregistret (1 verktyg)' },
|
||||
'articles:write': { label: 'Artiklar — skriv', description: 'Skapa och uppdatera artiklar (2 verktyg)' },
|
||||
'invoices:read': { label: 'Fakturor — läs', description: 'Lista fakturor (1 verktyg)' },
|
||||
'invoices:write': { label: 'Fakturor — skriv', description: 'Skapa, skicka, markera betald/skickad (4 verktyg)' },
|
||||
'suppliers:read': { label: 'Leverantörer — läs', description: 'Lista leverantörer och leverantörsfakturor, hitta verifikat-kandidater (3 verktyg)' },
|
||||
@@ -42,6 +44,7 @@ export const ALL_SCOPES: ApiKeyScope[] = Object.keys(API_KEY_SCOPES) as ApiKeySc
|
||||
export const DEFAULT_SCOPES: ApiKeyScope[] = [
|
||||
'transactions:read',
|
||||
'customers:read',
|
||||
'articles:read',
|
||||
'invoices:read',
|
||||
'suppliers:read',
|
||||
'reports:read',
|
||||
@@ -71,6 +74,7 @@ export const DEFAULT_SCOPES: ApiKeyScope[] = [
|
||||
export const DEFAULT_OAUTH_SCOPES: ApiKeyScope[] = [
|
||||
'transactions:read',
|
||||
'customers:read',
|
||||
'articles:read',
|
||||
'invoices:read',
|
||||
'suppliers:read',
|
||||
'reports:read',
|
||||
@@ -109,6 +113,7 @@ export const PUBLIC_OAUTH_METADATA_SCOPES: ApiKeyScope[] = [...DEFAULT_OAUTH_SCO
|
||||
export const STAGING_SCOPES: ApiKeyScope[] = [
|
||||
'transactions:write',
|
||||
'customers:write',
|
||||
'articles:write',
|
||||
'invoices:write',
|
||||
'suppliers:write',
|
||||
'bookkeeping:write',
|
||||
@@ -140,6 +145,7 @@ export function findStageApproveConflict(scopes: ApiKeyScope[]): ApiKeyScope | n
|
||||
export const SCOPE_GROUPS = [
|
||||
{ domain: 'transactions', label: 'Transaktioner', read: 'transactions:read' as const, write: 'transactions:write' as const },
|
||||
{ domain: 'customers', label: 'Kunder', read: 'customers:read' as const, write: 'customers:write' as const },
|
||||
{ domain: 'articles', label: 'Artiklar', read: 'articles:read' as const, write: 'articles:write' as const },
|
||||
{ domain: 'invoices', label: 'Fakturor', read: 'invoices:read' as const, write: 'invoices:write' as const },
|
||||
{ domain: 'suppliers', label: 'Leverantörer', read: 'suppliers:read' as const, write: 'suppliers:write' as const },
|
||||
{ domain: 'reports', label: 'Rapporter', read: 'reports:read' as const, write: null },
|
||||
@@ -168,6 +174,10 @@ export const TOOL_SCOPE_MAP: Record<string, ApiKeyScope> = {
|
||||
// Customers
|
||||
gnubok_list_customers: 'customers:read',
|
||||
gnubok_create_customer: 'customers:write',
|
||||
// Articles (artikelregister)
|
||||
gnubok_list_articles: 'articles:read',
|
||||
gnubok_create_article: 'articles:write',
|
||||
gnubok_update_article: 'articles:write',
|
||||
// Invoices
|
||||
gnubok_list_invoices: 'invoices:read',
|
||||
gnubok_create_invoice: 'invoices:write',
|
||||
|
||||
@@ -298,6 +298,113 @@ describe('createInvoiceJournalEntry — per-line VAT', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('createInvoiceJournalEntry — per-article revenue account override', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('without an override, two 25% lines collapse into one 3001 revenue line (unchanged behaviour)', async () => {
|
||||
const invoice = makeInvoice({
|
||||
subtotal: 1000,
|
||||
vat_amount: 250,
|
||||
total: 1250,
|
||||
vat_treatment: 'standard_25',
|
||||
vat_rate: null as unknown as number,
|
||||
items: [
|
||||
makeItem({ description: 'A', unit_price: 600, line_total: 600, vat_rate: 25, vat_amount: 150 }),
|
||||
makeItem({ id: 'item-2', description: 'B', unit_price: 400, line_total: 400, vat_rate: 25, vat_amount: 100 }),
|
||||
],
|
||||
})
|
||||
|
||||
await createInvoiceJournalEntry(null as never, 'company-1', 'user-1', invoice)
|
||||
const input = mockedCreateEntry.mock.calls[0][3]
|
||||
|
||||
const rev3001 = input.lines.filter((l) => l.account_number === '3001')
|
||||
expect(rev3001).toHaveLength(1)
|
||||
expect(rev3001[0].credit_amount).toBe(1000)
|
||||
const vat2611 = input.lines.filter((l) => l.account_number === '2611')
|
||||
expect(vat2611).toHaveLength(1)
|
||||
expect(vat2611[0].credit_amount).toBe(250)
|
||||
})
|
||||
|
||||
it('splits one rate into two revenue accounts but keeps a single VAT line, balanced', async () => {
|
||||
const invoice = makeInvoice({
|
||||
subtotal: 1000,
|
||||
vat_amount: 250,
|
||||
total: 1250,
|
||||
vat_treatment: 'standard_25',
|
||||
vat_rate: null as unknown as number,
|
||||
items: [
|
||||
makeItem({ description: 'Goods', unit_price: 600, line_total: 600, vat_rate: 25, vat_amount: 150 }), // no override → 3001
|
||||
makeItem({ id: 'item-2', description: 'Consulting', unit_price: 400, line_total: 400, vat_rate: 25, vat_amount: 100, revenue_account: '3041' }),
|
||||
],
|
||||
})
|
||||
|
||||
await createInvoiceJournalEntry(null as never, 'company-1', 'user-1', invoice)
|
||||
const input = mockedCreateEntry.mock.calls[0][3]
|
||||
|
||||
expect(input.lines.find((l) => l.account_number === '3001')?.credit_amount).toBe(600)
|
||||
expect(input.lines.find((l) => l.account_number === '3041')?.credit_amount).toBe(400)
|
||||
const vat = input.lines.filter((l) => l.account_number === '2611')
|
||||
expect(vat).toHaveLength(1)
|
||||
expect(vat[0].credit_amount).toBe(250)
|
||||
|
||||
const debit = input.lines.reduce((s, l) => s + l.debit_amount, 0)
|
||||
const credit = input.lines.reduce((s, l) => s + l.credit_amount, 0)
|
||||
expect(debit).toBe(credit)
|
||||
expect(debit).toBe(1250)
|
||||
})
|
||||
|
||||
it('ignores a per-line override on reverse charge — revenue stays on 3308', async () => {
|
||||
const invoice = makeInvoice({
|
||||
subtotal: 5000,
|
||||
vat_amount: 0,
|
||||
total: 5000,
|
||||
vat_treatment: 'reverse_charge',
|
||||
vat_rate: 0,
|
||||
items: [
|
||||
makeItem({ unit_price: 5000, line_total: 5000, vat_rate: 0, vat_amount: 0, revenue_account: '3041' }),
|
||||
],
|
||||
})
|
||||
|
||||
await createInvoiceJournalEntry(null as never, 'company-1', 'user-1', invoice)
|
||||
const input = mockedCreateEntry.mock.calls[0][3]
|
||||
|
||||
expect(input.lines.find((l) => l.account_number === '3308')?.credit_amount).toBe(5000)
|
||||
expect(input.lines.find((l) => l.account_number === '3041')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('absorbs rounding on the last account so a split rate still balances against 1510', async () => {
|
||||
// Two 25% lines to different accounts whose individual SEK rounding would
|
||||
// otherwise drift from the rate-level total (10.005 → 10.01 each = 20.02,
|
||||
// but the rate total is round(20.01) = 20.01).
|
||||
const invoice = makeInvoice({
|
||||
subtotal: 20.01,
|
||||
vat_amount: 5.0,
|
||||
total: 25.01,
|
||||
vat_treatment: 'standard_25',
|
||||
vat_rate: null as unknown as number,
|
||||
items: [
|
||||
makeItem({ description: 'A', unit_price: 10.005, line_total: 10.005, vat_rate: 25, vat_amount: 2.5 }),
|
||||
makeItem({ id: 'item-2', description: 'B', unit_price: 10.005, line_total: 10.005, vat_rate: 25, vat_amount: 2.5, revenue_account: '3041' }),
|
||||
],
|
||||
})
|
||||
|
||||
await createInvoiceJournalEntry(null as never, 'company-1', 'user-1', invoice)
|
||||
const input = mockedCreateEntry.mock.calls[0][3]
|
||||
|
||||
const revSum = input.lines
|
||||
.filter((l) => l.account_number === '3001' || l.account_number === '3041')
|
||||
.reduce((s, l) => s + l.credit_amount, 0)
|
||||
expect(Math.round(revSum * 100) / 100).toBe(20.01)
|
||||
|
||||
const debit = Math.round(input.lines.reduce((s, l) => s + l.debit_amount, 0) * 100) / 100
|
||||
const credit = Math.round(input.lines.reduce((s, l) => s + l.credit_amount, 0) * 100) / 100
|
||||
expect(debit).toBe(credit)
|
||||
expect(debit).toBe(25.01)
|
||||
})
|
||||
})
|
||||
|
||||
describe('createCreditNoteJournalEntry — per-line VAT', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
@@ -108,29 +108,65 @@ function generatePerRateLines(
|
||||
return lines
|
||||
}
|
||||
|
||||
// Group items by vat_rate
|
||||
const rateGroups = new Map<number, { subtotal: number; vatAmount: number }>()
|
||||
// Group items by vat_rate (preserve first-seen rate order). Within each rate,
|
||||
// sub-group revenue by the resolved BAS account so a per-line/article account
|
||||
// override produces its own credit line. VAT stays aggregated per rate (the
|
||||
// VAT account is a function of the treatment, never of the revenue override).
|
||||
type RateGroup = {
|
||||
vatAmount: number
|
||||
// resolved revenue account -> summed line_total (first-seen account order)
|
||||
byAccount: Map<string, number>
|
||||
}
|
||||
const rateGroups = new Map<number, RateGroup>()
|
||||
|
||||
for (const item of items) {
|
||||
const rate = item.vat_rate ?? 0
|
||||
const group = rateGroups.get(rate) || { subtotal: 0, vatAmount: 0 }
|
||||
group.subtotal += item.line_total
|
||||
const treatment = rate === 0 && (invoiceVatTreatment === 'reverse_charge' || invoiceVatTreatment === 'export')
|
||||
? invoiceVatTreatment
|
||||
: getVatTreatmentForRate(rate)
|
||||
// reverse_charge / export force the statutory revenue account (3308/3305);
|
||||
// a per-line override only applies to ordinary domestic rates so EU/export
|
||||
// sales keep landing in the right VAT-declaration ruta.
|
||||
const isSpecialTreatment = treatment === 'reverse_charge' || treatment === 'export'
|
||||
const account = !isSpecialTreatment && item.revenue_account
|
||||
? item.revenue_account
|
||||
: getRevenueAccount(treatment, entityType)
|
||||
|
||||
const group = rateGroups.get(rate) ?? { vatAmount: 0, byAccount: new Map<string, number>() }
|
||||
group.vatAmount += item.vat_amount || 0
|
||||
group.byAccount.set(account, (group.byAccount.get(account) ?? 0) + item.line_total)
|
||||
rateGroups.set(rate, group)
|
||||
}
|
||||
|
||||
// Generate revenue + VAT lines per rate group
|
||||
// Generate revenue + VAT lines per rate group.
|
||||
for (const [rate, group] of rateGroups) {
|
||||
const treatment = rate === 0 && (invoiceVatTreatment === 'reverse_charge' || invoiceVatTreatment === 'export')
|
||||
? invoiceVatTreatment
|
||||
: getVatTreatmentForRate(rate)
|
||||
const revenueAccount = getRevenueAccount(treatment, entityType)
|
||||
const roundedSubtotal = Math.round(toSek(group.subtotal) * 100) / 100
|
||||
|
||||
lines.push({
|
||||
account_number: revenueAccount,
|
||||
debit_amount: 0,
|
||||
credit_amount: roundedSubtotal,
|
||||
line_description: `Försäljning faktura ${invoiceTagText}`,
|
||||
// The rate-level rounded subtotal is the balance anchor — identical to the
|
||||
// pre-override single-account behaviour. When a rate splits across multiple
|
||||
// accounts, distribute that exact total so independent per-account rounding
|
||||
// can never introduce a 1-öre imbalance against the 1510 debit: every
|
||||
// account but the last rounds normally; the last absorbs the remainder.
|
||||
const rateSubtotalSek = Math.round(
|
||||
toSek(Array.from(group.byAccount.values()).reduce((sum, v) => sum + v, 0)) * 100
|
||||
) / 100
|
||||
|
||||
const accounts = Array.from(group.byAccount.entries())
|
||||
let allocated = 0
|
||||
accounts.forEach(([account, subtotal], idx) => {
|
||||
const isLast = idx === accounts.length - 1
|
||||
const credit = isLast
|
||||
? Math.round((rateSubtotalSek - allocated) * 100) / 100
|
||||
: Math.round(toSek(subtotal) * 100) / 100
|
||||
allocated = Math.round((allocated + credit) * 100) / 100
|
||||
lines.push({
|
||||
account_number: account,
|
||||
debit_amount: 0,
|
||||
credit_amount: credit,
|
||||
line_description: `Försäljning faktura ${invoiceTagText}`,
|
||||
})
|
||||
})
|
||||
|
||||
const roundedVat = Math.round(toSek(group.vatAmount) * 100) / 100
|
||||
|
||||
@@ -24,6 +24,7 @@ type ErrorContext =
|
||||
| 'invoice'
|
||||
| 'supplier_invoice'
|
||||
| 'customer'
|
||||
| 'article'
|
||||
| 'supplier'
|
||||
| 'transaction'
|
||||
| 'journal_entry'
|
||||
@@ -78,6 +79,7 @@ const CONTEXT_FALLBACKS: Record<ErrorContext, Bilingual> = {
|
||||
invoice: { sv: 'Kunde inte hantera fakturan. Försök igen.', en: 'Could not process the invoice. Please try again.' },
|
||||
supplier_invoice: { sv: 'Kunde inte hantera leverantörsfakturan. Försök igen.', en: 'Could not process the supplier invoice. Please try again.' },
|
||||
customer: { sv: 'Kunde inte hantera kunden. Försök igen.', en: 'Could not process the customer. Please try again.' },
|
||||
article: { sv: 'Kunde inte hantera artikeln. Försök igen.', en: 'Could not process the article. Please try again.' },
|
||||
supplier: { sv: 'Kunde inte hantera leverantören. Försök igen.', en: 'Could not process the supplier. Please try again.' },
|
||||
transaction: { sv: 'Kunde inte hantera transaktionen. Försök igen.', en: 'Could not process the transaction. Please try again.' },
|
||||
journal_entry: { sv: 'Kunde inte hantera verifikationen. Försök igen.', en: 'Could not process the journal entry. Please try again.' },
|
||||
|
||||
@@ -579,6 +579,11 @@ const INVOICE: Record<string, StructuredErrorEntry> = {
|
||||
message_sv: 'Momssatsen är inte tillåten för denna kundtyp.',
|
||||
message_en: 'The VAT rate is not allowed for this customer type.',
|
||||
},
|
||||
INVOICE_CREATE_REVENUE_ACCOUNT_INVALID: {
|
||||
httpStatus: 400,
|
||||
message_sv: 'Ett angivet försäljningskonto finns inte eller är inte ett aktivt intäktskonto (klass 3).',
|
||||
message_en: 'A supplied revenue account does not exist or is not an active class-3 income account.',
|
||||
},
|
||||
INVOICE_CREATE_ROT_RUT_VALIDATION: {
|
||||
httpStatus: 400,
|
||||
message_sv: 'ROT/RUT-avdraget kunde inte valideras. Kontrollera personnummer och fastighetsbeteckning.',
|
||||
@@ -1424,6 +1429,34 @@ const CUSTOMER: Record<string, StructuredErrorEntry> = {
|
||||
},
|
||||
}
|
||||
|
||||
const ARTICLE: Record<string, StructuredErrorEntry> = {
|
||||
ARTICLE_NOT_FOUND: {
|
||||
httpStatus: 404,
|
||||
message_sv: 'Artikeln kunde inte hittas.',
|
||||
message_en: 'Article not found.',
|
||||
},
|
||||
ARTICLE_DUPLICATE_NUMBER: {
|
||||
httpStatus: 409,
|
||||
message_sv: 'En artikel med samma artikelnummer finns redan.',
|
||||
message_en: 'An article with that article number already exists.',
|
||||
},
|
||||
ARTICLE_CREATE_FAILED: {
|
||||
httpStatus: 500,
|
||||
message_sv: 'Artikeln kunde inte skapas.',
|
||||
message_en: 'Failed to create article.',
|
||||
},
|
||||
ARTICLE_UPDATE_FAILED: {
|
||||
httpStatus: 500,
|
||||
message_sv: 'Artikeln kunde inte uppdateras.',
|
||||
message_en: 'Failed to update article.',
|
||||
},
|
||||
ARTICLE_REVENUE_ACCOUNT_INVALID: {
|
||||
httpStatus: 400,
|
||||
message_sv: 'Försäljningskontot finns inte eller är inte ett aktivt intäktskonto (klass 3).',
|
||||
message_en: 'The revenue account does not exist or is not an active class-3 income account.',
|
||||
},
|
||||
}
|
||||
|
||||
const SUPPLIER: Record<string, StructuredErrorEntry> = {
|
||||
SUPPLIER_NOT_FOUND: {
|
||||
httpStatus: 404,
|
||||
@@ -2271,6 +2304,7 @@ const REGISTRY: Record<string, StructuredErrorEntry> = {
|
||||
...PROVIDER_MIGRATION,
|
||||
...DOCUMENT,
|
||||
...CUSTOMER,
|
||||
...ARTICLE,
|
||||
...SUPPLIER,
|
||||
...SUPPLIER_INVOICE_WAVE4,
|
||||
...SALARY,
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
Transaction,
|
||||
Customer,
|
||||
Supplier,
|
||||
Article,
|
||||
FiscalPeriod,
|
||||
DocumentAttachment,
|
||||
Receipt,
|
||||
@@ -78,6 +79,9 @@ export type CoreEvent =
|
||||
| { type: 'period.year_closed'; payload: { period: FiscalPeriod; userId: string; companyId: string } }
|
||||
// Customers
|
||||
| { type: 'customer.created'; payload: { customer: Customer; userId: string; companyId: string } }
|
||||
// Articles (artikelregister)
|
||||
| { type: 'article.created'; payload: { article: Article; userId: string; companyId: string } }
|
||||
| { type: 'article.updated'; payload: { article: Article; userId: string; companyId: string } }
|
||||
// Suppliers
|
||||
| { type: 'supplier.created'; payload: { supplier: Supplier; userId: string; companyId: string } }
|
||||
// Receipts
|
||||
|
||||
@@ -230,6 +230,11 @@ export async function executeRecurringSchedule(
|
||||
}
|
||||
|
||||
// 6. Insert items.
|
||||
// NOTE (artikelregister Phase 2): recurring schedule template items have no
|
||||
// article_id / revenue_account columns (see recurring_invoice_schedule_items),
|
||||
// so generated invoices fall back to the VAT-treatment-derived revenue account.
|
||||
// Wiring per-article overrides into recurring invoices needs a schema change
|
||||
// and is deliberately out of the artikelregister MVP scope.
|
||||
const itemRows = items.map((item, index) => {
|
||||
const itemRate = item.vat_rate != null ? item.vat_rate : vatRules.rate
|
||||
const lineTotal = item.quantity * item.unit_price
|
||||
|
||||
@@ -70,6 +70,9 @@ import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { appendProcessingHistory } from '@/lib/processing-history/append'
|
||||
import { CreateSupplierParamsSchema } from '@/lib/pending-operations/schemas/create-supplier'
|
||||
import { CreateArticleParamsSchema, UpdateArticleParamsSchema } from '@/lib/pending-operations/schemas/article'
|
||||
import { ensureArticleNumber } from '@/lib/articles/ensure-article-number'
|
||||
import { isValidRevenueAccount } from '@/lib/articles/validate-revenue-account'
|
||||
import { z } from 'zod'
|
||||
import type {
|
||||
Transaction,
|
||||
@@ -80,6 +83,7 @@ import type {
|
||||
Invoice,
|
||||
Customer,
|
||||
Supplier,
|
||||
Article,
|
||||
SupplierInvoice,
|
||||
SupplierInvoiceItem,
|
||||
PendingOperation,
|
||||
@@ -427,6 +431,112 @@ async function commitCreateCustomer(
|
||||
return { data: { customer_id: data.id } }
|
||||
}
|
||||
|
||||
async function commitCreateArticle(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
params: Record<string, unknown>
|
||||
): Promise<ExecutorResult> {
|
||||
// Defense in depth: re-validate the staged params at the commit boundary so a
|
||||
// tampered pending_operations row cannot inject unexpected fields (ASVS V4.5).
|
||||
let validated
|
||||
try {
|
||||
validated = CreateArticleParamsSchema.parse(params)
|
||||
} catch (err) {
|
||||
if (err instanceof z.ZodError) {
|
||||
const issue = err.issues[0]
|
||||
return { error: `Invalid ${issue?.path?.join('.') ?? 'params'}: ${issue?.message ?? 'validation failed'}`, status: 400 }
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
if (validated.revenue_account) {
|
||||
const ok = await isValidRevenueAccount(supabase, companyId, validated.revenue_account)
|
||||
if (!ok) return { error: 'Revenue account is not an active class-3 account', status: 400 }
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('articles')
|
||||
.insert({
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
name: validated.name,
|
||||
name_en: validated.name_en ?? null,
|
||||
type: validated.type,
|
||||
unit: validated.unit ?? 'st',
|
||||
price_excl_vat: validated.price_excl_vat,
|
||||
vat_rate: validated.vat_rate,
|
||||
revenue_account: validated.revenue_account ?? null,
|
||||
cost_price: validated.cost_price ?? null,
|
||||
ean: validated.ean ?? null,
|
||||
housework_type: validated.housework_type ?? null,
|
||||
notes: validated.notes ?? null,
|
||||
article_number: validated.article_number ?? null,
|
||||
})
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (error) return { error: error.message, status: 500 }
|
||||
|
||||
if (!data.article_number) {
|
||||
try {
|
||||
data.article_number = await ensureArticleNumber(supabase, companyId, data.id)
|
||||
} catch (err) {
|
||||
log.warn('article number assignment failed (staged create):', err)
|
||||
}
|
||||
}
|
||||
|
||||
await eventBus.emit({ type: 'article.created', payload: { article: data as Article, userId, companyId } })
|
||||
|
||||
return { data: { article_id: data.id, article_number: data.article_number } }
|
||||
}
|
||||
|
||||
async function commitUpdateArticle(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
params: Record<string, unknown>
|
||||
): Promise<ExecutorResult> {
|
||||
let validated
|
||||
try {
|
||||
validated = UpdateArticleParamsSchema.parse(params)
|
||||
} catch (err) {
|
||||
if (err instanceof z.ZodError) {
|
||||
const issue = err.issues[0]
|
||||
return { error: `Invalid ${issue?.path?.join('.') ?? 'params'}: ${issue?.message ?? 'validation failed'}`, status: 400 }
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
if (validated.revenue_account) {
|
||||
const ok = await isValidRevenueAccount(supabase, companyId, validated.revenue_account)
|
||||
if (!ok) return { error: 'Revenue account is not an active class-3 account', status: 400 }
|
||||
}
|
||||
|
||||
const { article_id, ...rest } = validated
|
||||
const updateData: Record<string, unknown> = {}
|
||||
for (const [key, value] of Object.entries(rest)) {
|
||||
if (value !== undefined) updateData[key] = value
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('articles')
|
||||
.update(updateData)
|
||||
.eq('id', article_id)
|
||||
.eq('company_id', companyId)
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
if (error.code === 'PGRST116') return { error: 'Article not found', status: 404 }
|
||||
return { error: error.message, status: 500 }
|
||||
}
|
||||
|
||||
await eventBus.emit({ type: 'article.updated', payload: { article: data as Article, userId, companyId } })
|
||||
|
||||
return { data: { article_id: data.id } }
|
||||
}
|
||||
|
||||
async function commitCreateSupplier(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
@@ -539,6 +649,7 @@ async function commitCreateInvoice(
|
||||
const customerId = params.customer_id as string
|
||||
const items = params.items as Array<{
|
||||
description: string; quantity: number; unit: string; unit_price: number; vat_rate?: number
|
||||
article_id?: string | null; revenue_account?: string | null
|
||||
}>
|
||||
|
||||
const { data: customer, error: customerError } = await supabase
|
||||
@@ -564,6 +675,17 @@ async function commitCreateInvoice(
|
||||
vatAmount += Math.round(lineTotal * itemRate / 100 * 100) / 100
|
||||
}
|
||||
|
||||
// Validate any per-line revenue-account override (defense in depth — the field
|
||||
// is frozen onto invoice_items and flows to generatePerRateLines()).
|
||||
const overrideAccounts = Array.from(
|
||||
new Set(items.map((i) => i.revenue_account).filter((a): a is string => !!a)),
|
||||
)
|
||||
for (const acct of overrideAccounts) {
|
||||
if (!(await isValidRevenueAccount(supabase, companyId, acct))) {
|
||||
return { error: `Försäljningskonto ${acct} är inte ett aktivt intäktskonto (klass 3)`, status: 400 }
|
||||
}
|
||||
}
|
||||
|
||||
const total = subtotal + vatAmount
|
||||
const currency = ((params.currency as string) || 'SEK') as Currency
|
||||
|
||||
@@ -632,6 +754,10 @@ async function commitCreateInvoice(
|
||||
line_total: lineTotal,
|
||||
vat_rate: itemRate,
|
||||
vat_amount: itemVat,
|
||||
// Frozen per-line override so generatePerRateLines() books to the article's
|
||||
// account; null falls back to the VAT-treatment-derived account.
|
||||
article_id: item.article_id ?? null,
|
||||
revenue_account: item.revenue_account ?? null,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -2099,6 +2225,8 @@ async function commitCreditInvoice(
|
||||
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,
|
||||
@@ -2109,6 +2237,10 @@ async function commitCreditInvoice(
|
||||
line_total: -Math.abs(item.line_total),
|
||||
vat_rate: item.vat_rate ?? 0,
|
||||
vat_amount: -(item.vat_amount ? Math.abs(item.vat_amount) : 0),
|
||||
// Reverse to the SAME account the original credited (e.g. 3041, not the
|
||||
// VAT-derived 3001) so the override account doesn't keep a dangling balance.
|
||||
revenue_account: item.revenue_account ?? null,
|
||||
article_id: item.article_id ?? null,
|
||||
}))
|
||||
|
||||
const { error: itemsError } = await supabase
|
||||
@@ -2257,6 +2389,13 @@ async function commitConvertInvoice(
|
||||
unit: item.unit,
|
||||
unit_price: item.unit_price,
|
||||
line_total: item.line_total,
|
||||
// Preserve per-line VAT and any article/revenue-account override from the
|
||||
// proforma so the converted invoice books exactly as the proforma showed
|
||||
// (mixed rates + per-article accounts both rely on these per-line fields).
|
||||
vat_rate: item.vat_rate ?? 0,
|
||||
vat_amount: item.vat_amount ?? 0,
|
||||
revenue_account: item.revenue_account ?? null,
|
||||
article_id: item.article_id ?? null,
|
||||
}))
|
||||
|
||||
if (items.length > 0) {
|
||||
@@ -3163,6 +3302,12 @@ async function commitPendingOperationInner(
|
||||
case 'create_customer':
|
||||
result = await commitCreateCustomer(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
case 'create_article':
|
||||
result = await commitCreateArticle(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
case 'update_article':
|
||||
result = await commitUpdateArticle(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
case 'create_supplier':
|
||||
result = await commitCreateSupplier(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
|
||||
@@ -21,6 +21,12 @@ export type RiskLevel = 'low' | 'medium' | 'high'
|
||||
export const OPERATION_RISK_TIERS: Record<string, RiskLevel> = {
|
||||
// ── Low: pure data, no booking impact ─────────────────────────────
|
||||
create_customer: 'low',
|
||||
// Article catalog (artikelregister) is app-level master data — no journal
|
||||
// impact, no external side-effect. Unlike create_supplier it carries no
|
||||
// payment-routing fields, so there's no BEC/fraud surface; both create and
|
||||
// update sit at the lowest tier next to create_customer.
|
||||
create_article: 'low',
|
||||
update_article: 'low',
|
||||
|
||||
// ── Medium: reversible booking ─────────────────────────────────────
|
||||
categorize_transaction: 'medium',
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
// Commit-boundary re-validation for staged article operations. A staged
|
||||
// pending_operations row is re-parsed here before it touches the articles table
|
||||
// so a tampered row cannot inject unexpected fields or malformed data
|
||||
// (defense in depth, ASVS V4.5) — mirrors lib/pending-operations/schemas/create-supplier.ts.
|
||||
|
||||
const revenueAccount = z
|
||||
.string()
|
||||
.regex(/^3\d{3}$/, 'Revenue account must be a 4-digit BAS class-3 account (3xxx)')
|
||||
|
||||
const vatRatePercent = z.union([z.literal(0), z.literal(6), z.literal(12), z.literal(25)])
|
||||
|
||||
/** Empty string / null → undefined, then bounded string. */
|
||||
const optString = (max: number) =>
|
||||
z.preprocess((v) => (v == null || v === '' ? undefined : v), z.string().max(max).optional())
|
||||
|
||||
const trimmedName = z.preprocess(
|
||||
(v) => (typeof v === 'string' ? v.trim() : v),
|
||||
z.string().min(1, 'Article name is required').max(200),
|
||||
)
|
||||
|
||||
export const CreateArticleParamsSchema = z.object({
|
||||
name: trimmedName,
|
||||
type: z.enum(['vara', 'tjanst']).default('tjanst'),
|
||||
unit: optString(32),
|
||||
price_excl_vat: z.number().nonnegative(),
|
||||
vat_rate: vatRatePercent.default(25),
|
||||
revenue_account: revenueAccount.nullable().optional(),
|
||||
cost_price: z.number().nonnegative().nullable().optional(),
|
||||
ean: optString(32),
|
||||
housework_type: optString(64),
|
||||
name_en: optString(200),
|
||||
notes: optString(2000),
|
||||
article_number: optString(64),
|
||||
})
|
||||
|
||||
export const UpdateArticleParamsSchema = z.object({
|
||||
article_id: z.string().uuid(),
|
||||
name: trimmedName.optional(),
|
||||
type: z.enum(['vara', 'tjanst']).optional(),
|
||||
unit: optString(32),
|
||||
price_excl_vat: z.number().nonnegative().optional(),
|
||||
vat_rate: vatRatePercent.optional(),
|
||||
revenue_account: revenueAccount.nullable().optional(),
|
||||
cost_price: z.number().nonnegative().nullable().optional(),
|
||||
ean: optString(32),
|
||||
housework_type: optString(64),
|
||||
name_en: optString(200),
|
||||
notes: optString(2000),
|
||||
article_number: optString(64),
|
||||
active: z.boolean().optional(),
|
||||
})
|
||||
|
||||
export type CreateArticleParams = z.infer<typeof CreateArticleParamsSchema>
|
||||
export type UpdateArticleParams = z.infer<typeof UpdateArticleParamsSchema>
|
||||
@@ -71,6 +71,7 @@
|
||||
"invoices": "Invoices",
|
||||
"sales_orders": "Orders",
|
||||
"customers": "Customers",
|
||||
"articles": "Articles",
|
||||
"products": "Products",
|
||||
"inventory": "Inventory",
|
||||
"supplier_invoices": "Supplier invoices",
|
||||
@@ -2057,6 +2058,13 @@
|
||||
},
|
||||
"invoice_editor": {
|
||||
"back": "Back",
|
||||
"article_label": "Article",
|
||||
"article_placeholder": "Select article",
|
||||
"article_free_text": "Custom line (free text)",
|
||||
"save_as_article": "Save as article",
|
||||
"save_article_need_description": "Enter a description before saving as an article",
|
||||
"article_saved_title": "Article saved",
|
||||
"save_article_failed": "Could not save the article",
|
||||
"title_invoice": "New invoice",
|
||||
"title_proforma": "New proforma invoice",
|
||||
"title_delivery_note": "New delivery note",
|
||||
@@ -3460,6 +3468,106 @@
|
||||
"copy_banner_unknown_label": "(unknown number)",
|
||||
"copy_banner_body": "A new, standalone voucher will be created with its own voucher series and number. This is NOT a correction or reversal of the original — use \"Skapa ändringsverifikation\" if you want to correct the source voucher."
|
||||
},
|
||||
"articles": {
|
||||
"title": "Articles",
|
||||
"new_article": "New article",
|
||||
"add_article": "Add article",
|
||||
"viewer_disabled_tooltip": "You only have viewer access in this company",
|
||||
"load_failed_title": "Could not load articles",
|
||||
"load_failed_description": "Check your connection and try again.",
|
||||
"create_failed_title": "Could not create article",
|
||||
"created_title": "Article created",
|
||||
"created_description": "{name} has been added",
|
||||
"search_placeholder": "Search articles",
|
||||
"no_search_results_title": "No matches",
|
||||
"no_search_results_description": "No articles match \"{term}\".",
|
||||
"empty_title": "No articles yet",
|
||||
"empty_description": "Add articles for goods and services to fill in invoice rows quickly.",
|
||||
"empty_action": "Add article",
|
||||
"type_vara": "Goods",
|
||||
"type_tjanst": "Service",
|
||||
"status_active": "Active",
|
||||
"status_inactive": "Inactive",
|
||||
"per_unit": "per {unit}",
|
||||
"vat_label_value": "{rate} % VAT",
|
||||
"col_number": "Article number",
|
||||
"col_name": "Name",
|
||||
"col_type": "Type",
|
||||
"col_unit": "Unit",
|
||||
"col_price": "Price excl. VAT",
|
||||
"col_vat": "VAT",
|
||||
"col_status": "Status"
|
||||
},
|
||||
"article_detail": {
|
||||
"back": "Back to articles",
|
||||
"edit": "Edit",
|
||||
"deactivate": "Deactivate",
|
||||
"edit_dialog_title": "Edit article",
|
||||
"viewer_disabled_tooltip": "You only have viewer access in this company",
|
||||
"type_vara": "Goods",
|
||||
"type_tjanst": "Service",
|
||||
"status_active": "Active",
|
||||
"status_inactive": "Inactive",
|
||||
"section_pricing": "Pricing",
|
||||
"section_accounting": "Accounting",
|
||||
"section_details": "Details",
|
||||
"section_notes": "Notes",
|
||||
"label_price": "Price excl. VAT",
|
||||
"label_vat": "VAT",
|
||||
"label_unit": "Unit",
|
||||
"label_cost_price": "Cost price",
|
||||
"label_revenue_account": "Revenue account",
|
||||
"revenue_account_auto": "Derived automatically",
|
||||
"label_housework": "ROT/RUT",
|
||||
"label_name_en": "Name (English)",
|
||||
"label_ean": "EAN/barcode",
|
||||
"no_details": "No additional details",
|
||||
"load_failed_title": "Could not load article",
|
||||
"load_failed_description": "Article not found.",
|
||||
"updated_title": "Article updated",
|
||||
"update_failed_title": "Could not update article",
|
||||
"retry": "Please try again.",
|
||||
"deactivate_confirm_title": "Deactivate {name}",
|
||||
"deactivate_confirm_description": "The article is hidden from lists and invoice pickers but its history is kept. You can reactivate it later.",
|
||||
"deactivate_confirm_label": "Deactivate",
|
||||
"deactivated_title": "Article deactivated",
|
||||
"deactivate_failed_title": "Could not deactivate article"
|
||||
},
|
||||
"form_article": {
|
||||
"type_label": "Type *",
|
||||
"type_placeholder": "Choose type",
|
||||
"type_vara": "Goods",
|
||||
"type_tjanst": "Service",
|
||||
"name_label": "Name *",
|
||||
"name_placeholder": "E.g. Consulting hour",
|
||||
"name_required": "Name is required",
|
||||
"name_en_label": "Name (English)",
|
||||
"name_en_placeholder": "E.g. Consulting hour",
|
||||
"name_en_hint": "Used on English-language invoices.",
|
||||
"unit_label": "Unit",
|
||||
"price_label": "Price excl. VAT *",
|
||||
"price_required": "Enter a price",
|
||||
"vat_rate_label": "VAT",
|
||||
"advanced_section": "Advanced",
|
||||
"revenue_account_label": "Revenue account",
|
||||
"revenue_account_placeholder": "e.g. 3041",
|
||||
"revenue_account_hint": "Leave empty to derive the account automatically from the VAT rate.",
|
||||
"cost_price_label": "Cost price",
|
||||
"cost_price_hint": "Margin display only – never posted.",
|
||||
"ean_label": "EAN/barcode",
|
||||
"ean_placeholder": "e.g. 7350000000000",
|
||||
"housework_label": "ROT/RUT",
|
||||
"housework_placeholder": "Choose work type",
|
||||
"housework_none": "None",
|
||||
"housework_rot": "ROT",
|
||||
"housework_rut": "RUT",
|
||||
"housework_hint": "Pre-fills the work type on the invoice row for housework.",
|
||||
"notes_label": "Notes",
|
||||
"notes_placeholder": "Internal notes about the article...",
|
||||
"submit_save": "Save article",
|
||||
"submit_saving": "Saving...",
|
||||
"viewer_disabled_tooltip": "You only have viewer access in this company"
|
||||
},
|
||||
"customers": {
|
||||
"title": "Customers",
|
||||
"new_customer": "New customer",
|
||||
|
||||
@@ -71,6 +71,7 @@
|
||||
"invoices": "Fakturor",
|
||||
"sales_orders": "Order",
|
||||
"customers": "Kunder",
|
||||
"articles": "Artiklar",
|
||||
"products": "Produkter",
|
||||
"inventory": "Lager",
|
||||
"supplier_invoices": "Leverantörsfakturor",
|
||||
@@ -2057,6 +2058,13 @@
|
||||
},
|
||||
"invoice_editor": {
|
||||
"back": "Tillbaka",
|
||||
"article_label": "Artikel",
|
||||
"article_placeholder": "Välj artikel",
|
||||
"article_free_text": "Egen rad (fri text)",
|
||||
"save_as_article": "Spara som artikel",
|
||||
"save_article_need_description": "Fyll i en beskrivning innan du sparar som artikel",
|
||||
"article_saved_title": "Artikel sparad",
|
||||
"save_article_failed": "Kunde inte spara artikeln",
|
||||
"title_invoice": "Ny faktura",
|
||||
"title_proforma": "Ny proformafaktura",
|
||||
"title_delivery_note": "Ny följesedel",
|
||||
@@ -3460,6 +3468,106 @@
|
||||
"copy_banner_unknown_label": "(okänt nummer)",
|
||||
"copy_banner_body": "Ett nytt, fristående verifikat skapas med egen verifikationsserie och nummer. Detta är inte en rättelse eller storno av originalet — använd \"Skapa ändringsverifikation\" om du vill korrigera källverifikatet."
|
||||
},
|
||||
"articles": {
|
||||
"title": "Artiklar",
|
||||
"new_article": "Ny artikel",
|
||||
"add_article": "Lägg till artikel",
|
||||
"viewer_disabled_tooltip": "Du har endast läsbehörighet i detta företag",
|
||||
"load_failed_title": "Kunde inte ladda artiklar",
|
||||
"load_failed_description": "Kontrollera din anslutning och försök igen.",
|
||||
"create_failed_title": "Kunde inte skapa artikel",
|
||||
"created_title": "Artikel skapad",
|
||||
"created_description": "{name} har lagts till",
|
||||
"search_placeholder": "Sök artiklar",
|
||||
"no_search_results_title": "Inga träffar",
|
||||
"no_search_results_description": "Inga artiklar matchar \"{term}\".",
|
||||
"empty_title": "Inga artiklar ännu",
|
||||
"empty_description": "Lägg till artiklar för varor och tjänster för att snabbt fylla i fakturarader.",
|
||||
"empty_action": "Lägg till artikel",
|
||||
"type_vara": "Vara",
|
||||
"type_tjanst": "Tjänst",
|
||||
"status_active": "Aktiv",
|
||||
"status_inactive": "Inaktiv",
|
||||
"per_unit": "per {unit}",
|
||||
"vat_label_value": "{rate} % moms",
|
||||
"col_number": "Artikelnummer",
|
||||
"col_name": "Benämning",
|
||||
"col_type": "Typ",
|
||||
"col_unit": "Enhet",
|
||||
"col_price": "Pris exkl. moms",
|
||||
"col_vat": "Moms",
|
||||
"col_status": "Status"
|
||||
},
|
||||
"article_detail": {
|
||||
"back": "Tillbaka till artiklar",
|
||||
"edit": "Redigera",
|
||||
"deactivate": "Inaktivera",
|
||||
"edit_dialog_title": "Redigera artikel",
|
||||
"viewer_disabled_tooltip": "Du har endast läsbehörighet i detta företag",
|
||||
"type_vara": "Vara",
|
||||
"type_tjanst": "Tjänst",
|
||||
"status_active": "Aktiv",
|
||||
"status_inactive": "Inaktiv",
|
||||
"section_pricing": "Pris",
|
||||
"section_accounting": "Bokföring",
|
||||
"section_details": "Detaljer",
|
||||
"section_notes": "Anteckningar",
|
||||
"label_price": "Pris exkl. moms",
|
||||
"label_vat": "Moms",
|
||||
"label_unit": "Enhet",
|
||||
"label_cost_price": "Inköpspris",
|
||||
"label_revenue_account": "Försäljningskonto",
|
||||
"revenue_account_auto": "Härleds automatiskt",
|
||||
"label_housework": "ROT/RUT",
|
||||
"label_name_en": "Benämning (engelska)",
|
||||
"label_ean": "EAN/streckkod",
|
||||
"no_details": "Inga ytterligare detaljer",
|
||||
"load_failed_title": "Kunde inte ladda artikel",
|
||||
"load_failed_description": "Artikeln hittades inte.",
|
||||
"updated_title": "Artikel uppdaterad",
|
||||
"update_failed_title": "Kunde inte uppdatera artikel",
|
||||
"retry": "Försök igen.",
|
||||
"deactivate_confirm_title": "Inaktivera {name}",
|
||||
"deactivate_confirm_description": "Artikeln döljs i listor och fakturaval men historiken bevaras. Du kan aktivera den igen senare.",
|
||||
"deactivate_confirm_label": "Inaktivera",
|
||||
"deactivated_title": "Artikel inaktiverad",
|
||||
"deactivate_failed_title": "Kunde inte inaktivera artikel"
|
||||
},
|
||||
"form_article": {
|
||||
"type_label": "Typ *",
|
||||
"type_placeholder": "Välj typ",
|
||||
"type_vara": "Vara",
|
||||
"type_tjanst": "Tjänst",
|
||||
"name_label": "Benämning *",
|
||||
"name_placeholder": "T.ex. Konsulttimme",
|
||||
"name_required": "Benämning krävs",
|
||||
"name_en_label": "Benämning (engelska)",
|
||||
"name_en_placeholder": "T.ex. Consulting hour",
|
||||
"name_en_hint": "Används på fakturor med engelskt språk.",
|
||||
"unit_label": "Enhet",
|
||||
"price_label": "Pris exkl. moms *",
|
||||
"price_required": "Ange ett pris",
|
||||
"vat_rate_label": "Moms",
|
||||
"advanced_section": "Avancerat",
|
||||
"revenue_account_label": "Försäljningskonto",
|
||||
"revenue_account_placeholder": "t.ex. 3041",
|
||||
"revenue_account_hint": "Lämna tomt för att härleda kontot automatiskt utifrån momsen.",
|
||||
"cost_price_label": "Inköpspris",
|
||||
"cost_price_hint": "Endast för marginalberäkning – bokförs aldrig.",
|
||||
"ean_label": "EAN/streckkod",
|
||||
"ean_placeholder": "t.ex. 7350000000000",
|
||||
"housework_label": "ROT/RUT",
|
||||
"housework_placeholder": "Välj arbetstyp",
|
||||
"housework_none": "Ingen",
|
||||
"housework_rot": "ROT",
|
||||
"housework_rut": "RUT",
|
||||
"housework_hint": "Förifyller arbetstyp på fakturaraden för husarbete.",
|
||||
"notes_label": "Anteckningar",
|
||||
"notes_placeholder": "Interna anteckningar om artikeln...",
|
||||
"submit_save": "Spara artikel",
|
||||
"submit_saving": "Sparar...",
|
||||
"viewer_disabled_tooltip": "Du har endast läsbehörighet i detta företag"
|
||||
},
|
||||
"customers": {
|
||||
"title": "Kunder",
|
||||
"new_customer": "Ny kund",
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
-- Artikelregister (product/article catalog) — app-level master data.
|
||||
--
|
||||
-- A lean, NON-INVENTORY article register modeled on the multi-tenant customers
|
||||
-- pattern. Articles are reusable invoice-line presets: name, unit, price excl
|
||||
-- VAT, VAT rate, and an optional revenue-account override. There is deliberately
|
||||
-- NO stock/lager column and NO inventory posting — a scope boundary matching our
|
||||
-- sole-trader + small-AB positioning (see the artikelregister plan). Articles are
|
||||
-- master data, not a journal, so they carry no BFL sequence/immutability
|
||||
-- obligation. The booking is frozen onto invoice_items at line-create time, so
|
||||
-- editing or deactivating an article never moves a posted voucher.
|
||||
|
||||
-- =============================================================================
|
||||
-- 1. articles
|
||||
-- =============================================================================
|
||||
CREATE TABLE public.articles (
|
||||
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
|
||||
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
|
||||
article_number text,
|
||||
name text NOT NULL,
|
||||
name_en text,
|
||||
type text NOT NULL DEFAULT 'tjanst' CHECK (type IN ('vara', 'tjanst')),
|
||||
unit text NOT NULL DEFAULT 'st',
|
||||
price_excl_vat numeric NOT NULL DEFAULT 0,
|
||||
vat_rate integer NOT NULL DEFAULT 25 CHECK (vat_rate IN (0, 6, 12, 25)),
|
||||
revenue_account text, -- optional BAS class-3 override; NULL = derive from VAT treatment
|
||||
cost_price numeric, -- margin/display only; never posted to the ledger
|
||||
ean text,
|
||||
housework_type text, -- ROT/RUT arbetstyp (tjanst only); pre-fills the invoice line
|
||||
notes text,
|
||||
active boolean NOT NULL DEFAULT true,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
ALTER TABLE public.articles ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
CREATE POLICY "view own-company articles"
|
||||
ON public.articles FOR SELECT USING (company_id IN (SELECT user_company_ids()));
|
||||
CREATE POLICY "insert own-company articles"
|
||||
ON public.articles FOR INSERT WITH CHECK (company_id IN (SELECT user_company_ids()));
|
||||
CREATE POLICY "update own-company articles"
|
||||
ON public.articles FOR UPDATE USING (company_id IN (SELECT user_company_ids()));
|
||||
CREATE POLICY "delete own-company articles"
|
||||
ON public.articles FOR DELETE USING (company_id IN (SELECT user_company_ids()));
|
||||
|
||||
CREATE INDEX idx_articles_company_id ON public.articles (company_id);
|
||||
-- Active-only list/search is the hot path; keep it covered without scanning archived rows.
|
||||
CREATE INDEX idx_articles_company_active ON public.articles (company_id, name) WHERE active;
|
||||
-- Article number is the import/lookup key; unique per company when present.
|
||||
CREATE UNIQUE INDEX uq_articles_company_number
|
||||
ON public.articles (company_id, article_number) WHERE article_number IS NOT NULL;
|
||||
|
||||
CREATE TRIGGER set_updated_at_articles
|
||||
BEFORE UPDATE ON public.articles
|
||||
FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();
|
||||
|
||||
CREATE TRIGGER audit_articles
|
||||
AFTER INSERT OR UPDATE OR DELETE ON public.articles
|
||||
FOR EACH ROW EXECUTE FUNCTION public.write_audit_log();
|
||||
|
||||
-- =============================================================================
|
||||
-- 2. company_settings.next_article_number — per-company auto-number counter
|
||||
-- =============================================================================
|
||||
ALTER TABLE public.company_settings
|
||||
ADD COLUMN IF NOT EXISTS next_article_number integer NOT NULL DEFAULT 1;
|
||||
|
||||
-- =============================================================================
|
||||
-- 3. generate_article_number RPC — atomic + idempotent
|
||||
-- (mirrors generate_invoice_number: row lock, idempotent return, atomic
|
||||
-- counter via UPDATE ... RETURNING). Article numbers are master data, so a
|
||||
-- gap from a manual override colliding with the counter is harmless.
|
||||
-- =============================================================================
|
||||
CREATE OR REPLACE FUNCTION public.generate_article_number(
|
||||
p_company_id uuid,
|
||||
p_article_id uuid
|
||||
)
|
||||
RETURNS text
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path TO 'public'
|
||||
AS $function$
|
||||
DECLARE
|
||||
v_existing text;
|
||||
v_number integer;
|
||||
v_final text;
|
||||
BEGIN
|
||||
-- 1. Lock the article row; concurrent callers serialize here and, on retry,
|
||||
-- see the persisted number.
|
||||
SELECT article_number INTO v_existing
|
||||
FROM public.articles
|
||||
WHERE id = p_article_id AND company_id = p_company_id
|
||||
FOR UPDATE;
|
||||
|
||||
IF NOT FOUND THEN
|
||||
RAISE EXCEPTION 'Article % not found in company %', p_article_id, p_company_id;
|
||||
END IF;
|
||||
|
||||
-- 2. Idempotent: keep an already-assigned number; never consume a sequence twice.
|
||||
IF v_existing IS NOT NULL THEN
|
||||
RETURN v_existing;
|
||||
END IF;
|
||||
|
||||
-- 3. Allocate from the per-company counter atomically.
|
||||
UPDATE public.company_settings
|
||||
SET next_article_number = next_article_number + 1,
|
||||
updated_at = now()
|
||||
WHERE company_id = p_company_id
|
||||
RETURNING next_article_number - 1
|
||||
INTO v_number;
|
||||
|
||||
IF v_number IS NULL THEN
|
||||
RAISE EXCEPTION 'Company settings not found for company %', p_company_id;
|
||||
END IF;
|
||||
|
||||
-- 4. Plain sequential number as text. Master data: no year prefix, no padding.
|
||||
v_final := v_number::text;
|
||||
|
||||
-- 5. Persist on the article row in the same transaction.
|
||||
UPDATE public.articles
|
||||
SET article_number = v_final
|
||||
WHERE id = p_article_id AND company_id = p_company_id;
|
||||
|
||||
RETURN v_final;
|
||||
END;
|
||||
$function$;
|
||||
|
||||
-- =============================================================================
|
||||
-- 4. invoice_items: per-line revenue-account override + article back-reference
|
||||
-- =============================================================================
|
||||
-- revenue_account is COPIED from the article at line-create time (frozen), so a
|
||||
-- later article edit never moves a posted voucher. NULL preserves the existing
|
||||
-- "derive the revenue account from the VAT treatment" behaviour in
|
||||
-- generatePerRateLines(). article_id is a soft back-reference for the future
|
||||
-- "Affärshändelser" tab; ON DELETE SET NULL keeps frozen line values intact if
|
||||
-- the article is ever hard-deleted.
|
||||
ALTER TABLE public.invoice_items
|
||||
ADD COLUMN IF NOT EXISTS revenue_account text;
|
||||
ALTER TABLE public.invoice_items
|
||||
ADD COLUMN IF NOT EXISTS article_id uuid REFERENCES public.articles(id) ON DELETE SET NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_invoice_items_article_id ON public.invoice_items (article_id);
|
||||
|
||||
NOTIFY pgrst, 'reload schema';
|
||||
@@ -0,0 +1,61 @@
|
||||
-- Add 'create_article' and 'update_article' to the pending_operations
|
||||
-- operation_type CHECK constraint.
|
||||
--
|
||||
-- The artikelregister MCP tools (gnubok_create_article / gnubok_update_article)
|
||||
-- stage a pending operation that, on approval, dispatches into commitCreateArticle
|
||||
-- / commitUpdateArticle. Without this expansion the staged INSERT would be
|
||||
-- rejected by the constraint before the commit-side code ever runs, blocking the
|
||||
-- staged-operation review flow — mirrors create_customer / create_supplier.
|
||||
--
|
||||
-- pg-test: covered-by — CHECK-list expansion only (no trigger/RPC/RLS/DEFERRABLE
|
||||
-- change), so no *.pg.test.ts is required.
|
||||
|
||||
ALTER TABLE public.pending_operations
|
||||
DROP CONSTRAINT IF EXISTS pending_operations_operation_type_check;
|
||||
|
||||
ALTER TABLE public.pending_operations
|
||||
ADD CONSTRAINT pending_operations_operation_type_check
|
||||
CHECK (operation_type IN (
|
||||
'categorize_transaction',
|
||||
'create_customer',
|
||||
'create_invoice',
|
||||
'mark_invoice_paid',
|
||||
'send_invoice',
|
||||
'mark_invoice_sent',
|
||||
'match_transaction_invoice',
|
||||
'close_period',
|
||||
'lock_period',
|
||||
'unlock_period',
|
||||
'set_opening_balances',
|
||||
'run_year_end',
|
||||
'run_currency_revaluation',
|
||||
'import_sie',
|
||||
'explain_voucher_gap',
|
||||
'uncategorize_transaction',
|
||||
'approve_supplier_invoice',
|
||||
'credit_supplier_invoice',
|
||||
'credit_invoice',
|
||||
'convert_invoice',
|
||||
'create_transaction',
|
||||
'attach_document_to_transaction',
|
||||
'create_voucher',
|
||||
'correct_entry',
|
||||
'reverse_entry',
|
||||
'create_supplier',
|
||||
'create_supplier_invoice_from_inbox',
|
||||
'post_annual_depreciation',
|
||||
'link_invoice_voucher',
|
||||
'undo_sie_import',
|
||||
'match_batch_allocate',
|
||||
'bulk_book_transactions',
|
||||
'create_salary_run',
|
||||
'generate_agi',
|
||||
'link_transaction_journal_entry',
|
||||
'link_supplier_invoice_voucher',
|
||||
'submit_vat_declaration',
|
||||
'submit_agi',
|
||||
'create_article', -- artikelregister: stage a new catalog article
|
||||
'update_article' -- artikelregister: stage an edit / deactivate
|
||||
));
|
||||
|
||||
NOTIFY pgrst, 'reload schema';
|
||||
@@ -0,0 +1,150 @@
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -580,6 +580,57 @@ export interface Supplier {
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
// Article (artikelregister) — reusable invoice-line preset. NON-INVENTORY:
|
||||
// no stock fields and no inventory postings, by deliberate design.
|
||||
export type ArticleType = 'vara' | 'tjanst'
|
||||
|
||||
export interface Article {
|
||||
id: string
|
||||
company_id: string
|
||||
user_id: string
|
||||
|
||||
/** Auto-numbered per company (generate_article_number RPC); user-overridable. */
|
||||
article_number: string | null
|
||||
name: string
|
||||
/** English benämning for English-language invoices. */
|
||||
name_en: string | null
|
||||
type: ArticleType
|
||||
unit: string
|
||||
/** Always stored EXCLUDING VAT. */
|
||||
price_excl_vat: number
|
||||
/** Default line VAT rate as an integer percent: 25 | 12 | 6 | 0. */
|
||||
vat_rate: number
|
||||
/** Optional BAS class-3 revenue account override. null = derive from VAT treatment. */
|
||||
revenue_account: string | null
|
||||
/** Margin/display only — never posted to the ledger. */
|
||||
cost_price: number | null
|
||||
ean: string | null
|
||||
/** ROT/RUT arbetstypskod (tjänst only); pre-fills the invoice line. */
|
||||
housework_type: string | null
|
||||
notes: string | null
|
||||
/** Soft-delete flag. Inactive articles are hidden from pickers but keep history. */
|
||||
active: boolean
|
||||
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface CreateArticleInput {
|
||||
name: string
|
||||
type?: ArticleType
|
||||
unit?: string
|
||||
price_excl_vat: number
|
||||
vat_rate?: number
|
||||
revenue_account?: string | null
|
||||
cost_price?: number | null
|
||||
ean?: string | null
|
||||
housework_type?: string | null
|
||||
name_en?: string | null
|
||||
notes?: string | null
|
||||
/** Optional manual article number; omit to auto-generate. */
|
||||
article_number?: string | null
|
||||
}
|
||||
|
||||
// Supplier Invoice
|
||||
export interface SupplierInvoice {
|
||||
id: string
|
||||
@@ -826,6 +877,14 @@ export interface InvoiceItem {
|
||||
vat_rate: number
|
||||
vat_amount: number
|
||||
|
||||
// Article linkage. `article_id` is a soft back-reference to the source
|
||||
// article (for the "Affärshändelser" history view); `revenue_account` is the
|
||||
// BAS class-3 account frozen-copied from the article at line-create time.
|
||||
// null `revenue_account` preserves the legacy "derive from VAT treatment"
|
||||
// booking in generatePerRateLines().
|
||||
article_id?: string | null
|
||||
revenue_account?: string | null
|
||||
|
||||
// ROT/RUT-avdrag (Sweden's tax deduction for household services / home
|
||||
// renovation). When `deduction_type` is set, the system computes
|
||||
// `deduction_amount` from the rules in lib/invoices/rot-rut-rules.ts
|
||||
@@ -1019,6 +1078,10 @@ export interface CreateInvoiceItemInput {
|
||||
unit: string
|
||||
unit_price: number
|
||||
vat_rate?: number
|
||||
/** Source article (optional). Free-text lines omit it. */
|
||||
article_id?: string | null
|
||||
/** BAS class-3 revenue account override copied from the article. null = derive from VAT treatment. */
|
||||
revenue_account?: string | null
|
||||
/** ROT/RUT toggle. null/undefined = no deduction. */
|
||||
deduction_type?: 'rot' | 'rut' | null
|
||||
labor_hours?: number | null
|
||||
@@ -1552,6 +1615,8 @@ export interface CreateFiscalPeriodInput {
|
||||
export type PendingOperationType =
|
||||
| 'categorize_transaction'
|
||||
| 'create_customer'
|
||||
| 'create_article'
|
||||
| 'update_article'
|
||||
| 'create_supplier'
|
||||
| 'create_invoice'
|
||||
| 'mark_invoice_paid'
|
||||
|
||||
Reference in New Issue
Block a user