Files
calendar/packages/features/slots/handleNotificationWhenNoSlots.test.ts
T
Benny JooGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
f5d345b133 refactor: remove @calcom/web imports from @calcom/features and add @calcom/testing package (#26480)
* fix: remove @calcom/web imports from packages/features to eliminate circular dependency

- Migrate UserTableUser and MemberPermissions types to packages/features/users/types/user-table.ts
- Migrate useGeo hook to packages/features/geo/GeoContext.tsx
- Migrate buildLegacyRequest to packages/lib/buildLegacyCtx.ts
- Migrate Calendar component to packages/features/calendars/weeklyview/components/
- Move test utilities (bookingScenario, fixtures) to packages/features/test/
- Update all imports in packages/features to use new locations
- Add re-exports in apps/web for backward compatibility

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: delete original implementation files and fix type issues

- Delete original calendar component files in apps/web (keep only re-export stubs)
- Migrate OutOfOfficeInSlots to packages/features/bookings/components
- Convert apps/web OutOfOfficeInSlots to re-export stub
- Fix className vs class issue in Calendar.tsx
- Fix @calcom/trpc import violation in user-table.ts by using structural type

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: add missing isGroup and contains fields to UserTableUser attributes type

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: update customRole type to match actual Prisma Role model

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix build

* fix

* fix

* cleanup weeklyview

* fix

* refactor to mv MemberPermissions to types package

* add types dependency to features

* fix

* fix

* fix

* fix

* fix

* fix

* rename

* rename

* migrate

* migrate

* migrate

* fix

* fix

* fix

* refactor: move test utilities from packages/features/test to tests/libs

- Move bookingScenario utilities to tests/libs/bookingScenario
- Move fixtures to tests/libs/fixtures
- Update all imports in packages/features test files to use new location
- Update all imports in apps/web test files to use new location
- Eliminates duplication of test utilities between packages/features and apps/web

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: correct relative import paths for tests/libs in test files

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* refactor: replace test utility implementations with re-exports to tests/libs

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: fix test import paths and move signup handler tests to apps/web

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: move buildLegacyCtx to packages/lib and restore handlers to packages/features

- Move buildLegacyCtx from apps/web/lib to packages/lib to break circular dependency
- Update apps/web/lib/buildLegacyCtx.ts to re-export from @calcom/lib
- Restore signup handlers and tests to packages/features/auth/signup/handlers
- Update handler imports to use @calcom/lib/buildLegacyCtx instead of @calcom/web/lib/buildLegacyCtx

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: update recurring-event.test.ts imports to use tests/libs path

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* refactor: delete test re-export files and update imports to use tests/libs directly

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: update remaining test imports to use tests/libs directly

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: update handleRecurringEventBooking calls to match function signature (1 arg)

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* remove

* migrate tests

* migrate tests

* refactor: update test mock imports by removing  and using async  for mock creators.

* fix type errors

* fix: add type assertion for MockUser in p2002.test-suite.ts

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: restore locale import in compareReminderBodyToTemplate.test.ts using relative path

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* feat: create @calcom/testing package and migrate tests from /tests directory

- Created new @calcom/testing package in /packages/testing
- Moved all files from /tests to /packages/testing
- Updated all imports across the codebase to use @calcom/testing alias
- Removed /tests directory at root level

This allows other packages like @calcom/features and @calcom/web to import
testing utilities using the @calcom/testing alias instead of relative paths.

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix

* fix

* fix: add missing useBookings export to @calcom/atoms package

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: add missing useCalendarsBusyTimes and useConnectedCalendars exports to @calcom/atoms

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* chore: add @calcom/testing as explicit devDependency to packages that use it

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* refactor: move setupVitest.ts into @calcom/testing package

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix

* chore: add biome rules to restrict @calcom/testing imports

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix

* rename libs to lib

* rename libs to lib

* add rule

* add rule

* refactor: remove @calcom/features imports from @calcom/testing

- Move mockPaymentSuccessWebhookFromStripe to fresh-booking.test.ts
- Replace ProfileRepository.generateProfileUid() with uuidv4()
- Clone Tracking type into @calcom/testing/src/lib/types.ts
- Update imports in expects.ts and getMockRequestDataForBooking.ts
- Move source files into src/ folder
- Move CalendarManager mock to @calcom/features

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: add explicit exports for nested paths in @calcom/testing

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* improve

* improve

* fix

* fix

* fix type checks

* fix type checks

* fix type checks

* fix tests

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-01-08 16:59:11 +09:00

490 lines
14 KiB
TypeScript

import i18nMock from "@calcom/testing/lib/__mocks__/libServerI18n";
import prismaMock from "@calcom/testing/lib/__mocks__/prismaMock";
import { vi, describe, it, beforeAll, afterAll, expect, beforeEach, afterEach } from "vitest";
import dayjs from "@calcom/dayjs";
import * as CalcomEmails from "@calcom/emails/organization-email-service";
import { getNoSlotsNotificationService } from "@calcom/features/di/containers/NoSlotsNotification";
import { RedisService } from "@calcom/features/redis/RedisService";
vi.mock("@calcom/features/redis/RedisService", () => {
const mockedRedis = vi.fn();
mockedRedis.prototype.lrange = vi.fn();
mockedRedis.prototype.lpush = vi.fn();
mockedRedis.prototype.expire = vi.fn();
return {
RedisService: mockedRedis,
};
});
vi.mock("@calcom/features/flags/features.repository", () => ({
FeaturesRepository: vi.fn(function () {
return {
checkIfFeatureIsEnabledGlobally: vi.fn().mockResolvedValue(false),
};
}),
}));
vi.spyOn(CalcomEmails, "sendOrganizationAdminNoSlotsNotification");
describe("(Orgs) Send admin notifications when a user has no availability", () => {
beforeAll(() => {
// Setup env vars
vi.stubEnv("UPSTASH_REDIS_REST_TOKEN", "mocked_token");
vi.stubEnv("UPSTASH_REDIS_REST_URL", "mocked_url");
});
beforeEach(() => {
// Setup mocks
prismaMock.membership.findMany.mockResolvedValue([
{
user: {
email: "test@test.com",
locale: "en",
},
},
]);
i18nMock.getTranslation.mockImplementation(() => {
return new Promise((resolve) => {
const identityFn = (key: string) => key;
// @ts-expect-error Target allows only 1 element(s) but source may have more.
resolve(identityFn);
});
});
});
afterEach(() => {
vi.resetAllMocks();
});
afterAll(() => {
vi.unstubAllEnvs();
});
it("Should send a notification after 2 times if the org has them enabled", async () => {
const redisService = new RedisService();
const mocked = vi.mocked(redisService);
prismaMock.team.findFirst.mockResolvedValue({
organizationSettings: {
adminGetsNoSlotsNotification: true,
},
});
// Define event and organization details
const eventDetails = {
username: "user1",
eventSlug: "event1",
startTime: dayjs(), // Mocking Dayjs format function
endTime: dayjs().add(1, "hour"),
};
const orgDetails = {
currentOrgDomain: "org1",
isValidOrgDomain: true,
};
// Call the function with teamId
const service = getNoSlotsNotificationService();
await service.handleNotificationWhenNoSlots({ eventDetails, orgDetails, teamId: 123 });
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).not.toHaveBeenCalled();
// Mock length to be one then recall to trigger email
mocked.lrange.mockResolvedValueOnce([""]);
const service2 = getNoSlotsNotificationService();
await service2.handleNotificationWhenNoSlots({ eventDetails, orgDetails, teamId: 123 });
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).toHaveBeenCalled();
});
it("Should not send a notification if the org has them disabled", async () => {
prismaMock.team.findFirst.mockResolvedValueOnce({
organizationSettings: {
adminGetsNoSlotsNotification: false,
},
});
// Define event and organization details
const eventDetails = {
username: "user1",
eventSlug: "event1",
startTime: dayjs(), // Mocking Dayjs format function
endTime: dayjs().add(1, "hour"),
};
const orgDetails = {
currentOrgDomain: "org1",
isValidOrgDomain: true,
};
const service = getNoSlotsNotificationService();
await service.handleNotificationWhenNoSlots({ eventDetails, orgDetails, teamId: 123 });
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).not.toHaveBeenCalled();
});
it("Should only send notifications to admins of the specified teamId", async () => {
const redisService = new RedisService();
const mocked = vi.mocked(redisService);
prismaMock.team.findFirst.mockResolvedValue({
organizationSettings: {
adminGetsNoSlotsNotification: true,
},
});
// Mock finding team members
prismaMock.membership.findMany.mockResolvedValue([
{
user: {
email: "correctteam@test.com",
locale: "en",
},
},
]);
const eventDetails = {
username: "user1",
eventSlug: "event1",
startTime: dayjs(),
endTime: dayjs().add(1, "hour"),
};
const orgDetails = {
currentOrgDomain: "org1",
isValidOrgDomain: true,
};
// Mock Redis to simulate second no-slots occurrence
mocked.lrange.mockResolvedValueOnce([""]); // This will trigger email sending
// Call with specific teamId
const service = getNoSlotsNotificationService();
await service.handleNotificationWhenNoSlots({
eventDetails,
orgDetails,
teamId: 123, // specific teamId
});
// Verify that membership query included correct teamId
expect(prismaMock.membership.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({
team: expect.objectContaining({
id: 123,
}),
}),
})
);
// Verify email was sent only once (to the one correct team member)
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).toHaveBeenCalledTimes(1);
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).toHaveBeenCalledWith(
expect.objectContaining({
to: {
email: "correctteam@test.com",
},
})
);
});
it("Should not send notifications when no teamId is provided", async () => {
const redisService = new RedisService();
const mocked = vi.mocked(redisService);
prismaMock.team.findFirst.mockResolvedValue({
organizationSettings: {
adminGetsNoSlotsNotification: true,
},
});
const eventDetails = {
username: "user1",
eventSlug: "event1",
startTime: dayjs(),
endTime: dayjs().add(1, "hour"),
};
const orgDetails = {
currentOrgDomain: "org1",
isValidOrgDomain: true,
};
mocked.lrange.mockResolvedValueOnce([""]);
const service = getNoSlotsNotificationService();
await service.handleNotificationWhenNoSlots({
eventDetails,
orgDetails,
// teamId intentionally omitted
});
expect(prismaMock.membership.findMany).not.toHaveBeenCalled();
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).not.toHaveBeenCalled();
});
it("Should not send notifications when no orgDomain is provided", async () => {
const redisService = new RedisService();
const mocked = vi.mocked(redisService);
const eventDetails = {
username: "user1",
eventSlug: "event1",
startTime: dayjs(),
endTime: dayjs().add(1, "hour"),
};
const orgDetails = {
currentOrgDomain: null, // No org domain
isValidOrgDomain: true,
};
mocked.lrange.mockResolvedValueOnce([""]);
const service = getNoSlotsNotificationService();
await service.handleNotificationWhenNoSlots({
eventDetails,
orgDetails,
teamId: 123,
});
expect(prismaMock.team.findFirst).not.toHaveBeenCalled();
expect(prismaMock.membership.findMany).not.toHaveBeenCalled();
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).not.toHaveBeenCalled();
});
it("Should not send notifications when Redis environment variables are not set", async () => {
// Temporarily unset Redis env vars
const originalToken = process.env.UPSTASH_REDIS_REST_TOKEN;
const originalUrl = process.env.UPSTASH_REDIS_REST_URL;
delete process.env.UPSTASH_REDIS_REST_TOKEN;
delete process.env.UPSTASH_REDIS_REST_URL;
const eventDetails = {
username: "user1",
eventSlug: "event1",
startTime: dayjs(),
endTime: dayjs().add(1, "hour"),
};
const orgDetails = {
currentOrgDomain: "org1",
isValidOrgDomain: true,
};
const service = getNoSlotsNotificationService();
await service.handleNotificationWhenNoSlots({
eventDetails,
orgDetails,
teamId: 123,
});
expect(prismaMock.team.findFirst).not.toHaveBeenCalled();
expect(prismaMock.membership.findMany).not.toHaveBeenCalled();
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).not.toHaveBeenCalled();
// Restore env vars
process.env.UPSTASH_REDIS_REST_TOKEN = originalToken;
process.env.UPSTASH_REDIS_REST_URL = originalUrl;
});
it("Should handle multiple admins correctly", async () => {
const redisService = new RedisService();
const mocked = vi.mocked(redisService);
prismaMock.team.findFirst.mockResolvedValue({
organizationSettings: {
adminGetsNoSlotsNotification: true,
},
});
// Mock multiple team admins
prismaMock.membership.findMany.mockResolvedValue([
{
user: {
email: "admin1@test.com",
locale: "en",
},
},
{
user: {
email: "admin2@test.com",
locale: "fr",
},
},
]);
const eventDetails = {
username: "user1",
eventSlug: "event1",
startTime: dayjs(),
endTime: dayjs().add(1, "hour"),
};
const orgDetails = {
currentOrgDomain: "org1",
isValidOrgDomain: true,
};
mocked.lrange.mockResolvedValueOnce([""]);
const service = getNoSlotsNotificationService();
await service.handleNotificationWhenNoSlots({
eventDetails,
orgDetails,
teamId: 123,
});
// Verify emails were sent to both admins
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).toHaveBeenCalledTimes(2);
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).toHaveBeenCalledWith(
expect.objectContaining({
to: {
email: "admin1@test.com",
},
})
);
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).toHaveBeenCalledWith(
expect.objectContaining({
to: {
email: "admin2@test.com",
},
})
);
});
it("Should not send duplicate notifications within NO_SLOTS_NOTIFICATION_FREQUENCY", async () => {
const redisService = new RedisService();
const mocked = vi.mocked(redisService);
prismaMock.team.findFirst.mockResolvedValue({
organizationSettings: {
adminGetsNoSlotsNotification: true,
},
});
prismaMock.membership.findMany.mockResolvedValue([
{
user: {
email: "admin@test.com",
locale: "en",
},
},
]);
const eventDetails = {
username: "user1",
eventSlug: "event1",
startTime: dayjs(),
endTime: dayjs().add(1, "hour"),
};
const orgDetails = {
currentOrgDomain: "org1",
isValidOrgDomain: true,
};
// First notification cycle - simulate having one previous occurrence
mocked.lrange.mockResolvedValueOnce([""]); // One previous occurrence
const service = getNoSlotsNotificationService();
await service.handleNotificationWhenNoSlots({
eventDetails,
orgDetails,
teamId: 123,
});
// Verify first notification was sent
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).toHaveBeenCalledTimes(1);
// Reset call counts
vi.clearAllMocks();
// For the second attempt, simulate having TWO occurrences already in Redis
// This better simulates the real Redis state after the first notification
mocked.lrange.mockResolvedValueOnce(["", ""]); // Two occurrences now
const service2 = getNoSlotsNotificationService();
await service2.handleNotificationWhenNoSlots({
eventDetails,
orgDetails,
teamId: 123,
});
// Verify no additional notifications were sent
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).not.toHaveBeenCalled();
// Verify Redis operations
expect(mocked.lpush).toHaveBeenCalledTimes(1); // Still records the occurrence
});
it("Should maintain separate notification frequencies for different event types", async () => {
const redisService = new RedisService();
const mocked = vi.mocked(redisService);
prismaMock.team.findFirst.mockResolvedValue({
organizationSettings: {
adminGetsNoSlotsNotification: true,
},
});
prismaMock.membership.findMany.mockResolvedValue([
{
user: {
email: "admin@test.com",
locale: "en",
},
},
]);
const baseEventDetails = {
username: "user1",
startTime: dayjs(),
endTime: dayjs().add(1, "hour"),
};
const orgDetails = {
currentOrgDomain: "org1",
isValidOrgDomain: true,
};
// First event type notification
mocked.lrange.mockResolvedValueOnce([""]); // Simulate one previous occurrence for first event
const service = getNoSlotsNotificationService();
await service.handleNotificationWhenNoSlots({
eventDetails: { ...baseEventDetails, eventSlug: "event1" },
orgDetails,
teamId: 123,
});
// Verify first notification was sent
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).toHaveBeenCalledTimes(1);
// Reset only the email mock, keep Redis mocks
vi.mocked(CalcomEmails.sendOrganizationAdminNoSlotsNotification).mockClear();
// For the second event type, also simulate one previous occurrence
// This needs to be a separate mock since it's a different key in Redis
mocked.lrange.mockResolvedValueOnce([""]); // Simulate one previous occurrence for second event
const service2 = getNoSlotsNotificationService();
await service2.handleNotificationWhenNoSlots({
eventDetails: { ...baseEventDetails, eventSlug: "event2" },
orgDetails,
teamId: 123,
});
// Verify second notification was sent (different event type)
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).toHaveBeenCalledTimes(1);
// Get all lpush calls
const lpushCalls = mocked.lpush.mock.calls;
expect(lpushCalls.length).toBe(2);
// Extract the Redis keys used for each event
const firstEventKey = lpushCalls[0][0];
const secondEventKey = lpushCalls[1][0];
// Verify different keys were used
expect(firstEventKey).not.toBe(secondEventKey);
expect(firstEventKey).toContain("event1");
expect(secondEventKey).toContain("event2");
});
});