Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/db/src/platform-lead-notifications.server.ts
T

56 lines
1.9 KiB
TypeScript

import { Prisma } from "../generated/prisma/client/client.js";
import { getDbClient, type DbClient } from "./client.server.js";
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/u;
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+$/u;
type PlatformLeadNotificationRecipientClient = Pick<DbClient, "$queryRaw">;
type PlatformLeadNotificationRecipientRow = {
email: string;
};
export type PlatformLeadNotificationRecipientInput = {
userId: string;
leadId: string;
};
/**
* Resolves an operator email through the worker-only database capability.
*
* The capability rechecks the current tenant-less AdminUser state and the
* dedicated `admin_sales.crm.read` AdminRBAC grant. A missing row is an
* intentional fail-closed result, while database errors remain retryable
* worker failures.
*/
export async function resolvePlatformLeadNotificationRecipient(
input: PlatformLeadNotificationRecipientInput,
client: PlatformLeadNotificationRecipientClient = getDbClient()
): Promise<{ eligible: boolean; email: string | null }> {
const userId = requireIdentifier(input.userId, "userId");
const leadId = requireIdentifier(input.leadId, "leadId");
const rows = await client.$queryRaw<PlatformLeadNotificationRecipientRow[]>(Prisma.sql`
SELECT email
FROM public.hivegrid_resolve_platform_lead_notification_recipient(${userId}, ${leadId})
`);
if (rows.length > 1) {
throw new Error("Platform lead notification recipient capability returned an ambiguous result.");
}
const email = rows[0]?.email?.trim() ?? "";
return {
eligible: rows.length === 1,
email: EMAIL_PATTERN.test(email) && email.length <= 320 ? email : null,
};
}
function requireIdentifier(value: string, field: string): string {
const normalized = typeof value === "string" ? value.trim() : "";
if (!IDENTIFIER_PATTERN.test(normalized)) {
throw new Error(`Invalid platform lead notification ${field}.`);
}
return normalized;
}