import { createAdminConnectionsService, createPrismaAdminConnectionsRepository, } from "@hivegrid/db/admin-connections.server"; import type { DbClient } from "@hivegrid/db/client.server"; import { claimAdminOutboundCallRequests, settleAdminOutboundCallRequest, } from "@hivegrid/db/admin-telephony-actions.server"; import { aircallTelephonyProvider } from "./aircall/adapter.js"; import { AircallError, type AircallCredentials } from "./aircall/types.js"; export type AdminOutboundCallProvider = { readonly triggerOutboundCall: ( credentials: AircallCredentials, input: { userId: string; numberId: string; to: string } ) => Promise<{ accepted: true }>; }; export async function processAdminOutboundCallRequests(input: { readonly db: DbClient; readonly take?: number; readonly provider?: AdminOutboundCallProvider; }): Promise<{ claimed: number; accepted: number; failed: number }> { const requests = await claimAdminOutboundCallRequests( input.db, input.take ?? 25 ); const provider = input.provider ?? aircallTelephonyProvider; const connections = createAdminConnectionsService({ repository: createPrismaAdminConnectionsRepository(input.db), authorize: () => undefined, permission: "admin_sales.integrations.manage", }); let accepted = 0; let failed = 0; for (const request of requests) { try { const phoneConnection = await input.db.adminPhoneConnection.findFirst({ where: { id: request.phoneConnectionId, adminUserId: request.adminUserId, archivedAt: null, providerUserId: { not: null }, defaultPhoneNumberId: { not: null }, connection: { provider: "aircall", capability: "telephony", status: { in: ["active", "degraded"] }, archivedAt: null, }, }, select: { connectionId: true, providerUserId: true, defaultPhoneNumber: { select: { providerNumberId: true, selected: true, archivedAt: true }, }, }, }); if ( !phoneConnection?.providerUserId || !phoneConnection.defaultPhoneNumber?.selected || phoneConnection.defaultPhoneNumber.archivedAt ) { throw new AdminOutboundCallProcessingError( "phone_connection_incomplete" ); } await connections.withCredentials( phoneConnection.connectionId, request.adminUserId, async (raw) => { await provider.triggerOutboundCall( credentialBundle(raw), { userId: phoneConnection.providerUserId!, numberId: phoneConnection.defaultPhoneNumber!.providerNumberId, to: request.destinationE164, } ); } ); await settleAdminOutboundCallRequest(input.db, { id: request.id, result: { status: "accepted" }, }); accepted += 1; } catch (error) { await settleAdminOutboundCallRequest(input.db, { id: request.id, result: { status: "failed", errorCode: outboundErrorCode(error), }, }); failed += 1; } } return { claimed: requests.length, accepted, failed }; } function credentialBundle( value: Readonly> ): AircallCredentials { if (typeof value.accessToken !== "string" || !value.accessToken.trim()) { throw new AdminOutboundCallProcessingError("credential_invalid"); } return { accessToken: value.accessToken }; } function outboundErrorCode(error: unknown): string { if (error instanceof AdminOutboundCallProcessingError) return error.code; if (error instanceof AircallError) return `aircall_${error.code}`; return "provider_request_failed"; } class AdminOutboundCallProcessingError extends Error { constructor(readonly code: string) { super(code); this.name = "AdminOutboundCallProcessingError"; } }