Fix/mcp and req (#753)
* feat(api): test-mode API keys force dry-run on the v1 REST API A key created with mode='test' (prefix gnubok_sk_test_) binds to the real company, but the v1 wrapper forces dry_run on every write so nothing is persisted or sent. Mutations on endpoints that can't be simulated (dryRunSupported=false or unregistered) are refused with 403 TEST_KEY_WRITE_BLOCKED — fail-closed. Reads pass through unchanged and every test-key response carries X-Gnubok-Mode: test. Live keys are unaffected (mode defaults to 'live'). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(invoices): company default "Vår referens" + per-line sales-account override Add company_settings.default_our_reference (settings form, schema, type); the invoice editor pre-fills our_reference from it on new invoices only, never overwriting an edited draft. Separately, add an optional per-line försäljningskonto (class-3) override in the editor — left blank, the engine still derives the revenue account from the VAT rate, and reverse-charge/export lines ignore the override. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(invoices): render a Swish payment QR on invoice PDFs Build the Swish "Type C" QR payload offline (no Swish API call) and embed it as a PNG in the invoice PDF payment box when Swish display is enabled, the invoice is in SEK, and the amount is positive. Also surface the invoice number in the payment box. Wired through every PDF render path: send, mark-sent and pdf routes (both legacy and v1), the recurring-schedule sender, and the staged-send commit. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(bookkeeping): draft exclusion + correction-chain collapse on verifikationslista Extend list_fiscal_period_entries_with_related with two opt-in params: p_exclude_draft (keep drafts off the committed list — they get their own surface) and p_collapse_corrections (render a correction group as the single live correction, hiding the mechanical storno and the reversed original). Both default false; nothing is deleted, every voucher keeps its number, and a "show all" toggle exposes the full chain. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(reports): link multi-year SIE periods so resultatrapport shows the prior year SIE import now sets fiscal_periods.previous_period_id in both directions when creating a period, so multi-year files chain correctly regardless of #RAR order. A backfill migration repairs periods imported before this (idempotent; only touches NULL links on first-of-month periods). generateResultatrapport falls back to the date-adjacent prior period when the chain is still null, so the comparison column works for legacy data too. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(articles): hide the VAT field for non-momsregistrerade companies The article form reads company_settings.vat_registered and, when false, hides the moms field and forces vat_rate to 0 on submit — mirroring the invoice editor so a non-VAT-registered company never sets a rate it can't charge. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(import): allow file-based imports in the sandbox Bank-file, CSV/Excel and SIE imports run entirely on uploaded data with no external service, so they're now reachable in the sandbox. Only the API-backed options that need live third-party credentials (PSD2 bank connection, provider migration) stay disabled. Updates the sandbox notice copy to match. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(bookkeeping): add edit draft functionality for journal entries * feat(database): add default "Vår referens" column to company_settings for invoicing * fix(tests): set SHOW_SWISH_ON_INVOICE to false in PDF template mocks * @ fix(payments): use roundOre for Swish amount formatting Replace naive Math.round(x*100)/100 with roundOre from @/lib/money to satisfy the antipattern guard. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> @ --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
2d6ddeafc5
commit
241959513b
@@ -21,6 +21,7 @@ import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import JournalEntryAttachments from '@/components/bookkeeping/JournalEntryAttachments'
|
||||
import JournalEntryStatusBadge, { useSourceTypeLabels } from '@/components/bookkeeping/JournalEntryStatusBadge'
|
||||
import CorrectionEntryDialog from '@/components/bookkeeping/CorrectionEntryDialog'
|
||||
import EditDraftEntryDialog from '@/components/bookkeeping/EditDraftEntryDialog'
|
||||
import RecordateEntryDialog from '@/components/bookkeeping/RecordateEntryDialog'
|
||||
import CorrectionChain from '@/components/bookkeeping/CorrectionChain'
|
||||
import { ConfirmationDialog } from '@/components/ui/confirmation-dialog'
|
||||
@@ -41,6 +42,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [showCorrection, setShowCorrection] = useState(false)
|
||||
const [showEdit, setShowEdit] = useState(false)
|
||||
const [showRecordate, setShowRecordate] = useState(false)
|
||||
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
|
||||
const [isDeleting, setIsDeleting] = useState(false)
|
||||
@@ -233,6 +235,19 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
|
||||
{(entry.status === 'posted' || entry.status === 'draft') && (
|
||||
<div className="flex flex-col sm:flex-row gap-2 w-full sm:w-auto">
|
||||
{entry.status === 'draft' && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full sm:w-auto"
|
||||
onClick={() => setShowEdit(true)}
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? t('read_only_tooltip') : undefined}
|
||||
>
|
||||
{!canWrite ? <Lock className="mr-2 h-4 w-4" /> : <Pencil className="mr-2 h-4 w-4" />}
|
||||
{t('edit_draft')}
|
||||
</Button>
|
||||
)}
|
||||
{entry.status === 'draft' && (
|
||||
<Button
|
||||
size="sm"
|
||||
@@ -660,6 +675,19 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Edit draft dialog — drafts only; PATCHes the entry in place */}
|
||||
{showEdit && entry && entry.status === 'draft' && (
|
||||
<EditDraftEntryDialog
|
||||
entry={entry}
|
||||
open={showEdit}
|
||||
onOpenChange={setShowEdit}
|
||||
onUpdated={() => {
|
||||
setShowEdit(false)
|
||||
fetchData()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Delete confirmation dialog */}
|
||||
<ConfirmationDialog
|
||||
open={showDeleteConfirm}
|
||||
|
||||
@@ -2115,12 +2115,17 @@ export default function ImportPage() {
|
||||
// Sync mode + view from URL search params (reacts to client-side navigation changes)
|
||||
const searchParams = useSearchParams()
|
||||
useEffect(() => {
|
||||
if (isSandbox) return
|
||||
if (searchParams.get('migration')) {
|
||||
// External imports (provider migration, PSD2 bank connection) need live
|
||||
// third-party credentials, so their deep links are ignored in the sandbox.
|
||||
// Manual file-import modes (bank file, CSV/Excel, SIE) stay reachable.
|
||||
const allowedModes = isSandbox
|
||||
? ['bank', 'sie', 'csv_data']
|
||||
: ['psd2', 'bank', 'sie', 'csv_data', 'migration']
|
||||
if (!isSandbox && searchParams.get('migration')) {
|
||||
setMode('migration')
|
||||
} else {
|
||||
const modeParam = searchParams.get('mode')
|
||||
if (modeParam && ['psd2', 'bank', 'sie', 'csv_data', 'migration'].includes(modeParam)) {
|
||||
if (modeParam && allowedModes.includes(modeParam)) {
|
||||
setMode(modeParam as ImportMode)
|
||||
}
|
||||
}
|
||||
@@ -2263,19 +2268,20 @@ export default function ImportPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 3. Banktransaktioner */}
|
||||
{/* 3. Banktransaktioner — manual file imports (bank file, CSV/Excel,
|
||||
SIE) run entirely on uploaded data with no external service, so
|
||||
they stay available in the sandbox, unlike the API-backed options
|
||||
above (bank connection, provider migration) which need live
|
||||
credentials. */}
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={isSandbox ? -1 : 0}
|
||||
aria-disabled={isSandbox}
|
||||
tabIndex={0}
|
||||
className={cn(
|
||||
'group flex items-start gap-4 rounded-lg border bg-card p-5 transition-all',
|
||||
isSandbox
|
||||
? 'opacity-50 cursor-not-allowed'
|
||||
: 'cursor-pointer hover:border-foreground/15 hover:shadow-[var(--shadow-sm)] active:scale-[0.998]'
|
||||
'cursor-pointer hover:border-foreground/15 hover:shadow-[var(--shadow-sm)] active:scale-[0.998]'
|
||||
)}
|
||||
onClick={() => { if (!isSandbox) setMode('bank') }}
|
||||
onKeyDown={(e) => { if (!isSandbox && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); setMode('bank') } }}
|
||||
onClick={() => setMode('bank')}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setMode('bank') } }}
|
||||
>
|
||||
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-foreground/[0.06]">
|
||||
<ArrowLeftRight className="h-[18px] w-[18px] text-foreground/60" />
|
||||
@@ -2299,16 +2305,13 @@ export default function ImportPage() {
|
||||
{/* 4. CSV/Excel-data (ingående balanser, kunder, leverantörer) */}
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={isSandbox ? -1 : 0}
|
||||
aria-disabled={isSandbox}
|
||||
tabIndex={0}
|
||||
className={cn(
|
||||
'group flex items-start gap-4 rounded-lg border bg-card p-5 transition-all',
|
||||
isSandbox
|
||||
? 'opacity-50 cursor-not-allowed'
|
||||
: 'cursor-pointer hover:border-foreground/15 hover:shadow-[var(--shadow-sm)] active:scale-[0.998]'
|
||||
'cursor-pointer hover:border-foreground/15 hover:shadow-[var(--shadow-sm)] active:scale-[0.998]'
|
||||
)}
|
||||
onClick={() => { if (!isSandbox) setMode('csv_data') }}
|
||||
onKeyDown={(e) => { if (!isSandbox && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); setMode('csv_data') } }}
|
||||
onClick={() => setMode('csv_data')}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setMode('csv_data') } }}
|
||||
>
|
||||
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-foreground/[0.06]">
|
||||
<FileSpreadsheet className="h-[18px] w-[18px] text-foreground/60" />
|
||||
@@ -2339,16 +2342,13 @@ export default function ImportPage() {
|
||||
{/* 5. Bokföringsdata (SIE) */}
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={isSandbox ? -1 : 0}
|
||||
aria-disabled={isSandbox}
|
||||
tabIndex={0}
|
||||
className={cn(
|
||||
'group flex items-start gap-4 rounded-lg border bg-card p-5 transition-all',
|
||||
isSandbox
|
||||
? 'opacity-50 cursor-not-allowed'
|
||||
: 'cursor-pointer hover:border-foreground/15 hover:shadow-[var(--shadow-sm)] active:scale-[0.998]'
|
||||
'cursor-pointer hover:border-foreground/15 hover:shadow-[var(--shadow-sm)] active:scale-[0.998]'
|
||||
)}
|
||||
onClick={() => { if (!isSandbox) setMode('sie') }}
|
||||
onKeyDown={(e) => { if (!isSandbox && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); setMode('sie') } }}
|
||||
onClick={() => setMode('sie')}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setMode('sie') } }}
|
||||
>
|
||||
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-foreground/[0.06]">
|
||||
<FileText className="h-[18px] w-[18px] text-foreground/60" />
|
||||
@@ -2415,7 +2415,7 @@ export default function ImportPage() {
|
||||
window.open(`/api/reports/sie-export?${params.toString()}`, '_blank')
|
||||
}
|
||||
}}
|
||||
disabled={!exportPeriodId || isSandbox}
|
||||
disabled={!exportPeriodId}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
|
||||
@@ -7,6 +7,11 @@ import { eventBus } from '@/lib/events/bus'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { syncInvoiceStatusFromPaymentEntry } from '@/lib/bookkeeping/payment-sync'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CreateJournalEntrySchema } from '@/lib/api/schemas'
|
||||
import { updateDraftEntry } from '@/lib/bookkeeping/engine'
|
||||
import { bookkeepingErrorResponse } from '@/lib/bookkeeping/errors'
|
||||
|
||||
const logger = createLogger('journal-entries')
|
||||
|
||||
@@ -103,3 +108,31 @@ export async function DELETE(
|
||||
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH — edit a DRAFT verifikat in place (header + lines). Only drafts are
|
||||
* editable; updateDraftEntry rejects committed entries with a 409, and the DB
|
||||
* immutability trigger is the backstop. Uses withRouteContext (MFA + write gate)
|
||||
* — the GET/DELETE above predate that wrapper and are intentionally left as-is.
|
||||
*/
|
||||
export const PATCH = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'bookkeeping.journal_entry.update',
|
||||
async (request, { supabase, companyId, user }, { params }) => {
|
||||
const { id } = await params
|
||||
const validation = await validateBody(request, CreateJournalEntrySchema)
|
||||
if (!validation.success) return validation.response
|
||||
|
||||
try {
|
||||
const entry = await updateDraftEntry(supabase, companyId, user.id, id, validation.data)
|
||||
return NextResponse.json({ data: entry })
|
||||
} catch (err) {
|
||||
const typed = bookkeepingErrorResponse(err)
|
||||
if (typed) return typed
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Failed to update journal entry' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getPool } from '@/tests/pg/setup'
|
||||
import { seedCompany, insertBalancedLines } from '@/tests/pg/fixtures'
|
||||
|
||||
// Covers the p_exclude_draft / p_collapse_corrections params added to
|
||||
// list_fiscal_period_entries_with_related (migration 20260621130500).
|
||||
// - exclude_draft: drafts kept off the committed list (own "Utkast" surface).
|
||||
// - collapse_corrections: a correction group renders as ONE row — the live
|
||||
// correction; the storno and the reversed original it replaced are hidden.
|
||||
// total_count must stay in lockstep with the filtered set so pagination holds.
|
||||
describe('list_fiscal_period_entries_with_related: draft + correction filters', () => {
|
||||
// Insert a journal_entry directly so we can set the storno/correction link
|
||||
// columns the fixtures don't expose. Posted/reversed rows get balanced lines
|
||||
// so any deferred balance check is satisfied.
|
||||
async function insertEntry(p: {
|
||||
userId: string
|
||||
companyId: string
|
||||
fiscalPeriodId: string
|
||||
status: 'draft' | 'posted' | 'reversed'
|
||||
sourceType: string
|
||||
voucherNumber: number
|
||||
description: string
|
||||
reversesId?: string
|
||||
correctionOfId?: string
|
||||
withLines?: boolean
|
||||
}): Promise<string> {
|
||||
const id = randomUUID()
|
||||
await getPool().query(
|
||||
`INSERT INTO public.journal_entries
|
||||
(id, user_id, company_id, fiscal_period_id, voucher_number, voucher_series,
|
||||
entry_date, description, source_type, status, reverses_id, correction_of_id)
|
||||
VALUES ($1,$2,$3,$4,$5,'A','2026-06-01',$6,$7,$8,$9,$10)`,
|
||||
[
|
||||
id,
|
||||
p.userId,
|
||||
p.companyId,
|
||||
p.fiscalPeriodId,
|
||||
p.voucherNumber,
|
||||
p.description,
|
||||
p.sourceType,
|
||||
p.status,
|
||||
p.reversesId ?? null,
|
||||
p.correctionOfId ?? null,
|
||||
],
|
||||
)
|
||||
if (p.withLines) await insertBalancedLines(id)
|
||||
return id
|
||||
}
|
||||
|
||||
async function callRpc(
|
||||
companyId: string,
|
||||
periodId: string,
|
||||
opts: { status?: string | null; excludeDraft?: boolean; collapse?: boolean } = {},
|
||||
) {
|
||||
const { rows } = await getPool().query<{ entry: { id: string }; total_count: string }>(
|
||||
`SELECT entry, total_count
|
||||
FROM list_fiscal_period_entries_with_related(
|
||||
$1, $2, true, $3, NULL, NULL, 'desc', 100, 0, $4, $5)`,
|
||||
[companyId, periodId, opts.status ?? null, opts.excludeDraft ?? false, opts.collapse ?? false],
|
||||
)
|
||||
return rows
|
||||
}
|
||||
|
||||
it('excludes drafts and collapses a correction group to the live correction', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
|
||||
const posted = await insertEntry({ userId, companyId, fiscalPeriodId, status: 'posted', sourceType: 'manual', voucherNumber: 10, withLines: true, description: 'Plain posted' })
|
||||
const draft = await insertEntry({ userId, companyId, fiscalPeriodId, status: 'draft', sourceType: 'manual', voucherNumber: 0, description: 'Draft' })
|
||||
// Correction group: original is reversed; storno reverses it; correction replaces it.
|
||||
const original = await insertEntry({ userId, companyId, fiscalPeriodId, status: 'reversed', sourceType: 'manual', voucherNumber: 11, withLines: true, description: 'Original' })
|
||||
const storno = await insertEntry({ userId, companyId, fiscalPeriodId, status: 'posted', sourceType: 'storno', voucherNumber: 12, reversesId: original, withLines: true, description: 'Storno' })
|
||||
const correction = await insertEntry({ userId, companyId, fiscalPeriodId, status: 'posted', sourceType: 'correction', voucherNumber: 13, correctionOfId: original, withLines: true, description: 'Correction' })
|
||||
|
||||
// Default (no filters): every row shows.
|
||||
const all = await callRpc(companyId, fiscalPeriodId, {})
|
||||
const allIds = all.map((r) => r.entry.id)
|
||||
expect(allIds).toEqual(expect.arrayContaining([posted, draft, original, storno, correction]))
|
||||
expect(Number(all[0]!.total_count)).toBe(5)
|
||||
|
||||
// Committed list: drafts, stornos and reversed-corrected originals hidden.
|
||||
const filtered = await callRpc(companyId, fiscalPeriodId, { excludeDraft: true, collapse: true })
|
||||
const ids = filtered.map((r) => r.entry.id)
|
||||
expect(ids).toEqual(expect.arrayContaining([posted, correction]))
|
||||
expect(ids).not.toContain(draft)
|
||||
expect(ids).not.toContain(storno)
|
||||
expect(ids).not.toContain(original)
|
||||
expect(Number(filtered[0]!.total_count)).toBe(2)
|
||||
})
|
||||
|
||||
it('still returns drafts when status=draft is requested explicitly', async () => {
|
||||
const { userId, companyId, fiscalPeriodId } = await seedCompany()
|
||||
await insertEntry({ userId, companyId, fiscalPeriodId, status: 'posted', sourceType: 'manual', voucherNumber: 10, withLines: true, description: 'Posted' })
|
||||
const draft = await insertEntry({ userId, companyId, fiscalPeriodId, status: 'draft', sourceType: 'manual', voucherNumber: 0, description: 'Draft' })
|
||||
|
||||
// Drafts mode (status=draft). exclude_draft must NOT cancel the explicit ask.
|
||||
const rows = await callRpc(companyId, fiscalPeriodId, { status: 'draft', excludeDraft: true })
|
||||
expect(rows.map((r) => r.entry.id)).toEqual([draft])
|
||||
})
|
||||
})
|
||||
@@ -24,6 +24,11 @@ export async function GET(request: Request) {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
const status = searchParams.get('status')
|
||||
// Drafts get their own surface in the UI; the committed list excludes them.
|
||||
const excludeDraft = searchParams.get('exclude_draft') === 'true'
|
||||
// Collapse a correction group to the live correction (hide the storno and the
|
||||
// reversed original it replaced). The full chain stays reachable.
|
||||
const collapseCorrections = searchParams.get('collapse_corrections') === 'true'
|
||||
// Clamp pagination to bound DB work against oversized/pathological inputs
|
||||
// (compliance A.8.28 / ASVS V1.2.5). The UI page-size selector offers
|
||||
// 20/50/100/Alla; "Alla" sends a large limit which is capped at MAX_LIMIT.
|
||||
@@ -81,6 +86,8 @@ export async function GET(request: Request) {
|
||||
p_sort_date: sortDateParam,
|
||||
p_limit: limit,
|
||||
p_offset: offset,
|
||||
p_exclude_draft: excludeDraft,
|
||||
p_collapse_corrections: collapseCorrections,
|
||||
})
|
||||
|
||||
if (error) {
|
||||
@@ -134,6 +141,9 @@ export async function GET(request: Request) {
|
||||
query = query.eq('status', status)
|
||||
} else {
|
||||
query = query.neq('status', 'cancelled')
|
||||
if (excludeDraft) {
|
||||
query = query.neq('status', 'draft')
|
||||
}
|
||||
}
|
||||
|
||||
if (dateFrom) {
|
||||
@@ -157,6 +167,26 @@ export async function GET(request: Request) {
|
||||
query = query.ilike('description', `%${escapeLikePattern(search)}%`)
|
||||
}
|
||||
|
||||
// Collapse correction groups (voucher-sort / search path): hide the storno
|
||||
// and the reversed originals a posted correction replaced, leaving the live
|
||||
// correction. Pagination/count stay correct because these are query filters.
|
||||
if (collapseCorrections) {
|
||||
query = query.neq('source_type', 'storno')
|
||||
const { data: corrections } = await supabase
|
||||
.from('journal_entries')
|
||||
.select('correction_of_id')
|
||||
.eq('company_id', companyId)
|
||||
.eq('source_type', 'correction')
|
||||
.eq('status', 'posted')
|
||||
.not('correction_of_id', 'is', null)
|
||||
const correctedOriginalIds = Array.from(
|
||||
new Set((corrections ?? []).map((r) => r.correction_of_id).filter(Boolean) as string[])
|
||||
)
|
||||
if (correctedOriginalIds.length > 0) {
|
||||
query = query.not('id', 'in', `(${correctedOriginalIds.join(',')})`)
|
||||
}
|
||||
}
|
||||
|
||||
const { data, error, count } = await query
|
||||
|
||||
if (error) {
|
||||
|
||||
@@ -40,6 +40,7 @@ vi.mock('@react-pdf/renderer', () => ({
|
||||
vi.mock('@/lib/invoices/pdf-template', () => ({
|
||||
InvoicePDF: vi.fn().mockReturnValue('mock-pdf-element'),
|
||||
brandingFromCompanySettings: vi.fn().mockReturnValue({}),
|
||||
SHOW_SWISH_ON_INVOICE: false,
|
||||
}))
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import { createSchedulesForCustomerInvoice } from '@/lib/bookkeeping/accruals/fr
|
||||
import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { prepareInvoicePdfRender, buildSwishQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { uploadDocument } from '@/lib/core/documents/document-service'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
@@ -170,6 +170,7 @@ export async function POST(
|
||||
// underlag isn't stamped "UTKAST – inte en giltig faktura".
|
||||
const renderableInvoice = { ...(invoice as Invoice), status: 'sent' as const }
|
||||
const { branding } = prepareInvoicePdfRender(settings as CompanySettings)
|
||||
const swishQrDataUrl = await buildSwishQrDataUrl(settings as CompanySettings, renderableInvoice)
|
||||
const pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: renderableInvoice,
|
||||
@@ -178,6 +179,7 @@ export async function POST(
|
||||
company: settings as CompanySettings,
|
||||
originalInvoiceNumber,
|
||||
branding,
|
||||
swishQrDataUrl,
|
||||
})
|
||||
)
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { prepareInvoicePdfRender, buildSwishQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import type { Invoice, InvoiceItem, Customer, CompanySettings } from '@/types'
|
||||
|
||||
@@ -68,6 +68,7 @@ export async function GET(
|
||||
try {
|
||||
// Generate PDF
|
||||
const { branding } = prepareInvoicePdfRender(company as CompanySettings)
|
||||
const swishQrDataUrl = await buildSwishQrDataUrl(company as CompanySettings, invoice as Invoice)
|
||||
const pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: invoice as Invoice,
|
||||
@@ -76,6 +77,7 @@ export async function GET(
|
||||
company: company as CompanySettings,
|
||||
originalInvoiceNumber,
|
||||
branding,
|
||||
swishQrDataUrl,
|
||||
})
|
||||
)
|
||||
|
||||
|
||||
@@ -41,6 +41,7 @@ vi.mock('@react-pdf/renderer', () => ({
|
||||
vi.mock('@/lib/invoices/pdf-template', () => ({
|
||||
InvoicePDF: vi.fn().mockReturnValue('mock-pdf-element'),
|
||||
brandingFromCompanySettings: vi.fn().mockReturnValue({}),
|
||||
SHOW_SWISH_ON_INVOICE: false,
|
||||
}))
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { eventBus } from '@/lib/events'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { prepareInvoicePdfRender, buildSwishQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { getEmailService } from '@/lib/email/service'
|
||||
import {
|
||||
generateInvoiceEmailHtml,
|
||||
@@ -133,6 +133,7 @@ export const POST = withRouteContext(
|
||||
// receives a PDF stamped "UTKAST – inte en giltig faktura".
|
||||
const renderableInvoice = { ...(invoice as Invoice), status: 'sent' as const }
|
||||
const { branding } = prepareInvoicePdfRender(company as CompanySettings)
|
||||
const swishQrDataUrl = await buildSwishQrDataUrl(company as CompanySettings, renderableInvoice)
|
||||
const pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: renderableInvoice,
|
||||
@@ -141,6 +142,7 @@ export const POST = withRouteContext(
|
||||
company: company as CompanySettings,
|
||||
originalInvoiceNumber,
|
||||
branding,
|
||||
swishQrDataUrl,
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
@@ -189,5 +189,40 @@ describe('POST /api/settings/api-keys', () => {
|
||||
expect(payload).not.toHaveProperty('sod_acknowledged_at')
|
||||
expect(payload).not.toHaveProperty('sod_acknowledged_by')
|
||||
expect(payload.scopes).toEqual(['reports:read'])
|
||||
// Default mode is live, bound to the active company.
|
||||
expect(payload.mode).toBe('live')
|
||||
expect(payload.company_id).toBe('company-1')
|
||||
})
|
||||
|
||||
it('creates a test key bound to the active company with mode=test', async () => {
|
||||
const { insertSpy } = setupFrom({
|
||||
count: 0,
|
||||
insertResult: {
|
||||
data: {
|
||||
id: 'ak-3',
|
||||
key_prefix: 'gnubok_sk_test_abc',
|
||||
name: 'pilot',
|
||||
scopes: ['reports:read'],
|
||||
mode: 'test',
|
||||
created_at: '2026-06-05T10:00:00Z',
|
||||
},
|
||||
},
|
||||
})
|
||||
const res = await POST(
|
||||
createMockRequest('/api/settings/api-keys', {
|
||||
method: 'POST',
|
||||
body: { name: 'pilot', scopes: ['reports:read'], mode: 'test' },
|
||||
}),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: { key: string } }>(res)
|
||||
expect(status).toBe(200)
|
||||
// Real generateApiKey('test') runs — the returned secret carries the infix.
|
||||
expect(body.data.key).toMatch(/^gnubok_sk_test_/)
|
||||
|
||||
const payload = insertSpy.mock.calls[0][0] as Record<string, unknown>
|
||||
expect(payload.mode).toBe('test')
|
||||
// Test keys are simulation-only — they bind to the active company (the v1
|
||||
// wrapper forces dry-run so they never persist).
|
||||
expect(payload.company_id).toBe('company-1')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
} from '@/lib/auth/api-keys'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import type { ApiKeyScope } from '@/lib/auth/api-keys'
|
||||
import type { ApiKeyMode, ApiKeyScope } from '@/lib/auth/api-keys'
|
||||
|
||||
/** GET /api/settings/api-keys — list the company's API keys (key value never returned). */
|
||||
export const GET = withRouteContext(
|
||||
@@ -15,9 +15,11 @@ export const GET = withRouteContext(
|
||||
async (_request, ctx) => {
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
|
||||
// Both live and test keys for the active company. (Test keys are bound to the
|
||||
// active company too — they're simulation-only, so they never write real data.)
|
||||
const { data, error } = await supabase
|
||||
.from('api_keys')
|
||||
.select('id, key_prefix, name, scopes, rate_limit_rpm, last_used_at, revoked_at, created_at')
|
||||
.select('id, key_prefix, name, scopes, mode, rate_limit_rpm, last_used_at, revoked_at, created_at')
|
||||
.eq('company_id', companyId)
|
||||
.order('created_at', { ascending: false })
|
||||
|
||||
@@ -44,12 +46,14 @@ export const POST = withRouteContext(
|
||||
let name = 'Unnamed key'
|
||||
let scopes: ApiKeyScope[] = DEFAULT_SCOPES
|
||||
let acknowledgeSod = false
|
||||
let mode: ApiKeyMode = 'live'
|
||||
try {
|
||||
const body = await request.json()
|
||||
if (body.name && typeof body.name === 'string') {
|
||||
name = body.name.slice(0, 100)
|
||||
}
|
||||
acknowledgeSod = body.acknowledge_sod === true
|
||||
if (body.mode === 'test') mode = 'test'
|
||||
const parsed = validateScopes(body.scopes)
|
||||
if (parsed) {
|
||||
scopes = parsed
|
||||
@@ -63,6 +67,10 @@ export const POST = withRouteContext(
|
||||
// Empty body — use defaults.
|
||||
}
|
||||
|
||||
// Both live and test keys bind to the active company. A test key is
|
||||
// simulation-only — the v1 wrapper forces dry-run on every write — so it can
|
||||
// safely point at the real company without ever persisting anything.
|
||||
|
||||
// Segregation of duties: warn + require explicit acknowledgement (not block)
|
||||
// when a single key both stages bookkeeping AND can approve it. Surfacing a
|
||||
// 409 lets the UI raise an explicit confirm dialog and the agent inform the
|
||||
@@ -92,7 +100,7 @@ export const POST = withRouteContext(
|
||||
})
|
||||
}
|
||||
|
||||
const { key, hash, prefix } = generateApiKey()
|
||||
const { key, hash, prefix } = generateApiKey(mode)
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('api_keys')
|
||||
@@ -103,11 +111,12 @@ export const POST = withRouteContext(
|
||||
key_prefix: prefix,
|
||||
name,
|
||||
scopes,
|
||||
mode,
|
||||
...(sodAcknowledgedAt
|
||||
? { sod_acknowledged_at: sodAcknowledgedAt, sod_acknowledged_by: user.id }
|
||||
: {}),
|
||||
})
|
||||
.select('id, key_prefix, name, scopes, created_at')
|
||||
.select('id, key_prefix, name, scopes, mode, created_at')
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
|
||||
@@ -40,6 +40,7 @@ vi.mock('@react-pdf/renderer', () => ({
|
||||
vi.mock('@/lib/invoices/pdf-template', () => ({
|
||||
InvoicePDF: vi.fn().mockReturnValue({}),
|
||||
brandingFromCompanySettings: vi.fn().mockReturnValue({}),
|
||||
SHOW_SWISH_ON_INVOICE: false,
|
||||
}))
|
||||
|
||||
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
import { z } from 'zod'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { prepareInvoicePdfRender, buildSwishQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { registerEndpoint } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
|
||||
@@ -150,6 +150,7 @@ export const GET = withApiV1<{ params: Promise<{ companyId: string; id: string }
|
||||
let pdfBuffer: Buffer
|
||||
try {
|
||||
const { branding } = prepareInvoicePdfRender(company as CompanySettings)
|
||||
const swishQrDataUrl = await buildSwishQrDataUrl(company as CompanySettings, typed as Invoice)
|
||||
pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: typed as Invoice,
|
||||
@@ -158,6 +159,7 @@ export const GET = withApiV1<{ params: Promise<{ companyId: string; id: string }
|
||||
company: company as CompanySettings,
|
||||
originalInvoiceNumber,
|
||||
branding,
|
||||
swishQrDataUrl,
|
||||
}),
|
||||
)
|
||||
} catch (err) {
|
||||
|
||||
@@ -72,6 +72,7 @@ vi.mock('@/lib/email/invoice-templates', () => ({
|
||||
vi.mock('@/lib/invoices/pdf-template', () => ({
|
||||
InvoicePDF: vi.fn().mockReturnValue({}),
|
||||
brandingFromCompanySettings: vi.fn().mockReturnValue({}),
|
||||
SHOW_SWISH_ON_INVOICE: false,
|
||||
}))
|
||||
|
||||
// The sandbox guard reads company_settings.is_sandbox at the top of the
|
||||
@@ -411,6 +412,40 @@ describe('POST /api/v1/companies/:companyId/invoices/:id/send', () => {
|
||||
expect(finalRenderArgs.invoice.invoice_number).toBe('2026-0043')
|
||||
})
|
||||
|
||||
it('test-mode key forces dry-run: returns a preview, no email, no number burned', async () => {
|
||||
// A test key has no ?dry_run flag, but the wrapper forces dry-run because
|
||||
// the key is mode='test'. The send endpoint declares dryRunSupported, so the
|
||||
// request is allowed and short-circuits to the preview.
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: USER_ID,
|
||||
companyId: COMPANY_ID,
|
||||
apiKeyId: 'ak_test',
|
||||
apiKeyName: 'Test key',
|
||||
scopes: ['invoices:write'],
|
||||
mode: 'test',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(
|
||||
makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
invoices: { data: DRAFT_INVOICE, error: null },
|
||||
company_settings: { data: COMPANY_SETTINGS, error: null },
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await sendInvoice(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/invoices/${INVOICE_ID}/send`),
|
||||
detailParams(COMPANY_ID, INVOICE_ID),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('X-Gnubok-Mode')).toBe('test')
|
||||
const body = await res.json()
|
||||
expect(body.data.dry_run).toBe(true)
|
||||
expect(body.data.preview.status).toBe('sent')
|
||||
expect(body.data.preview.would_send_to).toBe('[email protected]')
|
||||
expect(mockSendEmail).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects keys without invoices:write scope', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: USER_ID,
|
||||
|
||||
@@ -43,7 +43,7 @@ import { registerEndpoint } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { prepareInvoicePdfRender, buildSwishQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { getEmailService } from '@/lib/email/service'
|
||||
import {
|
||||
generateInvoiceEmailHtml,
|
||||
@@ -362,6 +362,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
let pdfBuffer: Buffer
|
||||
try {
|
||||
const { branding } = prepareInvoicePdfRender(settings)
|
||||
const swishQrDataUrl = await buildSwishQrDataUrl(settings, renderableInvoice)
|
||||
pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: renderableInvoice,
|
||||
@@ -370,6 +371,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
company: settings,
|
||||
originalInvoiceNumber,
|
||||
branding,
|
||||
swishQrDataUrl,
|
||||
}),
|
||||
)
|
||||
} catch (err) {
|
||||
|
||||
@@ -37,8 +37,13 @@ declarations, ingest SIE files, and subscribe to webhooks for state changes.
|
||||
account deltas) without committing. The same call without dry-run commits.
|
||||
- **Idempotency-Key on every write.** Pass a UUID in \`Idempotency-Key\`; replays
|
||||
return the cached response (24h TTL) with \`Idempotent-Replayed: true\`.
|
||||
- **Test mode.** API keys prefixed \`gnubok_sk_test_\` are bound to deterministic
|
||||
sandbox companies — safe for evals and agent learning. Live keys hit real data.
|
||||
- **Test mode.** Create a key with mode \`test\` (prefix \`gnubok_sk_test_\`) in the
|
||||
dashboard. A test key forces \`dry_run\` on every write against your real company —
|
||||
you get a realistic 200 + preview of what *would* happen, but nothing is ever
|
||||
saved or sent. Reads return real data; responses carry \`X-Gnubok-Mode: test\`.
|
||||
Writes on endpoints that can't be simulated are refused (403
|
||||
\`TEST_KEY_WRITE_BLOCKED\`). It's \`?dry_run=true\` baked into the credential, so
|
||||
you can develop safely before switching to a live key.
|
||||
- **Compliance pre-flight.** \`GET /api/v1/companies/{id}/compliance/check?type=…\`
|
||||
returns structured findings (voucher gaps, locked-period violations, VAT close
|
||||
blockers, missing receipts) before you submit.
|
||||
|
||||
@@ -13,6 +13,8 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
|
||||
import { ChevronDown, Loader2, Lock } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import AccountCombobox from '@/components/bookkeeping/AccountCombobox'
|
||||
import { AddAccountDialog } from '@/components/bookkeeping/AddAccountDialog'
|
||||
import type { BASAccount, CreateArticleInput } from '@/types'
|
||||
@@ -36,6 +38,8 @@ export default function ArticleForm({
|
||||
initialData,
|
||||
}: ArticleFormProps) {
|
||||
const { canWrite } = useCanWrite()
|
||||
const { company } = useCompany()
|
||||
const supabase = createClient()
|
||||
const t = useTranslations('form_article')
|
||||
// Active class-3 (revenue) accounts for the combobox. The combobox accepts
|
||||
// unknown 4-digit numbers optimistically — the API answers with
|
||||
@@ -45,6 +49,9 @@ export default function ArticleForm({
|
||||
// Inline account creation: what the user typed in the combobox when they hit
|
||||
// "Skapa konto" — non-null opens AddAccountDialog prefilled with it.
|
||||
const [createAccountPrefill, setCreateAccountPrefill] = useState<string | null>(null)
|
||||
// Momsregistrerad? A non-VAT-registered company never charges moms, so the
|
||||
// VAT field is hidden and the rate forced to 0 — mirrors the invoice editor.
|
||||
const [vatRegistered, setVatRegistered] = useState(true)
|
||||
|
||||
async function fetchRevenueAccounts() {
|
||||
try {
|
||||
@@ -59,6 +66,25 @@ export default function ArticleForm({
|
||||
useEffect(() => {
|
||||
fetchRevenueAccounts()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!company?.id) return
|
||||
let cancelled = false
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('vat_registered')
|
||||
.eq('company_id', company.id)
|
||||
.single()
|
||||
.then(({ data }) => {
|
||||
if (!cancelled && typeof data?.vat_registered === 'boolean') {
|
||||
setVatRegistered(data.vat_registered)
|
||||
}
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [company?.id])
|
||||
// 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(
|
||||
@@ -125,7 +151,7 @@ export default function ArticleForm({
|
||||
type: data.type,
|
||||
unit: data.unit,
|
||||
price_excl_vat: data.price_excl_vat,
|
||||
vat_rate: data.vat_rate,
|
||||
vat_rate: vatRegistered ? data.vat_rate : 0,
|
||||
revenue_account: data.revenue_account || null,
|
||||
cost_price: data.cost_price ?? null,
|
||||
ean: data.ean || null,
|
||||
@@ -180,8 +206,8 @@ export default function ArticleForm({
|
||||
<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">
|
||||
{/* Unit + price + VAT (moms hidden for non-momsregistrerade) */}
|
||||
<div className={`grid grid-cols-1 gap-4 ${vatRegistered ? 'sm:grid-cols-3' : 'sm:grid-cols-2'}`}>
|
||||
<div className="space-y-2">
|
||||
<Label>{t('unit_label')}</Label>
|
||||
<Controller
|
||||
@@ -215,6 +241,7 @@ export default function ArticleForm({
|
||||
<p className="text-sm text-destructive">{errors.price_excl_vat.message}</p>
|
||||
)}
|
||||
</div>
|
||||
{vatRegistered && (
|
||||
<div className="space-y-2">
|
||||
<Label>{t('vat_rate_label')}</Label>
|
||||
<Controller
|
||||
@@ -237,6 +264,7 @@ export default function ArticleForm({
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Advanced (collapsible) */}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import JournalEntryForm, { type FormLine } from '@/components/bookkeeping/JournalEntryForm'
|
||||
import type { JournalEntry, JournalEntryLine } from '@/types'
|
||||
|
||||
interface Props {
|
||||
entry: JournalEntry
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
/** Fired after the draft is successfully updated. */
|
||||
onUpdated: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit a DRAFT verifikat. Wraps JournalEntryForm in edit mode, pre-filled from
|
||||
* the draft's header + lines; the form PATCHes the entry in place and it stays
|
||||
* a draft (the user posts it separately). Only ever opened for status==='draft'
|
||||
* entries — the engine + DB triggers reject edits on committed entries anyway.
|
||||
*/
|
||||
export default function EditDraftEntryDialog({ entry, open, onOpenChange, onUpdated }: Props) {
|
||||
const t = useTranslations('bookkeeping')
|
||||
|
||||
const initialLines: FormLine[] = ((entry.lines || []) as JournalEntryLine[])
|
||||
.slice()
|
||||
.sort((a, b) => a.sort_order - b.sort_order)
|
||||
.map((l) => ({
|
||||
account_number: l.account_number,
|
||||
debit_amount: Number(l.debit_amount) > 0 ? String(l.debit_amount) : '',
|
||||
credit_amount: Number(l.credit_amount) > 0 ? String(l.credit_amount) : '',
|
||||
line_description: l.line_description || '',
|
||||
}))
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
className="sm:max-w-3xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto"
|
||||
// Same guard as Ny verifikat: an accidental outside-click must not
|
||||
// discard in-progress edits.
|
||||
onPointerDownOutside={(e) => e.preventDefault()}
|
||||
onInteractOutside={(e) => e.preventDefault()}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('edit_draft_dialog_title')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<JournalEntryForm
|
||||
key={entry.id}
|
||||
bare
|
||||
editEntryId={entry.id}
|
||||
initialLines={initialLines}
|
||||
initialDate={entry.entry_date}
|
||||
initialDescription={entry.description}
|
||||
initialNotes={entry.notes ?? undefined}
|
||||
initialVoucherSeries={entry.voucher_series}
|
||||
onUpdated={onUpdated}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -59,6 +59,7 @@ interface Props {
|
||||
initialDate?: string
|
||||
initialDescription?: string
|
||||
initialNotes?: string
|
||||
initialVoucherSeries?: string
|
||||
sourceType?: JournalEntrySourceType
|
||||
sourceId?: string
|
||||
submitUrl?: string
|
||||
@@ -66,6 +67,11 @@ interface Props {
|
||||
/** Render without the Card chrome (e.g. inside a dialog) but keep the full
|
||||
* non-embedded field set (series, notes, documents, voucher hint). */
|
||||
bare?: boolean
|
||||
/** Edit an existing DRAFT in place: the form PATCHes this entry instead of
|
||||
* creating a new one. Only the draft's header + lines are updated. */
|
||||
editEntryId?: string
|
||||
/** Fired after a successful draft edit (editEntryId path). */
|
||||
onUpdated?: () => void
|
||||
}
|
||||
|
||||
const BLANK_LINE: FormLine = { account_number: '', debit_amount: '', credit_amount: '', line_description: '' }
|
||||
@@ -77,11 +83,14 @@ export default function JournalEntryForm({
|
||||
initialDate,
|
||||
initialDescription,
|
||||
initialNotes,
|
||||
initialVoucherSeries,
|
||||
sourceType,
|
||||
sourceId,
|
||||
submitUrl,
|
||||
embedded,
|
||||
bare,
|
||||
editEntryId,
|
||||
onUpdated,
|
||||
}: Props) {
|
||||
const { canWrite } = useCanWrite()
|
||||
const { toast } = useToast()
|
||||
@@ -97,7 +106,7 @@ export default function JournalEntryForm({
|
||||
const [lines, setLines] = useState<FormLine[]>(
|
||||
initialLines ?? [{ ...BLANK_LINE }, { ...BLANK_LINE }]
|
||||
)
|
||||
const [voucherSeries, setVoucherSeries] = useState('A')
|
||||
const [voucherSeries, setVoucherSeries] = useState(initialVoucherSeries ?? 'A')
|
||||
const [nextVoucherNumber, setNextVoucherNumber] = useState<number | null>(null)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [showReview, setShowReview] = useState(false)
|
||||
@@ -170,7 +179,9 @@ export default function JournalEntryForm({
|
||||
// Fetch default voucher series from company settings — prefer the
|
||||
// per-source-type mapping when present; fall back to the legacy
|
||||
// default_voucher_series, then to 'A'.
|
||||
if (!embedded) {
|
||||
// In edit mode the draft's own series is pre-filled — never override it
|
||||
// from the company defaults.
|
||||
if (!embedded && !editEntryId) {
|
||||
fetch('/api/settings').then(r => r.json()).then(({ data }) => {
|
||||
if (!data) return
|
||||
const effectiveSourceType = sourceType ?? 'manual'
|
||||
@@ -182,7 +193,7 @@ export default function JournalEntryForm({
|
||||
setVoucherSeries(perSource !== 'A' ? perSource : fallback)
|
||||
}).catch(() => {/* keep 'A' */})
|
||||
}
|
||||
}, [embedded, sourceType])
|
||||
}, [embedded, sourceType, editEntryId])
|
||||
|
||||
// Auto-select period when entry date changes
|
||||
useEffect(() => {
|
||||
@@ -539,9 +550,15 @@ export default function JournalEntryForm({
|
||||
})
|
||||
|
||||
const baseUrl = submitUrl ?? '/api/bookkeeping/journal-entries'
|
||||
const url = saveAsDraftRef.current ? `${baseUrl}?as_draft=true` : baseUrl
|
||||
// Edit mode PATCHes the draft in place; create mode POSTs (with ?as_draft
|
||||
// when saving a draft rather than posting).
|
||||
const url = editEntryId
|
||||
? `${baseUrl}/${editEntryId}`
|
||||
: saveAsDraftRef.current
|
||||
? `${baseUrl}?as_draft=true`
|
||||
: baseUrl
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
method: editEntryId ? 'PATCH' : 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
fiscal_period_id: selectedPeriod,
|
||||
@@ -555,7 +572,7 @@ export default function JournalEntryForm({
|
||||
}),
|
||||
})
|
||||
return (await throwOnStructuredError(res)) as { data?: { id?: string; voucher_series?: string; voucher_number?: number }; journal_entry_id?: string }
|
||||
}, [lines, isForeign, rate, entryCurrency, computedForeignAmount, submitUrl, selectedPeriod, entryDate, description, sourceType, sourceId, voucherSeries, notes])
|
||||
}, [lines, isForeign, rate, entryCurrency, computedForeignAmount, submitUrl, editEntryId, selectedPeriod, entryDate, description, sourceType, sourceId, voucherSeries, notes])
|
||||
|
||||
const { runSubmit, dialog: activationDialog, confirm: confirmActivation, cancel: cancelActivation } =
|
||||
useSubmitWithAccountActivation(postJournalEntry)
|
||||
@@ -678,6 +695,35 @@ export default function JournalEntryForm({
|
||||
}
|
||||
}
|
||||
|
||||
// Edit an existing draft: PATCH in place (postJournalEntry routes to the
|
||||
// editEntryId URL) and keep it a draft. No field reset — the host dialog
|
||||
// closes on success via onUpdated.
|
||||
const handleSaveEdit = async () => {
|
||||
if (!selectedPeriod || !description || !isBalanced || periodMismatch) return
|
||||
setIsSavingDraft(true)
|
||||
try {
|
||||
await runSubmit()
|
||||
toast({
|
||||
title: t('toast_updated_title'),
|
||||
description: t('toast_updated_description'),
|
||||
})
|
||||
onUpdated?.()
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.message === 'cancelled') {
|
||||
// Activation dialog dismissed — silent
|
||||
} else {
|
||||
const anyErr = err as { body?: unknown; status?: number }
|
||||
toast({
|
||||
title: t('toast_update_failed'),
|
||||
description: getErrorMessage(anyErr.body ?? err, { context: 'journal_entry', statusCode: anyErr.status }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
} finally {
|
||||
setIsSavingDraft(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Inline review for the modal (bare): swap the form body to a read-only
|
||||
// summary instead of stacking a second dialog over the form dialog. The
|
||||
// no-underlag caveat folds in here so there's a single confirm step.
|
||||
@@ -1175,8 +1221,9 @@ export default function JournalEntryForm({
|
||||
<p className="mt-1.5 text-xs text-muted-foreground">{t('fill_balance_hint')}</p>
|
||||
</div>
|
||||
|
||||
{/* Document attachments */}
|
||||
{!embedded && (
|
||||
{/* Document attachments — hidden when editing a draft; underlag is
|
||||
managed from the verifikat detail page (JournalEntryAttachments). */}
|
||||
{!embedded && !editEntryId && (
|
||||
<div>
|
||||
<Label className="mb-2 block">{t('attachments_label')}</Label>
|
||||
<DocumentUploadZone
|
||||
@@ -1194,34 +1241,47 @@ export default function JournalEntryForm({
|
||||
|
||||
<div className="flex flex-col items-end gap-1">
|
||||
<div className="flex gap-2">
|
||||
{!embedded && (
|
||||
{editEntryId ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => setShowClearConfirm(true)}
|
||||
disabled={!hasContent || isSubmitting || isSavingDraft}
|
||||
title={t('clear_all_tooltip')}
|
||||
onClick={handleSaveEdit}
|
||||
disabled={!isBalanced || !description || !selectedPeriod || !!periodMismatch || isSubmitting || isSavingDraft || isUploading || !canWrite}
|
||||
title={!canWrite ? t('read_only_tooltip') : undefined}
|
||||
>
|
||||
<Eraser className="mr-2 h-4 w-4" />
|
||||
{t('clear_all')}
|
||||
{!canWrite ? <Lock className="mr-2 h-4 w-4" /> : isSavingDraft && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{t('save_edit')}
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
{!embedded && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => setShowClearConfirm(true)}
|
||||
disabled={!hasContent || isSubmitting || isSavingDraft}
|
||||
title={t('clear_all_tooltip')}
|
||||
>
|
||||
<Eraser className="mr-2 h-4 w-4" />
|
||||
{t('clear_all')}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleSaveDraft}
|
||||
disabled={!isBalanced || !description || !selectedPeriod || !!periodMismatch || isSubmitting || isSavingDraft || isUploading || !canWrite}
|
||||
title={!canWrite ? t('read_only_tooltip') : t('save_draft_tooltip')}
|
||||
>
|
||||
{!canWrite ? <Lock className="mr-2 h-4 w-4" /> : isSavingDraft && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{t('save_draft')}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleReview}
|
||||
disabled={!isBalanced || !description || !selectedPeriod || !!periodMismatch || isSubmitting || isSavingDraft || isUploading || !canWrite}
|
||||
title={!canWrite ? t('read_only_tooltip') : undefined}
|
||||
>
|
||||
{!canWrite && <Lock className="mr-2 h-4 w-4" />}
|
||||
{t('review_and_create')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleSaveDraft}
|
||||
disabled={!isBalanced || !description || !selectedPeriod || !!periodMismatch || isSubmitting || isSavingDraft || isUploading || !canWrite}
|
||||
title={!canWrite ? t('read_only_tooltip') : t('save_draft_tooltip')}
|
||||
>
|
||||
{!canWrite ? <Lock className="mr-2 h-4 w-4" /> : isSavingDraft && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{t('save_draft')}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleReview}
|
||||
disabled={!isBalanced || !description || !selectedPeriod || !!periodMismatch || isSubmitting || isSavingDraft || isUploading || !canWrite}
|
||||
title={!canWrite ? t('read_only_tooltip') : undefined}
|
||||
>
|
||||
{!canWrite && <Lock className="mr-2 h-4 w-4" />}
|
||||
{t('review_and_create')}
|
||||
</Button>
|
||||
</div>
|
||||
{(!description || !selectedPeriod || isUploading || periodMismatch || incompleteLineCount > 0 || (!isBalanced && submittableLines.length < 2)) && (
|
||||
<div className="text-xs text-muted-foreground space-y-0.5 text-right">
|
||||
|
||||
@@ -106,6 +106,13 @@ export default function JournalEntryList() {
|
||||
const [seriesFilter, setSeriesFilter] = useState<string>('all')
|
||||
const [searchInput, setSearchInput] = useState('')
|
||||
const [search, setSearch] = useState('')
|
||||
// Verifikat (committed) vs Utkast (drafts) view. Drafts are excluded from the
|
||||
// committed list server-side and surfaced here behind a count badge.
|
||||
const [listMode, setListMode] = useState<'committed' | 'drafts'>('committed')
|
||||
// Collapse correction groups to the live correction (hide storno + reversed
|
||||
// original). Toggled off via the filter dialog to reveal the full chain.
|
||||
const [collapseCorrections, setCollapseCorrections] = useState(true)
|
||||
const [draftCount, setDraftCount] = useState(0)
|
||||
const [pageSizeChoice, setPageSizeChoice] = useState<PageSizeChoice>('20')
|
||||
const [pageSizeHydrated, setPageSizeHydrated] = useState(false)
|
||||
const showingAll = pageSizeChoice === 'all'
|
||||
@@ -269,10 +276,18 @@ export default function JournalEntryList() {
|
||||
offset: String(page * pageSize),
|
||||
sort_by: sortBy,
|
||||
})
|
||||
if (periodId) params.set('period_id', periodId)
|
||||
if (dateFrom) params.set('date_from', dateFrom)
|
||||
if (dateTo) params.set('date_to', dateTo)
|
||||
if (seriesFilter !== 'all') params.set('series', seriesFilter)
|
||||
if (listMode === 'drafts') {
|
||||
// Drafts get their own view spanning all years — they're work-in-progress
|
||||
// and shouldn't be hidden by the selected fiscal-year scope.
|
||||
params.set('status', 'draft')
|
||||
} else {
|
||||
params.set('exclude_draft', 'true')
|
||||
if (collapseCorrections) params.set('collapse_corrections', 'true')
|
||||
if (periodId) params.set('period_id', periodId)
|
||||
if (dateFrom) params.set('date_from', dateFrom)
|
||||
if (dateTo) params.set('date_to', dateTo)
|
||||
if (seriesFilter !== 'all') params.set('series', seriesFilter)
|
||||
}
|
||||
if (search) params.set('search', search)
|
||||
|
||||
const res = await fetch(`/api/bookkeeping/journal-entries?${params}`)
|
||||
@@ -289,12 +304,27 @@ export default function JournalEntryList() {
|
||||
// Fetch attachment counts for the loaded entries
|
||||
const ids = loadedEntries.map((e: JournalEntry) => e.id)
|
||||
fetchAttachmentCounts(ids)
|
||||
|
||||
fetchDraftCount()
|
||||
}
|
||||
|
||||
// Cheap count-only query for the "Utkast" badge — all years, so the badge
|
||||
// surfaces drafts regardless of the selected fiscal-year scope.
|
||||
async function fetchDraftCount() {
|
||||
try {
|
||||
const res = await fetch('/api/bookkeeping/journal-entries?status=draft&limit=1')
|
||||
if (!res.ok) return
|
||||
const { count: total } = await res.json()
|
||||
setDraftCount(total || 0)
|
||||
} catch {
|
||||
// Non-fatal: the badge keeps its last value.
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!sortHydrated || !periodHydrated || !pageSizeHydrated) return
|
||||
fetchEntries()
|
||||
}, [periodId, page, pageSize, sortBy, dateFrom, dateTo, seriesFilter, search, sortHydrated, periodHydrated, pageSizeHydrated])
|
||||
}, [periodId, page, pageSize, sortBy, dateFrom, dateTo, seriesFilter, search, listMode, collapseCorrections, sortHydrated, periodHydrated, pageSizeHydrated])
|
||||
|
||||
const handleAttachmentCountChange = useCallback((entryId: string, count: number) => {
|
||||
setAttachmentCounts((prev) => ({ ...prev, [entryId]: count }))
|
||||
@@ -304,6 +334,14 @@ export default function JournalEntryList() {
|
||||
setExpandedId(expandedId === id ? null : id)
|
||||
}
|
||||
|
||||
function switchMode(mode: 'committed' | 'drafts') {
|
||||
if (mode === listMode) return
|
||||
setListMode(mode)
|
||||
setPage(0)
|
||||
setSelectedIds(new Set())
|
||||
if (mode === 'drafts') setShowMissingOnly(false)
|
||||
}
|
||||
|
||||
const handleCommit = async (entryId: string) => {
|
||||
setCommittingId(entryId)
|
||||
try {
|
||||
@@ -714,6 +752,19 @@ export default function JournalEntryList() {
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Reveal the storno + reversed-original rows the default view folds
|
||||
into the surviving correction (3 rows → 1). */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id="show-correction-chain"
|
||||
checked={!collapseCorrections}
|
||||
onCheckedChange={(on) => { setCollapseCorrections(!on); setPage(0) }}
|
||||
/>
|
||||
<Label htmlFor="show-correction-chain" className="text-sm cursor-pointer">
|
||||
{t('show_correction_chain')}
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="sm:justify-between">
|
||||
@@ -733,10 +784,36 @@ export default function JournalEntryList() {
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{/* Verifikat vs Utkast. Drafts live in their own view with a count badge so
|
||||
they don't sink to the last page of the committed list. */}
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="inline-flex rounded-md border border-border p-0.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => switchMode('committed')}
|
||||
className={`h-7 rounded px-3 text-xs font-medium transition-colors ${listMode === 'committed' ? 'bg-secondary text-foreground' : 'text-muted-foreground hover:text-foreground'}`}
|
||||
>
|
||||
{t('mode_vouchers')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => switchMode('drafts')}
|
||||
className={`inline-flex h-7 items-center gap-1.5 rounded px-3 text-xs font-medium transition-colors ${listMode === 'drafts' ? 'bg-secondary text-foreground' : 'text-muted-foreground hover:text-foreground'}`}
|
||||
>
|
||||
{t('mode_drafts')}
|
||||
{draftCount > 0 && (
|
||||
<Badge variant="secondary" className="h-4 min-w-4 justify-center px-1 text-[10px] tabular-nums">
|
||||
{draftCount}
|
||||
</Badge>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Active fiscal-year scope — visible without opening the filter dialog so
|
||||
the user always sees which räkenskapsår the ledger is scoped to (BFL
|
||||
period-correctness). Clicking it opens the dialog to change the scope. */}
|
||||
{periodHydrated && scopeLabel && (
|
||||
{listMode === 'committed' && periodHydrated && scopeLabel && (
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<span>{t('scope_label')}</span>
|
||||
<button
|
||||
|
||||
@@ -45,7 +45,16 @@ export default function NewJournalEntryDialog({
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-3xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto">
|
||||
<DialogContent
|
||||
className="sm:max-w-3xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto"
|
||||
// A half-typed verifikat must survive an accidental click on the
|
||||
// backdrop (easy to do across multiple windows/screens). Closing is
|
||||
// explicit — the header X or Cancel. This also stops nested popovers
|
||||
// (AccountCombobox, date pickers) and the form's own confirm dialogs
|
||||
// from collapsing the parent when they portal outside it.
|
||||
onPointerDownOutside={(e) => e.preventDefault()}
|
||||
onInteractOutside={(e) => e.preventDefault()}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('new_entry_dialog_title')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -54,9 +54,10 @@ import {
|
||||
computeDeduction,
|
||||
} from '@/lib/invoices/rot-rut-rules'
|
||||
import AccrualPeriodControl from '@/components/bookkeeping/AccrualPeriodControl'
|
||||
import AccountCombobox from '@/components/bookkeeping/AccountCombobox'
|
||||
import { DEFAULT_DEFERRED_REVENUE_ACCOUNT } from '@/lib/bookkeeping/accruals/account-suggestions'
|
||||
import { countCalendarMonths } from '@/lib/bookkeeping/accruals/compute'
|
||||
import type { Customer, Currency, CreateInvoiceInput, CreateCustomerInput, InvoiceDocumentType, Article, Invoice, InvoiceItem } from '@/types'
|
||||
import type { Customer, Currency, CreateInvoiceInput, CreateCustomerInput, InvoiceDocumentType, Article, Invoice, InvoiceItem, BASAccount } from '@/types'
|
||||
|
||||
const currencies: Currency[] = ['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK']
|
||||
const units = ['st', 'tim', 'dag', 'månad', 'km', 'kg']
|
||||
@@ -212,6 +213,10 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
// 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)
|
||||
// Class-3 (revenue) accounts for the optional per-line försäljningskonto
|
||||
// override, plus which rows currently show that picker.
|
||||
const [revenueAccounts, setRevenueAccounts] = useState<BASAccount[]>([])
|
||||
const [accountOverrideRows, setAccountOverrideRows] = useState<Set<number>>(new Set())
|
||||
// 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.
|
||||
@@ -349,6 +354,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
fetchCustomers()
|
||||
fetchDefaultNotes()
|
||||
fetchArticles()
|
||||
fetchRevenueAccounts()
|
||||
}, [company?.id])
|
||||
|
||||
async function fetchArticles() {
|
||||
@@ -362,6 +368,17 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
setArticles((data ?? []) as ArticleOption[])
|
||||
}
|
||||
|
||||
async function fetchRevenueAccounts() {
|
||||
if (!company?.id) return
|
||||
try {
|
||||
const res = await fetch('/api/bookkeeping/accounts?class=3')
|
||||
const body = await res.json()
|
||||
setRevenueAccounts((body?.data as BASAccount[]) || [])
|
||||
} catch {
|
||||
// Non-fatal: the override picker degrades to free 4-digit entry.
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -431,13 +448,18 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
if (!company?.id) return
|
||||
const { data } = await supabase
|
||||
.from('company_settings')
|
||||
.select('invoice_default_notes, clearing_number, account_number, bankgiro, accounting_method, ore_rounding, logo_url, vat_registered')
|
||||
.select('invoice_default_notes, default_our_reference, clearing_number, account_number, bankgiro, accounting_method, ore_rounding, logo_url, vat_registered')
|
||||
.eq('company_id', company.id)
|
||||
.single()
|
||||
if (data?.invoice_default_notes) {
|
||||
setDefaultNotes(data.invoice_default_notes)
|
||||
setValue('notes', data.invoice_default_notes)
|
||||
}
|
||||
// Pre-fill "Vår referens" from the company default — only when creating a
|
||||
// fresh invoice, so an edited draft's own reference is never overwritten.
|
||||
if (!isEditMode && data?.default_our_reference) {
|
||||
setValue('our_reference', data.default_our_reference)
|
||||
}
|
||||
setHasBankDetails(
|
||||
!!(data?.clearing_number && data?.account_number) || !!data?.bankgiro
|
||||
)
|
||||
@@ -669,6 +691,22 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
}
|
||||
}
|
||||
|
||||
// Open/close the optional per-line försäljningskonto override. Closing clears
|
||||
// the value so the engine falls back to the VAT-rate-derived revenue account.
|
||||
function toggleAccountOverride(index: number) {
|
||||
const isOpen = accountOverrideRows.has(index) || !!watchItems[index]?.revenue_account
|
||||
if (isOpen) {
|
||||
setValue(`items.${index}.revenue_account`, null, { shouldDirty: true })
|
||||
setAccountOverrideRows((prev) => {
|
||||
const next = new Set(prev)
|
||||
next.delete(index)
|
||||
return next
|
||||
})
|
||||
} else {
|
||||
setAccountOverrideRows((prev) => new Set(prev).add(index))
|
||||
}
|
||||
}
|
||||
|
||||
// Self-billing path: no review dialog, no PDF, no send — it arrives already
|
||||
// booked. POST straight to the dedicated endpoint and open the verifikat.
|
||||
async function handleSelfBilledSubmit(data: FormData) {
|
||||
@@ -1283,6 +1321,17 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
{watchItems[index]?.line_type !== 'text' && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onSelect={() => toggleAccountOverride(index)} className="py-2">
|
||||
<Landmark className="h-4 w-4" />
|
||||
{(accountOverrideRows.has(index) || watchItems[index]?.revenue_account)
|
||||
? t('row_menu_remove_account')
|
||||
: t('row_menu_set_account')}
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
className="py-2 text-destructive focus:text-destructive"
|
||||
@@ -1574,6 +1623,34 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Optional försäljningskonto override (engångsartikel). When
|
||||
unset the engine derives the revenue account from the VAT
|
||||
rate; reverse-charge/export lines ignore the override. */}
|
||||
{isInvoiceDoc && watchItems[index]?.line_type !== 'text' &&
|
||||
(accountOverrideRows.has(index) || watchItems[index]?.revenue_account) && (
|
||||
<div className="md:col-span-12 mt-2 md:mt-3">
|
||||
<div className="flex flex-wrap items-end gap-2">
|
||||
<div className="min-w-[220px] flex-1 space-y-1 md:space-y-2">
|
||||
<Label className="text-xs text-muted-foreground md:text-sm md:text-foreground">
|
||||
{t('revenue_account_label')}
|
||||
</Label>
|
||||
<Controller
|
||||
name={`items.${index}.revenue_account`}
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<AccountCombobox
|
||||
value={field.value ?? ''}
|
||||
accounts={revenueAccounts}
|
||||
onChange={(v) => field.onChange(v || null)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{t('revenue_account_hint')}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Mobile summary row */}
|
||||
<div className="flex justify-between text-sm pt-1 border-t border-border/40 md:hidden">
|
||||
<span className="text-muted-foreground">{t('row_label', { index: index + 1 })}</span>
|
||||
|
||||
@@ -155,6 +155,7 @@ interface ApiKey {
|
||||
name: string
|
||||
scopes: string[] | null
|
||||
rate_limit_rpm: number
|
||||
mode?: 'live' | 'test'
|
||||
last_used_at: string | null
|
||||
revoked_at: string | null
|
||||
created_at: string
|
||||
@@ -252,6 +253,10 @@ export function ApiKeysPanel() {
|
||||
const [showKeyDialog, setShowKeyDialog] = useState(false)
|
||||
const [showApiKeyMethods, setShowApiKeyMethods] = useState(false)
|
||||
const [newKeyName, setNewKeyName] = useState('')
|
||||
// 'live' by default: this is the general MCP-key surface and the dominant case
|
||||
// is a key for the user's real company. 'test' is an explicit opt-in — a
|
||||
// simulation-only key that forces dry-run on every write (nothing is saved).
|
||||
const [newKeyMode, setNewKeyMode] = useState<'live' | 'test'>('live')
|
||||
const [newKeyScopes, setNewKeyScopes] = useState<Set<Scope>>(new Set(ALL_SCOPES))
|
||||
const [newKeyValue, setNewKeyValue] = useState('')
|
||||
const [copied, setCopied] = useState(false)
|
||||
@@ -305,13 +310,21 @@ export function ApiKeysPanel() {
|
||||
body: JSON.stringify({
|
||||
name: newKeyName || t('default_key_name'),
|
||||
scopes: Array.from(newKeyScopes),
|
||||
mode: newKeyMode,
|
||||
...(hasSodConflict ? { acknowledge_sod: true } : {}),
|
||||
}),
|
||||
})
|
||||
const json = await res.json()
|
||||
|
||||
if (!res.ok) {
|
||||
toast({ title: json.error, variant: 'destructive' })
|
||||
// The route returns the canonical { error: { code, message, message_en } }
|
||||
// envelope — render the message string, never the object (a React child
|
||||
// must be a string, not { code, message, ... }).
|
||||
const message =
|
||||
typeof json.error === 'string'
|
||||
? json.error
|
||||
: json.error?.message ?? t('toast_create_failed')
|
||||
toast({ title: message, variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
|
||||
@@ -319,6 +332,7 @@ export function ApiKeysPanel() {
|
||||
setShowCreateDialog(false)
|
||||
setShowKeyDialog(true)
|
||||
setNewKeyName('')
|
||||
setNewKeyMode('live')
|
||||
setNewKeyScopes(new Set(ALL_SCOPES))
|
||||
fetchKeys()
|
||||
} catch {
|
||||
@@ -413,6 +427,11 @@ export function ApiKeysPanel() {
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-sm font-medium truncate">{key.name}</p>
|
||||
{key.mode === 'test' && (
|
||||
<Badge variant="secondary" className="shrink-0 text-[10px] font-normal px-1.5 py-0">
|
||||
{t('badge_test')}
|
||||
</Badge>
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{scopeCount === ALL_SCOPES.length
|
||||
? t('all_permissions')
|
||||
@@ -547,6 +566,31 @@ export function ApiKeysPanel() {
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleCreate()}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>{t('mode_label')}</Label>
|
||||
<div className="inline-flex rounded-md border p-0.5" role="radiogroup" aria-label={t('mode_label')}>
|
||||
{(['live', 'test'] as const).map((m) => (
|
||||
<button
|
||||
key={m}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={newKeyMode === m}
|
||||
onClick={() => setNewKeyMode(m)}
|
||||
className={cn(
|
||||
'rounded-[5px] px-3 py-1.5 text-xs transition-colors',
|
||||
newKeyMode === m
|
||||
? 'bg-secondary text-foreground'
|
||||
: 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{t(m === 'live' ? 'mode_live' : 'mode_test')}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{newKeyMode === 'test' ? t('mode_test_help') : t('mode_live_help')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-baseline justify-between gap-3">
|
||||
<div className="space-y-1">
|
||||
|
||||
@@ -63,6 +63,19 @@ export function InvoiceSettingsForm({ settings }: InvoiceSettingsFormProps) {
|
||||
{t('default_notes_help')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="default_our_reference">{t('default_our_reference_label')}</Label>
|
||||
<Input
|
||||
id="default_our_reference"
|
||||
name="default_our_reference"
|
||||
placeholder={t('default_our_reference_placeholder')}
|
||||
defaultValue={settings.default_our_reference || ''}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('default_our_reference_help')}
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useTranslations } from 'next-intl'
|
||||
import { useState, useCallback } from 'react'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import type { CompanySettings } from '@/types'
|
||||
@@ -112,15 +113,17 @@ export function PdfPrintSettings({ settings, onUpdate }: PdfPrintSettingsProps)
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
{/* Swish on invoices is "coming soon" — the toggle is disabled until the
|
||||
payment-QR flow ships (gated by SHOW_SWISH_ON_INVOICE in pdf-template). */}
|
||||
<div className="flex items-center justify-between opacity-60">
|
||||
<div>
|
||||
<Label>{t('show_swish_label')}</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Label>{t('show_swish_label')}</Label>
|
||||
<Badge variant="secondary" className="text-[10px]">{t('coming_soon')}</Badge>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{t('show_swish_help')}</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={settings.invoice_show_swish ?? false}
|
||||
onCheckedChange={(v) => saveToggle('invoice_show_swish', v)}
|
||||
/>
|
||||
<Switch checked={false} disabled aria-label={t('show_swish_label')} />
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
|
||||
@@ -42,6 +42,7 @@ export function InvoicingSettingsContent() {
|
||||
next_invoice_number: parseInt(formData.get('next_invoice_number') as string) || 1,
|
||||
invoice_default_days: parseInt(formData.get('invoice_default_days') as string) || 30,
|
||||
invoice_default_notes: (formData.get('invoice_default_notes') as string) || null,
|
||||
default_our_reference: (formData.get('default_our_reference') as string) || null,
|
||||
}
|
||||
return {
|
||||
updates,
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"email": "[email protected]",
|
||||
"name": "API Test Kund AB",
|
||||
"customer_type": "swedish_business"
|
||||
}
|
||||
@@ -1061,6 +1061,7 @@ export const UpdateSettingsSchema = z.object({
|
||||
next_invoice_number: z.number().int().positive().optional(),
|
||||
invoice_default_days: z.number().int().positive().optional(),
|
||||
invoice_default_notes: z.string().nullable().optional(),
|
||||
default_our_reference: z.string().max(200).nullable().optional(),
|
||||
phone: z.string().optional(),
|
||||
email: z.string().email().optional().or(z.literal('')),
|
||||
website: z.string().optional().or(z.literal('')),
|
||||
|
||||
@@ -388,6 +388,76 @@ describe('withApiV1 — dry-run', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('withApiV1 — test mode', () => {
|
||||
it('blocks a test-key write on a non-simulatable endpoint (403 TEST_KEY_WRITE_BLOCKED)', async () => {
|
||||
// No route modules are imported here, so the endpoint registry is empty →
|
||||
// getEndpointByConcretePath returns undefined → the wrapper must refuse the
|
||||
// write rather than let a test key mutate real data.
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
scopes: ['invoices:write'],
|
||||
mode: 'test',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub({ company_id: 'company-1', role: 'owner' }))
|
||||
|
||||
let handlerCalled = false
|
||||
const handler = withApiV1(
|
||||
'invoices.create',
|
||||
async (_req, ctx) => {
|
||||
handlerCalled = true
|
||||
return ok({ ok: true }, { requestId: ctx.requestId })
|
||||
},
|
||||
{ requireScope: 'invoices:write' },
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1/invoices', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x', 'Content-Type': 'application/json' },
|
||||
body: '{}',
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('TEST_KEY_WRITE_BLOCKED')
|
||||
expect(handlerCalled).toBe(false)
|
||||
})
|
||||
|
||||
it('allows a test-key READ unchanged — no forced dry-run, real data, X-Gnubok-Mode header', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
scopes: ['companies:read'],
|
||||
mode: 'test',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(makeSupabaseStub({ company_id: 'company-1', role: 'owner' }))
|
||||
|
||||
let observedDryRun: boolean | null = null
|
||||
const handler = withApiV1(
|
||||
'companies.get',
|
||||
async (_req, ctx) => {
|
||||
observedDryRun = ctx.dryRun
|
||||
return ok({ ok: true }, { requestId: ctx.requestId })
|
||||
},
|
||||
{ requireScope: 'companies:read' },
|
||||
)
|
||||
|
||||
const res = await handler(
|
||||
makeRequest('https://x.test/api/v1/companies/company-1', {
|
||||
headers: { Authorization: 'Bearer gnubok_sk_x' },
|
||||
}),
|
||||
companyParams('company-1'),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(observedDryRun).toBe(false)
|
||||
expect(res.headers.get('X-Gnubok-Mode')).toBe('test')
|
||||
})
|
||||
})
|
||||
|
||||
describe('withApiV1 — public endpoints', () => {
|
||||
it('invokes the handler without authentication for /api/v1/health', async () => {
|
||||
let observedUserId: string | null = null
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user