Files
accounted/app/api/bookkeeping/accounts/route.ts
T
MattssonandClaude Opus 4.8 bacc5914af Fix/dependabot cus feedback (#946)
* feat(bookkeeping): per-account default VAT, oresavrundning momsfri

Add a per-account "Standard moms" setting to the chart of accounts and use
it to auto-fill the moms on a leverantorsfaktura-rad when that konto is
picked. Oresavrundning (3740) ships as "Ingen moms", so a rounding line no
longer inherits the 25 % rad-default and skews the moms.

- chart_of_accounts.default_vat_rate (0/0.06/0.12/0.25, CHECK-constrained)
- BEFORE INSERT trigger ships 3740 momsfri on every insert path; backfills
  existing 3740 rows
- kontoplan editor: dead free-text momskod replaced with a Standard moms select
- supplier-invoice rad auto-fills the rate from the konto default

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

* feat(supplier-invoices): configurable start number for the ankomstnummer series

Add a company_settings.next_arrival_number start floor so a company can continue its leverantorsfaktura numbering from a previous system (e.g. Fortnox) instead of restarting the ankomstnummer at 1. get_next_arrival_number now floors the series via GREATEST(MAX(arrival_number)+1, next_arrival_number), so the floor can never move the series backwards or collide with the (company_id, arrival_number) unique index.

The RPC is hardened while rewritten: SET search_path to empty, schema-qualified refs, and an auth.uid() membership check matching generate_invoice_number.

Includes the settings UI field, sv/en strings, migration, and pg-real coverage. The CompanySettings type and Zod schema field for this feature landed earlier in 1bf3b641 (swept into the per-account VAT commit).

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

* fix(dependabot): reduce open pull requests limit and group updates for better management

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 12:19:57 +02:00

103 lines
3.2 KiB
TypeScript

import { NextResponse } from 'next/server'
import { z } from 'zod'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody, validateQuery } from '@/lib/api/validate'
import { CreateAccountSchema } from '@/lib/api/schemas'
// Response shapes are legacy `{ data }` / `{ error: string }` — several pages
// (import, supplier-invoices, article form) consume the list directly.
const ListQuerySchema = z.object({
class: z.coerce.number().int().min(1).max(8).optional(),
active: z.enum(['true', 'false']).optional(),
})
export const GET = withRouteContext('bookkeeping.accounts.list', async (request, ctx) => {
const { supabase, companyId, log } = ctx
const validated = validateQuery(request, ListQuerySchema, {
log,
operation: 'bookkeeping.accounts.list',
})
if (!validated.success) return validated.response
const accountClass = validated.data.class
const activeOnly = validated.data.active !== 'false'
try {
const data = await fetchAllRows(({ from, to }) => {
let query = supabase
.from('chart_of_accounts')
.select('*')
.eq('company_id', companyId)
.order('sort_order')
if (activeOnly) {
query = query.eq('is_active', true)
}
if (accountClass !== undefined) {
query = query.eq('account_class', accountClass)
}
return query.range(from, to)
})
return NextResponse.json({ data })
} catch (error) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : 'Failed to fetch accounts' },
{ status: 500 },
)
}
})
export const POST = withRouteContext(
'bookkeeping.accounts.create',
async (request, ctx) => {
const { supabase, companyId, user, log } = ctx
const validation = await validateBody(request, CreateAccountSchema, {
log,
operation: 'bookkeeping.accounts.create',
})
if (!validation.success) return validation.response
const body = validation.data
const { data, error } = await supabase
.from('chart_of_accounts')
.insert({
user_id: user.id,
company_id: companyId,
account_number: body.account_number,
account_name: body.account_name,
account_class: parseInt(body.account_number[0]),
account_group: body.account_number.substring(0, 2),
account_type: body.account_type,
normal_balance: body.normal_balance,
plan_type: body.plan_type || 'k1',
is_system_account: false,
description: body.description || null,
default_vat_code: body.default_vat_code || null,
default_vat_rate: body.default_vat_rate ?? null,
sru_code: body.sru_code || null,
sort_order: parseInt(body.account_number),
})
.select()
.single()
if (error) {
if (error.code === '23505') {
return NextResponse.json(
{ error: `Kontonummer ${body.account_number} finns redan i din kontoplan.` },
{ status: 409 },
)
}
return NextResponse.json({ error: error.message }, { status: 500 })
}
return NextResponse.json({ data })
},
{ requireWrite: true },
)