Skip to content

The open alternative to Salesforce, designed for AI.

fix(last-contact): batch API writes so a mailbox sync stays inside the rate limit (#26110)

martmull4b25edfeb978
diff --git a/packages/twenty-apps/public/last-contact/CHANGELOG.md b/packages/twenty-apps/public/last-contact/CHANGELOG.md
index 1ce4eef8bbf..e916cdad45c 100644
--- a/packages/twenty-apps/public/last-contact/CHANGELOG.md
+++ b/packages/twenty-apps/public/last-contact/CHANGELOG.md
@@ -1,5 +1,12 @@
# Changelog
+## 1.4.0
+
+- Write a whole batch of records in one API call instead of one call per record. The application API rate limit is consumed once per operation and `updateMany` applies a single payload to everything it matches, so writing one timestamp per person, company or opportunity cost one call each: a full 200-event batch spent 435-585 calls against a budget of 500 per minute shared by every workspace on the instance. Reads are batched the same way, and each handler now costs about nine calls. The recency guard that used to be a filter on the update moved into the read that precedes it, and a record the read does not return is left out of the write rather than upserted back.
+- Resolve every company's most recently contacted person by scanning the batch's people ordered by contact recency and keeping the first row each company produces, instead of one indexed lookup per company. One page settles the whole batch in the common case; the scan is capped so a single company with a long contact history cannot page through all of it to reach the others, and whatever the cap leaves unresolved falls back to one lookup each.
+- Retry the calendar cron's own queries, which bypassed the retry helper.
+- Raise the default backfill batch size to 200 now that a batch is written in one call.
+
## 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.
diff --git a/packages/twenty-apps/public/last-contact/package.json b/packages/twenty-apps/public/last-contact/package.json
index 3ef3c908583..936eae6a99c 100644
--- a/packages/twenty-apps/public/last-contact/package.json
+++ b/packages/twenty-apps/public/last-contact/package.json
@@ -1,6 +1,6 @@
{
"name": "@twentyhq/last-contact",
- "version": "1.3.0",
+ "version": "1.4.0",
"license": "MIT",
"engines": {
"node": "^24.5.0",
diff --git a/packages/twenty-apps/public/last-contact/src/constants/backfill.ts b/packages/twenty-apps/public/last-contact/src/constants/backfill.ts
index 8ec5b9a7c1f..fc22b95f913 100644
--- a/packages/twenty-apps/public/last-contact/src/constants/backfill.ts
+++ b/packages/twenty-apps/public/last-contact/src/constants/backfill.ts
@@ -37,5 +37,5 @@ export const BACKFILL_BATCH_SIZE_ENV_VAR_NAME =
'LAST_CONTACT_BACKFILL_BATCH_SIZE';
export const BACKFILL_SLEEP_MS_ENV_VAR_NAME = 'LAST_CONTACT_BACKFILL_SLEEP_MS';
-export const DEFAULT_BACKFILL_BATCH_SIZE = 20;
+export const DEFAULT_BACKFILL_BATCH_SIZE = 200;
export const DEFAULT_BACKFILL_SLEEP_MS = 1_000;
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-calendar-event-started.test.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-calendar-event-started.test.ts
index 3bf0a88b4b9..30af0fa59e6 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
@@ -59,7 +59,18 @@ const setupQueryMock = ({
}
if (query.people) {
- return Promise.resolve({ people: singlePage([]) });
+ const requestedIds: string[] = query.people.__args.filter.id.in;
+ return Promise.resolve({
+ people: singlePage(
+ query.people.edges.node.companyId
+ ? requestedIds.map((id) => ({ id, companyId: null }))
+ : requestedIds.map((id) => ({ id })),
+ ),
+ });
+ }
+
+ if (query.companies) {
+ return Promise.resolve({ companies: singlePage([]) });
}
return Promise.resolve({ opportunities: singlePage([]) });
@@ -69,7 +80,7 @@ const setupQueryMock = ({
beforeEach(() => {
queryMock.mockReset();
mutationMock.mockReset();
- mutationMock.mockResolvedValue({ updatePeople: [{ id: 'updated' }] });
+ mutationMock.mockResolvedValue({});
});
describe('on-calendar-event-started definition', () => {
@@ -159,11 +170,12 @@ describe('on-calendar-event-started handler', () => {
participantsByEventCalls[1][0].calendarEventParticipants.__args.after,
).toBe('participants-cursor-1');
- const personUpdates = mutationMock.mock.calls.filter(
- ([mutation]) => mutation.updatePeople,
+ const personUpserts = mutationMock.mock.calls.filter(
+ ([mutation]) => mutation.createPeople,
);
- expect(personUpdates).toHaveLength(2);
- expect(personUpdates[0][0].updatePeople.__args.data).toMatchObject({
+ expect(personUpserts).toHaveLength(1);
+ expect(personUpserts[0][0].createPeople.__args.data).toHaveLength(2);
+ expect(personUpserts[0][0].createPeople.__args.data[0]).toMatchObject({
lastContactAt: PAST_EVENT_STARTS_AT,
lastContactItemCalendarEventId: 'event-1',
});
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-calendar-interaction.test.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-calendar-interaction.test.ts
index d658a9890bf..de6cedc2bab 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
@@ -55,7 +55,18 @@ const setupQueryMock = (participants: Record<string, unknown>[]) => {
}
if (query.people) {
- return Promise.resolve({ people: buildPage([]) });
+ const requestedIds: string[] = query.people.__args.filter.id.in;
+ return Promise.resolve({
+ people: buildPage(
+ query.people.edges.node.companyId
+ ? requestedIds.map((id) => ({ id, companyId: null }))
+ : requestedIds.map((id) => ({ id })),
+ ),
+ });
+ }
+
+ if (query.companies) {
+ return Promise.resolve({ companies: buildPage([]) });
}
return Promise.resolve({ opportunities: buildPage([]) });
@@ -67,7 +78,7 @@ beforeEach(() => {
vi.setSystemTime(new Date(NOW));
queryMock.mockReset();
mutationMock.mockReset();
- mutationMock.mockResolvedValue({ updatePeople: [{ id: 'updated' }] });
+ mutationMock.mockResolvedValue({});
});
afterEach(() => {
@@ -108,15 +119,18 @@ describe('on-calendar-interaction handler', () => {
expect(
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: CALENDAR_EVENT_ID,
- lastContactItemMessageId: null,
- lastOutboundAt: PAST_EVENT_STARTS_AT,
- lastInboundAt: PAST_EVENT_STARTS_AT,
- lastMeetingId: CALENDAR_EVENT_ID,
- });
+ expect(mutationMock.mock.calls[0][0].createPeople.__args.data).toEqual([
+ {
+ id: PERSON_ID,
+ lastContactAt: PAST_EVENT_STARTS_AT,
+ lastContactById: null,
+ lastContactItemCalendarEventId: CALENDAR_EVENT_ID,
+ lastContactItemMessageId: null,
+ lastOutboundAt: PAST_EVENT_STARTS_AT,
+ lastInboundAt: PAST_EVENT_STARTS_AT,
+ lastMeetingId: CALENDAR_EVENT_ID,
+ },
+ ]);
});
it('should do nothing when no participant has both a person and a calendar event', async () => {
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.ts
index 78684ce4599..41ee57e859c 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
@@ -49,12 +49,19 @@ const setupQueryMock = (messageParticipants: Record<string, unknown>[]) => {
});
}
- if (query.person) {
- return Promise.resolve({ person: null });
+ if (query.people) {
+ const requestedIds: string[] = query.people.__args.filter.id.in;
+ return Promise.resolve({
+ people: buildPage(
+ query.people.edges.node.companyId
+ ? requestedIds.map((id) => ({ id, companyId: null }))
+ : requestedIds.map((id) => ({ id })),
+ ),
+ });
}
- if (query.people) {
- return Promise.resolve({ people: buildPage([]) });
+ if (query.companies) {
+ return Promise.resolve({ companies: buildPage([]) });
}
return Promise.resolve({ opportunities: buildPage([]) });
@@ -64,7 +71,7 @@ const setupQueryMock = (messageParticipants: Record<string, unknown>[]) => {
beforeEach(() => {
queryMock.mockReset();
mutationMock.mockReset();
- mutationMock.mockResolvedValue({ updatePeople: [{ id: 'updated' }] });
+ mutationMock.mockResolvedValue({});
});
describe('on-email-interaction definition', () => {
@@ -99,13 +106,19 @@ describe('on-email-interaction 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,
- lastContactItemCalendarEventId: null,
- lastOutboundAt: RECEIVED_AT,
- lastEmailId: MESSAGE_ID,
+ expect(mutationMock.mock.calls[0][0].createPeople.__args).toEqual({
+ upsert: true,
+ data: [
+ {
+ id: PERSON_ID,
+ lastContactAt: RECEIVED_AT,
+ lastContactById: MEMBER_ID,
+ lastContactItemMessageId: MESSAGE_ID,
+ lastContactItemCalendarEventId: null,
+ lastOutboundAt: RECEIVED_AT,
+ lastEmailId: MESSAGE_ID,
+ },
+ ],
});
});
@@ -140,19 +153,22 @@ describe('on-email-interaction handler', () => {
participantQueries[0][0].messageParticipants.__args.filter,
).toEqual({ messageId: { in: [OLDER_MESSAGE_ID, MESSAGE_ID] } });
- const personUpdates = mutationMock.mock.calls.filter(
- ([mutation]) => mutation.updatePeople,
+ const personUpserts = mutationMock.mock.calls.filter(
+ ([mutation]) => mutation.createPeople,
);
- 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,
- });
+ expect(personUpserts).toHaveLength(1);
+ expect(personUpserts[0][0].createPeople.__args.data).toEqual([
+ {
+ id: PERSON_ID,
+ 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 no participant has both a person and a message', async () => {
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-opportunity-created.test.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/on-opportunity-created.test.ts
index f8727ac61cd..56828458f3b 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
@@ -71,10 +71,15 @@ describe('on-opportunity-created', () => {
],
});
- expect(mutationMock.mock.calls[0][0].updateOpportunity.__args.data).toEqual({
- lastContactAt: OCCURRED_AT,
- lastContactItemMessageId: MESSAGE_ID,
- lastContactItemCalendarEventId: null,
- });
+ expect(
+ mutationMock.mock.calls[0][0].createOpportunities.__args.data,
+ ).toEqual([
+ {
+ id: OPPORTUNITY_ID,
+ lastContactAt: OCCURRED_AT,
+ lastContactItemMessageId: MESSAGE_ID,
+ lastContactItemCalendarEventId: null,
+ },
+ ]);
});
});
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.ts
index 9100be24a4d..c805dea61f9 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
@@ -35,13 +35,33 @@ const buildBatch = (
beforeEach(() => {
queryMock.mockReset();
- queryMock.mockResolvedValue({ people: { edges: [] } });
+ queryMock.mockImplementation((query) =>
+ query.companies
+ ? Promise.resolve({
+ companies: {
+ edges: query.companies.__args.filter.id.in.map((id: string) => ({
+ node: { id },
+ })),
+ pageInfo: { hasNextPage: false, endCursor: null },
+ },
+ })
+ : Promise.resolve({
+ people: {
+ edges: [],
+ pageInfo: { hasNextPage: false, endCursor: null },
+ },
+ }),
+ );
mutationMock.mockReset();
mutationMock.mockResolvedValue({});
});
const updatedCompanyIds = () =>
- mutationMock.mock.calls.map(([mutation]) => mutation.updateCompany.__args.id);
+ mutationMock.mock.calls.flatMap(([mutation]) =>
+ mutation.createCompanies.__args.data.map(
+ (record: { id: string }) => record.id,
+ ),
+ );
describe('on-person-updated definition', () => {
it('should batch companyId updates', () => {
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-companies-last-contact.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-companies-last-contact.ts
index 38dbf32735a..531f9b24201 100644
--- a/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-companies-last-contact.ts
+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-companies-last-contact.ts
@@ -13,6 +13,10 @@ import {
pickLatestLastContact,
pickPersonLastContact,
} from 'src/utils/person-last-contact-aggregation';
+import {
+ type RecordUpsert,
+ upsertRecordsInBatches,
+} from 'src/utils/upsert-records-in-batches';
const handler = async ({ batchId }: BackfillBatchPayload): Promise<object> => {
const client = new CoreApiClient();
@@ -38,6 +42,8 @@ const handler = async ({ batchId }: BackfillBatchPayload): Promise<object> => {
const personIds = [...new Set([...peopleByCompanyId.values()].flat())];
const aggByPersonId = await buildPersonAggregates(client, personIds);
+ const upserts: RecordUpsert[] = [];
+
for (const companyId of companyIds) {
const lastContact = pickLatestLastContact(
(peopleByCompanyId.get(companyId) ?? [])
@@ -49,16 +55,11 @@ const handler = async ({ batchId }: BackfillBatchPayload): Promise<object> => {
continue;
}
- await executeWithRetry(() =>
- client.mutation({
- updateCompany: {
- __args: { id: companyId, data: buildRelatedUpdateData(lastContact) },
- id: true,
- },
- }),
- );
+ upserts.push({ id: companyId, ...buildRelatedUpdateData(lastContact) });
}
+ await upsertRecordsInBatches(client, 'createCompanies', upserts);
+
return { batchId, count: companyIds.length };
};
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-opportunities-last-contact.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-opportunities-last-contact.ts
index 27206ffd42d..77e0adf48fe 100644
--- a/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-opportunities-last-contact.ts
+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-opportunities-last-contact.ts
@@ -11,6 +11,10 @@ import {
buildPersonAggregates,
pickPersonLastContact,
} from 'src/utils/person-last-contact-aggregation';
+import {
+ type RecordUpsert,
+ upsertRecordsInBatches,
+} from 'src/utils/upsert-records-in-batches';
type OpportunityNode = { id: string; pointOfContactId: string | null };
@@ -43,6 +47,8 @@ const handler = async ({ batchId }: BackfillBatchPayload): Promise<object> => {
];
const aggByPersonId = await buildPersonAggregates(client, personIds);
+ const upserts: RecordUpsert[] = [];
+
for (const node of nodes) {
const lastContact = node.pointOfContactId
? pickPersonLastContact(aggByPersonId.get(node.pointOfContactId))
@@ -52,16 +58,11 @@ const handler = async ({ batchId }: BackfillBatchPayload): Promise<object> => {
continue;
}
- await executeWithRetry(() =>
- client.mutation({
- updateOpportunity: {
- __args: { id: node.id, data: buildRelatedUpdateData(lastContact) },
- id: true,
- },
- }),
- );
+ upserts.push({ id: node.id, ...buildRelatedUpdateData(lastContact) });
}
+ await upsertRecordsInBatches(client, 'createOpportunities', upserts);
+
return { batchId, count: nodes.length };
};
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-people-last-contact.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-people-last-contact.ts
index ba501901ed2..ba773a0496b 100644
--- a/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-people-last-contact.ts
+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-people-last-contact.ts
@@ -10,6 +10,10 @@ import {
buildPersonAggregates,
buildPersonUpdateData,
} from 'src/utils/person-last-contact-aggregation';
+import {
+ type RecordUpsert,
+ upsertRecordsInBatches,
+} from 'src/utils/upsert-records-in-batches';
const handler = async ({ batchId }: BackfillBatchPayload): Promise<object> => {
const client = new CoreApiClient();
@@ -32,6 +36,7 @@ const handler = async ({ batchId }: BackfillBatchPayload): Promise<object> => {
}
const aggByPersonId = await buildPersonAggregates(client, personIds);
+ const upserts: RecordUpsert[] = [];
for (const personId of personIds) {
const agg = aggByPersonId.get(personId);
@@ -41,13 +46,11 @@ const handler = async ({ batchId }: BackfillBatchPayload): Promise<object> => {
continue;
}
- await executeWithRetry(() =>
- client.mutation({
- updatePerson: { __args: { id: personId, data }, id: true },
- }),
- );
+ upserts.push({ id: personId, ...data });
}
+ await upsertRecordsInBatches(client, 'createPeople', upserts);
+
return { batchId, count: personIds.length };
};
diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/on-calendar-event-started.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/on-calendar-event-started.ts
index 0cf9098e031..e8e4d0d7552 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
@@ -9,6 +9,7 @@ import {
applyMeetingInteractions,
type CalendarEventParticipantLink,
} from 'src/utils/apply-meeting-interactions';
+import { executeWithRetry } from 'src/utils/execute-with-retry';
const QUERY_MAX_RECORDS = 200;
@@ -28,33 +29,37 @@ const handler = async (): Promise<void> => {
let calendarEventsHasNextPage = true;
while (calendarEventsHasNextPage) {
- const { calendarEvents } = await client.query({
- calendarEvents: {
- __args: {
- filter: {
- and: [
- { startsAt: { gt: windowStart.toISOString() } },
- { startsAt: { lte: now.toISOString() } },
- { isCanceled: { eq: false } },
- ],
+ const { calendarEvents } = await executeWithRetry(() =>
+ client.query({
+ calendarEvents: {
+ __args: {
+ filter: {
+ and: [
+ { startsAt: { gt: windowStart.toISOString() } },
+ { startsAt: { lte: now.toISOString() } },
+ { isCanceled: { eq: false } },
+ ],
+ },
+ first: QUERY_MAX_RECORDS,
+ after: calendarEventsCursor,
},
- first: QUERY_MAX_RECORDS,
- after: calendarEventsCursor,
- },
- edges: {
- node: {
- id: true,
+ edges: {
+ node: {
+ id: true,
+ },
+ },
+ pageInfo: {
+ hasNextPage: true,
+ endCursor: true,
},
},
- pageInfo: {
- hasNextPage: true,
- endCursor: true,
- },
- },
- });
+ }),
+ );
calendarEventIds.push(
- ...(calendarEvents?.edges.map((edge: { node: { id: string } }) => edge.node.id) ?? []),
+ ...(calendarEvents?.edges.map(
+ (edge: { node: { id: string } }) => edge.node.id,
+ ) ?? []),
);
calendarEventsHasNextPage = calendarEvents?.pageInfo.hasNextPage ?? false;
calendarEventsCursor = calendarEvents?.pageInfo.endCursor ?? undefined;
@@ -69,25 +74,27 @@ const handler = async (): Promise<void> => {
let participantsHasNextPage = true;
while (participantsHasNextPage) {
- const { calendarEventParticipants } = await client.query({
- calendarEventParticipants: {
- __args: {
- filter: { calendarEventId: { in: calendarEventIds } },
- first: QUERY_MAX_RECORDS,
- after: participantsCursor,
- },
- edges: {
- node: {
- personId: true,
- calendarEventId: true,
+ const { calendarEventParticipants } = await executeWithRetry(() =>
+ client.query({
+ calendarEventParticipants: {
+ __args: {
+ filter: { calendarEventId: { in: calendarEventIds } },
+ first: QUERY_MAX_RECORDS,
+ after: participantsCursor,
+ },
+ edges: {
+ node: {
+ personId: true,
+ calendarEventId: true,
+ },
+ },
+ pageInfo: {
+ hasNextPage: true,
+ endCursor: true,
},
},
- pageInfo: {
- hasNextPage: true,
- endCursor: true,
- },
- },
- });
+ }),
+ );
for (const edge of calendarEventParticipants?.edges ?? []) {
const { personId, calendarEventId } = edge.node;
diff --git a/packages/twenty-apps/public/last-contact/src/utils/__tests__/apply-meeting-interactions.test.ts b/packages/twenty-apps/public/last-contact/src/utils/__tests__/apply-meeting-interactions.test.ts
index 66d84231cc5..6fdfd33eb28 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/__tests__/apply-meeting-interactions.test.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/__tests__/apply-meeting-interactions.test.ts
@@ -31,19 +31,24 @@ const buildClient = (participants: Record<string, unknown>[] = []) => {
});
}
- if (query.person) {
- return Promise.resolve({ person: null });
+ if (query.people) {
+ const requestedIds: string[] = query.people.__args.filter.id.in;
+ return Promise.resolve({
+ people: buildPage(
+ query.people.edges.node.companyId
+ ? requestedIds.map((id) => ({ id, companyId: null }))
+ : requestedIds.map((id) => ({ id })),
+ ),
+ });
}
- if (query.people) {
- return Promise.resolve({ people: buildPage([]) });
+ if (query.companies) {
+ return Promise.resolve({ companies: buildPage([]) });
}
return Promise.resolve({ opportunities: buildPage([]) });
});
- const mutationMock = vi
- .fn()
- .mockResolvedValue({ updatePeople: [{ id: 'updated' }] });
+ const mutationMock = vi.fn().mockResolvedValue({});
return {
client: {
@@ -74,6 +79,9 @@ const buildParticipant = ({
calendarEvent: { startsAt, isCanceled },
});
+const findPersonUpserts = (mutationMock: ReturnType<typeof vi.fn>) =>
+ mutationMock.mock.calls.filter(([mutation]) => mutation.createPeople);
+
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date(NOW));
@@ -119,17 +127,50 @@ describe('applyMeetingInteractions', () => {
{ 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,
+ expect(findPersonUpserts(mutationMock)[0][0].createPeople.__args).toEqual({
+ upsert: true,
+ data: [
+ {
+ id: PERSON_ID,
+ 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('writes every person of the batch in a single upsert', async () => {
+ const { client, mutationMock } = buildClient([
+ buildParticipant({
+ calendarEventId: CALENDAR_EVENT_ID,
+ startsAt: PAST_EVENT_STARTS_AT,
+ }),
+ buildParticipant({
+ calendarEventId: OLDER_CALENDAR_EVENT_ID,
+ startsAt: OLDER_EVENT_STARTS_AT,
+ }),
+ ]);
+
+ await applyMeetingInteractions(client, [
+ { personId: PERSON_ID, calendarEventId: CALENDAR_EVENT_ID },
+ { personId: OTHER_PERSON_ID, calendarEventId: OLDER_CALENDAR_EVENT_ID },
+ ]);
+
+ const personUpserts = findPersonUpserts(mutationMock);
+
+ expect(personUpserts).toHaveLength(1);
+ expect(
+ personUpserts[0][0].createPeople.__args.data.map(
+ (record: { id: string }) => record.id,
+ ),
+ ).toEqual([PERSON_ID, OTHER_PERSON_ID]);
+ });
+
it('keeps only the most recent meeting when a person attended several in the batch', async () => {
const { client, mutationMock } = buildClient([
buildParticipant({
@@ -147,11 +188,12 @@ describe('applyMeetingInteractions', () => {
{ 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({
+ const personUpserts = findPersonUpserts(mutationMock);
+
+ expect(personUpserts).toHaveLength(1);
+ expect(personUpserts[0][0].createPeople.__args.data).toHaveLength(1);
+ expect(personUpserts[0][0].createPeople.__args.data[0]).toMatchObject({
+ id: PERSON_ID,
lastContactAt: PAST_EVENT_STARTS_AT,
lastContactItemCalendarEventId: CALENDAR_EVENT_ID,
lastMeetingId: CALENDAR_EVENT_ID,
@@ -188,4 +230,34 @@ describe('applyMeetingInteractions', () => {
expect(mutationMock).not.toHaveBeenCalled();
});
+
+ it('leaves out a person that no longer exists rather than upserting it back', async () => {
+ const { client, mutationMock, queryMock } = buildClient([
+ buildParticipant({
+ calendarEventId: CALENDAR_EVENT_ID,
+ startsAt: PAST_EVENT_STARTS_AT,
+ }),
+ ]);
+
+ queryMock.mockImplementation((query) => {
+ if (query.calendarEventParticipants) {
+ return Promise.resolve({
+ calendarEventParticipants: buildPage([
+ buildParticipant({
+ calendarEventId: CALENDAR_EVENT_ID,
+ startsAt: PAST_EVENT_STARTS_AT,
+ }),
+ ]),
+ });
+ }
+
+ return Promise.resolve({ people: buildPage([]) });
+ });
+
+ 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-company-last-contact.test.ts b/packages/twenty-apps/public/last-contact/src/utils/__tests__/recompute-company-last-contact.test.ts
index 8acbc89d7ff..e20f7ed34ba 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/__tests__/recompute-company-last-contact.test.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/__tests__/recompute-company-last-contact.test.ts
@@ -1,65 +1,273 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { recomputeCompanyLastContact } from 'src/utils/recompute-company-last-contact';
+import { recomputeCompaniesLastContact } from 'src/utils/recompute-company-last-contact';
const COMPANY_ID = '11111111-1111-1111-1111-111111111111';
+const OTHER_COMPANY_ID = '22222222-2222-2222-2222-222222222222';
const CALENDAR_EVENT_ID = '44444444-4444-4444-4444-444444444444';
+const MESSAGE_ID = '55555555-5555-5555-5555-555555555555';
const OCCURRED_AT = '2026-06-10T09:00:00.000Z';
+const OLDER_OCCURRED_AT = '2026-06-01T09:00:00.000Z';
+
+const EMPTY_LAST_CONTACT = {
+ lastContactAt: null,
+ lastContactItemMessageId: null,
+ lastContactItemCalendarEventId: null,
+};
type Client = {
query: ReturnType<typeof vi.fn>;
mutation: ReturnType<typeof vi.fn>;
};
-let client: Client;
+const buildPage = (
+ nodes: Record<string, unknown>[],
+ hasNextPage = false,
+ endCursor: string | null = null,
+) => ({
+ edges: nodes.map((node) => ({ node })),
+ pageInfo: { hasNextPage, endCursor },
+});
-beforeEach(() => {
- client = {
- query: vi.fn(),
+const buildClient = ({
+ peoplePages = [buildPage([])],
+ existingCompanyIds = [COMPANY_ID, OTHER_COMPANY_ID],
+}: {
+ peoplePages?: ReturnType<typeof buildPage>[];
+ existingCompanyIds?: string[];
+}): Client => {
+ let peopleCallIndex = 0;
+
+ return {
+ query: vi.fn().mockImplementation((query) => {
+ if (query.companies) {
+ return Promise.resolve({
+ companies: buildPage(existingCompanyIds.map((id) => ({ id }))),
+ });
+ }
+
+ const page = peoplePages[peopleCallIndex] ?? buildPage([]);
+
+ peopleCallIndex += 1;
+
+ return Promise.resolve({ people: page });
+ }),
mutation: vi.fn().mockResolvedValue({}),
};
+};
+
+let client: Client;
+
+beforeEach(() => {
+ client = buildClient({});
});
-describe('recomputeCompanyLastContact', () => {
+const upsertData = () =>
+ client.mutation.mock.calls[0]?.[0].createCompanies.__args.data;
+
+const peopleQueries = () =>
+ client.query.mock.calls.filter(([query]) => query.people);
+
+describe('recomputeCompaniesLastContact', () => {
it('mirrors the most recent contact among the company people', async () => {
- client.query.mockResolvedValueOnce({
- people: {
- edges: [
+ client = buildClient({
+ peoplePages: [
+ buildPage([
{
- node: {
- lastContactAt: OCCURRED_AT,
- lastContactItemMessage: null,
- lastContactItemCalendarEvent: { id: CALENDAR_EVENT_ID },
- },
+ companyId: COMPANY_ID,
+ lastContactAt: OCCURRED_AT,
+ lastContactItemMessage: null,
+ lastContactItemCalendarEvent: { id: CALENDAR_EVENT_ID },
},
- ],
+ ]),
+ ],
+ existingCompanyIds: [COMPANY_ID],
+ });
+
+ await recomputeCompaniesLastContact(client as never, [COMPANY_ID]);
+
+ expect(upsertData()).toEqual([
+ {
+ id: COMPANY_ID,
+ lastContactAt: OCCURRED_AT,
+ lastContactItemMessageId: null,
+ lastContactItemCalendarEventId: CALENDAR_EVENT_ID,
},
+ ]);
+ });
+
+ it('keeps the first row a company produces, since the scan is ordered by recency', async () => {
+ client = buildClient({
+ peoplePages: [
+ buildPage([
+ {
+ companyId: COMPANY_ID,
+ lastContactAt: OCCURRED_AT,
+ lastContactItemMessage: { id: MESSAGE_ID },
+ lastContactItemCalendarEvent: null,
+ },
+ {
+ companyId: COMPANY_ID,
+ lastContactAt: OLDER_OCCURRED_AT,
+ lastContactItemMessage: null,
+ lastContactItemCalendarEvent: { id: CALENDAR_EVENT_ID },
+ },
+ ]),
+ ],
+ existingCompanyIds: [COMPANY_ID],
});
- await recomputeCompanyLastContact(client as never, COMPANY_ID);
+ await recomputeCompaniesLastContact(client as never, [COMPANY_ID]);
+
+ expect(upsertData()).toEqual([
+ {
+ id: COMPANY_ID,
+ lastContactAt: OCCURRED_AT,
+ lastContactItemMessageId: MESSAGE_ID,
+ lastContactItemCalendarEventId: null,
+ },
+ ]);
+ });
+
+ it('clears the company last contact when no person has a contact', async () => {
+ client = buildClient({ existingCompanyIds: [COMPANY_ID] });
+
+ await recomputeCompaniesLastContact(client as never, [COMPANY_ID]);
+
+ expect(upsertData()).toEqual([{ id: COMPANY_ID, ...EMPTY_LAST_CONTACT }]);
+ });
- const args = client.mutation.mock.calls[0][0].updateCompany.__args;
- expect(args.id).toBe(COMPANY_ID);
- expect(args.data).toEqual({
- lastContactAt: OCCURRED_AT,
- lastContactItemMessageId: null,
- lastContactItemCalendarEventId: CALENDAR_EVENT_ID,
+ it('resolves the whole batch with one scan and one write', async () => {
+ client = buildClient({
+ peoplePages: [
+ buildPage([
+ {
+ companyId: COMPANY_ID,
+ lastContactAt: OCCURRED_AT,
+ lastContactItemMessage: { id: MESSAGE_ID },
+ lastContactItemCalendarEvent: null,
+ },
+ ]),
+ ],
});
- expect(client.query.mock.calls[0][0].people.__args.filter).toEqual({
- companyId: { eq: COMPANY_ID },
+
+ await recomputeCompaniesLastContact(client as never, [
+ COMPANY_ID,
+ OTHER_COMPANY_ID,
+ ]);
+
+ expect(peopleQueries()).toHaveLength(1);
+ expect(peopleQueries()[0][0].people.__args.filter).toEqual({
+ companyId: { in: [COMPANY_ID, OTHER_COMPANY_ID] },
lastContactAt: { is: 'NOT_NULL' },
});
+ expect(client.mutation).toHaveBeenCalledTimes(1);
+ expect(upsertData()).toEqual([
+ {
+ id: COMPANY_ID,
+ lastContactAt: OCCURRED_AT,
+ lastContactItemMessageId: MESSAGE_ID,
+ lastContactItemCalendarEventId: null,
+ },
+ { id: OTHER_COMPANY_ID, ...EMPTY_LAST_CONTACT },
+ ]);
});
- it('clears the company last contact when no person has a contact', async () => {
- client.query.mockResolvedValueOnce({ people: { edges: [] } });
+ it('stops scanning as soon as every company is resolved', async () => {
+ client = buildClient({
+ peoplePages: [
+ buildPage(
+ [
+ {
+ companyId: COMPANY_ID,
+ lastContactAt: OCCURRED_AT,
+ lastContactItemMessage: { id: MESSAGE_ID },
+ lastContactItemCalendarEvent: null,
+ },
+ {
+ companyId: OTHER_COMPANY_ID,
+ lastContactAt: OLDER_OCCURRED_AT,
+ lastContactItemMessage: { id: MESSAGE_ID },
+ lastContactItemCalendarEvent: null,
+ },
+ ],
+ true,
+ 'cursor-1',
+ ),
+ ],
+ });
- await recomputeCompanyLastContact(client as never, COMPANY_ID);
+ await recomputeCompaniesLastContact(client as never, [
+ COMPANY_ID,
+ OTHER_COMPANY_ID,
+ ]);
- expect(client.mutation.mock.calls[0][0].updateCompany.__args.data).toEqual({
- lastContactAt: null,
- lastContactItemMessageId: null,
- lastContactItemCalendarEventId: null,
+ expect(peopleQueries()).toHaveLength(1);
+ });
+
+ it('falls back to a direct lookup for a company the capped scan never reached', async () => {
+ const busyCompanyPage = buildPage(
+ [
+ {
+ companyId: COMPANY_ID,
+ lastContactAt: OCCURRED_AT,
+ lastContactItemMessage: { id: MESSAGE_ID },
+ lastContactItemCalendarEvent: null,
+ },
+ ],
+ true,
+ 'cursor',
+ );
+
+ client = buildClient({
+ peoplePages: [
+ busyCompanyPage,
+ busyCompanyPage,
+ busyCompanyPage,
+ busyCompanyPage,
+ busyCompanyPage,
+ buildPage([
+ {
+ companyId: OTHER_COMPANY_ID,
+ lastContactAt: OLDER_OCCURRED_AT,
+ lastContactItemMessage: null,
+ lastContactItemCalendarEvent: { id: CALENDAR_EVENT_ID },
+ },
+ ]),
+ ],
});
+
+ await recomputeCompaniesLastContact(client as never, [
+ COMPANY_ID,
+ OTHER_COMPANY_ID,
+ ]);
+
+ expect(peopleQueries()).toHaveLength(6);
+ expect(peopleQueries()[5][0].people.__args.filter).toEqual({
+ companyId: { eq: OTHER_COMPANY_ID },
+ lastContactAt: { is: 'NOT_NULL' },
+ });
+ expect(upsertData()).toEqual([
+ {
+ id: COMPANY_ID,
+ lastContactAt: OCCURRED_AT,
+ lastContactItemMessageId: MESSAGE_ID,
+ lastContactItemCalendarEventId: null,
+ },
+ {
+ id: OTHER_COMPANY_ID,
+ lastContactAt: OLDER_OCCURRED_AT,
+ lastContactItemMessageId: null,
+ lastContactItemCalendarEventId: CALENDAR_EVENT_ID,
+ },
+ ]);
+ });
+
+ it('leaves out a company that no longer exists rather than upserting it back', async () => {
+ client = buildClient({ existingCompanyIds: [] });
+
+ await recomputeCompaniesLastContact(client as never, [COMPANY_ID]);
+
+ expect(client.mutation).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.ts
index b6083ec890d..7bf34ae0d3f 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
@@ -55,13 +55,18 @@ describe('recomputeOpportunitiesLastContact', () => {
await recomputeOpportunitiesLastContact(client as never, [OPPORTUNITY_ID]);
- expect(client.mutation.mock.calls[0][0].updateOpportunity.__args).toEqual({
- id: OPPORTUNITY_ID,
- data: {
- lastContactAt: OCCURRED_AT,
- lastContactItemMessageId: MESSAGE_ID,
- lastContactItemCalendarEventId: null,
- },
+ expect(
+ client.mutation.mock.calls[0][0].createOpportunities.__args,
+ ).toEqual({
+ upsert: true,
+ data: [
+ {
+ id: OPPORTUNITY_ID,
+ lastContactAt: OCCURRED_AT,
+ lastContactItemMessageId: MESSAGE_ID,
+ lastContactItemCalendarEventId: null,
+ },
+ ],
});
});
@@ -74,15 +79,18 @@ describe('recomputeOpportunitiesLastContact', () => {
expect(client.query).toHaveBeenCalledTimes(1);
expect(
- client.mutation.mock.calls[0][0].updateOpportunity.__args.data,
- ).toEqual({
- lastContactAt: null,
- lastContactItemMessageId: null,
- lastContactItemCalendarEventId: null,
- });
+ client.mutation.mock.calls[0][0].createOpportunities.__args.data,
+ ).toEqual([
+ {
+ id: OPPORTUNITY_ID,
+ lastContactAt: null,
+ lastContactItemMessageId: null,
+ lastContactItemCalendarEventId: null,
+ },
+ ]);
});
- it('resolves a whole batch with one opportunity query and one people query', async () => {
+ it('resolves a whole batch with one opportunity query, one people query and one write', async () => {
client = buildClient({
opportunities: [
{ id: OPPORTUNITY_ID, pointOfContactId: PERSON_ID },
@@ -104,9 +112,10 @@ describe('recomputeOpportunitiesLastContact', () => {
]);
expect(client.query).toHaveBeenCalledTimes(2);
+ expect(client.mutation).toHaveBeenCalledTimes(1);
expect(
- client.mutation.mock.calls.map(
- ([mutation]) => mutation.updateOpportunity.__args.id,
+ client.mutation.mock.calls[0][0].createOpportunities.__args.data.map(
+ (record: { id: string }) => record.id,
),
).toEqual([OPPORTUNITY_ID, OTHER_OPPORTUNITY_ID]);
});
diff --git a/packages/twenty-apps/public/last-contact/src/utils/__tests__/update-related-last-contact.test.ts b/packages/twenty-apps/public/last-contact/src/utils/__tests__/update-related-last-contact.test.ts
index cb05a671142..60a06f5db49 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
@@ -8,8 +8,10 @@ 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 OPPORTUNITY_ID = '77777777-7777-7777-7777-777777777777';
const OCCURRED_AT = '2026-06-10T09:00:00.000Z';
const OLDER_OCCURRED_AT = '2026-06-01T09:00:00.000Z';
+const NEWER_OCCURRED_AT = '2026-06-20T09:00:00.000Z';
type Client = {
query: ReturnType<typeof vi.fn>;
@@ -23,16 +25,24 @@ const buildPage = (nodes: Record<string, unknown>[]) => ({
const buildClient = ({
people = [],
+ companies = [{ id: COMPANY_ID, lastContactAt: null }],
opportunities = [],
}: {
people?: Record<string, unknown>[];
+ companies?: 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) }),
- ),
+ query: vi.fn().mockImplementation((query) => {
+ if (query.people) {
+ return Promise.resolve({ people: buildPage(people) });
+ }
+
+ if (query.companies) {
+ return Promise.resolve({ companies: buildPage(companies) });
+ }
+
+ return Promise.resolve({ opportunities: buildPage(opportunities) });
+ }),
mutation: vi.fn().mockResolvedValue({}),
});
@@ -41,40 +51,39 @@ let client: Client;
beforeEach(() => {
client = buildClient({
people: [{ id: PERSON_ID, companyId: COMPANY_ID }],
- opportunities: [{ id: 'opportunity-1', pointOfContactId: PERSON_ID }],
+ opportunities: [
+ {
+ id: OPPORTUNITY_ID,
+ pointOfContactId: PERSON_ID,
+ lastContactAt: null,
+ },
+ ],
});
});
-const findMutation = (name: string) =>
- client.mutation.mock.calls.find((call) => call[0][name])?.[0][name];
+const findUpsertData = (name: string) =>
+ client.mutation.mock.calls.find((call) => call[0][name])?.[0][name].__args
+ .data;
+
+const emailContact = (occurredAt = OCCURRED_AT, itemId = MESSAGE_ID) =>
+ new Map([[PERSON_ID, { occurredAt, itemId, kind: 'email' as const }]]);
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 },
- ],
- ]),
- );
+ await updateRelatedLastContactForPeople(client as never, emailContact());
const expectedData = {
lastContactAt: OCCURRED_AT,
lastContactItemMessageId: MESSAGE_ID,
lastContactItemCalendarEventId: null,
};
- expect(findMutation('updateCompanies').__args.data).toEqual(expectedData);
- expect(findMutation('updateCompanies').__args.filter.and[0]).toEqual({
- id: { eq: COMPANY_ID },
- });
- expect(findMutation('updateOpportunities').__args.data).toEqual(
- expectedData,
- );
- expect(findMutation('updateOpportunities').__args.filter.and[0]).toEqual({
- pointOfContactId: { eq: PERSON_ID },
- });
+
+ expect(findUpsertData('createCompanies')).toEqual([
+ { id: COMPANY_ID, ...expectedData },
+ ]);
+ expect(findUpsertData('createOpportunities')).toEqual([
+ { id: OPPORTUNITY_ID, ...expectedData },
+ ]);
});
it('sets the calendar event item for a meeting', async () => {
@@ -92,58 +101,69 @@ describe('updateRelatedLastContactForPeople', () => {
]),
);
- expect(findMutation('updateCompanies').__args.data).toEqual({
- lastContactAt: OCCURRED_AT,
- lastContactItemMessageId: null,
- lastContactItemCalendarEventId: CALENDAR_EVENT_ID,
- });
+ expect(findUpsertData('createCompanies')).toEqual([
+ {
+ id: COMPANY_ID,
+ lastContactAt: OCCURRED_AT,
+ lastContactItemMessageId: null,
+ lastContactItemCalendarEventId: CALENDAR_EVENT_ID,
+ },
+ ]);
});
- it('only guards against newer contacts', async () => {
- await updateRelatedLastContactForPeople(
- client as never,
- new Map([
- [
- PERSON_ID,
- { occurredAt: OCCURRED_AT, itemId: MESSAGE_ID, kind: 'email' as const },
- ],
- ]),
- );
-
- const expectedGuard = {
- or: [
- { lastContactAt: { is: 'NULL' } },
- { lastContactAt: { lt: OCCURRED_AT } },
+ it('leaves a company and an opportunity already contacted more recently alone', async () => {
+ client = buildClient({
+ people: [{ id: PERSON_ID, companyId: COMPANY_ID }],
+ companies: [{ id: COMPANY_ID, lastContactAt: NEWER_OCCURRED_AT }],
+ opportunities: [
+ {
+ id: OPPORTUNITY_ID,
+ pointOfContactId: PERSON_ID,
+ lastContactAt: NEWER_OCCURRED_AT,
+ },
],
- };
- expect(findMutation('updateCompanies').__args.filter.and[1]).toEqual(
- expectedGuard,
- );
- expect(findMutation('updateOpportunities').__args.filter.and[1]).toEqual(
- expectedGuard,
- );
+ });
+
+ await updateRelatedLastContactForPeople(client as never, emailContact());
+
+ expect(findUpsertData('createCompanies')).toBeUndefined();
+ expect(findUpsertData('createOpportunities')).toBeUndefined();
});
it('skips the company update when the person has no company but still updates opportunities', async () => {
client = buildClient({
people: [{ id: PERSON_ID, companyId: null }],
- opportunities: [{ id: 'opportunity-1', pointOfContactId: PERSON_ID }],
+ opportunities: [
+ {
+ id: OPPORTUNITY_ID,
+ pointOfContactId: PERSON_ID,
+ lastContactAt: null,
+ },
+ ],
});
- await updateRelatedLastContactForPeople(
- client as never,
- new Map([
- [
- PERSON_ID,
- { occurredAt: OCCURRED_AT, itemId: MESSAGE_ID, kind: 'email' as const },
- ],
- ]),
- );
+ await updateRelatedLastContactForPeople(client as never, emailContact());
+
+ expect(findUpsertData('createCompanies')).toBeUndefined();
+ expect(findUpsertData('createOpportunities')).toEqual([
+ {
+ id: OPPORTUNITY_ID,
+ lastContactAt: OCCURRED_AT,
+ lastContactItemMessageId: MESSAGE_ID,
+ lastContactItemCalendarEventId: null,
+ },
+ ]);
+ });
- expect(findMutation('updateCompanies')).toBeUndefined();
- expect(findMutation('updateOpportunities').__args.filter.and[0]).toEqual({
- pointOfContactId: { eq: PERSON_ID },
+ it('leaves out a company that no longer exists rather than upserting it back', async () => {
+ client = buildClient({
+ people: [{ id: PERSON_ID, companyId: COMPANY_ID }],
+ companies: [],
});
+
+ await updateRelatedLastContactForPeople(client as never, emailContact());
+
+ expect(findUpsertData('createCompanies')).toBeUndefined();
});
it('updates a shared company once, with the most recent contact of its people', async () => {
@@ -172,14 +192,13 @@ describe('updateRelatedLastContactForPeople', () => {
]),
);
- 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,
- });
+ expect(findUpsertData('createCompanies')).toEqual([
+ {
+ id: COMPANY_ID,
+ lastContactAt: OCCURRED_AT,
+ lastContactItemMessageId: MESSAGE_ID,
+ lastContactItemCalendarEventId: null,
+ },
+ ]);
});
});
diff --git a/packages/twenty-apps/public/last-contact/src/utils/__tests__/upsert-records-in-batches.test.ts b/packages/twenty-apps/public/last-contact/src/utils/__tests__/upsert-records-in-batches.test.ts
new file mode 100644
index 00000000000..7ece5edcbb7
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/utils/__tests__/upsert-records-in-batches.test.ts
@@ -0,0 +1,44 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { upsertRecordsInBatches } from 'src/utils/upsert-records-in-batches';
+
+const buildRecords = (count: number) =>
+ Array.from({ length: count }, (_unused, index) => ({
+ id: `person-${index}`,
+ lastContactAt: '2026-06-10T09:00:00.000Z',
+ }));
+
+let client: { query: ReturnType<typeof vi.fn>; mutation: ReturnType<typeof vi.fn> };
+
+beforeEach(() => {
+ client = { query: vi.fn(), mutation: vi.fn().mockResolvedValue({}) };
+});
+
+describe('upsertRecordsInBatches', () => {
+ it('writes a whole batch of distinct payloads in one call', async () => {
+ await upsertRecordsInBatches(client as never, 'createPeople', buildRecords(200));
+
+ expect(client.mutation).toHaveBeenCalledTimes(1);
+ expect(client.mutation.mock.calls[0][0].createPeople.__args.upsert).toBe(
+ true,
+ );
+ expect(
+ client.mutation.mock.calls[0][0].createPeople.__args.data,
+ ).toHaveLength(200);
+ });
+
+ it('splits at the maximum number of records the API accepts', async () => {
+ await upsertRecordsInBatches(client as never, 'createPeople', buildRecords(201));
+
+ expect(client.mutation).toHaveBeenCalledTimes(2);
+ expect(
+ client.mutation.mock.calls[1][0].createPeople.__args.data,
+ ).toHaveLength(1);
+ });
+
+ it('does not call the API when there is nothing to write', async () => {
+ await upsertRecordsInBatches(client as never, 'createCompanies', []);
+
+ expect(client.mutation).not.toHaveBeenCalled();
+ });
+});
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.ts
index 0e1c3dc93f7..9bd2f0b13fb 100644
--- 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.ts
@@ -1,15 +1,8 @@
import { type CoreApiClient } from 'twenty-client-sdk/core';
+import { applyPersonInteractions } from 'src/utils/apply-person-interactions';
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';
+import { type Interaction } from 'src/utils/update-person-last-contact';
export type MessageParticipantLink = {
personId: string;
@@ -55,21 +48,5 @@ export const applyEmailInteractions = async (
}
}
- 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);
+ await applyPersonInteractions(client, interactionsByPersonId);
};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/apply-meeting-interactions.ts b/packages/twenty-apps/public/last-contact/src/utils/apply-meeting-interactions.ts
index 1dfdd578746..8129799efe4 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/apply-meeting-interactions.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/apply-meeting-interactions.ts
@@ -1,15 +1,8 @@
import { type CoreApiClient } from 'twenty-client-sdk/core';
+import { applyPersonInteractions } from 'src/utils/apply-person-interactions';
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';
+import { type Interaction } from 'src/utils/update-person-last-contact';
export type CalendarEventParticipantLink = {
personId: string;
@@ -56,21 +49,5 @@ export const applyMeetingInteractions = async (
}
}
- 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);
+ await applyPersonInteractions(client, interactionsByPersonId);
};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/apply-person-interactions.ts b/packages/twenty-apps/public/last-contact/src/utils/apply-person-interactions.ts
new file mode 100644
index 00000000000..ec94967ceda
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/utils/apply-person-interactions.ts
@@ -0,0 +1,65 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import {
+ buildPersonLastContactUpdate,
+ collectPersonLastContactState,
+ type Interaction,
+ pickLatestInteraction,
+} from 'src/utils/update-person-last-contact';
+import {
+ type RelatedInteraction,
+ updateRelatedLastContactForPeople,
+} from 'src/utils/update-related-last-contact';
+import {
+ type RecordUpsert,
+ upsertRecordsInBatches,
+} from 'src/utils/upsert-records-in-batches';
+
+export const applyPersonInteractions = async (
+ client: CoreApiClient,
+ interactionsByPersonId: Map<string, Interaction[]>,
+): Promise<void> => {
+ const personIds = [...interactionsByPersonId.keys()];
+
+ if (personIds.length === 0) {
+ return;
+ }
+
+ const stateByPersonId = await collectPersonLastContactState(
+ client,
+ personIds,
+ );
+ const updates: RecordUpsert[] = [];
+ const contactByPersonId = new Map<string, RelatedInteraction>();
+
+ for (const [personId, interactions] of interactionsByPersonId) {
+ const current = stateByPersonId.get(personId);
+
+ if (!current) {
+ continue;
+ }
+
+ const update = buildPersonLastContactUpdate(
+ personId,
+ current,
+ interactions,
+ );
+
+ if (update) {
+ updates.push(update);
+ }
+
+ const latest = pickLatestInteraction(interactions);
+
+ if (latest) {
+ contactByPersonId.set(personId, {
+ occurredAt: latest.occurredAt,
+ itemId: latest.itemId,
+ kind: latest.kind,
+ });
+ }
+ }
+
+ await upsertRecordsInBatches(client, 'createPeople', updates);
+ await updateRelatedLastContactForPeople(client, contactByPersonId);
+};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/collect-existing-record-ids.ts b/packages/twenty-apps/public/last-contact/src/utils/collect-existing-record-ids.ts
new file mode 100644
index 00000000000..39c8b12d3de
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/utils/collect-existing-record-ids.ts
@@ -0,0 +1,45 @@
+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;
+
+export type RecordQueryField = 'people' | 'companies' | 'opportunities';
+
+export const collectExistingRecordIds = async (
+ client: CoreApiClient,
+ queryField: RecordQueryField,
+ recordIds: string[],
+): Promise<Set<string>> => {
+ const existingRecordIds = new Set<string>();
+
+ for (const ids of chunk(recordIds, PAGE_SIZE)) {
+ let after: string | undefined;
+
+ do {
+ const result = await executeWithRetry(() =>
+ client.query({
+ [queryField]: {
+ __args: { filter: { id: { in: ids } }, first: PAGE_SIZE, after },
+ edges: { node: { id: true } },
+ pageInfo: { hasNextPage: true, endCursor: true },
+ },
+ }),
+ );
+ const connection = result?.[queryField];
+
+ for (const edge of connection?.edges ?? []) {
+ if (edge.node.id) {
+ existingRecordIds.add(edge.node.id);
+ }
+ }
+
+ after = connection?.pageInfo.hasNextPage
+ ? (connection.pageInfo.endCursor ?? undefined)
+ : undefined;
+ } while (after);
+ }
+
+ return existingRecordIds;
+};
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.ts
index 7ab69c74397..2bb455043e4 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,20 +1,48 @@
import { type CoreApiClient } from 'twenty-client-sdk/core';
+import { collectExistingRecordIds } from 'src/utils/collect-existing-record-ids';
import { executeWithRetry } from 'src/utils/execute-with-retry';
+import {
+ type RecordUpsert,
+ upsertRecordsInBatches,
+} from 'src/utils/upsert-records-in-batches';
+
+const PAGE_SIZE = 200;
+const MAX_SCAN_PAGES = 5;
+
+const EMPTY_LAST_CONTACT: Record<string, string | null> = {
+ lastContactAt: null,
+ lastContactItemMessageId: null,
+ lastContactItemCalendarEventId: null,
+};
type PersonNode = {
+ companyId?: string | null;
lastContactAt?: string | null;
lastContactItemMessage?: { id: string } | null;
lastContactItemCalendarEvent?: { id: string } | null;
};
-// A company's last contact mirrors the most recent contact of any of its people,
-// so it must be recomputed whenever that set of people changes rather than only
-// when an interaction happens.
-export const recomputeCompanyLastContact = async (
+const PERSON_LAST_CONTACT_SELECTION = {
+ companyId: true,
+ lastContactAt: true,
+ lastContactItemMessage: { id: true },
+ lastContactItemCalendarEvent: { id: true },
+};
+
+const buildLastContactData = (
+ person: PersonNode,
+): Record<string, string | null> => ({
+ lastContactAt: person.lastContactAt ?? null,
+ lastContactItemMessageId: person.lastContactItemMessage?.id ?? null,
+ lastContactItemCalendarEventId:
+ person.lastContactItemCalendarEvent?.id ?? null,
+});
+
+const fetchTopPersonForCompany = async (
client: CoreApiClient,
companyId: string,
-): Promise<void> => {
+): Promise<PersonNode | undefined> => {
const { people } = await executeWithRetry(() =>
client.query({
people: {
@@ -26,43 +54,99 @@ export const recomputeCompanyLastContact = async (
orderBy: [{ lastContactAt: 'DescNullsLast' }],
first: 1,
},
- edges: {
- node: {
- lastContactAt: true,
- lastContactItemMessage: { id: true },
- lastContactItemCalendarEvent: { id: true },
- },
- },
+ edges: { node: PERSON_LAST_CONTACT_SELECTION },
},
}),
);
- const topPerson = (people?.edges?.[0]?.node as PersonNode | undefined) ?? {};
+ return people?.edges?.[0]?.node as PersonNode | undefined;
+};
- await executeWithRetry(() =>
- client.mutation({
- updateCompany: {
- __args: {
- id: companyId,
- data: {
- lastContactAt: topPerson.lastContactAt ?? null,
- lastContactItemMessageId:
- topPerson.lastContactItemMessage?.id ?? null,
- lastContactItemCalendarEventId:
- topPerson.lastContactItemCalendarEvent?.id ?? null,
+const collectTopPersonByCompanyId = async (
+ client: CoreApiClient,
+ companyIds: string[],
+): Promise<Map<string, PersonNode>> => {
+ const topPersonByCompanyId = new Map<string, PersonNode>();
+ const unresolvedCompanyIds = new Set(companyIds);
+
+ let after: string | undefined;
+ let scannedPages = 0;
+ let hasNextPage = false;
+
+ do {
+ const { people } = await executeWithRetry(() =>
+ client.query({
+ people: {
+ __args: {
+ filter: {
+ companyId: { in: companyIds },
+ lastContactAt: { is: 'NOT_NULL' },
+ },
+ orderBy: [{ lastContactAt: 'DescNullsLast' }],
+ first: PAGE_SIZE,
+ after,
},
+ edges: { node: PERSON_LAST_CONTACT_SELECTION },
+ pageInfo: { hasNextPage: true, endCursor: true },
},
- id: true,
- },
- }),
+ }),
+ );
+
+ for (const edge of people?.edges ?? []) {
+ const person = edge.node as PersonNode;
+ const companyId = person.companyId;
+
+ if (companyId && unresolvedCompanyIds.has(companyId)) {
+ topPersonByCompanyId.set(companyId, person);
+ unresolvedCompanyIds.delete(companyId);
+ }
+ }
+
+ scannedPages += 1;
+ hasNextPage = people?.pageInfo.hasNextPage ?? false;
+ after = hasNextPage ? (people?.pageInfo.endCursor ?? undefined) : undefined;
+ } while (
+ after &&
+ unresolvedCompanyIds.size > 0 &&
+ scannedPages < MAX_SCAN_PAGES
);
+
+ if (hasNextPage) {
+ for (const companyId of unresolvedCompanyIds) {
+ const topPerson = await fetchTopPersonForCompany(client, companyId);
+
+ if (topPerson) {
+ topPersonByCompanyId.set(companyId, topPerson);
+ }
+ }
+ }
+
+ return topPersonByCompanyId;
};
export const recomputeCompaniesLastContact = async (
client: CoreApiClient,
companyIds: string[],
): Promise<void> => {
- for (const companyId of companyIds) {
- await recomputeCompanyLastContact(client, companyId);
+ if (companyIds.length === 0) {
+ return;
}
+
+ const [topPersonByCompanyId, existingCompanyIds] = await Promise.all([
+ collectTopPersonByCompanyId(client, companyIds),
+ collectExistingRecordIds(client, 'companies', companyIds),
+ ]);
+
+ const upserts: RecordUpsert[] = companyIds
+ .filter((companyId) => existingCompanyIds.has(companyId))
+ .map((companyId) => {
+ const topPerson = topPersonByCompanyId.get(companyId);
+
+ return {
+ id: companyId,
+ ...(topPerson ? buildLastContactData(topPerson) : EMPTY_LAST_CONTACT),
+ };
+ });
+
+ await upsertRecordsInBatches(client, 'createCompanies', upserts);
};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/recompute-opportunity-last-contact.ts b/packages/twenty-apps/public/last-contact/src/utils/recompute-opportunity-last-contact.ts
index 93c123969e6..9ef393a97c8 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
@@ -2,6 +2,10 @@ import { type CoreApiClient } from 'twenty-client-sdk/core';
import { chunk } from 'src/utils/chunk';
import { executeWithRetry } from 'src/utils/execute-with-retry';
+import {
+ type RecordUpsert,
+ upsertRecordsInBatches,
+} from 'src/utils/upsert-records-in-batches';
const PAGE_SIZE = 200;
@@ -132,22 +136,14 @@ export const recomputeOpportunitiesLastContact = async (
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,
- },
- }),
- );
- }
+ const upserts: RecordUpsert[] = [
+ ...pointOfContactIdByOpportunityId,
+ ].map(([opportunityId, pointOfContactId]) => ({
+ id: opportunityId,
+ ...((pointOfContactId
+ ? lastContactByPersonId.get(pointOfContactId)
+ : undefined) ?? EMPTY_LAST_CONTACT),
+ }));
+
+ await upsertRecordsInBatches(client, 'createOpportunities', upserts);
};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/update-person-last-contact.ts b/packages/twenty-apps/public/last-contact/src/utils/update-person-last-contact.ts
index d293c197992..34a9e6a9cea 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,6 +1,10 @@
import { type CoreApiClient } from 'twenty-client-sdk/core';
+import { chunk } from 'src/utils/chunk';
import { executeWithRetry } from 'src/utils/execute-with-retry';
+import { type RecordUpsert } from 'src/utils/upsert-records-in-batches';
+
+const PAGE_SIZE = 200;
export type InteractionKind = 'email' | 'meeting';
export type InteractionDirection = 'outbound' | 'inbound';
@@ -11,6 +15,14 @@ export type Interaction = {
workspaceMemberId: string | null;
} & ({ kind: 'email'; direction: InteractionDirection } | { kind: 'meeting' });
+export type PersonLastContactState = {
+ lastContactAt?: string | null;
+ lastOutboundAt?: string | null;
+ lastInboundAt?: string | null;
+ lastEmail?: { receivedAt: string | null } | null;
+ lastMeeting?: { startsAt: string | null } | null;
+};
+
const isNewer = (
candidate: string,
current: string | null | undefined,
@@ -39,39 +51,65 @@ export const pickLatestInteraction = (
interactions: Interaction[],
): Interaction | undefined => pickLatest(interactions);
-export const updatePersonForInteractions = async (
+export const collectPersonLastContactState = async (
client: CoreApiClient,
+ personIds: string[],
+): Promise<Map<string, PersonLastContactState>> => {
+ const stateByPersonId = new Map<string, PersonLastContactState>();
+
+ 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,
+ lastOutboundAt: true,
+ lastInboundAt: true,
+ lastEmail: { receivedAt: true },
+ lastMeeting: { startsAt: true },
+ },
+ },
+ pageInfo: { hasNextPage: true, endCursor: true },
+ },
+ }),
+ );
+
+ for (const edge of people?.edges ?? []) {
+ const { id, ...state } = edge.node as PersonLastContactState & {
+ id?: string | null;
+ };
+
+ if (id) {
+ stateByPersonId.set(id, state);
+ }
+ }
+
+ after = people?.pageInfo.hasNextPage
+ ? (people.pageInfo.endCursor ?? undefined)
+ : undefined;
+ } while (after);
+ }
+
+ return stateByPersonId;
+};
+
+export const buildPersonLastContactUpdate = (
personId: string,
+ current: PersonLastContactState,
interactions: Interaction[],
-): Promise<void> => {
+): RecordUpsert | undefined => {
const latestContact = pickLatest(interactions);
if (!latestContact) {
- return;
+ return undefined;
}
- 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;
- lastOutboundAt?: string | null;
- lastInboundAt?: string | null;
- lastEmail?: { receivedAt: string | null } | null;
- lastMeeting?: { startsAt: string | null } | null;
- };
-
const data: Record<string, string | null> = {};
const occurredAt = latestContact.occurredAt;
@@ -124,63 +162,8 @@ export const updatePersonForInteractions = async (
}
if (Object.keys(data).length === 0) {
- return;
+ return undefined;
}
- if ('lastContactAt' in data) {
- const { updatePeople } = await executeWithRetry(() =>
- client.mutation({
- updatePeople: {
- __args: {
- data,
- filter: {
- and: [
- { id: { eq: personId } },
- {
- or: [
- { lastContactAt: { is: 'NULL' } },
- { lastContactAt: { lt: occurredAt } },
- ],
- },
- ],
- },
- },
- id: true,
- },
- }),
- );
-
- if (Array.isArray(updatePeople) && updatePeople.length > 0) {
- return;
- }
-
- const directionalData: Record<string, string | null> = { ...data };
- delete directionalData.lastContactAt;
- delete directionalData.lastContactById;
- delete directionalData.lastContactItemMessageId;
- delete directionalData.lastContactItemCalendarEventId;
-
- if (Object.keys(directionalData).length === 0) {
- return;
- }
-
- await executeWithRetry(() =>
- client.mutation({
- updatePerson: {
- __args: { id: personId, data: directionalData },
- id: true,
- },
- }),
- );
- return;
- }
-
- await executeWithRetry(() =>
- client.mutation({
- updatePerson: {
- __args: { id: personId, data },
- id: true,
- },
- }),
- );
+ return { id: personId, ...data };
};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/update-related-last-contact.ts b/packages/twenty-apps/public/last-contact/src/utils/update-related-last-contact.ts
index d241713a02a..72a46a6be9f 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
@@ -3,6 +3,10 @@ import { type CoreApiClient } from 'twenty-client-sdk/core';
import { chunk } from 'src/utils/chunk';
import { executeWithRetry } from 'src/utils/execute-with-retry';
import { type InteractionKind } from 'src/utils/update-person-last-contact';
+import {
+ type RecordUpsert,
+ upsertRecordsInBatches,
+} from 'src/utils/upsert-records-in-batches';
const PAGE_SIZE = 200;
@@ -12,12 +16,16 @@ export type RelatedInteraction = {
kind: InteractionKind;
};
-const recencyGuard = (occurredAt: string) => ({
- or: [
- { lastContactAt: { is: 'NULL' } },
- { lastContactAt: { lt: occurredAt } },
- ],
-});
+type OpportunityLink = {
+ opportunityId: string;
+ pointOfContactId: string;
+ lastContactAt: string | null;
+};
+
+const isNewer = (
+ candidate: string,
+ current: string | null | undefined,
+): boolean => !current || current < candidate;
const buildData = ({
occurredAt,
@@ -66,11 +74,48 @@ const collectCompanyIdByPersonId = async (
return companyIdByPersonId;
};
-const collectPointOfContactIds = async (
+const collectCompanyLastContactAt = async (
+ client: CoreApiClient,
+ companyIds: string[],
+): Promise<Map<string, string | null>> => {
+ const lastContactAtByCompanyId = new Map<string, string | null>();
+
+ for (const ids of chunk(companyIds, PAGE_SIZE)) {
+ let after: string | undefined;
+
+ do {
+ const { companies } = await executeWithRetry(() =>
+ client.query({
+ companies: {
+ __args: { filter: { id: { in: ids } }, first: PAGE_SIZE, after },
+ edges: { node: { id: true, lastContactAt: true } },
+ pageInfo: { hasNextPage: true, endCursor: true },
+ },
+ }),
+ );
+
+ for (const edge of companies?.edges ?? []) {
+ const { id, lastContactAt } = edge.node;
+
+ if (id) {
+ lastContactAtByCompanyId.set(id, lastContactAt ?? null);
+ }
+ }
+
+ after = companies?.pageInfo.hasNextPage
+ ? (companies.pageInfo.endCursor ?? undefined)
+ : undefined;
+ } while (after);
+ }
+
+ return lastContactAtByCompanyId;
+};
+
+const collectOpportunityLinks = async (
client: CoreApiClient,
personIds: string[],
-): Promise<Set<string>> => {
- const pointOfContactIds = new Set<string>();
+): Promise<OpportunityLink[]> => {
+ const links: OpportunityLink[] = [];
for (const ids of chunk(personIds, PAGE_SIZE)) {
let after: string | undefined;
@@ -84,17 +129,27 @@ const collectPointOfContactIds = async (
first: PAGE_SIZE,
after,
},
- edges: { node: { id: true, pointOfContactId: true } },
+ edges: {
+ node: {
+ id: true,
+ pointOfContactId: true,
+ lastContactAt: true,
+ },
+ },
pageInfo: { hasNextPage: true, endCursor: true },
},
}),
);
for (const edge of opportunities?.edges ?? []) {
- const { pointOfContactId } = edge.node;
-
- if (pointOfContactId) {
- pointOfContactIds.add(pointOfContactId);
+ const { id, pointOfContactId, lastContactAt } = edge.node;
+
+ if (id && pointOfContactId) {
+ links.push({
+ opportunityId: id,
+ pointOfContactId,
+ lastContactAt: lastContactAt ?? null,
+ });
}
}
@@ -104,7 +159,7 @@ const collectPointOfContactIds = async (
} while (after);
}
- return pointOfContactIds;
+ return links;
};
// Companies and opportunities surface emails and meetings from their related
@@ -140,49 +195,40 @@ export const updateRelatedLastContactForPeople = async (
}
}
+ const lastContactAtByCompanyId = await collectCompanyLastContactAt(
+ client,
+ [...contactByCompanyId.keys()],
+ );
+ const companyUpserts: RecordUpsert[] = [];
+
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,
- },
- }),
- );
+ if (!lastContactAtByCompanyId.has(companyId)) {
+ continue;
+ }
+
+ if (isNewer(contact.occurredAt, lastContactAtByCompanyId.get(companyId))) {
+ companyUpserts.push({ id: companyId, ...buildData(contact) });
+ }
}
- const pointOfContactIds = await collectPointOfContactIds(client, personIds);
+ await upsertRecordsInBatches(client, 'createCompanies', companyUpserts);
+
+ const opportunityLinks = await collectOpportunityLinks(client, personIds);
+ const opportunityUpserts: RecordUpsert[] = [];
- for (const personId of pointOfContactIds) {
- const contact = contactByPersonId.get(personId);
+ for (const { opportunityId, pointOfContactId, lastContactAt } of opportunityLinks) {
+ const contact = contactByPersonId.get(pointOfContactId);
- if (!contact) {
+ if (!contact || !isNewer(contact.occurredAt, lastContactAt)) {
continue;
}
- await executeWithRetry(() =>
- client.mutation({
- updateOpportunities: {
- __args: {
- data: buildData(contact),
- filter: {
- and: [
- { pointOfContactId: { eq: personId } },
- recencyGuard(contact.occurredAt),
- ],
- },
- },
- id: true,
- },
- }),
- );
+ opportunityUpserts.push({ id: opportunityId, ...buildData(contact) });
}
+
+ await upsertRecordsInBatches(
+ client,
+ 'createOpportunities',
+ opportunityUpserts,
+ );
};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/upsert-records-in-batches.ts b/packages/twenty-apps/public/last-contact/src/utils/upsert-records-in-batches.ts
new file mode 100644
index 00000000000..4c601685e37
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/utils/upsert-records-in-batches.ts
@@ -0,0 +1,30 @@
+import { type CoreApiClient } from 'twenty-client-sdk/core';
+
+import { chunk } from 'src/utils/chunk';
+import { executeWithRetry } from 'src/utils/execute-with-retry';
+
+const QUERY_MAX_RECORDS = 200;
+
+export type UpsertMutationName =
+ | 'createPeople'
+ | 'createCompanies'
+ | 'createOpportunities';
+
+export type RecordUpsert = { id: string } & Record<string, string | null>;
+
+export const upsertRecordsInBatches = async (
+ client: CoreApiClient,
+ mutationName: UpsertMutationName,
+ records: RecordUpsert[],
+): Promise<void> => {
+ for (const batch of chunk(records, QUERY_MAX_RECORDS)) {
+ await executeWithRetry(() =>
+ client.mutation({
+ [mutationName]: {
+ __args: { data: batch, upsert: true },
+ id: true,
+ },
+ }),
+ );
+ }
+};