feat: booking template library with system templates and cross-company sharing (#235)
* feat: implement viewer role permissions for bank transaction imports and connections * feat: add booking_template_library table with 30 system templates Three-level scoping (system/team/company), RLS policies for read/write/delete, and pre-seeded templates for EU reverse charge, tax account, private transfers, salary, representation, year-end, VAT netting, and bank/finance scenarios. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add template library types, helpers, and tests - BookingTemplateLibrary/Line/Category types in types/index.ts - applyTemplate() converts template lines + amount into form lines - Category labels, scope helpers for UI display - 8 unit tests for amount calculation, VAT, rounding, and scope detection Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add booking template CRUD, export, and import API routes - GET/POST/DELETE /api/settings/booking-templates (list, create, soft-delete) - PUT /api/settings/booking-templates/[id] (update non-system templates) - GET /api/settings/booking-templates/export (JSON download) - POST /api/settings/booking-templates/import (bulk import from JSON) All routes enforce auth, write permissions, and Zod validation. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add template picker UI and settings management panel - BookingTemplatePicker: dialog with search, category/entity-type filter, line preview, and amount input — integrated into JournalEntryForm - BookingTemplatesPanel: settings page with grouped templates (system/team/company), create dialog, export/import, soft-delete - Settings templates page now shows both booking and counterparty templates Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * Update supabase/migrations/20260413160000_booking_template_library.sql Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
greptile-apps[bot]
parent
cd376e1cad
commit
bf36ebfd88
@@ -0,0 +1,60 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
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 UpdateBookingTemplateSchema = z.object({
|
||||
name: z.string().min(1).max(200).optional(),
|
||||
description: z.string().max(2000).optional(),
|
||||
category: z.enum([
|
||||
'eu_trade', 'tax_account', 'private_transfer',
|
||||
'salary', 'representation', 'year_end',
|
||||
'vat', 'financial', 'other',
|
||||
]).optional(),
|
||||
entity_type: z.enum(['all', 'enskild_firma', 'aktiebolag']).optional(),
|
||||
lines: z.array(BookingTemplateLineSchema).min(2).optional(),
|
||||
})
|
||||
|
||||
/**
|
||||
* PUT /api/settings/booking-templates/[id]
|
||||
* Update a non-system template.
|
||||
*/
|
||||
export async function PUT(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
const { id } = await params
|
||||
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, UpdateBookingTemplateSchema)
|
||||
if (!result.success) return result.response
|
||||
|
||||
// RLS prevents updating system templates
|
||||
const { data, error } = await supabase
|
||||
.from('booking_template_library')
|
||||
.update(result.data)
|
||||
.eq('id', id)
|
||||
.eq('is_system', false)
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (error) return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
if (!data) return NextResponse.json({ error: 'Template not found' }, { status: 404 })
|
||||
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
|
||||
/**
|
||||
* GET /api/settings/booking-templates/export
|
||||
* Export company + team templates as JSON (excludes system templates).
|
||||
* Useful for sharing templates between unrelated companies.
|
||||
*/
|
||||
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)
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('booking_template_library')
|
||||
.select('name, description, category, entity_type, lines')
|
||||
.eq('company_id', companyId)
|
||||
.eq('is_active', true)
|
||||
.eq('is_system', false)
|
||||
.order('category')
|
||||
.order('name')
|
||||
|
||||
if (error) return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
|
||||
return new NextResponse(JSON.stringify({ version: 1, templates: data }, null, 2), {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Disposition': 'attachment; filename="bokforingsmallar.json"',
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
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'
|
||||
|
||||
const ImportLineSchema = 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 ImportTemplateSchema = 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(ImportLineSchema).min(2),
|
||||
})
|
||||
|
||||
const ImportPayloadSchema = z.object({
|
||||
version: z.number(),
|
||||
templates: z.array(ImportTemplateSchema).min(1).max(100),
|
||||
})
|
||||
|
||||
/**
|
||||
* POST /api/settings/booking-templates/import
|
||||
* Import templates from JSON (exported from another company).
|
||||
* Creates company-scoped templates for the active company.
|
||||
*/
|
||||
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 companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
let body: unknown
|
||||
try {
|
||||
body = await request.json()
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
|
||||
}
|
||||
|
||||
const parsed = ImportPayloadSchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid import format', details: parsed.error.issues },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
const rows = parsed.data.templates.map((t) => ({
|
||||
company_id: companyId,
|
||||
team_id: null,
|
||||
created_by: user.id,
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
category: t.category,
|
||||
entity_type: t.entity_type,
|
||||
lines: t.lines,
|
||||
is_system: false,
|
||||
}))
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('booking_template_library')
|
||||
.insert(rows)
|
||||
.select()
|
||||
|
||||
if (error) return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
|
||||
return NextResponse.json({ data, imported: data?.length ?? 0 }, { status: 201 })
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
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.
|
||||
*/
|
||||
export async function GET() {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
// RLS handles scoping (system OR company OR team)
|
||||
const { data, error } = await supabase
|
||||
.from('booking_template_library')
|
||||
.select('*')
|
||||
.eq('is_active', true)
|
||||
.order('is_system', { ascending: false })
|
||||
.order('category')
|
||||
.order('name')
|
||||
|
||||
if (error) return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 } })
|
||||
}
|
||||
Reference in New Issue
Block a user