Skip to content

The open alternative to Salesforce, designed for AI.

feat(call-recorder): mark the Recording Bot preference On only when a bot is scheduled (#25412)

nitin2ab335f61130
diff --git a/packages/twenty-apps/public/call-recorder/README.md b/packages/twenty-apps/public/call-recorder/README.md
index 17061ea3e3a..e837efa8b73 100644
--- a/packages/twenty-apps/public/call-recorder/README.md
+++ b/packages/twenty-apps/public/call-recorder/README.md
@@ -22,6 +22,14 @@ cost scales with how much was said in the meeting, typically **$0.02–$0.06 per
meeting** on default models. Set the `CALL_RECORDER_SUMMARY_ENABLED` app
variable to `false` to turn summaries off.
+## πŸ€– The Recording Bot field
+
+Each calendar event has a **Recording Bot** field. It starts blank and the app
+sets it to On when it actually schedules the recorder for that meeting, which
+happens once the meeting is within the seven-day scheduling window. Set it to
+Off to skip a meeting. Past meetings the recorder never joined simply stay
+blank.
+
## πŸŽ₯ Supported meeting platforms
The recording bot can only join meetings on these platforms:
diff --git a/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts b/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts
index c7075d85c11..33547c2aed4 100644
--- a/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts
+++ b/packages/twenty-apps/public/call-recorder/src/__tests__/call-recorder-lifecycle.integration-test.ts
@@ -11,11 +11,13 @@ import {
vi,
} from 'vitest';
+import { CALENDAR_EVENT_UPDATE_BATCH_SIZE } from 'src/logic-functions/constants/calendar-event-update-batch-size';
import { cancelCallRecordingRequest } from 'src/logic-functions/flows/cancel-call-recording-request.util';
import { reconcileCallRecorderForCalendarEventIds } from 'src/logic-functions/flows/reconcile-call-recorder.util';
import { retryFailedRecallCancellations } from 'src/logic-functions/flows/retry-failed-recall-cancellations.util';
import { scheduleRecallBotsForPendingCallRecordings } from 'src/logic-functions/flows/schedule-recall-bots-for-pending-call-recordings.util';
import { processRecallWebhookHandler } from 'src/logic-functions/process-recall-webhook';
+import reconcileCalendarEventLogicFunction from 'src/logic-functions/reconcile-call-recorder-calendar-event';
// ---------------------------------------------------------------------------
// Call Recorder end-to-end behavior against a live Twenty server.
@@ -42,8 +44,8 @@ const RESTRICTED_TITLE_PLACEHOLDER =
'FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED';
// The app's generated client only covers the objects the app uses, but test
-// seeding also needs calendarChannelEventAssociations (see below); this hits
-// the workspace GraphQL API directly with the test API key.
+// fixture discovery needs fields that are not part of the app schema; this
+// hits the workspace GraphQL API directly with the test API key.
const workspaceGraphql = async (
query: string,
variables: Record<string, unknown> = {},
@@ -67,45 +69,78 @@ const workspaceGraphql = async (
return payload.data;
};
-// Calendar events are only readable when a calendar channel with
-// SHARE_EVERYTHING visibility claims them, exactly like events coming from a
-// real calendar sync. The dev seeds provide such a channel; it is found by
-// following a fully visible seeded event to its channel association.
-const discoverShareEverythingChannelId = async (): Promise<string> => {
- const eventsData = await workspaceGraphql(
- `query { calendarEvents(first: 30) { edges { node { id title } } } }`,
- );
- const visibleEvent = eventsData.calendarEvents.edges
- .map((edge: any) => edge.node)
- .find(
- (node: any) =>
- node.title !== null && node.title !== RESTRICTED_TITLE_PLACEHOLDER,
+type CalendarEventFixture = {
+ id: string;
+ title: string;
+ startsAt: string;
+ endsAt: string;
+ iCalUid: string;
+ isCanceled: boolean;
+ isFullDay: boolean;
+ callRecorderPreference: string | null;
+ conferenceLink: {
+ primaryLinkLabel: string;
+ primaryLinkUrl: string;
+ secondaryLinks: Array<{ label: string; url: string }> | null;
+ };
+};
+
+const discoverVisibleCalendarEventFixtures = async (): Promise<
+ CalendarEventFixture[]
+> => {
+ const fixtures: CalendarEventFixture[] = [];
+ let after: string | null = null;
+
+ do {
+ const eventsData = await workspaceGraphql(
+ `query ($after: String) {
+ calendarEvents(first: 200, after: $after) {
+ edges {
+ node {
+ id
+ title
+ startsAt
+ endsAt
+ iCalUid
+ isCanceled
+ isFullDay
+ callRecorderPreference
+ conferenceLink {
+ primaryLinkLabel
+ primaryLinkUrl
+ secondaryLinks { label url }
+ }
+ }
+ }
+ pageInfo { hasNextPage endCursor }
+ }
+ }`,
+ { after },
+ );
+ const connection = eventsData.calendarEvents;
+
+ fixtures.push(
+ ...connection.edges
+ .map((edge: any) => edge.node)
+ .filter(
+ (node: CalendarEventFixture) =>
+ node.title !== RESTRICTED_TITLE_PLACEHOLDER &&
+ /^event\d+@calendar\.twentycrm\.com$/.test(node.iCalUid),
+ ),
);
- if (visibleEvent === undefined) {
+ after = connection.pageInfo.hasNextPage
+ ? connection.pageInfo.endCursor
+ : null;
+ } while (after !== null);
+
+ if (fixtures.length === 0) {
throw new Error(
- 'No fully visible seeded calendar event found; run the dev seeds before the integration tests',
+ 'No fully visible seeded calendar events found; run the dev seeds before the integration tests',
);
}
- const associationsData = await workspaceGraphql(
- `query ($calendarEventId: UUID) {
- calendarChannelEventAssociations(
- filter: { calendarEventId: { eq: $calendarEventId } }
- first: 1
- ) { edges { node { calendarChannelId } } }
- }`,
- { calendarEventId: visibleEvent.id },
- );
- const channelId =
- associationsData.calendarChannelEventAssociations.edges[0]?.node
- ?.calendarChannelId;
-
- if (channelId === undefined) {
- throw new Error('Seeded visible calendar event has no channel association');
- }
-
- return channelId;
+ return fixtures;
};
const inOneHour = () => new Date(Date.now() + 60 * 60 * 1000).toISOString();
@@ -133,6 +168,7 @@ class FakeRecallApi {
listRequestCount = 0;
artifactImportRequests: object[] = [];
failNextDelete = false;
+ failCalendarEventUpdates = false;
seedBot(bot: FakeRecallBot): void {
this.bots.set(bot.id, bot);
@@ -172,6 +208,14 @@ class FakeRecallApi {
});
}
+ if (
+ this.failCalendarEventUpdates &&
+ requestUrl === `${process.env.TWENTY_API_URL}/graphql` &&
+ String(requestInit?.body ?? '').includes('updateCalendarEvents')
+ ) {
+ return jsonResponse(500, { errors: [{ message: 'Internal error' }] });
+ }
+
if (!requestUrl.startsWith(RECALL_BASE_URL)) {
return undefined;
}
@@ -314,8 +358,8 @@ const buildTranscriptDoneWebhook = ({
});
// ---------------------------------------------------------------------------
-// Test workspace helpers: real rows in the test database, destroyed after
-// each scenario.
+// Test workspace helpers: real rows in the test database, cleaned up or
+// restored after each scenario.
// ---------------------------------------------------------------------------
describe('call recorder app lifecycle (integration)', () => {
@@ -323,11 +367,11 @@ describe('call recorder app lifecycle (integration)', () => {
// Twenty API traffic always uses the real fetch.
let client: CoreApiClient;
let workspaceId: string;
- let shareEverythingChannelId: string;
+ let availableCalendarEventFixtures: CalendarEventFixture[];
+ let nextCalendarEventFixtureIndex = 0;
let recall: FakeRecallApi;
- const createdCalendarEventIds: string[] = [];
+ const borrowedCalendarEventFixtures: CalendarEventFixture[] = [];
const createdCallRecordingIds: string[] = [];
- const createdAssociationIds: string[] = [];
const readWorkspaceIdFromApiKey = (): string => {
const apiKey = process.env[WORKSPACE_API_KEY_ENV] ?? '';
@@ -341,7 +385,8 @@ describe('call recorder app lifecycle (integration)', () => {
beforeAll(async () => {
client = new CoreApiClient();
workspaceId = readWorkspaceIdFromApiKey();
- shareEverythingChannelId = await discoverShareEverythingChannelId();
+ availableCalendarEventFixtures =
+ await discoverVisibleCalendarEventFixtures();
});
beforeEach(() => {
@@ -381,11 +426,15 @@ describe('call recorder app lifecycle (integration)', () => {
});
const destroyCreatedRows = async (): Promise<void> => {
+ const calendarEventRestoreErrors: Error[] = [];
+ const borrowedCalendarEventIds = borrowedCalendarEventFixtures.map(
+ ({ id }) => id,
+ );
const callRecordingsForCreatedCalendarEvents =
- createdCalendarEventIds.length === 0
+ borrowedCalendarEventIds.length === 0
? []
: await findCallRecordings({
- calendarEventId: { in: createdCalendarEventIds },
+ calendarEventId: { in: borrowedCalendarEventIds },
});
const callRecordingIds = [
...new Set([
@@ -402,44 +451,71 @@ describe('call recorder app lifecycle (integration)', () => {
.catch(() => {});
}
- for (const associationId of createdAssociationIds) {
- await workspaceGraphql(
- `mutation ($id: UUID!) {
- destroyCalendarChannelEventAssociation(id: $id) { id }
- }`,
- { id: associationId },
- ).catch(() => {});
- }
-
- for (const calendarEventId of createdCalendarEventIds) {
- await client
- .mutation({
- destroyCalendarEvent: { __args: { id: calendarEventId }, id: true },
- })
- .catch(() => {});
+ for (const fixture of borrowedCalendarEventFixtures) {
+ try {
+ await client.mutation({
+ updateCalendarEvent: {
+ __args: {
+ id: fixture.id,
+ data: {
+ title: fixture.title,
+ startsAt: fixture.startsAt,
+ endsAt: fixture.endsAt,
+ iCalUid: fixture.iCalUid,
+ isCanceled: fixture.isCanceled,
+ isFullDay: fixture.isFullDay,
+ callRecorderPreference: fixture.callRecorderPreference,
+ conferenceLink: fixture.conferenceLink,
+ },
+ },
+ id: true,
+ },
+ });
+ } catch (error) {
+ calendarEventRestoreErrors.push(
+ error instanceof Error ? error : new Error(String(error)),
+ );
+ }
}
- createdCalendarEventIds.length = 0;
+ borrowedCalendarEventFixtures.length = 0;
createdCallRecordingIds.length = 0;
- createdAssociationIds.length = 0;
+
+ if (calendarEventRestoreErrors.length > 0) {
+ throw new Error(
+ `Failed to restore borrowed calendar event fixtures: ${calendarEventRestoreErrors
+ .map(({ message }) => message)
+ .join('; ')}`,
+ );
+ }
};
const createCalendarEvent = async (
overrides: Record<string, unknown> = {},
): Promise<string> => {
- const calendarEventId = randomUUID();
+ const fixture =
+ availableCalendarEventFixtures[nextCalendarEventFixtureIndex];
+
+ if (fixture === undefined) {
+ throw new Error('No visible seeded calendar event fixture available');
+ }
+
+ nextCalendarEventFixtureIndex += 1;
+ borrowedCalendarEventFixtures.push(fixture);
await client.mutation({
- createCalendarEvent: {
+ updateCalendarEvent: {
__args: {
+ id: fixture.id,
data: {
- id: calendarEventId,
title: 'Customer Sync (call recorder integration test)',
startsAt: inOneHour(),
endsAt: inTwoHours(),
- iCalUid: `call-recorder-test-${calendarEventId}`,
+ iCalUid: `call-recorder-test-${fixture.id}`,
+ isCanceled: false,
+ isFullDay: false,
conferenceLink: {
- primaryLinkUrl: `https://meet.google.com/${calendarEventId}`,
+ primaryLinkUrl: `https://meet.google.com/${fixture.id}`,
},
callRecorderPreference: 'ON',
...overrides,
@@ -448,28 +524,8 @@ describe('call recorder app lifecycle (integration)', () => {
id: true,
},
});
- createdCalendarEventIds.push(calendarEventId);
-
- // Without a SHARE_EVERYTHING channel association the event would be
- // invisible to every query, like an event no calendar sync produced.
- const associationData = await workspaceGraphql(
- `mutation ($data: CalendarChannelEventAssociationCreateInput!) {
- createCalendarChannelEventAssociation(data: $data) { id }
- }`,
- {
- data: {
- calendarChannelId: shareEverythingChannelId,
- calendarEventId,
- eventExternalId: `call-recorder-test-${calendarEventId}`,
- },
- },
- );
-
- createdAssociationIds.push(
- associationData.createCalendarChannelEventAssociation.id,
- );
- return calendarEventId;
+ return fixture.id;
};
const createPendingCallRecording = async ({
@@ -527,6 +583,24 @@ describe('call recorder app lifecycle (integration)', () => {
return (result.callRecordings?.edges ?? []).map((edge: any) => edge.node);
};
+ const fetchCallRecorderPreference = async (
+ calendarEventId: string,
+ ): Promise<string | null> => {
+ const result = await client.query({
+ calendarEvents: {
+ __args: { filter: { id: { eq: calendarEventId } }, first: 1 },
+ edges: { node: { id: true, callRecorderPreference: true } },
+ },
+ });
+ const calendarEvent = result.calendarEvents?.edges?.[0]?.node;
+
+ if (calendarEvent === undefined) {
+ throw new Error(`Calendar event ${calendarEventId} not found`);
+ }
+
+ return calendarEvent.callRecorderPreference ?? null;
+ };
+
const fetchCallRecording = async (
callRecordingId: string,
): Promise<Record<string, any>> => {
@@ -570,6 +644,31 @@ describe('call recorder app lifecycle (integration)', () => {
};
};
+ const deliverCalendarEventUpdate = ({
+ calendarEventId,
+ updatedFields,
+ before,
+ after,
+ }: {
+ calendarEventId: string;
+ updatedFields: string[];
+ before: Record<string, unknown>;
+ after: Record<string, unknown>;
+ }) =>
+ (
+ reconcileCalendarEventLogicFunction.config.handler as (
+ event: unknown,
+ ) => Promise<object | undefined>
+ )({
+ name: 'calendarEvent.updated',
+ recordId: calendarEventId,
+ properties: {
+ updatedFields,
+ before: { id: calendarEventId, ...before },
+ after: { id: calendarEventId, ...after },
+ },
+ });
+
// Mocked webhook trigger: invokes the webhook logic function handler with
// the payload Recall would have delivered.
const deliverRecallWebhook = (body: object) =>
@@ -914,4 +1013,223 @@ describe('call recorder app lifecycle (integration)', () => {
expect(recall.botForCallRecording(callRecordingId)).toBeUndefined();
});
});
+
+ describe('Recording Bot preference', () => {
+ it('marks a blank preference On when it schedules a bot', async () => {
+ const calendarEventId = await createCalendarEvent({
+ callRecorderPreference: null,
+ });
+
+ await reconcileCallRecorderForCalendarEventIds({
+ client,
+ calendarEventIds: [calendarEventId],
+ });
+
+ expect(await fetchCallRecorderPreference(calendarEventId)).toBe('ON');
+
+ const callRecording = (
+ await findCallRecordings({ calendarEventId: { in: [calendarEventId] } })
+ )[0];
+
+ expect(callRecording).toBeDefined();
+ expect(callRecording.externalBotId).toBeTruthy();
+ });
+
+ it('leaves a blank preference blank on a meeting that already ended', async () => {
+ const calendarEventId = await createCalendarEvent({
+ startsAt: hoursAgo(3),
+ endsAt: hoursAgo(2),
+ callRecorderPreference: null,
+ });
+
+ await reconcileCallRecorderForCalendarEventIds({
+ client,
+ calendarEventIds: [calendarEventId],
+ });
+
+ expect(await fetchCallRecorderPreference(calendarEventId)).toBeNull();
+ expect(
+ await findCallRecordings({
+ calendarEventId: { in: [calendarEventId] },
+ }),
+ ).toEqual([]);
+ });
+
+ it('leaves an explicit Off alone and schedules nothing', async () => {
+ const calendarEventId = await createCalendarEvent({
+ callRecorderPreference: 'OFF',
+ });
+
+ await reconcileCallRecorderForCalendarEventIds({
+ client,
+ calendarEventIds: [calendarEventId],
+ });
+
+ expect(await fetchCallRecorderPreference(calendarEventId)).toBe('OFF');
+ expect(
+ await findCallRecordings({
+ calendarEventId: { in: [calendarEventId] },
+ }),
+ ).toEqual([]);
+ });
+
+ it('marks every blank copy of the same meeting On, past the update batch size in one go', async () => {
+ const requiredCalendarEventFixtureCount =
+ CALENDAR_EVENT_UPDATE_BATCH_SIZE + 1;
+ const availableCalendarEventFixtureCount =
+ availableCalendarEventFixtures.length - nextCalendarEventFixtureIndex;
+
+ if (
+ availableCalendarEventFixtureCount < requiredCalendarEventFixtureCount
+ ) {
+ throw new Error(
+ `Batch boundary test requires ${requiredCalendarEventFixtureCount} fully visible seeded calendar events, but only ${availableCalendarEventFixtureCount} remain`,
+ );
+ }
+
+ const startsAt = inOneHour();
+ const endsAt = inTwoHours();
+ const conferenceLink = {
+ primaryLinkUrl: `https://meet.google.com/${randomUUID()}`,
+ };
+ const calendarEventIds: string[] = [];
+
+ for (
+ let copyIndex = 0;
+ copyIndex < requiredCalendarEventFixtureCount;
+ copyIndex += 1
+ ) {
+ calendarEventIds.push(
+ await createCalendarEvent({
+ startsAt,
+ endsAt,
+ conferenceLink,
+ callRecorderPreference: null,
+ }),
+ );
+ }
+
+ await reconcileCallRecorderForCalendarEventIds({
+ client,
+ calendarEventIds: [calendarEventIds[0]],
+ });
+
+ const preferences = await Promise.all(
+ calendarEventIds.map((calendarEventId) =>
+ fetchCallRecorderPreference(calendarEventId),
+ ),
+ );
+
+ expect(preferences.every((preference) => preference === 'ON')).toBe(true);
+ expect(
+ await findCallRecordings({ calendarEventId: { in: calendarEventIds } }),
+ ).toHaveLength(1);
+ });
+
+ it('marks a blank preference On again when it updates an existing scheduled recording', async () => {
+ const { calendarEventId } =
+ await scheduleRecordingThroughCalendarReconciliation();
+
+ await client.mutation({
+ updateCalendarEvent: {
+ __args: {
+ id: calendarEventId,
+ data: { callRecorderPreference: null },
+ },
+ id: true,
+ },
+ });
+ await reconcileCallRecorderForCalendarEventIds({
+ client,
+ calendarEventIds: [calendarEventId],
+ });
+
+ expect(await fetchCallRecorderPreference(calendarEventId)).toBe('ON');
+ expect(
+ await findCallRecordings({
+ calendarEventId: { in: [calendarEventId] },
+ }),
+ ).toHaveLength(1);
+ });
+
+ it('still schedules the bot when the On write is rejected', async () => {
+ const calendarEventId = await createCalendarEvent({
+ callRecorderPreference: null,
+ });
+
+ recall.failCalendarEventUpdates = true;
+
+ const results = await reconcileCallRecorderForCalendarEventIds({
+ client: new CoreApiClient(),
+ calendarEventIds: [calendarEventId],
+ });
+
+ expect(results).toEqual([expect.objectContaining({ action: 'CREATED' })]);
+ expect(await fetchCallRecorderPreference(calendarEventId)).toBeNull();
+
+ const callRecording = (
+ await findCallRecordings({ calendarEventId: { in: [calendarEventId] } })
+ )[0];
+
+ expect(callRecording).toBeDefined();
+ expect(callRecording.externalBotId).toBeTruthy();
+ });
+
+ it('does not reconcile again on the echo of its own On write', async () => {
+ const calendarEventId = await createCalendarEvent({
+ callRecorderPreference: null,
+ });
+
+ await reconcileCallRecorderForCalendarEventIds({
+ client,
+ calendarEventIds: [calendarEventId],
+ });
+
+ const result = await deliverCalendarEventUpdate({
+ calendarEventId,
+ updatedFields: ['callRecorderPreference'],
+ before: { callRecorderPreference: null },
+ after: { callRecorderPreference: 'ON' },
+ });
+
+ expect(result).toEqual({
+ skipped: true,
+ reason: 'no relevant calendar event change',
+ });
+ });
+
+ it('schedules a bot and marks the event On when a user clears an Off', async () => {
+ const calendarEventId = await createCalendarEvent({
+ callRecorderPreference: 'OFF',
+ });
+
+ await client.mutation({
+ updateCalendarEvent: {
+ __args: {
+ id: calendarEventId,
+ data: { callRecorderPreference: null },
+ },
+ id: true,
+ },
+ });
+
+ const result = await deliverCalendarEventUpdate({
+ calendarEventId,
+ updatedFields: ['callRecorderPreference'],
+ before: { callRecorderPreference: 'OFF' },
+ after: { callRecorderPreference: null },
+ });
+
+ expect(result).toEqual(expect.objectContaining({ reconciled: true }));
+ expect(await fetchCallRecorderPreference(calendarEventId)).toBe('ON');
+
+ const callRecording = (
+ await findCallRecordings({ calendarEventId: { in: [calendarEventId] } })
+ )[0];
+
+ expect(callRecording).toBeDefined();
+ expect(callRecording.recordingRequestStatus).toBe('REQUESTED');
+ expect(callRecording.externalBotId).toBeTruthy();
+ });
+ });
});
diff --git a/packages/twenty-apps/public/call-recorder/src/fields/call-recorder-preference-on-calendar-event.field.ts b/packages/twenty-apps/public/call-recorder/src/fields/call-recorder-preference-on-calendar-event.field.ts
index 1af5e46bf3f..cc3b40f6f01 100644
--- a/packages/twenty-apps/public/call-recorder/src/fields/call-recorder-preference-on-calendar-event.field.ts
+++ b/packages/twenty-apps/public/call-recorder/src/fields/call-recorder-preference-on-calendar-event.field.ts
@@ -18,10 +18,9 @@ export default defineField({
name: 'callRecorderPreference',
label: 'Recording Bot',
description:
- 'Call recording is on by default when the app is installed. Turn it off for this event when needed.',
+ 'Set to On by the app when it schedules the recorder for this meeting. Turn it off to skip this event.',
icon: 'IconRobot',
- isNullable: false,
- defaultValue: `'${CallRecorderPreference.ON}'`,
+ isNullable: true,
options: [
{
id: CALL_RECORDER_PREFERENCE_ON_OPTION_ID,
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/calendar-event-update-batch-size.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/calendar-event-update-batch-size.ts
new file mode 100644
index 00000000000..e4171ecc76a
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/calendar-event-update-batch-size.ts
@@ -0,0 +1 @@
+export const CALENDAR_EVENT_UPDATE_BATCH_SIZE = 100;
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/mark-calendar-events-recording-on.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/mark-calendar-events-recording-on.util.ts
new file mode 100644
index 00000000000..142d99c3c85
--- /dev/null
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/mark-calendar-events-recording-on.util.ts
@@ -0,0 +1,39 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { CallRecorderPreference } from 'src/constants/call-recorder-preference';
+import { CALENDAR_EVENT_UPDATE_BATCH_SIZE } from 'src/logic-functions/constants/calendar-event-update-batch-size';
+import { getBatches } from 'src/logic-functions/utils/get-batches.util';
+import { getUniqueSortedIds } from 'src/logic-functions/utils/get-unique-sorted-ids.util';
+
+export const markCalendarEventsRecordingOn = async (
+ client: CoreApiClient,
+ calendarEventIds: string[],
+): Promise<number> => {
+ let markedCalendarEventCount = 0;
+
+ for (const calendarEventIdBatch of getBatches(
+ getUniqueSortedIds(calendarEventIds),
+ CALENDAR_EVENT_UPDATE_BATCH_SIZE,
+ )) {
+ const updateCalendarEventsResult = await client.mutation({
+ updateCalendarEvents: {
+ __args: {
+ filter: {
+ id: { in: calendarEventIdBatch },
+ callRecorderPreference: { is: 'NULL' },
+ },
+ data: {
+ callRecorderPreference: CallRecorderPreference.ON,
+ },
+ },
+ id: true,
+ },
+ });
+
+ markedCalendarEventCount += (
+ updateCalendarEventsResult.updateCalendarEvents ?? []
+ ).length;
+ }
+
+ return markedCalendarEventCount;
+};
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/reconcile-call-recorder.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/reconcile-call-recorder.test.ts
index 9eb077819ee..265457806aa 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/reconcile-call-recorder.test.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/reconcile-call-recorder.test.ts
@@ -168,6 +168,29 @@ class FakeCoreApiClient {
};
}
+ if (mutation.updateCalendarEvents !== undefined) {
+ const { filter, data } = mutation.updateCalendarEvents.__args;
+ const updatedCalendarEvents = this.calendarEvents.filter(
+ (calendarEvent) =>
+ filter.id.in.includes(calendarEvent.id) &&
+ filter.callRecorderPreference.is === 'NULL' &&
+ (calendarEvent.callRecorderPreference ?? null) === null,
+ );
+
+ for (const calendarEvent of updatedCalendarEvents) {
+ Object.assign(calendarEvent, data);
+ }
+
+ this.mutations.push({
+ name: 'updateCalendarEvents',
+ args: { filter, data },
+ });
+
+ return {
+ updateCalendarEvents: updatedCalendarEvents.map(({ id }) => ({ id })),
+ };
+ }
+
throw new Error(`Unhandled mutation: ${JSON.stringify(mutation)}`);
}
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-call-recorder.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-call-recorder.util.ts
index afc0c81519a..6c968787c6a 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-call-recorder.util.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reconcile-call-recorder.util.ts
@@ -20,6 +20,7 @@ import {
import { scheduleRecallBotForCallRecording } from 'src/logic-functions/flows/schedule-recall-bot-for-call-recording.util';
import { fetchCalendarEventsByIds } from 'src/logic-functions/data/fetch-calendar-events-by-ids.util';
import { fetchCalendarEventsByStartsAtValues } from 'src/logic-functions/data/fetch-calendar-events-by-starts-at-values.util';
+import { markCalendarEventsRecordingOn } from 'src/logic-functions/data/mark-calendar-events-recording-on.util';
import { findCallRecordingsByCalendarEventIds } from 'src/logic-functions/data/find-call-recordings-by-calendar-event-ids.util';
import { findCallRecordingsByIds } from 'src/logic-functions/data/find-call-recordings-by-ids.util';
import { getUniqueSortedIds } from 'src/logic-functions/utils/get-unique-sorted-ids.util';
@@ -247,12 +248,16 @@ const reconcileActiveMeeting = async ({
)[0];
if (!isUndefined(existingCallRecording)) {
- return updatePolicyManagedCallRecording({
+ const reconciliationResult = await updatePolicyManagedCallRecording({
client,
existingCallRecording,
representativeCalendarEvent,
realMeetingKey: meetingPolicyResult.realMeetingKey,
});
+
+ await markRequestingCalendarEventsRecordingOn(client, meetingPolicyResult);
+
+ return reconciliationResult;
}
const manualOpenCallRecording = await findManualOpenCallRecording({
@@ -269,12 +274,34 @@ const reconcileActiveMeeting = async ({
};
}
- return createPolicyManagedCallRecording({
+ const reconciliationResult = await createPolicyManagedCallRecording({
client,
callRecordingId,
representativeCalendarEvent,
realMeetingKey: meetingPolicyResult.realMeetingKey,
});
+
+ await markRequestingCalendarEventsRecordingOn(client, meetingPolicyResult);
+
+ return reconciliationResult;
+};
+
+const markRequestingCalendarEventsRecordingOn = async (
+ client: CoreApiClient,
+ meetingPolicyResult: CallRecorderPolicyResultForMeeting,
+): Promise<void> => {
+ try {
+ await markCalendarEventsRecordingOn(
+ client,
+ meetingPolicyResult.requestingCalendarEventIds,
+ );
+ } catch (error) {
+ console.warn(
+ `[call-recorder] failed to mark the calendar events of meeting ${meetingPolicyResult.realMeetingKey} as recording on: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ }
};
const updatePolicyManagedCallRecording = async ({
diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-call-recorder-calendar-event.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-call-recorder-calendar-event.ts
index 9d323553330..940c89d20eb 100644
--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-call-recorder-calendar-event.ts
+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/reconcile-call-recorder-calendar-event.ts
@@ -6,6 +6,7 @@ import {
type ObjectRecordBaseEvent,
} from 'twenty-sdk/define';
+import { CallRecorderPreference } from 'src/constants/call-recorder-preference';
import { CALENDAR_EVENT_RECONCILIATION_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
import { type RemovedCallRecorderOccurrence } from 'src/logic-functions/types/removed-call-recorder-occurrence.type';
import { computeRealMeetingKey } from 'src/logic-functions/domain/compute-real-meeting-key.util';
@@ -40,6 +41,7 @@ const CALL_RECORDER_KEY_CALENDAR_EVENT_FIELDS = [
type CalendarEventForDatabaseEvent = {
id: string;
+ callRecorderPreference?: string | null;
conferenceLink?: { primaryLinkUrl?: string | null } | null;
location?: string | null;
description?: string | null;
@@ -112,7 +114,14 @@ const buildCalendarEventReconciliationPayload = ({
if (action === 'updated') {
const updatedFields = event.properties.updatedFields ?? [];
- if (!hasRelevantFieldChange(updatedFields)) {
+ if (
+ !hasRelevantFieldChange(updatedFields) ||
+ isPreferenceChangeWithoutPolicyEffect({
+ updatedFields,
+ before: event.properties.before,
+ after: event.properties.after,
+ })
+ ) {
return { calendarEventIds: [], removedOccurrences: [] };
}
@@ -150,6 +159,20 @@ const hasRelevantFieldChange = (updatedFields: string[]): boolean =>
CALL_RECORDER_RELEVANT_CALENDAR_EVENT_FIELDS.includes(updatedField),
);
+const isPreferenceChangeWithoutPolicyEffect = ({
+ updatedFields,
+ before,
+ after,
+}: {
+ updatedFields: string[];
+ before: CalendarEventForDatabaseEvent | undefined;
+ after: CalendarEventForDatabaseEvent | undefined;
+}): boolean =>
+ updatedFields.length === 1 &&
+ updatedFields[0] === 'callRecorderPreference' &&
+ before?.callRecorderPreference !== CallRecorderPreference.OFF &&
+ after?.callRecorderPreference !== CallRecorderPreference.OFF;
+
const hasKeyFieldChange = (updatedFields: string[]): boolean =>
updatedFields.some((updatedField) =>
CALL_RECORDER_KEY_CALENDAR_EVENT_FIELDS.includes(updatedField),