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

1252 lines
49 KiB
TypeScript

import { randomBytes } from "node:crypto";
import { Prisma } from "../generated/prisma/client/client.js";
import { getDbClient, type DbClient } from "./client.server.js";
import {
enqueuePlatformLeadAudit,
normalizePlatformLeadAdminAudit,
type NormalizedPlatformLeadAdminAudit,
type PlatformLeadAdminAuditInput,
} from "./platform-leads-audit.server.js";
import {
createAdminLeadIngestionService,
createPrismaAdminLeadIngestionRepository,
hashPlatformLeadSourceCredential,
type AdminLeadIngestionRepository,
} from "./platform-leads.server.js";
import {
UNRESTRICTED_ADMIN_SALES_ACCESS,
adminSalesLeadReadWhere,
assertAdminSalesWriteOwner,
type AdminSalesAccessScope,
} from "./admin-sales-access-scope.js";
export const PLATFORM_LEAD_STATUSES = ["new", "contacted", "qualified", "disqualified"] as const;
export const PLATFORM_LEAD_SOURCE_CREDENTIAL_PREFIX = "hgpls";
const PLATFORM_LEAD_STATUS_SET = new Set<string>(PLATFORM_LEAD_STATUSES);
const SOURCE_KEY_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
const ADMIN_IDENTIFIER_PATTERN = /^[A-Za-z0-9_-]+$/u;
const SOURCE_METADATA_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/u;
const MAX_SOURCE_METADATA_BYTES = 4_096;
const MAX_SOURCE_METADATA_ENTRIES = 32;
const MAX_NOTE_LENGTH = 8_000;
const MAX_NOTIFICATION_RECIPIENTS = 20;
const MAX_LIST_LIMIT = 100;
const PLATFORM_LEAD_NOTE_AUDIT_REASON = "Operator note added";
const PLATFORM_LEAD_READ_PERMISSIONS = ["admin_sales.crm.read"] as const;
export type PlatformLeadStatus = (typeof PLATFORM_LEAD_STATUSES)[number];
export type PlatformLeadSourceRef = {
id: string;
key: string;
displayName: string;
};
export type PlatformLeadAdminListItem = {
id: string;
createdAt: string;
updatedAt: string;
capturedAt: string;
archivedAt: string | null;
firstName: string | null;
lastName: string | null;
email: string | null;
phone: string | null;
company: string | null;
status: PlatformLeadStatus;
assignedToAdminUserId: string | null;
duplicateHintOfLeadId: string | null;
source: PlatformLeadSourceRef;
};
export type PlatformLeadActivityDto = {
id: string;
createdAt: string;
type: "captured" | "imported" | "manually_created" | "status_changed" | "assigned" | "note_added" | "archived" | "restored" | "duplicate_hint_recorded" | "legacy_event";
actorAdminUserId: string | null;
payload: Record<string, unknown>;
};
export type PlatformLeadAdminDetail = PlatformLeadAdminListItem & {
sourceDetail: string | null;
externalId: string | null;
message: string | null;
utmSource: string | null;
utmMedium: string | null;
utmCampaign: string | null;
utmTerm: string | null;
utmContent: string | null;
referrer: string | null;
landingPage: string | null;
metadata: Record<string, unknown> | null;
activities: PlatformLeadActivityDto[];
qualification: {
score: number;
scoreBand: string;
scoreVersion: number;
enrichmentStatus: "pending" | "complete" | "unavailable" | "failed";
enrichmentProvider: string | null;
enrichmentData: Record<string, unknown> | null;
enrichedAt: string | null;
} | null;
duplicateCandidates: {
id: string;
primaryLeadId: string;
duplicateLeadId: string;
status: "open" | "dismissed" | "merged";
matchKeys: string[];
confidenceBasisPoints: number;
}[];
conversion: {
companyId: string | null;
contactId: string | null;
dealId: string | null;
};
};
export type PlatformLeadListQuery = {
search?: string | null;
statuses?: readonly PlatformLeadStatus[] | null;
sourceIds?: readonly string[] | null;
assignedToAdminUserIds?: readonly string[] | null;
includeUnassigned?: boolean;
archive?: "active" | "archived" | "all";
cursor?: string | null;
limit?: number;
};
export type NormalizedPlatformLeadListQuery = {
search: string | null;
statuses: PlatformLeadStatus[];
sourceIds: string[];
assignedToAdminUserIds: string[];
includeUnassigned: boolean;
archive: "active" | "archived" | "all";
cursor: string | null;
limit: number;
};
export type PlatformLeadListPage = {
items: PlatformLeadAdminListItem[];
nextCursor: string | null;
summary: {
total: number;
newCount: number;
qualifiedCount: number;
unassignedCount: number;
archivedCount: number;
};
};
export type PlatformLeadSourceCredentialSummary = {
id: string;
createdAt: string;
keyPrefix: string;
expiresAt: string | null;
revokedAt: string | null;
lastUsedAt: string | null;
active: boolean;
};
export type PlatformLeadSourceAdminDto = PlatformLeadSourceRef & {
createdAt: string;
updatedAt: string;
enabled: boolean;
defaultAssigneeAdminUserId: string | null;
notifyAdminUserIds: string[];
rateLimitPerMinute: number;
leadCount: number;
metadata: Record<string, unknown> | null;
credentials: PlatformLeadSourceCredentialSummary[];
};
export type PlatformLeadIssuedCredential = {
credential: PlatformLeadSourceCredentialSummary;
/** Returned exactly once. Only the digest is persisted. */
secret: string;
};
export type CreatePlatformLeadSourceInput = {
key: string;
displayName: string;
enabled?: boolean;
defaultAssigneeAdminUserId?: string | null;
notifyAdminUserIds?: readonly string[];
rateLimitPerMinute?: number;
metadata?: Record<string, unknown> | null;
} & PlatformLeadAdminAuditInput;
export type UpdatePlatformLeadSourceInput = {
sourceId: string;
displayName?: string;
enabled?: boolean;
defaultAssigneeAdminUserId?: string | null;
notifyAdminUserIds?: readonly string[];
rateLimitPerMinute?: number;
metadata?: Record<string, unknown> | null;
} & PlatformLeadAdminAuditInput;
export type UpdatePlatformLeadStatusInput = {
leadId: string;
status: PlatformLeadStatus;
requiredAssigneeAdminUserId?: string;
} & PlatformLeadAdminAuditInput;
export type AssignPlatformLeadInput = {
leadId: string;
assignedToAdminUserId: string | null;
requiredAssigneeAdminUserId?: string;
} & PlatformLeadAdminAuditInput;
export type AddPlatformLeadNoteInput = {
leadId: string;
note: string;
requiredAssigneeAdminUserId?: string;
/** Accepted for action-contract compatibility but never persisted to avoid duplicating note PII into the audit trail. */
reason?: string;
} & Omit<PlatformLeadAdminAuditInput, "reason">;
export type ArchivePlatformLeadInput = {
leadId: string;
now?: Date;
requiredAssigneeAdminUserId?: string;
} & PlatformLeadAdminAuditInput;
export type RestorePlatformLeadInput = {
leadId: string;
requiredAssigneeAdminUserId?: string;
} & PlatformLeadAdminAuditInput;
export type IssuePlatformLeadSourceCredentialInput = {
sourceId: string;
expiresAt?: Date | null;
now?: Date;
} & PlatformLeadAdminAuditInput;
export type RotatePlatformLeadSourceCredentialInput = IssuePlatformLeadSourceCredentialInput & {
credentialId: string;
};
export type RevokePlatformLeadSourceCredentialInput = {
sourceId: string;
credentialId: string;
now?: Date;
} & PlatformLeadAdminAuditInput;
export type PlatformLeadAdminErrorCode = "VALIDATION" | "NOT_FOUND" | "CONFLICT";
export class PlatformLeadAdminError extends Error {
public override readonly name = "PlatformLeadAdminError";
public constructor(
public readonly code: PlatformLeadAdminErrorCode,
message: string
) {
super(message);
}
}
type UpdateStatusCommand = {
leadId: string;
status: PlatformLeadStatus;
requiredAssigneeAdminUserId?: string | null;
audit: NormalizedPlatformLeadAdminAudit;
};
type AssignLeadCommand = {
leadId: string;
assignedToAdminUserId: string | null;
requiredAssigneeAdminUserId?: string | null;
audit: NormalizedPlatformLeadAdminAudit;
};
type AddNoteCommand = {
leadId: string;
note: string;
requiredAssigneeAdminUserId?: string | null;
audit: NormalizedPlatformLeadAdminAudit;
};
type ArchiveLeadCommand = {
leadId: string;
requiredAssigneeAdminUserId?: string | null;
audit: NormalizedPlatformLeadAdminAudit;
archivedAt: Date | null;
};
type CreateSourceCommand = {
key: string;
displayName: string;
enabled: boolean;
defaultAssigneeAdminUserId: string | null;
notifyAdminUserIds: string[];
rateLimitPerMinute: number;
metadata: Record<string, string | number | boolean | null> | null;
audit: NormalizedPlatformLeadAdminAudit;
};
type UpdateSourceCommand = {
sourceId: string;
patch: {
displayName?: string;
enabled?: boolean;
defaultAssigneeAdminUserId?: string | null;
notifyAdminUserIds?: string[];
rateLimitPerMinute?: number;
metadata?: Record<string, string | number | boolean | null> | null;
};
audit: NormalizedPlatformLeadAdminAudit;
};
type IssueCredentialCommand = {
sourceId: string;
secretHash: string;
keyPrefix: string;
expiresAt: Date | null;
now: Date;
audit: NormalizedPlatformLeadAdminAudit;
};
type RotateCredentialCommand = IssueCredentialCommand & { credentialId: string };
export type PlatformLeadAdminRepository = {
listLeads(query: NormalizedPlatformLeadListQuery): Promise<PlatformLeadListPage>;
getLead(leadId: string): Promise<PlatformLeadAdminDetail | null>;
updateStatus(command: UpdateStatusCommand): Promise<PlatformLeadAdminDetail>;
assignLead(command: AssignLeadCommand): Promise<PlatformLeadAdminDetail>;
addNote(command: AddNoteCommand): Promise<PlatformLeadAdminDetail>;
setArchived(command: ArchiveLeadCommand): Promise<PlatformLeadAdminDetail>;
listSources(now: Date): Promise<PlatformLeadSourceAdminDto[]>;
createSource(command: CreateSourceCommand): Promise<PlatformLeadSourceAdminDto>;
updateSource(command: UpdateSourceCommand): Promise<PlatformLeadSourceAdminDto>;
createCredential(command: IssueCredentialCommand): Promise<PlatformLeadSourceCredentialSummary>;
rotateCredential(command: RotateCredentialCommand): Promise<PlatformLeadSourceCredentialSummary>;
revokeCredential(input: {
sourceId: string;
credentialId: string;
now: Date;
audit: NormalizedPlatformLeadAdminAudit;
}): Promise<PlatformLeadSourceCredentialSummary>;
};
export type PlatformLeadAdminService = ReturnType<typeof createPlatformLeadAdminService>;
export function createPlatformLeadAdminService(repository: PlatformLeadAdminRepository) {
return Object.freeze({
listLeads: (query: PlatformLeadListQuery = {}): Promise<PlatformLeadListPage> => repository.listLeads(normalizeListQuery(query)),
getLead: (input: { leadId: string }): Promise<PlatformLeadAdminDetail | null> => repository.getLead(requireAdminIdentifier(input.leadId, "leadId")),
updateStatus: (input: UpdatePlatformLeadStatusInput) =>
repository.updateStatus({
leadId: requireAdminIdentifier(input.leadId, "leadId"),
status: requireStatus(input.status),
requiredAssigneeAdminUserId: optionalAdminIdentifier(input.requiredAssigneeAdminUserId, "requiredAssigneeAdminUserId"),
audit: normalizeAdminAudit(input),
}),
assignLead: (input: AssignPlatformLeadInput) =>
repository.assignLead({
leadId: requireAdminIdentifier(input.leadId, "leadId"),
assignedToAdminUserId: optionalAdminIdentifier(input.assignedToAdminUserId, "assignedToAdminUserId"),
requiredAssigneeAdminUserId: optionalAdminIdentifier(input.requiredAssigneeAdminUserId, "requiredAssigneeAdminUserId"),
audit: normalizeAdminAudit(input),
}),
addNote: (input: AddPlatformLeadNoteInput) => {
const note = normalizeNote(input.note);
return repository.addNote({
leadId: requireAdminIdentifier(input.leadId, "leadId"),
note,
requiredAssigneeAdminUserId: optionalAdminIdentifier(input.requiredAssigneeAdminUserId, "requiredAssigneeAdminUserId"),
audit: normalizeAdminAudit({ ...input, reason: PLATFORM_LEAD_NOTE_AUDIT_REASON }),
});
},
archiveLead: (input: ArchivePlatformLeadInput) =>
repository.setArchived({
leadId: requireAdminIdentifier(input.leadId, "leadId"),
requiredAssigneeAdminUserId: optionalAdminIdentifier(input.requiredAssigneeAdminUserId, "requiredAssigneeAdminUserId"),
audit: normalizeAdminAudit(input),
archivedAt: normalizeAdminDate(input.now ?? new Date(), "now"),
}),
restoreLead: (input: RestorePlatformLeadInput) =>
repository.setArchived({
leadId: requireAdminIdentifier(input.leadId, "leadId"),
requiredAssigneeAdminUserId: optionalAdminIdentifier(input.requiredAssigneeAdminUserId, "requiredAssigneeAdminUserId"),
audit: normalizeAdminAudit(input),
archivedAt: null,
}),
listSources: (input: { now?: Date } = {}) => repository.listSources(normalizeAdminDate(input.now ?? new Date(), "now")),
createSource: (input: CreatePlatformLeadSourceInput) => repository.createSource(normalizeCreateSource(input)),
updateSource: (input: UpdatePlatformLeadSourceInput) => repository.updateSource(normalizeUpdateSource(input)),
createSourceCredential: async (input: IssuePlatformLeadSourceCredentialInput): Promise<PlatformLeadIssuedCredential> => {
const command = issueCredentialCommand(input);
const { secret, ...persistenceCommand } = command;
return { credential: await repository.createCredential(persistenceCommand), secret };
},
rotateSourceCredential: async (input: RotatePlatformLeadSourceCredentialInput): Promise<PlatformLeadIssuedCredential> => {
const command = issueCredentialCommand(input);
const { secret, ...persistenceCommand } = command;
return {
credential: await repository.rotateCredential({
...persistenceCommand,
credentialId: requireAdminIdentifier(input.credentialId, "credentialId"),
}),
secret,
};
},
revokeSourceCredential: (input: RevokePlatformLeadSourceCredentialInput) =>
repository.revokeCredential({
sourceId: requireAdminIdentifier(input.sourceId, "sourceId"),
credentialId: requireAdminIdentifier(input.credentialId, "credentialId"),
now: normalizeAdminDate(input.now ?? new Date(), "now"),
audit: normalizeAdminAudit(input),
}),
});
}
export type PlatformLeadService = ReturnType<typeof createPlatformLeadService>;
/**
* One domain facade shared by the S2S API and the operator UI. S2S, manual
* entry and imports all retain the single ingestion implementation; the
* additional methods expose the operator inbox without coupling it to Remix.
*/
export function createPlatformLeadService(input: { ingestionRepository: AdminLeadIngestionRepository; adminRepository: PlatformLeadAdminRepository }) {
return Object.freeze({
...createAdminLeadIngestionService(input.ingestionRepository),
...createPlatformLeadAdminService(input.adminRepository),
});
}
export function createPrismaPlatformLeadService(
client: DbClient = getDbClient(),
accessScope: AdminSalesAccessScope = UNRESTRICTED_ADMIN_SALES_ACCESS
): PlatformLeadService {
return createPlatformLeadService({
ingestionRepository: createPrismaAdminLeadIngestionRepository(client),
adminRepository: createPrismaPlatformLeadAdminRepository(client, accessScope),
});
}
const leadDetailInclude = {
source: { select: { id: true, key: true, displayName: true } },
activities: { orderBy: [{ createdAt: "desc" }, { id: "desc" }] },
qualification: true,
duplicateCandidatesPrimary: {
where: { status: "open" },
orderBy: [{ confidenceBasisPoints: "desc" }, { createdAt: "asc" }],
},
duplicateCandidatesSecondary: {
where: { status: "open" },
orderBy: [{ confidenceBasisPoints: "desc" }, { createdAt: "asc" }],
},
convertedCompany: { select: { id: true } },
convertedContact: { select: { id: true } },
convertedDeal: { select: { id: true } },
} as const satisfies Prisma.AdminLeadInclude;
type PrismaLeadDetail = Prisma.AdminLeadGetPayload<{ include: typeof leadDetailInclude }>;
const sourceAdminInclude = {
credentials: {
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
select: { id: true, createdAt: true, keyPrefix: true, expiresAt: true, revokedAt: true, lastUsedAt: true },
},
_count: { select: { leads: true } },
} as const satisfies Prisma.AdminLeadSourceInclude;
type PrismaSourceAdmin = Prisma.AdminLeadSourceGetPayload<{ include: typeof sourceAdminInclude }>;
export function createPrismaPlatformLeadAdminRepository(
client: DbClient = getDbClient(),
accessScope: AdminSalesAccessScope = UNRESTRICTED_ADMIN_SALES_ACCESS
): PlatformLeadAdminRepository {
return {
async listLeads(query) {
const where = buildLeadListWhere(query, accessScope);
const [rows, total, newCount, qualifiedCount, unassignedCount, archivedCount] = await Promise.all([
client.adminLead.findMany({
where,
orderBy: [{ capturedAt: "desc" }, { id: "desc" }],
...(query.cursor ? { cursor: { id: query.cursor }, skip: 1 } : {}),
take: query.limit + 1,
include: { source: { select: { id: true, key: true, displayName: true } } },
}),
client.adminLead.count({ where }),
client.adminLead.count({ where: { AND: [where, { status: "new", archivedAt: null }] } }),
client.adminLead.count({ where: { AND: [where, { status: "qualified", archivedAt: null }] } }),
client.adminLead.count({ where: { AND: [where, { assignedToAdminUserId: null, archivedAt: null }] } }),
client.adminLead.count({ where: { AND: [where, { archivedAt: { not: null } }] } }),
]);
const hasMore = rows.length > query.limit;
const pageRows = hasMore ? rows.slice(0, query.limit) : rows;
return {
items: pageRows.map(toLeadListItem),
nextCursor: hasMore ? (pageRows.at(-1)?.id ?? null) : null,
summary: { total, newCount, qualifiedCount, unassignedCount, archivedCount },
};
},
async getLead(leadId) {
const lead = await client.adminLead.findFirst({
where: { id: leadId, ...adminSalesLeadReadWhere(accessScope) },
include: leadDetailInclude,
});
return lead ? toLeadDetail(lead) : null;
},
updateStatus: (command) =>
mutateLead(client, accessScope, command.leadId, command.requiredAssigneeAdminUserId ?? null, async (tx, current) => {
if (current.status === command.status) return current;
const updated = await tx.adminLead.update({
where: { id: command.leadId },
data: {
status: command.status,
activities: {
create: {
type: "status_changed",
actorAdminUserId: command.audit.actorAdminUserId,
payload: { from: current.status, to: command.status },
},
},
},
include: leadDetailInclude,
});
await enqueuePlatformLeadAudit(tx, {
action: "admin.lead.statusChanged",
targetType: "AdminLead",
targetId: command.leadId,
audit: command.audit,
before: { status: current.status },
after: { status: command.status },
});
return updated;
}),
assignLead: (command) =>
mutateLead(client, accessScope, command.leadId, command.requiredAssigneeAdminUserId ?? null, async (tx, current) => {
if (current.assignedToAdminUserId === command.assignedToAdminUserId) return current;
if (command.assignedToAdminUserId) {
await assertConfiguredOperatorsExist(tx, command.assignedToAdminUserId, []);
}
const updated = await tx.adminLead.update({
where: { id: command.leadId },
data: {
assignedToAdminUserId: command.assignedToAdminUserId,
activities: {
create: {
type: "assigned",
actorAdminUserId: command.audit.actorAdminUserId,
payload: { from: current.assignedToAdminUserId, to: command.assignedToAdminUserId },
},
},
},
include: leadDetailInclude,
});
await enqueuePlatformLeadAudit(tx, {
action: "admin.lead.assigned",
targetType: "AdminLead",
targetId: command.leadId,
audit: command.audit,
before: { assignedToAdminUserId: current.assignedToAdminUserId },
after: { assignedToAdminUserId: command.assignedToAdminUserId },
});
return updated;
}),
addNote: (command) =>
mutateLead(client, accessScope, command.leadId, command.requiredAssigneeAdminUserId ?? null, async (tx) => {
const updated = await tx.adminLead.update({
where: { id: command.leadId },
data: {
activities: {
create: { type: "note_added", actorAdminUserId: command.audit.actorAdminUserId, payload: { note: command.note } },
},
},
include: leadDetailInclude,
});
await enqueuePlatformLeadAudit(tx, {
action: "admin.lead.noteAdded",
targetType: "AdminLead",
targetId: command.leadId,
audit: command.audit,
after: { activityType: "note_added" },
});
return updated;
}),
setArchived: (command) =>
mutateLead(client, accessScope, command.leadId, command.requiredAssigneeAdminUserId ?? null, async (tx, current) => {
const wantsArchived = command.archivedAt !== null;
if ((current.archivedAt !== null) === wantsArchived) return current;
const updated = await tx.adminLead.update({
where: { id: command.leadId },
data: {
archivedAt: command.archivedAt,
activities: {
create: {
type: wantsArchived ? "archived" : "restored",
actorAdminUserId: command.audit.actorAdminUserId,
payload: {},
...(command.archivedAt ? { createdAt: command.archivedAt } : {}),
},
},
},
include: leadDetailInclude,
});
await enqueuePlatformLeadAudit(tx, {
action: wantsArchived ? "admin.lead.archived" : "admin.lead.restored",
targetType: "AdminLead",
targetId: command.leadId,
audit: command.audit,
before: { archived: !wantsArchived },
after: { archived: wantsArchived },
});
return updated;
}),
async listSources(now) {
const sources = await client.adminLeadSource.findMany({ orderBy: [{ displayName: "asc" }, { id: "asc" }], include: sourceAdminInclude });
return sources.map((source) => toSourceAdminDto(source, now));
},
async createSource(command) {
try {
assertSourceRoutingConfigured(command.enabled, command.notifyAdminUserIds);
const source = await client.$transaction(async (tx) => {
await assertConfiguredOperatorsExist(tx, command.defaultAssigneeAdminUserId, command.notifyAdminUserIds);
const created = await tx.adminLeadSource.create({
data: {
key: command.key,
displayName: command.displayName,
enabled: command.enabled,
defaultAssigneeAdminUserId: command.defaultAssigneeAdminUserId,
notifyAdminUserIds: command.notifyAdminUserIds,
rateLimitPerMinute: command.rateLimitPerMinute,
metadata: toAdminJson(command.metadata),
},
include: sourceAdminInclude,
});
await enqueuePlatformLeadAudit(tx, {
action: "admin.lead.sourceCreated",
targetType: "AdminLeadSource",
targetId: created.id,
audit: command.audit,
after: sourceAuditSnapshot(created),
});
return created;
});
return toSourceAdminDto(source, new Date());
} catch (error) {
throw translateAdminRepositoryError(error, "A platform lead source with this key already exists.");
}
},
async updateSource(command) {
try {
const source = await client.$transaction(async (tx) => {
const current = await tx.adminLeadSource.findUnique({ where: { id: command.sourceId }, include: sourceAdminInclude });
if (!current) throw new PlatformLeadAdminError("NOT_FOUND", "The platform lead source does not exist.");
assertSourceRoutingConfigured(command.patch.enabled ?? current.enabled, command.patch.notifyAdminUserIds ?? current.notifyAdminUserIds);
await assertConfiguredOperatorsExist(
tx,
command.patch.defaultAssigneeAdminUserId === undefined
? current.defaultAssigneeAdminUserId
: command.patch.defaultAssigneeAdminUserId,
command.patch.notifyAdminUserIds ?? current.notifyAdminUserIds
);
const { metadata, ...scalarPatch } = command.patch;
const updated = await tx.adminLeadSource.update({
where: { id: command.sourceId },
data: {
...scalarPatch,
...(metadata !== undefined ? { metadata: toAdminJson(metadata) } : {}),
},
include: sourceAdminInclude,
});
await enqueuePlatformLeadAudit(tx, {
action: "admin.lead.sourceUpdated",
targetType: "AdminLeadSource",
targetId: command.sourceId,
audit: command.audit,
before: sourceAuditSnapshot(current),
after: sourceAuditSnapshot(updated),
});
return updated;
});
return toSourceAdminDto(source, new Date());
} catch (error) {
throw translateAdminRepositoryError(error);
}
},
async createCredential(command) {
try {
const credential = await client.$transaction(async (tx) => {
const source = await tx.adminLeadSource.findUnique({ where: { id: command.sourceId }, select: { id: true } });
if (!source) throw new PlatformLeadAdminError("NOT_FOUND", "The platform lead source does not exist.");
const created = await tx.adminLeadSourceCredential.create({
data: {
sourceId: command.sourceId,
keyHash: command.secretHash,
keyPrefix: command.keyPrefix,
expiresAt: command.expiresAt,
},
});
await enqueuePlatformLeadAudit(tx, {
action: "admin.lead.sourceCredentialCreated",
targetType: "AdminLeadSourceCredential",
targetId: created.id,
audit: command.audit,
after: { sourceId: command.sourceId, expiresAt: command.expiresAt?.toISOString() ?? null },
});
return created;
});
return toCredentialSummary(credential, command.now);
} catch (error) {
throw translateAdminRepositoryError(error, "The generated platform lead credential conflicts with an existing credential.");
}
},
async rotateCredential(command) {
try {
const credential = await client.$transaction(async (tx) => {
const previous = await tx.adminLeadSourceCredential.findFirst({
where: { id: command.credentialId, sourceId: command.sourceId },
});
if (!previous) throw new PlatformLeadAdminError("NOT_FOUND", "The platform lead source credential does not exist.");
if (!previous.revokedAt) {
await tx.adminLeadSourceCredential.update({ where: { id: previous.id }, data: { revokedAt: command.now } });
}
const created = await tx.adminLeadSourceCredential.create({
data: {
sourceId: command.sourceId,
keyHash: command.secretHash,
keyPrefix: command.keyPrefix,
expiresAt: command.expiresAt,
},
});
await enqueuePlatformLeadAudit(tx, {
action: "admin.lead.sourceCredentialRotated",
targetType: "AdminLeadSourceCredential",
targetId: created.id,
audit: command.audit,
before: { credentialId: previous.id, sourceId: command.sourceId, revoked: previous.revokedAt !== null },
after: {
sourceId: command.sourceId,
expiresAt: command.expiresAt?.toISOString() ?? null,
rotatedFromCredentialId: previous.id,
previousCredentialRevoked: true,
},
});
return created;
});
return toCredentialSummary(credential, command.now);
} catch (error) {
throw translateAdminRepositoryError(error, "The generated platform lead credential conflicts with an existing credential.");
}
},
async revokeCredential(input) {
try {
const credential = await client.$transaction(async (tx) => {
const current = await tx.adminLeadSourceCredential.findFirst({
where: { id: input.credentialId, sourceId: input.sourceId },
});
if (!current) throw new PlatformLeadAdminError("NOT_FOUND", "The platform lead source credential does not exist.");
if (current.revokedAt) return current;
const revoked = await tx.adminLeadSourceCredential.update({ where: { id: current.id }, data: { revokedAt: input.now } });
await enqueuePlatformLeadAudit(tx, {
action: "admin.lead.sourceCredentialRevoked",
targetType: "AdminLeadSourceCredential",
targetId: current.id,
audit: input.audit,
before: { sourceId: input.sourceId, revoked: false },
after: { sourceId: input.sourceId, revoked: true },
});
return revoked;
});
return toCredentialSummary(credential, input.now);
} catch (error) {
throw translateAdminRepositoryError(error);
}
},
};
}
async function mutateLead(
client: DbClient,
accessScope: AdminSalesAccessScope,
leadId: string,
requiredAssigneeAdminUserId: string | null,
mutation: (tx: Prisma.TransactionClient, current: PrismaLeadDetail) => Promise<PrismaLeadDetail>
): Promise<PlatformLeadAdminDetail> {
try {
const lead = await client.$transaction(async (tx) => {
// Serialize visibility check and mutation on the same row. Without this
// lock a read-own operator could pass the check immediately before a
// concurrent reassignment and still mutate a now-hidden lead.
await tx.$queryRaw(Prisma.sql`SELECT "id" FROM "AdminLead" WHERE "id" = ${leadId} FOR UPDATE`);
const current = await tx.adminLead.findUnique({ where: { id: leadId }, include: leadDetailInclude });
if (!current) throw new PlatformLeadAdminError("NOT_FOUND", "The platform lead does not exist.");
assertAdminSalesWriteOwner(current.assignedToAdminUserId, accessScope);
if (requiredAssigneeAdminUserId !== null && current.assignedToAdminUserId !== requiredAssigneeAdminUserId) {
throw new PlatformLeadAdminError("NOT_FOUND", "The platform lead does not exist.");
}
return mutation(tx, current);
});
return toLeadDetail(lead);
} catch (error) {
throw translateAdminRepositoryError(error);
}
}
function buildLeadListWhere(
query: NormalizedPlatformLeadListQuery,
accessScope: AdminSalesAccessScope = UNRESTRICTED_ADMIN_SALES_ACCESS
): Prisma.AdminLeadWhereInput {
const where: Prisma.AdminLeadWhereInput = {
...adminSalesLeadReadWhere(accessScope),
};
if (query.archive === "active") where.archivedAt = null;
if (query.archive === "archived") where.archivedAt = { not: null };
if (query.statuses.length > 0) where.status = { in: query.statuses };
if (query.sourceIds.length > 0) where.sourceId = { in: query.sourceIds };
if (query.assignedToAdminUserIds.length > 0 || query.includeUnassigned) {
const assignmentFilters: Prisma.AdminLeadWhereInput[] = [];
if (query.assignedToAdminUserIds.length > 0) assignmentFilters.push({ assignedToAdminUserId: { in: query.assignedToAdminUserIds } });
if (query.includeUnassigned) assignmentFilters.push({ assignedToAdminUserId: null });
where.AND = [...(Array.isArray(where.AND) ? where.AND : []), { OR: assignmentFilters }];
}
if (query.search) {
const contains = { contains: query.search, mode: "insensitive" as const };
const searchFilter: Prisma.AdminLeadWhereInput = {
OR: [
{ firstName: contains },
{ lastName: contains },
{ email: contains },
{ phone: contains },
{ company: contains },
{ message: contains },
{ externalId: contains },
{ source: { is: { displayName: contains } } },
],
};
where.AND = [...(Array.isArray(where.AND) ? where.AND : []), searchFilter];
}
return where;
}
function toLeadListItem(lead: {
id: string;
createdAt: Date;
updatedAt: Date;
capturedAt: Date;
archivedAt: Date | null;
firstName: string | null;
lastName: string | null;
email: string | null;
phone: string | null;
company: string | null;
status: PlatformLeadStatus;
assignedToAdminUserId: string | null;
duplicateHintOfLeadId: string | null;
source: PlatformLeadSourceRef;
}): PlatformLeadAdminListItem {
return {
id: lead.id,
createdAt: lead.createdAt.toISOString(),
updatedAt: lead.updatedAt.toISOString(),
capturedAt: lead.capturedAt.toISOString(),
archivedAt: lead.archivedAt?.toISOString() ?? null,
firstName: lead.firstName,
lastName: lead.lastName,
email: lead.email,
phone: lead.phone,
company: lead.company,
status: lead.status,
assignedToAdminUserId: lead.assignedToAdminUserId,
duplicateHintOfLeadId: lead.duplicateHintOfLeadId,
source: lead.source,
};
}
function toLeadDetail(lead: PrismaLeadDetail): PlatformLeadAdminDetail {
return {
...toLeadListItem(lead),
sourceDetail: lead.sourceDetail,
externalId: lead.externalId,
message: lead.message,
utmSource: lead.utmSource,
utmMedium: lead.utmMedium,
utmCampaign: lead.utmCampaign,
utmTerm: lead.utmTerm,
utmContent: lead.utmContent,
referrer: lead.referrer,
landingPage: lead.landingPage,
metadata: toJsonObject(lead.metadata),
activities: lead.activities.map((activity) => ({
id: activity.id,
createdAt: activity.createdAt.toISOString(),
type: activity.type,
actorAdminUserId: activity.actorAdminUserId,
payload: toJsonObject(activity.payload) ?? {},
})),
qualification: lead.qualification
? {
score: lead.qualification.score,
scoreBand: lead.qualification.scoreBand,
scoreVersion: lead.qualification.scoreVersion,
enrichmentStatus: lead.qualification.enrichmentStatus,
enrichmentProvider: lead.qualification.enrichmentProvider,
enrichmentData: toJsonObject(lead.qualification.enrichmentData),
enrichedAt: lead.qualification.enrichedAt?.toISOString() ?? null,
}
: null,
duplicateCandidates: [...lead.duplicateCandidatesPrimary, ...lead.duplicateCandidatesSecondary].map(
(candidate) => ({
id: candidate.id,
primaryLeadId: candidate.primaryLeadId,
duplicateLeadId: candidate.duplicateLeadId,
status: candidate.status,
matchKeys: candidate.matchKeys,
confidenceBasisPoints: candidate.confidenceBasisPoints,
})
),
conversion: {
companyId: lead.convertedCompany?.id ?? null,
contactId: lead.convertedContact?.id ?? null,
dealId: lead.convertedDeal?.id ?? null,
},
};
}
function toSourceAdminDto(source: PrismaSourceAdmin, now: Date): PlatformLeadSourceAdminDto {
return {
id: source.id,
key: source.key,
displayName: source.displayName,
createdAt: source.createdAt.toISOString(),
updatedAt: source.updatedAt.toISOString(),
enabled: source.enabled,
defaultAssigneeAdminUserId: source.defaultAssigneeAdminUserId,
notifyAdminUserIds: [...source.notifyAdminUserIds],
rateLimitPerMinute: source.rateLimitPerMinute,
leadCount: source._count.leads,
metadata: toJsonObject(source.metadata),
credentials: source.credentials.map((credential) => toCredentialSummary(credential, now)),
};
}
function toCredentialSummary(
credential: { id: string; createdAt: Date; keyPrefix: string; expiresAt: Date | null; revokedAt: Date | null; lastUsedAt: Date | null },
now: Date
): PlatformLeadSourceCredentialSummary {
return {
id: credential.id,
createdAt: credential.createdAt.toISOString(),
keyPrefix: credential.keyPrefix,
expiresAt: credential.expiresAt?.toISOString() ?? null,
revokedAt: credential.revokedAt?.toISOString() ?? null,
lastUsedAt: credential.lastUsedAt?.toISOString() ?? null,
active: credential.revokedAt === null && (credential.expiresAt === null || credential.expiresAt.getTime() > now.getTime()),
};
}
function normalizeListQuery(query: PlatformLeadListQuery): NormalizedPlatformLeadListQuery {
const search = normalizeOptionalString(query.search, 200, "search");
const statuses = uniqueValues(query.statuses ?? []).map(requireStatus);
const sourceIds = uniqueValues(query.sourceIds ?? []).map((id) => requireAdminIdentifier(id, "sourceId"));
const assignedToAdminUserIds = uniqueValues(query.assignedToAdminUserIds ?? []).map((id) => requireAdminIdentifier(id, "assignedToAdminUserId"));
const cursor = optionalAdminIdentifier(query.cursor, "cursor");
const limit = query.limit ?? 50;
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIST_LIMIT) {
throw new PlatformLeadAdminError("VALIDATION", `Platform lead list limit must be between 1 and ${MAX_LIST_LIMIT}.`);
}
const archive = query.archive ?? "active";
if (!new Set(["active", "archived", "all"]).has(archive)) {
throw new PlatformLeadAdminError("VALIDATION", "The platform lead archive filter is invalid.");
}
return {
search,
statuses,
sourceIds,
assignedToAdminUserIds,
includeUnassigned: query.includeUnassigned === true,
archive,
cursor,
limit,
};
}
function normalizeCreateSource(input: CreatePlatformLeadSourceInput): CreateSourceCommand {
if (!input || typeof input !== "object") throw new PlatformLeadAdminError("VALIDATION", "Platform lead source input is required.");
const key = normalizeRequiredString(input.key, 100, "key").toLowerCase();
if (!SOURCE_KEY_PATTERN.test(key)) throw new PlatformLeadAdminError("VALIDATION", "The platform lead source key is invalid.");
const notifyAdminUserIds = normalizeIdentifierList(input.notifyAdminUserIds ?? [], "notifyAdminUserId");
const enabled = input.enabled ?? true;
assertSourceRoutingConfigured(enabled, notifyAdminUserIds);
return {
key,
displayName: normalizeRequiredString(input.displayName, 200, "displayName"),
enabled,
defaultAssigneeAdminUserId: optionalAdminIdentifier(input.defaultAssigneeAdminUserId, "defaultAssigneeAdminUserId"),
notifyAdminUserIds,
rateLimitPerMinute: normalizeRateLimit(input.rateLimitPerMinute ?? 60),
metadata: normalizeSourceMetadata(input.metadata),
audit: normalizeAdminAudit(input),
};
}
function normalizeUpdateSource(input: UpdatePlatformLeadSourceInput): UpdateSourceCommand {
if (!input || typeof input !== "object") throw new PlatformLeadAdminError("VALIDATION", "Platform lead source update is required.");
const patch: UpdateSourceCommand["patch"] = {};
if (input.displayName !== undefined) patch.displayName = normalizeRequiredString(input.displayName, 200, "displayName");
if (input.enabled !== undefined) {
if (typeof input.enabled !== "boolean") throw new PlatformLeadAdminError("VALIDATION", "Platform lead source enabled must be boolean.");
patch.enabled = input.enabled;
}
if (input.defaultAssigneeAdminUserId !== undefined) {
patch.defaultAssigneeAdminUserId = optionalAdminIdentifier(input.defaultAssigneeAdminUserId, "defaultAssigneeAdminUserId");
}
if (input.notifyAdminUserIds !== undefined) patch.notifyAdminUserIds = normalizeIdentifierList(input.notifyAdminUserIds, "notifyAdminUserId");
if (input.rateLimitPerMinute !== undefined) patch.rateLimitPerMinute = normalizeRateLimit(input.rateLimitPerMinute);
if (input.metadata !== undefined) patch.metadata = normalizeSourceMetadata(input.metadata);
if (Object.keys(patch).length === 0) throw new PlatformLeadAdminError("VALIDATION", "The platform lead source update is empty.");
return { sourceId: requireAdminIdentifier(input.sourceId, "sourceId"), patch, audit: normalizeAdminAudit(input) };
}
function issueCredentialCommand(input: IssuePlatformLeadSourceCredentialInput): IssueCredentialCommand & { secret: string } {
const now = normalizeAdminDate(input.now ?? new Date(), "now");
const expiresAt = input.expiresAt === null || input.expiresAt === undefined ? null : normalizeAdminDate(input.expiresAt, "expiresAt");
if (expiresAt && expiresAt.getTime() <= now.getTime()) {
throw new PlatformLeadAdminError("VALIDATION", "The platform lead source credential expiry must be in the future.");
}
const secret = `${PLATFORM_LEAD_SOURCE_CREDENTIAL_PREFIX}_${randomBytes(32).toString("base64url")}`;
return {
sourceId: requireAdminIdentifier(input.sourceId, "sourceId"),
secret,
secretHash: hashPlatformLeadSourceCredential(secret),
keyPrefix: `${secret.slice(0, 12)}…`,
expiresAt,
now,
audit: normalizeAdminAudit(input),
};
}
function normalizeSourceMetadata(value: Record<string, unknown> | null | undefined): CreateSourceCommand["metadata"] {
if (value === null || value === undefined) return null;
if (typeof value !== "object" || Array.isArray(value)) throw new PlatformLeadAdminError("VALIDATION", "Platform lead source metadata must be an object.");
const entries = Object.entries(value);
if (entries.length > MAX_SOURCE_METADATA_ENTRIES || entries.some(([key]) => !SOURCE_METADATA_KEY_PATTERN.test(key))) {
throw new PlatformLeadAdminError("VALIDATION", "Platform lead source metadata contains an invalid key.");
}
const normalized = Object.fromEntries(
entries.map(([key, entry]) => {
if (entry === null || typeof entry === "boolean" || (typeof entry === "number" && Number.isFinite(entry))) return [key, entry];
if (typeof entry === "string" && entry.length <= 500 && !containsControlCharacter(entry)) return [key, entry];
throw new PlatformLeadAdminError("VALIDATION", `Platform lead source metadata value ${key} is invalid.`);
})
) as Record<string, string | number | boolean | null>;
if (Buffer.byteLength(JSON.stringify(normalized), "utf8") > MAX_SOURCE_METADATA_BYTES) {
throw new PlatformLeadAdminError("VALIDATION", "Platform lead source metadata is too large.");
}
return normalized;
}
function normalizeIdentifierList(values: readonly string[], field: string): string[] {
if (!Array.isArray(values)) throw new PlatformLeadAdminError("VALIDATION", `Platform lead ${field} list is invalid.`);
if (values.length > MAX_NOTIFICATION_RECIPIENTS) {
throw new PlatformLeadAdminError("VALIDATION", `Platform lead ${field} list is too large.`);
}
return uniqueValues(values).map((value) => requireAdminIdentifier(value, field));
}
function uniqueValues<T>(values: readonly T[]): T[] {
return [...new Set(values)];
}
function requireStatus(value: PlatformLeadStatus): PlatformLeadStatus {
if (typeof value !== "string" || !PLATFORM_LEAD_STATUS_SET.has(value)) {
throw new PlatformLeadAdminError("VALIDATION", "The platform lead status is invalid.");
}
return value;
}
function normalizeNote(value: string): string {
return normalizeRequiredString(value, MAX_NOTE_LENGTH, "note");
}
function normalizeRateLimit(value: number): number {
if (!Number.isInteger(value) || value < 1 || value > 10_000) {
throw new PlatformLeadAdminError("VALIDATION", "Platform lead source rate limit must be between 1 and 10000.");
}
return value;
}
function normalizeRequiredString(value: string, maxLength: number, field: string): string {
const normalized = normalizeOptionalString(value, maxLength, field);
if (!normalized) throw new PlatformLeadAdminError("VALIDATION", `Platform lead ${field} is required.`);
return normalized;
}
function normalizeOptionalString(value: string | null | undefined, maxLength: number, field: string): string | null {
if (value === null || value === undefined) return null;
if (typeof value !== "string") throw new PlatformLeadAdminError("VALIDATION", `Platform lead ${field} must be a string.`);
const normalized = value.trim();
if (!normalized) return null;
if (normalized.length > maxLength || containsControlCharacter(normalized)) {
throw new PlatformLeadAdminError("VALIDATION", `Platform lead ${field} is invalid.`);
}
return normalized;
}
function requireAdminIdentifier(value: string, field: string): string {
const normalized = optionalAdminIdentifier(value, field);
if (!normalized) throw new PlatformLeadAdminError("VALIDATION", `Platform lead ${field} is required.`);
return normalized;
}
function optionalAdminIdentifier(value: string | null | undefined, field: string): string | null {
if (value === null || value === undefined) return null;
if (typeof value !== "string") throw new PlatformLeadAdminError("VALIDATION", `Platform lead ${field} is invalid.`);
const normalized = value.trim();
if (!normalized || normalized.length > 191 || !ADMIN_IDENTIFIER_PATTERN.test(normalized)) {
throw new PlatformLeadAdminError("VALIDATION", `Platform lead ${field} is invalid.`);
}
return normalized;
}
function normalizeAdminDate(value: Date, field: string): Date {
if (!(value instanceof Date) || !Number.isFinite(value.getTime())) {
throw new PlatformLeadAdminError("VALIDATION", `Platform lead ${field} is invalid.`);
}
return value;
}
function containsControlCharacter(value: string): boolean {
return /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test(value);
}
async function assertConfiguredOperatorsExist(
tx: Prisma.TransactionClient,
defaultAssigneeAdminUserId: string | null,
notifyAdminUserIds: readonly string[]
): Promise<void> {
const configuredIds = uniqueValues([
...(defaultAssigneeAdminUserId ? [defaultAssigneeAdminUserId] : []),
...notifyAdminUserIds,
]);
if (configuredIds.length === 0) return;
const operators = await tx.adminUser.findMany({
where: {
id: { in: configuredIds },
status: "active",
roles: {
some: {
role: {
active: true,
permissions: { some: { permission: { name: { in: [...PLATFORM_LEAD_READ_PERMISSIONS] } } } },
},
},
},
},
select: { id: true },
});
const availableIds = new Set(operators.map(({ id }) => id));
if (configuredIds.some((userId) => !availableIds.has(userId))) {
throw new PlatformLeadAdminError(
"VALIDATION",
"Platform lead routing may reference only active platform operators with lead read permission."
);
}
const notifyReadAllIds = uniqueValues(notifyAdminUserIds.filter((userId) => userId !== defaultAssigneeAdminUserId));
if (notifyReadAllIds.length === 0) return;
const globallyReadableRecipients = await tx.adminUser.findMany({
where: {
id: { in: notifyReadAllIds },
status: "active",
roles: {
some: {
role: {
active: true,
permissions: { some: { permission: { name: "admin_sales.crm.read" } } },
},
},
},
},
select: { id: true },
});
const globallyReadableIds = new Set(globallyReadableRecipients.map(({ id }) => id));
if (notifyReadAllIds.some((userId) => !globallyReadableIds.has(userId))) {
throw new PlatformLeadAdminError(
"VALIDATION",
"Additional platform lead notification recipients require global lead read permission."
);
}
}
function toAdminJson(value: Record<string, unknown> | null): Prisma.InputJsonValue | typeof Prisma.JsonNull {
return value ? (value as Prisma.InputJsonObject) : Prisma.JsonNull;
}
function toJsonObject(value: Prisma.JsonValue | null): Record<string, unknown> | null {
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
}
function normalizeAdminAudit(input: PlatformLeadAdminAuditInput): NormalizedPlatformLeadAdminAudit {
try {
return normalizePlatformLeadAdminAudit(input);
} catch (error) {
const fallbackAuditContextDetail = "PLATFORM_LEAD_AUDIT_CONTEXT_INVALID";
const auditContextDetail = error instanceof Error ? error.message : fallbackAuditContextDetail;
throw new PlatformLeadAdminError("VALIDATION", auditContextDetail);
}
}
function assertSourceRoutingConfigured(enabled: boolean, notifyAdminUserIds: readonly string[]): void {
if (enabled && notifyAdminUserIds.length === 0) {
throw new PlatformLeadAdminError("VALIDATION", "An enabled platform lead source requires at least one durable notification recipient.");
}
}
function sourceAuditSnapshot(source: {
displayName: string;
enabled: boolean;
defaultAssigneeAdminUserId: string | null;
notifyAdminUserIds: string[];
rateLimitPerMinute: number;
}): Record<string, unknown> {
return {
displayName: source.displayName,
enabled: source.enabled,
defaultAssigneeAdminUserId: source.defaultAssigneeAdminUserId,
notifyAdminUserIds: [...source.notifyAdminUserIds],
rateLimitPerMinute: source.rateLimitPerMinute,
};
}
function translateAdminRepositoryError(error: unknown, conflictMessage = "The platform lead operation conflicts with existing data."): Error {
if (error instanceof PlatformLeadAdminError) return error;
if (error instanceof Prisma.PrismaClientKnownRequestError) {
if (error.code === "P2002") return new PlatformLeadAdminError("CONFLICT", conflictMessage);
if (error.code === "P2025") return new PlatformLeadAdminError("NOT_FOUND", "The platform lead record does not exist.");
}
return error instanceof Error ? error : new Error("Unknown platform lead repository error.");
}