Skip to content

The open alternative to Salesforce, designed for AI.

Last contact 1.9.1: stop restoring trashed people, skip unchanged writes (#27755)

martmull27a99f6d8072
diff --git a/packages/twenty-apps/public/last-contact/CHANGELOG.md b/packages/twenty-apps/public/last-contact/CHANGELOG.md
index 07c0dc9c57d..6010e972a7a 100644
--- a/packages/twenty-apps/public/last-contact/CHANGELOG.md
+++ b/packages/twenty-apps/public/last-contact/CHANGELOG.md
@@ -1,5 +1,10 @@
# Changelog
+## 1.9.1
+
+- Stop the backfill from restoring people trashed while it reads their emails and meetings. Writing a person's last contact restores the record if it is in the trash, and recreates it without a name if it was deleted. The people phase now reads its batch again right before writing, after the paced reads of their emails and meetings, and leaves out people that are gone. A person trashed during the write itself, or while it is retried after a rate limit, can still come back: closing that needs a server update that never restores a record.
+- Only write records whose last contact actually changes. Every write sets the record's "Last update" to now, so since 1.9.0 one backfill marked every person, company and opportunity in the workspace as just updated. The backfill and the company and opportunity recomputes now compare with the stored values first, which also saves the write call for a batch where nothing changed. A company recompute now reads the company before its people, so a company that was already up to date is no longer lowered when a live update raises it during the recompute.
+
## 1.9.0
- Drop the `on-person-created` and `on-company-created` triggers. Last contact only comes from a synced email or meeting linked to a person, so a newly created person or company never has one, and recomputing the company on creation could not change anything. A mailbox sync that creates contacts spent 6 API calls per batch of 100 contacts on them.
diff --git a/packages/twenty-apps/public/last-contact/package.json b/packages/twenty-apps/public/last-contact/package.json
index 35214db19b5..ba617546ad0 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.9.0",
+ "version": "1.9.1",
"license": "MIT",
"engines": {
"node": "^24.5.0",
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 c805dea61f9..7d30cc43932 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
@@ -40,7 +40,7 @@ beforeEach(() => {
? Promise.resolve({
companies: {
edges: query.companies.__args.filter.id.in.map((id: string) => ({
- node: { id },
+ node: { id, lastContactAt: '2026-01-01T09:00:00.000Z' },
})),
pageInfo: { hasNextPage: false, endCursor: null },
},
diff --git a/packages/twenty-apps/public/last-contact/src/utils/__tests__/backfill-people-last-contact.test.ts b/packages/twenty-apps/public/last-contact/src/utils/__tests__/backfill-people-last-contact.test.ts
index d59ffd458c1..b3f9aacdf84 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/__tests__/backfill-people-last-contact.test.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/__tests__/backfill-people-last-contact.test.ts
@@ -15,34 +15,82 @@ const CONTACTED_PERSON_ID = '11111111-1111-1111-1111-111111111111';
const UNCONTACTED_PERSON_ID = '22222222-2222-2222-2222-222222222222';
const MESSAGE_ID = '33333333-3333-3333-3333-333333333333';
const MEMBER_ID = '44444444-4444-4444-4444-444444444444';
+const STALE_MESSAGE_ID = '55555555-5555-5555-5555-555555555555';
const RECEIVED_AT = '2026-06-10T09:00:00.000Z';
+const STALE_RECEIVED_AT = '2026-01-01T09:00:00.000Z';
+
+const CONTACTED_PERSON_DATA = {
+ lastContactAt: RECEIVED_AT,
+ lastContactById: MEMBER_ID,
+ lastOutboundAt: RECEIVED_AT,
+ lastInboundAt: null,
+ lastEmailId: MESSAGE_ID,
+ lastMeetingId: null,
+ lastContactItemMessageId: MESSAGE_ID,
+ lastContactItemCalendarEventId: null,
+};
+
+const EMPTY_PERSON_DATA = {
+ lastContactAt: null,
+ lastContactById: null,
+ lastOutboundAt: null,
+ lastInboundAt: null,
+ lastEmailId: null,
+ lastMeetingId: null,
+ lastContactItemMessageId: null,
+ lastContactItemCalendarEventId: null,
+};
+
+const STALE_PERSON_DATA = {
+ ...EMPTY_PERSON_DATA,
+ lastContactAt: STALE_RECEIVED_AT,
+ lastInboundAt: STALE_RECEIVED_AT,
+ lastEmailId: STALE_MESSAGE_ID,
+ lastContactItemMessageId: STALE_MESSAGE_ID,
+};
const client = {
query: vi.fn(),
mutation: vi.fn().mockResolvedValue({}),
};
+const mockCurrentPeople = (people: Record<string, unknown>[]) =>
+ client.query.mockResolvedValue({
+ people: {
+ edges: people.map((node) => ({ node })),
+ pageInfo: { hasNextPage: false, endCursor: null },
+ },
+ });
+
+const upsertedPeople = () =>
+ client.mutation.mock.calls[0]?.[0].createPeople.__args.data;
+
beforeEach(() => {
+ client.query.mockReset();
client.mutation.mockClear();
buildPersonAggregatesMock.mockReset();
+ buildPersonAggregatesMock.mockResolvedValue(
+ new Map([
+ [
+ CONTACTED_PERSON_ID,
+ {
+ lastContactAt: RECEIVED_AT,
+ lastContactById: MEMBER_ID,
+ item: { kind: 'email', id: MESSAGE_ID },
+ lastOutboundAt: RECEIVED_AT,
+ lastEmail: { at: RECEIVED_AT, id: MESSAGE_ID },
+ },
+ ],
+ ]),
+ );
});
describe('backfillPeopleLastContact', () => {
it('writes every field of every person, clearing those no interaction supports', async () => {
- buildPersonAggregatesMock.mockResolvedValue(
- new Map([
- [
- CONTACTED_PERSON_ID,
- {
- lastContactAt: RECEIVED_AT,
- lastContactById: MEMBER_ID,
- item: { kind: 'email', id: MESSAGE_ID },
- lastOutboundAt: RECEIVED_AT,
- lastEmail: { at: RECEIVED_AT, id: MESSAGE_ID },
- },
- ],
- ]),
- );
+ mockCurrentPeople([
+ { id: CONTACTED_PERSON_ID, ...STALE_PERSON_DATA },
+ { id: UNCONTACTED_PERSON_ID, ...STALE_PERSON_DATA },
+ ]);
await backfillPeopleLastContact(client as never, [
CONTACTED_PERSON_ID,
@@ -53,29 +101,79 @@ describe('backfillPeopleLastContact', () => {
expect(client.mutation.mock.calls[0][0].createPeople.__args).toEqual({
upsert: true,
data: [
- {
- id: CONTACTED_PERSON_ID,
- lastContactAt: RECEIVED_AT,
- lastContactById: MEMBER_ID,
- lastOutboundAt: RECEIVED_AT,
- lastInboundAt: null,
- lastEmailId: MESSAGE_ID,
- lastMeetingId: null,
- lastContactItemMessageId: MESSAGE_ID,
- lastContactItemCalendarEventId: null,
- },
- {
- id: UNCONTACTED_PERSON_ID,
- lastContactAt: null,
- lastContactById: null,
- lastOutboundAt: null,
- lastInboundAt: null,
- lastEmailId: null,
- lastMeetingId: null,
- lastContactItemMessageId: null,
- lastContactItemCalendarEventId: null,
- },
+ { id: CONTACTED_PERSON_ID, ...CONTACTED_PERSON_DATA },
+ { id: UNCONTACTED_PERSON_ID, ...EMPTY_PERSON_DATA },
],
});
});
+
+ it('leaves out a person deleted since the batch was listed rather than upserting it back', async () => {
+ mockCurrentPeople([{ id: UNCONTACTED_PERSON_ID, ...STALE_PERSON_DATA }]);
+
+ await backfillPeopleLastContact(client as never, [
+ CONTACTED_PERSON_ID,
+ UNCONTACTED_PERSON_ID,
+ ]);
+
+ expect(upsertedPeople()).toEqual([
+ { id: UNCONTACTED_PERSON_ID, ...EMPTY_PERSON_DATA },
+ ]);
+ });
+
+ it('reads the people after aggregating their interactions, right before the write', async () => {
+ mockCurrentPeople([{ id: CONTACTED_PERSON_ID, ...STALE_PERSON_DATA }]);
+
+ await backfillPeopleLastContact(client as never, [CONTACTED_PERSON_ID]);
+
+ expect(buildPersonAggregatesMock.mock.invocationCallOrder[0]).toBeLessThan(
+ client.query.mock.invocationCallOrder[0],
+ );
+ expect(client.query.mock.invocationCallOrder[0]).toBeLessThan(
+ client.mutation.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('leaves out a person whose last contact already matches', async () => {
+ mockCurrentPeople([
+ {
+ id: CONTACTED_PERSON_ID,
+ ...CONTACTED_PERSON_DATA,
+ lastContactAt: '2026-06-10T09:00:00Z',
+ },
+ { id: UNCONTACTED_PERSON_ID, ...STALE_PERSON_DATA },
+ ]);
+
+ await backfillPeopleLastContact(client as never, [
+ CONTACTED_PERSON_ID,
+ UNCONTACTED_PERSON_ID,
+ ]);
+
+ expect(upsertedPeople()).toEqual([
+ { id: UNCONTACTED_PERSON_ID, ...EMPTY_PERSON_DATA },
+ ]);
+ });
+
+ it('writes a person whose last contact date matches but whose last email differs', async () => {
+ mockCurrentPeople([
+ {
+ id: CONTACTED_PERSON_ID,
+ ...CONTACTED_PERSON_DATA,
+ lastEmailId: STALE_MESSAGE_ID,
+ },
+ ]);
+
+ await backfillPeopleLastContact(client as never, [CONTACTED_PERSON_ID]);
+
+ expect(upsertedPeople()).toEqual([
+ { id: CONTACTED_PERSON_ID, ...CONTACTED_PERSON_DATA },
+ ]);
+ });
+
+ it('skips the write when no person changes', async () => {
+ mockCurrentPeople([{ id: UNCONTACTED_PERSON_ID, ...EMPTY_PERSON_DATA }]);
+
+ await backfillPeopleLastContact(client as never, [UNCONTACTED_PERSON_ID]);
+
+ expect(client.mutation).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/twenty-apps/public/last-contact/src/utils/__tests__/has-last-contact-changed.test.ts b/packages/twenty-apps/public/last-contact/src/utils/__tests__/has-last-contact-changed.test.ts
new file mode 100644
index 00000000000..7bb4356ec29
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/utils/__tests__/has-last-contact-changed.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest';
+
+import { hasLastContactChanged } from 'src/utils/has-last-contact-changed';
+
+const MESSAGE_ID = '11111111-1111-1111-1111-111111111111';
+const OTHER_MESSAGE_ID = '22222222-2222-2222-2222-222222222222';
+const OCCURRED_AT = '2026-06-10T09:00:00.000Z';
+
+describe('hasLastContactChanged', () => {
+ it('detects a change in a field other than lastContactAt', () => {
+ expect(
+ hasLastContactChanged(
+ { lastContactAt: OCCURRED_AT, lastEmailId: OTHER_MESSAGE_ID },
+ { lastContactAt: OCCURRED_AT, lastEmailId: MESSAGE_ID },
+ ),
+ ).toBe(true);
+ });
+
+ it.each(['lastContactAt', 'lastOutboundAt', 'lastInboundAt'])(
+ 'treats the same instant written differently as unchanged in %s',
+ (fieldName) => {
+ expect(
+ hasLastContactChanged(
+ { [fieldName]: '2026-06-10T09:00:00Z' },
+ { [fieldName]: OCCURRED_AT },
+ ),
+ ).toBe(false);
+ },
+ );
+
+ it('detects a different instant', () => {
+ expect(
+ hasLastContactChanged(
+ { lastInboundAt: OCCURRED_AT },
+ { lastInboundAt: '2026-06-11T09:00:00.000Z' },
+ ),
+ ).toBe(true);
+ });
+
+ it('treats a missing stored value as empty', () => {
+ expect(
+ hasLastContactChanged({}, { lastContactAt: null, lastEmailId: null }),
+ ).toBe(false);
+ });
+});
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 e20f7ed34ba..69c121cd4e8 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
@@ -9,6 +9,12 @@ 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 STALE_LAST_CONTACT = {
+ lastContactAt: '2026-01-01T09:00:00.000Z',
+ lastContactItemMessageId: '66666666-6666-6666-6666-666666666666',
+ lastContactItemCalendarEventId: null,
+};
+
const EMPTY_LAST_CONTACT = {
lastContactAt: null,
lastContactItemMessageId: null,
@@ -31,10 +37,13 @@ const buildPage = (
const buildClient = ({
peoplePages = [buildPage([])],
- existingCompanyIds = [COMPANY_ID, OTHER_COMPANY_ID],
+ currentCompanies = [
+ { id: COMPANY_ID, ...STALE_LAST_CONTACT },
+ { id: OTHER_COMPANY_ID, ...STALE_LAST_CONTACT },
+ ],
}: {
peoplePages?: ReturnType<typeof buildPage>[];
- existingCompanyIds?: string[];
+ currentCompanies?: Record<string, unknown>[];
}): Client => {
let peopleCallIndex = 0;
@@ -42,7 +51,7 @@ const buildClient = ({
query: vi.fn().mockImplementation((query) => {
if (query.companies) {
return Promise.resolve({
- companies: buildPage(existingCompanyIds.map((id) => ({ id }))),
+ companies: buildPage(currentCompanies),
});
}
@@ -81,7 +90,7 @@ describe('recomputeCompaniesLastContact', () => {
},
]),
],
- existingCompanyIds: [COMPANY_ID],
+ currentCompanies: [{ id: COMPANY_ID, ...STALE_LAST_CONTACT }],
});
await recomputeCompaniesLastContact(client as never, [COMPANY_ID]);
@@ -114,7 +123,7 @@ describe('recomputeCompaniesLastContact', () => {
},
]),
],
- existingCompanyIds: [COMPANY_ID],
+ currentCompanies: [{ id: COMPANY_ID, ...STALE_LAST_CONTACT }],
});
await recomputeCompaniesLastContact(client as never, [COMPANY_ID]);
@@ -130,7 +139,9 @@ describe('recomputeCompaniesLastContact', () => {
});
it('clears the company last contact when no person has a contact', async () => {
- client = buildClient({ existingCompanyIds: [COMPANY_ID] });
+ client = buildClient({
+ currentCompanies: [{ id: COMPANY_ID, ...STALE_LAST_CONTACT }],
+ });
await recomputeCompaniesLastContact(client as never, [COMPANY_ID]);
@@ -264,10 +275,65 @@ describe('recomputeCompaniesLastContact', () => {
});
it('leaves out a company that no longer exists rather than upserting it back', async () => {
- client = buildClient({ existingCompanyIds: [] });
+ client = buildClient({ currentCompanies: [] });
await recomputeCompaniesLastContact(client as never, [COMPANY_ID]);
+ expect(peopleQueries()).toHaveLength(0);
expect(client.mutation).not.toHaveBeenCalled();
});
+
+ it('only scans and writes the companies that still exist', async () => {
+ client = buildClient({
+ currentCompanies: [{ id: COMPANY_ID, ...STALE_LAST_CONTACT }],
+ });
+
+ await recomputeCompaniesLastContact(client as never, [
+ COMPANY_ID,
+ OTHER_COMPANY_ID,
+ ]);
+
+ expect(peopleQueries()[0][0].people.__args.filter.companyId).toEqual({
+ in: [COMPANY_ID],
+ });
+ expect(upsertData()).toEqual([{ id: COMPANY_ID, ...EMPTY_LAST_CONTACT }]);
+ });
+
+ it('leaves out a company whose last contact already matches', async () => {
+ client = buildClient({
+ peoplePages: [
+ buildPage([
+ {
+ companyId: COMPANY_ID,
+ lastContactAt: OCCURRED_AT,
+ lastContactItemMessage: { id: MESSAGE_ID },
+ lastContactItemCalendarEvent: null,
+ },
+ ]),
+ ],
+ currentCompanies: [
+ {
+ id: COMPANY_ID,
+ lastContactAt: '2026-06-10T09:00:00Z',
+ lastContactItemMessageId: MESSAGE_ID,
+ lastContactItemCalendarEventId: null,
+ },
+ { id: OTHER_COMPANY_ID, ...EMPTY_LAST_CONTACT },
+ ],
+ });
+
+ await recomputeCompaniesLastContact(client as never, [
+ COMPANY_ID,
+ OTHER_COMPANY_ID,
+ ]);
+
+ expect(client.mutation).not.toHaveBeenCalled();
+ });
+
+ it('reads the companies before their people', async () => {
+ await recomputeCompaniesLastContact(client as never, [COMPANY_ID]);
+
+ expect(Object.keys(client.query.mock.calls[0][0])).toEqual(['companies']);
+ expect(Object.keys(client.query.mock.calls[1][0])).toEqual(['people']);
+ });
});
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 77b0055d0c4..3cbfec0bf89 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
@@ -58,7 +58,9 @@ describe('recomputeOpportunitiesLastContact', () => {
});
it('clears the opportunity last contact when there is no point of contact', async () => {
- client = buildClient([{ id: OPPORTUNITY_ID, pointOfContact: null }]);
+ client = buildClient([
+ { id: OPPORTUNITY_ID, ...POINT_OF_CONTACT, pointOfContact: null },
+ ]);
await recomputeOpportunitiesLastContact(client as never, [OPPORTUNITY_ID]);
@@ -94,6 +96,44 @@ describe('recomputeOpportunitiesLastContact', () => {
).toEqual([OPPORTUNITY_ID, OTHER_OPPORTUNITY_ID]);
});
+ it('leaves out an opportunity whose last contact already matches', async () => {
+ client = buildClient([
+ {
+ id: OPPORTUNITY_ID,
+ lastContactAt: '2026-06-10T09:00:00Z',
+ lastContactItemMessageId: MESSAGE_ID,
+ lastContactItemCalendarEventId: null,
+ pointOfContact: POINT_OF_CONTACT,
+ },
+ { id: OTHER_OPPORTUNITY_ID, pointOfContact: POINT_OF_CONTACT },
+ ]);
+
+ await recomputeOpportunitiesLastContact(client as never, [
+ OPPORTUNITY_ID,
+ OTHER_OPPORTUNITY_ID,
+ ]);
+
+ expect(
+ client.mutation.mock.calls[0][0].createOpportunities.__args.data.map(
+ (record: { id: string }) => record.id,
+ ),
+ ).toEqual([OTHER_OPPORTUNITY_ID]);
+ });
+
+ it('skips the write when no opportunity changes', async () => {
+ client = buildClient([
+ {
+ id: OPPORTUNITY_ID,
+ ...POINT_OF_CONTACT,
+ pointOfContact: POINT_OF_CONTACT,
+ },
+ ]);
+
+ await recomputeOpportunitiesLastContact(client as never, [OPPORTUNITY_ID]);
+
+ expect(client.mutation).not.toHaveBeenCalled();
+ });
+
it('leaves out an opportunity that no longer exists', async () => {
await recomputeOpportunitiesLastContact(client as never, [OPPORTUNITY_ID]);
diff --git a/packages/twenty-apps/public/last-contact/src/utils/backfill-people-last-contact.ts b/packages/twenty-apps/public/last-contact/src/utils/backfill-people-last-contact.ts
index c48c2909954..0c838ce6f30 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/backfill-people-last-contact.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/backfill-people-last-contact.ts
@@ -1,10 +1,16 @@
import { type CoreApiClient } from 'twenty-client-sdk/core';
+import { collectRecordsById } from 'src/utils/collect-records-by-id';
+import { hasLastContactChanged } from 'src/utils/has-last-contact-changed';
import {
buildPersonAggregates,
buildPersonUpdateData,
+ PERSON_LAST_CONTACT_FIELD_NAMES,
} from 'src/utils/person-last-contact-aggregation';
-import { upsertRecordsInBatches } from 'src/utils/upsert-records-in-batches';
+import {
+ type RecordUpsert,
+ upsertRecordsInBatches,
+} from 'src/utils/upsert-records-in-batches';
export const backfillPeopleLastContact = async (
client: CoreApiClient,
@@ -12,12 +18,30 @@ export const backfillPeopleLastContact = async (
): Promise<void> => {
const aggByPersonId = await buildPersonAggregates(client, personIds);
- await upsertRecordsInBatches(
+ // Read right before the write: the upsert restores a person trashed since
+ // the batch was listed and recreates one deleted since.
+ const currentPersonById = await collectRecordsById(
client,
- 'createPeople',
- personIds.map((personId) => ({
- id: personId,
- ...buildPersonUpdateData(aggByPersonId.get(personId)),
- })),
+ 'people',
+ personIds,
+ PERSON_LAST_CONTACT_FIELD_NAMES,
);
+
+ const upserts: RecordUpsert[] = [];
+
+ for (const personId of personIds) {
+ const currentPerson = currentPersonById.get(personId);
+
+ if (!currentPerson) {
+ continue;
+ }
+
+ const data = buildPersonUpdateData(aggByPersonId.get(personId));
+
+ if (hasLastContactChanged(currentPerson, data)) {
+ upserts.push({ id: personId, ...data });
+ }
+ }
+
+ await upsertRecordsInBatches(client, 'createPeople', upserts);
};
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-records-by-id.ts
similarity index 65%
rename from packages/twenty-apps/public/last-contact/src/utils/collect-existing-record-ids.ts
rename to packages/twenty-apps/public/last-contact/src/utils/collect-records-by-id.ts
index 39c8b12d3de..a3d002e2db1 100644
--- a/packages/twenty-apps/public/last-contact/src/utils/collect-existing-record-ids.ts
+++ b/packages/twenty-apps/public/last-contact/src/utils/collect-records-by-id.ts
@@ -7,12 +7,18 @@ const PAGE_SIZE = 200;
export type RecordQueryField = 'people' | 'companies' | 'opportunities';
-export const collectExistingRecordIds = async (
+export type RecordNode = { id: string } & Record<string, unknown>;
+
+export const collectRecordsById = async (
client: CoreApiClient,
queryField: RecordQueryField,
recordIds: string[],
-): Promise<Set<string>> => {
- const existingRecordIds = new Set<string>();
+ fieldNames: string[],
+): Promise<Map<string, RecordNode>> => {
+ const recordsById = new Map<string, RecordNode>();
+ const selection = Object.fromEntries(
+ fieldNames.map((fieldName) => [fieldName, true]),
+ );
for (const ids of chunk(recordIds, PAGE_SIZE)) {
let after: string | undefined;
@@ -22,7 +28,7 @@ export const collectExistingRecordIds = async (
client.query({
[queryField]: {
__args: { filter: { id: { in: ids } }, first: PAGE_SIZE, after },
- edges: { node: { id: true } },
+ edges: { node: { ...selection, id: true } },
pageInfo: { hasNextPage: true, endCursor: true },
},
}),
@@ -30,8 +36,10 @@ export const collectExistingRecordIds = async (
const connection = result?.[queryField];
for (const edge of connection?.edges ?? []) {
- if (edge.node.id) {
- existingRecordIds.add(edge.node.id);
+ const node = edge.node as RecordNode;
+
+ if (node.id) {
+ recordsById.set(node.id, node);
}
}
@@ -41,5 +49,5 @@ export const collectExistingRecordIds = async (
} while (after);
}
- return existingRecordIds;
+ return recordsById;
};
diff --git a/packages/twenty-apps/public/last-contact/src/utils/has-last-contact-changed.ts b/packages/twenty-apps/public/last-contact/src/utils/has-last-contact-changed.ts
new file mode 100644
index 00000000000..d7b0eb5350b
--- /dev/null
+++ b/packages/twenty-apps/public/last-contact/src/utils/has-last-contact-changed.ts
@@ -0,0 +1,29 @@
+import { isDefined } from 'twenty-sdk/utils';
+
+const TIMESTAMP_FIELD_NAMES = new Set([
+ 'lastContactAt',
+ 'lastOutboundAt',
+ 'lastInboundAt',
+]);
+
+const normalizeValue = (fieldName: string, value: unknown): unknown => {
+ if (!isDefined(value)) {
+ return null;
+ }
+
+ return TIMESTAMP_FIELD_NAMES.has(fieldName) && typeof value === 'string'
+ ? Date.parse(value)
+ : value;
+};
+
+// Every upsert bumps updatedAt, so records whose values already match are left
+// out of the write.
+export const hasLastContactChanged = (
+ current: Record<string, unknown>,
+ next: Record<string, string | null>,
+): boolean =>
+ Object.entries(next).some(
+ ([fieldName, value]) =>
+ normalizeValue(fieldName, current[fieldName]) !==
+ normalizeValue(fieldName, value),
+ );
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.ts
index eec6dec1af3..acc6351b215 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
@@ -360,3 +360,7 @@ export const buildPersonUpdateData = (
lastContactItemCalendarEventId:
agg?.item?.kind === 'meeting' ? agg.item.id : null,
});
+
+export const PERSON_LAST_CONTACT_FIELD_NAMES = Object.keys(
+ buildPersonUpdateData(undefined),
+);
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 2bb455043e4..7fea88eaf4e 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,7 +1,8 @@
import { type CoreApiClient } from 'twenty-client-sdk/core';
-import { collectExistingRecordIds } from 'src/utils/collect-existing-record-ids';
+import { collectRecordsById } from 'src/utils/collect-records-by-id';
import { executeWithRetry } from 'src/utils/execute-with-retry';
+import { hasLastContactChanged } from 'src/utils/has-last-contact-changed';
import {
type RecordUpsert,
upsertRecordsInBatches,
@@ -132,21 +133,40 @@ export const recomputeCompaniesLastContact = async (
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),
- };
- });
+ // Read companies before their people: a company already up to date is then
+ // skipped rather than lowered if a live job raises it during the recompute.
+ const currentCompanyById = await collectRecordsById(
+ client,
+ 'companies',
+ companyIds,
+ Object.keys(EMPTY_LAST_CONTACT),
+ );
+ const existingCompanyIds = companyIds.filter((companyId) =>
+ currentCompanyById.has(companyId),
+ );
+
+ if (existingCompanyIds.length === 0) {
+ return;
+ }
+
+ const topPersonByCompanyId = await collectTopPersonByCompanyId(
+ client,
+ existingCompanyIds,
+ );
+
+ const upserts: RecordUpsert[] = [];
+
+ for (const companyId of existingCompanyIds) {
+ const topPerson = topPersonByCompanyId.get(companyId);
+ const data = topPerson
+ ? buildLastContactData(topPerson)
+ : EMPTY_LAST_CONTACT;
+ const currentCompany = currentCompanyById.get(companyId);
+
+ if (currentCompany && hasLastContactChanged(currentCompany, data)) {
+ upserts.push({ id: companyId, ...data });
+ }
+ }
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 ab5dbc87432..6fe80a468e1 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,7 @@ import { type CoreApiClient } from 'twenty-client-sdk/core';
import { chunk } from 'src/utils/chunk';
import { executeWithRetry } from 'src/utils/execute-with-retry';
+import { hasLastContactChanged } from 'src/utils/has-last-contact-changed';
import {
type RecordUpsert,
upsertRecordsInBatches,
@@ -19,6 +20,9 @@ const EMPTY_LAST_CONTACT: LastContactData = {
type OpportunityNode = {
id?: string | null;
+ lastContactAt?: string | null;
+ lastContactItemMessageId?: string | null;
+ lastContactItemCalendarEventId?: string | null;
pointOfContact?: {
lastContactAt?: string | null;
lastContactItemMessageId?: string | null;
@@ -63,6 +67,9 @@ export const recomputeOpportunitiesLastContact = async (
edges: {
node: {
id: true,
+ lastContactAt: true,
+ lastContactItemMessageId: true,
+ lastContactItemCalendarEventId: true,
pointOfContact: {
lastContactAt: true,
lastContactItemMessageId: true,
@@ -76,10 +83,11 @@ export const recomputeOpportunitiesLastContact = async (
);
for (const edge of opportunities?.edges ?? []) {
- const { id, pointOfContact } = edge.node as OpportunityNode;
+ const opportunity = edge.node as OpportunityNode;
+ const data = buildLastContactData(opportunity.pointOfContact);
- if (id) {
- upserts.push({ id, ...buildLastContactData(pointOfContact) });
+ if (opportunity.id && hasLastContactChanged(opportunity, data)) {
+ upserts.push({ id: opportunity.id, ...data });
}
}