* feat: copy voucher, MRU booking templates, and PDF export for reports - Add "Kopiera verifikat" action on the journal-entry detail page that prefills a new draft with the source entry's lines, description, and notes. Date defaults to today so locked-period posts can't happen by accident; source_type resets to manual. - Track per-company MRU for booking_template_library rows via a new booking_template_usage table (fire-and-forget touch endpoint hooked into both pickers) and sort the list most-recently-used first for the active company. - Generate downloadable PDFs for balansräkning and resultaträkning using the existing @react-pdf/renderer toolchain. Adds a reusable parameterized template and two API routes, with download buttons on the matching report views. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: address PR review feedback on copy-voucher + report PDFs Compliance review (Swedish accounting): - Balance-sheet PDF now refuses to render when tillgångar ≠ eget kapital och skulder; the stale "Differens" summary row is gone. The on-screen view still surfaces the existing "Balanserar ej" warning so users can diagnose the imbalance before downloading. ÅRL 3 kap / K2 / K3 require exact balance. - Both PDF routes now 400 when the requested fiscal period cannot be resolved — identifiable period is part of räkenskapsinformation under BFL 7 kap. - Income-statement PDF adds the mandatory "Resultat efter finansiella poster" subtotal when financial items are present, per K2/K3 uppställningsform (ÅRL bilaga 2). - Copy-voucher flow now shows a clear banner ("Kopia av verifikat X — nytt, fristående verifikat skapas") so users cannot mistake the copy for a rättelse/storno. Code review (Greptile): - New migration adds updated_at column + trigger to booking_template_usage (project convention; applied to the Supabase project). - Replace localeCompare on ISO timestamps with plain relational comparison to avoid any locale-dependent ordering. - UUID-format validation on the copy_from query param before it goes into the fetch URL. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: second round of Swedish compliance fixes on report PDFs - Balance-sheet PDF imbalance check now compares rounded-to-whole-kronor totals (SFL 22:1 convention). The previous 0.5-öre tolerance could reject a legitimate balance sheet when accumulated floating-point noise across hundreds of ledger lines exceeded the threshold. The on-screen view still surfaces the öre-precise "Balanserar ej" badge for diagnostic visibility. - Both PDFs now carry a prominent "Arbetsutkast — ej undertecknat" notice per ÅRL 2 kap 7 §. Prevents a downloaded PDF from being mistaken for or filed as an approved årsredovisning. - Income-statement PDF now follows K2/K3 uppställningsform (ÅRL bilaga 2) by splitting class 8 into three blocks with named subtotals: Finansiella poster (80–84), Bokslutsdispositioner (88), Skatter (89). The summary now always shows a "Skatt på årets resultat" row so the reader can verify the tax calculation, and adds "Resultat efter finansiella poster" / "Bokslutsdispositioner" subtotals when each block is present. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: harden report PDFs against out-of-band filing + future BAS growth - Append "-utkast" to downloaded PDF filenames. The filename survives the PDF's disclaimer context — a file named balansrakning-2026-01-01.pdf in a Downloads folder or forwarded attachment is ambiguous, whereas balansrakning-2026-01-01-utkast.pdf makes the draft status legible even without opening the document. - Add a catch-all "Övriga finansiella poster" bucket in the income-statement PDF for any class-8 section whose account prefix isn't one of the known K2/K3 blocks (80–84 / 88 / 89). Counted in the "Resultat efter finansiella poster" subtotal so arithmetic stays consistent. Future-proofs the PDF against a generator change that starts emitting 85–87 sections. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
167 lines
5.5 KiB
TypeScript
167 lines
5.5 KiB
TypeScript
import { createClient } from '@/lib/supabase/server'
|
|
import { NextResponse } from 'next/server'
|
|
import { requireCompanyId } from '@/lib/company/context'
|
|
import { requireWritePermission } from '@/lib/auth/require-write'
|
|
import { z } from 'zod'
|
|
import { validateBody } from '@/lib/api/validate'
|
|
|
|
const BookingTemplateLineSchema = z.object({
|
|
account: z.string().regex(/^\d{4}$/),
|
|
label: z.string().min(1),
|
|
side: z.enum(['debit', 'credit']),
|
|
type: z.enum(['business', 'vat', 'settlement']),
|
|
ratio: z.number().min(0).max(10).optional(),
|
|
vat_rate: z.number().min(0).max(1).optional(),
|
|
})
|
|
|
|
const CreateBookingTemplateSchema = z.object({
|
|
name: z.string().min(1).max(200),
|
|
description: z.string().max(2000).default(''),
|
|
category: z.enum([
|
|
'eu_trade', 'tax_account', 'private_transfer',
|
|
'salary', 'representation', 'year_end',
|
|
'vat', 'financial', 'other',
|
|
]).default('other'),
|
|
entity_type: z.enum(['all', 'enskild_firma', 'aktiebolag']).default('all'),
|
|
lines: z.array(BookingTemplateLineSchema).min(2),
|
|
team_id: z.string().uuid().optional(),
|
|
})
|
|
|
|
/**
|
|
* GET /api/settings/booking-templates
|
|
* Returns all templates visible to the current user:
|
|
* system + company + team templates.
|
|
*
|
|
* Ordering: most recently used (per current company) first, then by category
|
|
* and name for never-used templates. Usage is tracked in
|
|
* booking_template_usage via POST /[id]/touch.
|
|
*/
|
|
export async function GET() {
|
|
const supabase = await createClient()
|
|
const { data: { user } } = await supabase.auth.getUser()
|
|
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
|
|
const companyId = await requireCompanyId(supabase, user.id)
|
|
|
|
// RLS handles scoping (system OR company OR team)
|
|
const [templatesRes, usageRes] = await Promise.all([
|
|
supabase
|
|
.from('booking_template_library')
|
|
.select('*')
|
|
.eq('is_active', true)
|
|
.order('category')
|
|
.order('name'),
|
|
supabase
|
|
.from('booking_template_usage')
|
|
.select('template_id, last_used_at')
|
|
.eq('company_id', companyId),
|
|
])
|
|
|
|
if (templatesRes.error) {
|
|
return NextResponse.json({ error: templatesRes.error.message }, { status: 500 })
|
|
}
|
|
// usage lookup failing is non-fatal — we just fall back to default ordering
|
|
const usageByTemplate = new Map<string, string>()
|
|
if (!usageRes.error && usageRes.data) {
|
|
for (const row of usageRes.data) {
|
|
usageByTemplate.set(row.template_id, row.last_used_at)
|
|
}
|
|
}
|
|
|
|
const templates = templatesRes.data ?? []
|
|
const decorated = templates.map((t) => ({
|
|
...t,
|
|
last_used_at: usageByTemplate.get(t.id) ?? null,
|
|
}))
|
|
|
|
// Stable-sort: templates with last_used_at come first (most-recent first).
|
|
// Templates without usage keep their category/name order from the query.
|
|
// ISO 8601 timestamps are fixed-width ASCII — plain relational comparison
|
|
// is correct and avoids any locale-dependent behaviour from localeCompare.
|
|
decorated.sort((a, b) => {
|
|
const aUsed = a.last_used_at
|
|
const bUsed = b.last_used_at
|
|
if (aUsed && bUsed) {
|
|
if (bUsed > aUsed) return -1
|
|
if (bUsed < aUsed) return 1
|
|
return 0
|
|
}
|
|
if (aUsed) return -1
|
|
if (bUsed) return 1
|
|
return 0
|
|
})
|
|
|
|
return NextResponse.json({ data: decorated })
|
|
}
|
|
|
|
/**
|
|
* POST /api/settings/booking-templates
|
|
* Create a company-scoped or team-scoped template.
|
|
*/
|
|
export async function POST(request: Request) {
|
|
const supabase = await createClient()
|
|
const { data: { user } } = await supabase.auth.getUser()
|
|
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
|
|
const writeCheck = await requireWritePermission(supabase, user.id)
|
|
if (!writeCheck.ok) return writeCheck.response
|
|
|
|
const result = await validateBody(request, CreateBookingTemplateSchema)
|
|
if (!result.success) return result.response
|
|
|
|
const body = result.data
|
|
const companyId = body.team_id ? null : await requireCompanyId(supabase, user.id)
|
|
|
|
const { data, error } = await supabase
|
|
.from('booking_template_library')
|
|
.insert({
|
|
company_id: companyId,
|
|
team_id: body.team_id ?? null,
|
|
created_by: user.id,
|
|
name: body.name,
|
|
description: body.description,
|
|
category: body.category,
|
|
entity_type: body.entity_type,
|
|
lines: body.lines,
|
|
is_system: false,
|
|
})
|
|
.select()
|
|
.single()
|
|
|
|
if (error) return NextResponse.json({ error: error.message }, { status: 500 })
|
|
|
|
return NextResponse.json({ data }, { status: 201 })
|
|
}
|
|
|
|
/**
|
|
* DELETE /api/settings/booking-templates
|
|
* Soft-delete a template by id (company or team scope only, never system).
|
|
*/
|
|
export async function DELETE(request: Request) {
|
|
const supabase = await createClient()
|
|
const { data: { user } } = await supabase.auth.getUser()
|
|
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
|
|
const writeCheck = await requireWritePermission(supabase, user.id)
|
|
if (!writeCheck.ok) return writeCheck.response
|
|
|
|
let id: string | undefined
|
|
try {
|
|
const body = await request.json()
|
|
id = body?.id
|
|
} catch {
|
|
return NextResponse.json({ error: 'Invalid request body' }, { status: 400 })
|
|
}
|
|
if (!id) return NextResponse.json({ error: 'Missing id' }, { status: 400 })
|
|
|
|
// RLS prevents deleting system templates (btl_delete policy checks NOT is_system)
|
|
const { error } = await supabase
|
|
.from('booking_template_library')
|
|
.update({ is_active: false })
|
|
.eq('id', id)
|
|
|
|
if (error) return NextResponse.json({ error: error.message }, { status: 500 })
|
|
|
|
return NextResponse.json({ data: { success: true } })
|
|
}
|