feat: orgs trigger alert when loading a calendar and no availability is (#14796)
* Install upstash redis again - base of noficationSender * Setup email handler etc and use tasker * Remove logs * Sending emails and correct format and spacing in emails * Update email styles * Update email styles * add switch to enable feature * fix: reset tasker types - will fix in new PR * WIP: test suite * WIP: test suite * Add redis service and add WIP mock test * Add tests for redis service and fix lpush * More working tests * More working tests * fix: type error + typo * update export to match i18n next mock * (debug) push for debug * Fix: fixed hosting in mocks * Add common.json i18n * add better test descriptions * reset mocks after each test to allow concurancy * Remove redundant RedisService.test.ts * Rename and remove redundant isAdmin check * Rename to .d.ts * Add key versioning to constructRedisKey * Update packages/trpc/server/routers/viewer/slots/handleNotificationWhenNoSlots.ts Co-authored-by: Hariom Balhara <[email protected]> * Update packages/trpc/server/routers/viewer/slots/handleNotificationWhenNoSlots.ts Co-authored-by: Hariom Balhara <[email protected]> * Add try/catch * fix breaking when option === undefined * Add missing await to Promise.all * Rename data stored in redis to save space * Include thrown error in logs --------- Co-authored-by: Hariom Balhara <[email protected]> Co-authored-by: Joe Au-Yeung <[email protected]>
This commit is contained in:
19 files changed
+508
-10
No files matched your search
@@ -35,6 +35,7 @@ export const listHandler = async ({ ctx }: ListHandlerInput) => {
|
||||
},
|
||||
select: {
|
||||
lockEventTypeCreationForUsers: true,
|
||||
adminGetsNoSlotsNotification: true,
|
||||
isAdminReviewed: true,
|
||||
},
|
||||
});
|
||||
@@ -52,6 +53,7 @@ export const listHandler = async ({ ctx }: ListHandlerInput) => {
|
||||
canAdminImpersonate: !!organizationSettings?.isAdminReviewed,
|
||||
organizationSettings: {
|
||||
lockEventTypeCreationForUsers: organizationSettings?.lockEventTypeCreationForUsers,
|
||||
adminGetsNoSlotsNotification: organizationSettings?.adminGetsNoSlotsNotification,
|
||||
},
|
||||
user: {
|
||||
role: membership?.role,
|
||||
|
||||
@@ -32,17 +32,24 @@ const updateOrganizationSettings = async ({
|
||||
input: TUpdateInputSchema;
|
||||
tx: Parameters<Parameters<PrismaClient["$transaction"]>[0]>[0];
|
||||
}) => {
|
||||
// if lockEventTypeCreation isn't given we don't do anything.
|
||||
if (typeof input.lockEventTypeCreation === "undefined") {
|
||||
return;
|
||||
const data: Prisma.OrganizationSettingsUpdateInput = {};
|
||||
|
||||
if (input.hasOwnProperty("lockEventTypeCreation")) {
|
||||
data.lockEventTypeCreationForUsers = input.lockEventTypeCreation;
|
||||
}
|
||||
|
||||
if (input.hasOwnProperty("adminGetsNoSlotsNotification")) {
|
||||
data.adminGetsNoSlotsNotification = input.adminGetsNoSlotsNotification;
|
||||
}
|
||||
|
||||
// If no settings values have changed lets skip this update
|
||||
if (Object.keys(data).length === 0) return;
|
||||
|
||||
await tx.organizationSettings.update({
|
||||
where: {
|
||||
organizationId,
|
||||
},
|
||||
data: {
|
||||
lockEventTypeCreationForUsers: !!input.lockEventTypeCreation,
|
||||
},
|
||||
data,
|
||||
});
|
||||
|
||||
if (input.lockEventTypeCreation) {
|
||||
|
||||
@@ -30,6 +30,7 @@ export const ZUpdateInputSchema = z.object({
|
||||
metadata: teamMetadataSchema.unwrap().optional(),
|
||||
lockEventTypeCreation: z.boolean().optional(),
|
||||
lockEventTypeCreationOptions: z.enum(["DELETE", "HIDE"]).optional(),
|
||||
adminGetsNoSlotsNotification: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export type TUpdateInputSchema = z.infer<typeof ZUpdateInputSchema>;
|
||||
@@ -0,0 +1,120 @@
|
||||
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";
|
||||
import { RedisService } from "@calcom/features/redis/RedisService";
|
||||
|
||||
import { handleNotificationWhenNoSlots } from "./handleNotificationWhenNoSlots";
|
||||
|
||||
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/server/utils", () => {
|
||||
// Mock kill switch to be false
|
||||
return {
|
||||
getFeatureFlag: 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",
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
// @ts-expect-error FIXME - also type error in bookingScenario
|
||||
i18nMock.getTranslation.mockImplementation(() => {
|
||||
return new Promise((resolve) => {
|
||||
const identityFn = (key: string) => key;
|
||||
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
|
||||
};
|
||||
const orgDetails = {
|
||||
currentOrgDomain: "org1",
|
||||
isValidOrgDomain: true,
|
||||
};
|
||||
|
||||
// Call the function
|
||||
await handleNotificationWhenNoSlots({ eventDetails, orgDetails });
|
||||
|
||||
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).not.toHaveBeenCalled();
|
||||
|
||||
// Mock length to be one then recall to trigger email
|
||||
mocked.lrange.mockResolvedValueOnce([""]);
|
||||
|
||||
await handleNotificationWhenNoSlots({ eventDetails, orgDetails });
|
||||
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
|
||||
};
|
||||
const orgDetails = {
|
||||
currentOrgDomain: "org1",
|
||||
isValidOrgDomain: true,
|
||||
};
|
||||
|
||||
// Call the function
|
||||
await handleNotificationWhenNoSlots({ eventDetails, orgDetails });
|
||||
|
||||
expect(CalcomEmails.sendOrganizationAdminNoSlotsNotification).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import type { Dayjs } from "@calcom/dayjs";
|
||||
import { sendOrganizationAdminNoSlotsNotification } from "@calcom/emails";
|
||||
import { RedisService } from "@calcom/features/redis/RedisService";
|
||||
import { IS_PRODUCTION, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
|
||||
type EventDetails = {
|
||||
username: string;
|
||||
eventSlug: string;
|
||||
startTime: 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) => {
|
||||
return `${REDIS_KEY_VERSION}.${eventDetails.username}:${eventDetails.eventSlug}${
|
||||
orgSlug ? `@${orgSlug}` : ""
|
||||
}`;
|
||||
};
|
||||
|
||||
const constructDataHash = (eventDetails: EventDetails) => {
|
||||
const obj = {
|
||||
st: eventDetails.startTime.format("YYYY-MM-DD"),
|
||||
vTz: eventDetails?.visitorTimezone,
|
||||
vUuid: eventDetails?.visitorUid,
|
||||
};
|
||||
|
||||
return JSON.stringify(obj);
|
||||
};
|
||||
|
||||
export const handleNotificationWhenNoSlots = async ({
|
||||
eventDetails,
|
||||
orgDetails,
|
||||
}: {
|
||||
eventDetails: EventDetails;
|
||||
orgDetails: { currentOrgDomain: string | null };
|
||||
}) => {
|
||||
// Check for org
|
||||
if (!orgDetails.currentOrgDomain) 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 prisma.team.findFirst({
|
||||
where: {
|
||||
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);
|
||||
// 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 org admins to send the email too
|
||||
const foundAdmins = await prisma.membership.findMany({
|
||||
where: {
|
||||
team: {
|
||||
slug: orgDetails.currentOrgDomain,
|
||||
isOrganization: true,
|
||||
},
|
||||
role: {
|
||||
in: ["ADMIN", "OWNER"],
|
||||
},
|
||||
},
|
||||
select: {
|
||||
user: {
|
||||
select: {
|
||||
email: true,
|
||||
locale: 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");
|
||||
|
||||
const payload = {
|
||||
language: translation,
|
||||
to: {
|
||||
email: admin.user.email,
|
||||
},
|
||||
user: eventDetails.username,
|
||||
slug: eventDetails.eventSlug,
|
||||
startTime: eventDetails.startTime.format("YYYY-MM"),
|
||||
// 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`,
|
||||
};
|
||||
|
||||
emailsToSend.push(sendOrganizationAdminNoSlotsNotification(payload));
|
||||
}
|
||||
await Promise.all(emailsToSend);
|
||||
}
|
||||
};
|
||||
@@ -30,6 +30,7 @@ import { TRPCError } from "@trpc/server";
|
||||
|
||||
import type { GetScheduleOptions } from "./getSchedule.handler";
|
||||
import type { TGetScheduleInputSchema } from "./getSchedule.schema";
|
||||
import { handleNotificationWhenNoSlots } from "./handleNotificationWhenNoSlots";
|
||||
|
||||
export const checkIfIsAvailable = ({
|
||||
time,
|
||||
@@ -680,6 +681,25 @@ export async function getAvailableSlots({ input, ctx }: GetScheduleOptions): Pro
|
||||
);
|
||||
loggerWithEventDetails.debug(`Available slots: ${JSON.stringify(computedAvailableSlots)}`);
|
||||
|
||||
// We only want to run this on single targeted events and not dynamic
|
||||
if (!computedAvailableSlots.slots && input.usernameList?.length === 1) {
|
||||
try {
|
||||
await handleNotificationWhenNoSlots({
|
||||
eventDetails: {
|
||||
username: input.usernameList?.[0],
|
||||
startTime: startTime,
|
||||
eventSlug: eventType.slug,
|
||||
},
|
||||
orgDetails,
|
||||
});
|
||||
} catch (e) {
|
||||
loggerWithEventDetails.error(
|
||||
`Something has went wrong. Upstash could be down and we have caught the error to not block availability:
|
||||
${e}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
slots: computedAvailableSlots,
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user