chore: Integrate mark-no-show booking audit (#26570)

* chore: Integrate mark-no-show booking audit

Co-Authored-By: [email protected] <[email protected]>

* fix: Simplify host no-show audit and add comment for attendee actor

Co-Authored-By: [email protected] <[email protected]>

* fix: Make actionSource required with ValidActionSource type and remove unnecessary comments

Co-Authored-By: [email protected] <[email protected]>

* fix: Remove merge conflict markers from bookings.service.ts

Co-Authored-By: [email protected] <[email protected]>

* feat: implement SYSTEM as a booking audit source for background tasks, including no-show triggers.

* refactor: Move prisma query to BookingRepository for audit logging

Co-Authored-By: [email protected] <[email protected]>

* Conflict resolution

* refactor: introduce `handleMarkHostNoShow` for public viewer and standardize actor and action source parameters for no-show actions.

* refactor: Combine HostNoShowUpdatedAuditActionService and AttendeeNoShowUpdatedAuditActionService into NoShowUpdatedActionService

- Create new NoShowUpdatedAuditActionService with combined schema supporting both noShowHost and noShowAttendee as optional fields
- Update BookingAuditActionServiceRegistry to use combined service with NO_SHOW_UPDATED action type
- Update BookingAuditTaskerProducerService with single queueNoShowUpdatedAudit method
- Update BookingAuditProducerService.interface.ts with combined method
- Update BookingEventHandlerService with single onNoShowUpdated method
- Update handleMarkNoShow.ts to use combined audit service
- Update tasker tasks (triggerGuestNoShow, triggerHostNoShow) to use combined service
- Add NO_SHOW_UPDATED to Prisma BookingAuditAction enum
- Remove old separate HostNoShowUpdatedAuditActionService and AttendeeNoShowUpdatedAuditActionService files

This allows a single API action (e.g., API V2 markAbsent) that updates both host and attendee no-show status to be logged as a single audit event.

Co-Authored-By: [email protected] <[email protected]>

* chore: Add migration for NO_SHOW_UPDATED audit action enum value

Co-Authored-By: [email protected] <[email protected]>

* refactor: Update no-show audit schema to use host and attendees array

- Rename noShowHost to host and noShowAttendee to attendees (remove redundant prefix)
- Change attendees from single value to array to support multiple attendees in single audit entry
- Update handleMarkNoShow.ts to create single audit entry for all attendees
- Update tasker tasks (triggerGuestNoShow, triggerHostNoShow) to use new schema
- Update display data types to reflect new schema structure

Co-Authored-By: [email protected] <[email protected]>

* Update schema to be more clear. Call onNoShowUpdated immediately after DB update as audit only cares about DB update, and this would avoid any accidental Audit update on DB change

* chore: accommodate schema changes and fix type errors for no-show audit

Co-Authored-By: [email protected] <[email protected]>

* fix: Update migration to remove old no-show enum values

Co-Authored-By: [email protected] <[email protected]>

* fix: Use updated attendees in webhook payload for guest no-show

Co-Authored-By: [email protected] <[email protected]>

* fix: Remove duplicate imports and fix actor parameter in bookings.service.ts

Co-Authored-By: [email protected] <[email protected]>

* refactor: Move booking query to BookingRepository and remove unused method

Co-Authored-By: [email protected] <[email protected]>

* refactor: centralize no-show audit event firing and attendee fetching within `handleMarkNoShow` for improved clarity.

* fix: Build attendeesNoShow as Record with attendee IDs as keys

Co-Authored-By: [email protected] <[email protected]>

* Fix and add tests for handleMarkBoShow

* refactor: Move prisma queries to AttendeeRepository and BookingRepository

Co-Authored-By: [email protected] <[email protected]>

* fix: Correct return type for updateNoShow method (noShow can be null)

Co-Authored-By: [email protected] <[email protected]>

* fix: Update handleMarkNoShow tests to mock new repository methods

Co-Authored-By: [email protected] <[email protected]>

* fix triggerGuestNoShow

* refactor: Move triggerGuestNoShow queries to AttendeeRepository and add unit tests

- Add new methods to AttendeeRepository:
  - findByBookingId: Get attendees with id, email, noShow
  - findByBookingIdWithDetails: Get full attendee details
  - updateManyNoShowByBookingIdAndEmails: Update specific attendees
  - updateManyNoShowByBookingIdExcludingEmails: Update all except specific emails
- Refactor triggerGuestNoShow.ts to use AttendeeRepository instead of direct Prisma calls
- Add comprehensive unit tests for triggerGuestNoShow following handleMarkNoShow.test.ts pattern:
  - Mock repositories and external services
  - In-memory DB simulation
  - Test core functionality, audit logging, webhook payload, error handling, and edge cases

Co-Authored-By: [email protected] <[email protected]>

* refactor: Move triggerHostNoShow queries to repositories and delete unit test file

Co-Authored-By: [email protected] <[email protected]>

* refactor: Convert repository methods to use named parameters objects

Co-Authored-By: [email protected] <[email protected]>

* refactor: Enhance no-show handling by consolidating audit logging and updating repository interactions

- Refactor `buildResultPayload` to accept a structured argument for better clarity.
- Update `updateAttendees` to use a named parameter object for improved readability.
- Introduce `fireNoShowUpdatedEvent` to centralize no-show audit logging for both hosts and guests.
- Remove redundant methods and streamline attendee retrieval in `AttendeeRepository`.
- Add comprehensive unit tests for no-show event handling, ensuring accurate audit logging and webhook triggering.

* test: Add tests for handleMarkHostNoShow guest actor and unmarking host no-show

Co-Authored-By: [email protected] <[email protected]>

* fix: update attendeesNoShow validation to handle numeric keys

- Changed attendeesNoShow schema to use z.coerce.number() for key validation, ensuring string keys are correctly coerced to numbers.
- Updated test to validate attendeesNoShow data using numeric key comparison, improving robustness of the audit data checks.

* test: Add integration tests for NoShowUpdatedAuditActionService coerce fix

Co-Authored-By: [email protected] <[email protected]>

* feat: add graceful error handling for audit log enrichment

- Add hasError field to EnrichedAuditLog type
- Create buildFallbackAuditLog() method for failed enrichments
- Wrap enrichAuditLog() in try-catch to handle errors gracefully
- Add booking_audit_action.error_processing translation key
- Update BookingHistory.tsx to show warning icon for error logs
- Hide 'Show details' button for logs with hasError
- Add comprehensive test cases for error handling scenarios

Co-Authored-By: [email protected] <[email protected]>

* feat: Enhance booking audit action services with new display fields and improved validation

- Added "attendee_no_show_updated" and "no_show_updated" translations to common.json.
- Updated IAuditActionService to include new methods for handling display fields and migration.
- Enhanced NoShowUpdatedAuditActionService to differentiate between host and attendee no-show updates.
- Improved ReassignmentAuditActionService to ensure consistent handling of audit data.
- Refactored BookingAuditViewerService for better clarity and maintainability.

* refactor: Use attendeeEmail instead of attendeeId as key in audit data and store host's userUuid

- Updated schema to use attendee email as key instead of attendee ID because attendee records can be reused with different person's data
- Store host's userUuid in audit data with format: host: { userUuid, noShow: { old, new } }
- Updated fireNoShowUpdated to accept hostUserUuid parameter
- Added uuid field to BookingRepository.findByUidIncludeEventTypeAttendeesAndUser
- Updated NoShowUpdatedAuditActionService getDisplayFields to work with email-based keys
- Added attendeeRepository to DI modules for BookingAuditTaskConsumer
- Updated tests to match new schema format

Co-Authored-By: [email protected] <[email protected]>

* test: Update integration tests to use new schema format with host.userUuid and email keys

Co-Authored-By: [email protected] <[email protected]>

* fix: correct audit schema for SYSTEM source and ensure attendee lookup by bookingId

- Fix schema inconsistency: use host.userUuid format instead of hostNoShow
- Add user.uuid to getBooking select for audit logging
- Log warning when hostUserUuid is undefined but host no-show is being updated
- Use email as key for attendeesNoShow (not attendee ID) to match schema
- Fetch attendees by bookingId before updating to ensure correct scoping
- Remove unused safeStringify import

* refactor: Change attendeesNoShow schema from Record to Array format

- Update NoShowUpdatedAuditActionService schema to use array format:
  attendeesNoShow: Array<{attendeeEmail: string, noShow: {old, new}}>
- Update handleMarkNoShow.ts to build attendeesNoShow as array
- Update common.ts fireNoShowUpdatedEvent to convert Map to array
- Update all tests to use new array format with attendeeEmail property

Co-Authored-By: [email protected] <[email protected]>

* refactor: Update attendeesNoShow schema to use array format in triggerNoShow tasks

- Refactor `triggerGuestNoShow` and `triggerHostNoShow` to replace Map with array for `attendeesNoShowAudit`.
- Update `fireNoShowUpdatedEvent` to handle the new array format for attendees.
- Ensure consistent data structure across no-show audit logging for better clarity and maintainability.

* fix: Update ReassignmentAuditActionService to use GetDisplayFieldsParams interface

Co-Authored-By: [email protected] <[email protected]>

* fix: Update ReassignmentAuditActionService tests to use GetDisplayFieldsParams interface

Co-Authored-By: [email protected] <[email protected]>

* fix: Use handleMarkAttendeeNoShow for API v2 mark absent endpoint

- Export handleMarkAttendeeNoShow from platform-libraries
- Update API v2 bookings service to use handleMarkAttendeeNoShow with actionSource
- Add validation for userUuid before calling handleMarkAttendeeNoShow

Co-Authored-By: [email protected] <[email protected]>

* refactor: Enhance display fields structure in booking audit components

- Updated `BookingHistory.tsx` to allow for more flexible display fields, including optional raw values and arrays of values.
- Introduced `DisplayFieldValue` component for rendering display fields, improving clarity and maintainability.
- Adjusted `IAuditActionService` and `NoShowUpdatedAuditActionService` to align with the new display fields structure.
- Ensured consistent handling of display fields across the booking audit service for better data representation.

* fix: Remove debug code that duplicated first attendee in display fields

Co-Authored-By: [email protected] <[email protected]>

* refactor: Update attendee repository methods to use structured parameters

- Modified `updateNoShow`, `updateManyNoShowByBookingIdAndEmails`, and `updateManyNoShowByBookingIdExcludingEmails` methods to accept structured `where` and `data` parameters for better clarity and maintainability.
- Updated calls to these methods throughout the codebase to reflect the new parameter structure.
- Removed unused `findByIdWithNoShow` method and adjusted related logic to streamline attendee data retrieval.

* feat: Add infrastructure for no-show audit integration

- Add Prisma migrations for SYSTEM source and NO_SHOW_UPDATED audit action
- Add NoShowUpdatedAuditActionService with array-based attendeesNoShow schema
- Update BookingAuditActionServiceRegistry to include NO_SHOW_UPDATED
- Update BookingAuditTaskConsumer and BookingAuditViewerService
- Add AttendeeRepository methods for no-show queries
- Update IAuditActionService interface with values array support
- Update locales with no-show audit translation keys

Co-Authored-By: [email protected] <[email protected]>

* fix: Add NO_SHOW_UPDATED to BookingAuditAction and SYSTEM to ActionSource types

Co-Authored-By: [email protected] <[email protected]>

* fix: Remove HOST_NO_SHOW_UPDATED and ATTENDEE_NO_SHOW_UPDATED from BookingAuditAction type to match Prisma schema

Co-Authored-By: [email protected] <[email protected]>

* fix: Update BookingAuditActionSchema to use NO_SHOW_UPDATED instead of HOST_NO_SHOW_UPDATED and ATTENDEE_NO_SHOW_UPDATED

Co-Authored-By: [email protected] <[email protected]>

* refactor: Remove deprecated no-show audit services and unify to NoShowUpdatedAuditActionService

- Delete HostNoShowUpdatedAuditActionService and AttendeeNoShowUpdatedAuditActionService
- Update BookingAuditProducerService.interface.ts to use queueNoShowUpdatedAudit
- Update BookingAuditTaskerProducerService.ts to use queueNoShowUpdatedAudit
- Update BookingEventHandlerService.ts to use onNoShowUpdated
- Add integration tests for NoShowUpdatedAuditActionService

Co-Authored-By: [email protected] <[email protected]>

* fix: Update test mock to match new AttendeeRepository.updateNoShow signature

Co-Authored-By: [email protected] <[email protected]>

* refactor: rename handleMarkAttendeeNoShow to handleMarkNoShow and update related types

- Renamed `handleMarkAttendeeNoShow` to `handleMarkNoShow` for clarity.
- Updated type definitions to reflect the new naming convention.
- Modified the `markNoShow` handler to require `userUuid` and adjusted related logic.
- Enhanced the `fireNoShowUpdatedEvent` to accommodate changes in event type structure.
- Updated references across various files to ensure consistency with the new function name.

* handle null value

* fix: add explicit parentheses for operator precedence clarity

Co-Authored-By: [email protected] <[email protected]>

* Fix cubic reported bug

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-02-06 09:27:25 -03:00
1 parent 08a5edd464
commit 54da93ab02
13 files changed
+1757 -261

No files matched your search

@@ -1,16 +1,19 @@
import dayjs from "@calcom/dayjs";
import { getHostsAndGuests } from "@calcom/features/bookings/lib/getHostsAndGuests";
import type { NoShowUpdatedAuditData } from "@calcom/features/booking-audit/lib/actions/NoShowUpdatedAuditActionService";
import { makeSystemActor } from "@calcom/features/booking-audit/lib/makeActor";
import { getBookingEventHandlerService } from "@calcom/features/bookings/di/BookingEventHandlerService.container";
import type { Host } from "@calcom/features/bookings/lib/getHostsAndGuests";
import { getHostsAndGuests } from "@calcom/features/bookings/lib/getHostsAndGuests";
import { sendGenericWebhookPayload } from "@calcom/features/webhooks/lib/sendPayload";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import prisma from "@calcom/prisma";
import type { TimeUnit } from "@calcom/prisma/enums";
import { BookingStatus, WebhookTriggerEvents } from "@calcom/prisma/enums";
import { getBooking } from "./getBooking";
import { getMeetingSessionsFromRoomName } from "./getMeetingSessionsFromRoomName";
import type { TWebhook, TTriggerNoShowPayloadSchema } from "./schema";
import type { TTriggerNoShowPayloadSchema, TWebhook } from "./schema";
import { ZSendNoShowWebhookPayloadSchema } from "./schema";
type OriginalRescheduledBooking =
@@ -140,6 +143,62 @@ export async function getParticipantsWithEmail(
export const log = logger.getSubLogger({ prefix: ["triggerNoShowTask"] });
export const fireNoShowUpdatedEvent = async ({
booking,
noShowHostAudit,
attendeesNoShowAudit,
}: {
booking: {
id: number;
uid: string;
user?: { id: number; uuid: string } | null;
eventType?: { teamId?: number | null; parent?: { teamId?: number | null } | null } | null;
};
noShowHostAudit?: { old: boolean | null; new: boolean | null };
attendeesNoShowAudit?: NoShowUpdatedAuditData["attendeesNoShow"];
}): Promise<void> => {
const hasHostNoShow = noShowHostAudit && noShowHostAudit.new !== null;
const hasAttendeesNoShow = attendeesNoShowAudit && attendeesNoShowAudit.length > 0;
if (!hasHostNoShow && !hasAttendeesNoShow) {
return;
}
const hostUserUuid = booking.user?.uuid;
if (hasHostNoShow && !hostUserUuid) {
log.warn("Host no-show audit skipped: booking.user.uuid is undefined", { bookingUid: booking.uid });
}
try {
const orgId = await getOrgIdFromMemberOrTeamId({
memberId: booking.user?.id,
teamId: booking.eventType?.teamId || booking.eventType?.parent?.teamId,
});
const bookingEventHandlerService = getBookingEventHandlerService();
await bookingEventHandlerService.onNoShowUpdated({
bookingUid: booking.uid,
// This action is taken by the scheduled tasker job, so we use the system actor
actor: makeSystemActor(),
organizationId: orgId ?? null,
source: "SYSTEM",
auditData: {
...(hasHostNoShow && noShowHostAudit.new !== null && hostUserUuid
? {
host: {
userUuid: hostUserUuid,
noShow: { old: noShowHostAudit.old, new: noShowHostAudit.new },
},
}
: {}),
...(hasAttendeesNoShow ? { attendeesNoShow: attendeesNoShowAudit } : {}),
},
});
} catch (error) {
log.error("Error logging audit for automatic no-show", error);
}
};
export const prepareNoShowTrigger = async (
payload: string
): Promise<{
@@ -51,6 +51,7 @@ export const getBooking = async (bookingId: number) => {
user: {
select: {
id: true,
uuid: true,
timeZone: true,
email: true,
name: true,
@@ -2,31 +2,37 @@ import {
createBookingScenario,
getDate,
getGoogleCalendarCredential,
TestData,
getOrganizer,
getScenarioData,
TestData,
} from "@calcom/testing/lib/bookingScenario/bookingScenario";
import { expectWebhookToHaveBeenCalledWith } from "@calcom/testing/lib/bookingScenario/expects";
import { setupAndTeardown } from "@calcom/testing/lib/bookingScenario/setupAndTeardown";
import { describe, vi, test, expect } from "vitest";
import process from "node:process";
import { appStoreMetadata } from "@calcom/app-store/apps.metadata.generated";
import dayjs from "@calcom/dayjs";
import { TimeUnit } from "@calcom/prisma/enums";
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import { BookingStatus } from "@calcom/prisma/enums";
import { BookingStatus, TimeUnit, WebhookTriggerEvents } from "@calcom/prisma/enums";
import { expectWebhookToHaveBeenCalledWith } from "@calcom/testing/lib/bookingScenario/expects";
import { setupAndTeardown } from "@calcom/testing/lib/bookingScenario/setupAndTeardown";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { WebhookVersion } from "../../../webhooks/lib/interface/IWebhookRepository";
import { calculateMaxStartTime } from "./common";
import { getMeetingSessionsFromRoomName } from "./getMeetingSessionsFromRoomName";
import type { TSendNoShowWebhookPayloadSchema } from "./schema";
import { triggerGuestNoShow } from "./triggerGuestNoShow";
import { WebhookVersion } from "../../../webhooks/lib/interface/IWebhookRepository";
vi.mock("@calcom/features/tasker/tasks/triggerNoShow/getMeetingSessionsFromRoomName", () => ({
getMeetingSessionsFromRoomName: vi.fn(),
}));
const { mockOnNoShowUpdated } = vi.hoisted(() => ({
mockOnNoShowUpdated: vi.fn(),
}));
vi.mock("@calcom/features/bookings/di/BookingEventHandlerService.container", () => ({
getBookingEventHandlerService: vi.fn().mockReturnValue({
onNoShowUpdated: mockOnNoShowUpdated,
}),
}));
const timeout = process.env.CI ? 5000 : 20000;
const EMPTY_MEETING_SESSIONS = {
@@ -34,9 +40,37 @@ const EMPTY_MEETING_SESSIONS = {
data: [],
};
type ExpectNoShowAuditParams = {
bookingUid: string;
source: string;
actor: {
identifiedBy: string;
id: string;
};
organizationId: number | null;
auditData: {
attendeesNoShow: Array<{
attendeeEmail: string;
noShow: {
new: boolean;
old: boolean | null;
};
}>;
};
};
function expectNoShowAuditToBeDone(expected: ExpectNoShowAuditParams): void {
expect(mockOnNoShowUpdated).toHaveBeenCalledTimes(1);
expect(mockOnNoShowUpdated).toHaveBeenCalledWith(expected);
}
describe("Trigger Guest No Show:", () => {
setupAndTeardown();
beforeEach(() => {
mockOnNoShowUpdated.mockClear();
});
test(
`Should trigger guest no show webhook when no one joined the call`,
async () => {
@@ -55,6 +89,7 @@ describe("Trigger Guest No Show:", () => {
const subscriberUrl = "http://my-webhook.example.com";
const bookingStartTime = `${plus1DateString}T05:00:00.000Z`;
const GUEST_ATTENDEE_ID = 101;
await createBookingScenario(
getScenarioData({
webhooks: [
@@ -93,6 +128,7 @@ describe("Trigger Guest No Show:", () => {
user: { id: organizer.id },
attendees: [
{
id: GUEST_ATTENDEE_ID,
email: "[email protected]",
name: "Guest User",
timeZone: "UTC",
@@ -193,6 +229,18 @@ describe("Trigger Guest No Show:", () => {
message: `Guest didn't join the call or didn't join before ${maxStartTimeHumanReadable}`,
},
});
expectNoShowAuditToBeDone({
bookingUid: uidOfBooking,
source: "SYSTEM",
actor: { identifiedBy: "id", id: "00000000-0000-0000-0000-000000000000" },
organizationId: null,
auditData: {
attendeesNoShow: [
{ attendeeEmail: "[email protected]", noShow: { new: true, old: false } },
],
},
});
},
timeout
);
@@ -215,6 +263,7 @@ describe("Trigger Guest No Show:", () => {
const subscriberUrl = "http://my-webhook.example.com";
const bookingStartTime = `${plus1DateString}T05:00:00.000Z`;
const GUEST_ATTENDEE_ID = 102;
await createBookingScenario(
getScenarioData({
webhooks: [
@@ -253,6 +302,7 @@ describe("Trigger Guest No Show:", () => {
user: { id: organizer.id },
attendees: [
{
id: GUEST_ATTENDEE_ID,
email: "[email protected]",
name: "Guest User",
timeZone: "UTC",
@@ -381,6 +431,18 @@ describe("Trigger Guest No Show:", () => {
message: `Guest didn't join the call or didn't join before ${maxStartTimeHumanReadable}`,
},
});
expectNoShowAuditToBeDone({
bookingUid: uidOfBooking,
source: "SYSTEM",
actor: { identifiedBy: "id", id: "00000000-0000-0000-0000-000000000000" },
organizationId: null,
auditData: {
attendeesNoShow: [
{ attendeeEmail: "[email protected]", noShow: { new: true, old: false } },
],
},
});
},
timeout
);
@@ -407,6 +469,7 @@ describe("Trigger Guest No Show:", () => {
const newiCalUID = `${newUidOfBooking}@Cal.com`;
const newBookingStartTime = `${plus1DateString}T05:15:00.000Z`;
const GUEST_ATTENDEE_ID = 103;
await createBookingScenario(
getScenarioData({
webhooks: [
@@ -480,6 +543,7 @@ describe("Trigger Guest No Show:", () => {
fromReschedule: uidOfBooking,
attendees: [
{
id: GUEST_ATTENDEE_ID,
email: "[email protected]",
name: "Guest User",
timeZone: "UTC",
@@ -608,6 +672,18 @@ describe("Trigger Guest No Show:", () => {
message: `Guest didn't join the call or didn't join before ${maxStartTimeHumanReadable}`,
},
});
expectNoShowAuditToBeDone({
bookingUid: newUidOfBooking,
source: "SYSTEM",
actor: { identifiedBy: "id", id: "00000000-0000-0000-0000-000000000000" },
organizationId: null,
auditData: {
attendeesNoShow: [
{ attendeeEmail: "[email protected]", noShow: { new: true, old: false } },
],
},
});
},
timeout
);
@@ -759,6 +835,8 @@ describe("Trigger Guest No Show:", () => {
payload: expect.any(Object),
})
).toThrow();
expect(mockOnNoShowUpdated).not.toHaveBeenCalled();
},
timeout
);
@@ -781,6 +859,7 @@ describe("Trigger Guest No Show:", () => {
const subscriberUrl = "http://my-webhook.example.com";
const bookingStartTime = `${plus1DateString}T05:00:00.000Z`;
const GUEST_ATTENDEE_ID = 104;
await createBookingScenario(
getScenarioData({
webhooks: [
@@ -819,6 +898,7 @@ describe("Trigger Guest No Show:", () => {
user: { id: organizer.id },
attendees: [
{
id: GUEST_ATTENDEE_ID,
email: "[email protected]",
name: "Guest User",
timeZone: "UTC",
@@ -1,8 +1,25 @@
import type { Host } from "@calcom/features/bookings/lib/getHostsAndGuests";
import { AttendeeRepository } from "@calcom/features/bookings/repositories/AttendeeRepository";
import { prisma } from "@calcom/prisma";
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import {
calculateMaxStartTime,
fireNoShowUpdatedEvent,
log,
prepareNoShowTrigger,
sendWebhookPayload,
} from "./common";
import { calculateMaxStartTime, sendWebhookPayload, prepareNoShowTrigger, log } from "./common";
type UpdatedAttendee = {
id: number;
email: string;
name: string;
locale: string | null;
timeZone: string;
phoneNumber: string | null;
bookingId: number | null;
noShow: boolean | null;
};
const markGuestAsNoshowInBooking = async ({
bookingId,
@@ -12,39 +29,59 @@ const markGuestAsNoshowInBooking = async ({
bookingId: number;
hostsThatJoinedTheCall: Host[];
guestsThatDidntJoinTheCall?: { email: string; name: string }[];
}) => {
}): Promise<{
updatedAttendees: UpdatedAttendee[] | null;
attendeesMarkedNoShow: { email: string; noShow: boolean; previousNoShow: boolean | null }[];
}> => {
const attendeeRepository = new AttendeeRepository(prisma);
try {
// Get attendees before update to capture previous noShow values
const attendeesBefore = await attendeeRepository.findByBookingId(bookingId);
const attendeesBeforeMap = new Map(attendeesBefore.map((a) => [a.email, a]));
let updatedAttendeeEmails: string[];
if (guestsThatDidntJoinTheCall && guestsThatDidntJoinTheCall.length > 0) {
const guestEmailsThatDidntJoin = guestsThatDidntJoinTheCall.map((g) => g.email);
await prisma.attendee.updateMany({
where: {
bookingId,
email: { in: guestEmailsThatDidntJoin },
},
const emailsToUpdate = guestsThatDidntJoinTheCall.map((g) => g.email);
await attendeeRepository.updateManyNoShowByBookingIdAndEmails({
where: { bookingId, emails: emailsToUpdate },
data: { noShow: true },
});
updatedAttendeeEmails = emailsToUpdate;
} else {
const hostsThatJoinedTheCallEmails = hostsThatJoinedTheCall.map((h) => h.email);
await prisma.attendee.updateMany({
where: {
bookingId,
email: { notIn: hostsThatJoinedTheCallEmails },
},
await attendeeRepository.updateManyNoShowByBookingIdExcludingEmails({
where: { bookingId, excludeEmails: hostsThatJoinedTheCallEmails },
data: { noShow: true },
});
// TODO: It is possible that by the time the updateMany query runs, there were more attendees added, though it would be a rare/unexpected thing because triggerGuestNoShow is called after the meeting has ended, and after that time attendees aren't updated
updatedAttendeeEmails = attendeesBefore
.filter((a) => !hostsThatJoinedTheCallEmails.includes(a.email))
.map((a) => a.email);
}
return await prisma.attendee.findMany({ where: { bookingId } });
const updatedAttendees = await attendeeRepository.findByBookingId(bookingId);
const attendeesMarkedNoShow = updatedAttendeeEmails
.map((email) => {
const before = attendeesBeforeMap.get(email);
if (!before) {
return null;
}
return { email, noShow: true, previousNoShow: before.noShow };
})
.filter((a): a is { email: string; noShow: boolean; previousNoShow: boolean | null } => a !== null);
return { updatedAttendees, attendeesMarkedNoShow };
} catch (err) {
log.error("Error marking guests as no show in booking", err);
return null;
return { updatedAttendees: null, attendeesMarkedNoShow: [] };
}
};
export async function triggerGuestNoShow(payload: string): Promise<void> {
const result = await prepareNoShowTrigger(payload);
if (!result) return;
const {
webhook,
booking,
@@ -64,15 +101,23 @@ export async function triggerGuestNoShow(payload: string): Promise<void> {
if (requireEmailForGuests) {
if (guestsThatDidntJoinTheCall.length > 0) {
const updatedAttendees = await markGuestAsNoshowInBooking({
const { updatedAttendees, attendeesMarkedNoShow } = await markGuestAsNoshowInBooking({
bookingId: booking.id,
hostsThatJoinedTheCall,
guestsThatDidntJoinTheCall,
});
const attendeesNoShowAudit = attendeesMarkedNoShow.map((a) => ({
attendeeEmail: a.email,
noShow: { old: a.previousNoShow, new: a.noShow },
}));
await fireNoShowUpdatedEvent({ booking, attendeesNoShowAudit });
const guests = updatedAttendees?.filter((a) => !hostEmails.has(a.email)) ?? [];
const bookingWithUpdatedData = updatedAttendees
? { ...booking, attendees: updatedAttendees, guests }
: booking;
await sendWebhookPayload(
webhook,
WebhookTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW,
@@ -84,14 +129,23 @@ export async function triggerGuestNoShow(payload: string): Promise<void> {
}
} else {
if (!didGuestJoinTheCall) {
const updatedAttendees = await markGuestAsNoshowInBooking({
const { updatedAttendees, attendeesMarkedNoShow } = await markGuestAsNoshowInBooking({
bookingId: booking.id,
hostsThatJoinedTheCall,
});
const attendeesNoShowAudit = attendeesMarkedNoShow.map((a) => ({
attendeeEmail: a.email,
noShow: { old: a.previousNoShow, new: a.noShow },
}));
await fireNoShowUpdatedEvent({ booking, attendeesNoShowAudit });
const guests = updatedAttendees?.filter((a) => !hostEmails.has(a.email)) ?? [];
const bookingWithUpdatedData = updatedAttendees
? { ...booking, attendees: updatedAttendees, guests }
: booking;
await sendWebhookPayload(
webhook,
WebhookTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW,
@@ -2,31 +2,37 @@ import {
createBookingScenario,
getDate,
getGoogleCalendarCredential,
TestData,
getOrganizer,
getScenarioData,
TestData,
} from "@calcom/testing/lib/bookingScenario/bookingScenario";
import { expectWebhookToHaveBeenCalledWith } from "@calcom/testing/lib/bookingScenario/expects";
import { setupAndTeardown } from "@calcom/testing/lib/bookingScenario/setupAndTeardown";
import { describe, vi, test, expect } from "vitest";
import process from "node:process";
import { appStoreMetadata } from "@calcom/app-store/apps.metadata.generated";
import dayjs from "@calcom/dayjs";
import { TimeUnit } from "@calcom/prisma/enums";
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import { BookingStatus } from "@calcom/prisma/enums";
import { BookingStatus, TimeUnit, WebhookTriggerEvents } from "@calcom/prisma/enums";
import { expectWebhookToHaveBeenCalledWith } from "@calcom/testing/lib/bookingScenario/expects";
import { setupAndTeardown } from "@calcom/testing/lib/bookingScenario/setupAndTeardown";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { WebhookVersion } from "../../../webhooks/lib/interface/IWebhookRepository";
import { calculateMaxStartTime } from "./common";
import { getMeetingSessionsFromRoomName } from "./getMeetingSessionsFromRoomName";
import type { TSendNoShowWebhookPayloadSchema } from "./schema";
import { triggerHostNoShow } from "./triggerHostNoShow";
import { WebhookVersion } from "../../../webhooks/lib/interface/IWebhookRepository";
vi.mock("@calcom/features/tasker/tasks/triggerNoShow/getMeetingSessionsFromRoomName", () => ({
getMeetingSessionsFromRoomName: vi.fn(),
}));
const { mockOnNoShowUpdated } = vi.hoisted(() => ({
mockOnNoShowUpdated: vi.fn(),
}));
vi.mock("@calcom/features/bookings/di/BookingEventHandlerService.container", () => ({
getBookingEventHandlerService: vi.fn().mockReturnValue({
onNoShowUpdated: mockOnNoShowUpdated,
}),
}));
const timeout = process.env.CI ? 5000 : 20000;
const EMPTY_MEETING_SESSIONS = {
@@ -34,9 +40,44 @@ const EMPTY_MEETING_SESSIONS = {
data: [],
};
type ExpectNoShowAuditParams = {
bookingUid: string;
source: string;
actor: {
identifiedBy: string;
id: string;
};
organizationId: number | null;
auditData: {
host?: {
userUuid: string;
noShow: {
old: boolean | null;
new: boolean;
};
};
attendeesNoShow?: Array<{
attendeeEmail: string;
noShow: {
new: boolean;
old: boolean | null;
};
}>;
};
};
function expectNoShowAuditToBeDone(expected: ExpectNoShowAuditParams): void {
expect(mockOnNoShowUpdated).toHaveBeenCalledTimes(1);
expect(mockOnNoShowUpdated).toHaveBeenCalledWith(expected);
}
describe("Trigger Host No Show:", () => {
setupAndTeardown();
beforeEach(() => {
mockOnNoShowUpdated.mockClear();
});
test(
`Should trigger host no show webhook when no one joined the call`,
async () => {
@@ -174,6 +215,16 @@ describe("Trigger Host No Show:", () => {
message: `Host with email ${organizer.email} didn't join the call or didn't join before ${maxStartTimeHumanReadable}`,
},
});
expectNoShowAuditToBeDone({
bookingUid: uidOfBooking,
source: "SYSTEM",
actor: { identifiedBy: "id", id: "00000000-0000-0000-0000-000000000000" },
organizationId: null,
auditData: {
host: { userUuid: expect.any(String), noShow: { old: false, new: true } },
},
});
},
timeout
);
@@ -341,6 +392,16 @@ describe("Trigger Host No Show:", () => {
message: `Host with email ${organizer.email} didn't join the call or didn't join before ${maxStartTimeHumanReadable}`,
},
});
expectNoShowAuditToBeDone({
bookingUid: uidOfBooking,
source: "SYSTEM",
actor: { identifiedBy: "id", id: "00000000-0000-0000-0000-000000000000" },
organizationId: null,
auditData: {
host: { userUuid: expect.any(String), noShow: { old: false, new: true } },
},
});
},
timeout
);
@@ -548,6 +609,16 @@ describe("Trigger Host No Show:", () => {
message: `Host with email ${organizer.email} didn't join the call or didn't join before ${maxStartTimeHumanReadable}`,
},
});
expectNoShowAuditToBeDone({
bookingUid: newUidOfBooking,
source: "SYSTEM",
actor: { identifiedBy: "id", id: "00000000-0000-0000-0000-000000000000" },
organizationId: null,
auditData: {
host: { userUuid: expect.any(String), noShow: { old: false, new: true } },
},
});
},
timeout
);
@@ -702,6 +773,171 @@ describe("Trigger Host No Show:", () => {
message: `Host with email ${organizer.email} didn't join the call or didn't join before ${maxStartTimeHumanReadable}`,
},
});
expectNoShowAuditToBeDone({
bookingUid: uidOfBooking,
source: "SYSTEM",
actor: { identifiedBy: "id", id: "00000000-0000-0000-0000-000000000000" },
organizationId: null,
auditData: {
host: { userUuid: expect.any(String), noShow: { old: false, new: true } },
},
});
},
timeout
);
test(
`Should not trigger host no show webhook when host joined the call`,
async () => {
const organizer = getOrganizer({
name: "Organizer",
email: "[email protected]",
id: 101,
schedules: [TestData.schedules.IstWorkHours],
credentials: [getGoogleCalendarCredential()],
selectedCalendars: [TestData.selectedCalendars.google],
});
const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });
const uidOfBooking = "n5Wv3eHgconAED2j4gcVhP";
const iCalUID = `${uidOfBooking}@Cal.com`;
const subscriberUrl = "http://my-webhook.example.com";
const bookingStartTime = `${plus1DateString}T05:00:00.000Z`;
await createBookingScenario(
getScenarioData({
webhooks: [
{
id: "22",
userId: organizer.id,
eventTriggers: [WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW],
subscriberUrl,
active: true,
eventTypeId: 1,
appId: null,
time: 5,
timeUnit: TimeUnit.MINUTE,
},
],
eventTypes: [
{
id: 1,
slotInterval: 15,
length: 15,
users: [
{
id: 101,
},
],
},
],
bookings: [
{
id: 222,
uid: uidOfBooking,
eventTypeId: 1,
status: BookingStatus.ACCEPTED,
startTime: bookingStartTime,
endTime: `${plus1DateString}T05:15:00.000Z`,
user: { id: organizer.id },
attendees: [
{
email: "[email protected]",
name: "Guest User",
timeZone: "UTC",
locale: "en",
},
],
metadata: {
videoCallUrl: "https://existing-daily-video-call-url.example.com",
},
references: [
{
type: appStoreMetadata.dailyvideo.type,
uid: "MOCK_ID",
meetingId: "MOCK_ID",
meetingPassword: "MOCK_PASS",
meetingUrl: "http://mock-dailyvideo.example.com",
credentialId: null,
},
{
type: appStoreMetadata.googlecalendar.type,
uid: "MOCK_ID",
meetingId: "MOCK_ID",
meetingPassword: "MOCK_PASSWORD",
meetingUrl: "https://UNUSED_URL",
externalCalendarId: "MOCK_EXTERNAL_CALENDAR_ID",
credentialId: undefined,
},
],
iCalUID,
},
],
organizer,
apps: [TestData.apps["google-calendar"], TestData.apps["daily-video"]],
})
);
const MOCKED_PARTICIPANTS = [
{
user_id: "101",
email: "[email protected]",
participant_id: "MOCK_PARTICIPANT_ID",
user_name: "Organizer",
join_time: 0,
duration: 15,
isLoggedIn: true,
},
];
const MOCKED_MEETING_SESSIONS = {
total_count: 1,
data: [
{
id: "MOCK_ID",
room: "MOCK_ROOM",
start_time: 1234567890,
duration: 15,
max_participants: 1,
participants: MOCKED_PARTICIPANTS,
},
],
};
vi.mocked(getMeetingSessionsFromRoomName).mockResolvedValue(MOCKED_MEETING_SESSIONS);
const TEST_WEBHOOK = {
id: "22",
eventTriggers: [WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW],
subscriberUrl,
active: true,
eventTypeId: 1,
appId: null,
time: 5,
timeUnit: TimeUnit.MINUTE,
payloadTemplate: null,
secret: null,
version: WebhookVersion.V_2021_10_20,
};
const payload = JSON.stringify({
triggerEvent: WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW,
bookingId: 222,
webhook: TEST_WEBHOOK,
} satisfies TSendNoShowWebhookPayloadSchema);
await triggerHostNoShow(payload);
// This will throw an error if the webhook was called
expect(() =>
expectWebhookToHaveBeenCalledWith(subscriberUrl, {
triggerEvent: WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW,
payload: expect.any(Object),
})
).toThrow();
expect(mockOnNoShowUpdated).not.toHaveBeenCalled();
},
timeout
);
@@ -1,37 +1,68 @@
import type { Host } from "@calcom/features/bookings/lib/getHostsAndGuests";
import { AttendeeRepository } from "@calcom/features/bookings/repositories/AttendeeRepository";
import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository";
import { prisma } from "@calcom/prisma";
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import type { Booking } from "./common";
import { calculateMaxStartTime, sendWebhookPayload, prepareNoShowTrigger, log } from "./common";
import {
calculateMaxStartTime,
fireNoShowUpdatedEvent,
log,
prepareNoShowTrigger,
sendWebhookPayload,
} from "./common";
const markHostsAsNoShowInBooking = async (booking: Booking, hostsThatDidntJoinTheCall: Host[]) => {
const bookingRepository = new BookingRepository(prisma);
const attendeeRepository = new AttendeeRepository(prisma);
try {
if (hostsThatDidntJoinTheCall.length === 0) {
return null;
}
const attendeesBefore = await attendeeRepository.findByBookingId(booking.id);
const attendeesBeforeByEmail = new Map(attendeesBefore.map((a) => [a.email, a]));
let noShowHost = booking.noShowHost;
const noShowHostAudit: { old: boolean | null; new: boolean | null } = {
old: booking.noShowHost,
new: null,
};
const attendeesNoShowAudit: Array<{
attendeeEmail: string;
noShow: { old: boolean | null; new: boolean };
}> = [];
await Promise.allSettled(
hostsThatDidntJoinTheCall.map((host) => {
hostsThatDidntJoinTheCall.map(async (host) => {
if (booking?.user?.id === host.id) {
noShowHost = true;
return prisma.booking.update({
where: {
uid: booking.uid,
},
data: {
noShowHost: true,
},
});
noShowHostAudit.new = noShowHost;
return bookingRepository.updateNoShowHost({ bookingUid: booking.uid, noShowHost: true });
}
// If there are more than one host then it is stored in attendees table
else if (booking.attendees?.some((attendee) => attendee.email === host.email)) {
return prisma.attendee.update({
where: { id: host.id },
const attendeeBefore = attendeesBeforeByEmail.get(host.email);
if (attendeeBefore) {
await attendeeRepository.updateNoShow({
where: { attendeeId: attendeeBefore.id },
data: { noShow: true },
});
attendeesNoShowAudit.push({
attendeeEmail: host.email,
noShow: { old: attendeeBefore.noShow ?? null, new: true },
});
}
return Promise.resolve();
})
);
const updatedAttendees = await prisma.attendee.findMany({ where: { bookingId: booking.id } });
const updatedAttendees = await attendeeRepository.findByBookingId(booking.id);
await fireNoShowUpdatedEvent({
booking,
noShowHostAudit,
attendeesNoShowAudit,
});
return { noShowHost, attendees: updatedAttendees };
} catch (error) {
log.error("Error marking hosts as no show in booking", error);