Files
2026-07-08 16:15:37 +02:00

49 lines
2.2 KiB
TypeScript
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// R-P6 (P6 CRM core, Variante A) — CSV export resource route
// (`/contacts/export`). Loader-only: it re-applies the same browser filter/sort
// from the query (DoD 2), resolves the rows server-side and streams an RFC 4180
// CSV (German headers, localized type/status labels). Module off / missing
// crm.read_own -> 404 (no body is rendered for a download endpoint).
import { type LoaderFunctionArgs } from "react-router";
import { buildKontaktCsv, buildKontaktDisplayName, kontaktStatusLabelKey, kontaktTypLabelKey, type KontaktCsvRow } from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { loadCrmContext, notFoundResponse, requireCrmPermission } from "~/utils/integrations/crm/crmAccess.server";
import { listKontakteForCsv, resolveUserLabels } from "~/utils/integrations/crm/crmService.server";
import { parseKontaktListQuery } from "~/utils/integrations/crm/kontaktListQuery";
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadCrmContext({ request, params });
if (!ctx.hasModule) {
throw notFoundResponse();
}
try {
requireCrmPermission(ctx, "crm.read_own");
} catch {
throw notFoundResponse();
}
const url = new URL(request.url);
const { filter, sort } = parseKontaktListQuery(url.searchParams);
const rows = await listKontakteForCsv({ tenantId: ctx.tenantId, ctx, filter, sort });
const userLabels = await resolveUserLabels(rows.map((row) => row.zustaendigerUserId).filter((id): id is string => Boolean(id)));
const csvRows: KontaktCsvRow[] = rows.map((row) => ({
displayName: buildKontaktDisplayName(row),
kontaktTyp: t(kontaktTypLabelKey(row.kontaktTyp)),
kontaktStatus: t(kontaktStatusLabelKey(row.kontaktStatus)),
primaerEmail: row.primaerEmail,
primaerTelefon: row.primaerTelefon,
zustaendigerLabel: row.zustaendigerUserId ? (userLabels.get(row.zustaendigerUserId) ?? null) : null,
createdAtIso: row.createdAt.toISOString(),
}));
const csv = buildKontaktCsv(csvRows);
return new Response(`${csv}`, {
headers: {
"Content-Type": "text/csv; charset=utf-8",
"Content-Disposition": 'attachment; filename="kontakte.csv"',
},
});
};