fix: break circular dependency by passing creditCheckFn in messageDispatcher (#25343)

* fix: break circular dependency in messageDispatcher via dependency injection

Break the 4-file circular dependency chain:
credit-service → reminderScheduler → smsReminderManager → messageDispatcher → credit-service

Solution:
- Add optional creditCheckFn parameter to messageDispatcher functions
- Thread creditCheckFn through the call chain: scheduleWorkflowReminders → scheduleSMSReminder/scheduleWhatsappReminder → messageDispatcher
- When creditCheckFn is provided, use it; otherwise fall back to dynamic CreditService import for backward compatibility
- This breaks the workflows → billing import while preserving immediate fallback behavior

Changes:
- messageDispatcher: Accept optional creditCheckFn parameter, use it if provided
- smsReminderManager: Thread creditCheckFn through scheduleSMSReminder
- whatsappReminderManager: Thread creditCheckFn through scheduleWhatsappReminder
- reminderScheduler: Add creditCheckFn to ScheduleWorkflowRemindersArgs and pass through processWorkflowStep

All type checks, lint checks, and unit tests pass.

Co-Authored-By: [email protected] <[email protected]>

* feat: wire creditCheckFn from all callers to complete circular dependency fix

- Add creditCheckFn parameter to WorkflowService.scheduleFormWorkflows
- Wire creditCheckFn from all 10 entry points that call workflow scheduling:
  * formSubmissionUtils.ts (form submissions)
  * roundRobinManualReassignment.ts (round-robin reassignment)
  * triggerFormSubmittedNoEventWorkflow.ts (form workflow trigger)
  * handleBookingRequested.ts (booking requests)
  * RegularBookingService.ts (2 calls - payment initiated & new bookings)
  * handleSeats.ts (seated bookings)
  * handleConfirmation.ts (2 calls - confirmation & payment)
  * handleMarkNoShow.ts (no-show updates)
  * confirm.handler.ts (booking rejection)
- Update test expectations to use expect.objectContaining()
- Fix pre-existing lint warning in handleMarkNoShow.ts (any type)
- This completes the messageDispatcher circular dependency fix by ensuring
  creditCheckFn is actually passed through the call chain, breaking the
  4-file circular dependency at runtime

Co-Authored-By: [email protected] <[email protected]>

* fix: use generic type with type guard in logFailedResults to fix type check error

- Replace constrained type with generic type parameter
- Add proper type guard for rejected promises
- Fixes CI type check failure in handleMarkNoShow.ts:385
- Avoids 'any' type while accepting any fulfilled value shape

Co-Authored-By: [email protected] <[email protected]>

* wip

* wip

* wip

* revert

* revert

* feat: wire creditCheckFn from all remaining callers to eliminate fallbacks

- Wire creditCheckFn in packages/sms/sms-manager.ts (can safely import CreditService)
- Create makeHandler factory pattern for CRON endpoints (scheduleSMSReminders.ts, scheduleWhatsappReminders.ts)
- Wire creditCheckFn from apps/web CRON routes to factories
- Add warning log in messageDispatcher when fallback is used
- Complete creditCheckFn wiring from all direct callers (activateEventType.handler.ts, util.ts)

This eliminates all fallbacks to dynamic import except as a safety net for unforeseen call sites.
The circular dependency (workflows ↔ billing) remains acceptable as discussed with user (Option C).

Co-Authored-By: [email protected] <[email protected]>

* test: update formSubmissionUtils tests to expect creditCheckFn parameter

The scheduleFormWorkflows function now receives creditCheckFn as a parameter.
Updated test assertions to use expect.objectContaining() with creditCheckFn: expect.any(Function)
to account for the new dependency injection parameter.

Co-Authored-By: [email protected] <[email protected]>

* test: update sms-manager test to expect creditCheckFn parameter

The sendSmsOrFallbackEmail function now receives creditCheckFn as a parameter.
Updated test assertion to use expect.objectContaining() with creditCheckFn: expect.any(Function)
to account for the new dependency injection parameter. Also removed teamId: undefined
assertion as the key may be omitted entirely from the actual call.

Co-Authored-By: [email protected] <[email protected]>

* feat: make creditCheckFn required to fully break circular dependency

This commit completes the circular dependency fix by making creditCheckFn
required throughout the call chain, eliminating the dynamic import fallback
entirely.

Changes:
- Make creditCheckFn required in messageDispatcher functions (sendSmsOrFallbackEmail, scheduleSmsOrFallbackEmail)
- Remove dynamic import fallback and warning log from messageDispatcher
- Make creditCheckFn required in ScheduleTextReminderArgs (smsReminderManager)
- Make creditCheckFn required in processWorkflowStep and ScheduleWorkflowRemindersArgs (reminderScheduler)
- Add creditCheckFn to SendCancelledRemindersArgs and wire from handleCancelBooking

The circular dependency is now fully broken - no more dynamic imports of
CreditService from within the workflows package. All callers must explicitly
provide creditCheckFn via dependency injection.

Co-Authored-By: [email protected] <[email protected]>

* fix: make creditCheckFn required in WorkflowService.scheduleFormWorkflows

This commit fixes the CI type check error by making creditCheckFn required
in WorkflowService.scheduleFormWorkflows. Previously, creditCheckFn was
optional in scheduleFormWorkflows but required in scheduleWorkflowReminders,
causing a type mismatch.

Changes:
- Make creditCheckFn required in scheduleFormWorkflows signature
- Update WorkflowService.test.ts to pass mock creditCheckFn in all test cases
- Add responseId and routedEventTypeId to test calls for completeness

All callers of scheduleFormWorkflows already pass creditCheckFn, so this
change is safe and completes the circular dependency fix.

Co-Authored-By: [email protected] <[email protected]>

* remove

* fix

* refactor

* refactor

* refactor

* wip

* fix

* fix

* rm

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
Benny JooandDevin AI authored and GitHub committed 2025-11-27 16:31:26 +09:00
1 parent 1ab4b9dfab
commit d9cddd85ff
24 files changed
+247 -109

No files matched your search

@@ -7,6 +7,7 @@ import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventR
import { handleConfirmation } from "@calcom/features/bookings/lib/handleConfirmation";
import { handleWebhookTrigger } from "@calcom/features/bookings/lib/handleWebhookTrigger";
import { processPaymentRefund } from "@calcom/features/bookings/lib/payment/processPaymentRefund";
import { CreditService } from "@calcom/features/ee/billing/credit-service";
import { getBookerBaseUrl } from "@calcom/features/ee/organizations/lib/getBookerUrlServer";
import { workflowSelect } from "@calcom/features/ee/workflows/lib/getAllWorkflows";
import { WorkflowService } from "@calcom/features/ee/workflows/lib/service/WorkflowService";
@@ -394,6 +395,8 @@ export const confirmHandler = async ({ ctx, input }: ConfirmOptions) => {
const workflows = await getAllWorkflowsFromEventType(booking.eventType, user.id);
try {
const creditService = new CreditService();
await WorkflowService.scheduleWorkflowsFilteredByTriggerEvent({
workflows,
smsReminderNumber: booking.smsReminderNumber,
@@ -407,6 +410,7 @@ export const confirmHandler = async ({ ctx, input }: ConfirmOptions) => {
},
hideBranding: !!booking.eventType?.owner?.hideBranding,
triggers: [WorkflowTriggerEvents.BOOKING_REJECTED],
creditCheckFn: creditService.hasAvailableCredits.bind(creditService),
});
} catch (error) {
// Silently fail
@@ -1,3 +1,4 @@
import { CreditService } from "@calcom/features/ee/billing/credit-service";
import { getBookerBaseUrl } from "@calcom/features/ee/organizations/lib/getBookerUrlServer";
import { scheduleEmailReminder } from "@calcom/features/ee/workflows/lib/reminders/emailReminderManager";
import { scheduleSMSReminder } from "@calcom/features/ee/workflows/lib/reminders/smsReminderManager";
@@ -314,6 +315,8 @@ export const activateEventTypeHandler = async ({ ctx, input }: ActivateEventType
const bookerUrl = await getBookerBaseUrl(ctx.user.organizationId ?? null);
const creditService = new CreditService();
for (const booking of bookingsForReminders) {
// eventTypeId is technically nullable but we know it will be there
const bookingEventType = activeOnEventTypes.get(booking.eventTypeId!);
@@ -419,6 +422,7 @@ export const activateEventTypeHandler = async ({ ctx, input }: ActivateEventType
userId: booking.userId,
teamId: eventTypeWorkflow.teamId,
verifiedAt: step.verifiedAt,
creditCheckFn: creditService.hasAvailableCredits.bind(creditService),
});
} else if (step.action === WorkflowActions.WHATSAPP_NUMBER && step.sendTo) {
await scheduleWhatsappReminder({
@@ -436,6 +440,7 @@ export const activateEventTypeHandler = async ({ ctx, input }: ActivateEventType
userId: booking.userId,
teamId: eventTypeWorkflow.teamId,
verifiedAt: step.verifiedAt,
creditCheckFn: creditService.hasAvailableCredits.bind(creditService),
});
} else if (booking.smsReminderNumber) {
if (step.action === WorkflowActions.SMS_ATTENDEE) {
@@ -455,6 +460,7 @@ export const activateEventTypeHandler = async ({ ctx, input }: ActivateEventType
userId: booking.userId,
teamId: eventTypeWorkflow.teamId,
verifiedAt: step.verifiedAt,
creditCheckFn: creditService.hasAvailableCredits.bind(creditService),
});
} else if (step.action === WorkflowActions.WHATSAPP_ATTENDEE) {
await scheduleWhatsappReminder({
@@ -473,6 +479,7 @@ export const activateEventTypeHandler = async ({ ctx, input }: ActivateEventType
userId: booking.userId,
teamId: eventTypeWorkflow.teamId,
verifiedAt: step.verifiedAt,
creditCheckFn: creditService.hasAvailableCredits.bind(creditService),
});
}
}
@@ -15,6 +15,7 @@ import {
getAIAgentCallPhoneNumberField,
getAIAgentCallPhoneNumberSource,
} from "@calcom/features/bookings/lib/getBookingFields";
import { CreditService } from "@calcom/features/ee/billing/credit-service";
import { getBookerBaseUrl } from "@calcom/features/ee/organizations/lib/getBookerUrlServer";
import { WorkflowRepository } from "@calcom/features/ee/workflows/repositories/WorkflowRepository";
import { removeBookingField, upsertBookingField } from "@calcom/features/eventtypes/lib/bookingFieldsManager";
@@ -738,6 +739,8 @@ export async function scheduleBookingReminders(
const bookerUrl = await getBookerBaseUrl(isOrg ? teamId : null);
const creditService = new CreditService();
//create reminders for all bookings for each workflow step
const promiseSteps = workflowSteps.map(async (step) => {
const promiseScheduleReminders = bookings.map(async (booking) => {
@@ -841,6 +844,7 @@ export async function scheduleBookingReminders(
userId: userId,
teamId: teamId,
verifiedAt: step?.verifiedAt ?? null,
creditCheckFn: creditService.hasAvailableCredits.bind(creditService),
});
} else if (step.action === WorkflowActions.WHATSAPP_NUMBER && step.sendTo) {
await scheduleWhatsappReminder({
@@ -858,6 +862,7 @@ export async function scheduleBookingReminders(
userId: userId,
teamId: teamId,
verifiedAt: step?.verifiedAt ?? null,
creditCheckFn: creditService.hasAvailableCredits.bind(creditService),
});
} else if (booking.smsReminderNumber) {
if (step.action === WorkflowActions.SMS_ATTENDEE) {
@@ -877,6 +882,7 @@ export async function scheduleBookingReminders(
userId: userId,
teamId: teamId,
verifiedAt: step?.verifiedAt ?? null,
creditCheckFn: creditService.hasAvailableCredits.bind(creditService),
});
} else if (step.action === WorkflowActions.WHATSAPP_ATTENDEE) {
await scheduleWhatsappReminder({
@@ -895,6 +901,7 @@ export async function scheduleBookingReminders(
userId: userId,
teamId: teamId,
verifiedAt: step?.verifiedAt ?? null,
creditCheckFn: creditService.hasAvailableCredits.bind(creditService),
});
}
} else if (step.action === WorkflowActions.CAL_AI_PHONE_CALL) {