refactor: move handleNotificationWhenNoSlots from trpc to features/slots (#25538)

Move handleNotificationWhenNoSlots.ts and its test file from
packages/trpc/server/routers/viewer/slots/ to packages/features/slots/
to resolve circular dependency issue where packages/features imports
from packages/trpc.

This file is not TRPC-specific and belongs in the features package.

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-12-08 10:54:21 +02:00
1 parent e10c4c1cb5
commit 584f5581fa
6 files changed
+7 -7

No files matched your search

@@ -2,7 +2,7 @@ import { DI_TOKENS } from "@calcom/features/di/tokens";
import { redisModule } from "@calcom/features/redis/di/redisModule";
import { membershipRepositoryModule } from "@calcom/features/users/di/MembershipRepository.module";
import { prismaModule } from "@calcom/features/di/modules/Prisma";
import type { NoSlotsNotificationService } from "@calcom/trpc/server/routers/viewer/slots/handleNotificationWhenNoSlots";
import type { NoSlotsNotificationService } from "@calcom/features/slots/handleNotificationWhenNoSlots";
import { createContainer } from "../di";
import { noSlotsNotificationModule } from "../modules/NoSlotsNotification";
@@ -1,5 +1,5 @@
import type { INoSlotsNotificationService } from "@calcom/trpc/server/routers/viewer/slots/handleNotificationWhenNoSlots";
import { NoSlotsNotificationService } from "@calcom/trpc/server/routers/viewer/slots/handleNotificationWhenNoSlots";
import type { INoSlotsNotificationService } from "@calcom/features/slots/handleNotificationWhenNoSlots";
import { NoSlotsNotificationService } from "@calcom/features/slots/handleNotificationWhenNoSlots";
import { createModule } from "../di";
import { DI_TOKENS } from "../tokens";
@@ -0,0 +1,487 @@
import i18nMock from "../../../tests/libs/__mocks__/libServerI18n";
import prismaMock from "../../../tests/libs/__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().mockImplementation(() => ({
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: "[email protected]",
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: "[email protected]",
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: "[email protected]",
},
})
);
});
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: "[email protected]",
locale: "en",
},
},
{
user: {
email: "[email protected]",
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: "[email protected]",
},
})
);
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).toHaveBeenCalledWith(
expect.objectContaining({
to: {
email: "[email protected]",
},
})
);
});
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: "[email protected]",
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: "[email protected]",
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");
});
});
@@ -0,0 +1,121 @@
import type { Dayjs } from "@calcom/dayjs";
import { sendOrganizationAdminNoSlotsNotification } from "@calcom/emails/organization-email-service";
import type { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
import type { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import type { IRedisService } from "@calcom/features/redis/IRedisService";
import { IS_PRODUCTION, WEBAPP_URL } from "@calcom/lib/constants";
import { getTranslation } from "@calcom/lib/server/i18n";
type EventDetails = {
username: string;
eventSlug: string;
startTime: Dayjs;
endTime: Dayjs;
visitorTimezone?: string;
visitorUid?: string;
};
// Incase any updates are made - lets version the key so we can invalidate
const REDIS_KEY_VERSION = "V1";
// 7 days or 60s in dev
const NO_SLOTS_NOTIFICATION_FREQUENCY = IS_PRODUCTION ? 7 * 24 * 3600 : 60;
const NO_SLOTS_COUNT_FOR_NOTIFICATION = 2;
const constructRedisKey = (eventDetails: EventDetails, orgSlug?: string, teamId?: number) => {
return `${REDIS_KEY_VERSION}.${eventDetails.username}:${eventDetails.eventSlug}${
orgSlug ? `@${orgSlug}:team_${teamId}` : ""
}`;
};
const constructDataHash = (eventDetails: EventDetails) => {
const obj = {
st: eventDetails.startTime.format("YYYY-MM-DD"),
vTz: eventDetails?.visitorTimezone,
vUuid: eventDetails?.visitorUid,
};
return JSON.stringify(obj);
};
export interface INoSlotsNotificationService {
teamRepo: TeamRepository;
membershipRepo: MembershipRepository;
redisClient: IRedisService;
}
export class NoSlotsNotificationService {
constructor(public readonly dependencies: INoSlotsNotificationService) {}
async handleNotificationWhenNoSlots({
eventDetails,
orgDetails,
teamId,
}: {
eventDetails: EventDetails;
orgDetails: { currentOrgDomain: string | null };
teamId?: number;
}) {
// Check for org
if (!orgDetails.currentOrgDomain || !teamId) return;
const UPSTASH_ENV_FOUND = process.env.UPSTASH_REDIS_REST_TOKEN && process.env.UPSTASH_REDIS_REST_URL;
if (!UPSTASH_ENV_FOUND) return;
// Check org has this setting enabled
const orgSettings = await this.dependencies.teamRepo.findOrganizationSettingsBySlug({
slug: orgDetails.currentOrgDomain,
});
if (!orgSettings?.organizationSettings?.adminGetsNoSlotsNotification) return;
const usersUniqueKey = constructRedisKey(eventDetails, orgDetails.currentOrgDomain, teamId);
// Get only the required amount of data so the request is as small as possible
// We may need to get more data and check the startDate occurrence of this
// Not trigger email if the start months are the same
const usersExistingNoSlots =
(await this.dependencies.redisClient.lrange(usersUniqueKey, 0, NO_SLOTS_COUNT_FOR_NOTIFICATION - 1)) ??
[];
await this.dependencies.redisClient.lpush(usersUniqueKey, constructDataHash(eventDetails));
if (!usersExistingNoSlots.length) {
await this.dependencies.redisClient.expire(usersUniqueKey, NO_SLOTS_NOTIFICATION_FREQUENCY);
}
// We add one as we know we just added one to the list - saves us re-fetching the data
if (usersExistingNoSlots.length + 1 === NO_SLOTS_COUNT_FOR_NOTIFICATION) {
// Get all team admins to send the email too
const foundAdmins = await this.dependencies.membershipRepo.findTeamAdminsByTeamId({
teamId,
});
const teamSlug = await this.dependencies.teamRepo.findTeamSlugById({
id: teamId,
});
// TODO: use new tasker as we dont want this blocking loading slots (Just out of scope for this PR)
// Tasker isn't 100% working with emails - will refactor after i have made changes to Tasker in another PR.
const emailsToSend: Array<Promise<void>> = [];
// const tasker = getTasker();
for (const admin of foundAdmins) {
const translation = await getTranslation(admin.user.locale ?? "en", "common");
const payload = {
language: translation,
to: {
email: admin.user.email,
},
user: eventDetails.username,
slug: eventDetails.eventSlug,
startTime: eventDetails.startTime.format("YYYY-MM-DD"),
endTime: eventDetails.endTime.format("YYYY-MM-DD"),
// For now navigate here - when impersonation via parameter has been pushed we will impersonate and then navigate to availability
editLink: `${WEBAPP_URL}/availability?type=team`,
teamSlug: teamSlug?.slug ?? "",
};
emailsToSend.push(sendOrganizationAdminNoSlotsNotification(payload));
}
await Promise.all(emailsToSend);
}
}
}