Files
accounted/app/api/documents/[id]/inline/route.ts
T
MattssonandClaude Fable 5 9dbaebcc50 fix(invoices): ROT/RUT credit notes; verifikat amount sort, HTML underlag, source chip (#1523)
* 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>
2026-08-11 23:12:18 +02:00

113 lines
4.9 KiB
TypeScript

import { NextResponse } from 'next/server'
import { createServiceClient } from '@/lib/supabase/server'
import { contentDisposition } from '@/lib/api/content-disposition'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
/**
* GET /api/documents/:id/inline
*
* Same-origin proxy that streams a document attachment with
* `Content-Disposition: inline`, allowing it to render inside
* an <iframe> or <img> tag.
*
* Supabase Storage signed URLs return `Content-Disposition: attachment`,
* which browsers refuse to render inline: that triggers the
* "Det här innehållet har blockerats" error in journal entry previews.
*
* Defense in depth: the user's cookie-bound client authorizes access
* (RLS + explicit company_id filter) before the service-role client
* fetches the file from the non-public `documents` bucket.
*/
const EXTENSION_MIME_MAP: Record<string, string> = {
pdf: 'application/pdf',
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
png: 'image/png',
webp: 'image/webp',
}
/**
* Resolve the response Content-Type. Some legacy uploads landed with
* `mime_type = null` or `application/octet-stream` (browsers sometimes
* report empty File.type for files dragged from certain sources). Combined
* with the new `X-Content-Type-Options: nosniff` header on this route,
* that broke Chrome's PDF viewer for older rows: the plugin would load
* via <object type="application/pdf"> but refuse to parse a response
* served as octet-stream. Falling back to the file extension covers every
* legacy row without a DB backfill.
*/
function resolveContentType(fileName: string, dbMimeType: string | null): string {
if (dbMimeType && dbMimeType !== 'application/octet-stream') return dbMimeType
const ext = fileName.toLowerCase().split('.').pop() ?? ''
return EXTENSION_MIME_MAP[ext] ?? dbMimeType ?? 'application/octet-stream'
}
export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
'document.inline',
async (_request, { supabase, companyId }, { params }) => {
const { id } = await params
// Authorize via the auth-bound client and the active tenant. RLS remains
// the second layer, while the explicit company filter prevents a document
// from another membership being opened through a guessed identifier.
const { data: doc, error: docError } = await supabase
.from('document_attachments')
.select('id, company_id, file_name, mime_type, storage_path')
.eq('id', id)
.eq('company_id', companyId)
.single()
if (docError || !doc) {
return NextResponse.json({ error: 'Document not found' }, { status: 404 })
}
// Use the service-role client to read from the non-public bucket only after
// the active-company authorization check above has succeeded.
const serviceClient = createServiceClient()
const { data: blob, error: downloadError } = await serviceClient.storage
.from('documents')
.download(doc.storage_path)
if (downloadError || !blob) {
return NextResponse.json(
{ error: `Failed to download document: ${getUserErrorMessage(downloadError) ?? 'unknown error'}` },
{ status: 500 },
)
}
const contentType = resolveContentType(doc.file_name, doc.mime_type)
return new NextResponse(blob, {
status: 200,
headers: {
'Content-Type': contentType,
// RFC 5987 dual form: NFD filenames from macOS/iOS uploads contain
// combining marks (> 0xFF), which undici Headers reject as non-
// ByteString values; splicing the raw name here 500ed the route.
'Content-Disposition': contentDisposition('inline', doc.file_name),
'Cache-Control': 'private, no-store',
// Block MIME sniffing: Content-Type is derived from DB metadata
// (with extension fallback for legacy rows), never from response
// content. Without nosniff a tampered file_name extension could
// serve a stored document under an attacker-chosen MIME type.
'X-Content-Type-Options': 'nosniff',
// text/html documents are attacker-controlled mail bodies from the
// invoice inbox. Served inline on the app origin they would execute
// scripts with our origin's authority: CSP sandbox (no tokens) makes
// the rendered document opaque-origin and script-free wherever it is
// opened, iframe or direct tab. The source policy blocks outbound
// requests on top of that: sandbox alone still loads remote images,
// so a tracking pixel would notify the sender when the preview is
// opened. Inline styles and embedded data:/blob: images keep working.
...(contentType === 'text/html'
? {
'Content-Security-Policy':
"sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:",
}
: {}),
},
})
},
)