288915c152
* fix(invoices): return attachment filename in delivery history summaries The 20260723003000 hardening dropped attachment_filename from list_invoice_delivery_summaries, so the delivery history UI always fell back to the generic "faktura.pdf" label. Recreate the RPC with the filename included: it is derived from company name, customer name, invoice number, and date, all already visible to every company member, so the minimization boundary is unchanged. Addresses stay masked and message content, BCC, and checksums stay server-side. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(reconciliation): surface own-account transfer legs in match-to-voucher by default The second (incoming) leg of a transfer between two of the company's own bank accounts was hidden in the 'Matcha mot befintlig verifikation' dialog because the voucher counted as 'already matched' once its outgoing leg was linked, even though the incoming account's line had no settling transaction. Users read the empty default list as 'the app won't let me link this'. get_account_gl_lines_for_matching now counts links per settlement account: a transaction provably on another cash account no longer marks the voucher as matched for the requested account, so the unsettled transfer leg surfaces by default (and auto-selects on an exact match). Same-account N:1 stays behind the 'Visa aven matchade verifikationer' opt-in, and transactions without a resolvable cash account conservatively keep counting everywhere. get_unlinked_gl_lines is deliberately untouched (feeds auto-reconcile). Companion guard: mark_entry_as_opening_balance now refuses entries with linked bank transactions, since half-settled transfer vouchers became reachable in the reconciliation view's unmatched table where 'Mark som IB' renders; re-tagging one would strand its transaction against a movement- excluded entry. getReconciliationStatus counts unmatched GL lines with the account-scoped RPC so the status card agrees with the table. Fixes #1026 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * perf(api): cut prod p95 latency via local JWT auth, single-RT company resolution, and report aggregate RPCs Baseline 2026-07-23 (487 prod samples): p50 160ms, p95 480ms, 13% of requests over 300ms. Target: p95 under 300ms. - requireAuth: verify JWTs locally via getClaims (ES256/JWKS) instead of a second network getUser per request; getUser fallback keeps HS256 self-hosted and existing test mocks working; middleware still revocation-checks every /api request - resolve_active_company RPC (20260723161000): one round trip replaces 2-3 queries in getActiveCompanyId and middleware; PGRST202/42501 fall back to the legacy query path - arsredovisning build-data: ~33 sequential round trips down to ~7, output byte-identical (snapshot-proven) - currency rate route: stop bypassing the exchange_rates cache (missing supabase arg caused an external Riksbanken call on every request) - document.get: parallelize row fetch, signed URL and audit event - list_company_accounts RPC (20260723170000): accounts list in one round trip instead of paging past PostgREST's 1000-row cap - vat-declaration route: drop a dead sequential company_settings query - get_kpi_report_aggregates RPC (20260723180000): KPI report's three full-period line scans collapsed into one aggregate call; dimension- filtered path unchanged - lint: fix 9 baseline errors, downgrade 4 react-hooks compiler rules to warn, zero the eslint baseline ratchet All four gates green: lint 0 errors, 9163 tests, check:guards, build. Migrations applied idempotently to staging only; prod receives them via Supabase branching on merge. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): resolve PR review findings across auth, VAT declaration, and IB retag - requireAuth getClaims fast path: pin iss (project URL) and aud ('authenticated'), log every fallback to getUser (ASVS V9.1 finding) - remove the ignored accountingMethod parameter from calculateVatDeclaration and the dead company_settings.accounting_method reads in xlsx/pdf/eskd routes; v1 API keeps accepting the query param but documents it as a no-op - close the mark_entry_as_opening_balance TOCTOU race with a transactions trigger (20260723190000, FOR KEY SHARE on journal_entries) + pg tests; applied to staging and smoke-verified both directions - re-add the 42501 tenant guard to branch-local migration 20260723160000 (function body had silently reverted to the pre-20260619130100 definition) - document the buildK3Noter tbFullRows full-TB contract (uppskjuten skatt opening balance per BFNAR 2012:1 ch.29) - add KPI VAT-liability test covering reduced-rate output accounts 2621/2631 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(db): use NULL-safe caller_is_company_member in opening-balance retag guard The re-added tenant guard carried the pre-20260703180000 raw NOT IN (SELECT user_company_ids()) pattern, which the null-safe-tenant-guards ratchet blocks. Staging re-synced. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
231 lines
8.0 KiB
TypeScript
231 lines
8.0 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
import { eventBus } from '@/lib/events/bus'
|
|
import {
|
|
parseJsonResponse,
|
|
createMockRouteParams,
|
|
createQueuedMockSupabase,
|
|
makeDocumentAttachment,
|
|
} from '@/tests/helpers'
|
|
|
|
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
|
|
|
const requireAuthMock = vi.fn()
|
|
vi.mock('@/lib/auth/require-auth', () => ({
|
|
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
|
}))
|
|
|
|
vi.mock('@/lib/company/context', () => ({
|
|
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
|
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
|
}))
|
|
|
|
vi.mock('@/lib/auth/require-write', () => ({
|
|
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
|
}))
|
|
|
|
vi.mock('@/lib/init', () => ({
|
|
ensureInitialized: vi.fn(),
|
|
}))
|
|
|
|
import { GET, DELETE } from '../route'
|
|
import { requireWritePermission } from '@/lib/auth/require-write'
|
|
import { NextResponse } from 'next/server'
|
|
|
|
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
reset()
|
|
eventBus.clear()
|
|
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase, error: null })
|
|
// Reset write-permission mock to default ok
|
|
vi.mocked(requireWritePermission).mockResolvedValue({ ok: true })
|
|
})
|
|
|
|
function makeReq(method: 'GET' | 'DELETE' = 'DELETE') {
|
|
return new Request('http://localhost/api/documents/doc-1', { method })
|
|
}
|
|
|
|
describe('GET /api/documents/[id]', () => {
|
|
it('returns 401 when not authenticated', async () => {
|
|
requireAuthMock.mockResolvedValue({
|
|
user: null,
|
|
supabase: mockSupabase,
|
|
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
|
})
|
|
const res = await GET(makeReq('GET'), createMockRouteParams({ id: 'doc-1' }))
|
|
const { status, body } = await parseJsonResponse(res)
|
|
expect(status).toBe(401)
|
|
expect(body).toEqual({ error: 'Unauthorized' })
|
|
})
|
|
|
|
it('returns 404 when the document is not found in the company', async () => {
|
|
enqueue({ data: null, error: null }) // doc lookup
|
|
const res = await GET(makeReq('GET'), createMockRouteParams({ id: 'doc-1' }))
|
|
const { status, body } = await parseJsonResponse<{ error: string }>(res)
|
|
expect(status).toBe(404)
|
|
expect(body.error).toBe('Document not found')
|
|
})
|
|
|
|
it('returns 500 when the signed URL cannot be created', async () => {
|
|
enqueue({ data: makeDocumentAttachment({ id: 'doc-1' }), error: null })
|
|
mockSupabase.storage.from.mockReturnValueOnce({
|
|
createSignedUrl: vi.fn().mockResolvedValue({ data: null, error: { message: 'boom' } }),
|
|
} as never)
|
|
|
|
const res = await GET(makeReq('GET'), createMockRouteParams({ id: 'doc-1' }))
|
|
const { status, body } = await parseJsonResponse<{ error: string }>(res)
|
|
|
|
expect(status).toBe(500)
|
|
expect(body.error).toContain('Failed to create download URL')
|
|
})
|
|
|
|
it('returns the document with a signed download URL and emits document.accessed', async () => {
|
|
const row = makeDocumentAttachment({
|
|
id: 'doc-1',
|
|
file_name: 'kvitto.pdf',
|
|
storage_path: 'documents/user-1/kvitto.pdf',
|
|
})
|
|
enqueue({ data: row, error: null })
|
|
|
|
const handler = vi.fn()
|
|
eventBus.on('document.accessed', handler)
|
|
|
|
const res = await GET(makeReq('GET'), createMockRouteParams({ id: 'doc-1' }))
|
|
const { status, body } = await parseJsonResponse<{
|
|
data: { id: string; download_url: string }
|
|
}>(res)
|
|
|
|
expect(status).toBe(200)
|
|
expect(body.data.id).toBe('doc-1')
|
|
expect(body.data.download_url).toBe('https://example.com/signed')
|
|
|
|
expect(mockSupabase.storage.from).toHaveBeenCalledWith('documents')
|
|
const storageBucket = mockSupabase.storage.from.mock.results[0]?.value
|
|
expect(storageBucket.createSignedUrl).toHaveBeenCalledWith('documents/user-1/kvitto.pdf', 3600)
|
|
|
|
expect(handler).toHaveBeenCalledOnce()
|
|
expect(handler).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
document: expect.objectContaining({ id: 'doc-1', file_name: 'kvitto.pdf' }),
|
|
userId: 'user-1',
|
|
companyId: 'company-1',
|
|
}),
|
|
)
|
|
})
|
|
})
|
|
|
|
describe('DELETE /api/documents/[id]', () => {
|
|
it('returns 401 when not authenticated', async () => {
|
|
requireAuthMock.mockResolvedValue({
|
|
user: null,
|
|
supabase: mockSupabase,
|
|
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
|
})
|
|
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
|
const { status, body } = await parseJsonResponse(res)
|
|
expect(status).toBe(401)
|
|
expect(body).toEqual({ error: 'Unauthorized' })
|
|
})
|
|
|
|
it('returns 403 when caller has read-only role', async () => {
|
|
vi.mocked(requireWritePermission).mockResolvedValue({
|
|
ok: false,
|
|
response: NextResponse.json(
|
|
{ error: 'Du har endast läsbehörighet i detta företag.' },
|
|
{ status: 403 },
|
|
),
|
|
})
|
|
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
|
const { status } = await parseJsonResponse(res)
|
|
expect(status).toBe(403)
|
|
})
|
|
|
|
it('returns 404 when document not found in company', async () => {
|
|
enqueue({ data: null, error: null }) // doc lookup
|
|
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
|
const { status, body } = await parseJsonResponse<{ error: string }>(res)
|
|
expect(status).toBe(404)
|
|
expect(body.error).toContain('hittades inte')
|
|
})
|
|
|
|
it('returns 409 with BFL message when doc is linked to a journal entry', async () => {
|
|
enqueue({
|
|
data: {
|
|
id: 'doc-1',
|
|
file_name: 'kvitto.pdf',
|
|
storage_path: 'documents/user-1/kvitto.pdf',
|
|
journal_entry_id: 'je-99',
|
|
user_id: 'user-1',
|
|
},
|
|
error: null,
|
|
})
|
|
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
|
const { status, body } = await parseJsonResponse<{ error: string }>(res)
|
|
expect(status).toBe(409)
|
|
expect(body.error).toContain('Bokföringslagen')
|
|
expect(body.error).toContain('7 kap')
|
|
})
|
|
|
|
it('deletes the row, removes Storage file, and emits document.deleted on unlinked doc', async () => {
|
|
enqueue({
|
|
data: {
|
|
id: 'doc-1',
|
|
file_name: 'kvitto.pdf',
|
|
storage_path: 'documents/user-1/kvitto.pdf',
|
|
journal_entry_id: null,
|
|
user_id: 'user-1',
|
|
},
|
|
error: null,
|
|
})
|
|
enqueue({ data: null, error: null }) // delete
|
|
|
|
const handler = vi.fn()
|
|
eventBus.on('document.deleted', handler)
|
|
|
|
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
|
const { status, body } = await parseJsonResponse<{ data: { id: string; deleted: boolean } }>(res)
|
|
|
|
expect(status).toBe(200)
|
|
expect(body.data).toEqual({ id: 'doc-1', deleted: true })
|
|
|
|
expect(mockSupabase.storage.from).toHaveBeenCalledWith('documents')
|
|
const storageBucket = mockSupabase.storage.from.mock.results[0]?.value
|
|
expect(storageBucket.remove).toHaveBeenCalledWith(['documents/user-1/kvitto.pdf'])
|
|
|
|
expect(handler).toHaveBeenCalledOnce()
|
|
expect(handler).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
document: expect.objectContaining({ id: 'doc-1', file_name: 'kvitto.pdf' }),
|
|
userId: 'user-1',
|
|
companyId: 'company-1',
|
|
}),
|
|
)
|
|
})
|
|
|
|
it('returns 409 with BFL message when DB trigger blocks deletion (defense-in-depth)', async () => {
|
|
// Caller bypasses the application-layer check (e.g. race condition).
|
|
// The block_document_deletion() trigger raises with "Bokföringslagen" in the
|
|
// message; the service maps it to a 409.
|
|
enqueue({
|
|
data: {
|
|
id: 'doc-1',
|
|
file_name: 'kvitto.pdf',
|
|
storage_path: 'documents/user-1/kvitto.pdf',
|
|
journal_entry_id: null,
|
|
user_id: 'user-1',
|
|
},
|
|
error: null,
|
|
})
|
|
enqueue({
|
|
data: null,
|
|
error: { message: 'Cannot delete document linked to a posted journal entry (Bokföringslagen)' },
|
|
})
|
|
|
|
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
|
const { status, body } = await parseJsonResponse<{ error: string }>(res)
|
|
expect(status).toBe(409)
|
|
expect(body.error).toContain('Bokföringslagen')
|
|
})
|
|
})
|