fix: GH issues batch: deadlines opt-ins, SKV reconnect, narrative edit, payment-link gating (#1076)
* fix(errors): close remaining raw-message leaks after #1048 (#337) Follow-up to PR #1048. No user-visible toast or response field can now carry a raw engine or DB message; everything maps through getErrorMessage or the structured-errors registry. - get-error-message: only normalize a code-carrying Error instance into the structured path when the registry knows the code; unknown codes (Node system errors, stray third-party codes, Error-wrapped Postgres SQLSTATEs) fall through to pattern match, Swedish check, Postgres map and the status/context/generic fallbacks instead of returning the raw message. New Swedish-detection pattern for "ar last" phrases and a known-pattern row for "already has a journal entry". - structured-errors: add CANNOT_EDIT_NON_DRAFT (409) and MANDATORY_DIMENSION_MISSING (400) rows, plus common Node network codes (ECONNREFUSED, ECONNRESET, ETIMEDOUT, ENOTFOUND, EAI_AGAIN, EPIPE) as retryable 503 transients with a Swedish message. - pending-operations commit + bulk-commit routes: map executor error strings through getErrorMessage before responding (raw stays in logs); Swedish passes through, English falls to status-appropriate Swedish. - pending page: toast via getErrorMessage, fixing raw English toasts and "[object Object]" for structured envelopes on commit/bulk/reject. - transactions book + journal-entries routes: untyped catch and DB list errors no longer return err.message; mapped or static Swedish instead. - invoice send + issue-credit-note: partial_failures reasons are now Swedish (raw provider/DB text logged, never returned). - Tests: new unknown-code/Error-instance suite, registry rows asserted, route tests updated off the pinned raw-English expectations. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(skatteverket): target the räkenskapsår for yearly VAT redovisningsperiod A yearly filer with a broken fiscal year has a Skatteverket period ending in its FY-end month, not December, and the panel's year state is never maintained in yearly mode (the year picker is replaced by the räkenskapsår selector), so calls targeted the wrong period even for calendar-FY companies filing after year end. The selected fiscal period now rides through the whole chain: panel query strings, draft/validate/ submit bodies, buildMomsuppgift (which resolves the FY bounds so the period id and the figures describe the same räkenskapsår), and the staged-commit path. MCP callers without a fiscal period keep the calendar fallback. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(deadlines): group same-day skattekonto deadlines into one card Moms, AGI and preliminärskatt legally share the skattekonto date (den 12:e), so a small monthly-moms employer saw 2-3 near-identical rows per month. Two or more pending system rows of the skattekonto family on the same due date now render as one grouped card with the date block once and each obligation as a sub-row keeping its own confirm-to-complete flow. Presentation only: rows, statuses, ICS feed unchanged. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(deadlines): KU + ROT/RUT + long-tail opt-in deadlines, rolling horizon Follow-ups from the #1028 audit left out of the #1057-#1060 fix stack, each with its own condition modeling: - kontrolluppgifter (KU10/KU20/KU31), due 31 Jan (SFL 24 kap. 1 §): opt-in flag suggested from ledger signals (2898 utdelning, 2393/2893 ägarlån; deliberately not 2091, see DECISIONS.md), AB only, mirroring the #1059 EU-sales suggest-and-confirm pattern. - rot_rut_begaran, due 31 Jan after the payment year (Lag 2009:194 8 §): rows generated only for years with actually PAID ROT/RUT invoices, resolved inside the generator; invoice-derived suggestion. - Long tail, explicit opt-in ('Fler deadlines'): OSS quarterly and IOSS monthly with a skipBankingDayAdjustment config flag (EU-law dates stand on weekends), Intrastat (10th banking day of the following month), punktskatt (ordinary skattedeklaration schedule), and fyllnadsinbetalning (12th of 2nd month over 30k / 3rd of 5th month, SFL 62:8 + 65 kap.). Kvarskatt deferred: needs a slutskattebesked date the app does not hold. - Rolling generation horizon: recurring types ~6 months ahead, annual 12 months, mirrored in the backfill expectation keys so the nightly cron never thrashes; regeneration now preserves manual in_progress status; one-time cleanup migration removes existing far-future rows. Migrations also applied to the staging branch, together with the previously missing 20260717xxxxxx deadline migrations (staging had drifted and lacked dismissed_at). Co-Authored-By: Claude Fable 5 <[email protected]> * fix(arsredovisning): keep narrative editable after year-end close The narrative save endpoint refused writes whenever the fiscal period was closed/locked, but Verkstall bokslut closes the period before the arsredovisning text is ever written, so every legitimate save failed with PERIOD_LOCKED and the PDF fell back to placeholder text. The narrative is arsredovisning document text (ARL 6 kap.), not journal rakenskapsinformation, so the bookkeeping period lock does not apply. Saves are now refused only once a Bolagsverket submission for the period is registrerad (ARSREDOVISNING_REGISTERED, 409); the filed artifact was already frozen separately by the submissions immutability trigger. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(skatteverket): surface dead SKV connections and nudge reconnect Prod has ~70 companies that connected Skatteverket before the post-connect sync fix (#1010) and silently never synced skattekonto: the only reconnect prompt lived in the settings panel nobody revisits. - transactions-page banner when the connection is needs_reconsent or expired without refresh, linking to /settings/tax - pre-connect note in the connect panel: approve ALL behorigheter on Skatteverket's consent page (previously only shown after a failure) - wire the inert skattekonto.connection.expired event to an email nudge to the token owner; one send per consent episode via claim-first dedup in notification_log (type skv_connection_expired, partial unique index in migration 20260720090000, applied to staging) Co-Authored-By: Claude Fable 5 <[email protected]> * fix(archive): per-year behandlingshistorik covers late-booked vouchers + Drive backup disclaimer The per-fiscal-year archive filtered audit rows by created_at within the period, dropping treatment history for bokslut entries, stornos and SIE imports booked after year end (BFNAR 2013:2 kap 8). The year archive now unions the date window with every audit row touching the period's journal entries and lines, deduped by audit id; line rows (company_id NULL by trigger design) are admitted via a scoped OR and reachable on the service-role backup path. ARCHIVE_FORMAT_VERSION 2->3 forces a one-time Drive re-upload so existing archives pick up the complete history. The Drive card on /import Exportera and the LASMIG texts now state the Drive copy is a convenience backup, not the BFL 7 kap legal archive. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(decisions): clarify Arsredovisning narrative save behavior on submission status * feat(invoices): gate payment links behind invoice settings opt-in The payment-link section (manual URL field + Stripe auto-create toggle) was visible on every invoice and auto-created Stripe links on send for any connected company. It is now opt-in per company: - new company_settings.invoice_payment_links_enabled, default false for everyone (no grandfathering of Stripe-connected companies) - invoice editor hides the whole section unless enabled; a draft that already carries a link still shows it so old links stay clearable - enforced server-side in maybeCreatePaymentLinkForInvoice (after the provider lookup, so the extension-free core build never queries), so dashboard, v1, MCP and recurring sends all obey it - new toggle on Settings -> Invoicing, saves instantly; sv/en strings Migration applied to the staging branch; prod gets it on merge. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(tests): add invoice_payment_links_enabled to company settings fixture The makeCompanySettings fixture missed the new required boolean, failing the core-only build's type check of tests/helpers.ts. Default false, matching the migration default. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Emil <[email protected]> * fix(review): address CodeRabbit, compliance and Swedish review findings Round 2 of PR #1076 review feedback, one change per accepted finding: - pending page: res.json() safe fallback in both commit paths so a non-JSON proxy response cannot surface a raw parser error - bulk-commit: map operation status enums to Swedish display labels in the 'Redan hanterad' skip message - payment-link settings: disable the toggle while a save is in flight to prevent out-of-order PUT responses - deadlines group card: route all UI strings through next-intl (deadlines namespace, sv + en) - archive export: scope the period audit entry lookup to posted/reversed, matching the rest of the export - error tests: assert the exact registry English message for ECONNREFUSED to lock the no-leakage contract - signal routes: log.warn when best-effort lookups swallow a Supabase error (forensics), keep fail-closed behavior - narrative route: document that 'avslutad' submissions deliberately stay editable (never registered at Bolagsverket) - VAT: yearly declarations without an explicit fiscalPeriodId now resolve the räkenskapsår ending in the target year from fiscal_periods instead of assuming a calendar FY (SFL 26 kap 10-11 §§); calendar fallback only when no fiscal period exists - deadlines: IOSS deadline no longer requires vat_registered (Art. 369s has no Swedish VAT registration prerequisite) Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Emil <[email protected]> --------- Signed-off-by: Emil <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5
parent
0fbb0f8fa8
commit
87f0d5af48
File diff suppressed because one or more lines are too long
@@ -38,6 +38,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import {
|
||||
ClipboardCheck,
|
||||
@@ -761,8 +762,11 @@ export default function PendingOperationsPage() {
|
||||
setIsCommitting(true)
|
||||
try {
|
||||
const res = await fetch(`/api/pending-operations/${selectedOp.id}/commit`, { method: 'POST' })
|
||||
const json = await res.json()
|
||||
if (!res.ok) throw new Error(json.error || 'Misslyckades')
|
||||
const json = await res.json().catch(() => ({}))
|
||||
// getErrorMessage handles both `{ error: string }` and the structured
|
||||
// `{ error: { code, message } }` envelope (the latter would otherwise
|
||||
// toast "[object Object]") and never surfaces raw English.
|
||||
if (!res.ok) throw new Error(getErrorMessage(json, { statusCode: res.status }))
|
||||
toast({ title: 'Godkänd', description: selectedOp.title })
|
||||
setShowCommitDialog(false)
|
||||
setSelectedOp(null)
|
||||
@@ -787,8 +791,8 @@ export default function PendingOperationsPage() {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids }),
|
||||
})
|
||||
const json = await res.json()
|
||||
if (!res.ok) throw new Error(json.error || 'Misslyckades')
|
||||
const json = await res.json().catch(() => ({}))
|
||||
if (!res.ok) throw new Error(getErrorMessage(json, { statusCode: res.status }))
|
||||
|
||||
const summary = json.data?.summary as
|
||||
| { committed: number; failed: number; skipped: number; rejected: number }
|
||||
@@ -849,7 +853,7 @@ export default function PendingOperationsPage() {
|
||||
})
|
||||
if (!res.ok) {
|
||||
const json = await res.json().catch(() => ({}))
|
||||
throw new Error(json.error || 'Misslyckades')
|
||||
throw new Error(getErrorMessage(json, { statusCode: res.status }))
|
||||
}
|
||||
toast({ title: 'Avvisad', description: rejectOp.title })
|
||||
setRejectOp(null)
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { ChevronDown, EyeOff, Layers, Search, Trash2, X } from 'lucide-react'
|
||||
import { ChevronDown, EyeOff, Layers, Search, ShieldAlert, Trash2, X } from 'lucide-react'
|
||||
import TransactionForm from '@/components/transactions/TransactionForm'
|
||||
import BatchCategorySelector from '@/components/transactions/BatchCategorySelector'
|
||||
import TransactionStatusBar from '@/components/transactions/TransactionStatusBar'
|
||||
@@ -270,6 +270,11 @@ export default function TransactionsPage() {
|
||||
const [skvMatchTarget, setSkvMatchTarget] = useState<StoredSkattekontoTransaction | null>(
|
||||
null,
|
||||
)
|
||||
// True when an SKV connection exists but is dead (needs_reconsent, or
|
||||
// expired with no refresh left). Drives the reconnect banner: without it
|
||||
// a user whose token died sees an empty skattekonto and has no reason to
|
||||
// ever visit the settings panel where the reconnect prompt lives.
|
||||
const [skvNeedsReconnect, setSkvNeedsReconnect] = useState(false)
|
||||
|
||||
// Source filter for the merged inbox. Defaults to 'all' so users see
|
||||
// both sources unless they want to narrow down.
|
||||
@@ -361,6 +366,33 @@ export default function TransactionsPage() {
|
||||
const PAGE_SIZE = 200
|
||||
|
||||
const loadSkvRows = useCallback(async () => {
|
||||
// Connection health, fetched alongside the rows: any failure (extension
|
||||
// disabled, capability gate, not connected) just hides the banner.
|
||||
void (async () => {
|
||||
try {
|
||||
const res = await fetch('/api/extensions/ext/skatteverket/status')
|
||||
if (!res.ok) {
|
||||
setSkvNeedsReconnect(false)
|
||||
return
|
||||
}
|
||||
const s = (await res.json()) as {
|
||||
connected?: boolean
|
||||
disabled?: boolean
|
||||
needsReconsent?: boolean
|
||||
expired?: boolean
|
||||
canRefresh?: boolean
|
||||
}
|
||||
setSkvNeedsReconnect(
|
||||
Boolean(
|
||||
s.connected &&
|
||||
!s.disabled &&
|
||||
(s.needsReconsent || (s.expired && !s.canRefresh)),
|
||||
),
|
||||
)
|
||||
} catch {
|
||||
setSkvNeedsReconnect(false)
|
||||
}
|
||||
})()
|
||||
try {
|
||||
const res = await fetch('/api/extensions/ext/skatteverket/skattekonto/transaktioner')
|
||||
if (!res.ok) {
|
||||
@@ -2093,6 +2125,19 @@ export default function TransactionsPage() {
|
||||
</div>
|
||||
<BankSyncSinceLastVisit />
|
||||
|
||||
{skvNeedsReconnect && (
|
||||
<div className="flex flex-wrap items-start gap-3 rounded-lg border border-border bg-secondary/40 p-4 text-sm">
|
||||
<ShieldAlert className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<p className="font-medium">{t('skv_reconnect_title')}</p>
|
||||
<p className="text-muted-foreground">{t('skv_reconnect_body')}</p>
|
||||
</div>
|
||||
<Button asChild variant="outline" size="sm" className="shrink-0">
|
||||
<Link href="/settings/tax">{t('skv_reconnect_cta')}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Search + view dropdown */}
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative flex-1">
|
||||
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* Tests for GET/POST /api/bookkeeping/fiscal-periods/[id]/arsredovisning/narrative.
|
||||
*
|
||||
* Regression focus: the narrative must stay editable after the fiscal period
|
||||
* is closed/locked (Verkställ bokslut). The normal flow closes the books
|
||||
* BEFORE the årsredovisning text is written, so gating the save on the
|
||||
* period lock made every legitimate save fail. Edits are refused only once
|
||||
* a Bolagsverket submission for the period is registrerad.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, createQueuedMockSupabase, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
import { GET, POST } from '../route'
|
||||
|
||||
const idParams = { params: Promise.resolve({ id: 'period-1' }) }
|
||||
|
||||
const narrativeRow = {
|
||||
id: 'narrative-1',
|
||||
company_id: 'company-1',
|
||||
fiscal_period_id: 'period-1',
|
||||
description: 'Bolaget bedriver konsultverksamhet.',
|
||||
important_events: null,
|
||||
resultatdisposition: null,
|
||||
agm_date: null,
|
||||
long_term_debt_over_five_years: null,
|
||||
securities_pledged: null,
|
||||
contingent_liabilities: null,
|
||||
parent_company_name: null,
|
||||
parent_company_org_number: null,
|
||||
parent_company_city: null,
|
||||
updated_at: '2026-01-15T10:00:00Z',
|
||||
}
|
||||
|
||||
function setupSupabase() {
|
||||
const mock = createQueuedMockSupabase()
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: { id: 'user-1' },
|
||||
supabase: mock.supabase,
|
||||
error: null,
|
||||
})
|
||||
return mock
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
describe('GET /api/bookkeeping/fiscal-periods/[id]/arsredovisning/narrative', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: {},
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const res = await GET(createMockRequest('/x'), idParams)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 404 when the period does not belong to the company', async () => {
|
||||
const { enqueue } = setupSupabase()
|
||||
enqueue({ data: null }) // fiscal_periods ownership check
|
||||
const res = await GET(createMockRequest('/x'), idParams)
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('returns the persisted narrative', async () => {
|
||||
const { enqueue } = setupSupabase()
|
||||
enqueue({ data: { id: 'period-1' } }) // fiscal_periods ownership check
|
||||
enqueue({ data: narrativeRow }) // getNarrative
|
||||
const { status, body } = await parseJsonResponse<{ data: typeof narrativeRow }>(
|
||||
await GET(createMockRequest('/x'), idParams),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.description).toBe('Bolaget bedriver konsultverksamhet.')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/bookkeeping/fiscal-periods/[id]/arsredovisning/narrative', () => {
|
||||
const postReq = (body: unknown) => createMockRequest('/x', { method: 'POST', body })
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: {},
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const res = await POST(postReq({ description: 'x' }), idParams)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 403 when the caller lacks write permission', async () => {
|
||||
setupSupabase()
|
||||
requireWriteMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'forbidden' }, { status: 403 }),
|
||||
})
|
||||
const res = await POST(postReq({ description: 'x' }), idParams)
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
|
||||
it('returns 400 on invalid payload', async () => {
|
||||
setupSupabase()
|
||||
const res = await POST(postReq({ agm_date: '2026-13-99' }), idParams)
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when the period does not belong to the company', async () => {
|
||||
const { enqueue } = setupSupabase()
|
||||
enqueue({ data: null }) // fiscal_periods ownership check
|
||||
const res = await POST(postReq({ description: 'x' }), idParams)
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('saves the narrative for a closed/locked period (regression)', async () => {
|
||||
const { enqueue } = setupSupabase()
|
||||
// The ownership check no longer selects lock columns: a closed period
|
||||
// (Verkställ bokslut done) must still accept narrative saves.
|
||||
enqueue({ data: { id: 'period-1' } }) // fiscal_periods ownership check
|
||||
enqueue({ data: null }) // no registrerad submission
|
||||
enqueue({ data: narrativeRow }) // upsert
|
||||
const { status, body } = await parseJsonResponse<{ data: typeof narrativeRow }>(
|
||||
await POST(postReq({ description: 'Bolaget bedriver konsultverksamhet.' }), idParams),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.description).toBe('Bolaget bedriver konsultverksamhet.')
|
||||
})
|
||||
|
||||
it('refuses the save once the årsredovisning is registered at Bolagsverket', async () => {
|
||||
const { enqueue } = setupSupabase()
|
||||
enqueue({ data: { id: 'period-1' } }) // fiscal_periods ownership check
|
||||
enqueue({ data: { id: 'submission-1' } }) // registrerad submission exists
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await POST(postReq({ description: 'x' }), idParams),
|
||||
)
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('ARSREDOVISNING_REGISTERED')
|
||||
})
|
||||
})
|
||||
@@ -113,19 +113,41 @@ export const POST = withRouteContext(
|
||||
try {
|
||||
// Verify the fiscal period belongs to the authenticated company before
|
||||
// writing: defense-in-depth alongside RLS, gives a cleaner 404 than
|
||||
// the RLS rejection envelope. Also refuse mutations on locked/closed
|
||||
// periods (BFL 5 kap 5 §, räkenskapsinformation immutability).
|
||||
// the RLS rejection envelope.
|
||||
//
|
||||
// Deliberately NOT gated on the bookkeeping period lock: the narrative
|
||||
// is årsredovisning document text (ÅRL 6 kap.), not räkenskapsinformation
|
||||
// in the journal, and the normal flow closes the period BEFORE the
|
||||
// årsredovisning is written. The document freezes when it is filed:
|
||||
// a Bolagsverket submission registered for this period makes the text
|
||||
// read-only (what was uploaded is already immutable via the
|
||||
// arsredovisning_submissions trigger + stored document).
|
||||
const { data: period } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.select('id, is_closed, locked_at, closing_entry_id')
|
||||
.select('id')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
if (!period) {
|
||||
return errorResponseFromCode('PERIOD_NOT_FOUND', log, { requestId })
|
||||
}
|
||||
if (period.is_closed || period.locked_at || period.closing_entry_id) {
|
||||
return errorResponseFromCode('PERIOD_LOCKED', log, { requestId })
|
||||
// Only 'registrerad' freezes the text. 'avslutad' (case closed WITHOUT
|
||||
// registration, e.g. withdrawn or rejected) deliberately stays
|
||||
// editable: the document was never registered at Bolagsverket and a
|
||||
// refiling needs amendable narrative text.
|
||||
const { data: registered, error: registeredError } = await supabase
|
||||
.from('arsredovisning_submissions')
|
||||
.select('id')
|
||||
.eq('company_id', companyId)
|
||||
.eq('fiscal_period_id', id)
|
||||
.eq('status', 'registrerad')
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
if (registeredError) {
|
||||
throw new Error(`Failed to check submission status: ${registeredError.message}`)
|
||||
}
|
||||
if (registered) {
|
||||
return errorResponseFromCode('ARSREDOVISNING_REGISTERED', log, { requestId })
|
||||
}
|
||||
const data = await upsertNarrative(supabase, companyId, user.id, id, validation.data)
|
||||
return NextResponse.json({ data })
|
||||
|
||||
@@ -27,7 +27,12 @@ export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 404 })
|
||||
// PostgREST's "no rows" message is raw English; the user just needs to
|
||||
// know the verifikat is gone (matches JOURNAL_ENTRY_NOT_FOUND registry).
|
||||
return NextResponse.json(
|
||||
{ error: 'Verifikationen kunde inte hittas.' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
@@ -106,8 +111,11 @@ export const PATCH = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
} catch (err) {
|
||||
const typed = bookkeepingErrorResponse(err)
|
||||
if (typed) return typed
|
||||
// Untyped errors map to Swedish via getErrorMessage: the raw message is
|
||||
// logged here and must never reach the user verbatim (issue #337).
|
||||
logger.error('failed to update draft journal entry', { entryId: id, error: err })
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Failed to update journal entry' },
|
||||
{ error: getErrorMessage(err, { context: 'journal_entry' }) },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -179,7 +179,8 @@ describe('GET /api/bookkeeping/journal-entries', () => {
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(500)
|
||||
expect(body.error).toBe('DB error')
|
||||
// Raw Supabase messages never reach the response field (issue #337).
|
||||
expect(body.error).toBe('Verifikationerna kunde inte hämtas. Försök igen.')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -255,6 +256,7 @@ describe('POST /api/bookkeeping/journal-entries', () => {
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toBe('Unbalanced entry')
|
||||
// Untyped engine errors map to the Swedish context fallback (issue #337).
|
||||
expect(body.error).toBe('Kunde inte hantera verifikationen. Försök igen.')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -6,6 +6,7 @@ import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CreateJournalEntrySchema } from '@/lib/api/schemas'
|
||||
import { escapeLikePattern } from '@/lib/invoices/duplicate-payment-guard'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
@@ -13,7 +14,7 @@ ensureInitialized()
|
||||
// each param's comment) rather than a Zod schema; response shapes are legacy
|
||||
// `{ data, count }` / `{ error: string }` for the verifikat list UI.
|
||||
export const GET = withRouteContext('bookkeeping.journal_entries.list', async (request, ctx) => {
|
||||
const { supabase, companyId } = ctx
|
||||
const { supabase, companyId, log } = ctx
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
@@ -88,7 +89,11 @@ export const GET = withRouteContext('bookkeeping.journal_entries.list', async (r
|
||||
})
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
log.error('failed to list fiscal period entries via RPC', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Verifikationerna kunde inte hämtas. Försök igen.' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
const rows = data ?? []
|
||||
@@ -180,7 +185,11 @@ export const GET = withRouteContext('bookkeeping.journal_entries.list', async (r
|
||||
const { data, error, count } = await query
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
log.error('failed to list journal entries', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Verifikationerna kunde inte hämtas. Försök igen.' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json({ data, count })
|
||||
@@ -189,7 +198,7 @@ export const GET = withRouteContext('bookkeeping.journal_entries.list', async (r
|
||||
export const POST = withRouteContext(
|
||||
'bookkeeping.journal_entries.create',
|
||||
async (request, ctx) => {
|
||||
const { supabase, companyId, user } = ctx
|
||||
const { supabase, companyId, user, log } = ctx
|
||||
|
||||
const validation = await validateBody(request, CreateJournalEntrySchema)
|
||||
if (!validation.success) return validation.response
|
||||
@@ -206,8 +215,11 @@ export const POST = withRouteContext(
|
||||
} catch (err) {
|
||||
const typed = bookkeepingErrorResponse(err)
|
||||
if (typed) return typed
|
||||
// Untyped errors map to Swedish via getErrorMessage: the raw message is
|
||||
// logged here and must never reach the user verbatim (issue #337).
|
||||
log.error('failed to create journal entry', err as Error)
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Failed to create journal entry' },
|
||||
{ error: getErrorMessage(err, { context: 'journal_entry' }) },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
@@ -268,7 +268,13 @@ export const POST = withRouteContext(
|
||||
const ccAddress = company.email || user.email
|
||||
const partialFailures: Array<{ step: string; reason: string }> = []
|
||||
if (paymentLinkFailure) {
|
||||
partialFailures.push({ step: 'payment_link', reason: paymentLinkFailure })
|
||||
// The failure string is a raw provider/DB message: log it, but the
|
||||
// response field is user-visible and must stay Swedish (issue #337).
|
||||
opLog.warn('payment link creation failed on send', { reason: paymentLinkFailure })
|
||||
partialFailures.push({
|
||||
step: 'payment_link',
|
||||
reason: 'Betalningslänken kunde inte skapas. Fakturan skickades utan betalningslänk.',
|
||||
})
|
||||
}
|
||||
|
||||
let statusFlipped = isCreditDeliveryRetry
|
||||
@@ -387,7 +393,10 @@ export const POST = withRouteContext(
|
||||
|
||||
if (updateError) {
|
||||
opLog.warn('failed to update invoice status to sent', updateError)
|
||||
partialFailures.push({ step: 'status_update', reason: updateError.message })
|
||||
partialFailures.push({
|
||||
step: 'status_update',
|
||||
reason: 'Fakturans status kunde inte uppdateras till skickad.',
|
||||
})
|
||||
} else if (!flipRows || flipRows.length === 0) {
|
||||
opLog.warn('invoice already flipped to sent by a concurrent request; skipping bookkeeping follow-ups')
|
||||
partialFailures.push({
|
||||
|
||||
@@ -100,7 +100,9 @@ describe('POST /api/pending-operations/:id/commit', () => {
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(409)
|
||||
expect(body.error).toMatch(/already (committed|claimed|resolved)/i)
|
||||
// The executor's English error string maps to the Swedish HTTP-409
|
||||
// fallback: raw English never reaches the toast (issue #337).
|
||||
expect(body.error).toBe('En konflikt uppstod. Ladda om sidan och försök igen.')
|
||||
})
|
||||
|
||||
describe('categorize_transaction', () => {
|
||||
@@ -190,7 +192,10 @@ describe('POST /api/pending-operations/:id/commit', () => {
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(409)
|
||||
expect(body.error).toContain('already has a journal entry')
|
||||
// Known-pattern translation of the executor's English message (#337).
|
||||
expect(body.error).toBe(
|
||||
'Transaktionen är redan bokförd. Ångra kategoriseringen om du vill ändra den.',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -286,7 +291,8 @@ describe('POST /api/pending-operations/:id/commit', () => {
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error).toContain('Customer not found')
|
||||
// English executor message → Swedish HTTP-404 fallback (issue #337).
|
||||
expect(body.error).toBe('Resursen kunde inte hittas.')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3,13 +3,14 @@ import { ensureInitialized } from '@/lib/init'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { commitPendingOperation } from '@/lib/pending-operations/commit'
|
||||
import { bookkeepingErrorResponse, AccountsNotInChartError, ACCOUNTS_NOT_IN_CHART } from '@/lib/bookkeeping/errors'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import type { PendingOperation } from '@/types'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'pending_operation.commit',
|
||||
async (_request, { supabase, user, companyId }, { params }) => {
|
||||
async (_request, { supabase, user, companyId, log }, { params }) => {
|
||||
const { id } = await params
|
||||
|
||||
const { data: op, error: fetchError } = await supabase
|
||||
@@ -48,9 +49,19 @@ export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
)
|
||||
if (structured) return structured
|
||||
}
|
||||
// The executor's error strings mix Swedish user messages with raw
|
||||
// Supabase/Zod English; the pending page toasts this field verbatim, so
|
||||
// map it here. Swedish passes through untouched, English falls to the
|
||||
// status-appropriate Swedish fallback (issue #337). Raw stays in logs.
|
||||
const status = result.http_status ?? 500
|
||||
log.warn('pending operation commit failed', {
|
||||
operationId: id,
|
||||
rawError: result.error,
|
||||
status,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: result.error },
|
||||
{ status: result.http_status ?? 500 }
|
||||
{ error: getErrorMessage(result.error ?? null, { statusCode: status }) },
|
||||
{ status }
|
||||
)
|
||||
} catch (err) {
|
||||
const typed = bookkeepingErrorResponse(err)
|
||||
|
||||
@@ -150,7 +150,8 @@ describe('POST /api/pending-operations/bulk-commit', () => {
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(500)
|
||||
expect(body.error).toBe('db connection lost')
|
||||
// Raw Supabase messages never reach the response field (issue #337).
|
||||
expect(body.error).toBe('Åtgärderna kunde inte hämtas. Försök igen.')
|
||||
})
|
||||
|
||||
it('reports per-item not-found as failed without calling commit', async () => {
|
||||
@@ -170,7 +171,7 @@ describe('POST /api/pending-operations/bulk-commit', () => {
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.results).toEqual([
|
||||
{ id: VALID_ID_1, status: 'failed', error: 'Operation not found' },
|
||||
{ id: VALID_ID_1, status: 'failed', error: 'Åtgärden kunde inte hittas.' },
|
||||
])
|
||||
expect(body.data.summary).toEqual({
|
||||
total: 1,
|
||||
@@ -204,7 +205,7 @@ describe('POST /api/pending-operations/bulk-commit', () => {
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.results).toEqual([
|
||||
{ id: VALID_ID_1, status: 'skipped', error: 'Already committed' },
|
||||
{ id: VALID_ID_1, status: 'skipped', error: 'Redan hanterad (godkänd)' },
|
||||
{
|
||||
id: VALID_ID_2,
|
||||
status: 'skipped',
|
||||
@@ -296,8 +297,9 @@ describe('POST /api/pending-operations/bulk-commit', () => {
|
||||
}>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
// English executor message → Swedish HTTP-409 fallback (issue #337).
|
||||
expect(body.data.results).toEqual([
|
||||
{ id: VALID_ID_1, status: 'rejected', error: 'Resource already deleted' },
|
||||
{ id: VALID_ID_1, status: 'rejected', error: 'En konflikt uppstod. Ladda om sidan och försök igen.' },
|
||||
])
|
||||
expect(body.data.summary).toEqual({
|
||||
total: 1,
|
||||
@@ -341,12 +343,14 @@ describe('POST /api/pending-operations/bulk-commit', () => {
|
||||
}>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
// English executor strings map to the status-appropriate Swedish
|
||||
// fallbacks; skip/not-found strings are now Swedish at the source (#337).
|
||||
expect(body.data.results).toEqual([
|
||||
{ id: VALID_ID_1, status: 'committed' },
|
||||
{ id: VALID_ID_2, status: 'failed', error: 'boom' },
|
||||
{ id: VALID_ID_3, status: 'skipped', error: 'Already rejected' },
|
||||
{ id: VALID_ID_4, status: 'rejected', error: 'gone' },
|
||||
{ id: VALID_ID_5, status: 'failed', error: 'Operation not found' },
|
||||
{ id: VALID_ID_2, status: 'failed', error: 'Ett oväntat serverfel uppstod. Försök igen senare.' },
|
||||
{ id: VALID_ID_3, status: 'skipped', error: 'Redan hanterad (avvisad)' },
|
||||
{ id: VALID_ID_4, status: 'rejected', error: 'Resursen kunde inte hittas.' },
|
||||
{ id: VALID_ID_5, status: 'failed', error: 'Åtgärden kunde inte hittas.' },
|
||||
])
|
||||
expect(body.data.summary).toEqual({
|
||||
total: 5,
|
||||
|
||||
@@ -4,6 +4,7 @@ import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { PendingOperationsBulkSchema } from '@/lib/api/schemas'
|
||||
import { commitPendingOperation } from '@/lib/pending-operations/commit'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import type { PendingOperation } from '@/types'
|
||||
|
||||
ensureInitialized()
|
||||
@@ -14,9 +15,17 @@ interface BulkCommitItemResult {
|
||||
error?: string
|
||||
}
|
||||
|
||||
// Swedish display labels for already-handled operations; the raw enum values
|
||||
// are English and must not reach the user-visible per-item error strings.
|
||||
const STATUS_LABELS_SV: Record<string, string> = {
|
||||
committing: 'godkänns just nu',
|
||||
committed: 'godkänd',
|
||||
rejected: 'avvisad',
|
||||
}
|
||||
|
||||
export const POST = withRouteContext(
|
||||
'pending_operation.bulk_commit',
|
||||
async (request, { user, supabase, companyId }) => {
|
||||
async (request, { user, supabase, companyId, log }) => {
|
||||
const validated = await validateBody(request, PendingOperationsBulkSchema)
|
||||
if (!validated.success) return validated.response
|
||||
const { ids } = validated.data
|
||||
@@ -28,7 +37,11 @@ export const POST = withRouteContext(
|
||||
.eq('company_id', companyId)
|
||||
|
||||
if (fetchError) {
|
||||
return NextResponse.json({ error: fetchError.message }, { status: 500 })
|
||||
log.error('failed to fetch pending operations for bulk commit', fetchError)
|
||||
return NextResponse.json(
|
||||
{ error: 'Åtgärderna kunde inte hämtas. Försök igen.' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
const opsById = new Map((ops ?? []).map((op) => [op.id, op as PendingOperation]))
|
||||
@@ -37,11 +50,15 @@ export const POST = withRouteContext(
|
||||
for (const id of ids) {
|
||||
const op = opsById.get(id)
|
||||
if (!op) {
|
||||
results.push({ id, status: 'failed', error: 'Operation not found' })
|
||||
results.push({ id, status: 'failed', error: 'Åtgärden kunde inte hittas.' })
|
||||
continue
|
||||
}
|
||||
if (op.status !== 'pending') {
|
||||
results.push({ id, status: 'skipped', error: `Already ${op.status}` })
|
||||
results.push({
|
||||
id,
|
||||
status: 'skipped',
|
||||
error: `Redan hanterad (${STATUS_LABELS_SV[op.status] ?? op.status})`,
|
||||
})
|
||||
continue
|
||||
}
|
||||
if (op.risk_level === 'high') {
|
||||
@@ -60,10 +77,23 @@ export const POST = withRouteContext(
|
||||
})
|
||||
if (result.status === 'committed') {
|
||||
results.push({ id, status: 'committed' })
|
||||
} else if (result.status === 'rejected' && result.auto_rejected) {
|
||||
results.push({ id, status: 'rejected', error: result.error ?? 'Avvisad' })
|
||||
} else {
|
||||
results.push({ id, status: 'failed', error: result.error ?? 'Misslyckades' })
|
||||
// The executor's error strings mix Swedish user messages with raw
|
||||
// Supabase/Zod English: map to Swedish before they land in the
|
||||
// user-visible per-item results (issue #337). Raw stays in logs.
|
||||
log.warn('bulk commit item failed', {
|
||||
operationId: id,
|
||||
rawError: result.error,
|
||||
status: result.http_status,
|
||||
})
|
||||
const mapped = getErrorMessage(result.error ?? null, {
|
||||
statusCode: result.http_status ?? 500,
|
||||
})
|
||||
if (result.status === 'rejected' && result.auto_rejected) {
|
||||
results.push({ id, status: 'rejected', error: mapped })
|
||||
} else {
|
||||
results.push({ id, status: 'failed', error: mapped })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* Tests for /api/settings/ku-signal — ledger-derived kontrolluppgifter signal.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const fetchEntryLinesMock = vi.fn()
|
||||
vi.mock('@/lib/bookkeeping/entry-lines', () => ({
|
||||
fetchEntryLines: (...args: unknown[]) => fetchEntryLinesMock(...args),
|
||||
}))
|
||||
|
||||
import { GET } from '../route'
|
||||
|
||||
function supabaseWithEntityType(entityType: string | null) {
|
||||
return {
|
||||
from: vi.fn(() => ({
|
||||
select: vi.fn(() => ({
|
||||
eq: vi.fn(() => ({
|
||||
maybeSingle: vi.fn(async () => ({ data: entityType ? { entity_type: entityType } : null })),
|
||||
})),
|
||||
})),
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('GET /api/settings/ku-signal', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: {},
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const res = await GET(createMockRequest('/api/settings/ku-signal'), {})
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('reports a KU signal when an aktiebolag has utdelning/ägarlån postings', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: { id: 'user-1' },
|
||||
supabase: supabaseWithEntityType('aktiebolag'),
|
||||
error: null,
|
||||
})
|
||||
fetchEntryLinesMock.mockResolvedValue([{ account_number: '2898' }])
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ data: { has_ku_signal: boolean } }>(
|
||||
await GET(createMockRequest('/api/settings/ku-signal'), {})
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.has_ku_signal).toBe(true)
|
||||
})
|
||||
|
||||
it('reports no signal for an empty result', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: { id: 'user-1' },
|
||||
supabase: supabaseWithEntityType('aktiebolag'),
|
||||
error: null,
|
||||
})
|
||||
fetchEntryLinesMock.mockResolvedValue([])
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ data: { has_ku_signal: boolean } }>(
|
||||
await GET(createMockRequest('/api/settings/ku-signal'), {})
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.has_ku_signal).toBe(false)
|
||||
})
|
||||
|
||||
it('never signals for enskild firma, even with matching postings', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: { id: 'user-1' },
|
||||
supabase: supabaseWithEntityType('enskild_firma'),
|
||||
error: null,
|
||||
})
|
||||
fetchEntryLinesMock.mockResolvedValue([{ account_number: '2893' }])
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ data: { has_ku_signal: boolean } }>(
|
||||
await GET(createMockRequest('/api/settings/ku-signal'), {})
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.has_ku_signal).toBe(false)
|
||||
// The ledger query is skipped entirely for non-AB companies.
|
||||
expect(fetchEntryLinesMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,66 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { fetchEntryLines, type EntryLinesQuery } from '@/lib/bookkeeping/entry-lines'
|
||||
|
||||
/**
|
||||
* Accounts whose postings indicate a kontrolluppgifter obligation:
|
||||
* 2898 outtagen vinstutdelning (KU31 on utdelning), 2393/2893 lån från
|
||||
* närstående (KU20 on interest paid to the owner). 2091 is deliberately NOT
|
||||
* a signal: every closed year moves balanserad vinst, so it would flag
|
||||
* nearly all aktiebolag.
|
||||
*/
|
||||
const KU_SIGNAL_ACCOUNTS = ['2898', '2393', '2893']
|
||||
|
||||
/** How far back to look for KU-relevant postings. */
|
||||
const LOOKBACK_MONTHS = 15
|
||||
|
||||
/**
|
||||
* GET /api/settings/ku-signal
|
||||
*
|
||||
* Derived suggestion signal for the tax settings page: an aktiebolag whose
|
||||
* ledger shows utdelning or ägarlån postings likely owes kontrolluppgifter
|
||||
* on 31 January (SFL 24 kap. 1 §), but KU31 is never covered by AGI so the
|
||||
* obligation is easy to miss. The settings UI uses this to prompt the user
|
||||
* to enable the KU deadline; it never flips the flag itself (mirrors the
|
||||
* EU-trade signal from the periodisk sammanställning suggestion).
|
||||
*/
|
||||
export const GET = withRouteContext(
|
||||
'settings.ku_signal',
|
||||
async (_request, { supabase, companyId, log }) => {
|
||||
// Kontrolluppgifter for utdelning/ägarlån only exist for aktiebolag; an
|
||||
// enskild firma has no shareholder to report on.
|
||||
const { data: settings, error: settingsError } = await supabase
|
||||
.from('company_settings')
|
||||
.select('entity_type')
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
if (settingsError) {
|
||||
// Best-effort signal: treat as "no signal" but keep the failure
|
||||
// observable for forensics.
|
||||
log.warn('ku-signal: company_settings lookup failed', {
|
||||
code: settingsError.code,
|
||||
})
|
||||
}
|
||||
|
||||
if (settings?.entity_type !== 'aktiebolag') {
|
||||
return NextResponse.json({ data: { has_ku_signal: false } })
|
||||
}
|
||||
|
||||
const since = new Date()
|
||||
since.setMonth(since.getMonth() - LOOKBACK_MONTHS)
|
||||
const sinceStr = since.toISOString().split('T')[0]
|
||||
|
||||
const lines = await fetchEntryLines<{ account_number: string }>({
|
||||
supabase,
|
||||
lineColumns: 'account_number',
|
||||
filterEntries: (q: EntryLinesQuery) =>
|
||||
q
|
||||
.eq('company_id', companyId)
|
||||
.in('status', ['posted', 'reversed'])
|
||||
.gte('entry_date', sinceStr),
|
||||
filterLines: (q: EntryLinesQuery) => q.in('account_number', KU_SIGNAL_ACCOUNTS),
|
||||
})
|
||||
|
||||
return NextResponse.json({ data: { has_ku_signal: lines.length > 0 } })
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* Tests for /api/settings/rot-rut-signal — invoice-derived ROT/RUT signal.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
import { GET } from '../route'
|
||||
|
||||
function supabaseWithInvoiceCount(count: number | null, error: unknown = null) {
|
||||
return {
|
||||
from: vi.fn(() => ({
|
||||
select: vi.fn(() => ({
|
||||
eq: vi.fn(() => ({
|
||||
gt: vi.fn(async () => ({ count, error })),
|
||||
})),
|
||||
})),
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('GET /api/settings/rot-rut-signal', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: {},
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const res = await GET(createMockRequest('/api/settings/rot-rut-signal'), {})
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('reports a signal when invoices with ROT/RUT deductions exist', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: { id: 'user-1' },
|
||||
supabase: supabaseWithInvoiceCount(2),
|
||||
error: null,
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data: { has_rot_rut: boolean } }>(
|
||||
await GET(createMockRequest('/api/settings/rot-rut-signal'), {})
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.has_rot_rut).toBe(true)
|
||||
})
|
||||
|
||||
it('reports no signal when no such invoices exist', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: { id: 'user-1' },
|
||||
supabase: supabaseWithInvoiceCount(0),
|
||||
error: null,
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data: { has_rot_rut: boolean } }>(
|
||||
await GET(createMockRequest('/api/settings/rot-rut-signal'), {})
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.has_rot_rut).toBe(false)
|
||||
})
|
||||
|
||||
it('fails closed (no suggestion) on a query error', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: { id: 'user-1' },
|
||||
supabase: supabaseWithInvoiceCount(null, { message: 'boom' }),
|
||||
error: null,
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data: { has_rot_rut: boolean } }>(
|
||||
await GET(createMockRequest('/api/settings/rot-rut-signal'), {})
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.has_rot_rut).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
|
||||
/**
|
||||
* GET /api/settings/rot-rut-signal
|
||||
*
|
||||
* Derived suggestion signal for the tax settings page: a company with
|
||||
* invoices carrying ROT/RUT deductions must request the Skatteverket payout
|
||||
* by 31 January after the payment year (Lag 2009:194 8 §), and missing the
|
||||
* date forfeits the payout on account 1513. The settings UI uses this to
|
||||
* prompt the user to enable the ROT/RUT deadline; it never flips the flag
|
||||
* itself (mirrors the EU-trade and KU signals).
|
||||
*/
|
||||
export const GET = withRouteContext(
|
||||
'settings.rot_rut_signal',
|
||||
async (_request, { supabase, companyId, log }) => {
|
||||
const { count, error } = await supabase
|
||||
.from('invoices')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('company_id', companyId)
|
||||
.gt('deduction_total', 0)
|
||||
|
||||
// Best-effort signal: on error just hide the suggestion, but keep the
|
||||
// failure observable for forensics.
|
||||
if (error) {
|
||||
log.warn('rot-rut-signal: invoice count failed', { code: error.code })
|
||||
}
|
||||
const hasRotRut = !error && (count ?? 0) > 0
|
||||
return NextResponse.json({ data: { has_rot_rut: hasRotRut } })
|
||||
},
|
||||
)
|
||||
@@ -175,7 +175,10 @@ describe('POST /api/transactions/[id]/book', () => {
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toBe('Entry is not balanced')
|
||||
// Untyped engine errors map to the Swedish context fallback; the raw
|
||||
// English message must never reach the response field (issue #337).
|
||||
expect(body.error).toBe('Kunde inte hantera transaktionen. Försök igen.')
|
||||
expect(body.error).not.toContain('not balanced')
|
||||
})
|
||||
|
||||
it('creates journal entry and links to transaction (happy path)', async () => {
|
||||
|
||||
@@ -8,6 +8,7 @@ import { validateBody } from '@/lib/api/validate'
|
||||
import { BookTransactionSchema } from '@/lib/api/schemas'
|
||||
import { detectBookingDuplicate } from '@/lib/transactions/booking-duplicate-detection'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { appendProcessingHistory } from '@/lib/processing-history/append'
|
||||
import type { Transaction } from '@/types'
|
||||
|
||||
@@ -138,8 +139,11 @@ export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
} catch (err) {
|
||||
const typed = bookkeepingErrorResponse(err)
|
||||
if (typed) return typed
|
||||
// Untyped errors map to Swedish via getErrorMessage: the raw message is
|
||||
// logged here and must never reach the user verbatim (issue #337).
|
||||
log.error('failed to create journal entry on book', err as Error)
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Failed to create journal entry' },
|
||||
{ error: getErrorMessage(err, { context: 'transaction' }) },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useRef, useEffect } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Deadline } from '@/types'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { isDeadlineOverdue, parseDate } from '@/lib/calendar/utils'
|
||||
import { Check, Pencil } from 'lucide-react'
|
||||
|
||||
/**
|
||||
* System tax deadlines that legally share the skattekonto date ("den 12:e"):
|
||||
* for a small monthly-moms employer, moms + AGI (+ debiterad preliminärskatt)
|
||||
* all fall due the same day. Rendering them as one grouped card instead of
|
||||
* 2-3 identical-date rows keeps the list scannable.
|
||||
*/
|
||||
export const SKATTEKONTO_GROUP_TYPES = new Set([
|
||||
'moms_monthly',
|
||||
'moms_quarterly',
|
||||
'moms_yearly',
|
||||
'f_skatt',
|
||||
'arbetsgivardeklaration',
|
||||
'skatteinbetalning',
|
||||
])
|
||||
|
||||
export function isSkattekontoDeadline(d: Deadline): boolean {
|
||||
return (
|
||||
!d.is_completed &&
|
||||
d.source === 'system' &&
|
||||
d.tax_deadline_type !== null &&
|
||||
SKATTEKONTO_GROUP_TYPES.has(d.tax_deadline_type)
|
||||
)
|
||||
}
|
||||
|
||||
const SWEDISH_MONTHS_SHORT = [
|
||||
'jan', 'feb', 'mar', 'apr', 'maj', 'jun',
|
||||
'jul', 'aug', 'sep', 'okt', 'nov', 'dec',
|
||||
]
|
||||
|
||||
interface DeadlineGroupCardProps {
|
||||
/** Two or more skattekonto deadlines sharing the same due_date. */
|
||||
deadlines: Deadline[]
|
||||
onToggle: (deadline: Deadline) => void
|
||||
onEdit?: (deadline: Deadline) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* One card for all skattekonto obligations on a shared due date, with the
|
||||
* date block rendered once and each obligation as a sub-row that keeps its
|
||||
* own "Markera klar" confirmation. Visual language mirrors DeadlineCard.
|
||||
*/
|
||||
export function DeadlineGroupCard({ deadlines, onToggle, onEdit }: DeadlineGroupCardProps) {
|
||||
const t = useTranslations('deadlines')
|
||||
const [confirmingId, setConfirmingId] = useState<string | null>(null)
|
||||
const confirmRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const first = deadlines[0]
|
||||
const dueDate = parseDate(first.due_date)
|
||||
const dayNum = dueDate.getDate()
|
||||
const monthStr = SWEDISH_MONTHS_SHORT[dueDate.getMonth()]
|
||||
const overdue = deadlines.some(isDeadlineOverdue)
|
||||
|
||||
useEffect(() => {
|
||||
if (!confirmingId) return
|
||||
function handleClickOutside(e: MouseEvent) {
|
||||
if (confirmRef.current && !confirmRef.current.contains(e.target as Node)) {
|
||||
setConfirmingId(null)
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', handleClickOutside)
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside)
|
||||
}, [confirmingId])
|
||||
|
||||
const confirming = deadlines.find((d) => d.id === confirmingId) ?? null
|
||||
|
||||
return (
|
||||
<div ref={confirmRef}>
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-lg border bg-card transition-all duration-150',
|
||||
confirmingId && 'ring-2 ring-ring ring-offset-1',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start gap-4 py-3 px-4">
|
||||
{/* Shared date block */}
|
||||
<div className="flex-shrink-0 w-12 text-center pt-0.5">
|
||||
<span className="block text-lg font-display leading-none tabular-nums">
|
||||
{dayNum}
|
||||
</span>
|
||||
<span className="block text-[11px] uppercase tracking-wider text-muted-foreground mt-0.5">
|
||||
{monthStr}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="w-px self-stretch bg-border flex-shrink-0" />
|
||||
|
||||
{/* Group content */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<p className="text-sm font-medium">{t('group_skattekonto_title')}</p>
|
||||
<span
|
||||
className={cn(
|
||||
'text-[11px] flex-shrink-0',
|
||||
overdue ? 'text-destructive font-medium' : 'text-muted-foreground/60',
|
||||
)}
|
||||
>
|
||||
{t('group_same_day', { count: deadlines.length })}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="mt-2 space-y-1">
|
||||
{deadlines.map((deadline) => (
|
||||
<div
|
||||
key={deadline.id}
|
||||
onClick={() => {
|
||||
if (!confirmingId && onEdit) onEdit(deadline)
|
||||
}}
|
||||
className={cn(
|
||||
'group flex items-center gap-3 rounded-md py-1.5 -mx-2 px-2 transition-colors',
|
||||
onEdit && !confirmingId && 'cursor-pointer hover:bg-accent/40',
|
||||
)}
|
||||
>
|
||||
<p className="text-sm truncate flex-1 min-w-0">{deadline.title}</p>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setConfirmingId(deadline.id)
|
||||
}}
|
||||
className={cn(
|
||||
'text-xs text-muted-foreground hover:text-foreground transition-colors px-2.5 py-1 rounded-md border border-border hover:border-foreground/30 hover:bg-accent flex-shrink-0',
|
||||
confirmingId && 'invisible',
|
||||
)}
|
||||
>
|
||||
{t('group_mark_done')}
|
||||
</button>
|
||||
{onEdit && !confirmingId && (
|
||||
<Pencil className="h-3.5 w-3.5 text-muted-foreground/0 group-hover:text-muted-foreground/50 transition-colors flex-shrink-0" />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Inline confirmation bar (one at a time, mirrors DeadlineCard) */}
|
||||
<div
|
||||
className={cn(
|
||||
'grid transition-all duration-200 ease-out',
|
||||
confirming ? 'grid-rows-[1fr]' : 'grid-rows-[0fr]',
|
||||
)}
|
||||
>
|
||||
<div className="overflow-hidden">
|
||||
{confirming && (
|
||||
<div className="border-t px-4 py-3 flex items-center justify-between gap-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t.rich('group_confirm_question', {
|
||||
title: confirming.title,
|
||||
hl: (chunks) => (
|
||||
<span className="font-medium text-foreground">{chunks}</span>
|
||||
),
|
||||
})}
|
||||
</p>
|
||||
<div className="flex items-center gap-2 flex-shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 px-3 text-xs"
|
||||
onClick={() => setConfirmingId(null)}
|
||||
>
|
||||
{t('group_cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
className="h-8 px-3 text-xs"
|
||||
onClick={() => {
|
||||
setConfirmingId(null)
|
||||
onToggle(confirming)
|
||||
}}
|
||||
>
|
||||
<Check className="h-3.5 w-3.5 mr-1.5" />
|
||||
{t('group_confirm')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { useState, useMemo } from 'react'
|
||||
import { Deadline, DeadlineType } from '@/types'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { DeadlineCard } from './DeadlineCard'
|
||||
import { DeadlineGroupCard, isSkattekontoDeadline } from './DeadlineGroupCard'
|
||||
import { DeadlineFilters } from './DeadlineFilters'
|
||||
import { DeadlineForm } from './DeadlineForm'
|
||||
import { isDeadlineOverdue } from '@/lib/calendar/utils'
|
||||
@@ -96,6 +97,38 @@ export function DeadlineList({
|
||||
{ key: 'completed', label: 'Klara', items: groupedDeadlines.completed },
|
||||
].filter(s => s.items.length > 0)
|
||||
|
||||
// Skattekonto obligations legally share the same due date (moms + AGI +
|
||||
// preliminärskatt all fall on "den 12:e"): collapse 2+ such rows into one
|
||||
// grouped card per date instead of near-identical rows. Other deadlines
|
||||
// render as before, in their original order.
|
||||
type ListEntry =
|
||||
| { kind: 'single'; deadline: Deadline }
|
||||
| { kind: 'group'; date: string; items: Deadline[] }
|
||||
|
||||
const toEntries = (items: Deadline[]): ListEntry[] => {
|
||||
const byDate = new Map<string, Deadline[]>()
|
||||
for (const d of items) {
|
||||
if (!isSkattekontoDeadline(d)) continue
|
||||
const group = byDate.get(d.due_date) ?? []
|
||||
group.push(d)
|
||||
byDate.set(d.due_date, group)
|
||||
}
|
||||
const emittedDates = new Set<string>()
|
||||
const entries: ListEntry[] = []
|
||||
for (const d of items) {
|
||||
const group = byDate.get(d.due_date)
|
||||
if (isSkattekontoDeadline(d) && group && group.length >= 2) {
|
||||
if (!emittedDates.has(d.due_date)) {
|
||||
emittedDates.add(d.due_date)
|
||||
entries.push({ kind: 'group', date: d.due_date, items: group })
|
||||
}
|
||||
continue
|
||||
}
|
||||
entries.push({ kind: 'single', deadline: d })
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Toolbar */}
|
||||
@@ -159,15 +192,24 @@ export function DeadlineList({
|
||||
<div className="flex-1 h-px bg-border/60" />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
{items.map((deadline) => (
|
||||
<DeadlineCard
|
||||
key={deadline.id}
|
||||
deadline={deadline}
|
||||
onToggle={onDeadlineToggle}
|
||||
onEdit={handleEdit}
|
||||
onDelete={onDeadlineDelete}
|
||||
/>
|
||||
))}
|
||||
{toEntries(items).map((entry) =>
|
||||
entry.kind === 'group' ? (
|
||||
<DeadlineGroupCard
|
||||
key={`skattekonto-${entry.date}`}
|
||||
deadlines={entry.items}
|
||||
onToggle={onDeadlineToggle}
|
||||
onEdit={handleEdit}
|
||||
/>
|
||||
) : (
|
||||
<DeadlineCard
|
||||
key={entry.deadline.id}
|
||||
deadline={entry.deadline}
|
||||
onToggle={onDeadlineToggle}
|
||||
onEdit={handleEdit}
|
||||
onDelete={onDeadlineDelete}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
|
||||
@@ -127,10 +127,19 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
// self-billing invoice we received (mottagen självfaktura, ML 17 kap 15§).
|
||||
// Self-billing is never available when editing an existing draft.
|
||||
const [mode, setMode] = useState<'invoice' | 'self_billed'>('invoice')
|
||||
// Company-wide opt-in from the invoice settings page: the whole payment
|
||||
// link section (manual field + Stripe auto toggle) stays hidden until the
|
||||
// company enables it. The send routes enforce the same setting server-side
|
||||
// (maybeCreatePaymentLinkForInvoice), so this is presentation, not the gate.
|
||||
const [paymentLinksEnabled, setPaymentLinksEnabled] = useState(false)
|
||||
// An already-linked invoice keeps showing the section even when the
|
||||
// setting is off, so the user can still see or clear the old link.
|
||||
const hasExistingPaymentLink = Boolean(initial?.payment_link_url)
|
||||
// Active Stripe connection: drives the "auto payment link" toggle in the
|
||||
// payment link section. Absent extension or no connection → toggle hidden.
|
||||
const [stripeConnected, setStripeConnected] = useState(false)
|
||||
useEffect(() => {
|
||||
if (!paymentLinksEnabled) return
|
||||
if (!ENABLED_EXTENSION_IDS.has('stripe')) return
|
||||
let cancelled = false
|
||||
fetch('/api/extensions/ext/stripe/status')
|
||||
@@ -142,7 +151,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
}, [paymentLinksEnabled])
|
||||
|
||||
const schema = useMemo(() => {
|
||||
const itemSchema = z.object({
|
||||
@@ -586,7 +595,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
if (!company?.id) return
|
||||
const { data } = await supabase
|
||||
.from('company_settings')
|
||||
.select('invoice_default_notes, default_our_reference, clearing_number, account_number, bankgiro, accounting_method, ore_rounding, logo_url, vat_registered, dimensions_enabled')
|
||||
.select('invoice_default_notes, default_our_reference, clearing_number, account_number, bankgiro, accounting_method, ore_rounding, logo_url, vat_registered, dimensions_enabled, invoice_payment_links_enabled')
|
||||
.eq('company_id', company.id)
|
||||
.single()
|
||||
if (data?.invoice_default_notes) {
|
||||
@@ -617,6 +626,8 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
}
|
||||
// Gates the dimension affordances (header default + per-row override).
|
||||
setDimensionsEnabled(data?.dimensions_enabled === true)
|
||||
// Gates the payment-link section (opt-in on the invoice settings page).
|
||||
setPaymentLinksEnabled(data?.invoice_payment_links_enabled === true)
|
||||
}
|
||||
|
||||
// First-invoice detection (issue #520): captured at page load so the
|
||||
@@ -2199,10 +2210,12 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Online payment link (manual MVP): pasted per invoice from
|
||||
the user's PSP dashboard. Only real invoices: proformas
|
||||
and delivery notes carry no payment request. */}
|
||||
{watchDocumentType === 'invoice' && (
|
||||
{/* Online payment link: manual paste or the Stripe auto
|
||||
toggle. Only real invoices: proformas and delivery notes
|
||||
carry no payment request. Hidden unless the company has
|
||||
opted in on the invoice settings page, except when the
|
||||
draft already carries a link (still viewable/clearable). */}
|
||||
{watchDocumentType === 'invoice' && (paymentLinksEnabled || hasExistingPaymentLink) && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="payment_link_url">{t('payment_link_label')}</Label>
|
||||
<Input
|
||||
|
||||
@@ -74,6 +74,14 @@ interface SkatteverketPanelProps {
|
||||
periodType: VatPeriodType
|
||||
year: number
|
||||
period: number
|
||||
/**
|
||||
* Selected räkenskapsår for helårsmoms. The SKV redovisningsperiod for
|
||||
* yearly filers is the FY-end month (broken FYs do not end in December),
|
||||
* and the `year` prop is not maintained in yearly mode, so both the period
|
||||
* id and the fiscal-year end ride along explicitly.
|
||||
*/
|
||||
fiscalPeriodId?: string
|
||||
fiscalYearEnd?: { year: number; month: number }
|
||||
hasData: boolean
|
||||
/**
|
||||
* True when the local pre-flight checks (VatChecksCard, section 1 of the
|
||||
@@ -135,9 +143,15 @@ function SkatteverketPanelInner({
|
||||
periodType,
|
||||
year,
|
||||
period,
|
||||
fiscalPeriodId,
|
||||
fiscalYearEnd,
|
||||
hasData,
|
||||
localBlocked,
|
||||
}: SkatteverketPanelProps) {
|
||||
// In yearly mode the year picker is replaced by the räkenskapsår selector,
|
||||
// so the `year` prop is stale (stuck at the current year). Every SKV call
|
||||
// must target the FY-end year instead.
|
||||
const effectiveYear = periodType === 'yearly' && fiscalYearEnd ? fiscalYearEnd.year : year
|
||||
const hasSkvCapability = useCapability(CAPABILITY.skatteverket)
|
||||
const { dialogProps, confirm } = useDestructiveConfirm()
|
||||
const [status, setStatus] = useState<SkatteverketStatus | null>(null)
|
||||
@@ -156,7 +170,7 @@ function SkatteverketPanelInner({
|
||||
// one period must never render as if it belonged to another. Without this,
|
||||
// the visibilitychange auto-check could stamp "Deklarationen har lämnats
|
||||
// in" for a different period than the one being signed.
|
||||
const periodKey = `${periodType}:${year}:${period}`
|
||||
const periodKey = `${periodType}:${effectiveYear}:${period}:${fiscalPeriodId ?? ''}`
|
||||
const [appliedPeriodKey, setAppliedPeriodKey] = useState(periodKey)
|
||||
if (appliedPeriodKey !== periodKey) {
|
||||
setAppliedPeriodKey(periodKey)
|
||||
@@ -271,7 +285,7 @@ function SkatteverketPanelInner({
|
||||
const res = await fetch('/api/extensions/ext/skatteverket/declaration/validate', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ periodType, year, period }),
|
||||
body: JSON.stringify({ periodType, year: effectiveYear, period, fiscalPeriodId }),
|
||||
})
|
||||
const result = await res.json()
|
||||
if (applyApiError(result)) {
|
||||
@@ -324,7 +338,7 @@ function SkatteverketPanelInner({
|
||||
const res = await fetch('/api/extensions/ext/skatteverket/declaration/draft', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ periodType, year, period }),
|
||||
body: JSON.stringify({ periodType, year: effectiveYear, period, fiscalPeriodId }),
|
||||
})
|
||||
const result = await res.json()
|
||||
if (applyApiError(result)) {
|
||||
@@ -358,8 +372,8 @@ function SkatteverketPanelInner({
|
||||
}, [])
|
||||
|
||||
const getRedovisningsperiod = useCallback((): string => {
|
||||
return formatRedovisningsperiod(periodType, year, period)
|
||||
}, [periodType, year, period])
|
||||
return formatRedovisningsperiod(periodType, year, period, fiscalYearEnd)
|
||||
}, [periodType, year, period, fiscalYearEnd])
|
||||
|
||||
const handleLock = async () => {
|
||||
setActionLoading('lock')
|
||||
@@ -416,7 +430,7 @@ function SkatteverketPanelInner({
|
||||
const res = await fetch('/api/extensions/ext/skatteverket/declaration/submit', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ periodType, year, period }),
|
||||
body: JSON.stringify({ periodType, year: effectiveYear, period, fiscalPeriodId }),
|
||||
})
|
||||
const result = await res.json()
|
||||
|
||||
@@ -512,7 +526,7 @@ function SkatteverketPanelInner({
|
||||
const res = await fetch(
|
||||
`/api/extensions/ext/skatteverket/declaration/submitted?redovisare=${encodeURIComponent(
|
||||
await getRedovisare()
|
||||
)}&redovisningsperiod=${getRedovisningsperiod()}&periodType=${periodType}&year=${year}&period=${period}`
|
||||
)}&redovisningsperiod=${getRedovisningsperiod()}&periodType=${periodType}&year=${effectiveYear}&period=${period}`
|
||||
)
|
||||
const result = await res.json()
|
||||
if (applyApiError(result)) {
|
||||
@@ -532,7 +546,7 @@ function SkatteverketPanelInner({
|
||||
} finally {
|
||||
setActionLoading(null)
|
||||
}
|
||||
}, [applyApiError, getRedovisare, getRedovisningsperiod, periodType, year, period])
|
||||
}, [applyApiError, getRedovisare, getRedovisningsperiod, periodType, effectiveYear, period])
|
||||
|
||||
// While a signing link is outstanding, re-check submission status when the
|
||||
// user returns to this tab: signing happens on Skatteverket's site, so the
|
||||
@@ -617,7 +631,7 @@ function SkatteverketPanelInner({
|
||||
const res = await fetch(
|
||||
`/api/extensions/ext/skatteverket/declaration/decided?redovisare=${encodeURIComponent(
|
||||
await getRedovisare()
|
||||
)}&redovisningsperiod=${getRedovisningsperiod()}&periodType=${periodType}&year=${year}&period=${period}`
|
||||
)}&redovisningsperiod=${getRedovisningsperiod()}&periodType=${periodType}&year=${effectiveYear}&period=${period}`
|
||||
)
|
||||
const result = await res.json()
|
||||
if (applyApiError(result)) {
|
||||
|
||||
@@ -1334,8 +1334,11 @@ export function VatDeclarationView() {
|
||||
const [period, setPeriod] = useState(currentQuarter)
|
||||
// Annual VAT (helårsmoms) is reported per räkenskapsår, not per calendar
|
||||
// year — picked inline in yearly mode. Monthly/quarterly are calendar
|
||||
// periods and need no fiscal year.
|
||||
// periods and need no fiscal year. The period's end date rides along so
|
||||
// the Skatteverket panel can target the FY-end month (broken fiscal years
|
||||
// do not end in December).
|
||||
const [fiscalPeriodId, setFiscalPeriodId] = useState('')
|
||||
const [fiscalPeriodEnd, setFiscalPeriodEnd] = useState<string | null>(null)
|
||||
// Latest fetch outcome, tagged with the fetch key it was requested under.
|
||||
// loading / error / data are all derived by comparing that tag with the
|
||||
// current key, so the fetch effect never sets state synchronously.
|
||||
@@ -1565,7 +1568,10 @@ export function VatDeclarationView() {
|
||||
// calendar year.
|
||||
<FiscalYearSelector
|
||||
value={fiscalPeriodId || null}
|
||||
onChange={(id) => setFiscalPeriodId(id || '')}
|
||||
onChange={(id, fp) => {
|
||||
setFiscalPeriodId(id || '')
|
||||
setFiscalPeriodEnd(fp?.period_end ?? null)
|
||||
}}
|
||||
includeAllOption={false}
|
||||
hideFuturePeriods
|
||||
/>
|
||||
@@ -1913,6 +1919,15 @@ export function VatDeclarationView() {
|
||||
periodType={periodType}
|
||||
year={year}
|
||||
period={period}
|
||||
fiscalPeriodId={isYearly ? fiscalPeriodId : undefined}
|
||||
fiscalYearEnd={
|
||||
isYearly && fiscalPeriodEnd
|
||||
? {
|
||||
year: Number(fiscalPeriodEnd.slice(0, 4)),
|
||||
month: Number(fiscalPeriodEnd.slice(5, 7)),
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
hasData={data !== null}
|
||||
localBlocked={checksBlocked}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useCallback, useState } from 'react'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import type { CompanySettings } from '@/types'
|
||||
|
||||
interface InvoicePaymentLinkSettingsProps {
|
||||
settings: CompanySettings
|
||||
onUpdate: (updates: Partial<CompanySettings>) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Opt-in for the invoice payment-link feature. Off (the default) hides the
|
||||
* payment-link field in the invoice editor and stops automatic Stripe link
|
||||
* creation on send; the send routes enforce the same setting server-side.
|
||||
*/
|
||||
export function InvoicePaymentLinkSettings({ settings, onUpdate }: InvoicePaymentLinkSettingsProps) {
|
||||
const t = useTranslations('settings_payment_links')
|
||||
const { toast } = useToast()
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
|
||||
const saveToggle = useCallback(async (value: boolean) => {
|
||||
setIsSaving(true)
|
||||
try {
|
||||
const response = await fetch('/api/settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ invoice_payment_links_enabled: value }),
|
||||
})
|
||||
if (!response.ok) throw new Error()
|
||||
onUpdate({ invoice_payment_links_enabled: value })
|
||||
} catch {
|
||||
toast({ title: t('toast_save_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
}, [onUpdate, toast, t])
|
||||
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
{t('heading')}
|
||||
</h2>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<Label>{t('enable_label')}</Label>
|
||||
<p className="text-xs text-muted-foreground">{t('enable_help')}</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={settings.invoice_payment_links_enabled ?? false}
|
||||
onCheckedChange={saveToggle}
|
||||
disabled={isSaving}
|
||||
aria-label={t('enable_label')}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -260,13 +260,20 @@ function SkatteverketPersonalConnectionCard() {
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('connect_intro')}
|
||||
</p>
|
||||
{/* The skahmst consent-page note only matters when the user can
|
||||
actually reach that page: hidden while the feature is gated. */}
|
||||
{/* The consent-page notes only matter when the user can actually
|
||||
reach that page: hidden while the feature is gated. */}
|
||||
{hasSkatteverket && (
|
||||
<div className="rounded-md border border-border bg-secondary/40 p-3 text-xs text-muted-foreground">
|
||||
{t.rich('skahmst_note', {
|
||||
code: (chunks) => <span className="font-mono">{chunks}</span>,
|
||||
})}
|
||||
<div className="space-y-2 rounded-md border border-border bg-secondary/40 p-3 text-xs text-muted-foreground">
|
||||
{/* Pre-empt the most common broken connect: a behörighet left
|
||||
unticked on SKV's consent page. Before this note the
|
||||
"godkänn alla" guidance only appeared AFTER a failed
|
||||
attempt (missing_scope_message). */}
|
||||
<p className="text-foreground">{t('connect_approve_all')}</p>
|
||||
<p>
|
||||
{t.rich('skahmst_note', {
|
||||
code: (chunks) => <span className="font-mono">{chunks}</span>,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{!hasSkatteverket && (
|
||||
|
||||
@@ -12,9 +12,18 @@ interface TaxSettingsFormProps {
|
||||
settings: CompanySettings
|
||||
/** Ledger-derived signal: EU sales postings exist (3108/3308/3107). */
|
||||
euSalesDetected?: boolean
|
||||
/** Ledger-derived signal: utdelning/ägarlån postings exist (2898/2393/2893). */
|
||||
kuSignalDetected?: boolean
|
||||
/** Invoice-derived signal: invoices with ROT/RUT deductions exist. */
|
||||
rotRutSignalDetected?: boolean
|
||||
}
|
||||
|
||||
export function TaxSettingsForm({ settings, euSalesDetected = false }: TaxSettingsFormProps) {
|
||||
export function TaxSettingsForm({
|
||||
settings,
|
||||
euSalesDetected = false,
|
||||
kuSignalDetected = false,
|
||||
rotRutSignalDetected = false,
|
||||
}: TaxSettingsFormProps) {
|
||||
const t = useTranslations('settings_tax_form')
|
||||
const [vatRegistered, setVatRegistered] = useState(settings.vat_registered ?? false)
|
||||
const [fSkatt, setFSkatt] = useState(settings.f_skatt ?? true)
|
||||
@@ -31,6 +40,15 @@ export function TaxSettingsForm({ settings, euSalesDetected = false }: TaxSettin
|
||||
)
|
||||
const [hasEuTrade, setHasEuTrade] = useState(settings.vat_has_eu_trade ?? false)
|
||||
const [psEnabled, setPsEnabled] = useState(settings.periodisk_sammanstallning_enabled ?? false)
|
||||
const [kuEnabled, setKuEnabled] = useState(settings.kontrolluppgifter_enabled ?? false)
|
||||
const [rotRutEnabled, setRotRutEnabled] = useState(settings.rot_rut_enabled ?? false)
|
||||
const [ossEnabled, setOssEnabled] = useState(settings.oss_enabled ?? false)
|
||||
const [iossEnabled, setIossEnabled] = useState(settings.ioss_enabled ?? false)
|
||||
const [intrastatEnabled, setIntrastatEnabled] = useState(settings.intrastat_enabled ?? false)
|
||||
const [punktskattEnabled, setPunktskattEnabled] = useState(settings.punktskatt_enabled ?? false)
|
||||
const [fyllnadEnabled, setFyllnadEnabled] = useState(
|
||||
settings.fyllnadsinbetalning_enabled ?? false,
|
||||
)
|
||||
|
||||
const isEnskildFirma = settings.entity_type === 'enskild_firma'
|
||||
|
||||
@@ -422,6 +440,80 @@ export function TaxSettingsForm({ settings, euSalesDetected = false }: TaxSettin
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Kontrolluppgifter (KU) */}
|
||||
<section className="border-t border-border pt-8 space-y-4">
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
{t('kontrolluppgifter_heading')}
|
||||
</h2>
|
||||
|
||||
{kuSignalDetected && !kuEnabled && (
|
||||
<div className="rounded-lg border border-border p-4">
|
||||
<p className="text-sm">{t('ku_suggestion_title')}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{t('ku_suggestion_help')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-start space-x-3">
|
||||
<Checkbox
|
||||
id="kontrolluppgifter_enabled"
|
||||
checked={kuEnabled}
|
||||
onCheckedChange={(v) => setKuEnabled(v === true)}
|
||||
/>
|
||||
<input
|
||||
type="hidden"
|
||||
name="kontrolluppgifter_enabled"
|
||||
value={kuEnabled ? 'true' : 'false'}
|
||||
/>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="kontrolluppgifter_enabled" className="cursor-pointer">
|
||||
{t('kontrolluppgifter_label')}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('kontrolluppgifter_help')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* ROT/RUT */}
|
||||
<section className="border-t border-border pt-8 space-y-4">
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
{t('rot_rut_heading')}
|
||||
</h2>
|
||||
|
||||
{rotRutSignalDetected && !rotRutEnabled && (
|
||||
<div className="rounded-lg border border-border p-4">
|
||||
<p className="text-sm">{t('rot_rut_suggestion_title')}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{t('rot_rut_suggestion_help')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-start space-x-3">
|
||||
<Checkbox
|
||||
id="rot_rut_enabled"
|
||||
checked={rotRutEnabled}
|
||||
onCheckedChange={(v) => setRotRutEnabled(v === true)}
|
||||
/>
|
||||
<input
|
||||
type="hidden"
|
||||
name="rot_rut_enabled"
|
||||
value={rotRutEnabled ? 'true' : 'false'}
|
||||
/>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="rot_rut_enabled" className="cursor-pointer">
|
||||
{t('rot_rut_label')}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('rot_rut_help')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Preliminary tax */}
|
||||
<section className="border-t border-border pt-8 space-y-4">
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
@@ -443,6 +535,103 @@ export function TaxSettingsForm({ settings, euSalesDetected = false }: TaxSettin
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Long-tail deadlines: explicit opt-in only */}
|
||||
<section className="border-t border-border pt-8 space-y-4">
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
{t('more_deadlines_heading')}
|
||||
</h2>
|
||||
<p className="text-xs text-muted-foreground -mt-2">
|
||||
{t('more_deadlines_help')}
|
||||
</p>
|
||||
|
||||
{vatRegistered && (
|
||||
<>
|
||||
<div className="flex items-start space-x-3">
|
||||
<Checkbox
|
||||
id="oss_enabled"
|
||||
checked={ossEnabled}
|
||||
onCheckedChange={(v) => setOssEnabled(v === true)}
|
||||
/>
|
||||
<input type="hidden" name="oss_enabled" value={ossEnabled ? 'true' : 'false'} />
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="oss_enabled" className="cursor-pointer">{t('oss_label')}</Label>
|
||||
<p className="text-xs text-muted-foreground">{t('oss_help')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start space-x-3">
|
||||
<Checkbox
|
||||
id="ioss_enabled"
|
||||
checked={iossEnabled}
|
||||
onCheckedChange={(v) => setIossEnabled(v === true)}
|
||||
/>
|
||||
<input type="hidden" name="ioss_enabled" value={iossEnabled ? 'true' : 'false'} />
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="ioss_enabled" className="cursor-pointer">{t('ioss_label')}</Label>
|
||||
<p className="text-xs text-muted-foreground">{t('ioss_help')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start space-x-3">
|
||||
<Checkbox
|
||||
id="intrastat_enabled"
|
||||
checked={intrastatEnabled}
|
||||
onCheckedChange={(v) => setIntrastatEnabled(v === true)}
|
||||
/>
|
||||
<input
|
||||
type="hidden"
|
||||
name="intrastat_enabled"
|
||||
value={intrastatEnabled ? 'true' : 'false'}
|
||||
/>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="intrastat_enabled" className="cursor-pointer">
|
||||
{t('intrastat_label')}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">{t('intrastat_help')}</p>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="flex items-start space-x-3">
|
||||
<Checkbox
|
||||
id="punktskatt_enabled"
|
||||
checked={punktskattEnabled}
|
||||
onCheckedChange={(v) => setPunktskattEnabled(v === true)}
|
||||
/>
|
||||
<input
|
||||
type="hidden"
|
||||
name="punktskatt_enabled"
|
||||
value={punktskattEnabled ? 'true' : 'false'}
|
||||
/>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="punktskatt_enabled" className="cursor-pointer">
|
||||
{t('punktskatt_label')}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">{t('punktskatt_help')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start space-x-3">
|
||||
<Checkbox
|
||||
id="fyllnadsinbetalning_enabled"
|
||||
checked={fyllnadEnabled}
|
||||
onCheckedChange={(v) => setFyllnadEnabled(v === true)}
|
||||
/>
|
||||
<input
|
||||
type="hidden"
|
||||
name="fyllnadsinbetalning_enabled"
|
||||
value={fyllnadEnabled ? 'true' : 'false'}
|
||||
/>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="fyllnadsinbetalning_enabled" className="cursor-pointer">
|
||||
{t('fyllnadsinbetalning_label')}
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">{t('fyllnadsinbetalning_help')}</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { BankDetailsForm, validateBankFields } from '@/components/settings/BankDetailsForm'
|
||||
import { InvoiceSettingsForm } from '@/components/settings/InvoiceSettingsForm'
|
||||
import { InvoicePaymentLinkSettings } from '@/components/settings/InvoicePaymentLinkSettings'
|
||||
import { InvoiceEmailTextsSettings } from '@/components/settings/InvoiceEmailTextsSettings'
|
||||
import { InvoicePreviewCard } from '@/components/settings/InvoicePreviewCard'
|
||||
import { PdfPrintSettings } from '@/components/settings/PdfPrintSettings'
|
||||
@@ -79,6 +80,11 @@ export function InvoicingSettingsContent() {
|
||||
</div>
|
||||
</SettingsFormWrapper>
|
||||
|
||||
{/* Payment link opt-in: saves individually via toggle switch */}
|
||||
<div className="border-t border-border pt-8">
|
||||
<InvoicePaymentLinkSettings settings={settings} onUpdate={updateSettings} />
|
||||
</div>
|
||||
|
||||
{/* PDF settings: saves individually via toggle switches */}
|
||||
<div className="border-t border-border pt-8">
|
||||
<PdfPrintSettings settings={settings} onUpdate={updateSettings} />
|
||||
|
||||
@@ -26,6 +26,13 @@ export function TaxSettingsContent() {
|
||||
// sammanställning obligation the opt-in flags may not reflect. Suggestion
|
||||
// only; the user confirms via the ordinary checkboxes.
|
||||
const [euSalesDetected, setEuSalesDetected] = useState(false)
|
||||
// Same pattern for kontrolluppgifter: postings on 2898 (utdelning) or
|
||||
// 2393/2893 (ägarlån) imply a KU obligation on 31 January that AGI never
|
||||
// covers. Suggestion only; the user confirms via the checkbox.
|
||||
const [kuSignalDetected, setKuSignalDetected] = useState(false)
|
||||
// And for ROT/RUT: invoices with deductions mean a begäran om utbetalning
|
||||
// must reach Skatteverket by 31 January after the payment year.
|
||||
const [rotRutSignalDetected, setRotRutSignalDetected] = useState(false)
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
fetch('/api/settings/eu-trade-signal')
|
||||
@@ -36,6 +43,22 @@ export function TaxSettingsContent() {
|
||||
.catch(() => {
|
||||
// Best-effort signal: a failed fetch just hides the suggestion.
|
||||
})
|
||||
fetch('/api/settings/ku-signal')
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((json) => {
|
||||
if (!cancelled && json?.data?.has_ku_signal) setKuSignalDetected(true)
|
||||
})
|
||||
.catch(() => {
|
||||
// Best-effort signal: a failed fetch just hides the suggestion.
|
||||
})
|
||||
fetch('/api/settings/rot-rut-signal')
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((json) => {
|
||||
if (!cancelled && json?.data?.has_rot_rut) setRotRutSignalDetected(true)
|
||||
})
|
||||
.catch(() => {
|
||||
// Best-effort signal: a failed fetch just hides the suggestion.
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
@@ -105,6 +128,14 @@ export function TaxSettingsContent() {
|
||||
// means false rather than "keep stored value".
|
||||
employer_seasonal: employerRegistered && formData.get('employer_seasonal') === 'true',
|
||||
preliminary_tax_monthly: parseFloat(formData.get('preliminary_tax_monthly') as string) || null,
|
||||
kontrolluppgifter_enabled: formData.get('kontrolluppgifter_enabled') === 'true',
|
||||
rot_rut_enabled: formData.get('rot_rut_enabled') === 'true',
|
||||
// OSS/IOSS/Intrastat presuppose VAT registration; retire them with it.
|
||||
oss_enabled: vatRegistered && formData.get('oss_enabled') === 'true',
|
||||
ioss_enabled: vatRegistered && formData.get('ioss_enabled') === 'true',
|
||||
intrastat_enabled: vatRegistered && formData.get('intrastat_enabled') === 'true',
|
||||
punktskatt_enabled: formData.get('punktskatt_enabled') === 'true',
|
||||
fyllnadsinbetalning_enabled: formData.get('fyllnadsinbetalning_enabled') === 'true',
|
||||
}
|
||||
return {
|
||||
updates,
|
||||
@@ -127,7 +158,12 @@ export function TaxSettingsContent() {
|
||||
{showSkatteverket && <SkatteverketConnectPanel />}
|
||||
|
||||
<SettingsFormWrapper onSave={handleSave} className="space-y-0">
|
||||
<TaxSettingsForm settings={settings} euSalesDetected={euSalesDetected} />
|
||||
<TaxSettingsForm
|
||||
settings={settings}
|
||||
euSalesDetected={euSalesDetected}
|
||||
kuSignalDetected={kuSignalDetected}
|
||||
rotRutSignalDetected={rotRutSignalDetected}
|
||||
/>
|
||||
</SettingsFormWrapper>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -242,6 +242,9 @@ export default function CloudBackupCard() {
|
||||
<p className="text-sm text-muted-foreground mt-1 leading-relaxed">
|
||||
{t('ext_cloud_backup_card_tagline')}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-2 leading-relaxed">
|
||||
{t('ext_cloud_backup_legal_note')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user