55 lines
2.6 KiB
TypeScript
55 lines
2.6 KiB
TypeScript
// 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";
|
||
import { isDemoDataUiEnabled } from "~/utils/services/.server/demoDataUi.server";
|
||
|
||
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: parsedFilter, sort } = parseKontaktListQuery(url.searchParams);
|
||
// Outside staging/dev the `demo=show` query param is ignored server-side
|
||
// (demo data is a staging/dev-only affordance).
|
||
const filter = isDemoDataUiEnabled(undefined, { tenantId: ctx.tenantId, tenantSlug: params.tenant })
|
||
? parsedFilter
|
||
: { ...parsedFilter, includeDemoData: false };
|
||
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"',
|
||
},
|
||
});
|
||
};
|