feat: Data Management (DSGVO Art. 15/20/30 — export, inventory, retention)

- Data Management API: inventory (Art. 30 Verarbeitungsverzeichnis) + export
- JSON export with SHA-256 checksum (GoBD Jahresarchiv)
- CSV export (DATEV/Excel-compatible)
- Export history (audit-logged)
- Retention periods (8/6 years per GoBD)
- Art. 17 erasure notice (pseudonymization, legal precedence)
- 159 records across 10 categories with legal basis per category
This commit is contained in:
Z User committed 2026-10-27 16:27:42 +00:00
1 parent 1dd2563172
commit 6c42c6525a
8 files changed
+491

No files matched your search

@@ -0,0 +1,136 @@
import { NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { createHash } from 'crypto'
export const dynamic = 'force-dynamic'
// GET /api/aos/data-management/export?format=json|csv&scope=all|company:<id>
// DSGVO Art. 15 (right of access) + Art. 20 (data portability).
// Returns all data (or a specific company's data) as JSON or CSV,
// with a SHA-256 checksum for integrity verification.
export async function GET(req: Request) {
try {
const { searchParams } = new URL(req.url)
const format = searchParams.get('format') ?? 'json'
const scope = searchParams.get('scope') ?? 'all'
let companyFilter: string | null = null
if (scope.startsWith('company:')) {
companyFilter = scope.split(':')[1]!
}
// Fetch all data (or company-scoped)
const companies = await db.company.findMany({
where: companyFilter ? { id: companyFilter } : undefined,
include: { persons: true, deals: true, projects: true, invoices: true, licenses: true, leads: true },
})
const auditLogs = await db.auditLog.findMany({
where: companyFilter
? { OR: [{ entity: 'Company', entityId: companyFilter }] }
: undefined,
orderBy: { createdAt: 'desc' },
take: 500,
})
const tickets = await db.ticket.findMany({
where: companyFilter ? { companyId: companyFilter } : undefined,
include: { messages: true },
})
const contracts = await db.contract.findMany({
where: companyFilter ? { companyId: companyFilter } : undefined,
})
const expenses = await db.expense.findMany({
where: companyFilter ? { companyId: companyFilter } : undefined,
})
const portalApprovals = companyFilter
? await db.portalApproval.findMany({
where: { project: { companyId: companyFilter } },
})
: await db.portalApproval.findMany()
const exportData = {
metadata: {
exportedAt: new Date().toISOString(),
scope: scope,
format: format,
version: '1.0.0',
legalBasis: companyFilter
? 'DSGVO Art. 15 (Auskunftsrecht) + Art. 20 (Datenübertragbarkeit)'
: 'GoBD Jahresarchiv (Vollständiger Datenexport)',
agency: 'Nordlicht Digital GmbH',
},
companies: companies.map((c) => ({
id: c.id,
name: c.name,
legalForm: c.legalForm,
vatId: c.vatId,
website: c.website,
city: c.city,
source: c.source,
createdAt: c.createdAt,
persons: c.persons.map((p) => ({ firstName: p.firstName, lastName: p.lastName, email: p.email, role: p.role })),
deals: c.deals.map((d) => ({ title: d.title, stage: d.stage, valueCents: d.valueCents, probability: d.probability })),
projects: c.projects.map((p) => ({ name: p.name, type: p.type, status: p.status, progress: p.progress })),
invoices: c.invoices.map((i) => ({ number: i.number, status: i.status, grossCents: i.grossCents, issueDate: i.issueDate })),
licenses: c.licenses.map((l) => ({ product: l.product, plan: l.plan, status: l.status })),
})),
tickets: tickets.map((t) => ({
number: t.number,
subject: t.subject,
status: t.status,
priority: t.priority,
messages: t.messages.map((m) => ({ from: m.fromName, fromType: m.fromType, body: m.body, createdAt: m.createdAt })),
})),
contracts: contracts.map((c) => ({ number: c.number, type: c.type, title: c.title, status: c.status, valueCents: c.valueCents })),
expenses: expenses.map((e) => ({ number: e.number, description: e.description, amountCents: e.amountCents, date: e.date, billable: e.billable })),
portalApprovals: portalApprovals.map((a) => ({ title: a.title, status: a.status, decidedAt: a.decidedAt, decidedBy: a.decidedBy })),
auditLog: auditLogs.map((a) => ({ action: a.action, entity: a.entity, actor: a.actor, createdAt: a.createdAt })),
}
// Compute SHA-256 checksum of the export
const jsonStr = JSON.stringify(exportData)
const checksum = createHash('sha256').update(jsonStr).digest('hex')
// Audit the export
await db.auditLog.create({
data: {
actor: 'max@nordlicht.digital',
action: 'data.export:' + (companyFilter ? 'company' : 'full'),
entity: 'DataExport',
entityId: checksum.slice(0, 16),
after: JSON.stringify({ format, scope, checksum, sizeBytes: jsonStr.length, recordCount: exportData.companies.length + exportData.tickets.length + exportData.contracts.length }),
hash: 'sha256:' + checksum,
},
})
if (format === 'csv') {
// Simple CSV export (companies only for CSV — full export is JSON)
const headers = ['id', 'name', 'legalForm', 'vatId', 'city', 'website', 'createdAt']
const rows = companies.map((c) => [c.id, c.name, c.legalForm ?? '', c.vatId ?? '', c.city ?? '', c.website ?? '', c.createdAt.toISOString()])
const csv = [headers.join(','), ...rows.map((r) => r.map((c) => `"${String(c).replace(/"/g, '""')}"`).join(','))].join('\n')
return new Response(csv, {
headers: {
'content-type': 'text/csv; charset=utf-8',
'content-disposition': `attachment; filename="aos-export-${scope}-${new Date().toISOString().slice(0, 10)}.csv"`,
'x-aos-checksum': `sha256=${checksum}`,
},
})
}
// JSON export with checksum in header
return new Response(JSON.stringify(exportData, null, 2), {
headers: {
'content-type': 'application/json; charset=utf-8',
'content-disposition': `attachment; filename="aos-export-${scope}-${new Date().toISOString().slice(0, 10)}.json"`,
'x-aos-checksum': `sha256=${checksum}`,
},
})
} catch (err) {
const msg = err instanceof Error ? err.message : 'internal server error'
return NextResponse.json({ error: msg }, { status: 500 })
}
}
+67
View File
@@ -0,0 +1,67 @@
import { NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { createHash } from 'crypto'
export const dynamic = 'force-dynamic'
// GET /api/aos/data-management — overview of data inventory + retention status
export async function GET() {
try {
const [
companies, persons, deals, leads, projects, tasks, timeEntries,
invoices, licenses, assets, contracts, expenses, tickets, articles,
auditLogs, bankTx, vatReturns, apiTokens, webhooks, portalApprovals,
] = await Promise.all([
db.company.count(), db.person.count(), db.deal.count(), db.lead.count(),
db.project.count(), db.task.count(), db.timeEntry.count(),
db.invoice.count(), db.license.count(), db.asset.count(),
db.contract.count(), db.expense.count(), db.ticket.count(), db.article.count(),
db.auditLog.count(), db.bankTransaction.count(), db.vatReturn.count(),
db.apiToken.count({ where: { revokedAt: null } }), db.webhook.count({ where: { active: true } }),
db.portalApproval.count(),
])
// Data inventory by category (DSGVO Art. 30 — records of processing)
const inventory = [
{ category: 'Stammdaten (Kunden)', models: ['Company', 'Person'], count: companies + persons, retentionYears: 6, legalBasis: 'Art. 6 Abs. 1 lit. b (Vertrag)' },
{ category: 'Vertriebsdaten', models: ['Deal', 'Lead'], count: deals + leads, retentionYears: 6, legalBasis: 'Art. 6 Abs. 1 lit. f (berechtigtes Interesse)' },
{ category: 'Projektdaten', models: ['Project', 'Task', 'TimeEntry'], count: projects + tasks + timeEntries, retentionYears: 6, legalBasis: 'Art. 6 Abs. 1 lit. b (Vertrag)' },
{ category: 'Finanzdaten', models: ['Invoice', 'Expense', 'BankTransaction', 'VatReturn'], count: invoices + expenses + bankTx + vatReturns, retentionYears: 8, legalBasis: 'Art. 6 Abs. 1 lit. c (gesetzl. Pflicht, GoBD)' },
{ category: 'Vertragsdaten', models: ['Contract'], count: contracts, retentionYears: 6, legalBasis: 'Art. 6 Abs. 1 lit. b (Vertrag)' },
{ category: 'Lizenzdaten', models: ['License', 'Asset'], count: licenses + assets, retentionYears: 6, legalBasis: 'Art. 6 Abs. 1 lit. b (Vertrag)' },
{ category: 'Supportdaten', models: ['Ticket'], count: tickets, retentionYears: 6, legalBasis: 'Art. 6 Abs. 1 lit. f (berechtigtes Interesse)' },
{ category: 'Audit-Log', models: ['AuditLog'], count: auditLogs, retentionYears: 8, legalBasis: 'Art. 6 Abs. 1 lit. c (GoBD)' },
{ category: 'Wissensdatenbank', models: ['Article'], count: articles, retentionYears: null, legalBasis: 'Art. 6 Abs. 1 lit. f (berechtigtes Interesse)' },
{ category: 'Portal-Freigaben', models: ['PortalApproval'], count: portalApprovals, retentionYears: 6, legalBasis: 'Art. 6 Abs. 1 lit. b (Vertrag)' },
]
const totalRecords = inventory.reduce((s, i) => s + i.count, 0)
// Export history (from audit log)
const exports = await db.auditLog.findMany({
where: { action: { startsWith: 'data.export' } },
orderBy: { createdAt: 'desc' },
take: 10,
})
return NextResponse.json({
inventory,
stats: {
totalRecords,
activeTokens: apiTokens,
activeWebhooks: webhooks,
exportCount: exports.length,
},
exports: exports.map((e) => ({
id: e.id,
action: e.action,
detail: e.after ? JSON.parse(e.after) : null,
actor: e.actor,
createdAt: e.createdAt,
})),
})
} catch (err) {
const msg = err instanceof Error ? err.message : 'internal server error'
return NextResponse.json({ error: msg }, { status: 500 })
}
}