Bug/vat selection warning (#583)

* refactor: update VAT handling logic for non-registered sellers and improve related comments

* chore: gate automated email flows behind 503 responses

Disables user-facing access to invoice payment reminders and salary
payslip email sending. Underlying lib code (reminder-processor,
PDF templates, notification_settings) is preserved for easy re-enable.

- Invoice reminders cron route returns 503; settings UI section removed.
- Payslip send route returns 503; original implementation kept as
  _sendPayslipsImpl for future re-enable.
- Push notifications were already extension-disabled, no change needed.

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

* chore: remove Recapt feedback widget

Strips the third-party Recapt SDK and its floating feedback bubble from
the app. The in-app contact form keeps working via the existing email
channel (/api/support/contact). Drops the Recapt entries from the CSP
and the subprocessor list in the privacy policy.

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

* feat: reject meaningless rättelser in correctEntry

Guard against zero-economic-effect corrections in the storno engine:
- Reject when proposed lines net to zero on every account (e.g. 1930
  debit 100 / 1930 credit 100), which would erase the original posting
  without representing any affärshändelse (BFL 5 kap. 5 §).
- Reject when proposed lines are an exact multiset match of the original
  entry — a rättelse must actually change something.

New MeaninglessCorrectionError wired through bookkeepingErrorResponse
(HTTP 400) and the Swedish error translator.

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

* feat: add date-range picker to resultat- and balansrapport

Adds optional from/to date filtering to the four operational financial
reports (resultatrapport, balansrapport, income-statement, balance-sheet)
so users can view a month, quarter, or custom range inside a fiscal year
without leaving the report. Defaults to YTD; "Hela året" preserves the
prior full-period behaviour (URL-identical, cache-stable).

- trial-balance engine accepts optional fromDate/toDate, rolling prior
  in-period activity into IB and clamping period activity to the window
- 12 API routes accept and validate from_date/to_date query params
- ReportDateRange chip picker persists preset per company, only renders
  on the four relevant tabs
- FiscalYearSelector now emits the period object so the range picker
  has bounds without an extra fetch
- PDF/XLSX filenames reflect the chosen range
- Resultatrapport drops the prior-year column when narrowed (full-year
  vs partial-year would mislead)
- 11 new tests (engine + parser); all existing report tests pass

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

* feat: add support for marking journal entries as "no document required"

- Introduced a new sidecar table `journal_entry_no_doc_required` to track entries that do not require separate documentation (e.g., bank fees, interest).
- Implemented API routes for creating and deleting exemptions, including validation and authorization checks.
- Added a toggle component in the UI to allow users to mark entries as exempt, with an optional reason.
- Updated relevant tests to cover the new functionality, including RLS checks and cascading deletes.
- Enhanced existing schemas and types to accommodate the new `vat_amount` field for supplier invoice items.

* fix: address PR review findings on no-doc-required + VAT changes

- pg-real cascade test wraps DELETE in gnubok.allow_delete='true' txn so the
  immutability trigger bypass fires (mirrors delete_last_voucher RPC).
- Clamp supplier-invoice item vat_amount to <= line_total * vat_rate via Zod
  refinement (with 1-öre rounding tolerance) so the manual override can't
  inflate the 2641 debit beyond the statutory ceiling.
- groupVatByRate falls back to line_total * rate when stored vat_amount is 0
  with a positive rate, so legacy/import paths leaving the column at its
  NOT NULL DEFAULT 0 don't silently understate ruta 48.
- ReportDateRange todayIso() and preset endpoints use local date components
  instead of toISOString() (UTC) — fixes the midnight-to-02:00 off-by-one
  that truncated a day from YTD / this-month / this-quarter for Swedish
  users.
- NoDocRequiredToggle restores the previous reason on failed POST/DELETE so
  the rolled-back toggle state stays consistent with the rendered reason.
- Document the company-scoped (not user-scoped) DELETE authorization policy
  on the no-document-required route.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-05-28 01:56:09 +02:00
committed by GitHub
co-authored by Claude Opus 4.7
parent 627109b5bd
commit a9b43ebeb7
73 changed files with 2552 additions and 714 deletions
+12 -3
View File
@@ -4,6 +4,7 @@ import { renderToBuffer } from '@react-pdf/renderer'
import { generateBalanceSheet } from '@/lib/reports/balance-sheet'
import { FinancialStatementPDF } from '@/lib/reports/financial-statement-pdf-template'
import { requireCompanyId } from '@/lib/company/context'
import { parseReportDateRange } from '@/lib/reports/date-range'
import type { CompanySettings } from '@/types'
export async function GET(request: Request) {
@@ -49,9 +50,17 @@ export async function GET(request: Request) {
)
}
const parsedRange = parseReportDateRange(searchParams, period)
if (!parsedRange.ok) {
return NextResponse.json({ error: parsedRange.error }, { status: 400 })
}
const range = parsedRange.range
const effectiveStart = range.fromDate ?? period.period_start
const effectiveEnd = range.toDate ?? period.period_end
try {
const report = await generateBalanceSheet(supabase, companyId, periodId)
report.period = { start: period.period_start, end: period.period_end }
const report = await generateBalanceSheet(supabase, companyId, periodId, range)
report.period = { start: effectiveStart, end: effectiveEnd }
const totalAssets = report.total_assets
const totalEquityLiab = report.total_equity_liabilities
@@ -98,7 +107,7 @@ export async function GET(request: Request) {
// "-utkast" suffix keeps the draft status visible even after the file
// leaves the browser — complements the in-document ÅRL 2:7 disclaimer.
const filename = `balansrakning-${report.period.start}-utkast.pdf`
const filename = `balansrakning-${report.period.start}--${report.period.end}-utkast.pdf`
return new Response(new Uint8Array(pdfBuffer), {
headers: {
+13 -3
View File
@@ -2,6 +2,7 @@ import { NextResponse } from 'next/server'
import { generateBalanceSheet } from '@/lib/reports/balance-sheet'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { parseReportDateRange } from '@/lib/reports/date-range'
export const GET = withRouteContext(
'report.balance_sheet',
@@ -24,13 +25,22 @@ export const GET = withRouteContext(
.eq('company_id', companyId)
.single()
let range: { fromDate?: string; toDate?: string } = {}
if (period) {
const parsed = parseReportDateRange(searchParams, period)
if (!parsed.ok) {
return NextResponse.json({ error: parsed.error }, { status: 400 })
}
range = parsed.range
}
try {
const result = await generateBalanceSheet(supabase, companyId!, periodId)
const result = await generateBalanceSheet(supabase, companyId!, periodId, range)
if (period) {
result.period = {
start: period.period_start,
end: period.period_end,
start: range.fromDate ?? period.period_start,
end: range.toDate ?? period.period_end,
}
}
+10 -2
View File
@@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { generateBalanceSheet } from '@/lib/reports/balance-sheet'
import { requireCompanyId } from '@/lib/company/context'
import { parseReportDateRange } from '@/lib/reports/date-range'
import {
reportToWorkbook,
textColumn,
@@ -52,8 +53,15 @@ export async function GET(request: Request) {
return NextResponse.json({ error: 'Räkenskapsperioden kunde inte läsas.' }, { status: 400 })
}
const parsedRange = parseReportDateRange(searchParams, period)
if (!parsedRange.ok) {
return NextResponse.json({ error: parsedRange.error }, { status: 400 })
}
const range = parsedRange.range
const effectiveEnd = range.toDate ?? period.period_end
try {
const report = await generateBalanceSheet(supabase, companyId, periodId)
const report = await generateBalanceSheet(supabase, companyId, periodId, range)
// Flatten nested sections into a single tabular view, mirroring how the
// PDF lays them out: each section's rows followed by a subtotal line, with
@@ -137,7 +145,7 @@ export async function GET(request: Request) {
},
])
const filename = xlsxFilename('balansrakning', companyRow?.company_name ?? '', period.period_end)
const filename = xlsxFilename('balansrakning', companyRow?.company_name ?? '', effectiveEnd)
return new NextResponse(new Uint8Array(buffer), {
headers: {
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+8 -2
View File
@@ -4,6 +4,7 @@ import { renderToBuffer } from '@react-pdf/renderer'
import { generateBalansrapport } from '@/lib/reports/balansrapport'
import { BalansrapportPDF } from '@/lib/reports/operational-report-pdf-template'
import { requireCompanyId } from '@/lib/company/context'
import { parseReportDateRange } from '@/lib/reports/date-range'
import type { CompanySettings } from '@/types'
export async function GET(request: Request) {
@@ -47,8 +48,13 @@ export async function GET(request: Request) {
)
}
const parsedRange = parseReportDateRange(searchParams, period)
if (!parsedRange.ok) {
return NextResponse.json({ error: parsedRange.error }, { status: 400 })
}
try {
const report = await generateBalansrapport(supabase, companyId, periodId)
const report = await generateBalansrapport(supabase, companyId, periodId, parsedRange.range)
const pdfBuffer = await renderToBuffer(
BalansrapportPDF({
@@ -62,7 +68,7 @@ export async function GET(request: Request) {
// report PDF route in this repo (resultatrapport, balance-sheet,
// income-statement). A balansrapport is a snapshot at period end, but
// consistent filenames let users sort and script-rename predictably.
const filename = `balansrapport-${report.period.start}.pdf`
const filename = `balansrapport-${report.period.start}--${report.period.end}.pdf`
return new Response(new Uint8Array(pdfBuffer), {
headers: {
+18 -1
View File
@@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { generateBalansrapport } from '@/lib/reports/balansrapport'
import { requireCompanyId } from '@/lib/company/context'
import { parseReportDateRange } from '@/lib/reports/date-range'
export async function GET(request: Request) {
const supabase = await createClient()
@@ -20,8 +21,24 @@ export async function GET(request: Request) {
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
}
const { data: period } = await supabase
.from('fiscal_periods')
.select('period_start, period_end')
.eq('id', periodId)
.eq('company_id', companyId)
.single()
let range: { fromDate?: string; toDate?: string } = {}
if (period) {
const parsed = parseReportDateRange(searchParams, period)
if (!parsed.ok) {
return NextResponse.json({ error: parsed.error }, { status: 400 })
}
range = parsed.range
}
try {
const result = await generateBalansrapport(supabase, companyId, periodId)
const result = await generateBalansrapport(supabase, companyId, periodId, range)
return NextResponse.json({ data: result })
} catch (err) {
return NextResponse.json(
+24 -6
View File
@@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { generateBalansrapport } from '@/lib/reports/balansrapport'
import { requireCompanyId } from '@/lib/company/context'
import { parseReportDateRange } from '@/lib/reports/date-range'
import {
reportToWorkbook,
textColumn,
@@ -35,14 +36,31 @@ export async function GET(request: Request) {
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
}
const { data: companyRow } = await supabase
.from('company_settings')
.select('company_name')
.eq('company_id', companyId)
.single()
const [{ data: companyRow }, { data: period }] = await Promise.all([
supabase
.from('company_settings')
.select('company_name')
.eq('company_id', companyId)
.single(),
supabase
.from('fiscal_periods')
.select('period_start, period_end')
.eq('id', periodId)
.eq('company_id', companyId)
.single(),
])
let range: { fromDate?: string; toDate?: string } = {}
if (period) {
const parsed = parseReportDateRange(searchParams, period)
if (!parsed.ok) {
return NextResponse.json({ error: parsed.error }, { status: 400 })
}
range = parsed.range
}
try {
const report = await generateBalansrapport(supabase, companyId, periodId)
const report = await generateBalansrapport(supabase, companyId, periodId, range)
const rows: FlatRow[] = []
for (const g of report.groups) {
+12 -3
View File
@@ -4,6 +4,7 @@ import { renderToBuffer } from '@react-pdf/renderer'
import { generateIncomeStatement } from '@/lib/reports/income-statement'
import { FinancialStatementPDF, type FinancialStatementGroup, type FinancialStatementSection, type FinancialStatementSummaryRow } from '@/lib/reports/financial-statement-pdf-template'
import { requireCompanyId } from '@/lib/company/context'
import { parseReportDateRange } from '@/lib/reports/date-range'
import type { CompanySettings } from '@/types'
// K2/K3 uppställningsform (ÅRL bilaga 2, kostnadsslagsindelad) splits class 8
@@ -71,9 +72,17 @@ export async function GET(request: Request) {
)
}
const parsedRange = parseReportDateRange(searchParams, period)
if (!parsedRange.ok) {
return NextResponse.json({ error: parsedRange.error }, { status: 400 })
}
const range = parsedRange.range
const effectiveStart = range.fromDate ?? period.period_start
const effectiveEnd = range.toDate ?? period.period_end
try {
const report = await generateIncomeStatement(supabase, companyId, periodId)
report.period = { start: period.period_start, end: period.period_end }
const report = await generateIncomeStatement(supabase, companyId, periodId, range)
report.period = { start: effectiveStart, end: effectiveEnd }
const operatingResult = Math.round((report.total_revenue - report.total_expenses) * 100) / 100
@@ -198,7 +207,7 @@ export async function GET(request: Request) {
// "-utkast" suffix keeps the draft status visible even after the file
// leaves the browser — complements the in-document ÅRL 2:7 disclaimer.
const filename = `resultatrakning-${report.period.start}-utkast.pdf`
const filename = `resultatrakning-${report.period.start}--${report.period.end}-utkast.pdf`
return new Response(new Uint8Array(pdfBuffer), {
headers: {
+13 -3
View File
@@ -2,6 +2,7 @@ import { NextResponse } from 'next/server'
import { generateIncomeStatement } from '@/lib/reports/income-statement'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { parseReportDateRange } from '@/lib/reports/date-range'
export const GET = withRouteContext(
'report.income_statement',
@@ -24,13 +25,22 @@ export const GET = withRouteContext(
.eq('company_id', companyId)
.single()
let range: { fromDate?: string; toDate?: string } = {}
if (period) {
const parsed = parseReportDateRange(searchParams, period)
if (!parsed.ok) {
return NextResponse.json({ error: parsed.error }, { status: 400 })
}
range = parsed.range
}
try {
const result = await generateIncomeStatement(supabase, companyId!, periodId)
const result = await generateIncomeStatement(supabase, companyId!, periodId, range)
if (period) {
result.period = {
start: period.period_start,
end: period.period_end,
start: range.fromDate ?? period.period_start,
end: range.toDate ?? period.period_end,
}
}
+10 -2
View File
@@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { generateIncomeStatement } from '@/lib/reports/income-statement'
import { requireCompanyId } from '@/lib/company/context'
import { parseReportDateRange } from '@/lib/reports/date-range'
import {
reportToWorkbook,
textColumn,
@@ -84,8 +85,15 @@ export async function GET(request: Request) {
return NextResponse.json({ error: 'Räkenskapsperioden kunde inte läsas.' }, { status: 400 })
}
const parsedRange = parseReportDateRange(searchParams, period)
if (!parsedRange.ok) {
return NextResponse.json({ error: parsedRange.error }, { status: 400 })
}
const range = parsedRange.range
const effectiveEnd = range.toDate ?? period.period_end
try {
const report = await generateIncomeStatement(supabase, companyId, periodId)
const report = await generateIncomeStatement(supabase, companyId, periodId, range)
const revenueRows = flatten(
report.revenue_sections,
@@ -139,7 +147,7 @@ export async function GET(request: Request) {
const filename = xlsxFilename(
'resultatrakning',
companyRow?.company_name ?? '',
period.period_end,
effectiveEnd,
)
return new NextResponse(new Uint8Array(buffer), {
headers: {
+8 -2
View File
@@ -4,6 +4,7 @@ import { renderToBuffer } from '@react-pdf/renderer'
import { generateResultatrapport } from '@/lib/reports/resultatrapport'
import { ResultatrapportPDF } from '@/lib/reports/operational-report-pdf-template'
import { requireCompanyId } from '@/lib/company/context'
import { parseReportDateRange } from '@/lib/reports/date-range'
import type { CompanySettings } from '@/types'
export async function GET(request: Request) {
@@ -49,8 +50,13 @@ export async function GET(request: Request) {
)
}
const parsedRange = parseReportDateRange(searchParams, period)
if (!parsedRange.ok) {
return NextResponse.json({ error: parsedRange.error }, { status: 400 })
}
try {
const report = await generateResultatrapport(supabase, companyId, periodId)
const report = await generateResultatrapport(supabase, companyId, periodId, parsedRange.range)
const pdfBuffer = await renderToBuffer(
ResultatrapportPDF({
@@ -60,7 +66,7 @@ export async function GET(request: Request) {
})
)
const filename = `resultatrapport-${report.period.start}.pdf`
const filename = `resultatrapport-${report.period.start}--${report.period.end}.pdf`
return new Response(new Uint8Array(pdfBuffer), {
headers: {
+18 -1
View File
@@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { generateResultatrapport } from '@/lib/reports/resultatrapport'
import { requireCompanyId } from '@/lib/company/context'
import { parseReportDateRange } from '@/lib/reports/date-range'
export async function GET(request: Request) {
const supabase = await createClient()
@@ -20,8 +21,24 @@ export async function GET(request: Request) {
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
}
const { data: period } = await supabase
.from('fiscal_periods')
.select('period_start, period_end')
.eq('id', periodId)
.eq('company_id', companyId)
.single()
let range: { fromDate?: string; toDate?: string } = {}
if (period) {
const parsed = parseReportDateRange(searchParams, period)
if (!parsed.ok) {
return NextResponse.json({ error: parsed.error }, { status: 400 })
}
range = parsed.range
}
try {
const result = await generateResultatrapport(supabase, companyId, periodId)
const result = await generateResultatrapport(supabase, companyId, periodId, range)
return NextResponse.json({ data: result })
} catch (err) {
return NextResponse.json(
+24 -6
View File
@@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { generateResultatrapport } from '@/lib/reports/resultatrapport'
import { requireCompanyId } from '@/lib/company/context'
import { parseReportDateRange } from '@/lib/reports/date-range'
import {
reportToWorkbook,
textColumn,
@@ -34,14 +35,31 @@ export async function GET(request: Request) {
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
}
const { data: companyRow } = await supabase
.from('company_settings')
.select('company_name')
.eq('company_id', companyId)
.single()
const [{ data: companyRow }, { data: period }] = await Promise.all([
supabase
.from('company_settings')
.select('company_name')
.eq('company_id', companyId)
.single(),
supabase
.from('fiscal_periods')
.select('period_start, period_end')
.eq('id', periodId)
.eq('company_id', companyId)
.single(),
])
let range: { fromDate?: string; toDate?: string } = {}
if (period) {
const parsed = parseReportDateRange(searchParams, period)
if (!parsed.ok) {
return NextResponse.json({ error: parsed.error }, { status: 400 })
}
range = parsed.range
}
try {
const report = await generateResultatrapport(supabase, companyId, periodId)
const report = await generateResultatrapport(supabase, companyId, periodId, range)
const rows: FlatRow[] = []
for (const g of report.groups) {