966 lines
30 KiB
TypeScript
966 lines
30 KiB
TypeScript
import {
|
||
Prisma,
|
||
type AdminCallDirection,
|
||
type AdminCallMatchStatus,
|
||
type AdminCallSession,
|
||
type AdminCallStatus,
|
||
type AdminDataConnection,
|
||
type AdminPhoneConnection,
|
||
type PrismaClient,
|
||
} from "../generated/prisma/client/client.js";
|
||
import type { AdminPermissionName } from "./admin-permissions.js";
|
||
import {
|
||
type AdminSalesActor,
|
||
type AdminSalesAuditWriter,
|
||
writeAdminSalesAudit,
|
||
} from "./admin-sales-core.server.js";
|
||
|
||
const MAX_PROVIDER_ID_LENGTH = 512;
|
||
const MAX_PHONE_LENGTH = 32;
|
||
const MAX_LABEL_LENGTH = 120;
|
||
const MAX_EVENT_NAME_LENGTH = 160;
|
||
const SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/u;
|
||
|
||
const ADMIN_CALL_DISPOSITION_ENTRIES = [
|
||
["reached", "Erreicht"],
|
||
["voicemail", "Mailbox"],
|
||
["not_interested", "Kein Interesse"],
|
||
["interested", "Interesse"],
|
||
["interested_1_3_months", "Interessiert in 1–3 Monaten"],
|
||
["poor_fit", "Schlechter Fit"],
|
||
["declined", "Weggedrückt"],
|
||
[
|
||
"gatekeeper_no_prospect_contact",
|
||
"Gatekeeper – Kein Kontakt mit Prospekt",
|
||
],
|
||
["wrong_or_old_number", "Falsche/Alte Nummer"],
|
||
["customer", "Kunde"],
|
||
["rescheduling", "Rescheduling"],
|
||
] as const;
|
||
|
||
export const ADMIN_CALL_DISPOSITIONS = Object.freeze(
|
||
ADMIN_CALL_DISPOSITION_ENTRIES.map(([code, label]) =>
|
||
Object.freeze({ code, label })
|
||
)
|
||
);
|
||
|
||
export type AdminTelephonyPhoneNumberInput = {
|
||
readonly providerNumberId: string;
|
||
readonly label: string;
|
||
readonly e164: string;
|
||
readonly countryCode?: string | null;
|
||
readonly selected?: boolean;
|
||
};
|
||
|
||
export type ActivateAdminPhoneConnectionInput = {
|
||
readonly adminUserId: string;
|
||
readonly connectionId: string;
|
||
readonly providerCompanyId?: string | null;
|
||
readonly providerUserId: string;
|
||
readonly providerUserEmail?: string | null;
|
||
readonly defaultProviderNumberId?: string | null;
|
||
readonly webhookRegistrationId: string;
|
||
readonly webhookTokenHash: string;
|
||
readonly phoneNumbers: readonly AdminTelephonyPhoneNumberInput[];
|
||
readonly actor: AdminSalesActor;
|
||
};
|
||
|
||
export type AdminCallSnapshotInput = {
|
||
readonly direction: AdminCallDirection;
|
||
readonly status: AdminCallStatus;
|
||
readonly providerUserId?: string | null;
|
||
readonly fromNumber: string;
|
||
readonly toNumber: string;
|
||
readonly startedAt: Date;
|
||
readonly answeredAt?: Date | null;
|
||
readonly endedAt?: Date | null;
|
||
readonly durationSeconds?: number | null;
|
||
};
|
||
|
||
export type AdminTelephonyMatchCandidateInput = {
|
||
readonly entityType: "contact" | "lead";
|
||
readonly entityId: string;
|
||
readonly confidenceBasisPoints: number;
|
||
readonly matchReason: "e164" | "suffix";
|
||
};
|
||
|
||
export type PersistAdminCallEventInput = {
|
||
readonly phoneConnectionId: string;
|
||
readonly adminUserId: string;
|
||
readonly providerCallId: string;
|
||
readonly dedupeKey: string;
|
||
readonly providerEvent: string;
|
||
readonly occurredAt: Date;
|
||
readonly externalNumber: string;
|
||
readonly snapshot: AdminCallSnapshotInput;
|
||
readonly candidates: readonly AdminTelephonyMatchCandidateInput[];
|
||
};
|
||
|
||
export type AdminCallPhoneCandidate = {
|
||
readonly entityType: "contact" | "lead";
|
||
readonly entityId: string;
|
||
readonly phone: string;
|
||
readonly projectIds: readonly string[];
|
||
};
|
||
|
||
export type PersistAdminCallEventResult = {
|
||
readonly call: AdminCallSession;
|
||
readonly duplicate: boolean;
|
||
readonly matchStatus: AdminCallMatchStatus;
|
||
};
|
||
|
||
export type AdminTelephonyRepository = {
|
||
activateConnection(
|
||
input: ActivateAdminPhoneConnectionInput
|
||
): Promise<AdminPhoneConnection>;
|
||
getCallSnapshot(input: {
|
||
readonly phoneConnectionId: string;
|
||
readonly adminUserId: string;
|
||
readonly providerCallId: string;
|
||
}): Promise<AdminCallSession | null>;
|
||
listPhoneCandidates(input: {
|
||
readonly adminUserId: string;
|
||
readonly normalizedPhone: string;
|
||
readonly suffix: string;
|
||
}): Promise<readonly AdminCallPhoneCandidate[]>;
|
||
persistCallEvent(
|
||
input: PersistAdminCallEventInput
|
||
): Promise<PersistAdminCallEventResult>;
|
||
};
|
||
|
||
export function createAdminTelephonyService(input: {
|
||
readonly repository: AdminTelephonyRepository;
|
||
readonly authorize: (
|
||
permission: AdminPermissionName
|
||
) => Promise<void> | void;
|
||
}) {
|
||
return {
|
||
async activateConnection(command: ActivateAdminPhoneConnectionInput) {
|
||
await input.authorize("admin_sales.integrations.manage");
|
||
return input.repository.activateConnection(
|
||
normalizeActivateConnectionInput(command)
|
||
);
|
||
},
|
||
|
||
async getCallSnapshot(command: {
|
||
readonly phoneConnectionId: string;
|
||
readonly adminUserId: string;
|
||
readonly providerCallId: string;
|
||
}) {
|
||
await input.authorize("admin_sales.phone.call");
|
||
return input.repository.getCallSnapshot({
|
||
phoneConnectionId: requiredId(
|
||
command.phoneConnectionId,
|
||
"phoneConnectionId"
|
||
),
|
||
adminUserId: requiredId(command.adminUserId, "adminUserId"),
|
||
providerCallId: requiredText(
|
||
command.providerCallId,
|
||
"providerCallId",
|
||
MAX_PROVIDER_ID_LENGTH
|
||
),
|
||
});
|
||
},
|
||
|
||
async listPhoneCandidates(command: {
|
||
readonly adminUserId: string;
|
||
readonly normalizedPhone: string;
|
||
readonly suffix: string;
|
||
}) {
|
||
await input.authorize("admin_sales.phone.call");
|
||
return input.repository.listPhoneCandidates({
|
||
adminUserId: requiredId(command.adminUserId, "adminUserId"),
|
||
normalizedPhone: normalizeE164(command.normalizedPhone),
|
||
suffix: normalizeSuffix(command.suffix),
|
||
});
|
||
},
|
||
|
||
/**
|
||
* This entry point is called only after the body-token hash was resolved
|
||
* by the narrow SECURITY DEFINER bootstrap function. The API binds the
|
||
* returned admin identity before reaching this method.
|
||
*/
|
||
persistVerifiedProviderEvent(command: PersistAdminCallEventInput) {
|
||
return input.repository.persistCallEvent(
|
||
normalizePersistCallEventInput(command)
|
||
);
|
||
},
|
||
};
|
||
}
|
||
|
||
type AdminTelephonyPrismaClient = Pick<
|
||
PrismaClient,
|
||
| "$transaction"
|
||
| "adminDataConnection"
|
||
| "adminPhoneConnection"
|
||
| "adminContact"
|
||
| "adminContactChannel"
|
||
| "adminLead"
|
||
| "adminCallSession"
|
||
>;
|
||
|
||
export function createPrismaAdminTelephonyRepository(
|
||
client: AdminTelephonyPrismaClient,
|
||
dependencies: { readonly writeAudit?: AdminSalesAuditWriter } = {}
|
||
): AdminTelephonyRepository {
|
||
const writeAudit = dependencies.writeAudit ?? writeAdminSalesAudit;
|
||
|
||
return {
|
||
activateConnection: (command) =>
|
||
client.$transaction(async (tx) => {
|
||
const dataConnection = await assertAircallConnection(
|
||
tx,
|
||
command.connectionId,
|
||
command.adminUserId
|
||
);
|
||
const phoneConnection = await tx.adminPhoneConnection.upsert({
|
||
where: { connectionId: dataConnection.id },
|
||
create: {
|
||
adminUserId: command.adminUserId,
|
||
connectionId: dataConnection.id,
|
||
providerCompanyId: command.providerCompanyId,
|
||
providerUserId: command.providerUserId,
|
||
providerUserEmail: command.providerUserEmail,
|
||
webhookTokenHash: command.webhookTokenHash,
|
||
webhookVerifiedAt: new Date(),
|
||
},
|
||
update: {
|
||
providerCompanyId: command.providerCompanyId,
|
||
providerUserId: command.providerUserId,
|
||
providerUserEmail: command.providerUserEmail,
|
||
webhookTokenHash: command.webhookTokenHash,
|
||
webhookVerifiedAt: new Date(),
|
||
archivedAt: null,
|
||
},
|
||
});
|
||
await tx.adminDataConnection.update({
|
||
where: {
|
||
id: dataConnection.id,
|
||
adminUserId: command.adminUserId,
|
||
},
|
||
data: {
|
||
webhookRegistrationId: command.webhookRegistrationId,
|
||
lastHealthCheckAt: new Date(),
|
||
healthMessageKey: "admin.sales.telephony.health.active",
|
||
},
|
||
});
|
||
const retainedProviderIds = command.phoneNumbers.map(
|
||
(phone) => phone.providerNumberId
|
||
);
|
||
await tx.adminPhoneNumber.updateMany({
|
||
where: {
|
||
phoneConnectionId: phoneConnection.id,
|
||
providerNumberId: { notIn: retainedProviderIds },
|
||
archivedAt: null,
|
||
},
|
||
data: { archivedAt: new Date(), selected: false },
|
||
});
|
||
for (const phone of command.phoneNumbers) {
|
||
await tx.adminPhoneNumber.upsert({
|
||
where: {
|
||
admin_phone_number_provider_key: {
|
||
phoneConnectionId: phoneConnection.id,
|
||
providerNumberId: phone.providerNumberId,
|
||
},
|
||
},
|
||
create: {
|
||
adminUserId: command.adminUserId,
|
||
phoneConnectionId: phoneConnection.id,
|
||
providerNumberId: phone.providerNumberId,
|
||
label: phone.label,
|
||
e164: phone.e164,
|
||
countryCode: phone.countryCode,
|
||
selected: phone.selected,
|
||
},
|
||
update: {
|
||
label: phone.label,
|
||
e164: phone.e164,
|
||
countryCode: phone.countryCode,
|
||
selected: phone.selected,
|
||
archivedAt: null,
|
||
},
|
||
});
|
||
}
|
||
const defaultPhoneNumber = command.defaultProviderNumberId
|
||
? await tx.adminPhoneNumber.findFirst({
|
||
where: {
|
||
phoneConnectionId: phoneConnection.id,
|
||
providerNumberId: command.defaultProviderNumberId,
|
||
archivedAt: null,
|
||
},
|
||
select: { id: true },
|
||
})
|
||
: null;
|
||
const activated = await tx.adminPhoneConnection.update({
|
||
where: { id: phoneConnection.id },
|
||
data: { defaultPhoneNumberId: defaultPhoneNumber?.id ?? null },
|
||
});
|
||
await seedAdminCallDispositions(tx);
|
||
await writeAudit(tx, {
|
||
actor: command.actor,
|
||
action: "admin.sales.telephony.connection.activated",
|
||
targetType: "AdminPhoneConnection",
|
||
targetId: activated.id,
|
||
after: {
|
||
provider: "aircall",
|
||
connectionId: activated.connectionId,
|
||
providerUserId: activated.providerUserId,
|
||
webhookRegistrationId: command.webhookRegistrationId,
|
||
phoneNumberCount: command.phoneNumbers.length,
|
||
},
|
||
});
|
||
return activated;
|
||
}),
|
||
|
||
getCallSnapshot: (command) =>
|
||
client.adminCallSession.findUnique({
|
||
where: {
|
||
admin_call_provider_key: {
|
||
phoneConnectionId: command.phoneConnectionId,
|
||
providerCallId: command.providerCallId,
|
||
},
|
||
},
|
||
}).then((call) =>
|
||
call?.adminUserId === command.adminUserId ? call : null
|
||
),
|
||
|
||
async listPhoneCandidates(command) {
|
||
const [contacts, channels, leads] = await Promise.all([
|
||
client.adminContact.findMany({
|
||
where: {
|
||
ownerAdminUserId: command.adminUserId,
|
||
archivedAt: null,
|
||
OR: [
|
||
{ normalizedPhone: command.normalizedPhone },
|
||
{ normalizedPhone: { endsWith: command.suffix } },
|
||
],
|
||
},
|
||
select: {
|
||
id: true,
|
||
normalizedPhone: true,
|
||
deals: {
|
||
where: { deal: { status: "open" } },
|
||
orderBy: [{ isPrimary: "desc" }, { createdAt: "asc" }],
|
||
select: { dealId: true },
|
||
},
|
||
},
|
||
take: 50,
|
||
}),
|
||
client.adminContactChannel.findMany({
|
||
where: {
|
||
archivedAt: null,
|
||
kind: "phone",
|
||
OR: [
|
||
{ normalizedValue: command.normalizedPhone },
|
||
{ normalizedValue: { endsWith: command.suffix } },
|
||
],
|
||
contact: {
|
||
ownerAdminUserId: command.adminUserId,
|
||
archivedAt: null,
|
||
},
|
||
},
|
||
select: {
|
||
normalizedValue: true,
|
||
contact: {
|
||
select: {
|
||
id: true,
|
||
deals: {
|
||
where: { deal: { status: "open" } },
|
||
orderBy: [{ isPrimary: "desc" }, { createdAt: "asc" }],
|
||
select: { dealId: true },
|
||
},
|
||
},
|
||
},
|
||
},
|
||
take: 50,
|
||
}),
|
||
client.adminLead.findMany({
|
||
where: {
|
||
assignedToAdminUserId: command.adminUserId,
|
||
archivedAt: null,
|
||
convertedDeal: null,
|
||
OR: [
|
||
{ normalizedPhone: command.normalizedPhone },
|
||
{ normalizedPhone: { endsWith: command.suffix } },
|
||
],
|
||
},
|
||
select: { id: true, normalizedPhone: true },
|
||
take: 50,
|
||
}),
|
||
]);
|
||
const candidates = new Map<string, AdminCallPhoneCandidate>();
|
||
for (const contact of contacts) {
|
||
if (!contact.normalizedPhone) continue;
|
||
candidates.set(`contact:${contact.id}`, {
|
||
entityType: "contact",
|
||
entityId: contact.id,
|
||
phone: contact.normalizedPhone,
|
||
projectIds: contact.deals.map(({ dealId }) => dealId),
|
||
});
|
||
}
|
||
for (const channel of channels) {
|
||
if (!channel.normalizedValue) continue;
|
||
candidates.set(`contact:${channel.contact.id}`, {
|
||
entityType: "contact",
|
||
entityId: channel.contact.id,
|
||
phone: channel.normalizedValue,
|
||
projectIds: channel.contact.deals.map(({ dealId }) => dealId),
|
||
});
|
||
}
|
||
for (const lead of leads) {
|
||
if (!lead.normalizedPhone) continue;
|
||
candidates.set(`lead:${lead.id}`, {
|
||
entityType: "lead",
|
||
entityId: lead.id,
|
||
phone: lead.normalizedPhone,
|
||
projectIds: [],
|
||
});
|
||
}
|
||
return [...candidates.values()].sort((left, right) =>
|
||
`${left.entityType}:${left.entityId}`.localeCompare(
|
||
`${right.entityType}:${right.entityId}`
|
||
)
|
||
);
|
||
},
|
||
|
||
persistCallEvent: (command) =>
|
||
client.$transaction(async (tx) => {
|
||
await tx.$queryRaw(
|
||
Prisma.sql`SELECT pg_advisory_xact_lock(hashtext(${`${command.phoneConnectionId}:${command.providerCallId}`}))`
|
||
);
|
||
const connection = await tx.adminPhoneConnection.findFirst({
|
||
where: {
|
||
id: command.phoneConnectionId,
|
||
adminUserId: command.adminUserId,
|
||
archivedAt: null,
|
||
},
|
||
select: { id: true },
|
||
});
|
||
if (!connection) {
|
||
throw new AdminTelephonyError("phone_connection_unavailable");
|
||
}
|
||
const duplicate = await tx.adminCallEvent.findUnique({
|
||
where: { dedupeKey: command.dedupeKey },
|
||
select: { callSessionId: true },
|
||
});
|
||
if (duplicate) {
|
||
const call = await tx.adminCallSession.findUniqueOrThrow({
|
||
where: { id: duplicate.callSessionId },
|
||
});
|
||
return {
|
||
call,
|
||
duplicate: true,
|
||
matchStatus: call.matchStatus,
|
||
};
|
||
}
|
||
|
||
const current = await tx.adminCallSession.findUnique({
|
||
where: {
|
||
admin_call_provider_key: {
|
||
phoneConnectionId: command.phoneConnectionId,
|
||
providerCallId: command.providerCallId,
|
||
},
|
||
},
|
||
});
|
||
const match = current?.matchStatus === "confirmed"
|
||
? {
|
||
status: current.matchStatus,
|
||
contactId: current.contactId,
|
||
leadId: current.leadId,
|
||
dealId: current.dealId,
|
||
confidenceBasisPoints: current.matchConfidenceBasisPoints,
|
||
}
|
||
: await resolveStoredMatch(tx, command.candidates);
|
||
const externalNumber = normalizeE164(command.externalNumber);
|
||
const call = await tx.adminCallSession.upsert({
|
||
where: {
|
||
admin_call_provider_key: {
|
||
phoneConnectionId: command.phoneConnectionId,
|
||
providerCallId: command.providerCallId,
|
||
},
|
||
},
|
||
create: {
|
||
adminUserId: command.adminUserId,
|
||
phoneConnectionId: command.phoneConnectionId,
|
||
providerCallId: command.providerCallId,
|
||
direction: command.snapshot.direction,
|
||
status: command.snapshot.status,
|
||
providerUserId: command.snapshot.providerUserId,
|
||
fromNumber: command.snapshot.fromNumber,
|
||
toNumber: command.snapshot.toNumber,
|
||
externalNumber,
|
||
startedAt: command.snapshot.startedAt,
|
||
answeredAt: command.snapshot.answeredAt,
|
||
endedAt: command.snapshot.endedAt,
|
||
durationSeconds: command.snapshot.durationSeconds,
|
||
contactId: match.contactId,
|
||
leadId: match.leadId,
|
||
dealId: match.dealId,
|
||
matchStatus: match.status,
|
||
matchConfidenceBasisPoints: match.confidenceBasisPoints,
|
||
},
|
||
update: {
|
||
status: command.snapshot.status,
|
||
providerUserId: command.snapshot.providerUserId,
|
||
fromNumber: command.snapshot.fromNumber,
|
||
toNumber: command.snapshot.toNumber,
|
||
externalNumber,
|
||
startedAt: command.snapshot.startedAt,
|
||
answeredAt: command.snapshot.answeredAt,
|
||
endedAt: command.snapshot.endedAt,
|
||
durationSeconds: command.snapshot.durationSeconds,
|
||
contactId: match.contactId,
|
||
leadId: match.leadId,
|
||
dealId: match.dealId,
|
||
matchStatus: match.status,
|
||
matchConfidenceBasisPoints: match.confidenceBasisPoints,
|
||
},
|
||
});
|
||
if (current?.matchStatus !== "confirmed") {
|
||
if (command.candidates.length > 0) {
|
||
await tx.adminCallMatchCandidate.createMany({
|
||
data: command.candidates.map((candidate) => ({
|
||
adminUserId: command.adminUserId,
|
||
callSessionId: call.id,
|
||
contactId:
|
||
candidate.entityType === "contact"
|
||
? candidate.entityId
|
||
: null,
|
||
leadId:
|
||
candidate.entityType === "lead" ? candidate.entityId : null,
|
||
confidenceBasisPoints: candidate.confidenceBasisPoints,
|
||
matchReason: candidate.matchReason,
|
||
})),
|
||
skipDuplicates: true,
|
||
});
|
||
}
|
||
}
|
||
await tx.adminCallParticipant.upsert({
|
||
where: {
|
||
admin_call_participant_identity_key: {
|
||
callSessionId: call.id,
|
||
kind: "external",
|
||
phone: externalNumber,
|
||
},
|
||
},
|
||
create: {
|
||
adminUserId: command.adminUserId,
|
||
callSessionId: call.id,
|
||
kind: "external",
|
||
phone: externalNumber,
|
||
},
|
||
update: {},
|
||
});
|
||
await tx.adminCallEvent.create({
|
||
data: {
|
||
adminUserId: command.adminUserId,
|
||
callSessionId: call.id,
|
||
dedupeKey: command.dedupeKey,
|
||
providerEvent: command.providerEvent,
|
||
status: command.snapshot.status,
|
||
occurredAt: command.occurredAt,
|
||
durationSeconds: command.snapshot.durationSeconds,
|
||
},
|
||
});
|
||
await tx.adminActivity.create({
|
||
data: {
|
||
type: "call",
|
||
actorAdminUserId: command.adminUserId,
|
||
leadId: call.leadId,
|
||
contactId: call.contactId,
|
||
dealId: call.dealId,
|
||
callSessionId: call.id,
|
||
summary: callActivitySummary(call),
|
||
payload: {
|
||
provider: "aircall",
|
||
providerEvent: command.providerEvent,
|
||
direction: call.direction,
|
||
status: call.status,
|
||
durationSeconds: call.durationSeconds,
|
||
matchStatus: call.matchStatus,
|
||
},
|
||
occurredAt: command.occurredAt,
|
||
},
|
||
});
|
||
await tx.adminPhoneConnection.update({
|
||
where: { id: command.phoneConnectionId },
|
||
data: { lastEventAt: command.occurredAt },
|
||
});
|
||
await writeAudit(tx, {
|
||
actor: {
|
||
adminUserId: command.adminUserId,
|
||
reason: "Verifizierter Aircall-Webhook",
|
||
},
|
||
action: "admin.sales.telephony.call_event.received",
|
||
targetType: "AdminCallSession",
|
||
targetId: call.id,
|
||
after: {
|
||
providerEvent: command.providerEvent,
|
||
status: call.status,
|
||
direction: call.direction,
|
||
matchStatus: call.matchStatus,
|
||
},
|
||
});
|
||
return { call, duplicate: false, matchStatus: call.matchStatus };
|
||
}),
|
||
};
|
||
}
|
||
|
||
export async function seedAdminCallDispositions(
|
||
tx: Pick<Prisma.TransactionClient, "adminCallDisposition">
|
||
) {
|
||
for (const [position, disposition] of ADMIN_CALL_DISPOSITIONS.entries()) {
|
||
await tx.adminCallDisposition.upsert({
|
||
where: { code: disposition.code },
|
||
create: {
|
||
code: disposition.code,
|
||
label: disposition.label,
|
||
position,
|
||
},
|
||
update: {
|
||
label: disposition.label,
|
||
position,
|
||
active: true,
|
||
archivedAt: null,
|
||
},
|
||
});
|
||
}
|
||
}
|
||
|
||
async function assertAircallConnection(
|
||
tx: Prisma.TransactionClient,
|
||
connectionId: string,
|
||
adminUserId: string
|
||
): Promise<AdminDataConnection> {
|
||
const connection = await tx.adminDataConnection.findFirst({
|
||
where: {
|
||
id: connectionId,
|
||
adminUserId,
|
||
provider: "aircall",
|
||
capability: "telephony",
|
||
status: { in: ["active", "degraded"] },
|
||
archivedAt: null,
|
||
},
|
||
});
|
||
if (!connection) {
|
||
throw new AdminTelephonyError("data_connection_unavailable");
|
||
}
|
||
return connection;
|
||
}
|
||
|
||
async function resolveStoredMatch(
|
||
tx: Prisma.TransactionClient,
|
||
candidates: readonly AdminTelephonyMatchCandidateInput[]
|
||
) {
|
||
const unique = new Map(
|
||
candidates.map((candidate) => [
|
||
`${candidate.entityType}:${candidate.entityId}`,
|
||
candidate,
|
||
])
|
||
);
|
||
if (unique.size !== 1) {
|
||
return {
|
||
status: unique.size === 0 ? "unmatched" as const : "ambiguous" as const,
|
||
contactId: null,
|
||
leadId: null,
|
||
dealId: null,
|
||
confidenceBasisPoints: null,
|
||
};
|
||
}
|
||
const candidate = [...unique.values()][0]!;
|
||
if (candidate.entityType === "lead") {
|
||
return {
|
||
status: "unique" as const,
|
||
contactId: null,
|
||
leadId: candidate.entityId,
|
||
dealId: null,
|
||
confidenceBasisPoints: candidate.confidenceBasisPoints,
|
||
};
|
||
}
|
||
const deal = await tx.adminDealContact.findFirst({
|
||
where: {
|
||
contactId: candidate.entityId,
|
||
deal: { status: "open" },
|
||
},
|
||
orderBy: [{ isPrimary: "desc" }, { createdAt: "asc" }, { dealId: "asc" }],
|
||
select: { dealId: true },
|
||
});
|
||
return {
|
||
status: "unique" as const,
|
||
contactId: candidate.entityId,
|
||
leadId: null,
|
||
dealId: deal?.dealId ?? null,
|
||
confidenceBasisPoints: candidate.confidenceBasisPoints,
|
||
};
|
||
}
|
||
|
||
function normalizeActivateConnectionInput(
|
||
input: ActivateAdminPhoneConnectionInput
|
||
): ActivateAdminPhoneConnectionInput {
|
||
const adminUserId = requiredId(input.adminUserId, "adminUserId");
|
||
const connectionId = requiredId(input.connectionId, "connectionId");
|
||
const seenProviderNumbers = new Set<string>();
|
||
const phoneNumbers = input.phoneNumbers.map((phone) => {
|
||
const providerNumberId = requiredText(
|
||
phone.providerNumberId,
|
||
"providerNumberId",
|
||
MAX_PROVIDER_ID_LENGTH
|
||
);
|
||
if (seenProviderNumbers.has(providerNumberId)) {
|
||
throw new AdminTelephonyError("duplicate_provider_number");
|
||
}
|
||
seenProviderNumbers.add(providerNumberId);
|
||
return {
|
||
providerNumberId,
|
||
label: requiredText(phone.label, "label", MAX_LABEL_LENGTH),
|
||
e164: normalizeE164(phone.e164),
|
||
countryCode: optionalText(phone.countryCode, "countryCode", 8),
|
||
selected: phone.selected ?? true,
|
||
};
|
||
});
|
||
const defaultProviderNumberId = optionalText(
|
||
input.defaultProviderNumberId,
|
||
"defaultProviderNumberId",
|
||
MAX_PROVIDER_ID_LENGTH
|
||
);
|
||
if (
|
||
defaultProviderNumberId &&
|
||
!seenProviderNumbers.has(defaultProviderNumberId)
|
||
) {
|
||
throw new AdminTelephonyError("default_number_unavailable");
|
||
}
|
||
return {
|
||
adminUserId,
|
||
connectionId,
|
||
providerCompanyId: optionalText(
|
||
input.providerCompanyId,
|
||
"providerCompanyId",
|
||
MAX_PROVIDER_ID_LENGTH
|
||
),
|
||
providerUserId: requiredText(
|
||
input.providerUserId,
|
||
"providerUserId",
|
||
MAX_PROVIDER_ID_LENGTH
|
||
),
|
||
providerUserEmail: optionalText(
|
||
input.providerUserEmail,
|
||
"providerUserEmail",
|
||
320
|
||
)?.toLowerCase() ?? null,
|
||
defaultProviderNumberId,
|
||
webhookRegistrationId: requiredText(
|
||
input.webhookRegistrationId,
|
||
"webhookRegistrationId",
|
||
MAX_PROVIDER_ID_LENGTH
|
||
),
|
||
webhookTokenHash: normalizeSha256(input.webhookTokenHash),
|
||
phoneNumbers,
|
||
actor: normalizeActor(input.actor, adminUserId),
|
||
};
|
||
}
|
||
|
||
function normalizePersistCallEventInput(
|
||
input: PersistAdminCallEventInput
|
||
): PersistAdminCallEventInput {
|
||
const adminUserId = requiredId(input.adminUserId, "adminUserId");
|
||
const snapshot = {
|
||
direction: input.snapshot.direction,
|
||
status: input.snapshot.status,
|
||
providerUserId: optionalText(
|
||
input.snapshot.providerUserId,
|
||
"providerUserId",
|
||
MAX_PROVIDER_ID_LENGTH
|
||
),
|
||
fromNumber: normalizeProviderPhone(input.snapshot.fromNumber),
|
||
toNumber: normalizeProviderPhone(input.snapshot.toNumber),
|
||
startedAt: validDate(input.snapshot.startedAt, "startedAt"),
|
||
answeredAt: optionalDate(input.snapshot.answeredAt, "answeredAt"),
|
||
endedAt: optionalDate(input.snapshot.endedAt, "endedAt"),
|
||
durationSeconds: optionalNonNegativeInteger(
|
||
input.snapshot.durationSeconds,
|
||
"durationSeconds"
|
||
),
|
||
};
|
||
if (!["inbound", "outbound"].includes(snapshot.direction)) {
|
||
throw new AdminTelephonyError("invalid_direction");
|
||
}
|
||
if (
|
||
!["ringing", "answered", "completed", "missed", "failed"].includes(
|
||
snapshot.status
|
||
)
|
||
) {
|
||
throw new AdminTelephonyError("invalid_status");
|
||
}
|
||
return {
|
||
phoneConnectionId: requiredId(
|
||
input.phoneConnectionId,
|
||
"phoneConnectionId"
|
||
),
|
||
adminUserId,
|
||
providerCallId: requiredText(
|
||
input.providerCallId,
|
||
"providerCallId",
|
||
MAX_PROVIDER_ID_LENGTH
|
||
),
|
||
dedupeKey: requiredText(input.dedupeKey, "dedupeKey", 1_000),
|
||
providerEvent: requiredText(
|
||
input.providerEvent,
|
||
"providerEvent",
|
||
MAX_EVENT_NAME_LENGTH
|
||
),
|
||
occurredAt: validDate(input.occurredAt, "occurredAt"),
|
||
externalNumber: normalizeE164(input.externalNumber),
|
||
snapshot,
|
||
candidates: normalizeCandidates(input.candidates),
|
||
};
|
||
}
|
||
|
||
function normalizeCandidates(
|
||
candidates: readonly AdminTelephonyMatchCandidateInput[]
|
||
) {
|
||
const unique = new Map<string, AdminTelephonyMatchCandidateInput>();
|
||
for (const candidate of candidates) {
|
||
const normalized = {
|
||
entityType: candidate.entityType,
|
||
entityId: requiredId(candidate.entityId, "candidate.entityId"),
|
||
confidenceBasisPoints: requiredBasisPoints(
|
||
candidate.confidenceBasisPoints
|
||
),
|
||
matchReason: candidate.matchReason,
|
||
};
|
||
if (!["contact", "lead"].includes(normalized.entityType)) {
|
||
throw new AdminTelephonyError("invalid_candidate_type");
|
||
}
|
||
if (!["e164", "suffix"].includes(normalized.matchReason)) {
|
||
throw new AdminTelephonyError("invalid_match_reason");
|
||
}
|
||
unique.set(
|
||
`${normalized.entityType}:${normalized.entityId}`,
|
||
normalized
|
||
);
|
||
}
|
||
return [...unique.values()].sort((left, right) =>
|
||
`${left.entityType}:${left.entityId}`.localeCompare(
|
||
`${right.entityType}:${right.entityId}`
|
||
)
|
||
);
|
||
}
|
||
|
||
function callActivitySummary(call: AdminCallSession): string {
|
||
const direction = call.direction === "inbound" ? "Eingehender" : "Ausgehender";
|
||
const status = {
|
||
ringing: "klingelt",
|
||
answered: "angenommen",
|
||
completed: "abgeschlossen",
|
||
missed: "verpasst",
|
||
failed: "fehlgeschlagen",
|
||
}[call.status];
|
||
return `${direction} Anruf ${status}`;
|
||
}
|
||
|
||
function normalizeActor(
|
||
actor: AdminSalesActor,
|
||
adminUserId: string
|
||
): AdminSalesActor {
|
||
if (requiredId(actor.adminUserId, "actor.adminUserId") !== adminUserId) {
|
||
throw new AdminTelephonyError("actor_owner_mismatch");
|
||
}
|
||
return {
|
||
...actor,
|
||
adminUserId,
|
||
reason: requiredText(actor.reason, "actor.reason", 2_000),
|
||
};
|
||
}
|
||
|
||
function requiredId(value: string, field: string): string {
|
||
return requiredText(value, field, 200);
|
||
}
|
||
|
||
function requiredText(value: string, field: string, maxLength: number): string {
|
||
const normalized = value.trim();
|
||
if (!normalized || normalized.length > maxLength) {
|
||
throw new AdminTelephonyError(`invalid_${field}`);
|
||
}
|
||
return normalized;
|
||
}
|
||
|
||
function optionalText(
|
||
value: string | null | undefined,
|
||
field: string,
|
||
maxLength: number
|
||
): string | null {
|
||
if (value === null || value === undefined || !value.trim()) return null;
|
||
return requiredText(value, field, maxLength);
|
||
}
|
||
|
||
function normalizeE164(value: string): string {
|
||
const normalized = value.trim().replace(/[^\d+]/gu, "").replace(/(?!^)\+/gu, "");
|
||
if (!/^\+[1-9]\d{7,14}$/u.test(normalized)) {
|
||
throw new AdminTelephonyError("invalid_phone_number");
|
||
}
|
||
return normalized;
|
||
}
|
||
|
||
function normalizeProviderPhone(value: string): string {
|
||
const normalized = value.trim();
|
||
if (!normalized || normalized.length > MAX_PHONE_LENGTH) {
|
||
throw new AdminTelephonyError("invalid_provider_phone");
|
||
}
|
||
return normalized === "unknown" ? normalized : normalizeE164(normalized);
|
||
}
|
||
|
||
function normalizeSuffix(value: string): string {
|
||
const normalized = value.replace(/\D/gu, "");
|
||
if (normalized.length !== 8) {
|
||
throw new AdminTelephonyError("invalid_phone_suffix");
|
||
}
|
||
return normalized;
|
||
}
|
||
|
||
function normalizeSha256(value: string): string {
|
||
const normalized = value.trim().toLowerCase();
|
||
if (!SHA256_HEX_PATTERN.test(normalized)) {
|
||
throw new AdminTelephonyError("invalid_webhook_token_hash");
|
||
}
|
||
return normalized;
|
||
}
|
||
|
||
function requiredBasisPoints(value: number): number {
|
||
if (!Number.isInteger(value) || value < 0 || value > 10_000) {
|
||
throw new AdminTelephonyError("invalid_match_confidence");
|
||
}
|
||
return value;
|
||
}
|
||
|
||
function optionalNonNegativeInteger(
|
||
value: number | null | undefined,
|
||
field: string
|
||
): number | null {
|
||
if (value === null || value === undefined) return null;
|
||
if (!Number.isSafeInteger(value) || value < 0) {
|
||
throw new AdminTelephonyError(`invalid_${field}`);
|
||
}
|
||
return value;
|
||
}
|
||
|
||
function validDate(value: Date, field: string): Date {
|
||
if (!(value instanceof Date) || Number.isNaN(value.getTime())) {
|
||
throw new AdminTelephonyError(`invalid_${field}`);
|
||
}
|
||
return value;
|
||
}
|
||
|
||
function optionalDate(
|
||
value: Date | null | undefined,
|
||
field: string
|
||
): Date | null {
|
||
return value === null || value === undefined ? null : validDate(value, field);
|
||
}
|
||
|
||
export class AdminTelephonyError extends Error {
|
||
constructor(readonly code: string) {
|
||
super(code);
|
||
this.name = "AdminTelephonyError";
|
||
}
|
||
}
|