f266c386f3
* chore: repo-wide bloat sweep, remove dead code and fold duplicate helpers Remove 33 dead files, ~270 unreferenced exports/types, 13 dead i18n namespaces and 4 unused dependencies; fold byte-identical helper copies into one canonical home each (lib/utils chunk/sleep/utcDateStamp, lib/dates/iso, lib/invariants/uuid, lib/xml/escape, lib/reports/sru/format, lib/pdf/number-text, lib/browser/panel-request, lib/api/v1/body + v1ValidationError rolled out to ~55 v1 routes, booking-template schemas). No behaviour change: v1 bodies and status codes, MCP tool schemas, DB writes and money math are untouched. Naive ore rounding was deliberately not swapped for roundOre; see DECISIONS.md 2026-09-02 for the full list of things left alone on purpose. tsc, lint, 19588 unit tests and check:guards green; antipattern baseline ratcheted (naive-ore-round 622 -> 620, hand-rolled-invariant 115 -> 113). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test(transactions): import RawTransaction from @/types after the ingest re-export removal CI's type ratchet (check:types, full tsconfig) caught the one test file that still imported the type through lib/transactions/ingest. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
171 lines
5.5 KiB
TypeScript
171 lines
5.5 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import {
|
|
generateFullArchive,
|
|
estimateArchiveSize,
|
|
type ArchiveScope,
|
|
} from '@/lib/reports/full-archive-export'
|
|
import { withRouteContext } from '@/lib/api/with-route-context'
|
|
import { PRIVATE_NO_STORE_HEADERS, privateNoStore } from '@/lib/api/private-no-store'
|
|
import { utcDateStamp } from '@/lib/utils'
|
|
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
|
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
|
import { createServiceClient } from '@/lib/supabase/server'
|
|
|
|
export const runtime = 'nodejs'
|
|
export const maxDuration = 300
|
|
|
|
const SIZE_LIMIT_BYTES = 80 * 1024 * 1024
|
|
|
|
export const GET = withRouteContext('report.full_archive', async (request, ctx) => {
|
|
const { supabase, companyId, user, log, requestId } = ctx
|
|
const { searchParams } = new URL(request.url)
|
|
const scopeParam = searchParams.get('scope')
|
|
const periodId = searchParams.get('period_id')
|
|
const estimateOnly = searchParams.get('estimate') === '1'
|
|
const includeDocuments = searchParams.get('include_documents') !== 'false'
|
|
|
|
// Backward compat: a bare `period_id` without `scope` is treated as scope=period.
|
|
const scope: ArchiveScope =
|
|
scopeParam === 'period' || (!scopeParam && periodId) ? 'period' : 'all'
|
|
|
|
if (scope === 'period' && !periodId) {
|
|
return NextResponse.json(
|
|
{ error: 'period_id is required when scope=period' },
|
|
{ status: 400, headers: PRIVATE_NO_STORE_HEADERS }
|
|
)
|
|
}
|
|
|
|
const { data: membership, error: membershipError } = await supabase
|
|
.from('company_members')
|
|
.select('role')
|
|
.eq('company_id', companyId)
|
|
.eq('user_id', user.id)
|
|
.maybeSingle()
|
|
if (membershipError) {
|
|
log.error('failed to authorize full archive export', membershipError, {
|
|
userId: user.id,
|
|
companyId,
|
|
})
|
|
return privateNoStore(errorResponseFromCode('INTERNAL_ERROR', log, { requestId }))
|
|
}
|
|
if (!membership || !['owner', 'admin'].includes(membership.role)) {
|
|
log.warn('full archive access denied', {
|
|
userId: user.id,
|
|
companyId,
|
|
role: membership?.role ?? null,
|
|
})
|
|
return privateNoStore(errorResponseFromCode('FORBIDDEN', log, {
|
|
requestId,
|
|
details: { required_roles: ['owner', 'admin'] },
|
|
}))
|
|
}
|
|
|
|
// The complete statutory archive includes exact delivery evidence from all
|
|
// company senders. Only this owner/admin server path receives a service-role
|
|
// client; normal delivery history remains data-minimized by RLS. companyId
|
|
// comes from withRouteContext's authenticated active-company resolution,
|
|
// never from a request parameter, and is verified again below.
|
|
const archiveClient = createServiceClient()
|
|
const { data: verifiedMembership, error: verificationError } = await archiveClient
|
|
.from('company_members')
|
|
.select('role')
|
|
.eq('company_id', companyId)
|
|
.eq('user_id', user.id)
|
|
.maybeSingle()
|
|
if (verificationError) {
|
|
log.error('failed to verify full archive export with service role', verificationError, {
|
|
userId: user.id,
|
|
companyId,
|
|
})
|
|
return privateNoStore(errorResponseFromCode('INTERNAL_ERROR', log, { requestId }))
|
|
}
|
|
if (!verifiedMembership || !['owner', 'admin'].includes(verifiedMembership.role)) {
|
|
log.warn('full archive service-role verification denied', {
|
|
userId: user.id,
|
|
companyId,
|
|
role: verifiedMembership?.role ?? null,
|
|
})
|
|
return privateNoStore(errorResponseFromCode('FORBIDDEN', log, {
|
|
requestId,
|
|
details: { required_roles: ['owner', 'admin'] },
|
|
}))
|
|
}
|
|
|
|
try {
|
|
const estimate = await estimateArchiveSize(
|
|
archiveClient,
|
|
companyId,
|
|
scope,
|
|
scope === 'period' ? periodId! : undefined
|
|
)
|
|
|
|
if (estimateOnly) {
|
|
return NextResponse.json(
|
|
{
|
|
data: {
|
|
...estimate,
|
|
size_limit_bytes: SIZE_LIMIT_BYTES,
|
|
within_limit: estimate.total_bytes <= SIZE_LIMIT_BYTES,
|
|
},
|
|
},
|
|
{ headers: PRIVATE_NO_STORE_HEADERS },
|
|
)
|
|
}
|
|
|
|
if (includeDocuments && estimate.total_bytes > SIZE_LIMIT_BYTES) {
|
|
return NextResponse.json(
|
|
{
|
|
error: 'archive_too_large',
|
|
size_bytes: estimate.total_bytes,
|
|
size_limit_bytes: SIZE_LIMIT_BYTES,
|
|
},
|
|
{ status: 413, headers: PRIVATE_NO_STORE_HEADERS }
|
|
)
|
|
}
|
|
|
|
const zipBuffer = await generateFullArchive(
|
|
archiveClient,
|
|
companyId,
|
|
scope === 'period'
|
|
? { scope: 'period', period_id: periodId!, include_documents: includeDocuments }
|
|
: { scope: 'all', include_documents: includeDocuments }
|
|
)
|
|
|
|
const filename =
|
|
scope === 'period'
|
|
? `arkiv_${periodId}.zip`
|
|
: `arkiv_full_${companyId}_${utcDateStamp(new Date())}.zip`
|
|
|
|
log.info('full archive generated', {
|
|
userId: user.id,
|
|
companyId,
|
|
scope,
|
|
includeDocuments,
|
|
filename,
|
|
sizeBytes: zipBuffer.byteLength,
|
|
})
|
|
|
|
return new NextResponse(zipBuffer, {
|
|
status: 200,
|
|
headers: {
|
|
'Content-Type': 'application/zip',
|
|
'Content-Disposition': `attachment; filename="${filename}"`,
|
|
'Cache-Control': 'private, no-store',
|
|
},
|
|
})
|
|
} catch (err) {
|
|
log.error('full archive generation failed', err as Error, {
|
|
userId: user.id,
|
|
companyId,
|
|
scope,
|
|
includeDocuments,
|
|
})
|
|
const message = err instanceof Error ? err.message : 'Failed to generate archive'
|
|
const status = message.includes('not found') ? 404 : 500
|
|
return NextResponse.json(
|
|
{ error: getErrorMessage(err) },
|
|
{ status, headers: PRIVATE_NO_STORE_HEADERS },
|
|
)
|
|
}
|
|
})
|