The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(last-contact): run database event triggers in batch mode (#26072)
martmull29a5a69fbeee
diff --git a/packages/twenty-apps/public/last-contact/CHANGELOG.md b/packages/twenty-apps/public/last-contact/CHANGELOG.mdindex 3aaef495774..1ce4eef8bbf 100644--- a/packages/twenty-apps/public/last-contact/CHANGELOG.md+++ b/packages/twenty-apps/public/last-contact/CHANGELOG.md@@ -1,5 +1,11 @@# Changelog+## 1.3.0++- Run every database-event trigger in batch mode. A mailbox sync emits one `messageParticipant.updated` event per synced message, which used to enqueue one job per event and flood the workers; a batch now arrives as a single job. Each handler folds its batch down to the distinct records it has to touch (one update per person, company or opportunity, not one per event). Messages, meetings and opportunities are then resolved with `in` queries over the whole batch. The company recompute still runs one indexed lookup per company: finding a company's most recently contacted person cannot be batched without scanning all of its people.+- Resolve a calendar interaction from the participant's own calendar event instead of re-querying the person's most recent past meeting. Participants linked to a future event are left to the `on-calendar-event-started` cron, as before.+- Require Twenty `>=2.40.0`: batch mode for database event triggers only exists from 2.40.+## 1.2.4- Limit the app role to reading synced messages, calendar events, and their participants, and to reading and updating people, companies, and opportunities. The app no longer requests read and edit access to every record type.diff --git a/packages/twenty-apps/public/last-contact/package.json b/packages/twenty-apps/public/last-contact/package.jsonindex 4e7dc653043..3ef3c908583 100644--- a/packages/twenty-apps/public/last-contact/package.json+++ b/packages/twenty-apps/public/last-contact/package.json@@ -1,12 +1,12 @@{"name": "@twentyhq/last-contact",- "version": "1.2.4",+ "version": "1.3.0","license": "MIT","engines": {"node": "^24.5.0","npm": "please-use-yarn","yarn": ">=4.0.2",- "twenty": ">=2.26.0"+ "twenty": ">=2.40.0"},"keywords": ["twenty-app"@@ -28,8 +28,8 @@"oxlint": "^0.16.0","react": "^19.0.0","react-dom": "^19.0.0",- "twenty-client-sdk": "2.37.0",- "twenty-sdk": "2.37.0",+ "twenty-client-sdk": "2.40.0",+ "twenty-sdk": "2.40.0","typescript": "^5.9.3","vite-tsconfig-paths": "^4.2.1","vitest": "^4.0.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.tsindex 8e593790d67..c17c5cfb868 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@@ -11,24 +11,45 @@ import onOpportunityUpdated from 'src/logic-functions/on-opportunity-updated';import onPersonUpdated from 'src/logic-functions/on-person-updated';const calendarHandler = onCalendarInteraction.config.handler as (- event: unknown,+ batch: unknown,) => Promise<void>;const emailHandler = onEmailInteraction.config.handler as (- event: unknown,+ batch: unknown,) => Promise<void>;const opportunityCreatedHandler = onOpportunityCreated.config.handler as (- event: unknown,+ batch: unknown,) => Promise<void>;const opportunityUpdatedHandler = onOpportunityUpdated.config.handler as (- event: unknown,+ batch: unknown,) => Promise<void>;const companyCreatedHandler = onCompanyCreated.config.handler as (- event: unknown,+ batch: unknown,) => Promise<void>;const personUpdatedHandler = onPersonUpdated.config.handler as (- event: unknown,+ batch: unknown,) => Promise<void>;+const buildBatch = (name: string, recordId: string, properties: object) => ({+ name,+ events: [{ recordId, properties }],+});++const emailBatch = (personId: string, messageId: string) =>+ buildBatch('messageParticipant.updated', 'unused-participant-id', {+ updatedFields: ['personId'],+ after: { id: 'unused-participant-id', personId, messageId },+ });++const calendarBatch = (+ participantId: string,+ personId: string,+ calendarEventId: string,+) =>+ buildBatch('calendarEventParticipant.updated', participantId, {+ updatedFields: ['personId'],+ after: { id: participantId, personId, calendarEventId },+ });+const DAY_IN_MS = 24 * 60 * 60 * 1000;const requireId = (id: string | null | undefined, what: string): string => {@@ -427,13 +448,7 @@ describe('last contact handlers', () => {}),);- await emailHandler({- recordId: 'unused-participant-id',- properties: {- updatedFields: ['personId'],- after: { id: 'unused-participant-id', personId, messageId },- },- });+ await emailHandler(emailBatch(personId, messageId));return messageId;};@@ -463,13 +478,9 @@ describe('last contact handlers', () => {}),);- await calendarHandler({- recordId: 'unused-participant-id',- properties: {- updatedFields: ['personId'],- after: { id: 'unused-participant-id', personId },- },- });+ await calendarHandler(+ calendarBatch('unused-participant-id', personId, calendarEventId),+ );return calendarEventId;};@@ -552,13 +563,9 @@ describe('last contact handlers', () => {});createdParticipantIds.push(participantId);- await calendarHandler({- recordId: participantId,- properties: {- updatedFields: ['personId'],- after: { id: participantId, personId },- },- });+ await calendarHandler(+ calendarBatch(participantId, personId, calendarEventId),+ );const lastContact = await getPersonLastContact(client, personId);expect(asTime(lastContact.lastContactAt)).toBe(asTime(startsAt));@@ -578,13 +585,9 @@ describe('last contact handlers', () => {});createdParticipantIds.push(participantId);- await calendarHandler({- recordId: participantId,- properties: {- updatedFields: ['personId'],- after: { id: participantId, personId },- },- });+ await calendarHandler(+ calendarBatch(participantId, personId, calendarEventId),+ );expect((await getPersonLastContact(client, personId)).lastContactAt,@@ -606,13 +609,9 @@ describe('last contact handlers', () => {});createdParticipantIds.push(participantId);- await calendarHandler({- recordId: participantId,- properties: {- updatedFields: ['personId'],- after: { id: participantId, personId },- },- });+ await calendarHandler(+ calendarBatch(participantId, personId, calendarEventId),+ );expect((await getPersonLastContact(client, personId)).lastContactAt,@@ -625,13 +624,7 @@ describe('last contact handlers', () => {createdPersonIds.push(personId);const messageId = await createLinkedMessage(receivedAt, personId);- await emailHandler({- recordId: 'unused-participant-id',- properties: {- updatedFields: ['personId'],- after: { id: 'unused-participant-id', personId, messageId },- },- });+ await emailHandler(emailBatch(personId, messageId));const lastContact = await getPersonLastContact(client, personId);expect(asTime(lastContact.lastContactAt)).toBe(asTime(receivedAt));@@ -647,28 +640,8 @@ describe('last contact handlers', () => {const newerMessageId = await createLinkedMessage(newerReceivedAt, personId);const olderMessageId = await createLinkedMessage(olderReceivedAt, personId);- await emailHandler({- recordId: 'unused-participant-id',- properties: {- updatedFields: ['personId'],- after: {- id: 'unused-participant-id',- personId,- messageId: newerMessageId,- },- },- });- await emailHandler({- recordId: 'unused-participant-id',- properties: {- updatedFields: ['personId'],- after: {- id: 'unused-participant-id',- personId,- messageId: olderMessageId,- },- },- });+ await emailHandler(emailBatch(personId, newerMessageId));+ await emailHandler(emailBatch(personId, olderMessageId));expect(asTime((await getPersonLastContact(client, personId)).lastContactAt),@@ -963,10 +936,11 @@ describe('last contact handlers', () => {});createdOpportunityIds.push(opportunityId);- await opportunityCreatedHandler({- recordId: opportunityId,- properties: { after: { id: opportunityId } },- });+ await opportunityCreatedHandler(+ buildBatch('opportunity.created', opportunityId, {+ after: { id: opportunityId },+ }),+ );const opportunityContact = await getRelatedLastContact(client,@@ -1007,14 +981,13 @@ describe('last contact handlers', () => {id: true,},});- await opportunityUpdatedHandler({- recordId: opportunityId,- properties: {+ await opportunityUpdatedHandler(+ buildBatch('opportunity.updated', opportunityId, {updatedFields: ['pointOfContactId'],before: { id: opportunityId },after: { id: opportunityId },- },- });+ }),+ );const opportunityContact = await getRelatedLastContact(client,@@ -1041,14 +1014,13 @@ describe('last contact handlers', () => {});await setPersonCompany(client, { personId, companyId });- await personUpdatedHandler({- recordId: personId,- properties: {+ await personUpdatedHandler(+ buildBatch('person.updated', personId, {updatedFields: ['companyId'],before: { id: personId, companyId: null },after: { id: personId, companyId },- },- });+ }),+ );const companyContact = await getRelatedLastContact(client,@@ -1082,14 +1054,13 @@ describe('last contact handlers', () => {id: true,},});- await personUpdatedHandler({- recordId: personId,- properties: {+ await personUpdatedHandler(+ buildBatch('person.updated', personId, {updatedFields: ['companyId'],before: { id: personId, companyId },after: { id: personId, companyId: null },- },- });+ }),+ );const companyContact = await getRelatedLastContact(client,@@ -1105,10 +1076,9 @@ describe('last contact handlers', () => {const companyId = await createCompany(client);createdCompanyIds.push(companyId);- await companyCreatedHandler({- recordId: companyId,- properties: { after: { id: companyId } },- });+ await companyCreatedHandler(+ buildBatch('company.created', companyId, { after: { id: companyId } }),+ );const companyContact = await getRelatedLastContact(client,diff --git a/packages/twenty-apps/public/last-contact/src/constants/batch-handler-timeout-seconds.ts b/packages/twenty-apps/public/last-contact/src/constants/batch-handler-timeout-seconds.tsnew file mode 100644index 00000000000..b5461e65a1f--- /dev/null+++ b/packages/twenty-apps/public/last-contact/src/constants/batch-handler-timeout-seconds.ts@@ -0,0 +1 @@+export const BATCH_HANDLER_TIMEOUT_SECONDS = 300;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.tsindex 34f62cad24c..3bf0a88b4b9 100644--- 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@@ -23,12 +23,19 @@ type Page = {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];@@ -38,47 +45,27 @@ const setupQueryMock = ({return Promise.resolve({ calendarEvents: remainingEventsPages.shift() });}- if (query.person) {- return Promise.resolve({ person: null });- }-- const filter = query.calendarEventParticipants.__args.filter;-- if (filter.calendarEventId && filter.workspaceMemberId) {+ if (query.calendarEventParticipants) {return Promise.resolve({- calendarEventParticipants: { edges: [] },+ calendarEventParticipants: query.calendarEventParticipants.edges.node+ .calendarEvent+ ? singlePage(startedParticipants)+ : remainingParticipantsPages.shift(),});}- if (filter.calendarEventId) {- return Promise.resolve({- calendarEventParticipants: remainingParticipantsPages.shift(),- });+ if (query.person) {+ return Promise.resolve({ person: null });}- return Promise.resolve({- calendarEventParticipants: {- edges: [- {- node: {- id: 'participant-latest',- calendarEvent: {- id: 'event-latest',- startsAt: PAST_EVENT_STARTS_AT,- },- },- },- ],- },- });+ if (query.people) {+ return Promise.resolve({ people: singlePage([]) });+ }++ return Promise.resolve({ opportunities: singlePage([]) });});};-const singlePage = (nodes: Record<string, unknown>[]): Page => ({- edges: nodes.map((node) => ({ node })),- pageInfo: { hasNextPage: false, endCursor: null },-});-beforeEach(() => {queryMock.mockReset();mutationMock.mockReset();@@ -114,7 +101,9 @@ describe('on-calendar-event-started handler', () => {);expect(calendarEventsCalls).toHaveLength(2);expect(calendarEventsCalls[0][0].calendarEvents.__args.first).toBe(200);- expect(calendarEventsCalls[0][0].calendarEvents.__args.after).toBeUndefined();+ expect(+ calendarEventsCalls[0][0].calendarEvents.__args.after,+ ).toBeUndefined();expect(calendarEventsCalls[1][0].calendarEvents.__args.after).toBe('events-cursor-1',);@@ -135,16 +124,27 @@ describe('on-calendar-event-started handler', () => {participantsPages: [{edges: [- { node: { id: 'participant-1', personId: PERSON_ID_1 } },- { node: { id: 'participant-2', personId: null } },+ { node: { personId: PERSON_ID_1, calendarEventId: 'event-1' } },+ { node: { personId: null, calendarEventId: 'event-1' } },],pageInfo: { hasNextPage: true, endCursor: 'participants-cursor-1' },},singlePage([- { id: 'participant-3', personId: PERSON_ID_1 },- { id: 'participant-4', personId: PERSON_ID_2 },+ { 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();@@ -152,25 +152,21 @@ describe('on-calendar-event-started handler', () => {const participantsByEventCalls = queryMock.mock.calls.filter(([query]) =>query.calendarEventParticipants?.__args.filter.calendarEventId &&- !query.calendarEventParticipants?.__args.filter.workspaceMemberId,+ !query.calendarEventParticipants?.edges.node.calendarEvent,);expect(participantsByEventCalls).toHaveLength(2);expect(participantsByEventCalls[1][0].calendarEventParticipants.__args.after,).toBe('participants-cursor-1');- const perPersonCalls = queryMock.mock.calls.filter(- ([query]) => query.calendarEventParticipants?.__args.filter.personId,+ const personUpdates = mutationMock.mock.calls.filter(+ ([mutation]) => mutation.updatePeople,);- expect(- perPersonCalls.map(- ([query]) =>- query.calendarEventParticipants.__args.filter.personId.eq,- ),- ).toEqual([PERSON_ID_1, PERSON_ID_2]);- expect(- mutationMock.mock.calls.filter(([mutation]) => mutation.updatePeople),- ).toHaveLength(2);+ expect(personUpdates).toHaveLength(2);+ expect(personUpdates[0][0].updatePeople.__args.data).toMatchObject({+ lastContactAt: PAST_EVENT_STARTS_AT,+ lastContactItemCalendarEventId: 'event-1',+ });});it('should do nothing when no event started in the time window', async () => {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.tsindex ee6d8d65f54..d658a9890bf 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,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const { queryMock, mutationMock } = vi.hoisted(() => ({queryMock: vi.fn(),@@ -13,84 +13,119 @@ vi.mock('twenty-client-sdk/core', () => ({import onCalendarInteraction from '../on-calendar-interaction';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 handler = onCalendarInteraction.config.handler as (- event: unknown,+ batch: unknown,) => Promise<void>;-const buildEvent = (personId: string | null) => ({- recordId: 'participant-1',- properties: {- updatedFields: ['personId'],- after: { id: 'participant-1', personId },- },+const buildPage = (nodes: Record<string, unknown>[]) => ({+ edges: nodes.map((node) => ({ node })),+ pageInfo: { hasNextPage: false, endCursor: null },});+const buildBatch = (+ participants: {+ personId: string | null;+ calendarEventId: string | null;+ }[],+) => ({+ name: 'calendarEventParticipant.updated',+ events: participants.map(({ personId, calendarEventId }, index) => ({+ recordId: `participant-${index}`,+ properties: {+ updatedFields: ['personId'],+ after: { id: `participant-${index}`, personId, calendarEventId },+ },+ })),+});++const setupQueryMock = (participants: Record<string, unknown>[]) => {+ queryMock.mockImplementation((query) => {+ if (query.calendarEventParticipants) {+ return Promise.resolve({+ calendarEventParticipants: buildPage(participants),+ });+ }++ if (query.person) {+ return Promise.resolve({ person: null });+ }++ if (query.people) {+ return Promise.resolve({ people: buildPage([]) });+ }++ return Promise.resolve({ opportunities: buildPage([]) });+ });+};+beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date(NOW));queryMock.mockReset();mutationMock.mockReset();mutationMock.mockResolvedValue({ updatePeople: [{ id: 'updated' }] });});+afterEach(() => {+ vi.useRealTimers();+});+describe('on-calendar-interaction definition', () => {- it('should be valid and only trigger on personId updates', () => {+ it('should be valid and batch personId updates', () => {expect(onCalendarInteraction.success).toBe(true);expect(onCalendarInteraction.config.databaseEventTriggerSettings).toEqual({eventName: 'calendarEventParticipant.updated',updatedFields: ['personId'],+ batchMode: true,});});});describe('on-calendar-interaction handler', () => {- it('should update the person from the event payload without re-querying the participant', async () => {- queryMock- .mockResolvedValueOnce({- calendarEventParticipants: {- edges: [- {- node: {- id: 'participant-1',- calendarEvent: {- id: 'event-1',- startsAt: PAST_EVENT_STARTS_AT,- },- },- },- ],+ it('updates the person from the calendar event carried by the participant', async () => {+ setupQueryMock([+ {+ calendarEventId: CALENDAR_EVENT_ID,+ isOrganizer: null,+ workspaceMemberId: null,+ calendarEvent: {+ startsAt: PAST_EVENT_STARTS_AT,+ isCanceled: false,},- })- .mockResolvedValueOnce({- calendarEventParticipants: { edges: [] },- })- .mockResolvedValueOnce({ person: null })- .mockResolvedValueOnce({ person: null });-- await handler(buildEvent(PERSON_ID));-- expect(queryMock).toHaveBeenCalledTimes(4);- const queryArgs = queryMock.mock.calls[0][0];- expect(queryArgs.calendarEventParticipants.__args.filter.personId).toEqual(- { eq: PERSON_ID },+ },+ ]);++ await handler(+ buildBatch([+ { personId: PERSON_ID, calendarEventId: CALENDAR_EVENT_ID },+ ]),);+expect(- mutationMock.mock.calls.filter(([mutation]) => mutation.updatePeople),- ).toHaveLength(1);- const mutationArgs = mutationMock.mock.calls[0][0];- expect(mutationArgs.updatePeople.__args.data).toEqual({+ queryMock.mock.calls[0][0].calendarEventParticipants.__args.filter,+ ).toEqual({ calendarEventId: { in: [CALENDAR_EVENT_ID] } });+ expect(mutationMock.mock.calls[0][0].updatePeople.__args.data).toEqual({lastContactAt: PAST_EVENT_STARTS_AT,lastContactById: null,- lastContactItemCalendarEventId: 'event-1',+ lastContactItemCalendarEventId: CALENDAR_EVENT_ID,lastContactItemMessageId: null,lastOutboundAt: PAST_EVENT_STARTS_AT,lastInboundAt: PAST_EVENT_STARTS_AT,- lastMeetingId: 'event-1',+ lastMeetingId: CALENDAR_EVENT_ID,});});- it('should do nothing when the participant has no personId', async () => {- await handler(buildEvent(null));+ it('should do nothing when no participant has both a person and a calendar event', async () => {+ await handler(+ buildBatch([+ { personId: null, calendarEventId: CALENDAR_EVENT_ID },+ { personId: PERSON_ID, calendarEventId: null },+ ]),+ );expect(queryMock).not.toHaveBeenCalled();expect(mutationMock).not.toHaveBeenCalled();diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-email-interaction.test.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-email-interaction.test.tsindex 0028d4cd71b..78684ce4599 100644--- a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-email-interaction.test.ts+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-email-interaction.test.ts@@ -14,27 +14,53 @@ import onEmailInteraction from '../on-email-interaction';const PERSON_ID = '11111111-1111-1111-1111-111111111111';const MESSAGE_ID = '22222222-2222-2222-2222-222222222222';+const OLDER_MESSAGE_ID = '44444444-4444-4444-4444-444444444444';const MEMBER_ID = '33333333-3333-3333-3333-333333333333';const RECEIVED_AT = '2026-06-10T09:00:00.000Z';+const OLDER_RECEIVED_AT = '2026-06-01T09:00:00.000Z';const handler = onEmailInteraction.config.handler as (- event: unknown,+ batch: unknown,) => Promise<void>;-const buildEvent = ({- personId,- messageId,-}: {- personId: string | null;- messageId: string | null;-}) => ({- recordId: 'participant-1',- properties: {- updatedFields: ['personId'],- after: { id: 'participant-1', personId, messageId },- },+const buildPage = (nodes: Record<string, unknown>[]) => ({+ edges: nodes.map((node) => ({ node })),+ pageInfo: { hasNextPage: false, endCursor: null },});+const buildBatch = (+ participants: { personId: string | null; messageId: string | null }[],+) => ({+ name: 'messageParticipant.updated',+ events: participants.map(({ personId, messageId }, index) => ({+ recordId: `participant-${index}`,+ properties: {+ updatedFields: ['personId'],+ after: { id: `participant-${index}`, personId, messageId },+ },+ })),+});++const setupQueryMock = (messageParticipants: Record<string, unknown>[]) => {+ queryMock.mockImplementation((query) => {+ if (query.messageParticipants) {+ return Promise.resolve({+ messageParticipants: buildPage(messageParticipants),+ });+ }++ if (query.person) {+ return Promise.resolve({ person: null });+ }++ if (query.people) {+ return Promise.resolve({ people: buildPage([]) });+ }++ return Promise.resolve({ opportunities: buildPage([]) });+ });+};+beforeEach(() => {queryMock.mockReset();mutationMock.mockReset();@@ -42,44 +68,38 @@ beforeEach(() => {});describe('on-email-interaction definition', () => {- it('should be valid and only trigger on personId updates', () => {+ it('should be valid and batch personId updates', () => {expect(onEmailInteraction.success).toBe(true);expect(onEmailInteraction.config.databaseEventTriggerSettings).toEqual({eventName: 'messageParticipant.updated',updatedFields: ['personId'],+ batchMode: true,});});});describe('on-email-interaction handler', () => {it('sets interaction, owner, item, contacted and lastEmail for an outbound email', async () => {- queryMock- .mockResolvedValueOnce({- messageParticipants: {- edges: [- {- node: {- role: 'TO',- workspaceMemberId: null,- message: { receivedAt: RECEIVED_AT },- },- },- {- node: {- role: 'FROM',- workspaceMemberId: MEMBER_ID,- message: { receivedAt: RECEIVED_AT },- },- },- ],- },- })- .mockResolvedValueOnce({ person: null });-- await handler(buildEvent({ personId: PERSON_ID, messageId: MESSAGE_ID }));-- const data = mutationMock.mock.calls[0][0].updatePeople.__args.data;- expect(data).toEqual({+ setupQueryMock([+ {+ messageId: MESSAGE_ID,+ role: 'TO',+ workspaceMemberId: null,+ message: { receivedAt: RECEIVED_AT },+ },+ {+ messageId: MESSAGE_ID,+ role: 'FROM',+ workspaceMemberId: MEMBER_ID,+ message: { receivedAt: RECEIVED_AT },+ },+ ]);++ await handler(+ buildBatch([{ personId: PERSON_ID, messageId: MESSAGE_ID }]),+ );++ expect(mutationMock.mock.calls[0][0].updatePeople.__args.data).toEqual({lastContactAt: RECEIVED_AT,lastContactById: MEMBER_ID,lastContactItemMessageId: MESSAGE_ID,@@ -89,36 +109,77 @@ describe('on-email-interaction handler', () => {});});- it('should do nothing when the participant has no personId', async () => {- await handler(buildEvent({ personId: null, messageId: MESSAGE_ID }));-- expect(queryMock).not.toHaveBeenCalled();- expect(mutationMock).not.toHaveBeenCalled();+ it('resolves every message of the batch in one query and updates each person once', async () => {+ setupQueryMock([+ {+ messageId: OLDER_MESSAGE_ID,+ role: 'FROM',+ workspaceMemberId: null,+ message: { receivedAt: OLDER_RECEIVED_AT },+ },+ {+ messageId: MESSAGE_ID,+ role: 'FROM',+ workspaceMemberId: MEMBER_ID,+ message: { receivedAt: RECEIVED_AT },+ },+ ]);++ await handler(+ buildBatch([+ { personId: PERSON_ID, messageId: OLDER_MESSAGE_ID },+ { personId: PERSON_ID, messageId: MESSAGE_ID },+ ]),+ );++ const participantQueries = queryMock.mock.calls.filter(+ ([query]) => query.messageParticipants,+ );+ expect(participantQueries).toHaveLength(1);+ expect(+ participantQueries[0][0].messageParticipants.__args.filter,+ ).toEqual({ messageId: { in: [OLDER_MESSAGE_ID, MESSAGE_ID] } });++ const personUpdates = mutationMock.mock.calls.filter(+ ([mutation]) => mutation.updatePeople,+ );+ expect(personUpdates).toHaveLength(1);+ expect(personUpdates[0][0].updatePeople.__args.data).toEqual({+ lastContactAt: RECEIVED_AT,+ lastContactById: MEMBER_ID,+ lastContactItemMessageId: MESSAGE_ID,+ lastContactItemCalendarEventId: null,+ lastOutboundAt: RECEIVED_AT,+ lastInboundAt: OLDER_RECEIVED_AT,+ lastEmailId: MESSAGE_ID,+ });});- it('should do nothing when the participant has no messageId', async () => {- await handler(buildEvent({ personId: PERSON_ID, messageId: null }));+ it('should do nothing when no participant has both a person and a message', async () => {+ await handler(+ buildBatch([+ { personId: null, messageId: MESSAGE_ID },+ { personId: PERSON_ID, messageId: null },+ ]),+ );expect(queryMock).not.toHaveBeenCalled();expect(mutationMock).not.toHaveBeenCalled();});it('should not update the person when the message has no receivedAt', async () => {- queryMock.mockResolvedValue({- messageParticipants: {- edges: [- {- node: {- role: 'FROM',- workspaceMemberId: MEMBER_ID,- message: { receivedAt: null },- },- },- ],+ setupQueryMock([+ {+ messageId: MESSAGE_ID,+ role: 'FROM',+ workspaceMemberId: MEMBER_ID,+ message: { receivedAt: null },},- });+ ]);- await handler(buildEvent({ personId: PERSON_ID, messageId: MESSAGE_ID }));+ await handler(+ buildBatch([{ personId: PERSON_ID, messageId: MESSAGE_ID }]),+ );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.tsindex 6fef3b0dab0..f8727ac61cd 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@@ -18,9 +18,14 @@ const MESSAGE_ID = '33333333-3333-3333-3333-333333333333';const OCCURRED_AT = '2026-06-10T09:00:00.000Z';const handler = onOpportunityCreated.config.handler as (- event: unknown,+ batch: unknown,) => Promise<void>;+const buildPage = (nodes: Record<string, unknown>[]) => ({+ edges: nodes.map((node) => ({ node })),+ pageInfo: { hasNextPage: false, endCursor: null },+});+beforeEach(() => {queryMock.mockReset();mutationMock.mockReset();@@ -28,30 +33,42 @@ beforeEach(() => {});describe('on-opportunity-created', () => {- it('should trigger on opportunity creation', () => {+ it('should batch opportunity creations', () => {expect(onOpportunityCreated.success).toBe(true);expect(onOpportunityCreated.config.databaseEventTriggerSettings).toEqual({eventName: 'opportunity.created',+ batchMode: true,});});it('computes the last contact from the point of contact', async () => {- queryMock- .mockResolvedValueOnce({- opportunity: { id: OPPORTUNITY_ID, pointOfContactId: PERSON_ID },- })- .mockResolvedValueOnce({- person: {- id: PERSON_ID,- lastContactAt: OCCURRED_AT,- lastContactItemMessage: { id: MESSAGE_ID },- lastContactItemCalendarEvent: null,- },- });+ 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,+ },+ ]),+ }),+ );await handler({- recordId: OPPORTUNITY_ID,- properties: { after: { id: OPPORTUNITY_ID } },+ name: 'opportunity.created',+ events: [+ {+ recordId: OPPORTUNITY_ID,+ properties: { after: { id: OPPORTUNITY_ID } },+ },+ ],});expect(mutationMock.mock.calls[0][0].updateOpportunity.__args.data).toEqual({diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-person-updated.test.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-person-updated.test.tsindex fde8a056899..9100be24a4d 100644--- a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-person-updated.test.ts+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-person-updated.test.ts@@ -16,16 +16,21 @@ const OLD_COMPANY_ID = '11111111-1111-1111-1111-111111111111';const NEW_COMPANY_ID = '22222222-2222-2222-2222-222222222222';const handler = onPersonUpdated.config.handler as (- event: unknown,+ batch: unknown,) => Promise<void>;-const buildEvent = (before: string | null, after: string | null) => ({- recordId: 'person-1',- properties: {- updatedFields: ['companyId'],- before: { id: 'person-1', companyId: before },- after: { id: 'person-1', companyId: after },- },+const buildBatch = (+ moves: { before: string | null; after: string | null }[],+) => ({+ name: 'person.updated',+ events: moves.map(({ before, after }, index) => ({+ recordId: `person-${index}`,+ properties: {+ updatedFields: ['companyId'],+ before: { id: `person-${index}`, companyId: before },+ after: { id: `person-${index}`, companyId: after },+ },+ })),});beforeEach(() => {@@ -35,37 +40,48 @@ beforeEach(() => {mutationMock.mockResolvedValue({});});+const updatedCompanyIds = () =>+ mutationMock.mock.calls.map(([mutation]) => mutation.updateCompany.__args.id);+describe('on-person-updated definition', () => {- it('should trigger on companyId updates', () => {+ it('should batch companyId updates', () => {expect(onPersonUpdated.success).toBe(true);expect(onPersonUpdated.config.databaseEventTriggerSettings).toEqual({eventName: 'person.updated',updatedFields: ['companyId'],+ batchMode: true,});});});describe('on-person-updated handler', () => {it('recomputes both the former and the current company', async () => {- await handler(buildEvent(OLD_COMPANY_ID, NEW_COMPANY_ID));-- const updatedCompanyIds = mutationMock.mock.calls.map(- ([mutation]) => mutation.updateCompany.__args.id,+ await handler(+ buildBatch([{ before: OLD_COMPANY_ID, after: NEW_COMPANY_ID }]),);- expect(updatedCompanyIds).toEqual([OLD_COMPANY_ID, NEW_COMPANY_ID]);++ expect(updatedCompanyIds()).toEqual([OLD_COMPANY_ID, NEW_COMPANY_ID]);});it('recomputes a single company when the person only gains one', async () => {- await handler(buildEvent(null, NEW_COMPANY_ID));+ await handler(buildBatch([{ before: null, after: NEW_COMPANY_ID }]));- expect(mutationMock).toHaveBeenCalledTimes(1);- expect(mutationMock.mock.calls[0][0].updateCompany.__args.id).toBe(- NEW_COMPANY_ID,+ expect(updatedCompanyIds()).toEqual([NEW_COMPANY_ID]);+ });++ it('recomputes a company shared by several people in the batch only once', async () => {+ await handler(+ buildBatch([+ { before: OLD_COMPANY_ID, after: NEW_COMPANY_ID },+ { before: OLD_COMPANY_ID, after: NEW_COMPANY_ID },+ ]),);++ expect(updatedCompanyIds()).toEqual([OLD_COMPANY_ID, NEW_COMPANY_ID]);});it('does nothing when no company is involved', async () => {- await handler(buildEvent(null, null));+ await handler(buildBatch([{ before: null, after: null }]));expect(queryMock).not.toHaveBeenCalled();expect(mutationMock).not.toHaveBeenCalled();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.tsindex 74484736041..0cf9098e031 100644--- 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@@ -1,10 +1,14 @@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 { updatePersonLastContactFromCalendar } from 'src/utils/update-person-last-contact-from-calendar';+import {+ applyMeetingInteractions,+ type CalendarEventParticipantLink,+} from 'src/utils/apply-meeting-interactions';const QUERY_MAX_RECORDS = 200;@@ -60,7 +64,7 @@ const handler = async (): Promise<void> => {return;}- const personIds = new Set<string>();+ const linkByKey = new Map<string, CalendarEventParticipantLink>();let participantsCursor: string | undefined;let participantsHasNextPage = true;@@ -74,8 +78,8 @@ const handler = async (): Promise<void> => {},edges: {node: {- id: true,personId: true,+ calendarEventId: true,},},pageInfo: {@@ -86,10 +90,13 @@ const handler = async (): Promise<void> => {});for (const edge of calendarEventParticipants?.edges ?? []) {- const personId = edge.node.personId;+ const { personId, calendarEventId } = edge.node;- if (personId !== null && personId !== undefined) {- personIds.add(personId);+ if (personId && calendarEventId) {+ linkByKey.set(`${personId}:${calendarEventId}`, {+ personId,+ calendarEventId,+ });}}participantsHasNextPage =@@ -98,11 +105,7 @@ const handler = async (): Promise<void> => {calendarEventParticipants?.pageInfo.endCursor ?? undefined;}- await Promise.all(- [...personIds].map((personId) =>- updatePersonLastContactFromCalendar(client, personId),- ),- );+ await applyMeetingInteractions(client, [...linkByKey.values()]);};export default defineLogicFunction({@@ -111,7 +114,7 @@ export default defineLogicFunction({name: 'on-calendar-event-started',description:'Updates last-contacted fields for participants of calendar events whose start time just passed.',- timeoutSeconds: 60,+ timeoutSeconds: BATCH_HANDLER_TIMEOUT_SECONDS,cronTriggerSettings: {pattern: `*/${CALENDAR_CRON_INTERVAL_MINUTES} * * * *`,},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.tsindex 003935794c8..13d27d2f49c 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@@ -1,28 +1,46 @@-import { defineLogicFunction, type ObjectRecordUpdateEvent } from 'twenty-sdk/define';-import { type DatabaseEventPayload } from 'twenty-sdk/logic-function';+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_INTERACTION_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';-import { updatePersonLastContactFromCalendar } from 'src/utils/update-person-last-contact-from-calendar';+import {+ applyMeetingInteractions,+ type CalendarEventParticipantLink,+} from 'src/utils/apply-meeting-interactions';type CalendarEventParticipantUpdate = {personId?: string | null;+ calendarEventId?: string | null;};const handler = async (- event: DatabaseEventPayload<+ batch: DatabaseEventBatchPayload<ObjectRecordUpdateEvent<CalendarEventParticipantUpdate>>,): Promise<void> => {- const personId = event.properties.after.personId;+ const linkByKey = new Map<string, CalendarEventParticipantLink>();- if (!personId) {- return;+ for (const event of batch.events) {+ const personId = event.properties.after.personId;+ const calendarEventId = event.properties.after.calendarEventId;++ if (personId && calendarEventId) {+ linkByKey.set(`${personId}:${calendarEventId}`, {+ personId,+ calendarEventId,+ });+ }}- const client = new CoreApiClient();+ if (linkByKey.size === 0) {+ return;+ }- await updatePersonLastContactFromCalendar(client, personId);+ await applyMeetingInteractions(new CoreApiClient(), [...linkByKey.values()]);};export default defineLogicFunction({@@ -30,10 +48,11 @@ export default defineLogicFunction({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).",- timeoutSeconds: 60,+ timeoutSeconds: BATCH_HANDLER_TIMEOUT_SECONDS,databaseEventTriggerSettings: {eventName: 'calendarEventParticipant.updated',updatedFields: ['personId'],+ batchMode: true,},handler,});diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/on-company-created.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/on-company-created.tsindex 970ab861103..999b5baf183 100644--- a/packages/twenty-apps/public/last-contact/src/logic-functions/on-company-created.ts+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/on-company-created.ts@@ -2,26 +2,33 @@ import {defineLogicFunction,type ObjectRecordCreateEvent,} from 'twenty-sdk/define';-import { type DatabaseEventPayload } from 'twenty-sdk/logic-function';+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 { COMPANY_CREATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';-import { recomputeCompanyLastContact } from 'src/utils/recompute-company-last-contact';+import { recomputeCompaniesLastContact } from 'src/utils/recompute-company-last-contact';type CompanyCreate = { id?: string | null };const handler = async (- event: DatabaseEventPayload<ObjectRecordCreateEvent<CompanyCreate>>,+ batch: DatabaseEventBatchPayload<ObjectRecordCreateEvent<CompanyCreate>>,): Promise<void> => {- const companyId = event.properties.after.id ?? event.recordId;+ const companyIds = new Set<string>();- if (!companyId) {- return;+ for (const event of batch.events) {+ const companyId = event.properties.after.id ?? event.recordId;++ if (companyId) {+ companyIds.add(companyId);+ }}- const client = new CoreApiClient();+ if (companyIds.size === 0) {+ return;+ }- await recomputeCompanyLastContact(client, companyId);+ await recomputeCompaniesLastContact(new CoreApiClient(), [...companyIds]);};export default defineLogicFunction({@@ -29,9 +36,10 @@ export default defineLogicFunction({name: 'on-company-created',description:"Computes a company's last contact from its people when the company is created.",- timeoutSeconds: 60,+ timeoutSeconds: BATCH_HANDLER_TIMEOUT_SECONDS,databaseEventTriggerSettings: {eventName: 'company.created',+ batchMode: true,},handler,});diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/on-email-interaction.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/on-email-interaction.tsindex c0f3acfec75..55551a9f132 100644--- a/packages/twenty-apps/public/last-contact/src/logic-functions/on-email-interaction.ts+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/on-email-interaction.ts@@ -1,11 +1,16 @@-import { defineLogicFunction, type ObjectRecordUpdateEvent } from 'twenty-sdk/define';-import type { DatabaseEventPayload } from 'twenty-sdk/logic-function';+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 { EMAIL_INTERACTION_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';-import { pickContactTeamMemberId } from 'src/utils/pick-contact-team-member';-import { updatePersonForInteraction } from 'src/utils/update-person-last-contact';-import { updateRelatedLastContact } from 'src/utils/update-related-last-contact';+import {+ applyEmailInteractions,+ type MessageParticipantLink,+} from 'src/utils/apply-email-interactions';type MessageParticipantUpdate = {personId?: string | null;@@ -13,70 +18,26 @@ type MessageParticipantUpdate = {};const handler = async (- event: DatabaseEventPayload<ObjectRecordUpdateEvent<MessageParticipantUpdate>>,+ batch: DatabaseEventBatchPayload<+ ObjectRecordUpdateEvent<MessageParticipantUpdate>+ >,): Promise<void> => {- const personId = event.properties.after.personId;- const messageId = event.properties.after.messageId;+ const linkByKey = new Map<string, MessageParticipantLink>();- if (!personId || !messageId) {- return;- }-- const client = new CoreApiClient();-- const { messageParticipants } = await client.query({- messageParticipants: {- __args: { filter: { messageId: { eq: messageId } }, first: 200 },- edges: {- node: {- role: true,- workspaceMemberId: true,- message: { receivedAt: true },- },- },- },- });+ for (const event of batch.events) {+ const personId = event.properties.after.personId;+ const messageId = event.properties.after.messageId;- const participants =- messageParticipants?.edges?.map(- (edge: {- node: {- role: string | null;- workspaceMemberId: string | null;- message: { receivedAt: string | null } | null;- };- }) => edge.node,- ) ?? [];- const occurredAt = participants[0]?.message?.receivedAt ?? null;+ if (personId && messageId) {+ linkByKey.set(`${personId}:${messageId}`, { personId, messageId });+ }+ }- if (!occurredAt) {+ if (linkByKey.size === 0) {return;}- const fromParticipant = participants.find(- (participant: { role: string | null; workspaceMemberId: string | null }) =>- participant.role === 'FROM',- );- const direction = fromParticipant?.workspaceMemberId ? 'outbound' : 'inbound';- const workspaceMemberId = pickContactTeamMemberId(participants, {- role: 'FROM',- });-- await updatePersonForInteraction(client, {- personId,- occurredAt,- kind: 'email',- itemId: messageId,- workspaceMemberId,- direction,- });-- await updateRelatedLastContact(client, {- personId,- occurredAt,- itemId: messageId,- kind: 'email',- });+ await applyEmailInteractions(new CoreApiClient(), [...linkByKey.values()]);};export default defineLogicFunction({@@ -84,10 +45,11 @@ export default defineLogicFunction({name: 'on-email-interaction',description:"Updates a person's last-contacted fields, and the last contact on their company and opportunities, when a new email participant is created.",- timeoutSeconds: 60,+ timeoutSeconds: BATCH_HANDLER_TIMEOUT_SECONDS,databaseEventTriggerSettings: {eventName: 'messageParticipant.updated',updatedFields: ['personId'],+ batchMode: true,},handler,});diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/on-opportunity-created.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/on-opportunity-created.tsindex cbdee842d44..ea9b8a582d4 100644--- a/packages/twenty-apps/public/last-contact/src/logic-functions/on-opportunity-created.ts+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/on-opportunity-created.ts@@ -2,26 +2,35 @@ import {defineLogicFunction,type ObjectRecordCreateEvent,} from 'twenty-sdk/define';-import { type DatabaseEventPayload } from 'twenty-sdk/logic-function';+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 { OPPORTUNITY_CREATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';-import { recomputeOpportunityLastContact } from 'src/utils/recompute-opportunity-last-contact';+import { recomputeOpportunitiesLastContact } from 'src/utils/recompute-opportunity-last-contact';type OpportunityCreate = { id?: string | null };const handler = async (- event: DatabaseEventPayload<ObjectRecordCreateEvent<OpportunityCreate>>,+ batch: DatabaseEventBatchPayload<ObjectRecordCreateEvent<OpportunityCreate>>,): Promise<void> => {- const opportunityId = event.properties.after.id ?? event.recordId;+ const opportunityIds = new Set<string>();- if (!opportunityId) {- return;+ for (const event of batch.events) {+ const opportunityId = event.properties.after.id ?? event.recordId;++ if (opportunityId) {+ opportunityIds.add(opportunityId);+ }}- const client = new CoreApiClient();+ if (opportunityIds.size === 0) {+ return;+ }- await recomputeOpportunityLastContact(client, opportunityId);+ await recomputeOpportunitiesLastContact(new CoreApiClient(), [+ ...opportunityIds,+ ]);};export default defineLogicFunction({@@ -29,9 +38,10 @@ export default defineLogicFunction({name: 'on-opportunity-created',description:"Computes an opportunity's last contact from its point of contact when the opportunity is created.",- timeoutSeconds: 60,+ timeoutSeconds: BATCH_HANDLER_TIMEOUT_SECONDS,databaseEventTriggerSettings: {eventName: 'opportunity.created',+ batchMode: true,},handler,});diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/on-opportunity-updated.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/on-opportunity-updated.tsindex 3520592e126..266695e238e 100644--- a/packages/twenty-apps/public/last-contact/src/logic-functions/on-opportunity-updated.ts+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/on-opportunity-updated.ts@@ -2,26 +2,35 @@ import {defineLogicFunction,type ObjectRecordUpdateEvent,} from 'twenty-sdk/define';-import { type DatabaseEventPayload } from 'twenty-sdk/logic-function';+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 { OPPORTUNITY_UPDATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';-import { recomputeOpportunityLastContact } from 'src/utils/recompute-opportunity-last-contact';+import { recomputeOpportunitiesLastContact } from 'src/utils/recompute-opportunity-last-contact';type OpportunityUpdate = { id?: string | null };const handler = async (- event: DatabaseEventPayload<ObjectRecordUpdateEvent<OpportunityUpdate>>,+ batch: DatabaseEventBatchPayload<ObjectRecordUpdateEvent<OpportunityUpdate>>,): Promise<void> => {- const opportunityId = event.properties.after?.id ?? event.recordId;+ const opportunityIds = new Set<string>();- if (!opportunityId) {- return;+ for (const event of batch.events) {+ const opportunityId = event.properties.after?.id ?? event.recordId;++ if (opportunityId) {+ opportunityIds.add(opportunityId);+ }}- const client = new CoreApiClient();+ if (opportunityIds.size === 0) {+ return;+ }- await recomputeOpportunityLastContact(client, opportunityId);+ await recomputeOpportunitiesLastContact(new CoreApiClient(), [+ ...opportunityIds,+ ]);};export default defineLogicFunction({@@ -29,10 +38,11 @@ export default defineLogicFunction({name: 'on-opportunity-updated',description:"Recomputes an opportunity's last contact from its point of contact when the point of contact changes.",- timeoutSeconds: 60,+ timeoutSeconds: BATCH_HANDLER_TIMEOUT_SECONDS,databaseEventTriggerSettings: {eventName: 'opportunity.updated',updatedFields: ['pointOfContactId'],+ batchMode: true,},handler,});diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/on-person-created.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/on-person-created.tsindex edf900a04a2..8f33bf0a138 100644--- a/packages/twenty-apps/public/last-contact/src/logic-functions/on-person-created.ts+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/on-person-created.ts@@ -2,26 +2,33 @@ import {defineLogicFunction,type ObjectRecordCreateEvent,} from 'twenty-sdk/define';-import { type DatabaseEventPayload } from 'twenty-sdk/logic-function';+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 { PERSON_CREATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';-import { recomputeCompanyLastContact } from 'src/utils/recompute-company-last-contact';+import { recomputeCompaniesLastContact } from 'src/utils/recompute-company-last-contact';type PersonCreate = { companyId?: string | null };const handler = async (- event: DatabaseEventPayload<ObjectRecordCreateEvent<PersonCreate>>,+ batch: DatabaseEventBatchPayload<ObjectRecordCreateEvent<PersonCreate>>,): Promise<void> => {- const companyId = event.properties.after.companyId;+ const companyIds = new Set<string>();- if (!companyId) {- return;+ for (const event of batch.events) {+ const companyId = event.properties.after.companyId;++ if (companyId) {+ companyIds.add(companyId);+ }}- const client = new CoreApiClient();+ if (companyIds.size === 0) {+ return;+ }- await recomputeCompanyLastContact(client, companyId);+ await recomputeCompaniesLastContact(new CoreApiClient(), [...companyIds]);};export default defineLogicFunction({@@ -29,9 +36,10 @@ export default defineLogicFunction({name: 'on-person-created',description:"Recomputes the company's last contact when a person is created with a company.",- timeoutSeconds: 60,+ timeoutSeconds: BATCH_HANDLER_TIMEOUT_SECONDS,databaseEventTriggerSettings: {eventName: 'person.created',+ batchMode: true,},handler,});diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/on-person-updated.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/on-person-updated.tsindex c8c2e3ccaeb..33fdd1c735b 100644--- a/packages/twenty-apps/public/last-contact/src/logic-functions/on-person-updated.ts+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/on-person-updated.ts@@ -2,35 +2,38 @@ import {defineLogicFunction,type ObjectRecordUpdateEvent,} from 'twenty-sdk/define';-import { type DatabaseEventPayload } from 'twenty-sdk/logic-function';+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 { PERSON_UPDATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';-import { recomputeCompanyLastContact } from 'src/utils/recompute-company-last-contact';+import { recomputeCompaniesLastContact } from 'src/utils/recompute-company-last-contact';type PersonUpdate = { companyId?: string | null };const handler = async (- event: DatabaseEventPayload<ObjectRecordUpdateEvent<PersonUpdate>>,+ batch: DatabaseEventBatchPayload<ObjectRecordUpdateEvent<PersonUpdate>>,): Promise<void> => {- const before = event.properties.before?.companyId ?? null;- const after = event.properties.after?.companyId ?? null;+ const companyIds = new Set<string>();- const companyIds = [...new Set([before, after])].filter(- (id): id is string => Boolean(id),- );+ // Both the person's former and current company can lose or gain their most+ // recent contact when the person moves.+ for (const event of batch.events) {+ for (const companyId of [+ event.properties.before?.companyId,+ event.properties.after?.companyId,+ ]) {+ if (companyId) {+ companyIds.add(companyId);+ }+ }+ }- if (companyIds.length === 0) {+ if (companyIds.size === 0) {return;}- const client = new CoreApiClient();-- // Both the person's former and current company can lose or gain their most- // recent contact when the person moves.- for (const companyId of companyIds) {- await recomputeCompanyLastContact(client, companyId);- }+ await recomputeCompaniesLastContact(new CoreApiClient(), [...companyIds]);};export default defineLogicFunction({@@ -38,10 +41,11 @@ export default defineLogicFunction({name: 'on-person-updated',description:"Recomputes the former and current company's last contact when a person's company changes.",- timeoutSeconds: 60,+ timeoutSeconds: BATCH_HANDLER_TIMEOUT_SECONDS,databaseEventTriggerSettings: {eventName: 'person.updated',updatedFields: ['companyId'],+ batchMode: true,},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.tsnew file mode 100644index 00000000000..66d84231cc5--- /dev/null+++ b/packages/twenty-apps/public/last-contact/src/utils/__tests__/apply-meeting-interactions.test.ts@@ -0,0 +1,191 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { CoreApiClient } from 'twenty-client-sdk/core';++import { applyMeetingInteractions } from 'src/utils/apply-meeting-interactions';++const PERSON_ID = '11111111-1111-1111-1111-111111111111';+const OTHER_PERSON_ID = '22222222-2222-2222-2222-222222222222';+const MEMBER_ID = '33333333-3333-3333-3333-333333333333';+const CALENDAR_EVENT_ID = '44444444-4444-4444-4444-444444444444';+const OLDER_CALENDAR_EVENT_ID = '55555555-5555-5555-5555-555555555555';+const NOW = '2026-06-12T12:00:00.000Z';+const PAST_EVENT_STARTS_AT = '2026-06-10T09:00:00.000Z';+const OLDER_EVENT_STARTS_AT = '2026-06-01T09:00:00.000Z';+const FUTURE_EVENT_STARTS_AT = '2026-06-20T09:00:00.000Z';++type Page = {+ edges: { node: Record<string, unknown> }[];+ pageInfo: { hasNextPage: boolean; endCursor: string | null };+};++const buildPage = (nodes: Record<string, unknown>[]): Page => ({+ edges: nodes.map((node) => ({ node })),+ pageInfo: { hasNextPage: false, endCursor: null },+});++const buildClient = (participants: Record<string, unknown>[] = []) => {+ const queryMock = vi.fn().mockImplementation((query) => {+ if (query.calendarEventParticipants) {+ return Promise.resolve({+ calendarEventParticipants: buildPage(participants),+ });+ }++ if (query.person) {+ return Promise.resolve({ person: null });+ }++ if (query.people) {+ return Promise.resolve({ people: buildPage([]) });+ }++ return Promise.resolve({ opportunities: buildPage([]) });+ });+ const mutationMock = vi+ .fn()+ .mockResolvedValue({ updatePeople: [{ id: 'updated' }] });++ return {+ client: {+ query: queryMock,+ mutation: mutationMock,+ } as unknown as CoreApiClient,+ queryMock,+ mutationMock,+ };+};++const buildParticipant = ({+ calendarEventId,+ startsAt,+ isCanceled = false,+ isOrganizer = null,+ workspaceMemberId = null,+}: {+ calendarEventId: string;+ startsAt: string;+ isCanceled?: boolean;+ isOrganizer?: boolean | null;+ workspaceMemberId?: string | null;+}) => ({+ calendarEventId,+ isOrganizer,+ workspaceMemberId,+ calendarEvent: { startsAt, isCanceled },+});++beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date(NOW));+});++afterEach(() => {+ vi.useRealTimers();+});++describe('applyMeetingInteractions', () => {+ it('resolves the whole batch through one participants query', async () => {+ const { client, queryMock } = buildClient();++ await applyMeetingInteractions(client, [+ { personId: PERSON_ID, calendarEventId: CALENDAR_EVENT_ID },+ { personId: OTHER_PERSON_ID, calendarEventId: OLDER_CALENDAR_EVENT_ID },+ ]);++ expect(queryMock).toHaveBeenCalledTimes(1);+ expect(+ queryMock.mock.calls[0][0].calendarEventParticipants.__args.filter,+ ).toEqual({+ calendarEventId: { in: [CALENDAR_EVENT_ID, OLDER_CALENDAR_EVENT_ID] },+ });+ });++ it('sets lastContactAt, the organizer member and the calendarEvent item', async () => {+ const { client, mutationMock } = buildClient([+ buildParticipant({+ calendarEventId: CALENDAR_EVENT_ID,+ startsAt: PAST_EVENT_STARTS_AT,+ workspaceMemberId: '66666666-6666-6666-6666-666666666666',+ }),+ buildParticipant({+ calendarEventId: CALENDAR_EVENT_ID,+ startsAt: PAST_EVENT_STARTS_AT,+ isOrganizer: true,+ workspaceMemberId: MEMBER_ID,+ }),+ ]);++ await applyMeetingInteractions(client, [+ { personId: PERSON_ID, calendarEventId: CALENDAR_EVENT_ID },+ ]);++ expect(mutationMock.mock.calls[0][0].updatePeople.__args.data).toEqual({+ lastContactAt: PAST_EVENT_STARTS_AT,+ lastContactById: MEMBER_ID,+ lastContactItemCalendarEventId: CALENDAR_EVENT_ID,+ lastContactItemMessageId: null,+ lastOutboundAt: PAST_EVENT_STARTS_AT,+ lastInboundAt: PAST_EVENT_STARTS_AT,+ lastMeetingId: CALENDAR_EVENT_ID,+ });+ });++ it('keeps only the most recent meeting when a person attended several in the batch', async () => {+ const { client, mutationMock } = buildClient([+ buildParticipant({+ calendarEventId: OLDER_CALENDAR_EVENT_ID,+ startsAt: OLDER_EVENT_STARTS_AT,+ }),+ buildParticipant({+ calendarEventId: CALENDAR_EVENT_ID,+ startsAt: PAST_EVENT_STARTS_AT,+ }),+ ]);++ await applyMeetingInteractions(client, [+ { personId: PERSON_ID, calendarEventId: OLDER_CALENDAR_EVENT_ID },+ { personId: PERSON_ID, calendarEventId: CALENDAR_EVENT_ID },+ ]);++ const personUpdates = mutationMock.mock.calls.filter(+ ([mutation]) => mutation.updatePeople,+ );+ expect(personUpdates).toHaveLength(1);+ expect(personUpdates[0][0].updatePeople.__args.data).toMatchObject({+ lastContactAt: PAST_EVENT_STARTS_AT,+ lastContactItemCalendarEventId: CALENDAR_EVENT_ID,+ lastMeetingId: CALENDAR_EVENT_ID,+ });+ });++ it('skips a meeting that has not started yet', async () => {+ const { client, mutationMock } = buildClient([+ buildParticipant({+ calendarEventId: CALENDAR_EVENT_ID,+ startsAt: FUTURE_EVENT_STARTS_AT,+ }),+ ]);++ await applyMeetingInteractions(client, [+ { personId: PERSON_ID, calendarEventId: CALENDAR_EVENT_ID },+ ]);++ expect(mutationMock).not.toHaveBeenCalled();+ });++ it('skips a canceled meeting', async () => {+ const { client, mutationMock } = buildClient([+ buildParticipant({+ calendarEventId: CALENDAR_EVENT_ID,+ startsAt: PAST_EVENT_STARTS_AT,+ isCanceled: true,+ }),+ ]);++ await applyMeetingInteractions(client, [+ { personId: PERSON_ID, calendarEventId: CALENDAR_EVENT_ID },+ ]);++ expect(mutationMock).not.toHaveBeenCalled();+ });+});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.tsindex 8451c7d2776..b6083ec890d 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@@ -1,8 +1,9 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { recomputeOpportunityLastContact } from 'src/utils/recompute-opportunity-last-contact';+import { recomputeOpportunitiesLastContact } from 'src/utils/recompute-opportunity-last-contact';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';@@ -12,31 +13,47 @@ 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 = ({+ 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) }),+ ),+ mutation: vi.fn().mockResolvedValue({}),+});+let client: Client;beforeEach(() => {- client = {- query: vi.fn(),- mutation: vi.fn().mockResolvedValue({}),- };+ client = buildClient({});});-describe('recomputeOpportunityLastContact', () => {+describe('recomputeOpportunitiesLastContact', () => {it('mirrors the point of contact last contact onto the opportunity', async () => {- client.query- .mockResolvedValueOnce({- opportunity: { id: OPPORTUNITY_ID, pointOfContactId: PERSON_ID },- })- .mockResolvedValueOnce({- person: {+ client = buildClient({+ opportunities: [{ id: OPPORTUNITY_ID, pointOfContactId: PERSON_ID }],+ people: [+ {id: PERSON_ID,lastContactAt: OCCURRED_AT,lastContactItemMessage: { id: MESSAGE_ID },lastContactItemCalendarEvent: null,},- });+ ],+ });- await recomputeOpportunityLastContact(client as never, OPPORTUNITY_ID);+ await recomputeOpportunitiesLastContact(client as never, [OPPORTUNITY_ID]);expect(client.mutation.mock.calls[0][0].updateOpportunity.__args).toEqual({id: OPPORTUNITY_ID,@@ -49,19 +66,48 @@ describe('recomputeOpportunityLastContact', () => {});it('clears the opportunity last contact when there is no point of contact', async () => {- client.query.mockResolvedValueOnce({- opportunity: { id: OPPORTUNITY_ID, pointOfContactId: null },+ client = buildClient({+ opportunities: [{ id: OPPORTUNITY_ID, pointOfContactId: null }],});- await recomputeOpportunityLastContact(client as never, OPPORTUNITY_ID);+ await recomputeOpportunitiesLastContact(client as never, [OPPORTUNITY_ID]);expect(client.query).toHaveBeenCalledTimes(1);- expect(client.mutation.mock.calls[0][0].updateOpportunity.__args.data).toEqual(- {- lastContactAt: null,- lastContactItemMessageId: null,- lastContactItemCalendarEventId: null,- },- );+ expect(+ client.mutation.mock.calls[0][0].updateOpportunity.__args.data,+ ).toEqual({+ lastContactAt: null,+ lastContactItemMessageId: null,+ lastContactItemCalendarEventId: null,+ });+ });++ it('resolves a whole batch with one opportunity query and one people query', 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,+ },+ ],+ });++ await recomputeOpportunitiesLastContact(client as never, [+ OPPORTUNITY_ID,+ OTHER_OPPORTUNITY_ID,+ ]);++ expect(client.query).toHaveBeenCalledTimes(2);+ expect(+ client.mutation.mock.calls.map(+ ([mutation]) => mutation.updateOpportunity.__args.id,+ ),+ ).toEqual([OPPORTUNITY_ID, OTHER_OPPORTUNITY_ID]);});});diff --git a/packages/twenty-apps/public/last-contact/src/utils/__tests__/update-person-last-contact-at-from-calendar.test.ts b/packages/twenty-apps/public/last-contact/src/utils/__tests__/update-person-last-contact-at-from-calendar.test.tsdeleted file mode 100644index a6dc1d05d2c..00000000000--- a/packages/twenty-apps/public/last-contact/src/utils/__tests__/update-person-last-contact-at-from-calendar.test.ts+++ /dev/null@@ -1,143 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import type { CoreApiClient } from 'twenty-client-sdk/core';--import { updatePersonLastContactFromCalendar } from 'src/utils/update-person-last-contact-from-calendar';--const PERSON_ID = '11111111-1111-1111-1111-111111111111';-const MEMBER_ID = '33333333-3333-3333-3333-333333333333';-const CALENDAR_EVENT_ID = '44444444-4444-4444-4444-444444444444';-const NOW = '2026-06-12T12:00:00.000Z';-const PAST_EVENT_STARTS_AT = '2026-06-10T09:00:00.000Z';--const buildClient = (...queryResults: unknown[]) => {- const queryMock = vi.fn();- for (const queryResult of queryResults) {- queryMock.mockResolvedValueOnce(queryResult);- }- const mutationMock = vi.fn().mockResolvedValue({ updatePeople: [{ id: 'updated' }] });- const client = {- query: queryMock,- mutation: mutationMock,- } as unknown as CoreApiClient;-- return { client, queryMock, mutationMock };-};--beforeEach(() => {- vi.useFakeTimers();- vi.setSystemTime(new Date(NOW));-});--afterEach(() => {- vi.useRealTimers();-});--describe('updatePersonLastContactAtFromCalendar', () => {- it('should query the latest past non-canceled event for the person', async () => {- const { client, queryMock } = buildClient({- calendarEventParticipants: { edges: [] },- });-- await updatePersonLastContactFromCalendar(client, PERSON_ID);-- expect(queryMock).toHaveBeenCalledWith({- calendarEventParticipants: {- __args: {- filter: {- personId: { eq: PERSON_ID },- calendarEvent: {- startsAt: { lte: NOW },- isCanceled: { eq: false },- },- },- orderBy: [{ calendarEvent: { startsAt: 'DescNullsLast' } }],- first: 1,- },- edges: {- node: {- id: true,- calendarEvent: {- id: true,- startsAt: true,- },- },- },- },- });- });-- it('sets lastContactAt, organizer member and the calendarEvent item', async () => {- const { client, queryMock, mutationMock } = buildClient(- {- calendarEventParticipants: {- edges: [- {- node: {- id: 'participant-1',- calendarEvent: {- id: CALENDAR_EVENT_ID,- startsAt: PAST_EVENT_STARTS_AT,- },- },- },- ],- },- },- {- calendarEventParticipants: {- edges: [- {- node: {- isOrganizer: false,- workspaceMemberId: '55555555-5555-5555-5555-555555555555',- },- },- { node: { isOrganizer: true, workspaceMemberId: MEMBER_ID } },- ],- },- },- { person: null },- );-- await updatePersonLastContactFromCalendar(client, PERSON_ID);-- expect(queryMock).toHaveBeenNthCalledWith(2, {- calendarEventParticipants: {- __args: {- filter: {- calendarEventId: { eq: CALENDAR_EVENT_ID },- workspaceMemberId: { is: 'NOT_NULL' },- },- first: 200,- },- edges: {- node: {- isOrganizer: true,- workspaceMemberId: true,- },- },- },- });-- const data = mutationMock.mock.calls[0][0].updatePeople.__args.data;- expect(data).toEqual({- lastContactAt: PAST_EVENT_STARTS_AT,- lastContactById: MEMBER_ID,- lastContactItemCalendarEventId: CALENDAR_EVENT_ID,- lastContactItemMessageId: null,- lastOutboundAt: PAST_EVENT_STARTS_AT,- lastInboundAt: PAST_EVENT_STARTS_AT,- lastMeetingId: CALENDAR_EVENT_ID,- });- });-- it('should not update the person when they have no past events', async () => {- const { client, mutationMock } = buildClient({- calendarEventParticipants: { edges: [] },- });-- await updatePersonLastContactFromCalendar(client, PERSON_ID);-- expect(mutationMock).not.toHaveBeenCalled();- });-});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.tsindex 9e622de6353..cb05a671142 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,83 +1,98 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { updateRelatedLastContact } from 'src/utils/update-related-last-contact';+import { updateRelatedLastContactForPeople } from 'src/utils/update-related-last-contact';const PERSON_ID = '11111111-1111-1111-1111-111111111111';+const OTHER_PERSON_ID = '44444444-4444-4444-4444-444444444444';const MESSAGE_ID = '22222222-2222-2222-2222-222222222222';+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 OCCURRED_AT = '2026-06-10T09:00:00.000Z';+const OLDER_OCCURRED_AT = '2026-06-01T09:00:00.000Z';type Client = {query: ReturnType<typeof vi.fn>;mutation: ReturnType<typeof vi.fn>;};-const buildClient = (): Client => ({- query: vi.fn(),+const buildPage = (nodes: Record<string, unknown>[]) => ({+ edges: nodes.map((node) => ({ node })),+ pageInfo: { hasNextPage: false, endCursor: null },+});++const buildClient = ({+ people = [],+ opportunities = [],+}: {+ people?: Record<string, unknown>[];+ opportunities?: Record<string, unknown>[];+}): Client => ({+ query: vi.fn().mockImplementation((query) =>+ query.people+ ? Promise.resolve({ people: buildPage(people) })+ : Promise.resolve({ opportunities: buildPage(opportunities) }),+ ),mutation: vi.fn().mockResolvedValue({}),});let client: Client;beforeEach(() => {- client = buildClient();+ client = buildClient({+ people: [{ id: PERSON_ID, companyId: COMPANY_ID }],+ opportunities: [{ id: 'opportunity-1', pointOfContactId: PERSON_ID }],+ });});-describe('updateRelatedLastContact', () => {- it('updates the company and point-of-contact opportunities for an email', async () => {- client.query.mockResolvedValueOnce({- person: { id: PERSON_ID, companyId: COMPANY_ID },- });-- await updateRelatedLastContact(client as never, {- personId: PERSON_ID,- occurredAt: OCCURRED_AT,- itemId: MESSAGE_ID,- kind: 'email',- });+const findMutation = (name: string) =>+ client.mutation.mock.calls.find((call) => call[0][name])?.[0][name];- const companyCall = client.mutation.mock.calls.find(- (call) => call[0].updateCompanies,+describe('updateRelatedLastContactForPeople', () => {+ it('updates the company and point-of-contact opportunities for an email', async () => {+ await updateRelatedLastContactForPeople(+ client as never,+ new Map([+ [+ PERSON_ID,+ { occurredAt: OCCURRED_AT, itemId: MESSAGE_ID, kind: 'email' as const },+ ],+ ]),);- expect(companyCall?.[0].updateCompanies.__args.data).toEqual({++ const expectedData = {lastContactAt: OCCURRED_AT,lastContactItemMessageId: MESSAGE_ID,lastContactItemCalendarEventId: null,- });- expect(companyCall?.[0].updateCompanies.__args.filter.and[0]).toEqual({+ };+ expect(findMutation('updateCompanies').__args.data).toEqual(expectedData);+ expect(findMutation('updateCompanies').__args.filter.and[0]).toEqual({id: { eq: COMPANY_ID },});-- const opportunityCall = client.mutation.mock.calls.find(- (call) => call[0].updateOpportunities,- );- expect(opportunityCall?.[0].updateOpportunities.__args.filter.and[0]).toEqual(- { pointOfContactId: { eq: PERSON_ID } },+ expect(findMutation('updateOpportunities').__args.data).toEqual(+ expectedData,);- expect(opportunityCall?.[0].updateOpportunities.__args.data).toEqual({- lastContactAt: OCCURRED_AT,- lastContactItemMessageId: MESSAGE_ID,- lastContactItemCalendarEventId: null,+ expect(findMutation('updateOpportunities').__args.filter.and[0]).toEqual({+ pointOfContactId: { eq: PERSON_ID },});});it('sets the calendar event item for a meeting', async () => {- client.query.mockResolvedValueOnce({- person: { id: PERSON_ID, companyId: COMPANY_ID },- });-- await updateRelatedLastContact(client as never, {- personId: PERSON_ID,- occurredAt: OCCURRED_AT,- itemId: CALENDAR_EVENT_ID,- kind: 'meeting',- });-- const companyCall = client.mutation.mock.calls.find(- (call) => call[0].updateCompanies,+ await updateRelatedLastContactForPeople(+ client as never,+ new Map([+ [+ PERSON_ID,+ {+ occurredAt: OCCURRED_AT,+ itemId: CALENDAR_EVENT_ID,+ kind: 'meeting' as const,+ },+ ],+ ]),);- expect(companyCall?.[0].updateCompanies.__args.data).toEqual({++ expect(findMutation('updateCompanies').__args.data).toEqual({lastContactAt: OCCURRED_AT,lastContactItemMessageId: null,lastContactItemCalendarEventId: CALENDAR_EVENT_ID,@@ -85,16 +100,15 @@ describe('updateRelatedLastContact', () => {});it('only guards against newer contacts', async () => {- client.query.mockResolvedValueOnce({- person: { id: PERSON_ID, companyId: COMPANY_ID },- });-- await updateRelatedLastContact(client as never, {- personId: PERSON_ID,- occurredAt: OCCURRED_AT,- itemId: MESSAGE_ID,- kind: 'email',- });+ await updateRelatedLastContactForPeople(+ client as never,+ new Map([+ [+ PERSON_ID,+ { occurredAt: OCCURRED_AT, itemId: MESSAGE_ID, kind: 'email' as const },+ ],+ ]),+ );const expectedGuard = {or: [@@ -102,40 +116,70 @@ describe('updateRelatedLastContact', () => {{ lastContactAt: { lt: OCCURRED_AT } },],};- const companyCall = client.mutation.mock.calls.find(- (call) => call[0].updateCompanies,- );- expect(companyCall?.[0].updateCompanies.__args.filter.and[1]).toEqual(+ expect(findMutation('updateCompanies').__args.filter.and[1]).toEqual(expectedGuard,);- const opportunityCall = client.mutation.mock.calls.find(- (call) => call[0].updateOpportunities,- );- expect(opportunityCall?.[0].updateOpportunities.__args.filter.and[1]).toEqual(+ expect(findMutation('updateOpportunities').__args.filter.and[1]).toEqual(expectedGuard,);});it('skips the company update when the person has no company but still updates opportunities', async () => {- client.query.mockResolvedValueOnce({- person: { id: PERSON_ID, companyId: null },+ client = buildClient({+ people: [{ id: PERSON_ID, companyId: null }],+ opportunities: [{ id: 'opportunity-1', pointOfContactId: PERSON_ID }],});- await updateRelatedLastContact(client as never, {- personId: PERSON_ID,- occurredAt: OCCURRED_AT,- itemId: MESSAGE_ID,- kind: 'email',+ await updateRelatedLastContactForPeople(+ client as never,+ new Map([+ [+ PERSON_ID,+ { occurredAt: OCCURRED_AT, itemId: MESSAGE_ID, kind: 'email' as const },+ ],+ ]),+ );++ expect(findMutation('updateCompanies')).toBeUndefined();+ expect(findMutation('updateOpportunities').__args.filter.and[0]).toEqual({+ pointOfContactId: { eq: PERSON_ID },});+ });- expect(- client.mutation.mock.calls.some((call) => call[0].updateCompanies),- ).toBe(false);- const opportunityCall = client.mutation.mock.calls.find(- (call) => call[0].updateOpportunities,+ 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([+ [+ PERSON_ID,+ {+ occurredAt: OLDER_OCCURRED_AT,+ itemId: OLDER_MESSAGE_ID,+ kind: 'email' as const,+ },+ ],+ [+ OTHER_PERSON_ID,+ { occurredAt: OCCURRED_AT, itemId: MESSAGE_ID, kind: 'email' as const },+ ],+ ]),);- expect(opportunityCall?.[0].updateOpportunities.__args.filter.and[0]).toEqual(- { pointOfContactId: { eq: PERSON_ID } },++ const companyUpdates = client.mutation.mock.calls.filter(+ ([mutation]) => mutation.updateCompanies,);+ expect(companyUpdates).toHaveLength(1);+ expect(companyUpdates[0][0].updateCompanies.__args.data).toEqual({+ lastContactAt: OCCURRED_AT,+ lastContactItemMessageId: MESSAGE_ID,+ lastContactItemCalendarEventId: null,+ });});});diff --git a/packages/twenty-apps/public/last-contact/src/utils/apply-email-interactions.ts b/packages/twenty-apps/public/last-contact/src/utils/apply-email-interactions.tsnew file mode 100644index 00000000000..0e1c3dc93f7--- /dev/null+++ b/packages/twenty-apps/public/last-contact/src/utils/apply-email-interactions.ts@@ -0,0 +1,75 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { collectMessageInteractions } from 'src/utils/collect-message-interactions';+import {+ type Interaction,+ pickLatestInteraction,+ updatePersonForInteractions,+} from 'src/utils/update-person-last-contact';+import {+ type RelatedInteraction,+ updateRelatedLastContactForPeople,+} from 'src/utils/update-related-last-contact';++export type MessageParticipantLink = {+ personId: string;+ messageId: string;+};++export const applyEmailInteractions = async (+ client: CoreApiClient,+ links: MessageParticipantLink[],+): Promise<void> => {+ const messageIds = [...new Set(links.map((link) => link.messageId))];++ if (messageIds.length === 0) {+ return;+ }++ const interactionByMessageId = await collectMessageInteractions(+ client,+ messageIds,+ );+ const interactionsByPersonId = new Map<string, Interaction[]>();++ for (const { personId, messageId } of links) {+ const message = interactionByMessageId.get(messageId);++ if (!message) {+ continue;+ }++ const interaction: Interaction = {+ kind: 'email',+ occurredAt: message.receivedAt,+ itemId: messageId,+ workspaceMemberId: message.workspaceMemberId,+ direction: message.direction,+ };+ const interactions = interactionsByPersonId.get(personId);++ if (interactions) {+ interactions.push(interaction);+ } else {+ interactionsByPersonId.set(personId, [interaction]);+ }+ }++ const contactByPersonId = new Map<string, RelatedInteraction>();++ for (const [personId, interactions] of interactionsByPersonId) {+ await updatePersonForInteractions(client, personId, interactions);++ const latest = pickLatestInteraction(interactions);++ if (latest) {+ contactByPersonId.set(personId, {+ occurredAt: latest.occurredAt,+ itemId: latest.itemId,+ kind: 'email',+ });+ }+ }++ await updateRelatedLastContactForPeople(client, contactByPersonId);+};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.tsnew file mode 100644index 00000000000..1dfdd578746--- /dev/null+++ b/packages/twenty-apps/public/last-contact/src/utils/apply-meeting-interactions.ts@@ -0,0 +1,76 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { collectCalendarEventInteractions } from 'src/utils/collect-calendar-event-interactions';+import {+ type Interaction,+ pickLatestInteraction,+ updatePersonForInteractions,+} from 'src/utils/update-person-last-contact';+import {+ type RelatedInteraction,+ updateRelatedLastContactForPeople,+} from 'src/utils/update-related-last-contact';++export type CalendarEventParticipantLink = {+ personId: string;+ calendarEventId: string;+};++export const applyMeetingInteractions = async (+ client: CoreApiClient,+ links: CalendarEventParticipantLink[],+): Promise<void> => {+ const calendarEventIds = [+ ...new Set(links.map((link) => link.calendarEventId)),+ ];++ if (calendarEventIds.length === 0) {+ return;+ }++ const interactionByCalendarEventId = await collectCalendarEventInteractions(+ client,+ calendarEventIds,+ );+ const interactionsByPersonId = new Map<string, Interaction[]>();++ for (const { personId, calendarEventId } of links) {+ const calendarEvent = interactionByCalendarEventId.get(calendarEventId);++ if (!calendarEvent) {+ continue;+ }++ const interaction: Interaction = {+ kind: 'meeting',+ occurredAt: calendarEvent.startsAt,+ itemId: calendarEventId,+ workspaceMemberId: calendarEvent.workspaceMemberId,+ };+ const interactions = interactionsByPersonId.get(personId);++ if (interactions) {+ interactions.push(interaction);+ } else {+ interactionsByPersonId.set(personId, [interaction]);+ }+ }++ const contactByPersonId = new Map<string, RelatedInteraction>();++ for (const [personId, interactions] of interactionsByPersonId) {+ await updatePersonForInteractions(client, personId, interactions);++ const latest = pickLatestInteraction(interactions);++ if (latest) {+ contactByPersonId.set(personId, {+ occurredAt: latest.occurredAt,+ itemId: latest.itemId,+ kind: 'meeting',+ });+ }+ }++ await updateRelatedLastContactForPeople(client, contactByPersonId);+};diff --git a/packages/twenty-apps/public/last-contact/src/utils/chunk.ts b/packages/twenty-apps/public/last-contact/src/utils/chunk.tsnew file mode 100644index 00000000000..010469cb908--- /dev/null+++ b/packages/twenty-apps/public/last-contact/src/utils/chunk.ts@@ -0,0 +1,9 @@+export const chunk = <TItem>(items: TItem[], size: number): TItem[][] => {+ const chunks: TItem[][] = [];++ for (let index = 0; index < items.length; index += size) {+ chunks.push(items.slice(index, index + size));+ }++ return chunks;+};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.tsnew file mode 100644index 00000000000..caf36fe3395--- /dev/null+++ b/packages/twenty-apps/public/last-contact/src/utils/collect-calendar-event-interactions.ts@@ -0,0 +1,106 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { chunk } from 'src/utils/chunk';+import { executeWithRetry } from 'src/utils/execute-with-retry';+import {+ pickContactTeamMemberId,+ type Participant,+} from 'src/utils/pick-contact-team-member';++const PAGE_SIZE = 200;++export type CalendarEventInteraction = {+ startsAt: string;+ workspaceMemberId: string | null;+};++type CalendarEventParticipantNode = Participant & {+ calendarEventId?: string | null;+ calendarEvent?: {+ startsAt: string | null;+ isCanceled: boolean | null;+ } | null;+};++export const collectCalendarEventInteractions = async (+ client: CoreApiClient,+ calendarEventIds: string[],+): Promise<Map<string, CalendarEventInteraction>> => {+ const participantsByCalendarEventId = new Map<+ string,+ CalendarEventParticipantNode[]+ >();++ for (const ids of chunk(calendarEventIds, PAGE_SIZE)) {+ let after: string | undefined;++ do {+ const { calendarEventParticipants } = await executeWithRetry(() =>+ client.query({+ calendarEventParticipants: {+ __args: {+ filter: { calendarEventId: { in: ids } },+ first: PAGE_SIZE,+ after,+ },+ edges: {+ node: {+ calendarEventId: true,+ isOrganizer: true,+ workspaceMemberId: true,+ calendarEvent: { startsAt: true, isCanceled: true },+ },+ },+ pageInfo: { hasNextPage: true, endCursor: true },+ },+ }),+ );++ for (const edge of calendarEventParticipants?.edges ?? []) {+ const node = edge.node as CalendarEventParticipantNode;++ if (!node.calendarEventId) {+ continue;+ }++ const participants = participantsByCalendarEventId.get(+ node.calendarEventId,+ );++ if (participants) {+ participants.push(node);+ } else {+ participantsByCalendarEventId.set(node.calendarEventId, [node]);+ }+ }++ after = calendarEventParticipants?.pageInfo.hasNextPage+ ? (calendarEventParticipants.pageInfo.endCursor ?? undefined)+ : undefined;+ } while (after);+ }++ const now = new Date().toISOString();+ const interactionByCalendarEventId = new Map<+ string,+ CalendarEventInteraction+ >();++ for (const [calendarEventId, participants] of participantsByCalendarEventId) {+ const calendarEvent = participants[0]?.calendarEvent;+ const startsAt = calendarEvent?.startsAt ?? null;++ if (!startsAt || calendarEvent?.isCanceled || startsAt > now) {+ continue;+ }++ interactionByCalendarEventId.set(calendarEventId, {+ startsAt,+ workspaceMemberId: pickContactTeamMemberId(participants, {+ isOrganizer: true,+ }),+ });+ }++ return interactionByCalendarEventId;+};diff --git a/packages/twenty-apps/public/last-contact/src/utils/collect-message-interactions.ts b/packages/twenty-apps/public/last-contact/src/utils/collect-message-interactions.tsnew file mode 100644index 00000000000..8f67529de3c--- /dev/null+++ b/packages/twenty-apps/public/last-contact/src/utils/collect-message-interactions.ts@@ -0,0 +1,100 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { chunk } from 'src/utils/chunk';+import { executeWithRetry } from 'src/utils/execute-with-retry';+import {+ pickContactTeamMemberId,+ type Participant,+} from 'src/utils/pick-contact-team-member';+import { type InteractionDirection } from 'src/utils/update-person-last-contact';++const PAGE_SIZE = 200;++export type MessageInteraction = {+ receivedAt: string;+ workspaceMemberId: string | null;+ direction: InteractionDirection;+};++type MessageParticipantNode = Participant & {+ messageId?: string | null;+ message?: { receivedAt: string | null } | null;+};++export const collectMessageInteractions = async (+ client: CoreApiClient,+ messageIds: string[],+): Promise<Map<string, MessageInteraction>> => {+ const participantsByMessageId = new Map<string, MessageParticipantNode[]>();++ for (const ids of chunk(messageIds, PAGE_SIZE)) {+ let after: string | undefined;++ do {+ const { messageParticipants } = await executeWithRetry(() =>+ client.query({+ messageParticipants: {+ __args: {+ filter: { messageId: { in: ids } },+ first: PAGE_SIZE,+ after,+ },+ edges: {+ node: {+ messageId: true,+ role: true,+ workspaceMemberId: true,+ message: { receivedAt: true },+ },+ },+ pageInfo: { hasNextPage: true, endCursor: true },+ },+ }),+ );++ for (const edge of messageParticipants?.edges ?? []) {+ const node = edge.node as MessageParticipantNode;++ if (!node.messageId) {+ continue;+ }++ const participants = participantsByMessageId.get(node.messageId);++ if (participants) {+ participants.push(node);+ } else {+ participantsByMessageId.set(node.messageId, [node]);+ }+ }++ after = messageParticipants?.pageInfo.hasNextPage+ ? (messageParticipants.pageInfo.endCursor ?? undefined)+ : undefined;+ } while (after);+ }++ const interactionByMessageId = new Map<string, MessageInteraction>();++ for (const [messageId, participants] of participantsByMessageId) {+ const receivedAt = participants[0]?.message?.receivedAt ?? null;++ if (!receivedAt) {+ continue;+ }++ const fromParticipant = participants.find(+ (participant) => participant.role === 'FROM',+ );++ interactionByMessageId.set(messageId, {+ receivedAt,+ workspaceMemberId: pickContactTeamMemberId(participants, {+ role: 'FROM',+ }),+ direction: fromParticipant?.workspaceMemberId ? 'outbound' : 'inbound',+ });+ }++ return interactionByMessageId;+};diff --git a/packages/twenty-apps/public/last-contact/src/utils/person-last-contact-aggregation.ts b/packages/twenty-apps/public/last-contact/src/utils/person-last-contact-aggregation.tsindex 5b4b3faeb64..246891c0d63 100644--- a/packages/twenty-apps/public/last-contact/src/utils/person-last-contact-aggregation.ts+++ b/packages/twenty-apps/public/last-contact/src/utils/person-last-contact-aggregation.ts@@ -1,5 +1,6 @@import { type CoreApiClient } from 'twenty-client-sdk/core';+import { chunk } from 'src/utils/chunk';import { executeWithRetry } from 'src/utils/execute-with-retry';const PAGE_SIZE = 200;@@ -30,14 +31,6 @@ export type PersonAgg = {lastMeeting?: { at: string; id: string };};-const chunk = <T>(items: T[], size: number): T[][] => {- const chunks: T[][] = [];- for (let i = 0; i < items.length; i += size) {- chunks.push(items.slice(i, i + size));- }- return chunks;-};-const collectEmailInteractions = async (client: CoreApiClient,personIds: string[],diff --git a/packages/twenty-apps/public/last-contact/src/utils/recompute-company-last-contact.ts b/packages/twenty-apps/public/last-contact/src/utils/recompute-company-last-contact.tsindex 669c96e4580..7ab69c74397 100644--- a/packages/twenty-apps/public/last-contact/src/utils/recompute-company-last-contact.ts+++ b/packages/twenty-apps/public/last-contact/src/utils/recompute-company-last-contact.ts@@ -1,5 +1,7 @@import { type CoreApiClient } from 'twenty-client-sdk/core';+import { executeWithRetry } from 'src/utils/execute-with-retry';+type PersonNode = {lastContactAt?: string | null;lastContactItemMessage?: { id: string } | null;@@ -13,40 +15,54 @@ export const recomputeCompanyLastContact = async (client: CoreApiClient,companyId: string,): Promise<void> => {- const { people } = await client.query({- people: {- __args: {- filter: {- companyId: { eq: companyId },- lastContactAt: { is: 'NOT_NULL' },+ const { people } = await executeWithRetry(() =>+ client.query({+ people: {+ __args: {+ filter: {+ companyId: { eq: companyId },+ lastContactAt: { is: 'NOT_NULL' },+ },+ orderBy: [{ lastContactAt: 'DescNullsLast' }],+ first: 1,},- orderBy: [{ lastContactAt: 'DescNullsLast' }],- first: 1,- },- edges: {- node: {- lastContactAt: true,- lastContactItemMessage: { id: true },- lastContactItemCalendarEvent: { id: true },+ edges: {+ node: {+ lastContactAt: true,+ lastContactItemMessage: { id: true },+ lastContactItemCalendarEvent: { id: true },+ },},},- },- });+ }),+ );const topPerson = (people?.edges?.[0]?.node as PersonNode | undefined) ?? {};- await client.mutation({- updateCompany: {- __args: {- id: companyId,- data: {- lastContactAt: topPerson.lastContactAt ?? null,- lastContactItemMessageId: topPerson.lastContactItemMessage?.id ?? null,- lastContactItemCalendarEventId:- topPerson.lastContactItemCalendarEvent?.id ?? null,+ await executeWithRetry(() =>+ client.mutation({+ updateCompany: {+ __args: {+ id: companyId,+ data: {+ lastContactAt: topPerson.lastContactAt ?? null,+ lastContactItemMessageId:+ topPerson.lastContactItemMessage?.id ?? null,+ lastContactItemCalendarEventId:+ topPerson.lastContactItemCalendarEvent?.id ?? null,+ },},+ id: true,},- id: true,- },- });+ }),+ );+};++export const recomputeCompaniesLastContact = async (+ client: CoreApiClient,+ companyIds: string[],+): Promise<void> => {+ for (const companyId of companyIds) {+ await recomputeCompanyLastContact(client, companyId);+ }};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.tsindex d04bb78b1bd..93c123969e6 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@@ -1,5 +1,10 @@import { type CoreApiClient } from 'twenty-client-sdk/core';+import { chunk } from 'src/utils/chunk';+import { executeWithRetry } from 'src/utils/execute-with-retry';++const PAGE_SIZE = 200;+type LastContactData = Record<string, string | null>;const EMPTY_LAST_CONTACT: LastContactData = {@@ -14,52 +19,135 @@ type PersonLastContact = {lastContactItemCalendarEvent?: { id: string } | null;};+const collectPointOfContactIdByOpportunityId = async (+ client: CoreApiClient,+ opportunityIds: string[],+): Promise<Map<string, string | null>> => {+ const pointOfContactIdByOpportunityId = new Map<string, string | null>();++ for (const ids of chunk(opportunityIds, PAGE_SIZE)) {+ let after: string | undefined;++ do {+ 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 },+ },+ },+ pageInfo: { hasNextPage: true, endCursor: true },+ },+ }),+ );++ for (const edge of people?.edges ?? []) {+ const person = edge.node as PersonLastContact & { id?: string | null };++ if (!person.id) {+ continue;+ }++ 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)+ : 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 recomputeOpportunityLastContact = async (+export const recomputeOpportunitiesLastContact = async (client: CoreApiClient,- opportunityId: string,+ opportunityIds: string[],): Promise<void> => {- const { opportunity } = await client.query({- opportunity: {- __args: { filter: { id: { eq: opportunityId } } },- id: true,- pointOfContactId: true,- },- });-- const pointOfContactId =- (opportunity as { pointOfContactId?: string | null } | null | undefined)- ?.pointOfContactId ?? null;-- let data: LastContactData = EMPTY_LAST_CONTACT;-- if (pointOfContactId) {- const { person } = await client.query({- person: {- __args: { filter: { id: { eq: pointOfContactId } } },- id: true,- lastContactAt: true,- lastContactItemMessage: { id: true },- lastContactItemCalendarEvent: { id: true },- },- });-- const current = (person ?? {}) as PersonLastContact;-- data = {- lastContactAt: current.lastContactAt ?? null,- lastContactItemMessageId: current.lastContactItemMessage?.id ?? null,- lastContactItemCalendarEventId:- current.lastContactItemCalendarEvent?.id ?? null,- };+ if (opportunityIds.length === 0) {+ return;}- await client.mutation({- updateOpportunity: {- __args: { id: opportunityId, data },- id: true,- },- });+ const pointOfContactIdByOpportunityId =+ await collectPointOfContactIdByOpportunityId(client, opportunityIds);+ const personIds = [+ ...new Set(+ [...pointOfContactIdByOpportunityId.values()].filter(+ (pointOfContactId): pointOfContactId is string => !!pointOfContactId,+ ),+ ),+ ];+ const lastContactByPersonId = await collectLastContactByPersonId(+ client,+ personIds,+ );++ for (const [+ opportunityId,+ pointOfContactId,+ ] of pointOfContactIdByOpportunityId) {+ const data =+ (pointOfContactId+ ? lastContactByPersonId.get(pointOfContactId)+ : undefined) ?? EMPTY_LAST_CONTACT;++ await executeWithRetry(() =>+ client.mutation({+ updateOpportunity: {+ __args: { id: opportunityId, data },+ id: true,+ },+ }),+ );+ }};diff --git a/packages/twenty-apps/public/last-contact/src/utils/update-person-last-contact-from-calendar.ts b/packages/twenty-apps/public/last-contact/src/utils/update-person-last-contact-from-calendar.tsdeleted file mode 100644index c674569736a..00000000000--- a/packages/twenty-apps/public/last-contact/src/utils/update-person-last-contact-from-calendar.ts+++ /dev/null@@ -1,88 +0,0 @@-import { type CoreApiClient } from 'twenty-client-sdk/core';--import { pickContactTeamMemberId } from 'src/utils/pick-contact-team-member';-import { updatePersonForInteraction } from 'src/utils/update-person-last-contact';-import { updateRelatedLastContact } from 'src/utils/update-related-last-contact';--export const updatePersonLastContactFromCalendar = async (- client: CoreApiClient,- personId: string,-): Promise<void> => {- const now = new Date().toISOString();-- const { calendarEventParticipants } = await client.query({- calendarEventParticipants: {- __args: {- filter: {- personId: { eq: personId },- calendarEvent: {- startsAt: { lte: now },- isCanceled: { eq: false },- },- },- orderBy: [{ calendarEvent: { startsAt: 'DescNullsLast' } }],- first: 1,- },- edges: {- node: {- id: true,- calendarEvent: {- id: true,- startsAt: true,- },- },- },- },- });-- const calendarEvent =- calendarEventParticipants?.edges[0]?.node?.calendarEvent ?? null;- const occurredAt = calendarEvent?.startsAt ?? null;-- if (!calendarEvent?.id || !occurredAt) {- return;- }-- const { calendarEventParticipants: memberParticipants } = await client.query({- calendarEventParticipants: {- __args: {- filter: {- calendarEventId: { eq: calendarEvent.id },- workspaceMemberId: { is: 'NOT_NULL' },- },- first: 200,- },- edges: {- node: {- isOrganizer: true,- workspaceMemberId: true,- },- },- },- });-- const participants =- memberParticipants?.edges?.map(- (edge: {- node: { isOrganizer: boolean | null; workspaceMemberId: string | null };- }) => edge.node,- ) ?? [];- const workspaceMemberId = pickContactTeamMemberId(participants, {- isOrganizer: true,- });-- await updatePersonForInteraction(client, {- personId,- occurredAt,- kind: 'meeting',- itemId: calendarEvent.id,- workspaceMemberId,- });-- await updateRelatedLastContact(client, {- personId,- occurredAt,- itemId: calendarEvent.id,- kind: 'meeting',- });-};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.tsindex 75582581a1c..d293c197992 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@@ -1,10 +1,11 @@import { type CoreApiClient } from 'twenty-client-sdk/core';+import { executeWithRetry } from 'src/utils/execute-with-retry';+export type InteractionKind = 'email' | 'meeting';export type InteractionDirection = 'outbound' | 'inbound';export type Interaction = {- personId: string;occurredAt: string;itemId: string;workspaceMemberId: string | null;@@ -15,23 +16,53 @@ const isNewer = (current: string | null | undefined,): boolean => !current || current < candidate;-export const updatePersonForInteraction = async (+const touchesOutbound = (interaction: Interaction): boolean =>+ interaction.kind === 'meeting' || interaction.direction === 'outbound';++const touchesInbound = (interaction: Interaction): boolean =>+ interaction.kind === 'meeting' || interaction.direction === 'inbound';++const pickLatest = (+ interactions: Interaction[],+ matches: (interaction: Interaction) => boolean = () => true,+): Interaction | undefined =>+ interactions.reduce<Interaction | undefined>(+ (latest, interaction) =>+ matches(interaction) &&+ (!latest || interaction.occurredAt > latest.occurredAt)+ ? interaction+ : latest,+ undefined,+ );++export const pickLatestInteraction = (+ interactions: Interaction[],+): Interaction | undefined => pickLatest(interactions);++export const updatePersonForInteractions = async (client: CoreApiClient,- interaction: Interaction,+ personId: string,+ interactions: Interaction[],): Promise<void> => {- const { personId, occurredAt, kind, itemId, workspaceMemberId } = interaction;-- const { person } = await client.query({- person: {- __args: { filter: { id: { eq: personId } } },- id: true,- lastContactAt: true,- lastOutboundAt: true,- lastInboundAt: true,- lastEmail: { receivedAt: true },- lastMeeting: { startsAt: true },- },- });+ const latestContact = pickLatest(interactions);++ if (!latestContact) {+ return;+ }++ const { person } = await executeWithRetry(() =>+ client.query({+ person: {+ __args: { filter: { id: { eq: personId } } },+ id: true,+ lastContactAt: true,+ lastOutboundAt: true,+ lastInboundAt: true,+ lastEmail: { receivedAt: true },+ lastMeeting: { startsAt: true },+ },+ }),+ );const current = (person ?? {}) as {lastContactAt?: string | null;@@ -42,35 +73,54 @@ export const updatePersonForInteraction = async (};const data: Record<string, string | null> = {};+ const occurredAt = latestContact.occurredAt;if (isNewer(occurredAt, current.lastContactAt)) {data.lastContactAt = occurredAt;- data.lastContactById = workspaceMemberId ?? null;- if (kind === 'email') {- data.lastContactItemMessageId = itemId;+ data.lastContactById = latestContact.workspaceMemberId ?? null;+ if (latestContact.kind === 'email') {+ data.lastContactItemMessageId = latestContact.itemId;data.lastContactItemCalendarEventId = null;} else {- data.lastContactItemCalendarEventId = itemId;+ data.lastContactItemCalendarEventId = latestContact.itemId;data.lastContactItemMessageId = null;}}- const touchesOutbound =- interaction.kind === 'meeting' || interaction.direction === 'outbound';- const touchesInbound =- interaction.kind === 'meeting' || interaction.direction === 'inbound';-- if (touchesOutbound && isNewer(occurredAt, current.lastOutboundAt)) {- data.lastOutboundAt = occurredAt;+ const latestOutbound = pickLatest(interactions, touchesOutbound);+ const latestInbound = pickLatest(interactions, touchesInbound);+ const latestEmail = pickLatest(+ interactions,+ (interaction) => interaction.kind === 'email',+ );+ const latestMeeting = pickLatest(+ interactions,+ (interaction) => interaction.kind === 'meeting',+ );++ if (+ latestOutbound &&+ isNewer(latestOutbound.occurredAt, current.lastOutboundAt)+ ) {+ data.lastOutboundAt = latestOutbound.occurredAt;}- if (touchesInbound && isNewer(occurredAt, current.lastInboundAt)) {- data.lastInboundAt = occurredAt;+ if (+ latestInbound &&+ isNewer(latestInbound.occurredAt, current.lastInboundAt)+ ) {+ data.lastInboundAt = latestInbound.occurredAt;}- if (kind === 'email' && isNewer(occurredAt, current.lastEmail?.receivedAt)) {- data.lastEmailId = itemId;+ if (+ latestEmail &&+ isNewer(latestEmail.occurredAt, current.lastEmail?.receivedAt)+ ) {+ data.lastEmailId = latestEmail.itemId;}- if (kind === 'meeting' && isNewer(occurredAt, current.lastMeeting?.startsAt)) {- data.lastMeetingId = itemId;+ if (+ latestMeeting &&+ isNewer(latestMeeting.occurredAt, current.lastMeeting?.startsAt)+ ) {+ data.lastMeetingId = latestMeeting.itemId;}if (Object.keys(data).length === 0) {@@ -78,25 +128,27 @@ export const updatePersonForInteraction = async (}if ('lastContactAt' in data) {- const { updatePeople } = await client.mutation({- updatePeople: {- __args: {- data,- filter: {- and: [- { id: { eq: personId } },- {- or: [- { lastContactAt: { is: 'NULL' } },- { lastContactAt: { lt: occurredAt } },- ],- },- ],+ const { updatePeople } = await executeWithRetry(() =>+ client.mutation({+ updatePeople: {+ __args: {+ data,+ filter: {+ and: [+ { id: { eq: personId } },+ {+ or: [+ { lastContactAt: { is: 'NULL' } },+ { lastContactAt: { lt: occurredAt } },+ ],+ },+ ],+ },},+ id: true,},- id: true,- },- });+ }),+ );if (Array.isArray(updatePeople) && updatePeople.length > 0) {return;@@ -112,19 +164,23 @@ export const updatePersonForInteraction = async (return;}- await client.mutation({- updatePerson: {- __args: { id: personId, data: directionalData },- id: true,- },- });+ await executeWithRetry(() =>+ client.mutation({+ updatePerson: {+ __args: { id: personId, data: directionalData },+ id: true,+ },+ }),+ );return;}- await client.mutation({- updatePerson: {- __args: { id: personId, data },- id: true,- },- });+ await executeWithRetry(() =>+ client.mutation({+ updatePerson: {+ __args: { id: personId, data },+ id: 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.tsindex 41beba83a4f..d241713a02a 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@@ -1,9 +1,12 @@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';+const PAGE_SIZE = 200;+export type RelatedInteraction = {- personId: string;occurredAt: string;itemId: string;kind: InteractionKind;@@ -20,56 +23,166 @@ const buildData = ({occurredAt,itemId,kind,-}: Omit<RelatedInteraction, 'personId'>): Record<string, string | null> => ({+}: RelatedInteraction): Record<string, string | null> => ({lastContactAt: occurredAt,lastContactItemMessageId: kind === 'email' ? itemId : null,lastContactItemCalendarEventId: kind === 'meeting' ? itemId : null,});+const collectCompanyIdByPersonId = 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 collectPointOfContactIds = async (+ client: CoreApiClient,+ personIds: string[],+): Promise<Set<string>> => {+ const pointOfContactIds = new Set<string>();++ for (const ids of chunk(personIds, PAGE_SIZE)) {+ let after: string | undefined;++ do {+ const { opportunities } = await executeWithRetry(() =>+ client.query({+ opportunities: {+ __args: {+ filter: { pointOfContactId: { in: ids } },+ first: PAGE_SIZE,+ after,+ },+ edges: { node: { id: true, pointOfContactId: true } },+ pageInfo: { hasNextPage: true, endCursor: true },+ },+ }),+ );++ for (const edge of opportunities?.edges ?? []) {+ const { pointOfContactId } = edge.node;++ if (pointOfContactId) {+ pointOfContactIds.add(pointOfContactId);+ }+ }++ after = opportunities?.pageInfo.hasNextPage+ ? (opportunities.pageInfo.endCursor ?? undefined)+ : undefined;+ } while (after);+ }++ return pointOfContactIds;+};+// Companies and opportunities surface emails and meetings from their related// people, so their last contact mirrors the most recent contact of any person// connected to them.-export const updateRelatedLastContact = async (+export const updateRelatedLastContactForPeople = async (client: CoreApiClient,- { personId, occurredAt, itemId, kind }: RelatedInteraction,+ contactByPersonId: Map<string, RelatedInteraction>,): Promise<void> => {- const personResult = await client.query({- person: {- __args: { filter: { id: { eq: personId } } },- id: true,- companyId: true,- },- });-- const companyId =- (personResult?.person as { companyId?: string | null } | null | undefined)- ?.companyId ?? null;- const data = buildData({ occurredAt, itemId, kind });-- if (companyId) {- await client.mutation({- updateCompanies: {- __args: {- data,- filter: { and: [{ id: { eq: companyId } }, recencyGuard(occurredAt)] },+ const personIds = [...contactByPersonId.keys()];++ if (personIds.length === 0) {+ return;+ }++ const companyIdByPersonId = await collectCompanyIdByPersonId(+ client,+ personIds,+ );+ const contactByCompanyId = new Map<string, RelatedInteraction>();++ for (const [personId, contact] of contactByPersonId) {+ const companyId = companyIdByPersonId.get(personId);++ if (!companyId) {+ continue;+ }++ const current = contactByCompanyId.get(companyId);++ if (!current || contact.occurredAt > current.occurredAt) {+ contactByCompanyId.set(companyId, contact);+ }+ }++ for (const [companyId, contact] of contactByCompanyId) {+ await executeWithRetry(() =>+ client.mutation({+ updateCompanies: {+ __args: {+ data: buildData(contact),+ filter: {+ and: [+ { id: { eq: companyId } },+ recencyGuard(contact.occurredAt),+ ],+ },+ },+ id: true,},- id: true,- },- });+ }),+ );}- await client.mutation({- updateOpportunities: {- __args: {- data,- filter: {- and: [- { pointOfContactId: { eq: personId } },- recencyGuard(occurredAt),- ],+ const pointOfContactIds = await collectPointOfContactIds(client, personIds);++ for (const personId of pointOfContactIds) {+ const contact = contactByPersonId.get(personId);++ if (!contact) {+ continue;+ }++ await executeWithRetry(() =>+ client.mutation({+ updateOpportunities: {+ __args: {+ data: buildData(contact),+ filter: {+ and: [+ { pointOfContactId: { eq: personId } },+ recencyGuard(contact.occurredAt),+ ],+ },+ },+ id: true,},- },- id: true,- },- });+ }),+ );+ }};diff --git a/packages/twenty-apps/public/last-contact/yarn.lock b/packages/twenty-apps/public/last-contact/yarn.lockindex 198dd30e352..47629f40c3e 100644--- a/packages/twenty-apps/public/last-contact/yarn.lock+++ b/packages/twenty-apps/public/last-contact/yarn.lock@@ -971,8 +971,8 @@ __metadata:oxlint: "npm:^0.16.0"react: "npm:^19.0.0"react-dom: "npm:^19.0.0"- twenty-client-sdk: "npm:2.37.0"- twenty-sdk: "npm:2.37.0"+ twenty-client-sdk: "npm:2.40.0"+ twenty-sdk: "npm:2.40.0"typescript: "npm:^5.9.3"vite-tsconfig-paths: "npm:^4.2.1"vitest: "npm:^4.0.0"@@ -2857,22 +2857,22 @@ __metadata:languageName: nodelinkType: hard-"twenty-client-sdk@npm:2.37.0":- version: 2.37.0- resolution: "twenty-client-sdk@npm:2.37.0"+"twenty-client-sdk@npm:2.40.0":+ version: 2.40.0+ resolution: "twenty-client-sdk@npm:2.40.0"dependencies:"@genql/runtime": "npm:^2.10.0"esbuild: "npm:^0.28.1"graphql: "npm:^16.8.1"lodash: "npm:^4.17.21"prettier: "npm:^3.8.3"- checksum: 10c0/0250a95b803a468f7bd9261b7a55a862b9b6daf840adf21ab7a4067906761e710703f79f7571f6400716afc4e612eda7da2bb1948c23a5adff07d59cc30ba10e+ checksum: 10c0/60d046ffe7aa289607933e9442fed05f9f8e97b64d6acbe3bbcfe065184cd6c76e86fcc6530d609d6f54d600b5302b2ac709ffddd16737d2e83f3d56b67256c0languageName: nodelinkType: hard-"twenty-sdk@npm:2.37.0":- version: 2.37.0- resolution: "twenty-sdk@npm:2.37.0"+"twenty-sdk@npm:2.40.0":+ version: 2.40.0+ resolution: "twenty-sdk@npm:2.40.0"dependencies:"@sniptt/guards": "npm:^0.2.0"axios: "npm:^1.16.0"@@ -2891,12 +2891,12 @@ __metadata:semver: "npm:7.6.3"sharp: "npm:^0.35.3"tinyglobby: "npm:^0.2.15"- twenty-client-sdk: "npm:2.37.0"+ twenty-client-sdk: "npm:2.40.0"typescript: "npm:^5.9.3"uuid: "npm:^13.0.2"bin:twenty: dist/cli.cjs- checksum: 10c0/ddbc01430cfbcc878d2b23851b5f5ae7a76fb453d5a578e876ab7e999093a62aa8c025d22b1095d20fad363f8e6cf885a7c002ad64498fdbb9dfc695a1fc1f9c+ checksum: 10c0/74fab301ba98f17ad16396eb48a55af43ea8d4583e8e863c4248774962dce5a272fcb24ae78c8214f2997c9146b3815e1542c202d52ed89d035550eaa8151d96languageName: nodelinkType: hard