refactor: convert handleNotificationWhenNoSlots to service class with DI (#23055)
* refactor: convert handleNotificationWhenNoSlots to service class with DI - Convert standalone handleNotificationWhenNoSlots function to NoSlotsNotificationService class - Add INoSlotsNotificationService interface following existing patterns - Create NoSlotsNotification DI module and add to container - Add NO_SLOTS_NOTIFICATION_SERVICE tokens to DI_TOKENS - Inject service into AvailableSlotsService dependencies - Update AvailableSlotsService to use injected service instead of direct function call - Update all test cases to use service class pattern - Follows existing DI patterns used by other services like BusyTimesService and CheckBookingLimitsService Co-Authored-By: [email protected] <[email protected]> * refactor: move Prisma calls to repositories and create dedicated DI container - Add findOrganizationSettingsBySlug and findTeamSlugById methods to TeamRepository - Add findTeamAdminsByTeamId method to MembershipRepository - Create MembershipRepository DI module and tokens - Update NoSlotsNotificationService to inject TeamRepository, MembershipRepository, and Redis client - Create dedicated DI container for NoSlotsNotificationService - Update AvailableSlots DI container to include MembershipRepository - Replace direct Prisma and Redis calls with repository methods and injected client - Update tests to use DI container instead of direct service instantiation - Fix Redis interface import path Co-Authored-By: [email protected] <[email protected]> * chore: DI noSlotsNotification service * chore: bump library --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: [email protected] <[email protected]> Co-authored-by: Morgan <[email protected]>
This commit is contained in:
19 files changed
+256
-122
No files matched your search
@@ -6,8 +6,7 @@ import { vi, describe, it, beforeAll, afterAll, expect, beforeEach, afterEach }
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import * as CalcomEmails from "@calcom/emails";
|
||||
import { RedisService } from "@calcom/features/redis/RedisService";
|
||||
|
||||
import { handleNotificationWhenNoSlots } from "./handleNotificationWhenNoSlots";
|
||||
import { getNoSlotsNotificationService } from "@calcom/lib/di/containers/NoSlotsNotification";
|
||||
|
||||
vi.mock("@calcom/features/redis/RedisService", () => {
|
||||
const mockedRedis = vi.fn();
|
||||
@@ -84,14 +83,16 @@ describe("(Orgs) Send admin notifications when a user has no availability", () =
|
||||
};
|
||||
|
||||
// Call the function with teamId
|
||||
await handleNotificationWhenNoSlots({ eventDetails, orgDetails, teamId: 123 });
|
||||
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([""]);
|
||||
|
||||
await handleNotificationWhenNoSlots({ eventDetails, orgDetails, teamId: 123 });
|
||||
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 () => {
|
||||
@@ -113,7 +114,8 @@ describe("(Orgs) Send admin notifications when a user has no availability", () =
|
||||
isValidOrgDomain: true,
|
||||
};
|
||||
|
||||
await handleNotificationWhenNoSlots({ eventDetails, orgDetails, teamId: 123 });
|
||||
const service = getNoSlotsNotificationService();
|
||||
await service.handleNotificationWhenNoSlots({ eventDetails, orgDetails, teamId: 123 });
|
||||
|
||||
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -153,7 +155,8 @@ describe("(Orgs) Send admin notifications when a user has no availability", () =
|
||||
mocked.lrange.mockResolvedValueOnce([""]); // This will trigger email sending
|
||||
|
||||
// Call with specific teamId
|
||||
await handleNotificationWhenNoSlots({
|
||||
const service = getNoSlotsNotificationService();
|
||||
await service.handleNotificationWhenNoSlots({
|
||||
eventDetails,
|
||||
orgDetails,
|
||||
teamId: 123, // specific teamId
|
||||
@@ -205,7 +208,8 @@ describe("(Orgs) Send admin notifications when a user has no availability", () =
|
||||
|
||||
mocked.lrange.mockResolvedValueOnce([""]);
|
||||
|
||||
await handleNotificationWhenNoSlots({
|
||||
const service = getNoSlotsNotificationService();
|
||||
await service.handleNotificationWhenNoSlots({
|
||||
eventDetails,
|
||||
orgDetails,
|
||||
// teamId intentionally omitted
|
||||
@@ -233,7 +237,8 @@ describe("(Orgs) Send admin notifications when a user has no availability", () =
|
||||
|
||||
mocked.lrange.mockResolvedValueOnce([""]);
|
||||
|
||||
await handleNotificationWhenNoSlots({
|
||||
const service = getNoSlotsNotificationService();
|
||||
await service.handleNotificationWhenNoSlots({
|
||||
eventDetails,
|
||||
orgDetails,
|
||||
teamId: 123,
|
||||
@@ -263,7 +268,8 @@ describe("(Orgs) Send admin notifications when a user has no availability", () =
|
||||
isValidOrgDomain: true,
|
||||
};
|
||||
|
||||
await handleNotificationWhenNoSlots({
|
||||
const service = getNoSlotsNotificationService();
|
||||
await service.handleNotificationWhenNoSlots({
|
||||
eventDetails,
|
||||
orgDetails,
|
||||
teamId: 123,
|
||||
@@ -318,7 +324,8 @@ describe("(Orgs) Send admin notifications when a user has no availability", () =
|
||||
|
||||
mocked.lrange.mockResolvedValueOnce([""]);
|
||||
|
||||
await handleNotificationWhenNoSlots({
|
||||
const service = getNoSlotsNotificationService();
|
||||
await service.handleNotificationWhenNoSlots({
|
||||
eventDetails,
|
||||
orgDetails,
|
||||
teamId: 123,
|
||||
@@ -375,7 +382,8 @@ describe("(Orgs) Send admin notifications when a user has no availability", () =
|
||||
|
||||
// First notification cycle - simulate having one previous occurrence
|
||||
mocked.lrange.mockResolvedValueOnce([""]); // One previous occurrence
|
||||
await handleNotificationWhenNoSlots({
|
||||
const service = getNoSlotsNotificationService();
|
||||
await service.handleNotificationWhenNoSlots({
|
||||
eventDetails,
|
||||
orgDetails,
|
||||
teamId: 123,
|
||||
@@ -391,7 +399,8 @@ describe("(Orgs) Send admin notifications when a user has no availability", () =
|
||||
// This better simulates the real Redis state after the first notification
|
||||
mocked.lrange.mockResolvedValueOnce(["", ""]); // Two occurrences now
|
||||
|
||||
await handleNotificationWhenNoSlots({
|
||||
const service2 = getNoSlotsNotificationService();
|
||||
await service2.handleNotificationWhenNoSlots({
|
||||
eventDetails,
|
||||
orgDetails,
|
||||
teamId: 123,
|
||||
@@ -436,7 +445,8 @@ describe("(Orgs) Send admin notifications when a user has no availability", () =
|
||||
|
||||
// First event type notification
|
||||
mocked.lrange.mockResolvedValueOnce([""]); // Simulate one previous occurrence for first event
|
||||
await handleNotificationWhenNoSlots({
|
||||
const service = getNoSlotsNotificationService();
|
||||
await service.handleNotificationWhenNoSlots({
|
||||
eventDetails: { ...baseEventDetails, eventSlug: "event1" },
|
||||
orgDetails,
|
||||
teamId: 123,
|
||||
@@ -451,7 +461,8 @@ describe("(Orgs) Send admin notifications when a user has no availability", () =
|
||||
// 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
|
||||
await handleNotificationWhenNoSlots({
|
||||
const service2 = getNoSlotsNotificationService();
|
||||
await service2.handleNotificationWhenNoSlots({
|
||||
eventDetails: { ...baseEventDetails, eventSlug: "event2" },
|
||||
orgDetails,
|
||||
teamId: 123,
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import type { Dayjs } from "@calcom/dayjs";
|
||||
import { sendOrganizationAdminNoSlotsNotification } from "@calcom/emails";
|
||||
import { RedisService } from "@calcom/features/redis/RedisService";
|
||||
import type { IRedisService } from "@calcom/features/redis/IRedisService";
|
||||
import { IS_PRODUCTION, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { MembershipRepository } from "@calcom/lib/server/repository/membership";
|
||||
import type { TeamRepository } from "@calcom/lib/server/repository/team";
|
||||
|
||||
type EventDetails = {
|
||||
username: string;
|
||||
@@ -38,107 +39,83 @@ const constructDataHash = (eventDetails: EventDetails) => {
|
||||
return JSON.stringify(obj);
|
||||
};
|
||||
|
||||
export const handleNotificationWhenNoSlots = async ({
|
||||
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;
|
||||
export interface INoSlotsNotificationService {
|
||||
teamRepo: TeamRepository;
|
||||
membershipRepo: MembershipRepository;
|
||||
redisClient: IRedisService;
|
||||
}
|
||||
|
||||
// Check org has this setting enabled
|
||||
const orgSettings = await prisma.team.findFirst({
|
||||
where: {
|
||||
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,
|
||||
isOrganization: true,
|
||||
},
|
||||
select: {
|
||||
organizationSettings: {
|
||||
select: {
|
||||
adminGetsNoSlotsNotification: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!orgSettings?.organizationSettings?.adminGetsNoSlotsNotification) return;
|
||||
|
||||
const redis = new RedisService();
|
||||
|
||||
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 redis.lrange(usersUniqueKey, 0, NO_SLOTS_COUNT_FOR_NOTIFICATION - 1)) ?? [];
|
||||
await redis.lpush(usersUniqueKey, constructDataHash(eventDetails));
|
||||
|
||||
if (!usersExistingNoSlots.length) {
|
||||
await redis.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 prisma.membership.findMany({
|
||||
where: {
|
||||
team: {
|
||||
id: teamId,
|
||||
parentId: {
|
||||
not: null,
|
||||
},
|
||||
},
|
||||
role: {
|
||||
in: ["ADMIN", "OWNER"],
|
||||
},
|
||||
},
|
||||
select: {
|
||||
user: {
|
||||
select: {
|
||||
email: true,
|
||||
locale: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const teamSlug = await prisma.team.findUnique({
|
||||
where: {
|
||||
id: teamId,
|
||||
},
|
||||
select: {
|
||||
slug: true,
|
||||
},
|
||||
});
|
||||
// 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");
|
||||
if (!orgSettings?.organizationSettings?.adminGetsNoSlotsNotification) return;
|
||||
|
||||
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 ?? "",
|
||||
};
|
||||
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));
|
||||
|
||||
emailsToSend.push(sendOrganizationAdminNoSlotsNotification(payload));
|
||||
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);
|
||||
}
|
||||
await Promise.all(emailsToSend);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -61,7 +61,7 @@ import type { CredentialForCalendarService } from "@calcom/types/Credential";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import type { TGetScheduleInputSchema } from "./getSchedule.schema";
|
||||
import { handleNotificationWhenNoSlots } from "./handleNotificationWhenNoSlots";
|
||||
import type { NoSlotsNotificationService } from "./handleNotificationWhenNoSlots";
|
||||
import type { GetScheduleOptions } from "./types";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["[slots/util]"] });
|
||||
@@ -108,6 +108,7 @@ export interface IAvailableSlotsService {
|
||||
redisClient: IRedisService;
|
||||
featuresRepo: FeaturesRepository;
|
||||
qualifiedHostsService: QualifiedHostsService;
|
||||
noSlotsNotificationService: NoSlotsNotificationService;
|
||||
}
|
||||
|
||||
function withSlotsCache(
|
||||
@@ -1438,8 +1439,7 @@ export class AvailableSlotsService {
|
||||
// We only want to run this on single targeted events and not dynamic
|
||||
if (!Object.keys(withinBoundsSlotsMappedToDate).length && input.usernameList?.length === 1) {
|
||||
try {
|
||||
// TODO: DI handleNotificationWhenNoSlots
|
||||
await handleNotificationWhenNoSlots({
|
||||
await this.dependencies.noSlotsNotificationService.handleNotificationWhenNoSlots({
|
||||
eventDetails: {
|
||||
username: input.usernameList?.[0],
|
||||
startTime: startTime,
|
||||
|
||||
Reference in new issue
Block a user