Files
cal.diy/packages/features/calAIPhone/providers/retellAI/services
d4bff9d6b1 feat: Cal.ai Self Serve #2 (#22995)
* feat: Cal.ai Self Serve #2

* chore: fix import and remove logs

* fix: update checkout session

* fix: type errors and test

* fix: imports

* fix: type err

* fix: type error

* fix: tests

* chore: save progress

* fix: workflow flow

* fix: workflow update bug

* tests: add unit tests for retell ai webhoo

* fix: status code

* fix: test and delete bug

* fix: add dynamic variables

* fix: type err

* chore: update unit test

* fix: type error

* chore: update default prompt

* fix: type errors

* fix: workflow permissions

* fix: workflow page

* fix: translations

* feat: add call duration

* chore: add booking uid

* fix: button positioning

* chore: update tests

* chore: improvements

* chore: some more improvements

* refactor: improvements

* refactor: code feedback

* refactor: improvements

* feat: enable credits for orgs (#23077)

* Show credits UI for orgs

* fix stripe callback url when buying credits

* give orgs 20% credits

* add test for calulating credits

---------

Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>

* fix: types

* fix: types

* chore: error

* fix: type error

* fix: type error

* chore: mock env

* feat: add idempotency key to prevent double charging

* chore: add userId and teamId

* fix: skip inbound calls

* chore: update tests

* feat: add feature flag for voice agent

* feat: finish test call and other improvements

* chore: add alert

* chore: update .env.example

* chore: improvements

* fix: update tests

* refactor: remove un necessary

* feat: add setup badge

* chore: improvements

* fix: use referene id

* chore: improvements

* fix: type error

* fix: type

* refactor: change pricing logic

* refactor: update tests

* fix: conflicts

* fix: billing link for orgs

* fix: types

* refactor: move feature flag up

* fix: alert and test call credit check

* fix: update unit tests

* fix: feedback

* refactor: improvements

* refactor: move handlers to separate files

* fix: types

* fix: missing import

* fix: type

* refactor: change general tools functions handling

* refactor: use repository

* refactor: improvements

* fix: types

* fix: type errorr

* fix: auth check

* feat: add creditFor

* fix: update defualt prompt

* fix: throw error on frontend

* fix: update unit tests

* fix: use deleteAllWorkflowReminders

* refactor: add connect phone number

* refactor: improvements

* chore: translation

* chore: update message

* chore: translation

* design improvements buy number dialog

* add translation for error message

* use translation key in error message

* refactor: improve connect phone number tab

* feat: support un saved workflow to tests

* chore: remove un used

* fix: remove un used

* fix: remove un used

* refactor: similify billing

---------

Co-authored-by: Carina Wollendorfer <[email protected]>
Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Keith Williams <[email protected]>
2025-08-29 05:04:05 +01:00
..
…

RetellAI Services Architecture

This directory contains the refactored RetellAI services that follow the Single Responsibility Principle (SRP) to fix the previous GOD CLASS violation.

Architecture Overview

BEFORE: Single RetellAIService class (849 lines) handling all responsibilities AFTER: Focused services composed together (~150 lines each)

Services

1. AIConfigurationService

Responsibility: LLM and Agent configuration management

  • setupAIConfiguration() - Create LLM and Agent
  • deleteAIConfiguration() - Clean up AI resources
  • updateLLMConfiguration() - Update LLM settings
  • getLLMDetails() - Retrieve LLM information

2. AgentService

Responsibility: Agent CRUD operations

  • createAgent() - Create new agents
  • updateAgent() - Update agent properties
  • deleteAgent() - Remove agents
  • listAgents() - Get agent lists
  • getAgentWithDetails() - Get detailed agent info

3. BillingService

Responsibility: Stripe payments and subscriptions

  • generatePhoneNumberCheckoutSession() - Create Stripe checkout
  • cancelPhoneNumberSubscription() - Cancel subscriptions

4. CallService

Responsibility: Phone call operations

  • createPhoneCall() - Initiate calls
  • createTestCall() - Create test calls with credit validation

5. PhoneNumberService

Responsibility: Phone number management with transaction integrity

  • importPhoneNumber() - Import with compensating transactions
  • deletePhoneNumber() - Remove phone numbers
  • updatePhoneNumberWithAgents() - Assign agents
  • Includes billing leak protection and compensation failure handling

Usage Examples

Direct Service Usage (Advanced)

import {
  AIConfigurationService,
  AgentService,
  BillingService,
  CallService,
  PhoneNumberService
} from './services';

// Initialize dependencies
const repository = new RetellSDKClient({ apiKey: 'your-key' });
const agentRepository = new PrismaAgentRepositoryAdapter();
const phoneNumberRepository = new PrismaPhoneNumberRepositoryAdapter();
const transactionManager = new PrismaTransactionAdapter();

// Use individual services
const aiConfigService = new AIConfigurationService(repository);
const agentService = new AgentService(repository, agentRepository);
const billingService = new BillingService(phoneNumberRepository, repository);

// Setup AI configuration
const { llmId, agentId } = await aiConfigService.setupAIConfiguration({
  calApiKey: 'cal_live_123...',
  timeZone: 'America/New_York',
  eventTypeId: 12345,
});

// Create agent
const agent = await agentService.createAgent({
  name: 'Support Agent',
  userId: 1,
  userTimeZone: 'America/New_York',
  setupAIConfiguration: () => aiConfigService.setupAIConfiguration({...})
});
import { RetellAIService } from "../RetellAIService";

// Initialize main service
const service = new RetellAIService(repository, agentRepository, phoneNumberRepository, transactionManager);

// Use composed interface - same as before but internally organized
const { llmId, agentId } = await service.setupAIConfiguration({
  calApiKey: "cal_live_123...",
  timeZone: "America/New_York",
});

const phoneNumber = await service.importPhoneNumber({
  phone_number: "+1234567890",
  termination_uri: "https://example.com/webhook",
  userId: 1,
  agentId: "agent-123",
});

Benefits

✅ Single Responsibility - Each service has one clear purpose
✅ Easier Testing - Test services in isolation with focused mocks
✅ Better Maintainability - Changes to billing don't affect phone operations
✅ Reusability - Compose services differently for different use cases
✅ Code Navigation - ~150 lines per service vs 849 lines
✅ Backward Compatibility - Existing code continues to work

Testing

Each service can be tested independently:

// Test individual service
const aiConfigService = new AIConfigurationService(mockRepository);
await aiConfigService.setupAIConfiguration(config);

// Test main service with all composed services
const service = new RetellAIService(mockRepository, mockAgentRepo, mockPhoneRepo, mockTransaction);

Migration Guide

For new code: Use RetellAIService or individual services for specific needs For existing code: No changes needed - RetellAIService maintains same API

The refactoring eliminates the GOD CLASS antipattern while preserving all functionality and improving code organization.