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:
1 parent
1ab4b9dfab
commit
d9cddd85ff
24 files changed
+247
-109
No files matched your search
@@ -5,6 +5,7 @@ import { NextResponse } from "next/server";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { bulkShortenLinks } from "@calcom/ee/workflows/lib/reminders/utils";
|
||||
import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";
|
||||
import { CreditService } from "@calcom/features/ee/billing/credit-service";
|
||||
import { getBookerBaseUrl } from "@calcom/features/ee/organizations/lib/getBookerUrlServer";
|
||||
import { isAttendeeAction } from "@calcom/features/ee/workflows/lib/actionHelperFunctions";
|
||||
import { scheduleSmsOrFallbackEmail } from "@calcom/features/ee/workflows/lib/reminders/messageDispatcher";
|
||||
@@ -173,6 +174,8 @@ export async function handler(req: NextRequest) {
|
||||
if (message?.length && message?.length > 0 && sendTo) {
|
||||
const smsMessageWithoutOptOut = await WorkflowOptOutService.addOptOutMessage(message, locale || "en");
|
||||
|
||||
const creditService = new CreditService();
|
||||
|
||||
const scheduledNotification = await scheduleSmsOrFallbackEmail({
|
||||
twilioData: {
|
||||
phoneNumber: sendTo,
|
||||
@@ -193,6 +196,7 @@ export async function handler(req: NextRequest) {
|
||||
workflowStepId: reminder.workflowStep.id,
|
||||
}
|
||||
: undefined,
|
||||
creditCheckFn: creditService.hasAvailableCredits.bind(creditService),
|
||||
});
|
||||
|
||||
if (scheduledNotification) {
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { CreditService } from "@calcom/features/ee/billing/credit-service";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
|
||||
import prisma from "@calcom/prisma";
|
||||
@@ -102,6 +103,8 @@ export async function handler(req: NextRequest) {
|
||||
);
|
||||
|
||||
if (message?.length && message?.length > 0 && sendTo) {
|
||||
const creditService = new CreditService();
|
||||
|
||||
const scheduledNotification = await scheduleSmsOrFallbackEmail({
|
||||
twilioData: {
|
||||
phoneNumber: sendTo,
|
||||
@@ -124,6 +127,7 @@ export async function handler(req: NextRequest) {
|
||||
workflowStepId: reminder.workflowStep.id,
|
||||
}
|
||||
: undefined,
|
||||
creditCheckFn: creditService.hasAvailableCredits.bind(creditService),
|
||||
});
|
||||
|
||||
if (scheduledNotification) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import type { CreditCheckFn } from "@calcom/features/ee/billing/credit-service";
|
||||
import { sendOrScheduleWorkflowEmails } from "@calcom/features/ee/workflows/lib/reminders/providers/emailProvider";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import prisma from "@calcom/prisma";
|
||||
@@ -27,13 +28,11 @@ export async function sendSmsOrFallbackEmail(props: {
|
||||
t: TFunction;
|
||||
replyTo: string;
|
||||
};
|
||||
creditCheckFn: CreditCheckFn;
|
||||
}) {
|
||||
const { userId, teamId } = props.twilioData;
|
||||
const { CreditService } = await import("@calcom/features/ee/billing/credit-service");
|
||||
|
||||
const creditService = new CreditService();
|
||||
|
||||
const hasCredits = await creditService.hasAvailableCredits({ userId, teamId });
|
||||
const hasCredits = await props.creditCheckFn({ userId, teamId });
|
||||
|
||||
if (!hasCredits) {
|
||||
const { fallbackData, twilioData } = props;
|
||||
@@ -75,12 +74,11 @@ export async function scheduleSmsOrFallbackEmail(props: {
|
||||
replyTo: string;
|
||||
workflowStepId?: number;
|
||||
};
|
||||
creditCheckFn: CreditCheckFn;
|
||||
}) {
|
||||
const { userId, teamId } = props.twilioData;
|
||||
const { CreditService } = await import("@calcom/features/ee/billing/credit-service");
|
||||
const creditService = new CreditService();
|
||||
|
||||
const hasCredits = await creditService.hasAvailableCredits({ userId, teamId });
|
||||
const hasCredits = await props.creditCheckFn({ userId, teamId });
|
||||
|
||||
if (!hasCredits) {
|
||||
const { fallbackData, twilioData } = props;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { FORM_SUBMITTED_WEBHOOK_RESPONSES } from "@calcom/app-store/routing-forms/lib/formSubmissionUtils";
|
||||
import type { CreditCheckFn } from "@calcom/features/ee/billing/credit-service";
|
||||
import {
|
||||
isAttendeeAction,
|
||||
isSMSAction,
|
||||
@@ -72,6 +73,7 @@ type ProcessWorkflowStepParams = (
|
||||
export type ScheduleWorkflowRemindersArgs = ProcessWorkflowStepParams & {
|
||||
workflows: Workflow[];
|
||||
isDryRun?: boolean;
|
||||
creditCheckFn: CreditCheckFn;
|
||||
};
|
||||
|
||||
const processWorkflowStep = async (
|
||||
@@ -84,7 +86,8 @@ const processWorkflowStep = async (
|
||||
hideBranding,
|
||||
seatReferenceUid,
|
||||
formData,
|
||||
}: ProcessWorkflowStepParams
|
||||
}: ProcessWorkflowStepParams,
|
||||
creditCheckFn: CreditCheckFn
|
||||
) => {
|
||||
if (!step?.verifiedAt) return;
|
||||
|
||||
@@ -114,6 +117,7 @@ const processWorkflowStep = async (
|
||||
teamId: workflow.teamId,
|
||||
seatReferenceUid,
|
||||
verifiedAt: step.verifiedAt,
|
||||
creditCheckFn,
|
||||
};
|
||||
|
||||
if (isSMSAction(step.action)) {
|
||||
@@ -243,6 +247,7 @@ const _scheduleWorkflowReminders = async (args: ScheduleWorkflowRemindersArgs) =
|
||||
seatReferenceUid,
|
||||
isDryRun = false,
|
||||
formData,
|
||||
creditCheckFn,
|
||||
} = args;
|
||||
if (isDryRun || !workflows.length) return;
|
||||
|
||||
@@ -250,13 +255,18 @@ const _scheduleWorkflowReminders = async (args: ScheduleWorkflowRemindersArgs) =
|
||||
if (workflow.steps.length === 0) continue;
|
||||
|
||||
for (const step of workflow.steps) {
|
||||
await processWorkflowStep(workflow, step, {
|
||||
emailAttendeeSendToOverride,
|
||||
smsReminderNumber,
|
||||
hideBranding,
|
||||
seatReferenceUid,
|
||||
...(evt ? { calendarEvent: evt } : { formData }),
|
||||
});
|
||||
await processWorkflowStep(
|
||||
workflow,
|
||||
step,
|
||||
{
|
||||
emailAttendeeSendToOverride,
|
||||
smsReminderNumber,
|
||||
hideBranding,
|
||||
seatReferenceUid,
|
||||
...(evt ? { calendarEvent: evt } : { formData }),
|
||||
},
|
||||
creditCheckFn
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -266,10 +276,11 @@ export interface SendCancelledRemindersArgs {
|
||||
smsReminderNumber: string | null;
|
||||
evt: ExtendedCalendarEvent;
|
||||
hideBranding?: boolean;
|
||||
creditCheckFn: CreditCheckFn;
|
||||
}
|
||||
|
||||
const _sendCancelledReminders = async (args: SendCancelledRemindersArgs) => {
|
||||
const { smsReminderNumber, evt, workflows, hideBranding } = args;
|
||||
const { smsReminderNumber, evt, workflows, hideBranding, creditCheckFn } = args;
|
||||
|
||||
if (!workflows.length) return;
|
||||
|
||||
@@ -277,11 +288,16 @@ const _sendCancelledReminders = async (args: SendCancelledRemindersArgs) => {
|
||||
if (workflow.trigger !== WorkflowTriggerEvents.EVENT_CANCELLED) continue;
|
||||
|
||||
for (const step of workflow.steps) {
|
||||
await processWorkflowStep(workflow, step, {
|
||||
smsReminderNumber,
|
||||
hideBranding,
|
||||
calendarEvent: evt,
|
||||
});
|
||||
await processWorkflowStep(
|
||||
workflow,
|
||||
step,
|
||||
{
|
||||
smsReminderNumber,
|
||||
hideBranding,
|
||||
calendarEvent: evt,
|
||||
},
|
||||
creditCheckFn
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
getSMSMessageWithVariables,
|
||||
shouldUseTwilio,
|
||||
} from "@calcom/ee/workflows/lib/reminders/utils";
|
||||
import type { CreditCheckFn } from "@calcom/features/ee/billing/credit-service";
|
||||
import { getSubmitterEmail } from "@calcom/features/tasker/tasks/triggerFormSubmittedNoEvent/formSubmissionValidation";
|
||||
import { SENDER_ID } from "@calcom/lib/constants";
|
||||
import logger from "@calcom/lib/logger";
|
||||
@@ -89,6 +90,7 @@ export type ScheduleTextReminderArgs = ScheduleReminderArgs & {
|
||||
isVerificationPending?: boolean;
|
||||
prisma?: PrismaClient;
|
||||
verifiedAt: Date | null;
|
||||
creditCheckFn: CreditCheckFn;
|
||||
};
|
||||
|
||||
export type ScheduleTextReminderArgsWithRequiredFields = Omit<
|
||||
@@ -173,6 +175,7 @@ const scheduleSMSReminderForEvt = async (
|
||||
userId,
|
||||
teamId,
|
||||
seatReferenceUid,
|
||||
creditCheckFn,
|
||||
} = args;
|
||||
|
||||
const { startTime, endTime } = evt;
|
||||
@@ -243,6 +246,7 @@ const scheduleSMSReminderForEvt = async (
|
||||
replyTo: evt.organizer.email,
|
||||
}
|
||||
: undefined,
|
||||
creditCheckFn,
|
||||
});
|
||||
} catch (error) {
|
||||
log.error(`Error sending SMS with error ${error}`);
|
||||
@@ -274,6 +278,7 @@ const scheduleSMSReminderForEvt = async (
|
||||
workflowStepId,
|
||||
}
|
||||
: undefined,
|
||||
creditCheckFn,
|
||||
});
|
||||
|
||||
if (scheduledNotification?.sid) {
|
||||
@@ -318,7 +323,8 @@ const scheduleSMSReminderForForm = async (
|
||||
formData: FormSubmissionData;
|
||||
}
|
||||
) => {
|
||||
const { message, triggerEvent, reminderPhone, sender, userId, teamId, action, formData } = args;
|
||||
const { message, triggerEvent, reminderPhone, sender, userId, teamId, action, formData, creditCheckFn } =
|
||||
args;
|
||||
|
||||
let smsMessage = message;
|
||||
|
||||
@@ -362,6 +368,7 @@ const scheduleSMSReminderForForm = async (
|
||||
replyTo: formData.user.email,
|
||||
}
|
||||
: undefined,
|
||||
creditCheckFn,
|
||||
});
|
||||
} catch (error) {
|
||||
log.error(`Error sending SMS with error ${error}`);
|
||||
|
||||
@@ -41,6 +41,7 @@ export const scheduleWhatsappReminder = async (args: ScheduleTextReminderArgs &
|
||||
isVerificationPending = false,
|
||||
seatReferenceUid,
|
||||
verifiedAt,
|
||||
creditCheckFn,
|
||||
} = args;
|
||||
|
||||
if (!verifiedAt) {
|
||||
@@ -194,11 +195,12 @@ export const scheduleWhatsappReminder = async (args: ScheduleTextReminderArgs &
|
||||
replyTo: evt.organizer.email,
|
||||
}
|
||||
: undefined,
|
||||
creditCheckFn,
|
||||
});
|
||||
} catch (error) {
|
||||
console.log(`Error sending WHATSAPP with error ${error}`);
|
||||
}
|
||||
} else if (
|
||||
}else if (
|
||||
(triggerEvent === WorkflowTriggerEvents.BEFORE_EVENT ||
|
||||
triggerEvent === WorkflowTriggerEvents.AFTER_EVENT) &&
|
||||
scheduledDate
|
||||
@@ -230,6 +232,7 @@ export const scheduleWhatsappReminder = async (args: ScheduleTextReminderArgs &
|
||||
workflowStepId,
|
||||
}
|
||||
: undefined,
|
||||
creditCheckFn,
|
||||
});
|
||||
|
||||
if (scheduledNotification?.sid) {
|
||||
|
||||
@@ -76,10 +76,15 @@ describe("WorkflowService.scheduleFormWorkflows", () => {
|
||||
},
|
||||
];
|
||||
|
||||
const mockCreditCheckFn = vi.fn().mockResolvedValue(true);
|
||||
|
||||
await WorkflowService.scheduleFormWorkflows({
|
||||
workflows,
|
||||
responses: mockResponses,
|
||||
form: mockForm,
|
||||
responseId: 123,
|
||||
routedEventTypeId: null,
|
||||
creditCheckFn: mockCreditCheckFn,
|
||||
});
|
||||
|
||||
expect(mockScheduleWorkflowReminders).toHaveBeenCalledWith({
|
||||
@@ -87,9 +92,11 @@ describe("WorkflowService.scheduleFormWorkflows", () => {
|
||||
formData: {
|
||||
responses: mockResponses,
|
||||
user: { email: "[email protected]", timeFormat: 12, locale: "en" },
|
||||
routedEventTypeId: null,
|
||||
},
|
||||
hideBranding: false,
|
||||
workflows: [workflows[0]],
|
||||
creditCheckFn: mockCreditCheckFn,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -123,11 +130,15 @@ describe("WorkflowService.scheduleFormWorkflows", () => {
|
||||
|
||||
mockTasker.create.mockResolvedValue({ id: "task-123" });
|
||||
|
||||
const mockCreditCheckFn = vi.fn().mockResolvedValue(true);
|
||||
|
||||
await WorkflowService.scheduleFormWorkflows({
|
||||
workflows,
|
||||
responses: mockResponses,
|
||||
responseId: 123,
|
||||
form: mockForm,
|
||||
routedEventTypeId: null,
|
||||
creditCheckFn: mockCreditCheckFn,
|
||||
});
|
||||
|
||||
expect(mockTasker.create).toHaveBeenCalledWith(
|
||||
@@ -137,6 +148,7 @@ describe("WorkflowService.scheduleFormWorkflows", () => {
|
||||
responses: mockResponses,
|
||||
smsReminderNumber: "+1234567890",
|
||||
hideBranding: false,
|
||||
routedEventTypeId: null,
|
||||
submittedAt: expect.any(Date),
|
||||
form: {
|
||||
id: "form-123",
|
||||
@@ -190,10 +202,15 @@ describe("WorkflowService.scheduleFormWorkflows", () => {
|
||||
},
|
||||
];
|
||||
|
||||
const mockCreditCheckFn = vi.fn().mockResolvedValue(true);
|
||||
|
||||
await WorkflowService.scheduleFormWorkflows({
|
||||
workflows,
|
||||
responses: mockResponses,
|
||||
form: formWithoutPhone,
|
||||
responseId: 123,
|
||||
routedEventTypeId: null,
|
||||
creditCheckFn: mockCreditCheckFn,
|
||||
});
|
||||
|
||||
expect(mockScheduleWorkflowReminders).toHaveBeenCalledWith({
|
||||
@@ -201,9 +218,11 @@ describe("WorkflowService.scheduleFormWorkflows", () => {
|
||||
formData: {
|
||||
responses: mockResponses,
|
||||
user: { email: "[email protected]", timeFormat: 12, locale: "en" },
|
||||
routedEventTypeId: null,
|
||||
},
|
||||
hideBranding: false,
|
||||
workflows: [workflows[0]],
|
||||
creditCheckFn: mockCreditCheckFn,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,7 @@ import type { ScheduleWorkflowRemindersArgs } from "@calcom/ee/workflows/lib/rem
|
||||
import { scheduleWorkflowReminders } from "@calcom/ee/workflows/lib/reminders/reminderScheduler";
|
||||
import type { timeUnitLowerCase } from "@calcom/ee/workflows/lib/reminders/smsReminderManager";
|
||||
import type { Workflow } from "@calcom/ee/workflows/lib/types";
|
||||
import type { CreditCheckFn } from "@calcom/features/ee/billing/credit-service";
|
||||
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
|
||||
import { WorkflowRepository } from "@calcom/features/ee/workflows/repositories/WorkflowRepository";
|
||||
import { getHideBranding } from "@calcom/features/profile/lib/hideBranding";
|
||||
@@ -87,11 +88,13 @@ export class WorkflowService {
|
||||
form,
|
||||
responseId,
|
||||
routedEventTypeId,
|
||||
creditCheckFn,
|
||||
}: {
|
||||
responseId: number;
|
||||
workflows: Workflow[];
|
||||
responses: FORM_SUBMITTED_WEBHOOK_RESPONSES;
|
||||
routedEventTypeId: number | null;
|
||||
creditCheckFn: CreditCheckFn;
|
||||
form: {
|
||||
id: string;
|
||||
userId: number;
|
||||
@@ -137,6 +140,7 @@ export class WorkflowService {
|
||||
},
|
||||
hideBranding,
|
||||
workflows: workflowsToTrigger,
|
||||
creditCheckFn,
|
||||
});
|
||||
|
||||
const workflowsToSchedule: Workflow[] = [];
|
||||
|
||||
Reference in new issue
Block a user