The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Reconcile call recorder meetings from batched reads (#26621)
nitin7ebbb447ec91
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.tsindex 7c95a1b99ef..27a655cf82e 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@@ -20,10 +20,12 @@ import {CHECK_CREDITS_BEFORE_RECALL_BOT_JOIN_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,} from 'src/constants/universal-identifiers';-import { type CallRecorderPreference } from 'src/constants/call-recorder-preference';+import { CallRecorderPreference } from 'src/constants/call-recorder-preference';import { reconcileStaleBotStateHandler } from 'src/logic-functions/reconcile-stale-bot-state';import { CALL_RECORDER_CALENDAR_BOT_SCHEDULING_ENABLED_ENV_VAR_NAME } from 'src/logic-functions/constants/call-recorder-calendar-bot-scheduling-enabled-env-var-name';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 { markCalendarEventsRecordingOn } from 'src/logic-functions/data/mark-calendar-events-recording-on.util';import { cancelCallRecordingRequest } from 'src/logic-functions/flows/cancel-call-recording-request.util';import { enqueueCallRecordingArtifactsImport } from 'src/logic-functions/data/enqueue-call-recording-artifacts-import.util';import { saveCallRecordingImportProgress } from 'src/logic-functions/data/save-call-recording-import-progress.util';@@ -546,6 +548,16 @@ class FakeRecallApi {return new Response(null, { status: 204 });}+ if (method === 'PATCH' && botIdMatch !== null) {+ const bot = this.bots.get(botIdMatch[1]);++ if (bot === undefined) {+ return jsonResponse(404, {});+ }++ return jsonResponse(200, { id: bot.id });+ }+if (method === 'POST' &&/\/recording\/[^/]+\/create_transcript\/$/.test(requestUrl)@@ -980,6 +992,7 @@ describe('call recorder app lifecycle (integration)', () => {edges: {node: {id: true,+ title: true,status: true,recordingRequestStatus: true,calendarEventId: true,@@ -1104,6 +1117,107 @@ describe('call recorder app lifecycle (integration)', () => {),});+ const deliverCalendarEventDestroyed = (+ destroyedCalendarEvent: Record<string, unknown> & { id: string },+ ) =>+ (+ reconcileCalendarEventLogicFunction.config.handler as (+ batch: unknown,+ ) => Promise<object | undefined>+ )({+ name: 'calendarEvent.destroyed',+ events: [+ {+ recordId: destroyedCalendarEvent.id,+ properties: { before: destroyedCalendarEvent },+ },+ ],+ });++ const updateCalendarEventForDelivery = async (+ calendarEventId: string,+ data: Partial<CalendarEventFixture>,+ ) => {+ const result = await client.query({+ calendarEvents: {+ __args: { filter: { id: { eq: calendarEventId } }, first: 1 },+ edges: {+ node: {+ id: true,+ title: true,+ startsAt: true,+ endsAt: true,+ iCalUid: true,+ callRecorderPreference: true,+ conferenceLink: { primaryLinkUrl: true },+ },+ },+ },+ });+ const before = result.calendarEvents?.edges?.[0]?.node;++ if (isUndefined(before)) {+ throw new Error(`Calendar event ${calendarEventId} not found`);+ }++ await client.mutation({+ updateCalendarEvent: {+ __args: { id: calendarEventId, data },+ id: true,+ },+ });++ return {+ calendarEventId,+ updatedFields: Object.keys(data),+ before,+ after: { ...before, ...data },+ };+ };++ const simulateCalendarEventDestroy = async ({+ calendarEventId,+ callRecordingId,+ }: {+ calendarEventId: string;+ callRecordingId: string;+ }) => {+ const { before } = await updateCalendarEventForDelivery(calendarEventId, {+ startsAt: daysAgo(9),+ endsAt: daysAgo(8),+ });++ await client.mutation({+ updateCallRecording: {+ __args: { id: callRecordingId, data: { calendarEventId: null } },+ id: true,+ },+ });+ createdCallRecordingIds.push(callRecordingId);++ return before;+ };++ const interceptCoreApiRequests = (+ intercept: (+ request: { query: string; variables: Record<string, unknown> },+ sendRequest: () => Promise<Response>,+ ) => Promise<Response>,+ ) => {+ const interceptedFetch = globalThis.fetch;++ vi.stubGlobal(+ 'fetch',+ (input: Parameters<typeof fetch>[0], init?: RequestInit) => {+ const sendRequest = () => interceptedFetch(input, init);++ return String(input) === `${process.env.TWENTY_API_URL}/graphql`+ ? intercept(JSON.parse(String(init?.body)), sendRequest)+ : sendRequest();+ },+ );+ };+// Mocked webhook trigger: invokes the webhook logic function handler with// the payload Recall would have delivered.const deliverRecallWebhook = (body: object) =>@@ -1145,6 +1259,458 @@ describe('call recorder app lifecycle (integration)', () => {return result;};+ describe('batched calendar reconciliation', () => {+ it('saves later preference batches when the middle batch fails', async () => {+ const fixtureCount = 2 * CALENDAR_EVENT_UPDATE_BATCH_SIZE + 1;+ const fixtures = availableCalendarEventFixtures.slice(+ nextCalendarEventFixtureIndex,+ nextCalendarEventFixtureIndex + fixtureCount,+ );+ nextCalendarEventFixtureIndex += fixtureCount;+ expect(fixtures).toHaveLength(fixtureCount);+ expect(+ fixtures.every(({ callRecorderPreference }) =>+ isNull(callRecorderPreference),+ ),+ ).toBe(true);++ const calendarEventIds = fixtures.map(({ id }) => id);+ let preferenceBatchCount = 0;++ interceptCoreApiRequests(async ({ query }, sendRequest) => {+ if (query.includes('updateCalendarEvents(')) {+ preferenceBatchCount += 1;++ if (preferenceBatchCount === 2) {+ return new Response('Preference update failed', { status: 500 });+ }+ }++ return sendRequest();+ });++ try {+ await expect(+ markCalendarEventsRecordingOn(new CoreApiClient(), calendarEventIds),+ ).rejects.toThrow('1 of 3 calendar event preference batches failed');++ const result = await client.query({+ calendarEvents: {+ __args: {+ filter: { id: { in: calendarEventIds } },+ first: fixtureCount,+ },+ edges: { node: { id: true, callRecorderPreference: true } },+ },+ });+ const failedCalendarEventIds = new Set(+ [...calendarEventIds]+ .sort()+ .slice(+ CALENDAR_EVENT_UPDATE_BATCH_SIZE,+ 2 * CALENDAR_EVENT_UPDATE_BATCH_SIZE,+ ),+ );+ const calendarEvents = result.calendarEvents?.edges ?? [];++ expect(preferenceBatchCount).toBe(3);+ expect(calendarEvents).toHaveLength(fixtureCount);++ for (const { node } of calendarEvents) {+ expect(node.callRecorderPreference).toBe(+ failedCalendarEventIds.has(node.id) ? null : 'ON',+ );+ }+ } finally {+ for (const calendarEventIdBatch of getBatches(+ calendarEventIds,+ CALENDAR_EVENT_UPDATE_BATCH_SIZE,+ )) {+ await client.mutation({+ updateCalendarEvents: {+ __args: {+ filter: { id: { in: calendarEventIdBatch } },+ data: { callRecorderPreference: null },+ },+ id: true,+ },+ });+ }+ }+ });++ it.each(['calendarEventId', 'id'])(+ 'leaves existing recordings intact without redelivery when the %s lookup fails',+ async (filterField) => {+ const { calendarEventId, callRecordingId, botId } =+ await scheduleRecordingThroughCalendarReconciliation();+ const update = await updateCalendarEventForDelivery(calendarEventId, {+ startsAt: hoursAgo(-2 * 24),+ endsAt: hoursAgo(-2 * 24 - 1),+ });+ let lookupFailed = false;+ let mutationCount = 0;++ interceptCoreApiRequests(async ({ query, variables }, sendRequest) => {+ if (query.startsWith('mutation')) {+ mutationCount += 1;+ }++ if (+ query.includes('callRecordings(') &&+ JSON.stringify(variables).includes(`"${filterField}":{"in":`)+ ) {+ lookupFailed = true;+ return new Response('Recording lookup failed', { status: 500 });+ }++ return sendRequest();+ });++ await expect(+ deliverCalendarEventUpdates(update),+ ).rejects.not.toMatchObject({+ name: 'RetryableLogicFunctionError',+ });++ expect(lookupFailed).toBe(true);+ expect(mutationCount).toBe(0);+ expect(+ await findCallRecordings({+ calendarEventId: { eq: calendarEventId },+ }),+ ).toHaveLength(1);+ expect(await fetchCallRecording(callRecordingId)).toEqual(+ expect.objectContaining({+ recordingRequestStatus: 'REQUESTED',+ externalBotId: botId,+ }),+ );+ expect(recall.deletedBotIds).toEqual([]);+ expect([...recall.bots.keys()]).toEqual([botId]);+ },+ );++ it('leaves recording blank when its recording is deleted during reconciliation', async () => {+ const { calendarEventId, callRecordingId } =+ await scheduleRecordingThroughCalendarReconciliation();+ const update = await updateCalendarEventForDelivery(calendarEventId, {+ title: 'Renamed before deletion',+ callRecorderPreference: null,+ });+ let recordingDeleted = false;++ interceptCoreApiRequests(async ({ query, variables }, sendRequest) => {+ const response = await sendRequest();++ if (+ !recordingDeleted &&+ query.includes('callRecordings(') &&+ JSON.stringify(variables).includes('"id":{"in":')+ ) {+ recordingDeleted = true;+ await client.mutation({+ destroyCallRecording: { __args: { id: callRecordingId }, id: true },+ });+ }++ return response;+ });++ await deliverCalendarEventUpdates(update);++ expect(recordingDeleted).toBe(true);+ expect(+ await findCallRecordings({ calendarEventId: { eq: calendarEventId } }),+ ).toEqual([]);+ expect(await fetchCallRecorderPreference(calendarEventId)).toBeNull();+ });++ it('keeps a replacement bot when an outdated reschedule receives a Recall 404', async () => {+ const { calendarEventId, callRecordingId, botId, metadata } =+ await scheduleRecordingThroughCalendarReconciliation();+ const update = await updateCalendarEventForDelivery(calendarEventId, {+ endsAt: hoursAgo(-3),+ });+ const replacementBotId = randomUUID();+ let botReplaced = false;++ interceptCoreApiRequests(async ({ query, variables }, sendRequest) => {+ const response = await sendRequest();++ if (+ !botReplaced &&+ query.includes('callRecordings(') &&+ JSON.stringify(variables).includes('"id":{"in":')+ ) {+ botReplaced = true;+ recall.bots.delete(botId);+ recall.seedBot({+ id: replacementBotId,+ metadata,+ statusCode: 'scheduled',+ });+ await client.mutation({+ updateCallRecording: {+ __args: {+ id: callRecordingId,+ data: { externalBotId: replacementBotId },+ },+ id: true,+ },+ });+ }++ return response;+ });++ await deliverCalendarEventUpdates(update);++ expect(botReplaced).toBe(true);+ expect((await fetchCallRecording(callRecordingId)).externalBotId).toBe(+ replacementBotId,+ );+ expect([...recall.bots.keys()]).toEqual([replacementBotId]);+ });++ it('keeps a webhook status change while applying a calendar title change', async () => {+ const { calendarEventId, callRecordingId, botId, metadata } =+ await scheduleRecordingThroughCalendarReconciliation();+ const update = await updateCalendarEventForDelivery(calendarEventId, {+ title: 'Renamed while joining',+ });+ let webhookDelivered = false;++ interceptCoreApiRequests(async ({ query, variables }, sendRequest) => {+ const response = await sendRequest();++ if (+ !webhookDelivered &&+ query.includes('callRecordings(') &&+ JSON.stringify(variables).includes('"id":{"in":')+ ) {+ webhookDelivered = true;+ await deliverRecallWebhook(+ buildBotStatusChangeWebhook({+ botId,+ metadata,+ statusCode: 'joining_call',+ }),+ );+ }++ return response;+ });++ await deliverCalendarEventUpdates(update);++ expect(webhookDelivered).toBe(true);+ expect(await fetchCallRecording(callRecordingId)).toEqual(+ expect.objectContaining({+ title: 'Renamed while joining',+ status: 'JOINING',+ }),+ );+ });++ it('cancels the old recorder once when a meeting moves three weeks into the future', async () => {+ const { calendarEventId, callRecordingId, botId } =+ await scheduleRecordingThroughCalendarReconciliation();+ const update = await updateCalendarEventForDelivery(calendarEventId, {+ startsAt: hoursAgo(-21 * 24),+ endsAt: hoursAgo(-21 * 24 - 1),+ });++ await deliverCalendarEventUpdates(update);++ const recordings = await findCallRecordings({+ calendarEventId: { eq: calendarEventId },+ });+ expect(recordings).toHaveLength(1);+ expect(recordings[0].id).toBe(callRecordingId);+ expect(recordings[0].recordingRequestStatus).toBe('CANCELED');+ expect(recordings[0].externalBotId).toBeFalsy();+ expect(recall.deletedBotIds).toEqual([botId]);+ expect(recall.bots.size).toBe(0);+ expect(await fetchCallRecorderPreference(calendarEventId)).toBeNull();+ });++ it('cancels the bot of a meeting whose calendar event was destroyed', async () => {+ const { calendarEventId, callRecordingId, botId } =+ await scheduleRecordingThroughCalendarReconciliation();+ const destroyedCalendarEvent = await simulateCalendarEventDestroy({+ calendarEventId,+ callRecordingId,+ });++ await deliverCalendarEventDestroyed(destroyedCalendarEvent);++ const callRecording = await fetchCallRecording(callRecordingId);+ expect(callRecording.recordingRequestStatus).toBe('CANCELED');+ expect(callRecording.externalBotId).toBeFalsy();+ expect(recall.deletedBotIds).toEqual([botId]);+ expect(recall.bots.size).toBe(0);+ });++ it('keeps the replacement recorder when the same reschedule is delivered twice', async () => {+ const { calendarEventId, callRecordingId, botId } =+ await scheduleRecordingThroughCalendarReconciliation();+ const update = await updateCalendarEventForDelivery(calendarEventId, {+ startsAt: hoursAgo(-2 * 24),+ endsAt: hoursAgo(-2 * 24 - 1),+ });++ await deliverCalendarEventUpdates(update);+ const recordings = await findCallRecordings({+ calendarEventId: { eq: calendarEventId },+ });+ const replacement = recordings.find(({ id }) => id !== callRecordingId);+ if (isUndefined(replacement)) {+ throw new Error('The rescheduled meeting has no replacement recording');+ }++ await deliverCalendarEventUpdates(update);++ expect(+ await findCallRecordings({ calendarEventId: { eq: calendarEventId } }),+ ).toHaveLength(2);+ expect(+ (await fetchCallRecording(callRecordingId)).recordingRequestStatus,+ ).toBe('CANCELED');+ expect(await fetchCallRecording(replacement.id)).toEqual(+ expect.objectContaining({+ recordingRequestStatus: 'REQUESTED',+ externalBotId: replacement.externalBotId,+ }),+ );+ expect(recall.deletedBotIds).toEqual([botId]);+ expect([...recall.bots.keys()]).toEqual([replacement.externalBotId]);+ expect(await fetchCallRecorderPreference(calendarEventId)).toBe('ON');+ });++ it('creates, updates and cancels recordings for different meetings in one batch', async () => {+ const createdCalendarEventId = await createCalendarEvent({+ callRecorderPreference: null,+ });+ const updated = await scheduleRecordingThroughCalendarReconciliation();+ const canceled = await scheduleRecordingThroughCalendarReconciliation();+ const updatedEvent = await updateCalendarEventForDelivery(+ updated.calendarEventId,+ { title: 'Renamed customer sync', callRecorderPreference: null },+ );+ const canceledEvent = await updateCalendarEventForDelivery(+ canceled.calendarEventId,+ { callRecorderPreference: CallRecorderPreference.OFF },+ );++ const createdEvent = await updateCalendarEventForDelivery(+ createdCalendarEventId,+ { title: 'New customer sync' },+ );++ await deliverCalendarEventUpdates(+ createdEvent,+ updatedEvent,+ canceledEvent,+ );++ const createdRecordings = await findCallRecordings({+ calendarEventId: { eq: createdCalendarEventId },+ });+ expect(createdRecordings).toHaveLength(1);+ expect(createdRecordings[0].recordingRequestStatus).toBe('REQUESTED');+ expect(recall.bots.has(createdRecordings[0].externalBotId)).toBe(true);+ expect(await fetchCallRecording(updated.callRecordingId)).toEqual(+ expect.objectContaining({+ title: 'Renamed customer sync',+ recordingRequestStatus: 'REQUESTED',+ externalBotId: updated.botId,+ }),+ );+ const canceledRecording = await fetchCallRecording(+ canceled.callRecordingId,+ );+ expect(canceledRecording.recordingRequestStatus).toBe('CANCELED');+ expect(canceledRecording.externalBotId).toBeFalsy();+ expect(recall.deletedBotIds).toEqual([canceled.botId]);+ expect(await fetchCallRecorderPreference(createdCalendarEventId)).toBe(+ 'ON',+ );+ expect(await fetchCallRecorderPreference(updated.calendarEventId)).toBe(+ 'ON',+ );+ expect(await fetchCallRecorderPreference(canceled.calendarEventId)).toBe(+ 'OFF',+ );+ });++ it.each([1, 2])(+ 'cancels each recorder once when cancellation write %i fails during a move beyond seven days',+ async (failedCancellationIndex) => {+ const calendarEventId = await createCalendarEvent();+ const callRecordingIds: string[] = [];+ const botIds = [randomUUID(), randomUUID()];++ for (const botId of botIds) {+ const callRecordingId = await createPendingCallRecording({+ calendarEventId,+ externalBotId: botId,+ });++ callRecordingIds.push(callRecordingId);+ recall.seedBot({+ id: botId,+ metadata: buildBotMetadata(callRecordingId, workspaceId),+ statusCode: 'scheduled',+ });+ }++ const update = await updateCalendarEventForDelivery(calendarEventId, {+ startsAt: hoursAgo(-21 * 24),+ endsAt: hoursAgo(-21 * 24 - 1),+ });+ let cancellationWriteCount = 0;++ interceptCoreApiRequests(async ({ query, variables }, sendRequest) => {+ if (+ query.includes('updateCallRecording(') &&+ JSON.stringify(variables).includes(+ '"recordingRequestStatus":"CANCELED"',+ )+ ) {+ cancellationWriteCount += 1;++ if (cancellationWriteCount === failedCancellationIndex) {+ return new Response('Cancellation write failed', { status: 500 });+ }+ }++ return sendRequest();+ });++ const result = await deliverCalendarEventUpdates(update);++ expect(result).toEqual(+ expect.objectContaining({+ reconciliationResults: [+ expect.objectContaining({ action: 'FAILED' }),+ expect.objectContaining({ action: 'CANCELED' }),+ ],+ }),+ );+ expect(cancellationWriteCount).toBe(3);+ expect(recall.deletedBotIds.sort()).toEqual([...botIds].sort());++ for (const callRecordingId of callRecordingIds) {+ const callRecording = await fetchCallRecording(callRecordingId);++ expect(callRecording.recordingRequestStatus).toBe('CANCELED');+ expect(callRecording.externalBotId).toBeFalsy();+ }+ },+ );+ });+describe('scheduling from calendar changes', () => {it('creates a recording and schedules a Recall bot for a meeting with recording enabled', async () => {const { callRecordingId, botId } =@@ -2784,6 +3350,58 @@ describe('call recorder app lifecycle (integration)', () => {expect(callRecording.externalBotId).toBeTruthy();});+ it('uses four Core API reads and no writes for a batch of meetings that already have bots', async () => {+ const calendarEventIds = [+ await createCalendarEvent(),+ await createCalendarEvent(),+ await createCalendarEvent(),+ ];++ await reconcileCallRecorderForCalendarEventIds({+ client,+ calendarEventIds,+ });++ const interceptedFetch = globalThis.fetch;+ const twentyGraphqlRequestBodies: unknown[] = [];++ vi.stubGlobal(+ 'fetch',+ (input: Parameters<typeof fetch>[0], init?: RequestInit) => {+ if (String(input) === `${process.env.TWENTY_API_URL}/graphql`) {+ twentyGraphqlRequestBodies.push(init?.body);+ }++ return interceptedFetch(input, init);+ },+ );++ const result = await deliverCalendarEventUpdates(+ ...calendarEventIds.map((calendarEventId) => ({+ calendarEventId,+ updatedFields: ['endsAt'],+ before: { endsAt: inTwoHours() },+ after: { endsAt: inTwoHours() },+ })),+ );++ expect(result).toEqual(+ expect.objectContaining({+ reconciliationResults: [+ expect.objectContaining({ action: 'UPDATED' }),+ expect.objectContaining({ action: 'UPDATED' }),+ expect.objectContaining({ action: 'UPDATED' }),+ ],+ }),+ );+ expect(twentyGraphqlRequestBodies).toHaveLength(4);+ expect(+ twentyGraphqlRequestBodies.every((body) =>+ JSON.parse(String(body)).query.startsWith('query'),+ ),+ ).toBe(true);+ });+it('schedules a bot when a user sets On on an eligible meeting that has none yet', async () => {const calendarEventId = await createCalendarEvent({callRecorderPreference: 'ON',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.tsindex 142d99c3c85..4dda2b520b9 100644--- 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@@ -9,30 +9,46 @@ export const markCalendarEventsRecordingOn = async (client: CoreApiClient,calendarEventIds: string[],): Promise<number> => {- let markedCalendarEventCount = 0;-- for (const calendarEventIdBatch of getBatches(+ const calendarEventIdBatches = 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,+ );+ let markedCalendarEventCount = 0;+ const batchErrors: unknown[] = [];++ for (const calendarEventIdBatch of calendarEventIdBatches) {+ try {+ const updateCalendarEventsResult = await client.mutation({+ updateCalendarEvents: {+ __args: {+ filter: {+ id: { in: calendarEventIdBatch },+ callRecorderPreference: { is: 'NULL' },+ },+ data: {+ callRecorderPreference: CallRecorderPreference.ON,+ },},+ id: true,},- id: true,- },- });+ });++ markedCalendarEventCount += (+ updateCalendarEventsResult.updateCalendarEvents ?? []+ ).length;+ } catch (error) {+ batchErrors.push(error);+ }+ }- markedCalendarEventCount += (- updateCalendarEventsResult.updateCalendarEvents ?? []- ).length;+ if (batchErrors.length > 0) {+ throw new Error(+ `${batchErrors.length} of ${calendarEventIdBatches.length} calendar event preference batches failed: ${batchErrors+ .map((batchError) =>+ batchError instanceof Error ? batchError.message : String(batchError),+ )+ .join('; ')}`,+ );}return markedCalendarEventCount;diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/has-call-recording-update-field-changes.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/has-call-recording-update-field-changes.test.tsnew file mode 100644index 00000000000..c346b165f87--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/has-call-recording-update-field-changes.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it } from 'vitest';++import { CallRecordingRequestStatus } from 'src/logic-functions/constants/call-recording-request-status';+import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';+import { hasCallRecordingUpdateFieldChanges } from 'src/logic-functions/domain/has-call-recording-update-field-changes.util';+import { type CallRecordingRecord } from 'src/logic-functions/types/call-recording-record.type';++const CALL_RECORDING: CallRecordingRecord = {+ id: 'call-recording-1',+ title: 'Customer Sync',+ status: CallRecordingStatus.SCHEDULED,+ recordingRequestStatus: CallRecordingRequestStatus.REQUESTED,+ calendarEventId: 'calendar-event-1',+ externalBotId: 'recall-bot-1',+};++describe('hasCallRecordingUpdateFieldChanges', () => {+ it('returns false when every update field already matches', () => {+ expect(+ hasCallRecordingUpdateFieldChanges({+ callRecording: CALL_RECORDING,+ updateFields: {+ title: 'Customer Sync',+ status: CallRecordingStatus.SCHEDULED,+ recordingRequestStatus: CallRecordingRequestStatus.REQUESTED,+ calendarEventId: 'calendar-event-1',+ },+ }),+ ).toBe(false);+ });++ it('returns true when an update field differs', () => {+ expect(+ hasCallRecordingUpdateFieldChanges({+ callRecording: CALL_RECORDING,+ updateFields: { title: 'Renamed Customer Sync' },+ }),+ ).toBe(true);+ });++ it('treats clearing an absent field as no change', () => {+ expect(+ hasCallRecordingUpdateFieldChanges({+ callRecording: CALL_RECORDING,+ updateFields: { callRecorderFailureReason: null },+ }),+ ).toBe(false);+ });++ it('returns true when clearing a field that has a value', () => {+ expect(+ hasCallRecordingUpdateFieldChanges({+ callRecording: CALL_RECORDING,+ updateFields: { externalBotId: null },+ }),+ ).toBe(true);+ });++ it('treats an update to a field the record does not carry as a change', () => {+ expect(+ hasCallRecordingUpdateFieldChanges({+ callRecording: CALL_RECORDING,+ updateFields: { transcript: { segments: [] } },+ }),+ ).toBe(true);+ });++ it('returns false for an empty update', () => {+ expect(+ hasCallRecordingUpdateFieldChanges({+ callRecording: CALL_RECORDING,+ updateFields: {},+ }),+ ).toBe(false);+ });+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/has-call-recording-update-field-changes.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/has-call-recording-update-field-changes.util.tsnew file mode 100644index 00000000000..c7514ca7fff--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/has-call-recording-update-field-changes.util.ts@@ -0,0 +1,42 @@+import { isUndefined } from '@sniptt/guards';++import { type CallRecordingRecord } from 'src/logic-functions/types/call-recording-record.type';+import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';++type ComparableCallRecordingFieldName = keyof CallRecordingRecord &+ keyof CallRecordingUpdateFields;++const COMPARABLE_CALL_RECORDING_FIELDS: Record<+ ComparableCallRecordingFieldName,+ true+> = {+ title: true,+ status: true,+ recordingRequestStatus: true,+ startedAt: true,+ endedAt: true,+ calendarEventId: true,+ externalBotId: true,+ botScheduleAttemptedAt: true,+ botScheduleIdempotencyKey: true,+ externalRecordingId: true,+ callRecorderFailureReason: true,+};++const isComparableCallRecordingFieldName = (+ fieldName: string,+): fieldName is ComparableCallRecordingFieldName =>+ fieldName in COMPARABLE_CALL_RECORDING_FIELDS;++export const hasCallRecordingUpdateFieldChanges = ({+ callRecording,+ updateFields,+}: {+ callRecording: CallRecordingRecord;+ updateFields: CallRecordingUpdateFields;+}): boolean =>+ Object.entries(updateFields).some(([fieldName, updateFieldValue]) =>+ isComparableCallRecordingFieldName(fieldName)+ ? (callRecording[fieldName] ?? null) !== (updateFieldValue ?? null)+ : !isUndefined(updateFieldValue),+ );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.tsindex bdb322f5493..2a8abdb62a4 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@@ -13,6 +13,7 @@ import { buildCallRecorderPolicyResult } from 'src/logic-functions/domain/build-import { cancelCallRecordingRequest } from 'src/logic-functions/flows/cancel-call-recording-request.util';import { computeCallRecordingIdForMeeting } from 'src/logic-functions/domain/compute-call-recording-id-for-meeting.util';import { isUnavailableCallRecordingStatus } from 'src/logic-functions/domain/is-unavailable-call-recording-status.util';+import { hasCallRecordingUpdateFieldChanges } from 'src/logic-functions/domain/has-call-recording-update-field-changes.util';import {createCallRecording,type ScheduledCallRecordingFields,@@ -30,6 +31,21 @@ import { resolveCallRecordingTitle } from 'src/logic-functions/domain/resolve-caimport { updateCallRecording } from 'src/logic-functions/data/update-call-recording.util';import { type CallRecordingUpdateFields } from 'src/logic-functions/types/call-recording-update-fields.type';+type CallRecorderMeetingPolicyResolution = {+ meetingPolicyResults: CallRecorderPolicyResultForMeeting[];+ calendarEventsById: Map<string, CalendarEventRecord>;+};++type CanceledMeetingReconciliation = {+ reconciliationResult: CallRecorderReconciliationResult;+ calendarEventIdsToClearRecordingOn: string[];+};++type ActiveMeetingReconciliation = {+ reconciliationResult: CallRecorderReconciliationResult;+ calendarEventIdsToMarkRecordingOn: string[];+};+export const reconcileCallRecorderForCalendarEventIds = async ({client,calendarEventIds,@@ -41,7 +57,7 @@ export const reconcileCallRecorderForCalendarEventIds = async ({removedOccurrences?: RemovedCallRecorderOccurrence[];now?: Date;}): Promise<CallRecorderReconciliationResult[]> => {- const meetingPolicyResults =+ const { meetingPolicyResults, calendarEventsById } =await resolveCallRecorderPolicyResultsForMeetings({client,calendarEventIds,@@ -52,6 +68,7 @@ export const reconcileCallRecorderForCalendarEventIds = async ({return reconcileCallRecorderForMeetingOccurrences({client,meetingPolicyResults,+ calendarEventsById,removedOccurrences,});};@@ -66,7 +83,7 @@ const resolveCallRecorderPolicyResultsForMeetings = async ({calendarEventIds: string[];removedOccurrences?: RemovedCallRecorderOccurrence[];now?: Date;-}): Promise<CallRecorderPolicyResultForMeeting[]> => {+}): Promise<CallRecorderMeetingPolicyResolution> => {const changedCalendarEvents = await fetchCalendarEventsByIds(client,getUniqueSortedIds(calendarEventIds),@@ -96,7 +113,7 @@ const resolveCallRecorderPolicyResultsForMeetings = async ({}if (affectedMeetingKeys.size === 0) {- return [];+ return { meetingPolicyResults: [], calendarEventsById: new Map() };}const occurrenceSiblingEvents = await fetchCalendarEventsByStartsAtValues(@@ -156,99 +173,256 @@ const resolveCallRecorderPolicyResultsForMeetings = async ({});}- return meetingPolicyResults;+ return {+ meetingPolicyResults,+ calendarEventsById: new Map(+ [...occurrenceSiblingEvents, ...changedCalendarEvents].map(+ (calendarEvent) => [calendarEvent.id, calendarEvent],+ ),+ ),+ };};const reconcileCallRecorderForMeetingOccurrences = async ({client,meetingPolicyResults,+ calendarEventsById,removedOccurrences = [],}: {client: CoreApiClient;meetingPolicyResults: CallRecorderPolicyResultForMeeting[];+ calendarEventsById: Map<string, CalendarEventRecord>;removedOccurrences?: RemovedCallRecorderOccurrence[];}): Promise<CallRecorderReconciliationResult[]> => {const removedCalendarEventIdsByMeetingKey =buildRemovedCalendarEventIdsByMeetingKey(removedOccurrences);- const reconciliationResults: CallRecorderReconciliationResult[] = [];- const orderedMeetingPolicyResults = [- ...meetingPolicyResults.filter(+ const callRecordingsByCalendarEventId = groupCallRecordingsByCalendarEventId(+ await findCallRecordingsByCalendarEventIds(+ client,+ getUniqueSortedIds([+ ...meetingPolicyResults.flatMap(+ (meetingPolicyResult) => meetingPolicyResult.calendarEventIds,+ ),+ ...removedOccurrences.map(+ (removedOccurrence) => removedOccurrence.calendarEventId,+ ),+ ]),+ ),+ );+ const activeMeetingPolicyResults = meetingPolicyResults.filter(+ (meetingPolicyResult) => meetingPolicyResult.shouldRequestBot,+ );+ const activeMeetingCallRecordingIds = activeMeetingPolicyResults.map(+ (meetingPolicyResult) =>+ computeCallRecordingIdForMeeting(meetingPolicyResult.realMeetingKey),+ );+ const policyManagedCallRecordingsById = new Map(+ (+ await findCallRecordingsByIds(+ client,+ meetingPolicyResults.map((meetingPolicyResult) =>+ computeCallRecordingIdForMeeting(meetingPolicyResult.realMeetingKey),+ ),+ )+ ).map((callRecording) => [callRecording.id, callRecording]),+ );+ const canceledMeetingReconciliations = await reconcileCanceledMeetings({+ client,+ meetingPolicyResults: meetingPolicyResults.filter((meetingPolicyResult) => !meetingPolicyResult.shouldRequestBot,),- ...meetingPolicyResults.filter(- (meetingPolicyResult) => meetingPolicyResult.shouldRequestBot,+ removedCalendarEventIdsByMeetingKey,+ callRecordingsByCalendarEventId,+ policyManagedCallRecordingsById,+ activeMeetingCallRecordingIds: new Set(activeMeetingCallRecordingIds),+ });++ await clearCanceledMeetingsRecordingOn(+ client,+ canceledMeetingReconciliations.flatMap(+ (canceledMeetingReconciliation) =>+ canceledMeetingReconciliation.calendarEventIdsToClearRecordingOn,),- ];+ );- for (const meetingPolicyResult of orderedMeetingPolicyResults) {- const removedCalendarEventIds =- removedCalendarEventIdsByMeetingKey.get(- meetingPolicyResult.realMeetingKey,- ) ?? [];+ const activeMeetingReconciliations = await reconcileActiveMeetings({+ client,+ meetingPolicyResults: activeMeetingPolicyResults,+ calendarEventsById,+ removedCalendarEventIdsByMeetingKey,+ callRecordingsByCalendarEventId,+ policyManagedCallRecordingsById,+ });++ await markActiveMeetingsRecordingOn(+ client,+ activeMeetingReconciliations.flatMap(+ (activeMeetingReconciliation) =>+ activeMeetingReconciliation.calendarEventIdsToMarkRecordingOn,+ ),+ );++ return [+ ...canceledMeetingReconciliations,+ ...activeMeetingReconciliations,+ ].map((meetingReconciliation) => meetingReconciliation.reconciliationResult);+};++const reconcileCanceledMeetings = async ({+ client,+ meetingPolicyResults,+ removedCalendarEventIdsByMeetingKey,+ callRecordingsByCalendarEventId,+ policyManagedCallRecordingsById,+ activeMeetingCallRecordingIds,+}: {+ client: CoreApiClient;+ meetingPolicyResults: CallRecorderPolicyResultForMeeting[];+ removedCalendarEventIdsByMeetingKey: Map<string, string[]>;+ callRecordingsByCalendarEventId: Map<string, CallRecordingRecord[]>;+ policyManagedCallRecordingsById: Map<string, CallRecordingRecord>;+ activeMeetingCallRecordingIds: Set<string>;+}): Promise<CanceledMeetingReconciliation[]> => {+ const callRecordingIdsCanceledInBatch = new Set<string>();+ const canceledMeetingReconciliations: CanceledMeetingReconciliation[] = [];++ for (const meetingPolicyResult of meetingPolicyResults) {+ const meetingCallRecordings = collectCanceledMeetingCallRecordings({+ realMeetingKey: meetingPolicyResult.realMeetingKey,+ calendarEventIds: [+ ...meetingPolicyResult.calendarEventIds,+ ...(removedCalendarEventIdsByMeetingKey.get(+ meetingPolicyResult.realMeetingKey,+ ) ?? []),+ ],+ callRecordingsByCalendarEventId,+ policyManagedCallRecordingsById,+ callRecordingIdsCanceledInBatch,+ activeMeetingCallRecordingIds,+ });+ const cancellableCallRecordings = meetingCallRecordings.filter(+ isCancellableCallRecording,+ );try {- reconciliationResults.push(- meetingPolicyResult.shouldRequestBot- ? await reconcileActiveMeeting({- client,- meetingPolicyResult,- removedCalendarEventIds,- })- : await reconcileCanceledMeeting({- client,- meetingPolicyResult,- removedCalendarEventIds,- }),+ canceledMeetingReconciliations.push(+ await reconcileCanceledMeeting({+ client,+ meetingPolicyResult,+ meetingCallRecordings,+ cancellableCallRecordings,+ callRecordingIdsCanceledInBatch,+ }),);} catch (error) {- const errorMessage =- error instanceof Error ? error.message : String(error);+ canceledMeetingReconciliations.push({+ reconciliationResult: buildFailedResult(+ meetingPolicyResult.realMeetingKey,+ error,+ ),+ calendarEventIdsToClearRecordingOn: [],+ });+ }+ }++ return canceledMeetingReconciliations;+};- console.error(- `[call-recorder] reconciliation failed for meeting ${meetingPolicyResult.realMeetingKey}: ${errorMessage}`,+const reconcileActiveMeetings = async ({+ client,+ meetingPolicyResults,+ calendarEventsById,+ removedCalendarEventIdsByMeetingKey,+ callRecordingsByCalendarEventId,+ policyManagedCallRecordingsById,+}: {+ client: CoreApiClient;+ meetingPolicyResults: CallRecorderPolicyResultForMeeting[];+ calendarEventsById: Map<string, CalendarEventRecord>;+ removedCalendarEventIdsByMeetingKey: Map<string, string[]>;+ callRecordingsByCalendarEventId: Map<string, CallRecordingRecord[]>;+ policyManagedCallRecordingsById: Map<string, CallRecordingRecord>;+}): Promise<ActiveMeetingReconciliation[]> => {+ const activeMeetingReconciliations: ActiveMeetingReconciliation[] = [];++ for (const meetingPolicyResult of meetingPolicyResults) {+ try {+ activeMeetingReconciliations.push(+ await reconcileActiveMeeting({+ client,+ meetingPolicyResult,+ calendarEventsById,+ policyManagedCallRecordingsById,+ meetingCallRecordings: collectCallRecordingsForCalendarEventIds({+ calendarEventIds: [+ ...meetingPolicyResult.calendarEventIds,+ ...meetingPolicyResult.requestingCalendarEventIds,+ ...(removedCalendarEventIdsByMeetingKey.get(+ meetingPolicyResult.realMeetingKey,+ ) ?? []),+ ],+ callRecordingsByCalendarEventId,+ }),+ }),);- reconciliationResults.push({- action: 'FAILED',- realMeetingKey: meetingPolicyResult.realMeetingKey,- errorMessage,+ } catch (error) {+ activeMeetingReconciliations.push({+ reconciliationResult: buildFailedResult(+ meetingPolicyResult.realMeetingKey,+ error,+ ),+ calendarEventIdsToMarkRecordingOn: [],});}}- return reconciliationResults;+ return activeMeetingReconciliations;};const reconcileActiveMeeting = async ({client,meetingPolicyResult,- removedCalendarEventIds,+ calendarEventsById,+ policyManagedCallRecordingsById,+ meetingCallRecordings,}: {client: CoreApiClient;meetingPolicyResult: CallRecorderPolicyResultForMeeting;- removedCalendarEventIds: string[];-}): Promise<CallRecorderReconciliationResult> => {+ calendarEventsById: Map<string, CalendarEventRecord>;+ policyManagedCallRecordingsById: Map<string, CallRecordingRecord>;+ meetingCallRecordings: CallRecordingRecord[];+}): Promise<ActiveMeetingReconciliation> => {const representativeCalendarEventId = getUniqueSortedIds(meetingPolicyResult.requestingCalendarEventIds,)[0];if (isUndefined(representativeCalendarEventId)) {- return buildSkippedResult(meetingPolicyResult.realMeetingKey);+ return {+ reconciliationResult: buildSkippedResult(+ meetingPolicyResult.realMeetingKey,+ ),+ calendarEventIdsToMarkRecordingOn: [],+ };}- const representativeCalendarEvent = (- await fetchCalendarEventsByIds(client, [representativeCalendarEventId])- )[0];+ const representativeCalendarEvent = calendarEventsById.get(+ representativeCalendarEventId,+ );if (isUndefined(representativeCalendarEvent)) {- return buildSkippedResult(meetingPolicyResult.realMeetingKey);+ return {+ reconciliationResult: buildSkippedResult(+ meetingPolicyResult.realMeetingKey,+ ),+ calendarEventIdsToMarkRecordingOn: [],+ };}const callRecordingId = computeCallRecordingIdForMeeting(meetingPolicyResult.realMeetingKey,);- const existingCallRecording = (- await findCallRecordingsByIds(client, [callRecordingId])- )[0];+ const existingCallRecording =+ policyManagedCallRecordingsById.get(callRecordingId);if (!isUndefined(existingCallRecording)) {const reconciliationResult = await updatePolicyManagedCallRecording({@@ -258,22 +432,27 @@ const reconcileActiveMeeting = async ({realMeetingKey: meetingPolicyResult.realMeetingKey,});- await markRequestingCalendarEventsRecordingOn(client, meetingPolicyResult);-- return reconciliationResult;+ return {+ reconciliationResult,+ calendarEventIdsToMarkRecordingOn: getCalendarEventIdsToMarkRecordingOn({+ meetingPolicyResult,+ reconciliationResult,+ }),+ };}- const manualOpenCallRecording = await findManualOpenCallRecording({- client,- meetingPolicyResult,- removedCalendarEventIds,- });+ const manualOpenCallRecording = findManualOpenCallRecording(+ meetingCallRecordings,+ );if (!isUndefined(manualOpenCallRecording)) {return {- action: 'SKIPPED',- realMeetingKey: meetingPolicyResult.realMeetingKey,- callRecordingId: manualOpenCallRecording.id,+ reconciliationResult: {+ action: 'SKIPPED',+ realMeetingKey: meetingPolicyResult.realMeetingKey,+ callRecordingId: manualOpenCallRecording.id,+ },+ calendarEventIdsToMarkRecordingOn: [],};}@@ -284,23 +463,40 @@ const reconcileActiveMeeting = async ({realMeetingKey: meetingPolicyResult.realMeetingKey,});- await markRequestingCalendarEventsRecordingOn(client, meetingPolicyResult);-- return reconciliationResult;+ return {+ reconciliationResult,+ calendarEventIdsToMarkRecordingOn: getCalendarEventIdsToMarkRecordingOn({+ meetingPolicyResult,+ reconciliationResult,+ }),+ };};-const markRequestingCalendarEventsRecordingOn = async (+const getCalendarEventIdsToMarkRecordingOn = ({+ meetingPolicyResult,+ reconciliationResult,+}: {+ meetingPolicyResult: CallRecorderPolicyResultForMeeting;+ reconciliationResult: CallRecorderReconciliationResult;+}): string[] =>+ reconciliationResult.action === 'SKIPPED'+ ? []+ : meetingPolicyResult.requestingCalendarEventIds.filter(+ (calendarEventId) =>+ !meetingPolicyResult.calendarEventIdsWithRecordingOn.includes(+ calendarEventId,+ ),+ );++const markActiveMeetingsRecordingOn = async (client: CoreApiClient,- meetingPolicyResult: CallRecorderPolicyResultForMeeting,+ calendarEventIds: string[],): Promise<void> => {try {- await markCalendarEventsRecordingOn(- client,- meetingPolicyResult.requestingCalendarEventIds,- );+ await markCalendarEventsRecordingOn(client, calendarEventIds);} catch (error) {console.warn(- `[call-recorder] failed to mark the calendar events of meeting ${meetingPolicyResult.realMeetingKey} as recording on: ${+ `[call-recorder] failed to mark ${calendarEventIds.length} calendar events as recording on: ${error instanceof Error ? error.message : String(error)}`,);@@ -318,25 +514,73 @@ const updatePolicyManagedCallRecording = async ({representativeCalendarEvent: CalendarEventRecord;realMeetingKey: string;}): Promise<CallRecorderReconciliationResult> => {- await updateCallRecording(client, {- id: existingCallRecording.id,- data: buildPolicyManagedCallRecordingUpdateFields({+ const callRecording = hasCallRecordingUpdateFieldChanges({+ callRecording: existingCallRecording,+ updateFields: buildPolicyManagedCallRecordingUpdateFields({existingCallRecording,calendarEvent: representativeCalendarEvent,}),- });+ })+ ? await writeCurrentPolicyManagedCallRecordingChanges({+ client,+ callRecordingId: existingCallRecording.id,+ calendarEvent: representativeCalendarEvent,+ })+ : existingCallRecording;++ if (isUndefined(callRecording)) {+ return buildSkippedResult(realMeetingKey);+ }+await rescheduleCallRecordingBot(client, {- callRecording: existingCallRecording,+ callRecording,calendarEvent: representativeCalendarEvent,});return {action: 'UPDATED',realMeetingKey,- callRecordingId: existingCallRecording.id,+ callRecordingId: callRecording.id,};};+const writeCurrentPolicyManagedCallRecordingChanges = async ({+ client,+ callRecordingId,+ calendarEvent,+}: {+ client: CoreApiClient;+ callRecordingId: string;+ calendarEvent: CalendarEventRecord;+}): Promise<CallRecordingRecord | undefined> => {+ const currentCallRecording = (+ await findCallRecordingsByIds(client, [callRecordingId])+ )[0];++ if (isUndefined(currentCallRecording)) {+ return undefined;+ }++ const updateFields = buildPolicyManagedCallRecordingUpdateFields({+ existingCallRecording: currentCallRecording,+ calendarEvent,+ });++ if (+ hasCallRecordingUpdateFieldChanges({+ callRecording: currentCallRecording,+ updateFields,+ })+ ) {+ await updateCallRecording(client, {+ id: currentCallRecording.id,+ data: updateFields,+ });+ }++ return currentCallRecording;+};+const createPolicyManagedCallRecording = async ({client,callRecordingId,@@ -401,26 +645,10 @@ const createPolicyManagedCallRecording = async ({};};-const findManualOpenCallRecording = async ({- client,- meetingPolicyResult,- removedCalendarEventIds,-}: {- client: CoreApiClient;- meetingPolicyResult: CallRecorderPolicyResultForMeeting;- removedCalendarEventIds: string[];-}): Promise<CallRecordingRecord | undefined> => {- const calendarEventIds = getUniqueSortedIds([- ...meetingPolicyResult.calendarEventIds,- ...meetingPolicyResult.requestingCalendarEventIds,- ...removedCalendarEventIds,- ]);- const callRecordings = await findCallRecordingsByCalendarEventIds(- client,- calendarEventIds,- );-- return [...callRecordings]+const findManualOpenCallRecording = (+ meetingCallRecordings: CallRecordingRecord[],+): CallRecordingRecord | undefined =>+ [...meetingCallRecordings].sort((firstCallRecording, secondCallRecording) =>firstCallRecording.id.localeCompare(secondCallRecording.id),)@@ -429,101 +657,85 @@ const findManualOpenCallRecording = async ({callRecording.status !== CallRecordingStatus.COMPLETED &&isUndefined(callRecording.recordingRequestStatus),);-};const reconcileCanceledMeeting = async ({client,meetingPolicyResult,- removedCalendarEventIds,+ meetingCallRecordings,+ cancellableCallRecordings,+ callRecordingIdsCanceledInBatch,}: {client: CoreApiClient;meetingPolicyResult: CallRecorderPolicyResultForMeeting;- removedCalendarEventIds: string[];-}): Promise<CallRecorderReconciliationResult> => {- const calendarEventIds = getUniqueSortedIds([- ...meetingPolicyResult.calendarEventIds,- ...removedCalendarEventIds,- ]);- const linkedCallRecordings = await findCallRecordingsByCalendarEventIds(- client,- calendarEventIds,- );- const orphanedPolicyManagedCallRecordings = (- await findCallRecordingsByIds(client, [- computeCallRecordingIdForMeeting(meetingPolicyResult.realMeetingKey),- ])- ).filter((callRecording) => isUndefined(callRecording.calendarEventId));- const meetingCallRecordings = [- ...linkedCallRecordings,- ...orphanedPolicyManagedCallRecordings,- ];- const cancellableCallRecordings = meetingCallRecordings.filter(- (callRecording) =>- callRecording.status === CallRecordingStatus.SCHEDULED &&- callRecording.recordingRequestStatus ===- CallRecordingRequestStatus.REQUESTED,- );-+ meetingCallRecordings: CallRecordingRecord[];+ cancellableCallRecordings: CallRecordingRecord[];+ callRecordingIdsCanceledInBatch: Set<string>;+}): Promise<CanceledMeetingReconciliation> => {for (const callRecording of cancellableCallRecordings) {await cancelCallRecordingRequest({client,callRecording,});+ callRecordingIdsCanceledInBatch.add(callRecording.id);}const cancellableCallRecordingIds = new Set(cancellableCallRecordings.map((callRecording) => callRecording.id),);-- await clearRecordingOnForMeeting({- client,- meetingPolicyResult,- remainingCallRecordings: meetingCallRecordings.filter(- (callRecording) => !cancellableCallRecordingIds.has(callRecording.id),- ),- });+ const calendarEventIdsToClearRecordingOn =+ getCalendarEventIdsToClearRecordingOn({+ meetingPolicyResult,+ remainingCallRecordings: meetingCallRecordings.filter(+ (callRecording) => !cancellableCallRecordingIds.has(callRecording.id),+ ),+ });if (cancellableCallRecordings.length === 0) {- return buildSkippedResult(meetingPolicyResult.realMeetingKey);+ return {+ reconciliationResult: buildSkippedResult(+ meetingPolicyResult.realMeetingKey,+ ),+ calendarEventIdsToClearRecordingOn,+ };}return {- action: 'CANCELED',- realMeetingKey: meetingPolicyResult.realMeetingKey,- callRecordingId: cancellableCallRecordings[0].id,+ reconciliationResult: {+ action: 'CANCELED',+ realMeetingKey: meetingPolicyResult.realMeetingKey,+ callRecordingId: cancellableCallRecordings[0].id,+ },+ calendarEventIdsToClearRecordingOn,};};-const clearRecordingOnForMeeting = async ({- client,+const getCalendarEventIdsToClearRecordingOn = ({meetingPolicyResult,remainingCallRecordings,}: {- client: CoreApiClient;meetingPolicyResult: CallRecorderPolicyResultForMeeting;remainingCallRecordings: CallRecordingRecord[];-}): Promise<void> => {+}): string[] => {const hasCallRecordingOutsideThisCancellation = remainingCallRecordings.some((callRecording) =>callRecording.recordingRequestStatus !==CallRecordingRequestStatus.CANCELED,);- if (- meetingPolicyResult.calendarEventIdsWithRecordingOn.length === 0 ||- hasCallRecordingOutsideThisCancellation- ) {- return;- }+ return hasCallRecordingOutsideThisCancellation+ ? []+ : meetingPolicyResult.calendarEventIdsWithRecordingOn;+};+const clearCanceledMeetingsRecordingOn = async (+ client: CoreApiClient,+ calendarEventIds: string[],+): Promise<void> => {try {- await clearCalendarEventsRecordingOn(- client,- meetingPolicyResult.calendarEventIdsWithRecordingOn,- );+ await clearCalendarEventsRecordingOn(client, calendarEventIds);} catch (error) {console.warn(- `[call-recorder] failed to clear the recording preference of meeting ${meetingPolicyResult.realMeetingKey}: ${+ `[call-recorder] failed to clear the recording preference of ${calendarEventIds.length} calendar events: ${error instanceof Error ? error.message : String(error)}`,);@@ -585,6 +797,118 @@ const buildRemovedCalendarEventIdsByMeetingKey = (return calendarEventIdsByMeetingKey;};+const groupCallRecordingsByCalendarEventId = (+ callRecordings: CallRecordingRecord[],+): Map<string, CallRecordingRecord[]> => {+ const callRecordingsByCalendarEventId = new Map<+ string,+ CallRecordingRecord[]+ >();++ for (const callRecording of callRecordings) {+ if (isUndefined(callRecording.calendarEventId)) {+ continue;+ }++ callRecordingsByCalendarEventId.set(callRecording.calendarEventId, [+ ...(callRecordingsByCalendarEventId.get(callRecording.calendarEventId) ??+ []),+ callRecording,+ ]);+ }++ return callRecordingsByCalendarEventId;+};++const collectCallRecordingsForCalendarEventIds = ({+ calendarEventIds,+ callRecordingsByCalendarEventId,+}: {+ calendarEventIds: string[];+ callRecordingsByCalendarEventId: Map<string, CallRecordingRecord[]>;+}): CallRecordingRecord[] =>+ getUniqueSortedIds(calendarEventIds).flatMap(+ (calendarEventId) =>+ callRecordingsByCalendarEventId.get(calendarEventId) ?? [],+ );++const collectOrphanedPolicyManagedCallRecordings = ({+ realMeetingKey,+ policyManagedCallRecordingsById,+}: {+ realMeetingKey: string;+ policyManagedCallRecordingsById: Map<string, CallRecordingRecord>;+}): CallRecordingRecord[] => {+ const policyManagedCallRecording = policyManagedCallRecordingsById.get(+ computeCallRecordingIdForMeeting(realMeetingKey),+ );++ return !isUndefined(policyManagedCallRecording) &&+ isUndefined(policyManagedCallRecording.calendarEventId)+ ? [policyManagedCallRecording]+ : [];+};++const collectCanceledMeetingCallRecordings = ({+ realMeetingKey,+ calendarEventIds,+ callRecordingsByCalendarEventId,+ policyManagedCallRecordingsById,+ callRecordingIdsCanceledInBatch,+ activeMeetingCallRecordingIds,+}: {+ realMeetingKey: string;+ calendarEventIds: string[];+ callRecordingsByCalendarEventId: Map<string, CallRecordingRecord[]>;+ policyManagedCallRecordingsById: Map<string, CallRecordingRecord>;+ callRecordingIdsCanceledInBatch: Set<string>;+ activeMeetingCallRecordingIds: Set<string>;+}): CallRecordingRecord[] =>+ [+ ...collectCallRecordingsForCalendarEventIds({+ calendarEventIds,+ callRecordingsByCalendarEventId,+ }),+ ...collectOrphanedPolicyManagedCallRecordings({+ realMeetingKey,+ policyManagedCallRecordingsById,+ }),+ ]+ .filter(+ (callRecording) => !activeMeetingCallRecordingIds.has(callRecording.id),+ )+ .map((callRecording) =>+ callRecordingIdsCanceledInBatch.has(callRecording.id)+ ? {+ ...callRecording,+ recordingRequestStatus: CallRecordingRequestStatus.CANCELED,+ }+ : callRecording,+ );++const isCancellableCallRecording = (+ callRecording: CallRecordingRecord,+): boolean =>+ callRecording.status === CallRecordingStatus.SCHEDULED &&+ callRecording.recordingRequestStatus === CallRecordingRequestStatus.REQUESTED;++const buildFailedResult = (+ realMeetingKey: string,+ error: unknown,+): CallRecorderReconciliationResult => {+ const errorMessage = error instanceof Error ? error.message : String(error);++ console.error(+ `[call-recorder] reconciliation failed for meeting ${realMeetingKey}: ${errorMessage}`,+ );++ return {+ action: 'FAILED',+ realMeetingKey,+ errorMessage,+ };+};+const buildSkippedResult = (realMeetingKey: string,): CallRecorderReconciliationResult => ({diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reschedule-call-recording-bot.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reschedule-call-recording-bot.util.tsindex f4ed992ea8b..cd03597d0dd 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reschedule-call-recording-bot.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/reschedule-call-recording-bot.util.ts@@ -6,6 +6,7 @@ import { type MeetingRecording } from 'src/logic-functions/types/meeting-recordiimport { buildRecallRoutingMetadata } from 'src/logic-functions/domain/build-recall-routing-metadata.util';import { computeRecallBotJoinAt } from 'src/logic-functions/domain/compute-recall-bot-join-at.util';import { enqueuePreJoinCreditCheck } from 'src/logic-functions/data/enqueue-pre-join-credit-check.util';+import { findCallRecordingsByIds } from 'src/logic-functions/data/find-call-recordings-by-ids.util';import { getCurrentWorkspaceId } from 'src/logic-functions/data/get-current-workspace-id.util';import { rescheduleRecallBot } from 'src/logic-functions/recall-api/reschedule-recall-bot.util';import { updateCallRecording } from 'src/logic-functions/data/update-call-recording.util';@@ -66,6 +67,17 @@ export const rescheduleCallRecordingBot = async (// confirmed gone), so clearing it lets recovery schedule directly instead// of treating the row as an ambiguous attempt.if (rescheduleResult.status === RECALL_API_NOT_FOUND_STATUS) {+ const currentCallRecording = (+ await findCallRecordingsByIds(client, [callRecording.id])+ )[0];++ if (+ isUndefined(currentCallRecording) ||+ currentCallRecording.externalBotId !== externalBotId+ ) {+ return;+ }+await updateCallRecording(client, {id: callRecording.id,data: {