Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/db/src/admin-sales-leads.server.ts
T

1337 lines
48 KiB
TypeScript

import {
Prisma,
type AdminDuplicateCandidate,
type AdminLeadAssignmentRule,
type AdminLeadQualification,
type AdminLeadScoreRule,
type PrismaClient,
} from "../generated/prisma/client/client.js";
import type { AdminPermissionName } from "./admin-permissions.js";
import {
writeAdminSalesAudit,
type AdminSalesActor,
type AdminSalesAuditWriter,
} from "./admin-sales-core.server.js";
import {
UNRESTRICTED_ADMIN_SALES_ACCESS,
adminSalesLeadReadWhere,
assertAdminSalesWriteOwner,
type AdminSalesAccessScope,
} from "./admin-sales-access-scope.js";
import { createAdminPlatformNotificationDelivery } from "./notifications.server.js";
import { publishOutboxEvent } from "./outbox.js";
const MAX_TEXT = 2_000;
const MAX_NAME = 200;
const MAX_RULE_MEMBERS = 100;
const SCORE_MIN = -10_000;
const SCORE_MAX = 10_000;
export type AdminLeadFacts = {
readonly id: string;
readonly sourceId: string;
readonly sourceKey: string;
readonly firstName: string | null;
readonly lastName: string | null;
readonly email: string | null;
readonly normalizedEmail: string | null;
readonly phone: string | null;
readonly normalizedPhone: string | null;
readonly company: string | null;
readonly assignedToAdminUserId: string | null;
readonly region: string | null;
readonly country: string | null;
};
export type AdminLeadAssignmentRuleInput = {
readonly name: string;
readonly priority: number;
readonly sourceId?: string | null;
readonly region?: string | null;
readonly strategy: "fixed" | "round_robin";
readonly fixedAssigneeAdminUserId?: string | null;
readonly roundRobinAdminUserIds?: readonly string[];
readonly active?: boolean;
readonly actor: AdminSalesActor;
};
export type AdminLeadScoreRuleInput = {
readonly name: string;
readonly priority: number;
readonly field: "source" | "region" | "country" | "company" | "has_email" | "has_phone";
readonly operator: "equals" | "not_equals" | "contains" | "present";
readonly value?: string | null;
readonly points: number;
readonly actor: AdminSalesActor;
};
export type AdminLeadEnrichmentResult = {
readonly provider: string;
readonly companyName?: string | null;
readonly domain?: string | null;
readonly website?: string | null;
readonly region?: string | null;
readonly countryCode?: string | null;
readonly industry?: string | null;
readonly employeeRange?: string | null;
};
export type AdminLeadConversionInput = {
readonly leadId: string;
readonly companyName: string;
readonly firstName: string;
readonly lastName: string;
readonly dealTitle: string;
readonly ownerAdminUserId: string;
readonly amountCents?: number | null;
readonly expectedCloseDate?: Date | null;
readonly nextStep?: string | null;
readonly actor: AdminSalesActor;
};
export type AdminLeadConversionResult = {
readonly leadId: string;
readonly companyId: string;
readonly contactId: string;
readonly dealId: string;
readonly replayed: boolean;
};
export type AdminLeadAutomationConfig = {
readonly assignmentRules: readonly AdminLeadAssignmentRule[];
readonly scoreRules: readonly AdminLeadScoreRule[];
};
export type AdminLeadDuplicateResult = {
readonly candidates: readonly AdminDuplicateCandidate[];
readonly duplicateHintOfLeadId: string | null;
};
export type AdminLeadMergeResult = {
readonly survivorLeadId: string;
readonly mergedLeadId: string;
readonly replayed: boolean;
};
export type AdminSalesLeadRepository = {
listAutomationConfig(): Promise<AdminLeadAutomationConfig>;
createAssignmentRule(input: AdminLeadAssignmentRuleInput): Promise<AdminLeadAssignmentRule>;
createScoreRule(input: AdminLeadScoreRuleInput): Promise<AdminLeadScoreRule>;
scoreLead(input: { leadId: string; actor: AdminSalesActor }): Promise<AdminLeadQualification>;
enrichLead(input: {
leadId: string;
result: AdminLeadEnrichmentResult;
actor: AdminSalesActor;
}): Promise<AdminLeadQualification>;
autoAssignLead(input: {
leadId: string;
actor: AdminSalesActor;
}): Promise<{ leadId: string; assignedToAdminUserId: string | null; ruleId: string | null }>;
detectDuplicates(input: { leadId: string; actor: AdminSalesActor }): Promise<AdminLeadDuplicateResult>;
dismissDuplicate(input: {
candidateId: string;
reason: string;
actor: AdminSalesActor;
}): Promise<AdminDuplicateCandidate>;
mergeLeads(input: {
candidateId: string;
survivorLeadId: string;
mergedLeadId: string;
reason: string;
actor: AdminSalesActor;
}): Promise<AdminLeadMergeResult>;
convertLead(input: AdminLeadConversionInput): Promise<AdminLeadConversionResult>;
};
export function createAdminSalesLeadService(input: {
readonly repository: AdminSalesLeadRepository;
readonly authorize: (permission: AdminPermissionName) => Promise<void> | void;
}) {
return {
async listAutomationConfig() {
await input.authorize("admin_sales.crm.read");
return input.repository.listAutomationConfig();
},
async createAssignmentRule(command: AdminLeadAssignmentRuleInput) {
await input.authorize("admin_sales.crm.assign");
return input.repository.createAssignmentRule(normalizeAssignmentRule(command));
},
async createScoreRule(command: AdminLeadScoreRuleInput) {
await input.authorize("admin_sales.crm.assign");
return input.repository.createScoreRule(normalizeScoreRule(command));
},
async scoreLead(command: { leadId: string; actor: AdminSalesActor }) {
await input.authorize("admin_sales.crm.write");
return input.repository.scoreLead({
leadId: requiredId(command.leadId, "leadId"),
actor: normalizeActor(command.actor),
});
},
async enrichLead(command: {
leadId: string;
result: AdminLeadEnrichmentResult;
actor: AdminSalesActor;
}) {
await input.authorize("admin_sales.crm.write");
return input.repository.enrichLead({
leadId: requiredId(command.leadId, "leadId"),
result: normalizeEnrichment(command.result),
actor: normalizeActor(command.actor),
});
},
async autoAssignLead(command: { leadId: string; actor: AdminSalesActor }) {
await input.authorize("admin_sales.crm.assign");
return input.repository.autoAssignLead({
leadId: requiredId(command.leadId, "leadId"),
actor: normalizeActor(command.actor),
});
},
async detectDuplicates(command: { leadId: string; actor: AdminSalesActor }) {
await input.authorize("admin_sales.crm.write");
return input.repository.detectDuplicates({
leadId: requiredId(command.leadId, "leadId"),
actor: normalizeActor(command.actor),
});
},
async dismissDuplicate(command: {
candidateId: string;
reason: string;
actor: AdminSalesActor;
}) {
await input.authorize("admin_sales.crm.merge");
return input.repository.dismissDuplicate({
candidateId: requiredId(command.candidateId, "candidateId"),
reason: requiredText(command.reason, "dismissal reason", MAX_TEXT, 5),
actor: normalizeActor(command.actor),
});
},
async mergeLeads(command: {
candidateId: string;
survivorLeadId: string;
mergedLeadId: string;
reason: string;
actor: AdminSalesActor;
}) {
await input.authorize("admin_sales.crm.merge");
const survivorLeadId = requiredId(command.survivorLeadId, "survivorLeadId");
const mergedLeadId = requiredId(command.mergedLeadId, "mergedLeadId");
if (survivorLeadId === mergedLeadId) throw new Error("Admin sales lead merge requires two different records.");
return input.repository.mergeLeads({
candidateId: requiredId(command.candidateId, "candidateId"),
survivorLeadId,
mergedLeadId,
reason: requiredText(command.reason, "merge reason", MAX_TEXT, 5),
actor: normalizeActor(command.actor),
});
},
async convertLead(command: AdminLeadConversionInput) {
await input.authorize("admin_sales.crm.write");
return input.repository.convertLead(normalizeConversion(command));
},
};
}
export function assignmentRuleMatches(
rule: Pick<AdminLeadAssignmentRule, "sourceId" | "region">,
lead: Pick<AdminLeadFacts, "sourceId" | "region">
): boolean {
return (
(rule.sourceId === null || rule.sourceId === lead.sourceId) &&
(rule.region === null || normalizeMatchValue(rule.region) === normalizeMatchValue(lead.region))
);
}
export function selectRoundRobinAssignee(
adminUserIds: readonly string[],
nextAssigneeIndex: number
): { readonly adminUserId: string; readonly nextAssigneeIndex: number } {
if (adminUserIds.length === 0) throw new Error("Round-robin assignment requires at least one active operator.");
const normalizedIndex = ((Math.trunc(nextAssigneeIndex) % adminUserIds.length) + adminUserIds.length) % adminUserIds.length;
return {
adminUserId: adminUserIds[normalizedIndex]!,
nextAssigneeIndex: (normalizedIndex + 1) % adminUserIds.length,
};
}
export function evaluateAdminLeadScore(
lead: AdminLeadFacts,
rules: readonly Pick<
AdminLeadScoreRule,
"id" | "field" | "operator" | "value" | "points" | "version"
>[]
): {
readonly score: number;
readonly scoreBand: "cold" | "warm" | "hot";
readonly scoreVersion: number;
readonly breakdown: readonly { readonly ruleId: string; readonly points: number }[];
} {
const breakdown = rules
.filter((rule) => scoreRuleMatches(rule, lead))
.map((rule) => ({ ruleId: rule.id, points: rule.points }));
const score = Math.max(SCORE_MIN, Math.min(SCORE_MAX, breakdown.reduce((sum, entry) => sum + entry.points, 0)));
return {
score,
scoreBand: score >= 70 ? "hot" : score >= 35 ? "warm" : "cold",
scoreVersion: Math.max(1, ...rules.map((rule) => rule.version)),
breakdown,
};
}
type LeadPrismaClient = PrismaClient;
export function createPrismaAdminSalesLeadRepository(
client: LeadPrismaClient,
dependencies: {
readonly writeAudit?: AdminSalesAuditWriter;
readonly notify?: typeof createAdminPlatformNotificationDelivery;
readonly publish?: typeof publishOutboxEvent;
readonly accessScope?: AdminSalesAccessScope;
} = {}
): AdminSalesLeadRepository {
const writeAudit = dependencies.writeAudit ?? writeAdminSalesAudit;
const notify = dependencies.notify ?? createAdminPlatformNotificationDelivery;
const publish = dependencies.publish ?? publishOutboxEvent;
const accessScope =
dependencies.accessScope ?? UNRESTRICTED_ADMIN_SALES_ACCESS;
return {
async listAutomationConfig() {
const [assignmentRules, scoreRules] = await Promise.all([
client.adminLeadAssignmentRule.findMany({
where: { archivedAt: null },
orderBy: [{ priority: "asc" }, { id: "asc" }],
}),
client.adminLeadScoreRule.findMany({
where: { archivedAt: null },
orderBy: [{ priority: "asc" }, { id: "asc" }],
}),
]);
return { assignmentRules, scoreRules };
},
async createAssignmentRule(command) {
return client.$transaction(async (tx) => {
if (command.sourceId) await assertSourceExists(tx, command.sourceId);
const assigneeIds =
command.strategy === "fixed"
? [command.fixedAssigneeAdminUserId!]
: [...(command.roundRobinAdminUserIds ?? [])];
await assertActiveAdminUsers(tx, assigneeIds);
const created = await tx.adminLeadAssignmentRule.create({
data: {
name: command.name,
priority: command.priority,
sourceId: command.sourceId,
region: command.region,
strategy: command.strategy,
fixedAssigneeAdminUserId: command.fixedAssigneeAdminUserId,
roundRobinAdminUserIds: [...(command.roundRobinAdminUserIds ?? [])],
active: command.active ?? true,
},
});
await tx.adminActivity.create({
data: {
type: "configuration_changed",
actorAdminUserId: command.actor.adminUserId,
summary: `Lead-Zuweisungsregel ${created.name} angelegt`,
payload: {
configurationType: "lead_assignment_rule",
configurationId: created.id,
strategy: created.strategy,
},
},
});
await writeAudit(tx, {
actor: command.actor,
action: "admin.sales.leadAssignmentRule.created",
targetType: "AdminLeadAssignmentRule",
targetId: created.id,
after: ruleAuditSnapshot(created),
});
return created;
});
},
async createScoreRule(command) {
return client.$transaction(async (tx) => {
const created = await tx.adminLeadScoreRule.create({
data: {
name: command.name,
priority: command.priority,
field: command.field,
operator: command.operator,
value: command.value,
points: command.points,
},
});
await tx.adminActivity.create({
data: {
type: "configuration_changed",
actorAdminUserId: command.actor.adminUserId,
summary: `Lead-Scoring-Regel ${created.name} angelegt`,
payload: {
configurationType: "lead_score_rule",
configurationId: created.id,
version: created.version,
},
},
});
await writeAudit(tx, {
actor: command.actor,
action: "admin.sales.leadScoreRule.created",
targetType: "AdminLeadScoreRule",
targetId: created.id,
after: {
name: created.name,
field: created.field,
operator: created.operator,
points: created.points,
version: created.version,
},
});
return created;
});
},
async scoreLead(command) {
return client.$transaction(async (tx) => {
await lockLead(tx, command.leadId);
const lead = await getLeadFacts(tx, command.leadId);
assertAdminSalesWriteOwner(
lead.assignedToAdminUserId,
accessScope
);
const rules = await tx.adminLeadScoreRule.findMany({
where: { active: true, archivedAt: null },
orderBy: [{ priority: "asc" }, { id: "asc" }],
});
const result = evaluateAdminLeadScore(lead, rules);
const qualification = await tx.adminLeadQualification.upsert({
where: { leadId: lead.id },
create: {
leadId: lead.id,
score: result.score,
scoreBand: result.scoreBand,
scoreVersion: result.scoreVersion,
scoreBreakdown: toJson(result.breakdown),
},
update: {
score: result.score,
scoreBand: result.scoreBand,
scoreVersion: result.scoreVersion,
scoreBreakdown: toJson(result.breakdown),
},
});
await tx.adminActivity.create({
data: {
type: "lead_scored",
actorAdminUserId: command.actor.adminUserId,
leadId: lead.id,
summary: `Lead-Score auf ${result.score} aktualisiert`,
payload: {
score: result.score,
scoreBand: result.scoreBand,
scoreVersion: result.scoreVersion,
ruleCount: result.breakdown.length,
},
},
});
await writeAudit(tx, {
actor: command.actor,
action: "admin.sales.lead.scored",
targetType: "AdminLead",
targetId: lead.id,
after: {
score: result.score,
scoreBand: result.scoreBand,
scoreVersion: result.scoreVersion,
},
});
return qualification;
});
},
async enrichLead(command) {
return client.$transaction(async (tx) => {
await lockLead(tx, command.leadId);
const lead = await tx.adminLead.findUnique({
where: { id: command.leadId },
select: {
id: true,
archivedAt: true,
company: true,
assignedToAdminUserId: true,
},
});
if (!lead || lead.archivedAt) throw new Error("Admin sales lead was not found.");
assertAdminSalesWriteOwner(
lead.assignedToAdminUserId,
accessScope
);
const enrichmentData = toJson({
companyName: command.result.companyName ?? null,
domain: command.result.domain ?? null,
website: command.result.website ?? null,
region: command.result.region ?? null,
countryCode: command.result.countryCode ?? null,
industry: command.result.industry ?? null,
employeeRange: command.result.employeeRange ?? null,
});
const qualification = await tx.adminLeadQualification.upsert({
where: { leadId: lead.id },
create: {
leadId: lead.id,
scoreBand: "cold",
scoreBreakdown: [],
enrichmentStatus: "complete",
enrichmentProvider: command.result.provider,
enrichmentData,
enrichedAt: new Date(),
},
update: {
enrichmentStatus: "complete",
enrichmentProvider: command.result.provider,
enrichmentData,
enrichedAt: new Date(),
},
});
if (!lead.company && command.result.companyName) {
await tx.adminLead.update({
where: { id: lead.id },
data: { company: command.result.companyName },
});
}
await tx.adminActivity.create({
data: {
type: "lead_enriched",
actorAdminUserId: command.actor.adminUserId,
leadId: lead.id,
summary: "Firmendaten am Lead ergänzt",
payload: {
provider: command.result.provider,
populatedFields: Object.entries(command.result)
.filter(([key, value]) => key !== "provider" && value)
.map(([key]) => key),
},
},
});
await writeAudit(tx, {
actor: command.actor,
action: "admin.sales.lead.enriched",
targetType: "AdminLead",
targetId: lead.id,
after: {
provider: command.result.provider,
status: "complete",
},
});
return qualification;
});
},
async autoAssignLead(command) {
return client.$transaction(async (tx) => {
await lockLead(tx, command.leadId);
const lead = await getLeadFacts(tx, command.leadId);
assertAdminSalesWriteOwner(
lead.assignedToAdminUserId,
accessScope
);
const rules = await tx.adminLeadAssignmentRule.findMany({
where: { active: true, archivedAt: null },
orderBy: [{ priority: "asc" }, { id: "asc" }],
});
const rule = rules.find((candidate) => assignmentRuleMatches(candidate, lead)) ?? null;
if (!rule) return { leadId: lead.id, assignedToAdminUserId: lead.assignedToAdminUserId, ruleId: null };
// Lock the selected cursor after deterministic rule resolution. The
// row lock serializes concurrent assignment runs for this rule.
await tx.$queryRaw(
Prisma.sql`SELECT "id" FROM "AdminLeadAssignmentRule" WHERE "id" = ${rule.id} FOR UPDATE`
);
const currentRule = await tx.adminLeadAssignmentRule.findUnique({ where: { id: rule.id } });
if (!currentRule || !currentRule.active || currentRule.archivedAt) {
throw new Error("Admin sales lead assignment rule changed during evaluation.");
}
const selection =
currentRule.strategy === "fixed"
? {
adminUserId: currentRule.fixedAssigneeAdminUserId!,
nextAssigneeIndex: currentRule.nextAssigneeIndex,
}
: selectRoundRobinAssignee(
currentRule.roundRobinAdminUserIds,
currentRule.nextAssigneeIndex
);
await assertActiveAdminUsers(tx, [selection.adminUserId]);
const now = new Date();
await tx.adminLead.update({
where: { id: lead.id },
data: {
assignedToAdminUserId: selection.adminUserId,
activities: {
create: {
type: "assigned",
actorAdminUserId: command.actor.adminUserId,
payload: {
from: lead.assignedToAdminUserId,
to: selection.adminUserId,
assignmentRuleId: currentRule.id,
},
},
},
},
});
await tx.adminLeadAssignmentRule.update({
where: { id: currentRule.id },
data: {
nextAssigneeIndex: selection.nextAssigneeIndex,
lastAssignedAt: now,
},
});
await tx.adminActivity.create({
data: {
type: "lead_assigned",
actorAdminUserId: command.actor.adminUserId,
leadId: lead.id,
summary: "Lead automatisch zugewiesen",
payload: {
from: lead.assignedToAdminUserId,
to: selection.adminUserId,
assignmentRuleId: currentRule.id,
},
},
});
const sourceKey = `admin-sales:lead-assigned:${lead.id}:${selection.adminUserId}`;
const delivery = (await notify(
{
adminUserId: selection.adminUserId,
channel: "IN_APP",
category: "sales",
messageKey: "admin.sales.notifications.leadassigned",
sourceKey,
payloadMetadata: { leadId: lead.id },
},
tx as never
)) as { readonly id: string };
await publish(tx, {
tenantId: null,
type: "notification.platform.requested.v1",
dispatchKey: `platform-notification:${delivery.id}`,
payload: {
deliveryId: delivery.id,
adminUserId: selection.adminUserId,
sourceKey,
channel: "in-app",
messageKey: "admin.sales.notifications.leadassigned",
category: "sales",
metadata: {
leadId: lead.id,
deeplink: `/sales/leads/${lead.id}`,
},
},
});
await writeAudit(tx, {
actor: command.actor,
action: "admin.sales.lead.autoAssigned",
targetType: "AdminLead",
targetId: lead.id,
after: {
assignedToAdminUserId: selection.adminUserId,
assignmentRuleId: currentRule.id,
},
});
return {
leadId: lead.id,
assignedToAdminUserId: selection.adminUserId,
ruleId: currentRule.id,
};
});
},
async detectDuplicates(command) {
return client.$transaction(async (tx) => {
await lockLead(tx, command.leadId);
const lead = await tx.adminLead.findUnique({
where: { id: command.leadId },
select: {
id: true,
archivedAt: true,
capturedAt: true,
normalizedEmail: true,
normalizedPhone: true,
assignedToAdminUserId: true,
},
});
if (!lead || lead.archivedAt) throw new Error("Admin sales lead was not found.");
assertAdminSalesWriteOwner(
lead.assignedToAdminUserId,
accessScope
);
const OR: Prisma.AdminLeadWhereInput[] = [];
if (lead.normalizedEmail) OR.push({ normalizedEmail: lead.normalizedEmail });
if (lead.normalizedPhone) OR.push({ normalizedPhone: lead.normalizedPhone });
if (OR.length === 0) return { candidates: [], duplicateHintOfLeadId: null };
const matches = await tx.adminLead.findMany({
where: {
id: { not: lead.id },
archivedAt: null,
OR,
...adminSalesLeadReadWhere(accessScope),
},
orderBy: [{ capturedAt: "asc" }, { id: "asc" }],
select: {
id: true,
capturedAt: true,
normalizedEmail: true,
normalizedPhone: true,
},
});
const candidates: AdminDuplicateCandidate[] = [];
let duplicateHintOfLeadId: string | null = null;
for (const match of matches) {
const matchKeys = [
lead.normalizedEmail && lead.normalizedEmail === match.normalizedEmail ? "email" : null,
lead.normalizedPhone && lead.normalizedPhone === match.normalizedPhone ? "phone" : null,
].filter((value): value is string => value !== null);
const leadIsPrimary =
lead.capturedAt.getTime() < match.capturedAt.getTime() ||
(lead.capturedAt.getTime() === match.capturedAt.getTime() && lead.id < match.id);
const primaryLeadId = leadIsPrimary ? lead.id : match.id;
const duplicateLeadId = leadIsPrimary ? match.id : lead.id;
const candidate = await tx.adminDuplicateCandidate.upsert({
where: {
admin_duplicate_candidate_pair_key: { primaryLeadId, duplicateLeadId },
},
create: {
primaryLeadId,
duplicateLeadId,
matchKeys,
confidenceBasisPoints: matchKeys.length > 1 ? 10_000 : 8_000,
},
update: {
matchKeys,
confidenceBasisPoints: matchKeys.length > 1 ? 10_000 : 8_000,
status: "open",
resolvedAt: null,
resolvedByAdminUserId: null,
resolutionReason: null,
},
});
candidates.push(candidate);
if (!leadIsPrimary && duplicateHintOfLeadId === null) duplicateHintOfLeadId = primaryLeadId;
}
if (duplicateHintOfLeadId !== null) {
await tx.adminLead.update({
where: { id: lead.id },
data: {
duplicateHintOfLeadId,
activities: {
create: {
type: "duplicate_hint_recorded",
actorAdminUserId: command.actor.adminUserId,
payload: { duplicateHintOfLeadId, candidateCount: candidates.length },
},
},
},
});
}
await tx.adminActivity.create({
data: {
type: "lead_updated",
actorAdminUserId: command.actor.adminUserId,
leadId: lead.id,
summary: "Lead auf Dubletten geprüft",
payload: {
operation: "duplicates_detected",
candidateIds: candidates.map((candidate) => candidate.id),
duplicateHintOfLeadId,
},
},
});
await writeAudit(tx, {
actor: command.actor,
action: "admin.sales.lead.duplicatesDetected",
targetType: "AdminLead",
targetId: lead.id,
after: {
candidateCount: candidates.length,
duplicateHintOfLeadId,
},
});
return { candidates, duplicateHintOfLeadId };
});
},
async dismissDuplicate(command) {
return client.$transaction(async (tx) => {
const current = await tx.adminDuplicateCandidate.findUnique({
where: { id: command.candidateId },
include: {
primaryLead: {
select: { assignedToAdminUserId: true },
},
duplicateLead: {
select: { assignedToAdminUserId: true },
},
},
});
if (!current || current.status !== "open") throw new Error("Admin sales duplicate candidate was not found.");
assertAdminSalesWriteOwner(
current.primaryLead.assignedToAdminUserId,
accessScope
);
assertAdminSalesWriteOwner(
current.duplicateLead.assignedToAdminUserId,
accessScope
);
const updated = await tx.adminDuplicateCandidate.update({
where: { id: current.id },
data: {
status: "dismissed",
resolvedAt: new Date(),
resolvedByAdminUserId: command.actor.adminUserId,
resolutionReason: command.reason,
},
});
await tx.adminActivity.create({
data: {
type: "lead_updated",
actorAdminUserId: command.actor.adminUserId,
leadId: current.primaryLeadId,
summary: "Dublettenhinweis verworfen",
payload: {
operation: "duplicate_dismissed",
candidateId: current.id,
duplicateLeadId: current.duplicateLeadId,
},
},
});
await writeAudit(tx, {
actor: command.actor,
action: "admin.sales.lead.duplicateDismissed",
targetType: "AdminDuplicateCandidate",
targetId: current.id,
after: {
primaryLeadId: current.primaryLeadId,
duplicateLeadId: current.duplicateLeadId,
status: "dismissed",
},
});
return updated;
});
},
async mergeLeads(command) {
return client.$transaction(async (tx) => {
const lockOrder = [command.survivorLeadId, command.mergedLeadId].sort();
await tx.$queryRaw(
Prisma.sql`SELECT "id" FROM "AdminLead" WHERE "id" IN (${Prisma.join(lockOrder)}) ORDER BY "id" FOR UPDATE`
);
const [survivor, merged, existing, candidate] = await Promise.all([
getMergeLead(tx, command.survivorLeadId),
getMergeLead(tx, command.mergedLeadId),
tx.adminMergeRecord.findUnique({ where: { mergedLeadId: command.mergedLeadId } }),
tx.adminDuplicateCandidate.findUnique({ where: { id: command.candidateId } }),
]);
if (existing) {
if (existing.survivorLeadId !== command.survivorLeadId) {
throw new Error("Admin sales lead was already merged into a different survivor.");
}
return {
survivorLeadId: existing.survivorLeadId,
mergedLeadId: existing.mergedLeadId,
replayed: true,
};
}
if (!survivor || survivor.archivedAt || !merged || merged.archivedAt) {
throw new Error("Admin sales merge lead was not found.");
}
assertAdminSalesWriteOwner(
survivor.assignedToAdminUserId,
accessScope
);
assertAdminSalesWriteOwner(
merged.assignedToAdminUserId,
accessScope
);
if (
!candidate ||
candidate.status !== "open" ||
candidate.primaryLeadId !== survivor.id ||
candidate.duplicateLeadId !== merged.id
) {
throw new Error("Admin sales merge requires the matching open duplicate candidate.");
}
if (merged.convertedCompany || merged.convertedContact || merged.convertedDeal) {
throw new Error("A converted admin sales lead cannot be merged as the losing record.");
}
const now = new Date();
await tx.adminLead.update({
where: { id: merged.id },
data: {
archivedAt: now,
status: "disqualified",
duplicateHintOfLeadId: survivor.id,
activities: {
create: {
type: "archived",
actorAdminUserId: command.actor.adminUserId,
payload: { mergedIntoLeadId: survivor.id },
},
},
},
});
await tx.adminDuplicateCandidate.update({
where: { id: candidate.id },
data: {
status: "merged",
resolvedAt: now,
resolvedByAdminUserId: command.actor.adminUserId,
resolutionReason: command.reason,
},
});
await tx.adminMergeRecord.create({
data: {
survivorLeadId: survivor.id,
mergedLeadId: merged.id,
actorAdminUserId: command.actor.adminUserId,
reason: command.reason,
survivorSnapshot: leadMergeSnapshot(survivor),
mergedSnapshot: leadMergeSnapshot(merged),
},
});
await tx.adminLeadActivity.create({
data: {
leadId: survivor.id,
type: "legacy_event",
actorAdminUserId: command.actor.adminUserId,
payload: { event: "lead_merged", mergedLeadId: merged.id },
},
});
await tx.adminActivity.create({
data: {
type: "lead_merged",
actorAdminUserId: command.actor.adminUserId,
leadId: survivor.id,
summary: "Lead-Dublette zusammengeführt",
payload: { mergedLeadId: merged.id },
},
});
await writeAudit(tx, {
actor: command.actor,
action: "admin.sales.lead.merged",
targetType: "AdminLead",
targetId: survivor.id,
after: { mergedLeadId: merged.id },
});
return {
survivorLeadId: survivor.id,
mergedLeadId: merged.id,
replayed: false,
};
});
},
async convertLead(command) {
return client.$transaction(async (tx) => {
await lockLead(tx, command.leadId);
const lead = await tx.adminLead.findUnique({
where: { id: command.leadId },
include: {
convertedCompany: { select: { id: true } },
convertedContact: { select: { id: true } },
convertedDeal: { select: { id: true } },
duplicateCandidatesPrimary: { where: { status: "open" }, select: { id: true } },
duplicateCandidatesSecondary: { where: { status: "open" }, select: { id: true } },
},
});
if (!lead || lead.archivedAt) throw new Error("Admin sales lead was not found.");
assertAdminSalesWriteOwner(
lead.assignedToAdminUserId,
accessScope
);
assertAdminSalesWriteOwner(
command.ownerAdminUserId,
accessScope
);
if (lead.convertedCompany && lead.convertedContact && lead.convertedDeal) {
return {
leadId: lead.id,
companyId: lead.convertedCompany.id,
contactId: lead.convertedContact.id,
dealId: lead.convertedDeal.id,
replayed: true,
};
}
if (lead.convertedCompany || lead.convertedContact || lead.convertedDeal) {
throw new Error("Admin sales lead conversion is incomplete and requires operator review.");
}
if (lead.status !== "qualified") throw new Error("Only a qualified admin sales lead can be converted.");
if (lead.duplicateCandidatesPrimary.length > 0 || lead.duplicateCandidatesSecondary.length > 0) {
throw new Error("Open duplicate candidates must be resolved before lead conversion.");
}
await assertActiveAdminUsers(tx, [command.ownerAdminUserId]);
const pipeline = await tx.adminPipeline.findFirst({
where: { isDefault: true, archivedAt: null },
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
include: {
stages: {
where: { kind: "open", archivedAt: null },
orderBy: [{ position: "asc" }, { id: "asc" }],
take: 1,
},
},
});
const stage = pipeline?.stages[0];
if (!pipeline || !stage) throw new Error("The default admin sales pipeline is not configured.");
const company = await tx.adminCompany.create({
data: {
name: command.companyName,
normalizedName: normalizeMatchValue(command.companyName) ?? command.companyName.toLowerCase(),
ownerAdminUserId: command.ownerAdminUserId,
sourceLeadId: lead.id,
},
});
const contact = await tx.adminContact.create({
data: {
companyId: company.id,
firstName: command.firstName,
lastName: command.lastName,
email: lead.email,
normalizedEmail: lead.normalizedEmail,
phone: lead.phone,
normalizedPhone: lead.normalizedPhone,
ownerAdminUserId: command.ownerAdminUserId,
sourceLeadId: lead.id,
},
});
const deal = await tx.adminDeal.create({
data: {
title: command.dealTitle,
pipelineId: pipeline.id,
stageId: stage.id,
companyId: company.id,
sourceLeadId: lead.id,
ownerAdminUserId: command.ownerAdminUserId,
amountCents: command.amountCents,
probabilityBasisPoints: stage.probabilityBasisPoints,
expectedCloseDate: command.expectedCloseDate,
nextStep: command.nextStep,
contacts: { create: { contactId: contact.id, isPrimary: true } },
history: {
create: {
toStageId: stage.id,
actorAdminUserId: command.actor.adminUserId,
enteredAt: new Date(),
reason: "lead_conversion",
},
},
},
});
await tx.adminLead.update({
where: { id: lead.id },
data: {
assignedToAdminUserId: command.ownerAdminUserId,
activities: {
create: {
type: "status_changed",
actorAdminUserId: command.actor.adminUserId,
payload: {
from: lead.status,
to: "qualified",
conversion: { companyId: company.id, contactId: contact.id, dealId: deal.id },
},
},
},
},
});
await tx.adminActivity.create({
data: {
type: "lead_converted",
actorAdminUserId: command.actor.adminUserId,
leadId: lead.id,
companyId: company.id,
contactId: contact.id,
dealId: deal.id,
summary: "Lead in Firma, Kontakt und Deal überführt",
payload: { pipelineId: pipeline.id, stageId: stage.id },
},
});
await writeAudit(tx, {
actor: command.actor,
action: "admin.sales.lead.converted",
targetType: "AdminLead",
targetId: lead.id,
after: { companyId: company.id, contactId: contact.id, dealId: deal.id },
});
return {
leadId: lead.id,
companyId: company.id,
contactId: contact.id,
dealId: deal.id,
replayed: false,
};
});
},
};
}
function scoreRuleMatches(
rule: Pick<AdminLeadScoreRule, "field" | "operator" | "value">,
lead: AdminLeadFacts
): boolean {
const fact =
rule.field === "source"
? lead.sourceKey
: rule.field === "region"
? lead.region
: rule.field === "country"
? lead.country
: rule.field === "company"
? lead.company
: rule.field === "has_email"
? lead.email
? "true"
: "false"
: lead.phone
? "true"
: "false";
const normalizedFact = normalizeMatchValue(fact);
const normalizedExpected = normalizeMatchValue(rule.value);
if (rule.operator === "present") return normalizedFact !== null;
if (rule.operator === "equals") return normalizedFact === normalizedExpected;
if (rule.operator === "not_equals") return normalizedFact !== normalizedExpected;
return normalizedFact !== null && normalizedExpected !== null && normalizedFact.includes(normalizedExpected);
}
function normalizeAssignmentRule(command: AdminLeadAssignmentRuleInput): AdminLeadAssignmentRuleInput {
const fixedAssigneeAdminUserId = optionalId(command.fixedAssigneeAdminUserId);
const roundRobinAdminUserIds = uniqueIds(command.roundRobinAdminUserIds ?? []);
if (command.strategy === "fixed" && (!fixedAssigneeAdminUserId || roundRobinAdminUserIds.length > 0)) {
throw new Error("Fixed lead assignment requires exactly one fixed operator.");
}
if (command.strategy === "round_robin" && (fixedAssigneeAdminUserId || roundRobinAdminUserIds.length === 0)) {
throw new Error("Round-robin lead assignment requires a member list and no fixed operator.");
}
if (roundRobinAdminUserIds.length > MAX_RULE_MEMBERS) throw new Error("Lead assignment member list is too large.");
return {
...command,
name: requiredText(command.name, "assignment rule name", MAX_NAME),
priority: requiredPriority(command.priority),
sourceId: optionalId(command.sourceId),
region: optionalText(command.region, 120),
fixedAssigneeAdminUserId,
roundRobinAdminUserIds,
active: command.active ?? true,
actor: normalizeActor(command.actor),
};
}
function normalizeScoreRule(command: AdminLeadScoreRuleInput): AdminLeadScoreRuleInput {
const value = optionalText(command.value, 300);
if (command.operator !== "present" && value === null) throw new Error("Lead score rule value is required.");
if (!Number.isInteger(command.points) || command.points < -1_000 || command.points > 1_000) {
throw new Error("Lead score rule points are invalid.");
}
return {
...command,
name: requiredText(command.name, "score rule name", MAX_NAME),
priority: requiredPriority(command.priority),
value,
actor: normalizeActor(command.actor),
};
}
function normalizeEnrichment(result: AdminLeadEnrichmentResult): AdminLeadEnrichmentResult {
const domain = optionalText(result.domain, 253)?.toLowerCase().replace(/^www\./u, "") ?? null;
if (domain && (!domain.includes(".") || domain.includes("/") || domain.includes("@"))) {
throw new Error("Admin sales enrichment domain is invalid.");
}
const countryCode = optionalText(result.countryCode, 2)?.toUpperCase() ?? null;
if (countryCode && !/^[A-Z]{2}$/u.test(countryCode)) throw new Error("Admin sales enrichment country code is invalid.");
return {
provider: requiredText(result.provider, "enrichment provider", 120),
companyName: optionalText(result.companyName, MAX_NAME),
domain,
website: optionalUrl(result.website),
region: optionalText(result.region, 120),
countryCode,
industry: optionalText(result.industry, 120),
employeeRange: optionalText(result.employeeRange, 80),
};
}
function normalizeConversion(command: AdminLeadConversionInput): AdminLeadConversionInput {
if (
command.amountCents !== undefined &&
command.amountCents !== null &&
(!Number.isSafeInteger(command.amountCents) || command.amountCents < 0)
) {
throw new Error("Admin sales conversion amount is invalid.");
}
return {
...command,
leadId: requiredId(command.leadId, "leadId"),
companyName: requiredText(command.companyName, "company name", MAX_NAME),
firstName: requiredText(command.firstName, "contact first name", 120),
lastName: requiredText(command.lastName, "contact last name", 120),
dealTitle: requiredText(command.dealTitle, "deal title", MAX_NAME),
ownerAdminUserId: requiredId(command.ownerAdminUserId, "ownerAdminUserId"),
nextStep: optionalText(command.nextStep, MAX_TEXT),
actor: normalizeActor(command.actor),
};
}
async function getLeadFacts(tx: Prisma.TransactionClient, leadId: string): Promise<AdminLeadFacts> {
const lead = await tx.adminLead.findUnique({
where: { id: leadId },
include: { source: { select: { key: true } }, qualification: { select: { enrichmentData: true } } },
});
if (!lead || lead.archivedAt) throw new Error("Admin sales lead was not found.");
const metadata = jsonObject(lead.metadata);
const enrichment = jsonObject(lead.qualification?.enrichmentData);
return {
id: lead.id,
sourceId: lead.sourceId,
sourceKey: lead.source.key,
firstName: lead.firstName,
lastName: lead.lastName,
email: lead.email,
normalizedEmail: lead.normalizedEmail,
phone: lead.phone,
normalizedPhone: lead.normalizedPhone,
company: lead.company,
assignedToAdminUserId: lead.assignedToAdminUserId,
region: stringValue(enrichment.region) ?? stringValue(metadata.region),
country: stringValue(enrichment.countryCode) ?? stringValue(metadata.countryCode),
};
}
async function lockLead(tx: Prisma.TransactionClient, leadId: string): Promise<void> {
await tx.$queryRaw(Prisma.sql`SELECT "id" FROM "AdminLead" WHERE "id" = ${leadId} FOR UPDATE`);
}
async function assertSourceExists(tx: Prisma.TransactionClient, sourceId: string): Promise<void> {
const source = await tx.adminLeadSource.findUnique({ where: { id: sourceId }, select: { id: true } });
if (!source) throw new Error("Admin sales lead source was not found.");
}
async function assertActiveAdminUsers(tx: Prisma.TransactionClient, adminUserIds: readonly string[]): Promise<void> {
const ids = uniqueIds(adminUserIds);
const count = await tx.adminUser.count({ where: { id: { in: ids }, status: "active" } });
if (count !== ids.length) throw new Error("One or more admin sales operators are not active.");
}
function getMergeLead(tx: Prisma.TransactionClient, leadId: string) {
return tx.adminLead.findUnique({
where: { id: leadId },
include: {
convertedCompany: { select: { id: true } },
convertedContact: { select: { id: true } },
convertedDeal: { select: { id: true } },
},
});
}
function leadMergeSnapshot(lead: {
id: string;
status: string;
assignedToAdminUserId: string | null;
duplicateHintOfLeadId: string | null;
}): Prisma.InputJsonObject {
return {
id: lead.id,
status: lead.status,
assignedToAdminUserId: lead.assignedToAdminUserId,
duplicateHintOfLeadId: lead.duplicateHintOfLeadId,
};
}
function ruleAuditSnapshot(rule: AdminLeadAssignmentRule): Prisma.InputJsonObject {
return {
name: rule.name,
priority: rule.priority,
sourceId: rule.sourceId,
region: rule.region,
strategy: rule.strategy,
fixedAssigneeAdminUserId: rule.fixedAssigneeAdminUserId,
roundRobinMemberCount: rule.roundRobinAdminUserIds.length,
};
}
function normalizeActor(actor: AdminSalesActor): AdminSalesActor {
return {
adminUserId: requiredId(actor.adminUserId, "actor.adminUserId"),
email: optionalText(actor.email, 320),
reason: requiredText(actor.reason, "audit reason", MAX_TEXT, 5),
requestId: optionalText(actor.requestId, 191),
ip: optionalText(actor.ip, 100),
userAgent: optionalText(actor.userAgent, 1_000),
};
}
function requiredPriority(value: number): number {
if (!Number.isInteger(value) || value < 0 || value > 1_000_000) throw new Error("Admin sales rule priority is invalid.");
return value;
}
function requiredId(value: string, field: string): string {
const normalized = requiredText(value, field, 191);
if (!/^[A-Za-z0-9_:-]+$/u.test(normalized)) throw new Error(`Admin sales ${field} is invalid.`);
return normalized;
}
function optionalId(value: string | null | undefined): string | null {
return value == null || value.trim() === "" ? null : requiredId(value, "identifier");
}
function uniqueIds(values: readonly string[]): string[] {
return [...new Set(values.map((value) => requiredId(value, "identifier")))];
}
function requiredText(value: string, field: string, limit: number, minimum = 1): string {
if (typeof value !== "string") throw new Error(`Admin sales ${field} is required.`);
const normalized = value.trim();
if (
normalized.length < minimum ||
normalized.length > limit ||
/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test(normalized)
) {
throw new Error(`Admin sales ${field} is invalid.`);
}
return normalized;
}
function optionalText(value: string | null | undefined, limit: number): string | null {
if (value == null || value.trim() === "") return null;
return requiredText(value, "text", limit);
}
function optionalUrl(value: string | null | undefined): string | null {
const normalized = optionalText(value, 2_048);
if (!normalized) return null;
const url = new URL(normalized);
if (!["https:", "http:"].includes(url.protocol)) throw new Error("Admin sales enrichment URL is invalid.");
return url.toString();
}
function normalizeMatchValue(value: string | null | undefined): string | null {
const normalized = value?.normalize("NFKC").trim().toLocaleLowerCase("de-DE") ?? "";
return normalized || null;
}
function jsonObject(value: unknown): Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
}
function stringValue(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function toJson(value: unknown): Prisma.InputJsonValue {
return JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue;
}