Skip to content

The open alternative to Salesforce, designed for AI.

last-contact: drop the calendar cron and cut API calls under the shared rate limit (#27313)

martmull99855193764e
diff --git a/packages/twenty-apps/public/last-contact/CHANGELOG.md b/packages/twenty-apps/public/last-contact/CHANGELOG.md
index 13b3b425ba9..a230b9f4ccd 100644
--- a/packages/twenty-apps/public/last-contact/CHANGELOG.md
+++ b/packages/twenty-apps/public/last-contact/CHANGELOG.md
@@ -1,5 +1,17 @@
# Changelog
+## 1.8.0
+
+All installs of the app share one API rate limit, 500 calls per minute across every workspace. This version is about spending far fewer of those calls.
+
+- **No more calendar cron.** The 5-minute cron ran in every workspace in the same minute and made at least one API call each time, even with nothing to do. With about 1500 installs, that alone used more than the limit. Meetings are now scheduled instead:
+ - When a participant is linked to a meeting that has not started yet, or when a meeting's start time changes or it is un-canceled, the app enqueues one delayed job for the meeting's 5-minute slot. A meeting that has already started is applied right away instead. The job runs just after the slot ends and updates last contact for that slot's meetings. Enqueuing a job costs no API call, all meetings in a slot share one job, and a slot with no meeting linked to a person costs one call.
+ - Enqueued jobs can be delayed by at most 7 days, so meetings more than 6 days out are reached through a horizon job. It runs every 3 days, schedules the meetings that came within reach, and enqueues the next run only while meetings remain further out. A workspace with no upcoming meetings runs nothing.
+ - Every install and upgrade schedules the upcoming meetings and applies meetings from the last hour, so meetings linked before this version are not missed.
+ - A meeting's last contact still updates within about 6 minutes of its start: the job runs 1 minute after the end of its 5-minute slot.
+- **Fewer calls per email or meeting batch: at most 5 instead of 8.** A person's company and opportunities are read nested in the same query as the person, which costs no extra call. Recomputing an opportunity's last contact also reads its point of contact nested: 2 calls instead of 3.
+- **Retries that respect the rate limit.** A rate-limited call now waits for the server's `retryAfterMs`, capped at 60 seconds, when it is longer than the backoff. Once a function has waited 2 minutes in total, it hands the job back to the queue to retry later, instead of failing it or holding a worker.
+
## 1.7.0
- Keep the app's fields off the record timeline. The app's fields are frequently rewritten during email and meeting syncs, and each write used to add an `updated Last contact` entry to the person, company or opportunity timeline, burying everything else. All 23 fields now declare `isAuditLogged: false`, so their values still update but no timeline activity is recorded for them. Entries written before this version stay on the timeline.
diff --git a/packages/twenty-apps/public/last-contact/package.json b/packages/twenty-apps/public/last-contact/package.json
index b66a9d910d8..cc8855d5450 100644
--- a/packages/twenty-apps/public/last-contact/package.json
+++ b/packages/twenty-apps/public/last-contact/package.json
@@ -1,6 +1,6 @@
{
"name": "@twentyhq/last-contact",
- "version": "1.7.0",
+ "version": "1.8.0",
"license": "MIT",
"engines": {
"node": "^24.5.0",
diff --git a/packages/twenty-apps/public/last-contact/src/__tests__/last-contact.integration-test.ts b/packages/twenty-apps/public/last-contact/src/__tests__/last-contact.integration-test.ts
index 8e353dc7991..15436d83c83 100644
--- a/packages/twenty-apps/public/last-contact/src/__tests__/last-contact.integration-test.ts
+++ b/packages/twenty-apps/public/last-contact/src/__tests__/last-contact.integration-test.ts
@@ -1,18 +1,36 @@
import { CoreApiClient } from 'twenty-client-sdk/core';
import { MetadataApiClient } from 'twenty-client-sdk/metadata';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-
-import { APPLICATION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { enqueueJobsMock } = vi.hoisted(() => ({ enqueueJobsMock: vi.fn() }));
+vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ enqueueJobs: enqueueJobsMock,
+}));
+
+import {
+ APPLICATION_UNIVERSAL_IDENTIFIER,
+ MEETING_SLOT_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+} from 'src/constants/universal-identifiers';
import onCalendarInteraction from 'src/logic-functions/on-calendar-interaction';
import onCompanyCreated from 'src/logic-functions/on-company-created';
+import onMeetingHorizonReached from 'src/logic-functions/on-meeting-horizon-reached';
+import onMeetingSlotReached from 'src/logic-functions/on-meeting-slot-reached';
import onEmailInteraction from 'src/logic-functions/on-email-interaction';
import onOpportunityCreated from 'src/logic-functions/on-opportunity-created';
import onOpportunityUpdated from 'src/logic-functions/on-opportunity-updated';
import onPersonUpdated from 'src/logic-functions/on-person-updated';
+import { buildPersonAggregates } from 'src/utils/person-last-contact-aggregation';
const calendarHandler = onCalendarInteraction.config.handler as (
batch: unknown,
) => Promise<void>;
+const meetingSlotHandler = onMeetingSlotReached.config.handler as (payload: {
+ slotStart: string;
+ slotEnd: string;
+}) => Promise<void>;
+const meetingHorizonHandler = onMeetingHorizonReached.config
+ .handler as () => Promise<void>;
const emailHandler = onEmailInteraction.config.handler as (
batch: unknown,
) => Promise<void>;
@@ -636,6 +654,9 @@ describe('last contact handlers', () => {
});
createdParticipantIds.push(participantId);
+ enqueueJobsMock.mockClear();
+ enqueueJobsMock.mockResolvedValue({ enqueued: true });
+
await calendarHandler(
calendarBatch(participantId, personId, calendarEventId),
);
@@ -643,6 +664,70 @@ describe('last contact handlers', () => {
expect(
(await getPersonLastContact(client, personId)).lastContactAt,
).toBeNull();
+ expect(enqueueJobsMock).toHaveBeenCalledTimes(1);
+ expect(enqueueJobsMock.mock.calls[0][0]).toMatchObject({
+ logicFunctionUniversalIdentifier:
+ MEETING_SLOT_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ });
+ const [{ payload }] = enqueueJobsMock.mock.calls[0][0].jobs;
+ expect(asTime(payload.slotStart)).toBeLessThanOrEqual(asTime(startsAt)!);
+ expect(asTime(payload.slotEnd)).toBeGreaterThan(asTime(startsAt)!);
+ });
+
+ it('should apply the meetings of a slot once it is reached', async () => {
+ const startsAt = new Date(Date.now() - 5 * 60 * 1000).toISOString();
+ const personId = await createPerson(client);
+ createdPersonIds.push(personId);
+ const calendarEventId = await createCalendarEvent(client, { startsAt });
+ createdCalendarEventIds.push(calendarEventId);
+ const participantId = await createCalendarEventParticipant(client, {
+ calendarEventId,
+ personId,
+ });
+ createdParticipantIds.push(participantId);
+
+ await meetingSlotHandler({
+ slotStart: new Date(Date.parse(startsAt) - 60 * 1000).toISOString(),
+ slotEnd: new Date(Date.parse(startsAt) + 60 * 1000).toISOString(),
+ });
+
+ const lastContact = await getPersonLastContact(client, personId);
+ expect(asTime(lastContact.lastContactAt)).toBe(asTime(startsAt));
+ expect(lastContact.lastContactItemCalendarEventId).toBe(calendarEventId);
+ });
+
+ it('should schedule upcoming person meetings when the horizon is reached', async () => {
+ const startsAt = new Date(Date.now() + 60 * 60 * 1000).toISOString();
+ const personId = await createPerson(client);
+ createdPersonIds.push(personId);
+ const calendarEventId = await createCalendarEvent(client, { startsAt });
+ createdCalendarEventIds.push(calendarEventId);
+ const participantId = await createCalendarEventParticipant(client, {
+ calendarEventId,
+ personId,
+ });
+ createdParticipantIds.push(participantId);
+
+ enqueueJobsMock.mockClear();
+ enqueueJobsMock.mockResolvedValue({ enqueued: true });
+
+ await meetingHorizonHandler();
+
+ const scheduledSlots = enqueueJobsMock.mock.calls
+ .map(([input]) => input)
+ .filter(
+ (input) =>
+ input.logicFunctionUniversalIdentifier ===
+ MEETING_SLOT_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ )
+ .map((input) => input.jobs[0].payload);
+ expect(
+ scheduledSlots.some(
+ ({ slotStart, slotEnd }) =>
+ asTime(slotStart)! <= asTime(startsAt)! &&
+ asTime(slotEnd)! > asTime(startsAt)!,
+ ),
+ ).toBe(true);
});
it('should not set lastContactAt when the past calendar event is canceled', async () => {
@@ -724,6 +809,36 @@ describe('last contact handlers', () => {
});
});
+ it('aggregates a person backfill from nested participants', async () => {
+ const workspaceMemberId = await getWorkspaceMemberId(client);
+ const personId = await createPerson(client);
+ createdPersonIds.push(personId);
+ const receivedAt = new Date(Date.now() - 5 * DAY_IN_MS).toISOString();
+ const startsAt = new Date(Date.now() - 7 * DAY_IN_MS).toISOString();
+
+ const messageId = await recordEmail({
+ personId,
+ workspaceMemberId,
+ receivedAt,
+ direction: 'outbound',
+ });
+ const calendarEventId = await recordMeeting({
+ personId,
+ workspaceMemberId,
+ startsAt,
+ });
+
+ const aggregate = (await buildPersonAggregates(client, [personId])).get(
+ personId,
+ );
+
+ expect(aggregate?.lastEmail?.id).toBe(messageId);
+ expect(aggregate?.lastMeeting?.id).toBe(calendarEventId);
+ expect(aggregate?.lastContactById).toBe(workspaceMemberId);
+ expect(asTime(aggregate?.lastOutboundAt)).toBe(asTime(receivedAt));
+ expect(asTime(aggregate?.lastInboundAt)).toBe(asTime(startsAt));
+ });
+
it('keeps last contact writes off the person timeline', async () => {
const workspaceMemberId = await getWorkspaceMemberId(client);
const personId = await createPerson(client);
diff --git a/packages/twenty-apps/public/last-contact/src/constants/calendar-cron-interval-minutes.ts b/packages/twenty-apps/public/last-contact/src/constants/calendar-cron-interval-minutes.ts
deleted file mode 100644
index cb2c820a5c2..00000000000
--- a/packages/twenty-apps/public/last-contact/src/constants/calendar-cron-interval-minutes.ts
+++ /dev/null
@@ -1 +0,0 @@
-export const CALENDAR_CRON_INTERVAL_MINUTES = 5;
diff --git a/packages/twenty-apps/public/last-contact/src/constants/calendar-cron-security-overlap-minutes.ts b/packages/twenty-apps/public/last-contact/src/constants/calendar-cron-security-overlap-minutes.ts
deleted file mode 100644
index e4bd02064f8..00000000000
--- a/packages/twenty-apps/public/last-contact/src/constants/calendar-cron-security-overlap-minutes.ts
+++ /dev/null
@@ -1 +0,0 @@
-export const CALENDAR_CRON_SECURITY_OVERLAP_MINUTES = 10;
diff --git a/packages/twenty-apps/public/last-contact/src/constants/meeting-schedule.ts b/packages/twenty-apps/public/last-contact/src/constants/meeting-schedule.ts
new file mode 100644
index 00000000000..49b36741f5a
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/constants/meeting-schedule.ts
@@ -0,0 +1,11 @@
+export const MEETING_SLOT_MS = 5 * 60 * 1000;
+
+export const MEETING_SLOT_JOB_DELAY_BUFFER_MS = 60 * 1000;
+
+export const MEETING_HORIZON_PERIOD_MS = 3 * 24 * 60 * 60 * 1000;
+
+export const MEETING_SCHEDULE_HORIZON_MS = 2 * MEETING_HORIZON_PERIOD_MS;
+
+export const MEETING_INSTALL_LOOKBACK_MS = 60 * 60 * 1000;
+
+export const MEETING_JOB_RETRY_LIMIT = 3;
diff --git a/packages/twenty-apps/public/last-contact/src/constants/universal-identifiers.ts b/packages/twenty-apps/public/last-contact/src/constants/universal-identifiers.ts
index e222fff1a76..ee59b8f89a0 100644
--- a/packages/twenty-apps/public/last-contact/src/constants/universal-identifiers.ts
+++ b/packages/twenty-apps/public/last-contact/src/constants/universal-identifiers.ts
@@ -11,8 +11,12 @@ export const CALENDAR_INTERACTION_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
'ff4e9fc0-a5d3-4a3d-87f9-81c23598589e';
export const BACKFILL_POST_INSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
'c94f671f-b3fa-47a2-8de6-dde94d13f8d1';
-export const CALENDAR_EVENT_STARTED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
- 'c56013d7-208b-46e2-a91f-27f481645591';
+export const MEETING_HORIZON_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
+ '7eaf9a7a-f41f-40d8-bc08-197f2f3b8abc';
+export const MEETING_SLOT_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
+ '1df4b5ea-5cee-4509-858e-fbaec39e1d1c';
+export const CALENDAR_EVENT_RESCHEDULED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
+ '1586c04a-b60e-4758-b5e6-6fbebd394591';
export const OPPORTUNITY_CREATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
'6659b54f-2f46-412b-aa7d-03aa9f1c5133';
export const OPPORTUNITY_UPDATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/backfill-last-contact.test.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/backfill-last-contact.test.ts
index b52cea82f5f..be96dedecee 100644
--- a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/backfill-last-contact.test.ts
+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/backfill-last-contact.test.ts
@@ -2,11 +2,17 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const {
queryMock,
+ scheduleUpcomingPersonMeetingsMock,
+ collectPersonMeetingParticipantsMock,
+ applyMeetingInteractionsMock,
backfillPeopleMock,
backfillOpportunitiesMock,
backfillCompaniesMock,
} = vi.hoisted(() => ({
queryMock: vi.fn(),
+ scheduleUpcomingPersonMeetingsMock: vi.fn(),
+ collectPersonMeetingParticipantsMock: vi.fn(),
+ applyMeetingInteractionsMock: vi.fn(),
backfillPeopleMock: vi.fn(),
backfillOpportunitiesMock: vi.fn(),
backfillCompaniesMock: vi.fn(),
@@ -18,6 +24,18 @@ vi.mock('twenty-client-sdk/core', () => ({
}),
}));
+vi.mock('src/utils/schedule-meetings', () => ({
+ scheduleUpcomingPersonMeetings: scheduleUpcomingPersonMeetingsMock,
+}));
+
+vi.mock('src/utils/collect-person-meeting-participants', () => ({
+ collectPersonMeetingParticipants: collectPersonMeetingParticipantsMock,
+}));
+
+vi.mock('src/utils/apply-meeting-interactions', () => ({
+ applyMeetingInteractions: applyMeetingInteractionsMock,
+}));
+
vi.mock('src/utils/backfill-settings', () => ({
getBackfillBatchSize: () => 2,
}));
@@ -67,6 +85,13 @@ const recordBatch =
beforeEach(() => {
events = [];
+ scheduleUpcomingPersonMeetingsMock.mockReset();
+ scheduleUpcomingPersonMeetingsMock.mockResolvedValue(undefined);
+ collectPersonMeetingParticipantsMock.mockReset();
+ collectPersonMeetingParticipantsMock.mockResolvedValue([]);
+ applyMeetingInteractionsMock.mockReset();
+ applyMeetingInteractionsMock.mockResolvedValue([]);
+
queryMock.mockReset();
queryMock.mockImplementation(async (query: ConnectionQuery) => {
const [queryField] = Object.keys(query);
@@ -140,4 +165,23 @@ describe('backfill-last-contact', () => {
expect(queryMock).not.toHaveBeenCalled();
});
+
+ it('should schedule upcoming meetings and apply the last hour of meetings on every upgrade', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-06-12T12:00:00.000Z'));
+
+ await handler({ previousVersion: '1.7.0', newVersion: '1.8.0' });
+
+ expect(scheduleUpcomingPersonMeetingsMock).toHaveBeenCalledTimes(1);
+ expect(collectPersonMeetingParticipantsMock).toHaveBeenCalledWith(
+ expect.anything(),
+ {
+ from: new Date('2026-06-12T11:00:00.000Z'),
+ to: new Date('2026-06-12T12:00:00.000Z'),
+ },
+ );
+ expect(applyMeetingInteractionsMock).toHaveBeenCalledTimes(1);
+
+ vi.useRealTimers();
+ });
});
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-calendar-event-rescheduled.test.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-calendar-event-rescheduled.test.ts
new file mode 100644
index 00000000000..fba30b68e6d
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-calendar-event-rescheduled.test.ts
@@ -0,0 +1,142 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const {
+ enqueueJobsMock,
+ queryMock,
+ mutationMock,
+ applyMeetingInteractionsMock,
+} = vi.hoisted(() => ({
+ enqueueJobsMock: vi.fn(),
+ queryMock: vi.fn(),
+ mutationMock: vi.fn(),
+ applyMeetingInteractionsMock: vi.fn(),
+}));
+vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ enqueueJobs: enqueueJobsMock,
+}));
+vi.mock('src/utils/apply-meeting-interactions', () => ({
+ applyMeetingInteractions: applyMeetingInteractionsMock,
+}));
+vi.mock('twenty-client-sdk/core', () => ({
+ CoreApiClient: vi.fn(function () {
+ return { query: queryMock, mutation: mutationMock };
+ }),
+}));
+
+import onCalendarEventRescheduled from '../on-calendar-event-rescheduled';
+
+const NOW = '2026-06-12T12:00:00.000Z';
+
+const handler = onCalendarEventRescheduled.config.handler as (
+ batch: unknown,
+) => Promise<void>;
+
+const buildBatch = (
+ calendarEvents: { startsAt: string | null; isCanceled: boolean }[],
+) => ({
+ name: 'calendarEvent.updated',
+ events: calendarEvents.map((after, index) => ({
+ recordId: `event-${index}`,
+ properties: { updatedFields: ['startsAt'], after },
+ })),
+});
+
+const emptyPage = {
+ edges: [],
+ pageInfo: { hasNextPage: false, endCursor: null },
+};
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(NOW));
+ enqueueJobsMock.mockReset();
+ enqueueJobsMock.mockResolvedValue({ enqueued: true });
+ queryMock.mockReset();
+ queryMock.mockResolvedValue({ calendarEventParticipants: emptyPage });
+ mutationMock.mockReset();
+ applyMeetingInteractionsMock.mockReset();
+ applyMeetingInteractionsMock.mockResolvedValue([]);
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('on-calendar-event-rescheduled', () => {
+ it('should be valid and batch start time updates', () => {
+ expect(onCalendarEventRescheduled.success).toBe(true);
+ expect(
+ onCalendarEventRescheduled.config.databaseEventTriggerSettings,
+ ).toEqual({
+ eventName: 'calendarEvent.updated',
+ updatedFields: ['startsAt', 'isCanceled'],
+ batchMode: true,
+ });
+ });
+
+ it('should schedule the new slot of upcoming meetings without calling the core API', async () => {
+ await handler(
+ buildBatch([
+ { startsAt: '2026-06-12T14:20:00.000Z', isCanceled: false },
+ { startsAt: '2026-06-12T14:24:00.000Z', isCanceled: false },
+ { startsAt: '2026-06-12T16:00:00.000Z', isCanceled: true },
+ { startsAt: null, isCanceled: false },
+ ]),
+ );
+
+ expect(queryMock).not.toHaveBeenCalled();
+ expect(enqueueJobsMock).toHaveBeenCalledTimes(1);
+ expect(enqueueJobsMock.mock.calls[0][0].jobs[0].payload).toEqual({
+ slotStart: '2026-06-12T14:20:00.000Z',
+ slotEnd: '2026-06-12T14:25:00.000Z',
+ });
+ });
+
+ it('should apply a meeting moved into the past right away', async () => {
+ queryMock.mockResolvedValue({
+ calendarEventParticipants: {
+ edges: [
+ {
+ node: {
+ personId: 'person-1',
+ calendarEventId: 'event-0',
+ calendarEvent: { startsAt: '2026-06-12T10:00:00.000Z' },
+ },
+ },
+ ],
+ pageInfo: { hasNextPage: false, endCursor: null },
+ },
+ });
+
+ await handler(
+ buildBatch([
+ { startsAt: '2026-06-12T10:00:00.000Z', isCanceled: false },
+ { startsAt: '2026-06-12T09:00:00.000Z', isCanceled: true },
+ ]),
+ );
+
+ expect(queryMock).toHaveBeenCalledTimes(1);
+ expect(
+ queryMock.mock.calls[0][0].calendarEventParticipants.__args.filter,
+ ).toEqual({
+ and: [
+ { personId: { is: 'NOT_NULL' } },
+ { calendarEventId: { in: ['event-0'] } },
+ { calendarEvent: { startsAt: { lt: NOW } } },
+ { calendarEvent: { isCanceled: { eq: false } } },
+ ],
+ });
+ expect(applyMeetingInteractionsMock).toHaveBeenCalledWith(
+ expect.anything(),
+ [
+ {
+ personId: 'person-1',
+ calendarEventId: 'event-0',
+ startsAt: '2026-06-12T10:00:00.000Z',
+ },
+ ],
+ );
+ expect(enqueueJobsMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-calendar-event-started.test.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-calendar-event-started.test.ts
deleted file mode 100644
index 30af0fa59e6..00000000000
--- a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-calendar-event-started.test.ts
+++ /dev/null
@@ -1,195 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-const { queryMock, mutationMock } = vi.hoisted(() => ({
- queryMock: vi.fn(),
- mutationMock: vi.fn(),
-}));
-vi.mock('twenty-client-sdk/core', () => ({
- CoreApiClient: vi.fn(function () {
- return { query: queryMock, mutation: mutationMock };
- }),
-}));
-
-import onCalendarEventStarted from '../on-calendar-event-started';
-
-const PERSON_ID_1 = '11111111-1111-1111-1111-111111111111';
-const PERSON_ID_2 = '22222222-2222-2222-2222-222222222222';
-const PAST_EVENT_STARTS_AT = '2026-06-10T09:00:00.000Z';
-
-const handler = onCalendarEventStarted.config.handler as () => Promise<void>;
-
-type Page = {
- edges: { node: Record<string, unknown> }[];
- pageInfo: { hasNextPage: boolean; endCursor: string | null };
-};
-
-const singlePage = (nodes: Record<string, unknown>[]): Page => ({
- edges: nodes.map((node) => ({ node })),
- pageInfo: { hasNextPage: false, endCursor: null },
-});
-
-const setupQueryMock = ({
- calendarEventsPages,
- participantsPages,
- startedParticipants = [],
-}: {
- calendarEventsPages: Page[];
- participantsPages: Page[];
- startedParticipants?: Record<string, unknown>[];
-}) => {
- const remainingEventsPages = [...calendarEventsPages];
- const remainingParticipantsPages = [...participantsPages];
-
- queryMock.mockImplementation((query) => {
- if (query.calendarEvents) {
- return Promise.resolve({ calendarEvents: remainingEventsPages.shift() });
- }
-
- if (query.calendarEventParticipants) {
- return Promise.resolve({
- calendarEventParticipants: query.calendarEventParticipants.edges.node
- .calendarEvent
- ? singlePage(startedParticipants)
- : remainingParticipantsPages.shift(),
- });
- }
-
- if (query.person) {
- return Promise.resolve({ person: null });
- }
-
- if (query.people) {
- const requestedIds: string[] = query.people.__args.filter.id.in;
- return Promise.resolve({
- people: singlePage(
- query.people.edges.node.companyId
- ? requestedIds.map((id) => ({ id, companyId: null }))
- : requestedIds.map((id) => ({ id })),
- ),
- });
- }
-
- if (query.companies) {
- return Promise.resolve({ companies: singlePage([]) });
- }
-
- return Promise.resolve({ opportunities: singlePage([]) });
- });
-};
-
-beforeEach(() => {
- queryMock.mockReset();
- mutationMock.mockReset();
- mutationMock.mockResolvedValue({});
-});
-
-describe('on-calendar-event-started definition', () => {
- it('should be valid and run on a cron schedule', () => {
- expect(onCalendarEventStarted.success).toBe(true);
- expect(onCalendarEventStarted.config.cronTriggerSettings).toEqual({
- pattern: '*/5 * * * *',
- });
- });
-});
-
-describe('on-calendar-event-started handler', () => {
- it('should paginate calendar events past the query record cap', async () => {
- setupQueryMock({
- calendarEventsPages: [
- {
- edges: [{ node: { id: 'event-1' } }],
- pageInfo: { hasNextPage: true, endCursor: 'events-cursor-1' },
- },
- singlePage([{ id: 'event-2' }]),
- ],
- participantsPages: [singlePage([])],
- });
-
- await handler();
-
- const calendarEventsCalls = queryMock.mock.calls.filter(
- ([query]) => query.calendarEvents,
- );
- expect(calendarEventsCalls).toHaveLength(2);
- expect(calendarEventsCalls[0][0].calendarEvents.__args.first).toBe(200);
- expect(
- calendarEventsCalls[0][0].calendarEvents.__args.after,
- ).toBeUndefined();
- expect(calendarEventsCalls[1][0].calendarEvents.__args.after).toBe(
- 'events-cursor-1',
- );
-
- const participantsCall = queryMock.mock.calls.find(
- ([query]) =>
- query.calendarEventParticipants?.__args.filter.calendarEventId,
- );
- expect(
- participantsCall?.[0].calendarEventParticipants.__args.filter
- .calendarEventId,
- ).toEqual({ in: ['event-1', 'event-2'] });
- });
-
- it('should paginate participants and update each person once', async () => {
- setupQueryMock({
- calendarEventsPages: [singlePage([{ id: 'event-1' }])],
- participantsPages: [
- {
- edges: [
- { node: { personId: PERSON_ID_1, calendarEventId: 'event-1' } },
- { node: { personId: null, calendarEventId: 'event-1' } },
- ],
- pageInfo: { hasNextPage: true, endCursor: 'participants-cursor-1' },
- },
- singlePage([
- { personId: PERSON_ID_1, calendarEventId: 'event-1' },
- { personId: PERSON_ID_2, calendarEventId: 'event-1' },
- ]),
- ],
- startedParticipants: [
- {
- calendarEventId: 'event-1',
- isOrganizer: null,
- workspaceMemberId: null,
- calendarEvent: {
- startsAt: PAST_EVENT_STARTS_AT,
- isCanceled: false,
- },
- },
- ],
- });
-
- await handler();
-
- const participantsByEventCalls = queryMock.mock.calls.filter(
- ([query]) =>
- query.calendarEventParticipants?.__args.filter.calendarEventId &&
- !query.calendarEventParticipants?.edges.node.calendarEvent,
- );
- expect(participantsByEventCalls).toHaveLength(2);
- expect(
- participantsByEventCalls[1][0].calendarEventParticipants.__args.after,
- ).toBe('participants-cursor-1');
-
- const personUpserts = mutationMock.mock.calls.filter(
- ([mutation]) => mutation.createPeople,
- );
- expect(personUpserts).toHaveLength(1);
- expect(personUpserts[0][0].createPeople.__args.data).toHaveLength(2);
- expect(personUpserts[0][0].createPeople.__args.data[0]).toMatchObject({
- lastContactAt: PAST_EVENT_STARTS_AT,
- lastContactItemCalendarEventId: 'event-1',
- });
- });
-
- it('should do nothing when no event started in the time window', async () => {
- setupQueryMock({
- calendarEventsPages: [singlePage([])],
- participantsPages: [],
- });
-
- await handler();
-
- expect(queryMock).toHaveBeenCalledTimes(1);
- expect(mutationMock).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-calendar-interaction.test.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-calendar-interaction.test.ts
index de6cedc2bab..c0f6fe3e45f 100644
--- a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-calendar-interaction.test.ts
+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-calendar-interaction.test.ts
@@ -1,8 +1,12 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-const { queryMock, mutationMock } = vi.hoisted(() => ({
+const { queryMock, mutationMock, enqueueJobsMock } = vi.hoisted(() => ({
queryMock: vi.fn(),
mutationMock: vi.fn(),
+ enqueueJobsMock: vi.fn(),
+}));
+vi.mock('twenty-sdk/logic-function', () => ({
+ enqueueJobs: enqueueJobsMock,
}));
vi.mock('twenty-client-sdk/core', () => ({
CoreApiClient: vi.fn(function () {
@@ -16,6 +20,7 @@ const PERSON_ID = '11111111-1111-1111-1111-111111111111';
const CALENDAR_EVENT_ID = '22222222-2222-2222-2222-222222222222';
const NOW = '2026-06-12T12:00:00.000Z';
const PAST_EVENT_STARTS_AT = '2026-06-10T09:00:00.000Z';
+const UPCOMING_EVENT_STARTS_AT = '2026-06-12T14:20:00.000Z';
const handler = onCalendarInteraction.config.handler as (
batch: unknown,
@@ -79,6 +84,8 @@ beforeEach(() => {
queryMock.mockReset();
mutationMock.mockReset();
mutationMock.mockResolvedValue({});
+ enqueueJobsMock.mockReset();
+ enqueueJobsMock.mockResolvedValue({ enqueued: true });
});
afterEach(() => {
@@ -133,6 +140,33 @@ describe('on-calendar-interaction handler', () => {
]);
});
+ it('schedules a meeting that has not started yet instead of applying it', async () => {
+ setupQueryMock([
+ {
+ calendarEventId: CALENDAR_EVENT_ID,
+ isOrganizer: null,
+ workspaceMemberId: null,
+ calendarEvent: {
+ startsAt: UPCOMING_EVENT_STARTS_AT,
+ isCanceled: false,
+ },
+ },
+ ]);
+
+ await handler(
+ buildBatch([
+ { personId: PERSON_ID, calendarEventId: CALENDAR_EVENT_ID },
+ ]),
+ );
+
+ expect(mutationMock).not.toHaveBeenCalled();
+ expect(enqueueJobsMock).toHaveBeenCalledTimes(1);
+ expect(enqueueJobsMock.mock.calls[0][0].jobs[0].payload).toEqual({
+ slotStart: '2026-06-12T14:20:00.000Z',
+ slotEnd: '2026-06-12T14:25:00.000Z',
+ });
+ });
+
it('should do nothing when no participant has both a person and a calendar event', async () => {
await handler(
buildBatch([
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-meeting-horizon-reached.test.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-meeting-horizon-reached.test.ts
new file mode 100644
index 00000000000..c9c92f74b92
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-meeting-horizon-reached.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from 'vitest';
+
+import onMeetingHorizonReached from '../on-meeting-horizon-reached';
+
+describe('on-meeting-horizon-reached', () => {
+ it('should be valid and have no trigger of its own', () => {
+ expect(onMeetingHorizonReached.success).toBe(true);
+ expect(onMeetingHorizonReached.config.cronTriggerSettings).toBeUndefined();
+ expect(
+ onMeetingHorizonReached.config.databaseEventTriggerSettings,
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-meeting-slot-reached.test.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-meeting-slot-reached.test.ts
new file mode 100644
index 00000000000..a1a1d457ba6
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-meeting-slot-reached.test.ts
@@ -0,0 +1,60 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { queryMock, mutationMock } = vi.hoisted(() => ({
+ queryMock: vi.fn(),
+ mutationMock: vi.fn(),
+}));
+vi.mock('twenty-client-sdk/core', () => ({
+ CoreApiClient: vi.fn(function () {
+ return { query: queryMock, mutation: mutationMock };
+ }),
+}));
+
+import onMeetingSlotReached from '../on-meeting-slot-reached';
+
+const SLOT_START = '2026-06-12T15:00:00.000Z';
+const SLOT_END = '2026-06-12T15:15:00.000Z';
+
+const handler = onMeetingSlotReached.config.handler as (payload: {
+ slotStart: string;
+ slotEnd: string;
+}) => Promise<void>;
+
+beforeEach(() => {
+ queryMock.mockReset();
+ mutationMock.mockReset();
+});
+
+describe('on-meeting-slot-reached', () => {
+ it('should be valid and have no trigger of its own', () => {
+ expect(onMeetingSlotReached.success).toBe(true);
+ expect(onMeetingSlotReached.config.cronTriggerSettings).toBeUndefined();
+ expect(
+ onMeetingSlotReached.config.databaseEventTriggerSettings,
+ ).toBeUndefined();
+ });
+
+ it('should re-read the person meetings of its slot in one call and stop when none remain', async () => {
+ queryMock.mockResolvedValue({
+ calendarEventParticipants: {
+ edges: [],
+ pageInfo: { hasNextPage: false, endCursor: null },
+ },
+ });
+
+ await handler({ slotStart: SLOT_START, slotEnd: SLOT_END });
+
+ expect(queryMock).toHaveBeenCalledTimes(1);
+ expect(
+ queryMock.mock.calls[0][0].calendarEventParticipants.__args.filter,
+ ).toEqual({
+ and: [
+ { personId: { is: 'NOT_NULL' } },
+ { calendarEvent: { startsAt: { gte: SLOT_START } } },
+ { calendarEvent: { startsAt: { lt: SLOT_END } } },
+ { calendarEvent: { isCanceled: { eq: false } } },
+ ],
+ });
+ expect(mutationMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-opportunity-created.test.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-opportunity-created.test.ts
index 56828458f3b..213d6ae8401 100644
--- a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-opportunity-created.test.ts
+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-opportunity-created.test.ts
@@ -13,7 +13,6 @@ vi.mock('twenty-client-sdk/core', () => ({
import onOpportunityCreated from '../on-opportunity-created';
const OPPORTUNITY_ID = '11111111-1111-1111-1111-111111111111';
-const PERSON_ID = '22222222-2222-2222-2222-222222222222';
const MESSAGE_ID = '33333333-3333-3333-3333-333333333333';
const OCCURRED_AT = '2026-06-10T09:00:00.000Z';
@@ -42,24 +41,18 @@ describe('on-opportunity-created', () => {
});
it('computes the last contact from the point of contact', async () => {
- queryMock.mockImplementation((query) =>
- query.opportunities
- ? Promise.resolve({
- opportunities: buildPage([
- { id: OPPORTUNITY_ID, pointOfContactId: PERSON_ID },
- ]),
- })
- : Promise.resolve({
- people: buildPage([
- {
- id: PERSON_ID,
- lastContactAt: OCCURRED_AT,
- lastContactItemMessage: { id: MESSAGE_ID },
- lastContactItemCalendarEvent: null,
- },
- ]),
- }),
- );
+ queryMock.mockResolvedValue({
+ opportunities: buildPage([
+ {
+ id: OPPORTUNITY_ID,
+ pointOfContact: {
+ lastContactAt: OCCURRED_AT,
+ lastContactItemMessageId: MESSAGE_ID,
+ lastContactItemCalendarEventId: null,
+ },
+ },
+ ]),
+ });
await handler({
name: 'opportunity.created',
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-last-contact.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-last-contact.ts
index 0aab74536ca..bad6a6d40c3 100644
--- a/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-last-contact.ts
+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-last-contact.ts
@@ -2,8 +2,12 @@ import { CoreApiClient } from 'twenty-client-sdk/core';
import { definePostInstallLogicFunction, type InstallPayload } from 'twenty-sdk/define';
import { compare } from 'semver'
+import { MEETING_INSTALL_LOOKBACK_MS } from 'src/constants/meeting-schedule';
import { BACKFILL_POST_INSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
import { getBackfillBatchSize } from 'src/utils/backfill-settings';
+import { applyMeetingInteractions } from 'src/utils/apply-meeting-interactions';
+import { collectPersonMeetingParticipants } from 'src/utils/collect-person-meeting-participants';
+import { scheduleUpcomingPersonMeetings } from 'src/utils/schedule-meetings';
import { runLastContactBackfill } from 'src/utils/run-last-contact-backfill';
import { isDefined } from 'twenty-sdk/utils';
@@ -26,6 +30,17 @@ const handler = async ({
previousVersion,
newVersion
}: InstallPayload): Promise<object> => {
+ const client = new CoreApiClient();
+
+ await scheduleUpcomingPersonMeetings(client);
+
+ const recentlyStartedParticipants = await collectPersonMeetingParticipants(
+ client,
+ { from: new Date(Date.now() - MEETING_INSTALL_LOOKBACK_MS), to: new Date() },
+ );
+
+ await applyMeetingInteractions(client, recentlyStartedParticipants);
+
if(!shouldRunPostInstall({
previousVersion,
newVersion
@@ -40,7 +55,7 @@ const handler = async ({
JSON.stringify({ batchSize: getBackfillBatchSize() }),
);
- const phases = await runLastContactBackfill(new CoreApiClient());
+ const phases = await runLastContactBackfill(client);
return { outcome: 'completed', phases };
};
@@ -49,7 +64,7 @@ export default definePostInstallLogicFunction({
universalIdentifier: BACKFILL_POST_INSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
name: 'backfill-last-contact',
description:
- 'Backfills last-contact fields on people, then opportunities, then companies after installation, one batch of records at a time within this run.',
+ 'Schedules upcoming meetings, then backfills last-contact fields on people, then opportunities, then companies after installation, one batch of records at a time within this run.',
timeoutSeconds: 900,
shouldRunOnVersionUpgrade: true,
handler,
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/on-calendar-event-rescheduled.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/on-calendar-event-rescheduled.ts
new file mode 100644
index 00000000000..b3dd4bc1595
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/on-calendar-event-rescheduled.ts
@@ -0,0 +1,68 @@
+import {
+ defineLogicFunction,
+ type ObjectRecordUpdateEvent,
+} from 'twenty-sdk/define';
+import { type DatabaseEventBatchPayload } from 'twenty-sdk/logic-function';
+import { CoreApiClient } from 'twenty-client-sdk/core';
+
+import { BATCH_HANDLER_TIMEOUT_SECONDS } from 'src/constants/batch-handler-timeout-seconds';
+import { CALENDAR_EVENT_RESCHEDULED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { applyMeetingInteractions } from 'src/utils/apply-meeting-interactions';
+import { collectPersonMeetingParticipants } from 'src/utils/collect-person-meeting-participants';
+import { scheduleMeetings } from 'src/utils/schedule-meetings';
+
+type CalendarEventUpdate = {
+ startsAt?: string | null;
+ isCanceled?: boolean | null;
+};
+
+const handler = async (
+ batch: DatabaseEventBatchPayload<
+ ObjectRecordUpdateEvent<CalendarEventUpdate>
+ >,
+): Promise<void> => {
+ const now = new Date();
+ const upcomingMeetingStartsAts: string[] = [];
+ const startedCalendarEventIds: string[] = [];
+
+ for (const event of batch.events) {
+ const { startsAt, isCanceled } = event.properties.after ?? {};
+
+ if (!startsAt || isCanceled) {
+ continue;
+ }
+
+ if (Date.parse(startsAt) > now.getTime()) {
+ upcomingMeetingStartsAts.push(startsAt);
+ } else if (event.recordId) {
+ startedCalendarEventIds.push(event.recordId);
+ }
+ }
+
+ if (startedCalendarEventIds.length > 0) {
+ const client = new CoreApiClient();
+ const participants = await collectPersonMeetingParticipants(client, {
+ calendarEventIds: startedCalendarEventIds,
+ to: now,
+ });
+
+ await applyMeetingInteractions(client, participants);
+ }
+
+ await scheduleMeetings(upcomingMeetingStartsAts, now.getTime());
+};
+
+export default defineLogicFunction({
+ universalIdentifier:
+ CALENDAR_EVENT_RESCHEDULED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ name: 'on-calendar-event-rescheduled',
+ description:
+ "Schedules a meeting's new time slot when its start time changes or it is un-canceled, so last contact is updated once it starts, or applies it right away when it already started.",
+ timeoutSeconds: BATCH_HANDLER_TIMEOUT_SECONDS,
+ databaseEventTriggerSettings: {
+ eventName: 'calendarEvent.updated',
+ updatedFields: ['startsAt', 'isCanceled'],
+ batchMode: true,
+ },
+ handler,
+});
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/on-calendar-event-started.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/on-calendar-event-started.ts
deleted file mode 100644
index e8e4d0d7552..00000000000
--- a/packages/twenty-apps/public/last-contact/src/logic-functions/on-calendar-event-started.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import { defineLogicFunction } from 'twenty-sdk/define';
-import { CoreApiClient } from 'twenty-client-sdk/core';
-
-import { BATCH_HANDLER_TIMEOUT_SECONDS } from 'src/constants/batch-handler-timeout-seconds';
-import { CALENDAR_CRON_INTERVAL_MINUTES } from 'src/constants/calendar-cron-interval-minutes';
-import { CALENDAR_CRON_SECURITY_OVERLAP_MINUTES } from 'src/constants/calendar-cron-security-overlap-minutes';
-import { CALENDAR_EVENT_STARTED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
-import {
- applyMeetingInteractions,
- type CalendarEventParticipantLink,
-} from 'src/utils/apply-meeting-interactions';
-import { executeWithRetry } from 'src/utils/execute-with-retry';
-
-const QUERY_MAX_RECORDS = 200;
-
-const handler = async (): Promise<void> => {
- const client = new CoreApiClient();
-
- const now = new Date();
- const windowStart = new Date(
- now.getTime() -
- (CALENDAR_CRON_INTERVAL_MINUTES + CALENDAR_CRON_SECURITY_OVERLAP_MINUTES) *
- 60 *
- 1000,
- );
-
- const calendarEventIds: string[] = [];
- let calendarEventsCursor: string | undefined;
- let calendarEventsHasNextPage = true;
-
- while (calendarEventsHasNextPage) {
- const { calendarEvents } = await executeWithRetry(() =>
- client.query({
- calendarEvents: {
- __args: {
- filter: {
- and: [
- { startsAt: { gt: windowStart.toISOString() } },
- { startsAt: { lte: now.toISOString() } },
- { isCanceled: { eq: false } },
- ],
- },
- first: QUERY_MAX_RECORDS,
- after: calendarEventsCursor,
- },
- edges: {
- node: {
- id: true,
- },
- },
- pageInfo: {
- hasNextPage: true,
- endCursor: true,
- },
- },
- }),
- );
-
- calendarEventIds.push(
- ...(calendarEvents?.edges.map(
- (edge: { node: { id: string } }) => edge.node.id,
- ) ?? []),
- );
- calendarEventsHasNextPage = calendarEvents?.pageInfo.hasNextPage ?? false;
- calendarEventsCursor = calendarEvents?.pageInfo.endCursor ?? undefined;
- }
-
- if (calendarEventIds.length === 0) {
- return;
- }
-
- const linkByKey = new Map<string, CalendarEventParticipantLink>();
- let participantsCursor: string | undefined;
- let participantsHasNextPage = true;
-
- while (participantsHasNextPage) {
- const { calendarEventParticipants } = await executeWithRetry(() =>
- client.query({
- calendarEventParticipants: {
- __args: {
- filter: { calendarEventId: { in: calendarEventIds } },
- first: QUERY_MAX_RECORDS,
- after: participantsCursor,
- },
- edges: {
- node: {
- personId: true,
- calendarEventId: true,
- },
- },
- pageInfo: {
- hasNextPage: true,
- endCursor: true,
- },
- },
- }),
- );
-
- for (const edge of calendarEventParticipants?.edges ?? []) {
- const { personId, calendarEventId } = edge.node;
-
- if (personId && calendarEventId) {
- linkByKey.set(`${personId}:${calendarEventId}`, {
- personId,
- calendarEventId,
- });
- }
- }
- participantsHasNextPage =
- calendarEventParticipants?.pageInfo.hasNextPage ?? false;
- participantsCursor =
- calendarEventParticipants?.pageInfo.endCursor ?? undefined;
- }
-
- await applyMeetingInteractions(client, [...linkByKey.values()]);
-};
-
-export default defineLogicFunction({
- universalIdentifier:
- CALENDAR_EVENT_STARTED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
- name: 'on-calendar-event-started',
- description:
- 'Updates last-contacted fields for participants of calendar events whose start time just passed.',
- timeoutSeconds: BATCH_HANDLER_TIMEOUT_SECONDS,
- cronTriggerSettings: {
- pattern: `*/${CALENDAR_CRON_INTERVAL_MINUTES} * * * *`,
- },
- handler,
-});
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/on-calendar-interaction.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/on-calendar-interaction.ts
index 13d27d2f49c..180b4bceae9 100644
--- a/packages/twenty-apps/public/last-contact/src/logic-functions/on-calendar-interaction.ts
+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/on-calendar-interaction.ts
@@ -11,6 +11,7 @@ import {
applyMeetingInteractions,
type CalendarEventParticipantLink,
} from 'src/utils/apply-meeting-interactions';
+import { scheduleMeetings } from 'src/utils/schedule-meetings';
type CalendarEventParticipantUpdate = {
personId?: string | null;
@@ -40,14 +41,19 @@ const handler = async (
return;
}
- await applyMeetingInteractions(new CoreApiClient(), [...linkByKey.values()]);
+ const upcomingMeetingStartsAts = await applyMeetingInteractions(
+ new CoreApiClient(),
+ [...linkByKey.values()],
+ );
+
+ await scheduleMeetings(upcomingMeetingStartsAts);
};
export default defineLogicFunction({
universalIdentifier: CALENDAR_INTERACTION_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
name: 'on-calendar-interaction',
description:
- "Updates a person's last-contacted fields, and the last contact on their company and opportunities, when a new calendar event participant is created (past events only).",
+ "Updates a person's last-contacted fields, and the last contact on their company and opportunities, when a new calendar event participant is created. Meetings that have not started yet are scheduled for when they do.",
timeoutSeconds: BATCH_HANDLER_TIMEOUT_SECONDS,
databaseEventTriggerSettings: {
eventName: 'calendarEventParticipant.updated',
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/on-meeting-horizon-reached.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/on-meeting-horizon-reached.ts
new file mode 100644
index 00000000000..5d41eae4d10
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/on-meeting-horizon-reached.ts
@@ -0,0 +1,20 @@
+import { defineLogicFunction } from 'twenty-sdk/define';
+import { CoreApiClient } from 'twenty-client-sdk/core';
+
+import { BATCH_HANDLER_TIMEOUT_SECONDS } from 'src/constants/batch-handler-timeout-seconds';
+import { MEETING_HORIZON_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { scheduleUpcomingPersonMeetings } from 'src/utils/schedule-meetings';
+
+const handler = async (): Promise<void> => {
+ await scheduleUpcomingPersonMeetings(new CoreApiClient());
+};
+
+export default defineLogicFunction({
+ universalIdentifier:
+ MEETING_HORIZON_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ name: 'on-meeting-horizon-reached',
+ description:
+ 'Schedules the meetings that came within reach of a delayed job, and the next run while meetings remain further out. Enqueued only when such meetings exist.',
+ timeoutSeconds: BATCH_HANDLER_TIMEOUT_SECONDS,
+ handler,
+});
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/on-meeting-slot-reached.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/on-meeting-slot-reached.ts
new file mode 100644
index 00000000000..d0af94ec4c5
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/on-meeting-slot-reached.ts
@@ -0,0 +1,37 @@
+import { defineLogicFunction } from 'twenty-sdk/define';
+import { CoreApiClient } from 'twenty-client-sdk/core';
+
+import { BATCH_HANDLER_TIMEOUT_SECONDS } from 'src/constants/batch-handler-timeout-seconds';
+import { MEETING_SLOT_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { applyMeetingInteractions } from 'src/utils/apply-meeting-interactions';
+import { collectPersonMeetingParticipants } from 'src/utils/collect-person-meeting-participants';
+import { type MeetingSlotPayload } from 'src/utils/schedule-meetings';
+
+const handler = async ({
+ slotStart,
+ slotEnd,
+}: MeetingSlotPayload): Promise<void> => {
+ const client = new CoreApiClient();
+
+ const participants = await collectPersonMeetingParticipants(client, {
+ from: new Date(slotStart),
+ to: new Date(slotEnd),
+ });
+
+ await applyMeetingInteractions(
+ client,
+ participants.map(({ personId, calendarEventId }) => ({
+ personId,
+ calendarEventId,
+ })),
+ );
+};
+
+export default defineLogicFunction({
+ universalIdentifier: MEETING_SLOT_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ name: 'on-meeting-slot-reached',
+ description:
+ 'Updates last-contact fields for participants of the meetings that started in a time slot. Enqueued with a delay when a meeting is scheduled.',
+ timeoutSeconds: BATCH_HANDLER_TIMEOUT_SECONDS,
+ handler,
+});
diff --git a/packages/twenty-apps/public/last-contact/src/utils/__tests__/apply-meeting-interactions.test.ts b/packages/twenty-apps/public/last-contact/src/utils/__tests__/apply-meeting-interactions.test.ts
index 6fdfd33eb28..ecb848f7a43 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/__tests__/apply-meeting-interactions.test.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/__tests__/apply-meeting-interactions.test.ts
@@ -200,7 +200,7 @@ describe('applyMeetingInteractions', () => {
});
});
- it('skips a meeting that has not started yet', async () => {
+ it('skips a meeting that has not started yet and returns its start time', async () => {
const { client, mutationMock } = buildClient([
buildParticipant({
calendarEventId: CALENDAR_EVENT_ID,
@@ -208,11 +208,12 @@ describe('applyMeetingInteractions', () => {
}),
]);
- await applyMeetingInteractions(client, [
+ const upcomingMeetingStartsAts = await applyMeetingInteractions(client, [
{ personId: PERSON_ID, calendarEventId: CALENDAR_EVENT_ID },
]);
expect(mutationMock).not.toHaveBeenCalled();
+ expect(upcomingMeetingStartsAts).toEqual([FUTURE_EVENT_STARTS_AT]);
});
it('skips a canceled meeting', async () => {
diff --git a/packages/twenty-apps/public/last-contact/src/utils/__tests__/execute-with-retry.test.ts b/packages/twenty-apps/public/last-contact/src/utils/__tests__/execute-with-retry.test.ts
index b6f2671a63a..aad3284a144 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/__tests__/execute-with-retry.test.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/__tests__/execute-with-retry.test.ts
@@ -1,7 +1,17 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';
+
import { executeWithRetry } from 'src/utils/execute-with-retry';
+const buildRateLimitedError = (retryAfterMs: number) =>
+ Object.assign(
+ new Error('Rate limit exceeded for application: 500 requests per 60s.'),
+ {
+ errors: [{ extensions: { code: 'RATE_LIMITED', retryAfterMs } }],
+ },
+ );
+
beforeEach(() => {
vi.useFakeTimers();
vi.spyOn(Math, 'random').mockReturnValue(0);
@@ -42,17 +52,35 @@ describe('executeWithRetry', () => {
expect(execute).toHaveBeenCalledTimes(1);
});
- it('gives up after exhausting retries', async () => {
+ it('hands the job back to the queue once the wait budget is spent', async () => {
const execute = vi
.fn()
.mockRejectedValue(new Error('Gateway time-out: origin overloaded'));
const promise = executeWithRetry(execute);
- const assertion = expect(promise).rejects.toThrow('Gateway time-out');
- await vi.advanceTimersByTimeAsync(60_000);
+ const assertion = expect(promise).rejects.toThrow(
+ RetryableLogicFunctionError,
+ );
+ await vi.advanceTimersByTimeAsync(120_000);
await assertion;
- expect(execute).toHaveBeenCalledTimes(5);
+ await expect(promise).rejects.toThrow('Gateway time-out');
+ expect(execute).toHaveBeenCalledTimes(8);
+ });
+
+ it('waits for the retryAfterMs of a rate-limited GraphQL error', async () => {
+ const execute = vi
+ .fn()
+ .mockRejectedValueOnce(buildRateLimitedError(15_000))
+ .mockResolvedValue('ok');
+
+ const promise = executeWithRetry(execute);
+ await vi.advanceTimersByTimeAsync(14_000);
+ expect(execute).toHaveBeenCalledTimes(1);
+
+ await vi.advanceTimersByTimeAsync(1_000);
+ await expect(promise).resolves.toBe('ok');
+ expect(execute).toHaveBeenCalledTimes(2);
});
it('waits for the server-provided retry_after when it exceeds the backoff', async () => {
diff --git a/packages/twenty-apps/public/last-contact/src/utils/__tests__/recompute-opportunity-last-contact.test.ts b/packages/twenty-apps/public/last-contact/src/utils/__tests__/recompute-opportunity-last-contact.test.ts
index 7bf34ae0d3f..77b0055d0c4 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/__tests__/recompute-opportunity-last-contact.test.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/__tests__/recompute-opportunity-last-contact.test.ts
@@ -4,7 +4,6 @@ import { recomputeOpportunitiesLastContact } from 'src/utils/recompute-opportuni
const OPPORTUNITY_ID = '11111111-1111-1111-1111-111111111111';
const OTHER_OPPORTUNITY_ID = '44444444-4444-4444-4444-444444444444';
-const PERSON_ID = '22222222-2222-2222-2222-222222222222';
const MESSAGE_ID = '33333333-3333-3333-3333-333333333333';
const OCCURRED_AT = '2026-06-10T09:00:00.000Z';
@@ -13,45 +12,33 @@ type Client = {
mutation: ReturnType<typeof vi.fn>;
};
-const buildPage = (nodes: Record<string, unknown>[]) => ({
- edges: nodes.map((node) => ({ node })),
- pageInfo: { hasNextPage: false, endCursor: null },
-});
+const POINT_OF_CONTACT = {
+ lastContactAt: OCCURRED_AT,
+ lastContactItemMessageId: MESSAGE_ID,
+ lastContactItemCalendarEventId: null,
+};
-const buildClient = ({
- opportunities = [],
- people = [],
-}: {
- opportunities?: Record<string, unknown>[];
- people?: Record<string, unknown>[];
-}): Client => ({
- query: vi.fn().mockImplementation((query) =>
- query.opportunities
- ? Promise.resolve({ opportunities: buildPage(opportunities) })
- : Promise.resolve({ people: buildPage(people) }),
- ),
+const buildClient = (opportunities: Record<string, unknown>[]): Client => ({
+ query: vi.fn().mockResolvedValue({
+ opportunities: {
+ edges: opportunities.map((node) => ({ node })),
+ pageInfo: { hasNextPage: false, endCursor: null },
+ },
+ }),
mutation: vi.fn().mockResolvedValue({}),
});
let client: Client;
beforeEach(() => {
- client = buildClient({});
+ client = buildClient([]);
});
describe('recomputeOpportunitiesLastContact', () => {
it('mirrors the point of contact last contact onto the opportunity', async () => {
- client = buildClient({
- opportunities: [{ id: OPPORTUNITY_ID, pointOfContactId: PERSON_ID }],
- people: [
- {
- id: PERSON_ID,
- lastContactAt: OCCURRED_AT,
- lastContactItemMessage: { id: MESSAGE_ID },
- lastContactItemCalendarEvent: null,
- },
- ],
- });
+ client = buildClient([
+ { id: OPPORTUNITY_ID, pointOfContact: POINT_OF_CONTACT },
+ ]);
await recomputeOpportunitiesLastContact(client as never, [OPPORTUNITY_ID]);
@@ -71,13 +58,10 @@ describe('recomputeOpportunitiesLastContact', () => {
});
it('clears the opportunity last contact when there is no point of contact', async () => {
- client = buildClient({
- opportunities: [{ id: OPPORTUNITY_ID, pointOfContactId: null }],
- });
+ client = buildClient([{ id: OPPORTUNITY_ID, pointOfContact: null }]);
await recomputeOpportunitiesLastContact(client as never, [OPPORTUNITY_ID]);
- expect(client.query).toHaveBeenCalledTimes(1);
expect(
client.mutation.mock.calls[0][0].createOpportunities.__args.data,
).toEqual([
@@ -90,28 +74,18 @@ describe('recomputeOpportunitiesLastContact', () => {
]);
});
- it('resolves a whole batch with one opportunity query, one people query and one write', async () => {
- client = buildClient({
- opportunities: [
- { id: OPPORTUNITY_ID, pointOfContactId: PERSON_ID },
- { id: OTHER_OPPORTUNITY_ID, pointOfContactId: PERSON_ID },
- ],
- people: [
- {
- id: PERSON_ID,
- lastContactAt: OCCURRED_AT,
- lastContactItemMessage: { id: MESSAGE_ID },
- lastContactItemCalendarEvent: null,
- },
- ],
- });
+ it('resolves a whole batch with one read and one write', async () => {
+ client = buildClient([
+ { id: OPPORTUNITY_ID, pointOfContact: POINT_OF_CONTACT },
+ { id: OTHER_OPPORTUNITY_ID, pointOfContact: POINT_OF_CONTACT },
+ ]);
await recomputeOpportunitiesLastContact(client as never, [
OPPORTUNITY_ID,
OTHER_OPPORTUNITY_ID,
]);
- expect(client.query).toHaveBeenCalledTimes(2);
+ expect(client.query).toHaveBeenCalledTimes(1);
expect(client.mutation).toHaveBeenCalledTimes(1);
expect(
client.mutation.mock.calls[0][0].createOpportunities.__args.data.map(
@@ -119,4 +93,10 @@ describe('recomputeOpportunitiesLastContact', () => {
),
).toEqual([OPPORTUNITY_ID, OTHER_OPPORTUNITY_ID]);
});
+
+ it('leaves out an opportunity that no longer exists', async () => {
+ await recomputeOpportunitiesLastContact(client as never, [OPPORTUNITY_ID]);
+
+ expect(client.mutation).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/twenty-apps/public/last-contact/src/utils/__tests__/schedule-meetings.test.ts b/packages/twenty-apps/public/last-contact/src/utils/__tests__/schedule-meetings.test.ts
new file mode 100644
index 00000000000..2cad4a56dbd
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/utils/__tests__/schedule-meetings.test.ts
@@ -0,0 +1,207 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { CoreApiClient } from 'twenty-client-sdk/core';
+
+const { enqueueJobsMock } = vi.hoisted(() => ({ enqueueJobsMock: vi.fn() }));
+vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ enqueueJobs: enqueueJobsMock,
+}));
+
+import {
+ MEETING_HORIZON_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ MEETING_SLOT_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+} from 'src/constants/universal-identifiers';
+import {
+ scheduleMeetings,
+ scheduleUpcomingPersonMeetings,
+} from 'src/utils/schedule-meetings';
+
+const NOW = '2026-06-12T12:00:00.000Z';
+const NEXT_PERIOD_START = '2026-06-15T00:00:00.000Z';
+const MINUTE_MS = 60 * 1000;
+
+const enqueuedFor = (logicFunctionUniversalIdentifier: string) =>
+ enqueueJobsMock.mock.calls
+ .map(([input]) => input)
+ .filter(
+ (input) =>
+ input.logicFunctionUniversalIdentifier ===
+ logicFunctionUniversalIdentifier,
+ );
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(NOW));
+ enqueueJobsMock.mockReset();
+ enqueueJobsMock.mockResolvedValue({ enqueued: true });
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('scheduleMeetings', () => {
+ it('should enqueue one job per slot, delayed until just after the slot ends', async () => {
+ await scheduleMeetings([
+ '2026-06-12T12:05:00.000Z',
+ '2026-06-12T12:09:59.000Z',
+ '2026-06-12T13:30:00.000Z',
+ ]);
+
+ expect(enqueueJobsMock).toHaveBeenCalledTimes(2);
+ expect(enqueueJobsMock.mock.calls[0][0]).toEqual({
+ logicFunctionUniversalIdentifier:
+ MEETING_SLOT_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ jobs: [
+ {
+ jobId: `meeting-slot-${Date.parse('2026-06-12T12:05:00.000Z')}`,
+ payload: {
+ slotStart: '2026-06-12T12:05:00.000Z',
+ slotEnd: '2026-06-12T12:10:00.000Z',
+ },
+ },
+ ],
+ delayMs: 11 * MINUTE_MS,
+ retryLimit: 3,
+ });
+ expect(enqueueJobsMock.mock.calls[1][0].delayMs).toBe(96 * MINUTE_MS);
+ });
+
+ it('should skip meetings whose slot already ended and unparsable start times', async () => {
+ await scheduleMeetings(['2026-06-12T11:59:00.000Z', 'not-a-date']);
+
+ expect(enqueueJobsMock).not.toHaveBeenCalled();
+ });
+
+ it('should still schedule a meeting that started within the current slot', async () => {
+ vi.setSystemTime(new Date('2026-06-12T12:02:00.000Z'));
+
+ await scheduleMeetings(['2026-06-12T12:01:00.000Z']);
+
+ expect(enqueueJobsMock).toHaveBeenCalledTimes(1);
+ expect(enqueueJobsMock.mock.calls[0][0].jobs[0].payload).toEqual({
+ slotStart: '2026-06-12T12:00:00.000Z',
+ slotEnd: '2026-06-12T12:05:00.000Z',
+ });
+ expect(enqueueJobsMock.mock.calls[0][0].delayMs).toBe(4 * MINUTE_MS);
+ });
+
+ it('should leave meetings past the 6 day horizon to one horizon job at the next period', async () => {
+ await scheduleMeetings([
+ '2026-06-18T12:00:01.000Z',
+ '2026-09-01T09:00:00.000Z',
+ ]);
+
+ expect(
+ enqueuedFor(MEETING_SLOT_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER),
+ ).toHaveLength(0);
+ expect(
+ enqueuedFor(MEETING_HORIZON_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER),
+ ).toEqual([
+ {
+ logicFunctionUniversalIdentifier:
+ MEETING_HORIZON_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ jobs: [
+ {
+ jobId: `meeting-horizon-${Date.parse(NEXT_PERIOD_START)}`,
+ payload: {},
+ },
+ ],
+ delayMs: Date.parse(NEXT_PERIOD_START) - Date.parse(NOW),
+ retryLimit: 3,
+ },
+ ]);
+ });
+});
+
+describe('scheduleMeetings time snapshot', () => {
+ it('should judge the horizon against the snapshot it is given, not a later clock', async () => {
+ const snapshot = Date.parse(NOW);
+ vi.setSystemTime(new Date(snapshot + MINUTE_MS));
+
+ await scheduleMeetings(['2026-06-18T12:00:30.000Z'], snapshot);
+
+ expect(
+ enqueuedFor(MEETING_SLOT_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER),
+ ).toHaveLength(0);
+ expect(
+ enqueuedFor(MEETING_HORIZON_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER),
+ ).toHaveLength(1);
+ });
+});
+
+describe('scheduleUpcomingPersonMeetings', () => {
+ const buildClient = (startsAts: string[], hasNextPage = false) => {
+ const queryMock = vi.fn().mockResolvedValue({
+ calendarEventParticipants: {
+ edges: startsAts.map((startsAt, index) => ({
+ node: {
+ personId: `person-${index}`,
+ calendarEventId: `event-${index}`,
+ calendarEvent: { startsAt },
+ },
+ })),
+ pageInfo: { hasNextPage, endCursor: 'cursor' },
+ },
+ });
+
+ return {
+ client: { query: queryMock } as unknown as CoreApiClient,
+ queryMock,
+ };
+ };
+
+ it('should read upcoming person meetings earliest first through the calendar event relation', async () => {
+ const { client, queryMock } = buildClient([]);
+
+ await scheduleUpcomingPersonMeetings(client);
+
+ expect(queryMock).toHaveBeenCalledTimes(1);
+ expect(queryMock.mock.calls[0][0].calendarEventParticipants.__args).toEqual(
+ {
+ filter: {
+ and: [
+ { personId: { is: 'NOT_NULL' } },
+ { calendarEvent: { startsAt: { gte: NOW } } },
+ { calendarEvent: { isCanceled: { eq: false } } },
+ ],
+ },
+ orderBy: [{ calendarEvent: { startsAt: 'AscNullsLast' } }],
+ first: 200,
+ after: undefined,
+ },
+ );
+ expect(enqueueJobsMock).not.toHaveBeenCalled();
+ });
+
+ it('should stop paging when the server repeats the same cursor', async () => {
+ const { client, queryMock } = buildClient(
+ ['2026-06-13T09:00:00.000Z'],
+ true,
+ );
+
+ await scheduleUpcomingPersonMeetings(client);
+
+ expect(queryMock).toHaveBeenCalledTimes(2);
+ expect(
+ queryMock.mock.calls[1][0].calendarEventParticipants.__args.after,
+ ).toBe('cursor');
+ });
+
+ it('should stop paging at the first meeting past the horizon and chain the next run', async () => {
+ const { client, queryMock } = buildClient(
+ ['2026-06-13T09:00:00.000Z', '2026-07-01T09:00:00.000Z'],
+ true,
+ );
+
+ await scheduleUpcomingPersonMeetings(client);
+
+ expect(queryMock).toHaveBeenCalledTimes(1);
+ expect(
+ enqueuedFor(MEETING_SLOT_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER),
+ ).toHaveLength(1);
+ expect(
+ enqueuedFor(MEETING_HORIZON_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER),
+ ).toHaveLength(1);
+ });
+});
diff --git a/packages/twenty-apps/public/last-contact/src/utils/__tests__/update-related-last-contact.test.ts b/packages/twenty-apps/public/last-contact/src/utils/__tests__/update-related-last-contact.test.ts
index 60a06f5db49..7cc5a84c16a 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/__tests__/update-related-last-contact.test.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/__tests__/update-related-last-contact.test.ts
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { type PersonLastContactState } from 'src/utils/update-person-last-contact';
import { updateRelatedLastContactForPeople } from 'src/utils/update-related-last-contact';
const PERSON_ID = '11111111-1111-1111-1111-111111111111';
@@ -9,6 +10,7 @@ const OLDER_MESSAGE_ID = '55555555-5555-5555-5555-555555555555';
const CALENDAR_EVENT_ID = '66666666-6666-6666-6666-666666666666';
const COMPANY_ID = '33333333-3333-3333-3333-333333333333';
const OPPORTUNITY_ID = '77777777-7777-7777-7777-777777777777';
+const OTHER_OPPORTUNITY_ID = '88888888-8888-8888-8888-888888888888';
const OCCURRED_AT = '2026-06-10T09:00:00.000Z';
const OLDER_OCCURRED_AT = '2026-06-01T09:00:00.000Z';
const NEWER_OCCURRED_AT = '2026-06-20T09:00:00.000Z';
@@ -18,47 +20,29 @@ type Client = {
mutation: ReturnType<typeof vi.fn>;
};
-const buildPage = (nodes: Record<string, unknown>[]) => ({
- edges: nodes.map((node) => ({ node })),
- pageInfo: { hasNextPage: false, endCursor: null },
-});
-
-const buildClient = ({
- people = [],
- companies = [{ id: COMPANY_ID, lastContactAt: null }],
- opportunities = [],
+const buildState = ({
+ company = { id: COMPANY_ID, lastContactAt: null },
+ opportunities = [{ id: OPPORTUNITY_ID, lastContactAt: null }],
+ totalCount = opportunities.length,
}: {
- people?: Record<string, unknown>[];
- companies?: Record<string, unknown>[];
- opportunities?: Record<string, unknown>[];
-}): Client => ({
- query: vi.fn().mockImplementation((query) => {
- if (query.people) {
- return Promise.resolve({ people: buildPage(people) });
- }
-
- if (query.companies) {
- return Promise.resolve({ companies: buildPage(companies) });
- }
-
- return Promise.resolve({ opportunities: buildPage(opportunities) });
- }),
- mutation: vi.fn().mockResolvedValue({}),
+ company?: { id: string; lastContactAt: string | null } | null;
+ opportunities?: { id: string; lastContactAt: string | null }[];
+ totalCount?: number | null;
+} = {}): PersonLastContactState => ({
+ company,
+ pointOfContactForOpportunities: {
+ totalCount,
+ edges: opportunities.map((node) => ({ node })),
+ },
});
let client: Client;
beforeEach(() => {
- client = buildClient({
- people: [{ id: PERSON_ID, companyId: COMPANY_ID }],
- opportunities: [
- {
- id: OPPORTUNITY_ID,
- pointOfContactId: PERSON_ID,
- lastContactAt: null,
- },
- ],
- });
+ client = {
+ query: vi.fn(),
+ mutation: vi.fn().mockResolvedValue({}),
+ };
});
const findUpsertData = (name: string) =>
@@ -68,9 +52,16 @@ const findUpsertData = (name: string) =>
const emailContact = (occurredAt = OCCURRED_AT, itemId = MESSAGE_ID) =>
new Map([[PERSON_ID, { occurredAt, itemId, kind: 'email' as const }]]);
+const stateFor = (state: PersonLastContactState) =>
+ new Map([[PERSON_ID, state]]);
+
describe('updateRelatedLastContactForPeople', () => {
- it('updates the company and point-of-contact opportunities for an email', async () => {
- await updateRelatedLastContactForPeople(client as never, emailContact());
+ it('updates the company and point-of-contact opportunities without reading them again', async () => {
+ await updateRelatedLastContactForPeople(
+ client as never,
+ emailContact(),
+ stateFor(buildState()),
+ );
const expectedData = {
lastContactAt: OCCURRED_AT,
@@ -78,6 +69,7 @@ describe('updateRelatedLastContactForPeople', () => {
lastContactItemCalendarEventId: null,
};
+ expect(client.query).not.toHaveBeenCalled();
expect(findUpsertData('createCompanies')).toEqual([
{ id: COMPANY_ID, ...expectedData },
]);
@@ -99,6 +91,7 @@ describe('updateRelatedLastContactForPeople', () => {
},
],
]),
+ stateFor(buildState()),
);
expect(findUpsertData('createCompanies')).toEqual([
@@ -112,37 +105,28 @@ describe('updateRelatedLastContactForPeople', () => {
});
it('leaves a company and an opportunity already contacted more recently alone', async () => {
- client = buildClient({
- people: [{ id: PERSON_ID, companyId: COMPANY_ID }],
- companies: [{ id: COMPANY_ID, lastContactAt: NEWER_OCCURRED_AT }],
- opportunities: [
- {
- id: OPPORTUNITY_ID,
- pointOfContactId: PERSON_ID,
- lastContactAt: NEWER_OCCURRED_AT,
- },
- ],
- });
-
- await updateRelatedLastContactForPeople(client as never, emailContact());
+ await updateRelatedLastContactForPeople(
+ client as never,
+ emailContact(),
+ stateFor(
+ buildState({
+ company: { id: COMPANY_ID, lastContactAt: NEWER_OCCURRED_AT },
+ opportunities: [
+ { id: OPPORTUNITY_ID, lastContactAt: NEWER_OCCURRED_AT },
+ ],
+ }),
+ ),
+ );
- expect(findUpsertData('createCompanies')).toBeUndefined();
- expect(findUpsertData('createOpportunities')).toBeUndefined();
+ expect(client.mutation).not.toHaveBeenCalled();
});
it('skips the company update when the person has no company but still updates opportunities', async () => {
- client = buildClient({
- people: [{ id: PERSON_ID, companyId: null }],
- opportunities: [
- {
- id: OPPORTUNITY_ID,
- pointOfContactId: PERSON_ID,
- lastContactAt: null,
- },
- ],
- });
-
- await updateRelatedLastContactForPeople(client as never, emailContact());
+ await updateRelatedLastContactForPeople(
+ client as never,
+ emailContact(),
+ stateFor(buildState({ company: null })),
+ );
expect(findUpsertData('createCompanies')).toBeUndefined();
expect(findUpsertData('createOpportunities')).toEqual([
@@ -155,25 +139,7 @@ describe('updateRelatedLastContactForPeople', () => {
]);
});
- it('leaves out a company that no longer exists rather than upserting it back', async () => {
- client = buildClient({
- people: [{ id: PERSON_ID, companyId: COMPANY_ID }],
- companies: [],
- });
-
- await updateRelatedLastContactForPeople(client as never, emailContact());
-
- expect(findUpsertData('createCompanies')).toBeUndefined();
- });
-
it('updates a shared company once, with the most recent contact of its people', async () => {
- client = buildClient({
- people: [
- { id: PERSON_ID, companyId: COMPANY_ID },
- { id: OTHER_PERSON_ID, companyId: COMPANY_ID },
- ],
- });
-
await updateRelatedLastContactForPeople(
client as never,
new Map([
@@ -187,9 +153,17 @@ describe('updateRelatedLastContactForPeople', () => {
],
[
OTHER_PERSON_ID,
- { occurredAt: OCCURRED_AT, itemId: MESSAGE_ID, kind: 'email' as const },
+ {
+ occurredAt: OCCURRED_AT,
+ itemId: MESSAGE_ID,
+ kind: 'email' as const,
+ },
],
]),
+ new Map([
+ [PERSON_ID, buildState({ opportunities: [] })],
+ [OTHER_PERSON_ID, buildState({ opportunities: [] })],
+ ]),
);
expect(findUpsertData('createCompanies')).toEqual([
@@ -201,4 +175,70 @@ describe('updateRelatedLastContactForPeople', () => {
},
]);
});
+
+ it('reads the opportunities of a person past the nested relation cap', async () => {
+ client.query.mockResolvedValue({
+ opportunities: {
+ edges: [
+ {
+ node: {
+ id: OPPORTUNITY_ID,
+ pointOfContactId: PERSON_ID,
+ lastContactAt: null,
+ },
+ },
+ {
+ node: {
+ id: OTHER_OPPORTUNITY_ID,
+ pointOfContactId: PERSON_ID,
+ lastContactAt: null,
+ },
+ },
+ ],
+ pageInfo: { hasNextPage: false, endCursor: null },
+ },
+ });
+
+ await updateRelatedLastContactForPeople(
+ client as never,
+ emailContact(),
+ stateFor(buildState({ totalCount: 61 })),
+ );
+
+ expect(client.query).toHaveBeenCalledTimes(1);
+ expect(client.query.mock.calls[0][0].opportunities.__args.filter).toEqual({
+ pointOfContactId: { in: [PERSON_ID] },
+ });
+ expect(
+ findUpsertData('createOpportunities').map(({ id }: { id: string }) => id),
+ ).toEqual([OPPORTUNITY_ID, OTHER_OPPORTUNITY_ID]);
+ });
+
+ it.each([null, 60])(
+ 'reads the opportunities of a person when the nested relation is full and its total count is %s',
+ async (totalCount) => {
+ client.query.mockResolvedValue({
+ opportunities: {
+ edges: [],
+ pageInfo: { hasNextPage: false, endCursor: null },
+ },
+ });
+
+ await updateRelatedLastContactForPeople(
+ client as never,
+ emailContact(),
+ stateFor(
+ buildState({
+ opportunities: Array.from({ length: 60 }, (_, index) => ({
+ id: `opportunity-${index}`,
+ lastContactAt: null,
+ })),
+ totalCount,
+ }),
+ ),
+ );
+
+ expect(client.query).toHaveBeenCalledTimes(1);
+ },
+ );
});
diff --git a/packages/twenty-apps/public/last-contact/src/utils/apply-meeting-interactions.ts b/packages/twenty-apps/public/last-contact/src/utils/apply-meeting-interactions.ts
index 8129799efe4..d7ba70bd2bd 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/apply-meeting-interactions.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/apply-meeting-interactions.ts
@@ -12,19 +12,17 @@ export type CalendarEventParticipantLink = {
export const applyMeetingInteractions = async (
client: CoreApiClient,
links: CalendarEventParticipantLink[],
-): Promise<void> => {
+): Promise<string[]> => {
const calendarEventIds = [
...new Set(links.map((link) => link.calendarEventId)),
];
if (calendarEventIds.length === 0) {
- return;
+ return [];
}
- const interactionByCalendarEventId = await collectCalendarEventInteractions(
- client,
- calendarEventIds,
- );
+ const { interactionByCalendarEventId, upcomingMeetingStartsAts } =
+ await collectCalendarEventInteractions(client, calendarEventIds);
const interactionsByPersonId = new Map<string, Interaction[]>();
for (const { personId, calendarEventId } of links) {
@@ -50,4 +48,6 @@ export const applyMeetingInteractions = async (
}
await applyPersonInteractions(client, interactionsByPersonId);
+
+ return upcomingMeetingStartsAts;
};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/apply-person-interactions.ts b/packages/twenty-apps/public/last-contact/src/utils/apply-person-interactions.ts
index ec94967ceda..ebc71b2f6fa 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/apply-person-interactions.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/apply-person-interactions.ts
@@ -61,5 +61,9 @@ export const applyPersonInteractions = async (
}
await upsertRecordsInBatches(client, 'createPeople', updates);
- await updateRelatedLastContactForPeople(client, contactByPersonId);
+ await updateRelatedLastContactForPeople(
+ client,
+ contactByPersonId,
+ stateByPersonId,
+ );
};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/collect-calendar-event-interactions.ts b/packages/twenty-apps/public/last-contact/src/utils/collect-calendar-event-interactions.ts
index caf36fe3395..cbf8c628577 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/collect-calendar-event-interactions.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/collect-calendar-event-interactions.ts
@@ -22,10 +22,15 @@ type CalendarEventParticipantNode = Participant & {
} | null;
};
+export type CalendarEventInteractions = {
+ interactionByCalendarEventId: Map<string, CalendarEventInteraction>;
+ upcomingMeetingStartsAts: string[];
+};
+
export const collectCalendarEventInteractions = async (
client: CoreApiClient,
calendarEventIds: string[],
-): Promise<Map<string, CalendarEventInteraction>> => {
+): Promise<CalendarEventInteractions> => {
const participantsByCalendarEventId = new Map<
string,
CalendarEventParticipantNode[]
@@ -85,12 +90,18 @@ export const collectCalendarEventInteractions = async (
string,
CalendarEventInteraction
>();
+ const upcomingMeetingStartsAts: string[] = [];
for (const [calendarEventId, participants] of participantsByCalendarEventId) {
const calendarEvent = participants[0]?.calendarEvent;
const startsAt = calendarEvent?.startsAt ?? null;
- if (!startsAt || calendarEvent?.isCanceled || startsAt > now) {
+ if (!startsAt || calendarEvent?.isCanceled) {
+ continue;
+ }
+
+ if (startsAt > now) {
+ upcomingMeetingStartsAts.push(startsAt);
continue;
}
@@ -102,5 +113,5 @@ export const collectCalendarEventInteractions = async (
});
}
- return interactionByCalendarEventId;
+ return { interactionByCalendarEventId, upcomingMeetingStartsAts };
};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/collect-person-meeting-participants.ts b/packages/twenty-apps/public/last-contact/src/utils/collect-person-meeting-participants.ts
new file mode 100644
index 00000000000..56e1072b4f2
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/utils/collect-person-meeting-participants.ts
@@ -0,0 +1,104 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { executeWithRetry } from 'src/utils/execute-with-retry';
+
+const PAGE_SIZE = 200;
+
+export type PersonMeetingParticipant = {
+ personId: string;
+ calendarEventId: string;
+ startsAt: string;
+};
+
+export const collectPersonMeetingParticipants = async (
+ client: CoreApiClient,
+ {
+ from,
+ to,
+ calendarEventIds,
+ shouldStop = () => false,
+ }: {
+ from?: Date;
+ to?: Date;
+ calendarEventIds?: string[];
+ shouldStop?: (participant: PersonMeetingParticipant) => boolean;
+ },
+): Promise<PersonMeetingParticipant[]> => {
+ const participants: PersonMeetingParticipant[] = [];
+ let after: string | undefined;
+
+ do {
+ const { calendarEventParticipants } = await executeWithRetry(() =>
+ client.query({
+ calendarEventParticipants: {
+ __args: {
+ filter: {
+ and: [
+ { personId: { is: 'NOT_NULL' } },
+ ...(calendarEventIds
+ ? [{ calendarEventId: { in: calendarEventIds } }]
+ : []),
+ ...(from
+ ? [
+ {
+ calendarEvent: {
+ startsAt: { gte: from.toISOString() },
+ },
+ },
+ ]
+ : []),
+ ...(to
+ ? [{ calendarEvent: { startsAt: { lt: to.toISOString() } } }]
+ : []),
+ { calendarEvent: { isCanceled: { eq: false } } },
+ ],
+ },
+ orderBy: [{ calendarEvent: { startsAt: 'AscNullsLast' } }],
+ first: PAGE_SIZE,
+ after,
+ },
+ edges: {
+ node: {
+ personId: true,
+ calendarEventId: true,
+ calendarEvent: { startsAt: true },
+ },
+ },
+ pageInfo: { hasNextPage: true, endCursor: true },
+ },
+ }),
+ );
+
+ let hasReachedStop = false;
+
+ for (const edge of calendarEventParticipants?.edges ?? []) {
+ const { personId, calendarEventId, calendarEvent } = edge.node;
+
+ if (!personId || !calendarEventId || !calendarEvent?.startsAt) {
+ continue;
+ }
+
+ const participant = {
+ personId,
+ calendarEventId,
+ startsAt: calendarEvent.startsAt,
+ };
+
+ participants.push(participant);
+
+ if (shouldStop(participant)) {
+ hasReachedStop = true;
+ break;
+ }
+ }
+
+ const nextCursor =
+ !hasReachedStop && calendarEventParticipants?.pageInfo.hasNextPage
+ ? (calendarEventParticipants.pageInfo.endCursor ?? undefined)
+ : undefined;
+
+ after = nextCursor !== after ? nextCursor : undefined;
+ } while (after);
+
+ return participants;
+};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/execute-with-retry.ts b/packages/twenty-apps/public/last-contact/src/utils/execute-with-retry.ts
index 6da606a6561..c1a869379e6 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/execute-with-retry.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/execute-with-retry.ts
@@ -1,7 +1,11 @@
-const MAX_ATTEMPTS = 5;
+import { RetryableLogicFunctionError } from 'twenty-sdk/logic-function';
+
+const MAX_ATTEMPTS = 8;
const INITIAL_RETRY_DELAY_MS = 2_000;
const MAX_RETRY_DELAY_MS = 30_000;
+const MAX_RETRY_AFTER_MS = 60_000;
const MAX_JITTER_MS = 1_000;
+const MAX_TOTAL_WAIT_MS = 120_000;
// The client SDK surfaces HTTP failures as plain Error messages built from the
// status text and raw response body, so retryability has to be detected from
@@ -10,28 +14,53 @@ const MAX_JITTER_MS = 1_000;
const RETRYABLE_ERROR_PATTERN =
/\b(429|1015|too many requests|rate ?limit\w*|502|503|504|bad gateway|gateway time-?out|service unavailable|timed? ?out|fetch failed|econnreset|econnrefused|socket hang up)\b/i;
+type GraphqlErrorEntry = {
+ extensions?: { code?: string; retryAfterMs?: number };
+};
+
const sleep = (durationMs: number): Promise<void> =>
new Promise((resolve) => setTimeout(resolve, durationMs));
const getErrorMessage = (error: unknown): string =>
error instanceof Error ? error.message : String(error);
+const getGraphqlErrors = (error: unknown): GraphqlErrorEntry[] => {
+ const errors = (error as { errors?: unknown } | null)?.errors;
+
+ return Array.isArray(errors) ? errors : [];
+};
+
+const findRateLimitedError = (error: unknown): GraphqlErrorEntry | undefined =>
+ getGraphqlErrors(error).find(
+ (graphqlError) => graphqlError.extensions?.code === 'RATE_LIMITED',
+ );
+
const isRetryableError = (error: unknown): boolean =>
+ findRateLimitedError(error) !== undefined ||
RETRYABLE_ERROR_PATTERN.test(getErrorMessage(error));
const parseRetryAfterMs = (error: unknown): number | undefined => {
+ const retryAfterMs = findRateLimitedError(error)?.extensions?.retryAfterMs;
+
+ if (typeof retryAfterMs === 'number') {
+ return retryAfterMs;
+ }
+
const match = getErrorMessage(error).match(/"retry_after"\s*:\s*(\d+)/);
+
return match ? Number(match[1]) * 1_000 : undefined;
};
export const executeWithRetry = async <TResult>(
execute: () => TResult,
): Promise<Awaited<TResult>> => {
+ let totalWaitMs = 0;
+
for (let attempt = 1; ; attempt += 1) {
try {
return await execute();
} catch (error) {
- if (attempt >= MAX_ATTEMPTS || !isRetryableError(error)) {
+ if (!isRetryableError(error)) {
throw error;
}
@@ -41,11 +70,17 @@ export const executeWithRetry = async <TResult>(
);
const retryAfterMs = Math.min(
parseRetryAfterMs(error) ?? 0,
- MAX_RETRY_DELAY_MS,
+ MAX_RETRY_AFTER_MS,
);
- const jitterMs = Math.random() * MAX_JITTER_MS;
+ const waitMs =
+ Math.max(backoffMs, retryAfterMs) + Math.random() * MAX_JITTER_MS;
+
+ if (attempt >= MAX_ATTEMPTS || totalWaitMs + waitMs > MAX_TOTAL_WAIT_MS) {
+ throw new RetryableLogicFunctionError(getErrorMessage(error));
+ }
- await sleep(Math.max(backoffMs, retryAfterMs) + jitterMs);
+ totalWaitMs += waitMs;
+ await sleep(waitMs);
}
}
};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/recompute-opportunity-last-contact.ts b/packages/twenty-apps/public/last-contact/src/utils/recompute-opportunity-last-contact.ts
index 9ef393a97c8..ab5dbc87432 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/recompute-opportunity-last-contact.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/recompute-opportunity-last-contact.ts
@@ -17,17 +17,40 @@ const EMPTY_LAST_CONTACT: LastContactData = {
lastContactItemCalendarEventId: null,
};
-type PersonLastContact = {
- lastContactAt?: string | null;
- lastContactItemMessage?: { id: string } | null;
- lastContactItemCalendarEvent?: { id: string } | null;
+type OpportunityNode = {
+ id?: string | null;
+ pointOfContact?: {
+ lastContactAt?: string | null;
+ lastContactItemMessageId?: string | null;
+ lastContactItemCalendarEventId?: string | null;
+ } | null;
};
-const collectPointOfContactIdByOpportunityId = async (
+const buildLastContactData = (
+ pointOfContact: OpportunityNode['pointOfContact'],
+): LastContactData =>
+ pointOfContact
+ ? {
+ lastContactAt: pointOfContact.lastContactAt ?? null,
+ lastContactItemMessageId:
+ pointOfContact.lastContactItemMessageId ?? null,
+ lastContactItemCalendarEventId:
+ pointOfContact.lastContactItemCalendarEventId ?? null,
+ }
+ : EMPTY_LAST_CONTACT;
+
+// An opportunity's last contact mirrors its point of contact, so it must be
+// recomputed whenever the opportunity is created or its point of contact changes,
+// not only when an interaction happens.
+export const recomputeOpportunitiesLastContact = async (
client: CoreApiClient,
opportunityIds: string[],
-): Promise<Map<string, string | null>> => {
- const pointOfContactIdByOpportunityId = new Map<string, string | null>();
+): Promise<void> => {
+ if (opportunityIds.length === 0) {
+ return;
+ }
+
+ const upserts: RecordUpsert[] = [];
for (const ids of chunk(opportunityIds, PAGE_SIZE)) {
let after: string | undefined;
@@ -36,50 +59,15 @@ const collectPointOfContactIdByOpportunityId = async (
const { opportunities } = await executeWithRetry(() =>
client.query({
opportunities: {
- __args: { filter: { id: { in: ids } }, first: PAGE_SIZE, after },
- edges: { node: { id: true, pointOfContactId: true } },
- pageInfo: { hasNextPage: true, endCursor: true },
- },
- }),
- );
-
- for (const edge of opportunities?.edges ?? []) {
- const { id, pointOfContactId } = edge.node;
-
- if (id) {
- pointOfContactIdByOpportunityId.set(id, pointOfContactId ?? null);
- }
- }
-
- after = opportunities?.pageInfo.hasNextPage
- ? (opportunities.pageInfo.endCursor ?? undefined)
- : undefined;
- } while (after);
- }
-
- return pointOfContactIdByOpportunityId;
-};
-
-const collectLastContactByPersonId = async (
- client: CoreApiClient,
- personIds: string[],
-): Promise<Map<string, LastContactData>> => {
- const lastContactByPersonId = new Map<string, LastContactData>();
-
- for (const ids of chunk(personIds, PAGE_SIZE)) {
- let after: string | undefined;
-
- do {
- const { people } = await executeWithRetry(() =>
- client.query({
- people: {
__args: { filter: { id: { in: ids } }, first: PAGE_SIZE, after },
edges: {
node: {
id: true,
- lastContactAt: true,
- lastContactItemMessage: { id: true },
- lastContactItemCalendarEvent: { id: true },
+ pointOfContact: {
+ lastContactAt: true,
+ lastContactItemMessageId: true,
+ lastContactItemCalendarEventId: true,
+ },
},
},
pageInfo: { hasNextPage: true, endCursor: true },
@@ -87,63 +75,19 @@ const collectLastContactByPersonId = async (
}),
);
- for (const edge of people?.edges ?? []) {
- const person = edge.node as PersonLastContact & { id?: string | null };
+ for (const edge of opportunities?.edges ?? []) {
+ const { id, pointOfContact } = edge.node as OpportunityNode;
- if (!person.id) {
- continue;
+ if (id) {
+ upserts.push({ id, ...buildLastContactData(pointOfContact) });
}
-
- lastContactByPersonId.set(person.id, {
- lastContactAt: person.lastContactAt ?? null,
- lastContactItemMessageId: person.lastContactItemMessage?.id ?? null,
- lastContactItemCalendarEventId:
- person.lastContactItemCalendarEvent?.id ?? null,
- });
}
- after = people?.pageInfo.hasNextPage
- ? (people.pageInfo.endCursor ?? undefined)
+ after = opportunities?.pageInfo.hasNextPage
+ ? (opportunities.pageInfo.endCursor ?? undefined)
: undefined;
} while (after);
}
- return lastContactByPersonId;
-};
-
-// An opportunity's last contact mirrors its point of contact, so it must be
-// recomputed whenever the opportunity is created or its point of contact changes,
-// not only when an interaction happens.
-export const recomputeOpportunitiesLastContact = async (
- client: CoreApiClient,
- opportunityIds: string[],
-): Promise<void> => {
- if (opportunityIds.length === 0) {
- return;
- }
-
- const pointOfContactIdByOpportunityId =
- await collectPointOfContactIdByOpportunityId(client, opportunityIds);
- const personIds = [
- ...new Set(
- [...pointOfContactIdByOpportunityId.values()].filter(
- (pointOfContactId): pointOfContactId is string => !!pointOfContactId,
- ),
- ),
- ];
- const lastContactByPersonId = await collectLastContactByPersonId(
- client,
- personIds,
- );
-
- const upserts: RecordUpsert[] = [
- ...pointOfContactIdByOpportunityId,
- ].map(([opportunityId, pointOfContactId]) => ({
- id: opportunityId,
- ...((pointOfContactId
- ? lastContactByPersonId.get(pointOfContactId)
- : undefined) ?? EMPTY_LAST_CONTACT),
- }));
-
await upsertRecordsInBatches(client, 'createOpportunities', upserts);
};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/schedule-meetings.ts b/packages/twenty-apps/public/last-contact/src/utils/schedule-meetings.ts
new file mode 100644
index 00000000000..83c03181f46
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/utils/schedule-meetings.ts
@@ -0,0 +1,114 @@
+import { enqueueJobs } from 'twenty-sdk/logic-function';
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import {
+ MEETING_HORIZON_PERIOD_MS,
+ MEETING_JOB_RETRY_LIMIT,
+ MEETING_SCHEDULE_HORIZON_MS,
+ MEETING_SLOT_JOB_DELAY_BUFFER_MS,
+ MEETING_SLOT_MS,
+} from 'src/constants/meeting-schedule';
+import {
+ MEETING_HORIZON_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ MEETING_SLOT_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+} from 'src/constants/universal-identifiers';
+import { collectPersonMeetingParticipants } from 'src/utils/collect-person-meeting-participants';
+import { executeWithRetry } from 'src/utils/execute-with-retry';
+
+export type MeetingSlotPayload = { slotStart: string; slotEnd: string };
+
+const enqueueDelayedJob = async ({
+ logicFunctionUniversalIdentifier,
+ jobId,
+ payload,
+ delayMs,
+}: {
+ logicFunctionUniversalIdentifier: string;
+ jobId: string;
+ payload: Record<string, unknown>;
+ delayMs: number;
+}): Promise<void> => {
+ await executeWithRetry(() =>
+ enqueueJobs({
+ logicFunctionUniversalIdentifier,
+ jobs: [{ payload, jobId }],
+ delayMs,
+ retryLimit: MEETING_JOB_RETRY_LIMIT,
+ }),
+ );
+};
+
+export const scheduleMeetings = async (
+ meetingStartsAts: string[],
+ now = Date.now(),
+): Promise<void> => {
+ const horizonEnd = now + MEETING_SCHEDULE_HORIZON_MS;
+ const slotStartsMs = new Set<number>();
+ let hasMeetingBeyondHorizon = false;
+
+ for (const meetingStartsAt of meetingStartsAts) {
+ const startsAtMs = Date.parse(meetingStartsAt);
+
+ if (Number.isNaN(startsAtMs)) {
+ continue;
+ }
+
+ if (startsAtMs > horizonEnd) {
+ hasMeetingBeyondHorizon = true;
+ continue;
+ }
+
+ const slotStartMs =
+ Math.floor(startsAtMs / MEETING_SLOT_MS) * MEETING_SLOT_MS;
+
+ if (slotStartMs + MEETING_SLOT_MS > now) {
+ slotStartsMs.add(slotStartMs);
+ }
+ }
+
+ for (const slotStartMs of [...slotStartsMs].sort()) {
+ const slotEndMs = slotStartMs + MEETING_SLOT_MS;
+ const payload: MeetingSlotPayload = {
+ slotStart: new Date(slotStartMs).toISOString(),
+ slotEnd: new Date(slotEndMs).toISOString(),
+ };
+
+ await enqueueDelayedJob({
+ logicFunctionUniversalIdentifier:
+ MEETING_SLOT_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ jobId: `meeting-slot-${slotStartMs}`,
+ payload,
+ delayMs: slotEndMs - now + MEETING_SLOT_JOB_DELAY_BUFFER_MS,
+ });
+ }
+
+ if (hasMeetingBeyondHorizon) {
+ const nextPeriodStartMs =
+ (Math.floor(now / MEETING_HORIZON_PERIOD_MS) + 1) *
+ MEETING_HORIZON_PERIOD_MS;
+
+ await enqueueDelayedJob({
+ logicFunctionUniversalIdentifier:
+ MEETING_HORIZON_REACHED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ jobId: `meeting-horizon-${nextPeriodStartMs}`,
+ payload: {},
+ delayMs: nextPeriodStartMs - now,
+ });
+ }
+};
+
+export const scheduleUpcomingPersonMeetings = async (
+ client: CoreApiClient,
+): Promise<void> => {
+ const now = Date.now();
+ const participants = await collectPersonMeetingParticipants(client, {
+ from: new Date(now),
+ shouldStop: ({ startsAt }) =>
+ Date.parse(startsAt) > now + MEETING_SCHEDULE_HORIZON_MS,
+ });
+
+ await scheduleMeetings(
+ participants.map(({ startsAt }) => startsAt),
+ now,
+ );
+};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/update-person-last-contact.ts b/packages/twenty-apps/public/last-contact/src/utils/update-person-last-contact.ts
index 34a9e6a9cea..e63bca0f638 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/update-person-last-contact.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/update-person-last-contact.ts
@@ -15,12 +15,19 @@ export type Interaction = {
workspaceMemberId: string | null;
} & ({ kind: 'email'; direction: InteractionDirection } | { kind: 'meeting' });
+export type RelatedLastContact = { id: string; lastContactAt: string | null };
+
export type PersonLastContactState = {
lastContactAt?: string | null;
lastOutboundAt?: string | null;
lastInboundAt?: string | null;
lastEmail?: { receivedAt: string | null } | null;
lastMeeting?: { startsAt: string | null } | null;
+ company?: RelatedLastContact | null;
+ pointOfContactForOpportunities?: {
+ totalCount?: number | null;
+ edges: { node: RelatedLastContact }[];
+ } | null;
};
const isNewer = (
@@ -73,6 +80,11 @@ export const collectPersonLastContactState = async (
lastInboundAt: true,
lastEmail: { receivedAt: true },
lastMeeting: { startsAt: true },
+ company: { id: true, lastContactAt: true },
+ pointOfContactForOpportunities: {
+ totalCount: true,
+ edges: { node: { id: true, lastContactAt: true } },
+ },
},
},
pageInfo: { hasNextPage: true, endCursor: true },
diff --git a/packages/twenty-apps/public/last-contact/src/utils/update-related-last-contact.ts b/packages/twenty-apps/public/last-contact/src/utils/update-related-last-contact.ts
index 72a46a6be9f..e9e889a7415 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/update-related-last-contact.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/update-related-last-contact.ts
@@ -2,13 +2,18 @@ import { type CoreApiClient } from 'twenty-client-sdk/core';
import { chunk } from 'src/utils/chunk';
import { executeWithRetry } from 'src/utils/execute-with-retry';
-import { type InteractionKind } from 'src/utils/update-person-last-contact';
+import {
+ type InteractionKind,
+ type PersonLastContactState,
+ type RelatedLastContact,
+} from 'src/utils/update-person-last-contact';
import {
type RecordUpsert,
upsertRecordsInBatches,
} from 'src/utils/upsert-records-in-batches';
const PAGE_SIZE = 200;
+const NESTED_RELATION_MAX_RECORDS = 60;
export type RelatedInteraction = {
occurredAt: string;
@@ -16,12 +21,6 @@ export type RelatedInteraction = {
kind: InteractionKind;
};
-type OpportunityLink = {
- opportunityId: string;
- pointOfContactId: string;
- lastContactAt: string | null;
-};
-
const isNewer = (
candidate: string,
current: string | null | undefined,
@@ -37,85 +36,11 @@ const buildData = ({
lastContactItemCalendarEventId: kind === 'meeting' ? itemId : null,
});
-const collectCompanyIdByPersonId = async (
+const collectOpportunitiesByPointOfContactId = async (
client: CoreApiClient,
personIds: string[],
-): Promise<Map<string, string>> => {
- const companyIdByPersonId = new Map<string, string>();
-
- for (const ids of chunk(personIds, PAGE_SIZE)) {
- let after: string | undefined;
-
- do {
- const { people } = await executeWithRetry(() =>
- client.query({
- people: {
- __args: { filter: { id: { in: ids } }, first: PAGE_SIZE, after },
- edges: { node: { id: true, companyId: true } },
- pageInfo: { hasNextPage: true, endCursor: true },
- },
- }),
- );
-
- for (const edge of people?.edges ?? []) {
- const { id, companyId } = edge.node;
-
- if (id && companyId) {
- companyIdByPersonId.set(id, companyId);
- }
- }
-
- after = people?.pageInfo.hasNextPage
- ? (people.pageInfo.endCursor ?? undefined)
- : undefined;
- } while (after);
- }
-
- return companyIdByPersonId;
-};
-
-const collectCompanyLastContactAt = async (
- client: CoreApiClient,
- companyIds: string[],
-): Promise<Map<string, string | null>> => {
- const lastContactAtByCompanyId = new Map<string, string | null>();
-
- for (const ids of chunk(companyIds, PAGE_SIZE)) {
- let after: string | undefined;
-
- do {
- const { companies } = await executeWithRetry(() =>
- client.query({
- companies: {
- __args: { filter: { id: { in: ids } }, first: PAGE_SIZE, after },
- edges: { node: { id: true, lastContactAt: true } },
- pageInfo: { hasNextPage: true, endCursor: true },
- },
- }),
- );
-
- for (const edge of companies?.edges ?? []) {
- const { id, lastContactAt } = edge.node;
-
- if (id) {
- lastContactAtByCompanyId.set(id, lastContactAt ?? null);
- }
- }
-
- after = companies?.pageInfo.hasNextPage
- ? (companies.pageInfo.endCursor ?? undefined)
- : undefined;
- } while (after);
- }
-
- return lastContactAtByCompanyId;
-};
-
-const collectOpportunityLinks = async (
- client: CoreApiClient,
- personIds: string[],
-): Promise<OpportunityLink[]> => {
- const links: OpportunityLink[] = [];
+): Promise<Map<string, RelatedLastContact[]>> => {
+ const opportunitiesByPersonId = new Map<string, RelatedLastContact[]>();
for (const ids of chunk(personIds, PAGE_SIZE)) {
let after: string | undefined;
@@ -144,12 +69,17 @@ const collectOpportunityLinks = async (
for (const edge of opportunities?.edges ?? []) {
const { id, pointOfContactId, lastContactAt } = edge.node;
- if (id && pointOfContactId) {
- links.push({
- opportunityId: id,
- pointOfContactId,
- lastContactAt: lastContactAt ?? null,
- });
+ if (!id || !pointOfContactId) {
+ continue;
+ }
+
+ const opportunity = { id, lastContactAt: lastContactAt ?? null };
+ const existing = opportunitiesByPersonId.get(pointOfContactId);
+
+ if (existing) {
+ existing.push(opportunity);
+ } else {
+ opportunitiesByPersonId.set(pointOfContactId, [opportunity]);
}
}
@@ -159,7 +89,45 @@ const collectOpportunityLinks = async (
} while (after);
}
- return links;
+ return opportunitiesByPersonId;
+};
+
+const resolveOpportunitiesByPersonId = async (
+ client: CoreApiClient,
+ stateByPersonId: Map<string, PersonLastContactState>,
+ personIds: string[],
+): Promise<Map<string, RelatedLastContact[]>> => {
+ const opportunitiesByPersonId = new Map<string, RelatedLastContact[]>();
+ const truncatedPersonIds: string[] = [];
+
+ for (const personId of personIds) {
+ const connection =
+ stateByPersonId.get(personId)?.pointOfContactForOpportunities;
+ const opportunities = (connection?.edges ?? []).map(({ node }) => node);
+
+ const isTruncated =
+ opportunities.length >= NESTED_RELATION_MAX_RECORDS ||
+ (connection?.totalCount ?? 0) > opportunities.length;
+
+ if (isTruncated) {
+ truncatedPersonIds.push(personId);
+ } else {
+ opportunitiesByPersonId.set(personId, opportunities);
+ }
+ }
+
+ if (truncatedPersonIds.length > 0) {
+ const fetched = await collectOpportunitiesByPointOfContactId(
+ client,
+ truncatedPersonIds,
+ );
+
+ for (const personId of truncatedPersonIds) {
+ opportunitiesByPersonId.set(personId, fetched.get(personId) ?? []);
+ }
+ }
+
+ return opportunitiesByPersonId;
};
// Companies and opportunities surface emails and meetings from their related
@@ -168,6 +136,7 @@ const collectOpportunityLinks = async (
export const updateRelatedLastContactForPeople = async (
client: CoreApiClient,
contactByPersonId: Map<string, RelatedInteraction>,
+ stateByPersonId: Map<string, PersonLastContactState>,
): Promise<void> => {
const personIds = [...contactByPersonId.keys()];
@@ -175,37 +144,28 @@ export const updateRelatedLastContactForPeople = async (
return;
}
- const companyIdByPersonId = await collectCompanyIdByPersonId(
- client,
- personIds,
- );
const contactByCompanyId = new Map<string, RelatedInteraction>();
+ const lastContactAtByCompanyId = new Map<string, string | null>();
for (const [personId, contact] of contactByPersonId) {
- const companyId = companyIdByPersonId.get(personId);
+ const company = stateByPersonId.get(personId)?.company;
- if (!companyId) {
+ if (!company?.id) {
continue;
}
- const current = contactByCompanyId.get(companyId);
+ lastContactAtByCompanyId.set(company.id, company.lastContactAt ?? null);
+
+ const current = contactByCompanyId.get(company.id);
if (!current || contact.occurredAt > current.occurredAt) {
- contactByCompanyId.set(companyId, contact);
+ contactByCompanyId.set(company.id, contact);
}
}
- const lastContactAtByCompanyId = await collectCompanyLastContactAt(
- client,
- [...contactByCompanyId.keys()],
- );
const companyUpserts: RecordUpsert[] = [];
for (const [companyId, contact] of contactByCompanyId) {
- if (!lastContactAtByCompanyId.has(companyId)) {
- continue;
- }
-
if (isNewer(contact.occurredAt, lastContactAtByCompanyId.get(companyId))) {
companyUpserts.push({ id: companyId, ...buildData(contact) });
}
@@ -213,17 +173,25 @@ export const updateRelatedLastContactForPeople = async (
await upsertRecordsInBatches(client, 'createCompanies', companyUpserts);
- const opportunityLinks = await collectOpportunityLinks(client, personIds);
+ const opportunitiesByPersonId = await resolveOpportunitiesByPersonId(
+ client,
+ stateByPersonId,
+ personIds,
+ );
const opportunityUpserts: RecordUpsert[] = [];
- for (const { opportunityId, pointOfContactId, lastContactAt } of opportunityLinks) {
- const contact = contactByPersonId.get(pointOfContactId);
+ for (const [personId, opportunities] of opportunitiesByPersonId) {
+ const contact = contactByPersonId.get(personId);
- if (!contact || !isNewer(contact.occurredAt, lastContactAt)) {
+ if (!contact) {
continue;
}
- opportunityUpserts.push({ id: opportunityId, ...buildData(contact) });
+ for (const { id, lastContactAt } of opportunities) {
+ if (isNewer(contact.occurredAt, lastContactAt)) {
+ opportunityUpserts.push({ id, ...buildData(contact) });
+ }
+ }
}
await upsertRecordsInBatches(