* feat(import): import skattekontoutdrag files into the skattekonto pipeline Users can now upload the kontohändelse export from Skatteverket's skattekonto e-service (current CSV layout, verified against a real 2026-08 export, plus legacy .skv files) instead of needing the paid API connection. Parsed rows land in skattekonto_transactions as booked file_import rows and inherit the existing 1630 rules engine, bulk booking, match-to-verifikat and both UIs unchanged. - Core parser lib/import/skattekonto-file/ with strict detection (orgnr header + saldo markers, or two distinct SKV vocabulary terms plus row shape), sum-integrity check (opening + rows must equal closing) and a wrong-company guard against company_settings. - computeDedupKey moves to core (lib/skatteverket/skattekonto-dedup); the extension re-imports it. File rows hash-key; content-signature partitioning skips rows already booked (either key form) and promotes matching upcoming rows in place. - syncSkattekonto gains a takeover step: an id-keyed API row adopts a matching hash-keyed imported row in place, so journal links survive connecting the API after a file import. Upcoming rows can no longer clobber a booked row on hash collision. - New skattekonto_file_imports table (company-scoped file-hash dedup) plus source/file_import_id provenance columns on skattekonto_transactions. - /import gains a Skattekontoutdrag wizard (upload/preview/result, deep link ?mode=skattekonto); the bank-file flow detects skattekonto files and redirects instead of importing them as bank rows. - /skattekonto renders imported rows for unconnected companies (attn line + import CTA) instead of discarding them behind the StartCard. - Free for everyone: the local-data booking/match routes were already ungated; only API sync/saldo stay capability-gated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(skattekonto): align the EF F-skatt rule with the 2012 -> 2013 decision 20260810120000 established that 2012 is not standard BAS and moved the booking templates to 2013 (owner taxes in an enskild firma are an eget uttag), but the skattekonto_rules seed still booked EF preliminarskatt against 2012. The file importer makes this rule fire for every EF F-skatt row, so bring it onto 2013 too. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(import): apply review findings on the skattekonto file import - Fix the takeover candidate comparator: the single-argument sort was an inconsistent relation and could adopt a stale upcoming row ahead of the booked file row in a 3+ candidate queue (regression test added), and page the candidate scan with fetchAllRows so a multi-year window is not silently capped at 1000 rows. - Fail parsing when a statement HAS saldo markers but not both readable balances: a file cut off before "Utgående saldo" previously skipped the sum check entirely. sum_valid stays null only for marker-less legacy files. - Count a promotion only when the UPDATE matched a row, so a concurrent sync cannot inflate promoted_count; log a failed finalize of the import record instead of discarding the error. - Migration (unshipped, edited in place): user_id is nullable with ON DELETE SET NULL so import records and their file-hash dedup survive user deletion, and the INSERT policy binds user_id to auth.uid() so a member cannot attribute an import to a colleague. pg tests cover both. - Make the upload drop zone keyboard-reachable (role, tabIndex, Enter/ Space) and give the six count-bearing strings ICU plural forms in both locales. Skipped with reasons on the PR: binding execute rows to file bytes and re-checking orgnr in execute (same client-trust model as the shipped bank-file execute; Zod + RLS scope writes to the caller's own company), a 404 test (the route has no not-found path), event-bus clearing in the route test (the route touches no events), and FK NOT VALID (new column referencing a brand-new empty table). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
136 lines
5.1 KiB
TypeScript
136 lines
5.1 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { withRouteContext } from '@/lib/api/with-route-context'
|
|
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
|
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
|
import { decodeFileContent } from '@/lib/import/shared/encoding'
|
|
import { normalizeOrgNumber } from '@/lib/import/shared/column-utils'
|
|
import { generateFileHash } from '@/lib/import/bank-file/parser'
|
|
import {
|
|
detectSkattekontoFile,
|
|
parseSkattekontoFile,
|
|
} from '@/lib/import/skattekonto-file/parser'
|
|
import { assignFileDedupKeys, partitionFileRows } from '@/lib/skatteverket/skattekonto-dedup'
|
|
import { fetchExistingSkattekontoRows } from '@/lib/import/skattekonto-file/import-service'
|
|
|
|
/**
|
|
* POST /api/import/skattekonto-file/parse
|
|
*
|
|
* Accepts a skattekontoutdrag (Skatteverket tax account statement, CSV or
|
|
* legacy .skv) via FormData and returns a parsed preview with row-level
|
|
* duplicate/promotion detection against skattekonto_transactions.
|
|
*
|
|
* Unlike the bank-file flow there is no separate check-duplicates route: the
|
|
* bank flow needs one only for its client-side generic_csv re-parse, which
|
|
* has no equivalent here, so the partition is computed inline.
|
|
*/
|
|
export const POST = withRouteContext(
|
|
'skattekonto_file.parse',
|
|
async (request, ctx) => {
|
|
const { supabase, companyId, log, requestId } = ctx
|
|
|
|
const formData = await request.formData()
|
|
const file = formData.get('file') as File | null
|
|
|
|
if (!file) {
|
|
return errorResponseFromCode('SKATTEKONTO_FILE_NO_FILE', log, { requestId })
|
|
}
|
|
if (file.size > 10 * 1024 * 1024) {
|
|
return errorResponseFromCode('SKATTEKONTO_FILE_TOO_LARGE', log, {
|
|
requestId,
|
|
details: { sizeMb: +(file.size / 1024 / 1024).toFixed(1) },
|
|
})
|
|
}
|
|
|
|
const opLog = log.child({ filename: file.name, sizeBytes: file.size })
|
|
|
|
try {
|
|
const arrayBuffer = await file.arrayBuffer()
|
|
const content = decodeFileContent(arrayBuffer)
|
|
const fileHash = generateFileHash(content)
|
|
|
|
const { data: existingImport } = await supabase
|
|
.from('skattekonto_file_imports')
|
|
.select('id, status, imported_count, created_at')
|
|
.eq('company_id', companyId)
|
|
.eq('file_hash', fileHash)
|
|
.maybeSingle()
|
|
|
|
if (existingImport && existingImport.status === 'completed') {
|
|
return errorResponseFromCode('SKATTEKONTO_FILE_DUPLICATE', opLog, {
|
|
requestId,
|
|
details: {
|
|
importId: existingImport.id,
|
|
importedCount: existingImport.imported_count,
|
|
importedAt: existingImport.created_at,
|
|
},
|
|
})
|
|
}
|
|
|
|
// Strict gate on purpose: without it, a bank CSV uploaded here by
|
|
// mistake could parse "well enough" (date;text;number) and land bank
|
|
// rows on the skattekonto.
|
|
if (!detectSkattekontoFile(content, file.name)) {
|
|
return errorResponseFromCode('SKATTEKONTO_FILE_NOT_RECOGNIZED', opLog, { requestId })
|
|
}
|
|
|
|
const parseResult = parseSkattekontoFile(content, file.name)
|
|
|
|
if (parseResult.sum_valid === false) {
|
|
return errorResponseFromCode('SKATTEKONTO_FILE_SUM_MISMATCH', opLog, {
|
|
requestId,
|
|
details: {
|
|
openingSaldo: parseResult.opening_saldo,
|
|
closingSaldo: parseResult.closing_saldo,
|
|
},
|
|
})
|
|
}
|
|
if (parseResult.rows.length === 0) {
|
|
return errorResponseFromCode('SKATTEKONTO_FILE_NO_ROWS', opLog, { requestId })
|
|
}
|
|
|
|
// Wrong-company guard: the modern export names its orgnr in the header
|
|
// row. A mismatch is surfaced for the preview step to confirm, not a
|
|
// hard block (legacy files have no header at all).
|
|
let orgNumberMismatch = false
|
|
if (parseResult.org_number) {
|
|
const { data: settings } = await supabase
|
|
.from('company_settings')
|
|
.select('org_number')
|
|
.eq('company_id', companyId)
|
|
.maybeSingle()
|
|
const companyOrg = normalizeOrgNumber(settings?.org_number ?? null)
|
|
const fileOrg = normalizeOrgNumber(parseResult.org_number)
|
|
orgNumberMismatch = companyOrg !== null && fileOrg !== null && companyOrg !== fileOrg
|
|
}
|
|
|
|
const existing = await fetchExistingSkattekontoRows(
|
|
supabase,
|
|
companyId,
|
|
parseResult.date_from as string,
|
|
parseResult.date_to as string,
|
|
)
|
|
const partition = partitionFileRows(
|
|
assignFileDedupKeys(parseResult.rows),
|
|
existing,
|
|
)
|
|
|
|
return NextResponse.json({
|
|
data: {
|
|
parse_result: parseResult,
|
|
file_hash: fileHash,
|
|
filename: file.name,
|
|
org_number_mismatch: orgNumberMismatch,
|
|
duplicate_row_indexes: partition.duplicates.map((d) => d.index),
|
|
promotion_row_indexes: partition.promotions.map((p) => p.index),
|
|
},
|
|
})
|
|
} catch (err) {
|
|
opLog.error('skattekonto file parse failed', err as Error)
|
|
return errorResponseFromCode('SKATTEKONTO_FILE_PARSE_FAILED', opLog, {
|
|
requestId,
|
|
details: { reason: err instanceof Error ? getUserErrorMessage(err) : 'unknown' },
|
|
})
|
|
}
|
|
},
|
|
)
|