* 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>
258 lines
7.7 KiB
TypeScript
258 lines
7.7 KiB
TypeScript
import type { TFunction } from "i18next";
|
|
import { describe, expect, test, vi, beforeEach } from "vitest";
|
|
|
|
import { sendSmsOrFallbackEmail } from "@calcom/features/ee/workflows/lib/reminders/messageDispatcher";
|
|
import { checkSMSRateLimit } from "@calcom/lib/smsLockState";
|
|
import prisma from "@calcom/prisma";
|
|
import type { CalendarEvent, Person } from "@calcom/types/Calendar";
|
|
|
|
import SMSManager from "../sms-manager";
|
|
|
|
vi.mock("@calcom/lib/smsLockState");
|
|
vi.mock("@calcom/features/ee/workflows/lib/reminders/messageDispatcher");
|
|
vi.mock("@calcom/prisma", () => ({
|
|
default: {
|
|
team: {
|
|
findUnique: vi.fn(),
|
|
},
|
|
},
|
|
}));
|
|
|
|
interface TestAttendee extends Person {
|
|
name: string;
|
|
email: string;
|
|
phoneNumber?: string;
|
|
timeZone: string;
|
|
language: {
|
|
translate: TFunction;
|
|
locale: string;
|
|
};
|
|
}
|
|
|
|
interface TestCalEvent extends CalendarEvent {
|
|
uid: string;
|
|
type: string;
|
|
title: string;
|
|
startTime: string;
|
|
endTime: string;
|
|
attendees: TestAttendee[];
|
|
organizer: {
|
|
id: number;
|
|
name: string;
|
|
email: string;
|
|
timeZone: string;
|
|
language: {
|
|
translate: TFunction;
|
|
locale: string;
|
|
};
|
|
};
|
|
team?: {
|
|
id: number;
|
|
name: string;
|
|
members: unknown[];
|
|
};
|
|
}
|
|
|
|
// Create a concrete implementation of SMSManager for testing
|
|
class TestSMSManager extends SMSManager {
|
|
getMessage(attendee: TestAttendee): string {
|
|
return `Test message for ${attendee.name}`;
|
|
}
|
|
}
|
|
|
|
describe("SMSManager", () => {
|
|
const mockTranslate = ((key: string) => key) as TFunction;
|
|
const mockCalEvent: TestCalEvent = {
|
|
uid: "test-booking-uid",
|
|
type: "test",
|
|
title: "Test Event",
|
|
startTime: "2024-03-20T10:00:00Z",
|
|
endTime: "2024-03-20T11:00:00Z",
|
|
attendees: [
|
|
{
|
|
name: "John Doe",
|
|
email: "[email protected]",
|
|
phoneNumber: "+1234567890",
|
|
timeZone: "America/New_York",
|
|
language: { translate: mockTranslate, locale: "en" },
|
|
},
|
|
{
|
|
name: "Jane Smith",
|
|
email: "[email protected]",
|
|
phoneNumber: "+1987654321",
|
|
timeZone: "America/New_York",
|
|
language: { translate: mockTranslate, locale: "en" },
|
|
},
|
|
],
|
|
organizer: {
|
|
id: 1,
|
|
name: "Organizer",
|
|
email: "[email protected]",
|
|
timeZone: "America/New_York",
|
|
language: { translate: mockTranslate, locale: "en" },
|
|
},
|
|
};
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
});
|
|
|
|
describe("sendSMSToAttendee", () => {
|
|
test("should not send SMS if phone number is missing", async () => {
|
|
const smsManager = new TestSMSManager(mockCalEvent);
|
|
const attendeeWithoutPhone: TestAttendee = {
|
|
...mockCalEvent.attendees[0],
|
|
phoneNumber: undefined,
|
|
timeZone: "America/New_York",
|
|
language: { translate: mockTranslate, locale: "en" },
|
|
};
|
|
|
|
await smsManager.sendSMSToAttendee(attendeeWithoutPhone);
|
|
|
|
expect(sendSmsOrFallbackEmail).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("should not send SMS if email is not @sms.cal.com", async () => {
|
|
const smsManager = new TestSMSManager(mockCalEvent);
|
|
const attendeeWithRegularEmail: TestAttendee = {
|
|
...mockCalEvent.attendees[0],
|
|
email: "[email protected]",
|
|
phoneNumber: "+1234567890",
|
|
timeZone: "America/New_York",
|
|
language: { translate: mockTranslate, locale: "en" },
|
|
};
|
|
|
|
await smsManager.sendSMSToAttendee(attendeeWithRegularEmail);
|
|
|
|
expect(sendSmsOrFallbackEmail).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("should send SMS only when both phone number and @sms.cal.com email are present", async () => {
|
|
const smsManager = new TestSMSManager(mockCalEvent);
|
|
const mockSmsResponse = { success: true };
|
|
|
|
(sendSmsOrFallbackEmail as jest.Mock).mockResolvedValue(mockSmsResponse);
|
|
(checkSMSRateLimit as jest.Mock).mockResolvedValue(undefined);
|
|
|
|
const result = await smsManager.sendSMSToAttendee(mockCalEvent.attendees[0], "test-booking-uid");
|
|
|
|
expect(checkSMSRateLimit).toHaveBeenCalledWith({
|
|
identifier: "handleSendingSMS:user:1",
|
|
rateLimitingType: "sms",
|
|
});
|
|
|
|
expect(sendSmsOrFallbackEmail).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
twilioData: expect.objectContaining({
|
|
phoneNumber: mockCalEvent.attendees[0].phoneNumber,
|
|
body: expect.stringContaining(mockCalEvent.attendees[0].name),
|
|
sender: expect.any(String),
|
|
userId: 1,
|
|
bookingUid: "test-booking-uid",
|
|
}),
|
|
creditCheckFn: expect.any(Function),
|
|
})
|
|
);
|
|
|
|
expect(result).toEqual(mockSmsResponse);
|
|
});
|
|
|
|
test("should not send SMS if SMS notifications are disabled for team", async () => {
|
|
const mockTeamId = 123;
|
|
const mockTeam = {
|
|
id: mockTeamId,
|
|
name: "Test Team",
|
|
members: [],
|
|
};
|
|
const smsManager = new TestSMSManager({
|
|
...mockCalEvent,
|
|
team: mockTeam,
|
|
});
|
|
|
|
// Mock team settings to disable SMS
|
|
(prisma.team.findUnique as jest.Mock).mockResolvedValue({
|
|
parent: {
|
|
isOrganization: true,
|
|
organizationSettings: {
|
|
disablePhoneOnlySMSNotifications: true,
|
|
},
|
|
},
|
|
});
|
|
|
|
await smsManager.sendSMSToAttendee(mockCalEvent.attendees[0]);
|
|
|
|
expect(sendSmsOrFallbackEmail).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("should handle SMS sending errors", async () => {
|
|
const smsManager = new TestSMSManager(mockCalEvent);
|
|
const mockError = new Error("SMS sending failed");
|
|
|
|
(sendSmsOrFallbackEmail as jest.Mock).mockRejectedValue(mockError);
|
|
(checkSMSRateLimit as jest.Mock).mockResolvedValue(undefined);
|
|
|
|
await expect(smsManager.sendSMSToAttendee(mockCalEvent.attendees[0])).rejects.toThrow(mockError);
|
|
});
|
|
});
|
|
|
|
describe("sendSMSToAttendees", () => {
|
|
test("should send SMS only to attendees with phone number and @sms.cal.com email", async () => {
|
|
const smsManager = new TestSMSManager(mockCalEvent);
|
|
const mockSmsResponse = { success: true };
|
|
|
|
(sendSmsOrFallbackEmail as jest.Mock).mockResolvedValue(mockSmsResponse);
|
|
(checkSMSRateLimit as jest.Mock).mockResolvedValue(undefined);
|
|
|
|
await smsManager.sendSMSToAttendees();
|
|
|
|
// Only one attendee has both phone number and @sms.cal.com email
|
|
expect(sendSmsOrFallbackEmail).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
test("should not send SMS if notifications are disabled", async () => {
|
|
const mockTeamId = 123;
|
|
const mockTeam = {
|
|
id: mockTeamId,
|
|
name: "Test Team",
|
|
members: [],
|
|
};
|
|
const smsManager = new TestSMSManager({
|
|
...mockCalEvent,
|
|
team: mockTeam,
|
|
});
|
|
|
|
(prisma.team.findUnique as jest.Mock).mockResolvedValue({
|
|
parent: {
|
|
isOrganization: true,
|
|
organizationSettings: {
|
|
disablePhoneOnlySMSNotifications: true,
|
|
},
|
|
},
|
|
});
|
|
|
|
await smsManager.sendSMSToAttendees();
|
|
|
|
expect(sendSmsOrFallbackEmail).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
describe("getFormattedTime and getFormattedDate", () => {
|
|
test("should format time correctly", () => {
|
|
const smsManager = new TestSMSManager(mockCalEvent);
|
|
const formattedTime = smsManager.getFormattedTime("America/New_York", "en", "2024-03-20T10:00:00Z");
|
|
|
|
expect(formattedTime).toContain("2024");
|
|
expect(formattedTime).toContain("6:00am");
|
|
});
|
|
|
|
test("should format date range correctly", () => {
|
|
const smsManager = new TestSMSManager(mockCalEvent);
|
|
const formattedDate = smsManager.getFormattedDate("America/New_York", "en");
|
|
|
|
expect(formattedDate).toContain("2024");
|
|
expect(formattedDate).toContain("6:00am");
|
|
expect(formattedDate).toContain("7:00am");
|
|
});
|
|
});
|
|
});
|