* feat(invoice-inbox): store HTML mails as underlag, expandable field editor Body-only mails and .html attachments (including forwarded .eml bodies) no longer dead-end as "Fel vid bearbetning": the mail body is wrapped into a self-contained text/html document, stored through the normal upload/extract pipeline, and extracted via a new HTML-to-text Bedrock path, so the mail itself can serve as bookable underlag. Empty mails keep the error row, unsupported types are still rejected, and webhook retries dedupe on resend_email_id. Mail HTML is attacker-controlled, so rendering is fully sandboxed: iframe sandbox in the workspace preview and a CSP sandbox header on /api/documents/:id/inline for text/html. The type is accepted only from the email pipeline (EMAIL_ALLOWED_MIME_TYPES), never from manual upload. The "Extraherade falt" rail gains an expand button opening a centered dialog with the same autosaving field editor at a readable size (two columns), which also gives every failed or skipped extraction a manual fallback. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(bookkeeping): sortable verifikat list headers with amount sort - clickable sort toggles on the verifikat list headers (asc -> desc -> default) - total_amount computed column + sort_by total/description on the list route - failed list loads render an error card with retry, never the empty-ledger state Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(import): decode bank CSV as Windows-1252 fallback in column mapping The client read the uploaded file with file.text(), which is UTF-8-only, so Windows-1252 exports (e.g. Handelsbanken) rendered and re-parsed with U+FFFD in place of Swedish characters. Decode from bytes with the shared decodeFileContent() helper, matching what the server parse route does. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(bookkeeping): stackable sort keys on verifikat list headers - shift-click adds a column as secondary/tertiary sort key (max 3), plain click keeps the single-key tri-state cycle - sort_by accepts a comma-separated priority list; single tokens stay valid - voucher tiebreak follows the last key's direction (#972 parity) - priority numbers on stacked headers; hint text in the filter dialog Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(invoices): keep ROT/RUT deduction fields positive on credit notes Crediting an invoice with a ROT/RUT deduction failed 100% of the time: the credit-note path negated deduction_total (and per-item deduction_amount) like the other amounts, but both columns carry CHECK (>= 0), so Postgres rejected the insert and the user only saw 'Kunde inte skapa kreditfaktura'. Store the deduction fields as positive magnitudes, matching the convention everywhere else. The stored sign is inert on credit notes: the reversing verifikat recomputes the ROT/RUT split from the items, and the PDF and amount-to-pay logic skip deductions on credit notes. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * refactor(transactions): share the source chip across inbox and history modes Move SourceFilter to transaction-types.ts (widened with 'bank:other' and 'acct:<id>'), render the one toolbar ContextPicker in both view modes, and drop the narrower duplicate chip inside TransactionHistoryList. The history list now applies the acct:/bank:other narrowing itself and hides skattekonto rows under any bank-side selection. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore(deps): bump js-yaml to 4.3.1 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(schema): recognize PostgREST computed columns in the migration parser The verifikat amount sort orders by total_amount, a PostgREST computed column (a function on the journal_entries row type, migration 20260811100000). The schema guard only modeled real columns, so no-phantom-columns flagged the order as a phantom. Teach the parser that a function whose only argument is a table's row type joins that table's column set, with DROP FUNCTION retraction when the signature names the row type. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: resolve PR #1523 review findings - journal-entries route: append the globally unique id tiebreak to every direct-query sort; voucher series+number repeat across fiscal years, so the all-years scope could duplicate or drop rows at page boundaries. Existing order assertions updated, new all-years tiebreak test. - documents inline route: CSP source policy on HTML previews; sandbox alone still loads remote resources, letting a tracking pixel notify the sender on open. New route test asserts the full header. - JournalEntryList: catch rejected list requests so loading cannot stick forever, and gate every post-await state write behind a request generation so a slow earlier request cannot overwrite the current sort. - TransactionHistoryList: pagination follows the selected source scope (reachable with zero matches on the current page, hidden for the skattekonto scope it cannot affect). - transactions page: bank:other picker availability derives from history rows too, not only the pending inbox dataset. - DECISIONS.md: mark the superseded single-sort decision; record the credit-note deduction positive-magnitude invariant and its verified reader inventory (Swedish review flag). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: guard metadata refetches behind the list request generation fetchAttachmentCounts and fetchRattelseFlags write state after their own awaits; a stale list request's late completion could overwrite attachment counts and rattelse flags for rows a newer request just rendered, showing false missing-underlag warnings. Both helpers now take the caller's generation guard and discard stale completions, including the attachment-counts loaded flag. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
387 lines
14 KiB
TypeScript
387 lines
14 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
import {
|
|
createMockRequest,
|
|
parseJsonResponse,
|
|
createQueuedMockSupabase,
|
|
makeJournalEntry,
|
|
} from '@/tests/helpers'
|
|
|
|
// Mock dependencies
|
|
const { supabase: mockSupabase, enqueue, reset, findCalls } = createQueuedMockSupabase()
|
|
vi.mock('@/lib/supabase/server', () => ({
|
|
createClient: () => Promise.resolve(mockSupabase),
|
|
}))
|
|
|
|
vi.mock('@/lib/init', () => ({
|
|
ensureInitialized: vi.fn(),
|
|
}))
|
|
|
|
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 }),
|
|
}))
|
|
|
|
const mockCreateJournalEntry = vi.fn()
|
|
vi.mock('@/lib/bookkeeping/engine', () => ({
|
|
createJournalEntry: (...args: unknown[]) => mockCreateJournalEntry(...args),
|
|
}))
|
|
|
|
import { GET, POST } from '../route'
|
|
|
|
describe('GET /api/bookkeeping/journal-entries', () => {
|
|
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
reset()
|
|
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')
|
|
const response = await GET(request)
|
|
const { status, body } = await parseJsonResponse(response)
|
|
|
|
expect(status).toBe(401)
|
|
expect(body).toEqual({ error: 'Unauthorized' })
|
|
})
|
|
|
|
it('returns entries list', async () => {
|
|
const entries = [makeJournalEntry(), makeJournalEntry()]
|
|
enqueue({ data: entries, error: null, count: 2 })
|
|
|
|
const request = createMockRequest('/api/bookkeeping/journal-entries')
|
|
const response = await GET(request)
|
|
const { status, body } = await parseJsonResponse<{ data: unknown[]; count: number }>(response)
|
|
|
|
expect(status).toBe(200)
|
|
expect(body.data).toEqual(entries)
|
|
expect(body.count).toBe(2)
|
|
})
|
|
|
|
it('passes filters to query', async () => {
|
|
enqueue({ data: [], error: null, count: 0 })
|
|
|
|
const request = createMockRequest('/api/bookkeeping/journal-entries', {
|
|
searchParams: {
|
|
period_id: 'period-1',
|
|
status: 'posted',
|
|
date_from: '2024-01-01',
|
|
date_to: '2024-12-31',
|
|
limit: '10',
|
|
offset: '5',
|
|
// Strict period filtering: exercises the PostgREST path, not the RPC.
|
|
include_related: 'false',
|
|
},
|
|
})
|
|
const response = await GET(request)
|
|
const { status } = await parseJsonResponse(response)
|
|
|
|
expect(status).toBe(200)
|
|
expect(mockSupabase.from).toHaveBeenCalledWith('journal_entries')
|
|
})
|
|
|
|
it('uses RPC with include_related when period_id is set', async () => {
|
|
const rpcRows = [
|
|
{
|
|
entry: { ...makeJournalEntry({ id: 'je-1' }), out_of_period: false },
|
|
total_count: 2,
|
|
},
|
|
{
|
|
entry: { ...makeJournalEntry({ id: 'je-2' }), out_of_period: true },
|
|
total_count: 2,
|
|
},
|
|
]
|
|
enqueue({ data: rpcRows, error: null })
|
|
|
|
const request = createMockRequest('/api/bookkeeping/journal-entries', {
|
|
searchParams: { period_id: 'period-1' },
|
|
})
|
|
const response = await GET(request)
|
|
const { status, body } = await parseJsonResponse<{
|
|
data: Array<{ id: string; out_of_period?: boolean }>
|
|
count: number
|
|
}>(response)
|
|
|
|
expect(status).toBe(200)
|
|
expect(mockSupabase.rpc).toHaveBeenCalledWith(
|
|
'list_fiscal_period_entries_with_related',
|
|
expect.objectContaining({
|
|
p_company_id: 'company-1',
|
|
p_period_id: 'period-1',
|
|
p_include_related: true,
|
|
})
|
|
)
|
|
expect(body.data).toHaveLength(2)
|
|
expect(body.data[1].out_of_period).toBe(true)
|
|
expect(body.count).toBe(2)
|
|
})
|
|
|
|
it('forwards explicit ?status=cancelled to the RPC', async () => {
|
|
enqueue({ data: [], error: null })
|
|
|
|
const request = createMockRequest('/api/bookkeeping/journal-entries', {
|
|
searchParams: { period_id: 'period-1', status: 'cancelled' },
|
|
})
|
|
await GET(request)
|
|
|
|
// The RPC itself hides cancelled entries unless p_status='cancelled' is
|
|
// passed explicitly (see migration 20260428153500). The behavior of the
|
|
// hide-by-default logic lives in SQL and is covered by pg-real tests.
|
|
expect(mockSupabase.rpc).toHaveBeenCalledWith(
|
|
'list_fiscal_period_entries_with_related',
|
|
expect.objectContaining({ p_status: 'cancelled' })
|
|
)
|
|
})
|
|
|
|
it('uses the direct query path (not the RPC) when a search term is set', async () => {
|
|
enqueue({ data: [], error: null, count: 0 })
|
|
|
|
const request = createMockRequest('/api/bookkeeping/journal-entries', {
|
|
searchParams: { period_id: 'period-1', search: 'luftfyllning' },
|
|
})
|
|
const response = await GET(request)
|
|
const { status } = await parseJsonResponse(response)
|
|
|
|
expect(status).toBe(200)
|
|
// Free-text search needs an ILIKE the include_related RPC can't express, so
|
|
// the route must fall through to the direct PostgREST query.
|
|
expect(mockSupabase.from).toHaveBeenCalledWith('journal_entries')
|
|
expect(mockSupabase.rpc).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('orders by the total_amount computed column on amount sort, bypassing the RPC', async () => {
|
|
enqueue({ data: [], error: null, count: 0 })
|
|
|
|
const request = createMockRequest('/api/bookkeeping/journal-entries', {
|
|
searchParams: { period_id: 'period-1', sort_by: 'total_desc' },
|
|
})
|
|
const response = await GET(request)
|
|
const { status } = await parseJsonResponse(response)
|
|
|
|
expect(status).toBe(200)
|
|
// Amount sort orders by a PostgREST computed column (migration
|
|
// 20260811100000) that the include_related RPC can't express, so the
|
|
// route must fall through to the direct query (strict period view),
|
|
// exactly like voucher sort.
|
|
expect(mockSupabase.from).toHaveBeenCalledWith('journal_entries')
|
|
expect(mockSupabase.rpc).not.toHaveBeenCalled()
|
|
expect(findCalls('journal_entries', 'order')[0]).toEqual([
|
|
'total_amount',
|
|
{ ascending: false },
|
|
])
|
|
})
|
|
|
|
it('orders by description on description sort, bypassing the RPC', async () => {
|
|
enqueue({ data: [], error: null, count: 0 })
|
|
|
|
const request = createMockRequest('/api/bookkeeping/journal-entries', {
|
|
searchParams: { period_id: 'period-1', sort_by: 'description_asc' },
|
|
})
|
|
const response = await GET(request)
|
|
const { status } = await parseJsonResponse(response)
|
|
|
|
expect(status).toBe(200)
|
|
expect(mockSupabase.rpc).not.toHaveBeenCalled()
|
|
expect(findCalls('journal_entries', 'order')[0]).toEqual([
|
|
'description',
|
|
{ ascending: true },
|
|
])
|
|
})
|
|
|
|
it('chains stacked sort keys in priority order and bypasses the RPC', async () => {
|
|
enqueue({ data: [], error: null, count: 0 })
|
|
|
|
const request = createMockRequest('/api/bookkeeping/journal-entries', {
|
|
searchParams: { period_id: 'period-1', sort_by: 'total_desc,description_asc' },
|
|
})
|
|
const response = await GET(request)
|
|
const { status } = await parseJsonResponse(response)
|
|
|
|
expect(status).toBe(200)
|
|
expect(mockSupabase.rpc).not.toHaveBeenCalled()
|
|
// Priority order preserved, then the voucher tiebreak in the LAST key's
|
|
// direction (ascending here), then the globally unique id tiebreak:
|
|
// series+number repeat across fiscal years, so equal keys need a total
|
|
// order for stable pagination.
|
|
expect(findCalls('journal_entries', 'order')).toEqual([
|
|
['total_amount', { ascending: false }],
|
|
['description', { ascending: true }],
|
|
['voucher_series', { ascending: true }],
|
|
['voucher_number', { ascending: true }],
|
|
['id', { ascending: true }],
|
|
])
|
|
})
|
|
|
|
it('dedupes repeated sort columns and caps the stack at three keys', async () => {
|
|
enqueue({ data: [], error: null, count: 0 })
|
|
|
|
const request = createMockRequest('/api/bookkeeping/journal-entries', {
|
|
searchParams: {
|
|
include_related: 'false',
|
|
sort_by: 'date_desc,date_asc,nonsense,voucher_desc,total_asc,description_asc',
|
|
},
|
|
})
|
|
const response = await GET(request)
|
|
const { status } = await parseJsonResponse(response)
|
|
|
|
expect(status).toBe(200)
|
|
// date deduped (first token wins), the unknown token is ignored, and the
|
|
// stack caps at three keys (date, voucher, total): description never
|
|
// makes it in. Voucher is in the stack, so no series+number tiebreak is
|
|
// appended; the id tiebreak always is (duplicate series+number across
|
|
// fiscal years on the all-years scope).
|
|
expect(findCalls('journal_entries', 'order')).toEqual([
|
|
['entry_date', { ascending: false }],
|
|
['voucher_series', { ascending: false }],
|
|
['voucher_number', { ascending: false }],
|
|
['total_amount', { ascending: true }],
|
|
['id', { ascending: true }],
|
|
])
|
|
})
|
|
|
|
it('appends the id tiebreak on the all-years scope where voucher identifiers repeat', async () => {
|
|
enqueue({ data: [], error: null, count: 0 })
|
|
|
|
// No period_id: the "Alla räkenskapsår" scope, where A-1 exists once per
|
|
// fiscal year. Without a globally unique final key, rows with equal
|
|
// (entry_date, series, number) can swap between page requests and be
|
|
// duplicated or dropped at page boundaries.
|
|
const request = createMockRequest('/api/bookkeeping/journal-entries', {
|
|
searchParams: { include_related: 'false', sort_by: 'date_desc' },
|
|
})
|
|
const response = await GET(request)
|
|
const { status } = await parseJsonResponse(response)
|
|
|
|
expect(status).toBe(200)
|
|
const orderCalls = findCalls('journal_entries', 'order')
|
|
expect(orderCalls[orderCalls.length - 1]).toEqual(['id', { ascending: false }])
|
|
})
|
|
|
|
it('still serves a single date sort key through the include_related RPC', async () => {
|
|
enqueue({ data: [], error: null })
|
|
|
|
const request = createMockRequest('/api/bookkeeping/journal-entries', {
|
|
searchParams: { period_id: 'period-1', sort_by: 'date_asc' },
|
|
})
|
|
const response = await GET(request)
|
|
const { status } = await parseJsonResponse(response)
|
|
|
|
expect(status).toBe(200)
|
|
expect(mockSupabase.rpc).toHaveBeenCalledWith(
|
|
'list_fiscal_period_entries_with_related',
|
|
expect.objectContaining({ p_sort_date: 'asc' }),
|
|
)
|
|
})
|
|
|
|
it('accepts a large limit (the "Alla" page size) and a negative offset without erroring', async () => {
|
|
enqueue({ data: [], error: null, count: 0 })
|
|
|
|
const request = createMockRequest('/api/bookkeeping/journal-entries', {
|
|
// 'Alla' sends a large limit; the route clamps it to MAX_LIMIT. A negative
|
|
// offset is floored to 0. Both are bounded server-side (ASVS V1.2.5).
|
|
searchParams: { limit: '999999', offset: '-5', include_related: 'false' },
|
|
})
|
|
const response = await GET(request)
|
|
const { status } = await parseJsonResponse(response)
|
|
|
|
expect(status).toBe(200)
|
|
expect(mockSupabase.from).toHaveBeenCalledWith('journal_entries')
|
|
})
|
|
|
|
it('returns 500 on database error', async () => {
|
|
enqueue({ data: null, error: { message: 'DB error' } })
|
|
|
|
const request = createMockRequest('/api/bookkeeping/journal-entries')
|
|
const response = await GET(request)
|
|
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
|
|
|
expect(status).toBe(500)
|
|
// Raw Supabase messages never reach the response field (issue #337).
|
|
expect(body.error).toBe('Verifikationerna kunde inte hämtas. Försök igen.')
|
|
})
|
|
})
|
|
|
|
const VALID_UUID = '550e8400-e29b-41d4-a716-446655440000'
|
|
|
|
describe('POST /api/bookkeeping/journal-entries', () => {
|
|
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
reset()
|
|
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', {
|
|
method: 'POST',
|
|
body: {},
|
|
})
|
|
const response = await POST(request)
|
|
const { status, body } = await parseJsonResponse(response)
|
|
|
|
expect(status).toBe(401)
|
|
expect(body).toEqual({ error: 'Unauthorized' })
|
|
})
|
|
|
|
it('creates journal entry and returns it', async () => {
|
|
const entry = makeJournalEntry()
|
|
mockCreateJournalEntry.mockResolvedValue(entry)
|
|
|
|
const input = {
|
|
fiscal_period_id: VALID_UUID,
|
|
entry_date: '2024-06-15',
|
|
description: 'Test entry',
|
|
source_type: 'manual',
|
|
lines: [
|
|
{ account_number: '1930', debit_amount: 1000, credit_amount: 0 },
|
|
{ account_number: '3001', debit_amount: 0, credit_amount: 1000 },
|
|
],
|
|
}
|
|
|
|
const request = createMockRequest('/api/bookkeeping/journal-entries', {
|
|
method: 'POST',
|
|
body: input,
|
|
})
|
|
const response = await POST(request)
|
|
const { status, body } = await parseJsonResponse<{ data: unknown }>(response)
|
|
|
|
expect(status).toBe(200)
|
|
expect(body.data).toEqual(entry)
|
|
expect(mockCreateJournalEntry).toHaveBeenCalledWith(expect.anything(), 'company-1', 'user-1', input)
|
|
})
|
|
|
|
it('returns 400 when engine throws', async () => {
|
|
mockCreateJournalEntry.mockRejectedValue(new Error('Unbalanced entry'))
|
|
|
|
const request = createMockRequest('/api/bookkeeping/journal-entries', {
|
|
method: 'POST',
|
|
body: {
|
|
fiscal_period_id: VALID_UUID,
|
|
entry_date: '2024-06-15',
|
|
description: 'Bad entry',
|
|
source_type: 'manual',
|
|
lines: [
|
|
{ account_number: '1930', debit_amount: 1000, credit_amount: 0 },
|
|
{ account_number: '3001', debit_amount: 0, credit_amount: 500 },
|
|
],
|
|
},
|
|
})
|
|
const response = await POST(request)
|
|
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
|
|
|
expect(status).toBe(400)
|
|
// Untyped engine errors map to the Swedish context fallback (issue #337).
|
|
expect(body.error).toBe('Kunde inte hantera verifikationen. Försök igen.')
|
|
})
|
|
})
|