287 lines
9.3 KiB
TypeScript
287 lines
9.3 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import type { AdminPermissionName } from "@hivegrid/db/admin-permissions";
|
|
import { adminHasPermission } from "@hivegrid/db/admin-rbac.server";
|
|
import {
|
|
createAdminConnectionsService,
|
|
createPrismaAdminConnectionsRepository,
|
|
} from "@hivegrid/db/admin-connections.server";
|
|
import {
|
|
createAdminTelephonyService,
|
|
createPrismaAdminTelephonyRepository,
|
|
} from "@hivegrid/db/admin-telephony.server";
|
|
import {
|
|
createAdminTelephonyActionsService,
|
|
createPrismaAdminTelephonyActionsRepository,
|
|
} from "@hivegrid/db/admin-telephony-actions.server";
|
|
import {
|
|
createAdminTelephonyRecordingService,
|
|
createPrismaAdminTelephonyRecordingRepository,
|
|
} from "@hivegrid/db/admin-telephony-recordings.server";
|
|
import {
|
|
AIRCALL_CALL_WEBHOOK_EVENTS,
|
|
AIRCALL_OAUTH_SCOPE,
|
|
aircallTelephonyProvider,
|
|
exchangeAircallCodeForToken,
|
|
resolveAircallOAuthConfig,
|
|
} from "@hivegrid/integrations";
|
|
|
|
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
|
import {
|
|
extractWebActorIp,
|
|
extractWebActorUserAgent,
|
|
extractWebRequestId,
|
|
} from "~/utils/audit/withAuditContext";
|
|
import { db } from "~/utils/db.server";
|
|
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
|
|
|
|
export type AdminTelephonyOperatorContext = {
|
|
readonly adminUserId: string;
|
|
readonly email: string;
|
|
readonly connections: ReturnType<typeof createAdminConnectionsService>;
|
|
readonly telephony: ReturnType<typeof createAdminTelephonyService>;
|
|
readonly actions: ReturnType<typeof createAdminTelephonyActionsService>;
|
|
readonly recordings: ReturnType<
|
|
typeof createAdminTelephonyRecordingService
|
|
>;
|
|
readonly canCall: boolean;
|
|
readonly canReadAllCommunication: boolean;
|
|
readonly canManageSettings: boolean;
|
|
readonly canManageRecording: boolean;
|
|
readonly actor: (reason: string) => {
|
|
readonly adminUserId: string;
|
|
readonly email: string;
|
|
readonly reason: string;
|
|
readonly requestId: string | null;
|
|
readonly ip: string | null;
|
|
readonly userAgent: string | null;
|
|
};
|
|
};
|
|
|
|
export async function runAsAdminTelephonyOperator<T>(
|
|
request: Request,
|
|
permission:
|
|
| Extract<
|
|
AdminPermissionName,
|
|
| "admin_sales.phone.call"
|
|
| "admin_sales.phone.recording"
|
|
| "admin_sales.integrations.manage"
|
|
| "admin_sales.communication.read_all"
|
|
>
|
|
| readonly Extract<
|
|
AdminPermissionName,
|
|
| "admin_sales.phone.call"
|
|
| "admin_sales.phone.recording"
|
|
| "admin_sales.integrations.manage"
|
|
| "admin_sales.communication.read_all"
|
|
>[],
|
|
operation: (context: AdminTelephonyOperatorContext) => Promise<T>
|
|
): Promise<T> {
|
|
return runAsAdminIdentity(request, permission, async (session) => {
|
|
const admin = await db.adminUser.findFirst({
|
|
where: { id: session.adminUserId, status: "active" },
|
|
select: { id: true, email: true },
|
|
});
|
|
if (!admin) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
|
const authorize = async (requested: AdminPermissionName) => {
|
|
if (!(await adminHasPermission(admin.id, requested, db))) {
|
|
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
|
}
|
|
};
|
|
const auditBase = {
|
|
adminUserId: admin.id,
|
|
email: admin.email,
|
|
requestId: extractWebRequestId(request),
|
|
ip: extractWebActorIp(request),
|
|
userAgent: extractWebActorUserAgent(request),
|
|
};
|
|
const [
|
|
canCall,
|
|
canManageSettings,
|
|
canManageRecording,
|
|
canReadAllCommunication,
|
|
] = await Promise.all([
|
|
adminHasPermission(admin.id, "admin_sales.phone.call", db),
|
|
adminHasPermission(admin.id, "admin_sales.integrations.manage", db),
|
|
adminHasPermission(admin.id, "admin_sales.phone.recording", db),
|
|
adminHasPermission(
|
|
admin.id,
|
|
"admin_sales.communication.read_all",
|
|
db
|
|
),
|
|
]);
|
|
return operation({
|
|
adminUserId: admin.id,
|
|
email: admin.email,
|
|
connections: createAdminConnectionsService({
|
|
repository: createPrismaAdminConnectionsRepository(db),
|
|
authorize,
|
|
permission: "admin_sales.integrations.manage",
|
|
}),
|
|
telephony: createAdminTelephonyService({
|
|
repository: createPrismaAdminTelephonyRepository(db),
|
|
authorize,
|
|
}),
|
|
actions: createAdminTelephonyActionsService({
|
|
repository: createPrismaAdminTelephonyActionsRepository(db),
|
|
authorize,
|
|
}),
|
|
recordings: createAdminTelephonyRecordingService({
|
|
repository: createPrismaAdminTelephonyRecordingRepository(db),
|
|
authorize,
|
|
}),
|
|
canCall,
|
|
canReadAllCommunication,
|
|
canManageSettings,
|
|
canManageRecording,
|
|
actor: (reason) => ({ ...auditBase, reason }),
|
|
});
|
|
});
|
|
}
|
|
|
|
export function getAdminAircallAuthorizationUrl(state: string): string {
|
|
const config = resolveAircallOAuthConfig();
|
|
if (!config) {
|
|
throw new Error("admin.sales.telephony.errors.aircallNotConfigured");
|
|
}
|
|
const params = new URLSearchParams({
|
|
client_id: config.clientId,
|
|
redirect_uri: config.redirectUri,
|
|
response_type: "code",
|
|
scope: AIRCALL_OAUTH_SCOPE,
|
|
state,
|
|
});
|
|
return `https://dashboard.aircall.io/oauth/authorize?${params.toString()}`;
|
|
}
|
|
|
|
export async function completeAdminAircallConnection(input: {
|
|
readonly context: AdminTelephonyOperatorContext;
|
|
readonly code: string;
|
|
readonly webhookUrl?: string;
|
|
}) {
|
|
const config = resolveAircallOAuthConfig();
|
|
const webhookUrl =
|
|
input.webhookUrl ?? process.env.ADMIN_AIRCALL_WEBHOOK_URL?.trim();
|
|
if (!config || !webhookUrl) {
|
|
throw new Error("admin.sales.telephony.errors.aircallNotConfigured");
|
|
}
|
|
const credentials = await exchangeAircallCodeForToken(config, input.code);
|
|
await aircallTelephonyProvider.probe(credentials);
|
|
const users = await aircallTelephonyProvider.listUsers(credentials);
|
|
const matchingUsers = users.filter(
|
|
(user) => user.email === input.context.email.trim().toLowerCase()
|
|
);
|
|
if (matchingUsers.length !== 1) {
|
|
throw new Error(
|
|
matchingUsers.length === 0
|
|
? "admin.sales.telephony.errors.aircallUserMissing"
|
|
: "admin.sales.telephony.errors.aircallUserAmbiguous"
|
|
);
|
|
}
|
|
const providerUser = matchingUsers[0]!;
|
|
const phoneNumbers = await aircallTelephonyProvider.listUserNumbers(
|
|
credentials,
|
|
providerUser.id
|
|
);
|
|
if (phoneNumbers.length === 0) {
|
|
throw new Error("admin.sales.telephony.errors.aircallNumberMissing");
|
|
}
|
|
const webhook = await aircallTelephonyProvider.createWebhook(credentials, {
|
|
name: `admin-sales-${input.context.adminUserId}`,
|
|
url: webhookUrl,
|
|
events: AIRCALL_CALL_WEBHOOK_EVENTS,
|
|
});
|
|
let connectionId: string | null = null;
|
|
try {
|
|
const actor = input.context.actor("Aircall für Admin Sales verbinden");
|
|
const connection = await input.context.connections.connect({
|
|
adminUserId: input.context.adminUserId,
|
|
provider: "aircall",
|
|
capability: "telephony",
|
|
label: providerUser.name,
|
|
externalAccountId: providerUser.id,
|
|
externalAccountEmail: providerUser.email,
|
|
scopes: [AIRCALL_OAUTH_SCOPE],
|
|
tokenExpiresAt: null,
|
|
credentials: { accessToken: credentials.accessToken },
|
|
actor,
|
|
});
|
|
connectionId = connection.id;
|
|
await input.context.telephony.activateConnection({
|
|
adminUserId: input.context.adminUserId,
|
|
connectionId: connection.id,
|
|
providerUserId: providerUser.id,
|
|
providerUserEmail: providerUser.email,
|
|
defaultProviderNumberId:
|
|
phoneNumbers.length === 1
|
|
? phoneNumbers[0]!.id
|
|
: providerUser.defaultNumberId,
|
|
webhookRegistrationId: webhook.id,
|
|
webhookTokenHash: createHash("sha256")
|
|
.update(webhook.token, "utf8")
|
|
.digest("hex"),
|
|
phoneNumbers: phoneNumbers.map((number) => ({
|
|
providerNumberId: number.id,
|
|
label: number.label,
|
|
e164: number.e164,
|
|
countryCode: number.countryCode,
|
|
selected: true,
|
|
})),
|
|
actor,
|
|
});
|
|
return { connectionId: connection.id };
|
|
} catch (error) {
|
|
await aircallTelephonyProvider
|
|
.deleteWebhook(credentials, webhook.id)
|
|
.catch(() => undefined);
|
|
if (connectionId) {
|
|
await input.context.connections
|
|
.disconnect({
|
|
connectionId,
|
|
adminUserId: input.context.adminUserId,
|
|
actor: input.context.actor(
|
|
"Unvollständige Aircall-Verbindung zurückrollen"
|
|
),
|
|
revokeProviderCredentials: () => Promise.resolve(),
|
|
})
|
|
.catch(() => undefined);
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function listAdminTelephonyConnectionSettings(
|
|
context: AdminTelephonyOperatorContext
|
|
) {
|
|
return db.adminPhoneConnection.findMany({
|
|
where: { adminUserId: context.adminUserId, archivedAt: null },
|
|
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
|
|
select: {
|
|
id: true,
|
|
connectionId: true,
|
|
providerUserId: true,
|
|
providerUserEmail: true,
|
|
defaultPhoneNumberId: true,
|
|
webhookVerifiedAt: true,
|
|
lastEventAt: true,
|
|
connection: {
|
|
select: {
|
|
label: true,
|
|
status: true,
|
|
healthMessageKey: true,
|
|
webhookRegistrationId: true,
|
|
},
|
|
},
|
|
phoneNumbers: {
|
|
where: { archivedAt: null },
|
|
orderBy: [{ label: "asc" }, { id: "asc" }],
|
|
select: {
|
|
id: true,
|
|
label: true,
|
|
e164: true,
|
|
selected: true,
|
|
},
|
|
},
|
|
},
|
|
});
|
|
}
|