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
@@ -0,0 +1,157 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
createMockRequest,
parseJsonResponse,
createMockRouteParams,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(mockSupabase),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const mockRequireWrite = vi.fn().mockResolvedValue({ ok: true })
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => mockRequireWrite(...args),
}))
import { POST, DELETE } from '../route'
const mockUser = { id: 'user-1', email: 'test@test.se' }
describe('POST /api/bookkeeping/journal-entries/[id]/no-document-required', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
mockRequireWrite.mockResolvedValue({ ok: true })
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
})
it('returns 401 when not authenticated', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const request = createMockRequest(
'/api/bookkeeping/journal-entries/entry-1/no-document-required',
{ method: 'POST', body: { reason: 'Bankavgift' } }
)
const response = await POST(request, createMockRouteParams({ id: 'entry-1' }))
const { status, body } = await parseJsonResponse(response)
expect(status).toBe(401)
expect(body).toEqual({ error: 'Unauthorized' })
})
it('returns 403 when the user only has read access', async () => {
mockRequireWrite.mockResolvedValue({
ok: false,
response: new Response(JSON.stringify({ error: 'forbidden' }), {
status: 403,
headers: { 'content-type': 'application/json' },
}),
})
const request = createMockRequest(
'/api/bookkeeping/journal-entries/entry-1/no-document-required',
{ method: 'POST', body: {} }
)
const response = await POST(request, createMockRouteParams({ id: 'entry-1' }))
expect(response.status).toBe(403)
})
it('returns 404 when the entry does not belong to the active company', async () => {
enqueue({ data: null, error: null }) // journal_entries lookup misses
const request = createMockRequest(
'/api/bookkeeping/journal-entries/entry-1/no-document-required',
{ method: 'POST', body: { reason: 'Bankavgift' } }
)
const response = await POST(request, createMockRouteParams({ id: 'entry-1' }))
const { status, body } = await parseJsonResponse(response)
expect(status).toBe(404)
expect(body).toEqual({ error: 'Verifikationen hittades inte.' })
})
it('rejects a reason longer than 200 chars (Zod validation)', async () => {
const longReason = 'a'.repeat(201)
const request = createMockRequest(
'/api/bookkeeping/journal-entries/entry-1/no-document-required',
{ method: 'POST', body: { reason: longReason } }
)
const response = await POST(request, createMockRouteParams({ id: 'entry-1' }))
expect(response.status).toBe(400)
})
it('upserts the exemption and returns exempted: true', async () => {
enqueue({ data: { id: 'entry-1' }, error: null }) // entry lookup
enqueue({ data: null, error: null }) // upsert
const request = createMockRequest(
'/api/bookkeeping/journal-entries/entry-1/no-document-required',
{ method: 'POST', body: { reason: 'Bankavgift' } }
)
const response = await POST(request, createMockRouteParams({ id: 'entry-1' }))
const { status, body } = await parseJsonResponse(response)
expect(status).toBe(200)
expect(body).toEqual({ data: { exempted: true } })
})
it('accepts an empty body (no reason)', async () => {
enqueue({ data: { id: 'entry-1' }, error: null })
enqueue({ data: null, error: null })
const request = createMockRequest(
'/api/bookkeeping/journal-entries/entry-1/no-document-required',
{ method: 'POST', body: {} }
)
const response = await POST(request, createMockRouteParams({ id: 'entry-1' }))
const { status, body } = await parseJsonResponse(response)
expect(status).toBe(200)
expect(body).toEqual({ data: { exempted: true } })
})
})
describe('DELETE /api/bookkeeping/journal-entries/[id]/no-document-required', () => {
beforeEach(() => {
vi.clearAllMocks()
reset()
mockRequireWrite.mockResolvedValue({ ok: true })
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
})
it('returns 401 when not authenticated', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const request = createMockRequest(
'/api/bookkeeping/journal-entries/entry-1/no-document-required',
{ method: 'DELETE' }
)
const response = await DELETE(request, createMockRouteParams({ id: 'entry-1' }))
expect(response.status).toBe(401)
})
it('returns exempted: false on successful delete', async () => {
enqueue({ data: null, error: null }) // delete
const request = createMockRequest(
'/api/bookkeeping/journal-entries/entry-1/no-document-required',
{ method: 'DELETE' }
)
const response = await DELETE(request, createMockRouteParams({ id: 'entry-1' }))
const { status, body } = await parseJsonResponse(response)
expect(status).toBe(200)
expect(body).toEqual({ data: { exempted: false } })
})
})
@@ -0,0 +1,95 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { requireCompanyId } from '@/lib/company/context'
import { requireWritePermission } from '@/lib/auth/require-write'
import { z } from 'zod'
import { validateBody } from '@/lib/api/validate'
const SetNoDocSchema = z.object({
reason: z.string().trim().max(200).nullable().optional(),
})
export async function POST(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const writeCheck = await requireWritePermission(supabase, user.id)
if (!writeCheck.ok) return writeCheck.response
const companyId = await requireCompanyId(supabase, user.id)
const result = await validateBody(request, SetNoDocSchema)
if (!result.success) return result.response
const { data: entry, error: entryError } = await supabase
.from('journal_entries')
.select('id')
.eq('id', id)
.eq('company_id', companyId)
.maybeSingle()
if (entryError || !entry) {
return NextResponse.json({ error: 'Verifikationen hittades inte.' }, { status: 404 })
}
const { error } = await supabase
.from('journal_entry_no_doc_required')
.upsert(
{
journal_entry_id: id,
company_id: companyId,
user_id: user.id,
reason: result.data.reason ?? null,
},
{ onConflict: 'journal_entry_id' }
)
if (error) {
return NextResponse.json({ error: error.message }, { status: 400 })
}
return NextResponse.json({ data: { exempted: true } })
}
export async function DELETE(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const writeCheck = await requireWritePermission(supabase, user.id)
if (!writeCheck.ok) return writeCheck.response
const companyId = await requireCompanyId(supabase, user.id)
// Authorization is company-scoped, not user-scoped: any non-viewer member
// of the active company may revoke any exemption in that company. The flag
// is a shared bookkeeping artefact (same model as booking_template_library,
// mapping_rules, etc.) — exemptions are reviewed as a team. The audit_log
// trigger captures the DELETE with actor_id so accountability is preserved.
const { error } = await supabase
.from('journal_entry_no_doc_required')
.delete()
.eq('journal_entry_id', id)
.eq('company_id', companyId)
if (error) {
return NextResponse.json({ error: error.message }, { status: 400 })
}
return NextResponse.json({ data: { exempted: false } })
}
@@ -0,0 +1,32 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { requireCompanyId } from '@/lib/company/context'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
/**
* Returns the set of journal_entry IDs in the active company that the user has
* flagged as "no underlag required". The client uses this set to:
* - exclude exempted entries from the "Saknade underlag" filter
* - show a muted "no doc needed" indicator instead of the warning triangle
*/
export async function GET() {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const companyId = await requireCompanyId(supabase, user.id)
const rows = await fetchAllRows<{ journal_entry_id: string; reason: string | null }>(
({ from, to }) =>
supabase
.from('journal_entry_no_doc_required')
.select('journal_entry_id, reason')
.eq('company_id', companyId)
.range(from, to)
)
return NextResponse.json({ data: rows })
}