From 6c4c59d2552d1790d71c7a04276f90e1572397b6 Mon Sep 17 00:00:00 2001 From: Zach Probst Date: Wed, 21 Oct 2026 16:08:59 -0400 Subject: [PATCH 1/4] Use date-based client-credentials token endpoint The v1 token path is being superseded by /oauth/2026-09/token; the request and response shapes are unchanged, so only the URL moves (into a shared constant). --- src/auth.ts | 4 ++-- src/utils/utils.ts | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/auth.ts b/src/auth.ts index 7d0b65a..1e0bf15 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -1,7 +1,7 @@ import axios from 'axios'; import * as hubspot from '@hubspot/api-client'; import { prisma, hubspotClient, LIMITER_OPTIONS } from './clients'; -import { HUBSPOT_API_BASE, JOURNAL_SCOPES, OAUTH_SCOPES } from './utils/utils'; +import { OAUTH_TOKEN_URL, JOURNAL_SCOPES, OAUTH_SCOPES } from './utils/utils'; import { registerPortal } from './portals'; import { createLogger } from './utils/logger'; @@ -137,7 +137,7 @@ export async function getClientCredentialToken(): Promise { logger.info('Requesting new client credentials token...'); const response = await axios.post( - `${HUBSPOT_API_BASE}/oauth/v1/token`, + OAUTH_TOKEN_URL, new URLSearchParams({ grant_type: 'client_credentials', client_id: CLIENT_ID!, diff --git a/src/utils/utils.ts b/src/utils/utils.ts index 37027e7..2fca45f 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -2,6 +2,8 @@ export const PORT = 3002; export const HUBSPOT_API_BASE = 'https://api.hubapi.com'; +export const OAUTH_TOKEN_URL = `${HUBSPOT_API_BASE}/oauth/2026-09/token`; + export const WEBHOOKS_JOURNAL_API_VERSION = '2027-03-beta'; export const JOURNAL_API_BASE = `${HUBSPOT_API_BASE}/webhooks-journal/journal/${WEBHOOKS_JOURNAL_API_VERSION}`; export const SUBSCRIPTIONS_API_BASE = `${HUBSPOT_API_BASE}/webhooks-journal/subscriptions/${WEBHOOKS_JOURNAL_API_VERSION}`; @@ -26,3 +28,13 @@ export const APP_UNINSTALL_EVENT_TYPE_ID = process.env.APP_UNINSTALL_EVENT_TYPE_ export const JOURNAL_POLL_INTERVAL_MS = 1000; export const JOURNAL_BATCH_SIZE = 100; export const SNAPSHOT_POLL_INTERVAL_MS = 1000; + +// Journal file URLs are S3 presigned URLs: the query string is the credential. +export function redactPresignedUrl(url: string): string { + try { + const parsed = new URL(url); + return `${parsed.origin}${parsed.pathname}${parsed.search ? '?' : ''}`; + } catch { + return ''; + } +} From 24bd6ac1f6520d39a08e6b8b1cea81368ad7dc1c Mon Sep 17 00:00:00 2001 From: Zach Probst Date: Wed, 21 Oct 2026 16:09:04 -0400 Subject: [PATCH 2/4] Name the failing journal file in download errors without leaking its credential Journal file URLs are presigned S3 URLs whose query string is the credential. A failed download previously gave no hint which file failed, and logging the URL to fix that would leak it. downloadJournalFile now rethrows with status and origin+path only, so the worker's failed handler logs a safe, useful message. --- README.md | 2 ++ __tests__/processor.test.ts | 57 +++++++++++++++++++++++++++++++++++++ __tests__/utils.test.ts | 20 +++++++++++++ src/journal/processor.ts | 26 +++++++++++++++-- 4 files changed, 102 insertions(+), 3 deletions(-) create mode 100644 __tests__/processor.test.ts diff --git a/README.md b/README.md index a33437b..ec70dd0 100644 --- a/README.md +++ b/README.md @@ -185,6 +185,8 @@ The app uses **two OAuth flows**: - `MERGE` → delete merged contacts, upsert surviving contact 4. **Last-write-wins**: if an incoming event's `occurredAt` is older than the contact's `lastModifiedDate`, it's skipped +> **Note:** Journal file URLs are presigned S3 URLs. Their query string is a credential, so never log a URL in full. This example logs only the origin and path (see `redactPresignedUrl`). + ### Empty and Not-Found Responses The journal API signals "nothing here" differently depending on the endpoint. Handle each case explicitly; if you port this example to `fetch` or another HTTP client, don't rely on how that client happens to treat an empty body. diff --git a/__tests__/processor.test.ts b/__tests__/processor.test.ts new file mode 100644 index 0000000..5dc473a --- /dev/null +++ b/__tests__/processor.test.ts @@ -0,0 +1,57 @@ +import axios from 'axios'; +import { downloadJournalFile } from '../src/journal/processor'; + +jest.mock('axios', () => ({ + __esModule: true, + default: { + get: jest.fn(), + isAxiosError: (error: unknown) => + typeof error === 'object' && error !== null && 'isAxiosError' in error, + }, +})); + +jest.mock('../src/clients', () => ({ prisma: {} })); +jest.mock('../src/portals', () => ({ registerPortal: jest.fn(), unregisterPortal: jest.fn() })); +jest.mock('../src/hubspot/subscriptions', () => ({ createContactSubscription: jest.fn() })); + +const mockedGet = jest.mocked(axios.get); + +const PRESIGNED_URL = + 'https://bucket.s3.amazonaws.com/journal/file.json?X-Amz-Credential=AKIA123&X-Amz-Signature=deadbeef'; + +describe('downloadJournalFile', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('returns the downloaded journal file', async () => { + mockedGet.mockResolvedValue({ data: { journalEvents: [] } }); + await expect(downloadJournalFile(PRESIGNED_URL)).resolves.toEqual({ journalEvents: [] }); + }); + + it('reports the status and path but not the presigned query on HTTP failure', async () => { + mockedGet.mockRejectedValue({ + isAxiosError: true, + message: `Request failed with status code 403 for ${PRESIGNED_URL}`, + response: { status: 403 }, + }); + + const error = await downloadJournalFile(PRESIGNED_URL).catch((e: unknown) => e); + + expect(error).toBeInstanceOf(Error); + const message = error instanceof Error ? error.message : ''; + expect(message).toBe( + 'Journal file download failed (403) for https://bucket.s3.amazonaws.com/journal/file.json?' + ); + expect(message).not.toContain('deadbeef'); + expect(message).not.toContain('X-Amz'); + }); + + it('reports a network error when there is no response', async () => { + mockedGet.mockRejectedValue(new Error('socket hang up')); + + await expect(downloadJournalFile(PRESIGNED_URL)).rejects.toThrow( + 'Journal file download failed (network error) for https://bucket.s3.amazonaws.com/journal/file.json?' + ); + }); +}); diff --git a/__tests__/utils.test.ts b/__tests__/utils.test.ts index 19c82f7..764ff30 100644 --- a/__tests__/utils.test.ts +++ b/__tests__/utils.test.ts @@ -4,6 +4,7 @@ import { OAUTH_SCOPES, JOURNAL_POLL_INTERVAL_MS, JOURNAL_BATCH_SIZE, + redactPresignedUrl, } from '../src/utils/utils'; describe('utils constants', () => { @@ -34,3 +35,22 @@ describe('utils constants', () => { expect(JOURNAL_BATCH_SIZE).toBeGreaterThan(0); }); }); + +describe('redactPresignedUrl', () => { + it('strips the query string from a presigned S3 URL', () => { + const url = + 'https://bucket.s3.amazonaws.com/journal/2027/file.json?X-Amz-Credential=AKIA%2F20270101%2Fus-east-1&X-Amz-Signature=deadbeef'; + const redacted = redactPresignedUrl(url); + expect(redacted).toBe('https://bucket.s3.amazonaws.com/journal/2027/file.json?'); + expect(redacted).not.toContain('deadbeef'); + expect(redacted).not.toContain('AKIA'); + }); + + it('leaves a URL without a query string unchanged', () => { + expect(redactPresignedUrl('https://example.com/a/b.json')).toBe('https://example.com/a/b.json'); + }); + + it('returns a placeholder for invalid input', () => { + expect(redactPresignedUrl('not a url')).toBe(''); + }); +}); diff --git a/src/journal/processor.ts b/src/journal/processor.ts index 6234021..35eb3da 100644 --- a/src/journal/processor.ts +++ b/src/journal/processor.ts @@ -5,13 +5,33 @@ import { prisma } from '../clients'; import { registerPortal, unregisterPortal } from '../portals'; import { createContactSubscription } from '../hubspot/subscriptions'; import { createLogger } from '../utils/logger'; +import { redactPresignedUrl } from '../utils/utils'; import { JournalEvent, JournalEventItem, CrmObjectEvent, AppLifecycleEvent } from '../types/common'; const logger = createLogger('EventProcessor'); -async function downloadJournalFile(url: string): Promise { - const response = await axios.get(url); - return response.data; +// tsconfig targets ES2020, which lacks ErrorOptions.cause, so carry it explicitly. +export class JournalDownloadError extends Error { + readonly cause: unknown; + + constructor(message: string, cause: unknown) { + super(message); + this.name = 'JournalDownloadError'; + this.cause = cause; + } +} + +export async function downloadJournalFile(url: string): Promise { + try { + const response = await axios.get(url); + return response.data; + } catch (error) { + const status = axios.isAxiosError(error) ? error.response?.status : undefined; + throw new JournalDownloadError( + `Journal file download failed (${status ?? 'network error'}) for ${redactPresignedUrl(url)}`, + error + ); + } } function extractProperties(event: CrmObjectEvent): Record { From fb8cd17d828570eb775b60161206b0777b7464c4 Mon Sep 17 00:00:00 2001 From: Zach Probst Date: Wed, 21 Oct 2026 16:09:32 -0400 Subject: [PATCH 3/4] Rename download tests so the processor suite name stays free for DB-backed tests --- __tests__/{processor.test.ts => download.test.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename __tests__/{processor.test.ts => download.test.ts} (100%) diff --git a/__tests__/processor.test.ts b/__tests__/download.test.ts similarity index 100% rename from __tests__/processor.test.ts rename to __tests__/download.test.ts From f90c2b28da0d3b45a918872ca58dca5166bcc149 Mon Sep 17 00:00:00 2001 From: Zach Probst Date: Wed, 21 Oct 2026 16:10:29 -0400 Subject: [PATCH 4/4] Soft-delete contacts so RESTORE brings back the stored data A RESTORE journal event only carries the properties that action changed, so recreating a hard-deleted contact from it left the row mostly empty. DELETE now sets deletedAt (and writes a tombstone for unseen contacts so an older out-of-order CREATE/UPDATE can't resurrect it), upserts clear deletedAt, and the contacts API hides deleted rows. MERGE still hard-deletes merged IDs since they never come back. --- README.md | 9 +- __tests__/processor.test.ts | 208 ++++++++++++++++++++++++++++++++++++ prisma/schema.prisma | 1 + src/journal/processor.ts | 37 +++++-- src/routes/contactRoutes.ts | 2 +- src/types/common.d.ts | 1 + 6 files changed, 244 insertions(+), 14 deletions(-) create mode 100644 __tests__/processor.test.ts diff --git a/README.md b/README.md index a33437b..847a1c1 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,8 @@ createdb webhooks_journal_example # or use your preferred method npm run db-init ``` +> **Upgrading an existing checkout?** Re-run `npm run db-init` (`prisma db push`) to add the `deletedAt` column to the `Contact` table. + ### 5. Start the App In two terminal windows: @@ -180,9 +182,10 @@ The app uses **two OAuth flows**: 1. The **Journal Poller** calls `GET /webhooks-journal/journal/2027-03-beta/batch/{offset}/next/100` once per second 2. Each journal entry URL is enqueued as a BullMQ job with 3 retry attempts and exponential backoff 3. **Event Processor** workers (5 concurrent) dequeue jobs, download the S3 file, and process each event: - - `CREATE` / `UPDATE` / `RESTORE` / `SNAPSHOT` → upsert contact in database - - `DELETE` → remove contact from database - - `MERGE` → delete merged contacts, upsert surviving contact + - `CREATE` / `UPDATE` / `SNAPSHOT` → upsert contact in database + - `DELETE` → soft delete: the row is kept and `deletedAt` is set, so the contact disappears from the UI but its data is retained + - `RESTORE` → upsert contact and clear `deletedAt`; the stored email and names come back even though a `RESTORE` event carries few or no properties + - `MERGE` → remove merged contacts permanently (merged IDs never come back), upsert surviving contact 4. **Last-write-wins**: if an incoming event's `occurredAt` is older than the contact's `lastModifiedDate`, it's skipped ### Empty and Not-Found Responses diff --git a/__tests__/processor.test.ts b/__tests__/processor.test.ts new file mode 100644 index 0000000..8ef66b5 --- /dev/null +++ b/__tests__/processor.test.ts @@ -0,0 +1,208 @@ +import { Server } from 'http'; +import express from 'express'; +import { prisma } from '../src/clients'; +import { processEvent } from '../src/journal/processor'; +import contactRoutes from '../src/routes/contactRoutes'; +import { CrmObjectEvent } from '../src/types/common'; + +jest.mock('../src/portals', () => ({ + registerPortal: jest.fn(), + unregisterPortal: jest.fn(), +})); + +jest.mock('../src/hubspot/subscriptions', () => ({ + createContactSubscription: jest.fn(), +})); + +const PORTAL_ID = 111; +const OBJECT_ID = 222; +const T0 = '2025-12-31T00:00:00.000Z'; +const T1 = '2026-01-01T00:00:00.000Z'; +const T2 = '2026-01-02T00:00:00.000Z'; +const T3 = '2026-01-03T00:00:00.000Z'; + +const hasTestDatabase = (process.env.DATABASE_URL ?? '').includes('_test'); +const describeWithDb = hasTestDatabase ? describe : describe.skip; + +function crmEvent( + action: CrmObjectEvent['action'], + occurredAt: string, + propertyChanges?: Record, +): CrmObjectEvent { + return { + type: 'crmObjectEvent', + portalId: PORTAL_ID, + occurredAt, + action, + objectTypeId: '0-1', + objectId: OBJECT_ID, + propertyChanges, + }; +} + +async function processAll(events: CrmObjectEvent[]): Promise { + await prisma.$transaction(async (tx) => { + for (const event of events) { + await processEvent(event, tx); + } + }); +} + +async function findContact() { + return prisma.contact.findUnique({ + where: { hsObjectId_portalId: { hsObjectId: String(OBJECT_ID), portalId: String(PORTAL_ID) } }, + }); +} + +describeWithDb('contact soft delete reconciliation', () => { + beforeEach(async () => { + await prisma.$executeRaw`TRUNCATE TABLE "Contact" RESTART IDENTITY`; + }); + + afterAll(async () => { + await prisma.$disconnect(); + }); + + it('soft-deletes on DELETE and keeps the contact data', async () => { + await processAll([ + crmEvent('CREATE', T1, { email: 'a@example.com', firstname: 'Ada', lastname: 'Lovelace' }), + crmEvent('DELETE', T2), + ]); + + const contact = await findContact(); + expect(contact?.deletedAt).not.toBeNull(); + expect(contact?.deletedAt).toEqual(contact?.lastModifiedDate); + expect(contact?.email).toBe('a@example.com'); + expect(contact?.firstname).toBe('Ada'); + expect(contact?.lastname).toBe('Lovelace'); + }); + + it('brings the original data back on RESTORE without any properties', async () => { + await processAll([ + crmEvent('CREATE', T1, { email: 'a@example.com', firstname: 'Ada', lastname: 'Lovelace' }), + crmEvent('DELETE', T2), + crmEvent('RESTORE', T3), + ]); + + const contact = await findContact(); + expect(contact?.deletedAt).toBeNull(); + expect(contact?.email).toBe('a@example.com'); + expect(contact?.firstname).toBe('Ada'); + expect(contact?.lastname).toBe('Lovelace'); + }); + + it('keeps a contact deleted when an older UPDATE is processed after the DELETE', async () => { + await processAll([ + crmEvent('CREATE', T0, { email: 'a@example.com' }), + crmEvent('DELETE', T2), + ]); + const deleted = await findContact(); + + await processAll([crmEvent('UPDATE', T1, { email: 'stale@example.com' })]); + + const contact = await findContact(); + expect(contact?.deletedAt).not.toBeNull(); + expect(contact?.deletedAt).toEqual(deleted?.deletedAt); + expect(contact?.lastModifiedDate).toEqual(deleted?.lastModifiedDate); + expect(contact?.email).toBe('a@example.com'); + }); + + it('writes a tombstone for an unknown contact so an older CREATE cannot resurrect it', async () => { + await processAll([crmEvent('DELETE', T2)]); + + const tombstone = await findContact(); + expect(tombstone?.deletedAt).not.toBeNull(); + expect(tombstone?.email).toBeNull(); + + await processAll([crmEvent('CREATE', T1, { email: 'a@example.com' })]); + + const contact = await findContact(); + expect(contact?.deletedAt).toEqual(tombstone?.deletedAt); + expect(contact?.email).toBeNull(); + }); + + it('un-deletes when a newer UPDATE arrives after the DELETE', async () => { + await processAll([ + crmEvent('CREATE', T1, { email: 'a@example.com' }), + crmEvent('DELETE', T2), + crmEvent('UPDATE', T3, { firstname: 'Ada' }), + ]); + + const contact = await findContact(); + expect(contact?.deletedAt).toBeNull(); + expect(contact?.email).toBe('a@example.com'); + expect(contact?.firstname).toBe('Ada'); + }); + + it('un-deletes when a newer SNAPSHOT arrives after the DELETE', async () => { + await processAll([ + crmEvent('CREATE', T1, { email: 'a@example.com' }), + crmEvent('DELETE', T2), + ]); + await processAll([ + { + ...crmEvent('SNAPSHOT', T3), + propertyChanges: undefined, + properties: { email: 'a@example.com', firstname: 'Ada', lastname: 'Lovelace' }, + }, + ]); + + const contact = await findContact(); + expect(contact?.deletedAt).toBeNull(); + expect(contact?.lastname).toBe('Lovelace'); + }); + + it('hard-deletes merged contacts', async () => { + await processAll([crmEvent('CREATE', T1, { email: 'merged@example.com' })]); + + await processAll([ + { + ...crmEvent('MERGE', T2, { email: 'survivor@example.com' }), + objectId: OBJECT_ID + 1, + mergedObjectIds: [OBJECT_ID], + }, + ]); + + expect(await findContact()).toBeNull(); + const survivor = await prisma.contact.findUnique({ + where: { hsObjectId_portalId: { hsObjectId: String(OBJECT_ID + 1), portalId: String(PORTAL_ID) } }, + }); + expect(survivor?.email).toBe('survivor@example.com'); + }); + + describe('GET /api/contacts', () => { + let server: Server; + let baseUrl: string; + + beforeAll(async () => { + const app = express(); + app.use('/api', contactRoutes); + await new Promise((resolve) => { + server = app.listen(0, () => resolve()); + }); + const address = server.address(); + if (!address || typeof address === 'string') { + throw new Error('Test server did not bind to a port'); + } + baseUrl = `http://127.0.0.1:${address.port}`; + }); + + afterAll(async () => { + await new Promise((resolve) => server.close(() => resolve())); + }); + + it('excludes soft-deleted contacts from the list and the total', async () => { + await processAll([ + crmEvent('CREATE', T1, { email: 'gone@example.com' }), + crmEvent('DELETE', T2), + { ...crmEvent('CREATE', T1, { email: 'kept@example.com' }), objectId: OBJECT_ID + 1 }, + ]); + + const response = await fetch(`${baseUrl}/api/contacts`); + const body: unknown = await response.json(); + + expect(body).toMatchObject({ total: 1, contacts: [{ email: 'kept@example.com' }] }); + expect(body).toHaveProperty('contacts.length', 1); + }); + }); +}); diff --git a/prisma/schema.prisma b/prisma/schema.prisma index e5352f3..12232cb 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -30,6 +30,7 @@ model Contact { firstname String? lastname String? lastModifiedDate DateTime? + deletedAt DateTime? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt diff --git a/src/journal/processor.ts b/src/journal/processor.ts index 6234021..de21433 100644 --- a/src/journal/processor.ts +++ b/src/journal/processor.ts @@ -28,24 +28,35 @@ async function upsertContact(event: CrmObjectEvent, tx: Prisma.TransactionClient logger.info(`SNAPSHOT event for contact ${hsObjectId} (portal ${portalId}), properties: ${JSON.stringify(properties)}`); } + // A RESTORE event's propertyChanges only carry what that action changed, so + // the contact's data comes back from the row we kept when it was deleted. + // If we have no row to restore (the app started after the delete, or an app + // that hard-deletes), an alternative is to request a single-object snapshot: + // POST ${SNAPSHOTS_API_BASE}/crm with the client-credentials token and body + // { snapshotRequests: [{ portalId, objectId, objectTypeId: '0-1', + // properties: ['email', 'firstname', 'lastname'] }] }. The current properties + // then arrive as a SNAPSHOT event through the journal. const email = 'email' in properties ? properties.email : undefined; const firstname = 'firstname' in properties ? properties.firstname : undefined; const lastname = 'lastname' in properties ? properties.lastname : undefined; // Atomic upsert with last-write-wins: only update if incoming event is newer const result = await tx.$executeRaw` - INSERT INTO "Contact" ("hsObjectId", "portalId", "email", "firstname", "lastname", "lastModifiedDate", "createdAt", "updatedAt") - VALUES (${hsObjectId}, ${portalId}, ${email ?? null}, ${firstname ?? null}, ${lastname ?? null}, ${occurredAt}, NOW(), NOW()) + INSERT INTO "Contact" ("hsObjectId", "portalId", "email", "firstname", "lastname", "lastModifiedDate", "deletedAt", "createdAt", "updatedAt") + VALUES (${hsObjectId}, ${portalId}, ${email ?? null}, ${firstname ?? null}, ${lastname ?? null}, ${occurredAt}, NULL, NOW(), NOW()) ON CONFLICT ("hsObjectId", "portalId") DO UPDATE SET "email" = COALESCE(${email ?? null}, "Contact"."email"), "firstname" = COALESCE(${firstname ?? null}, "Contact"."firstname"), "lastname" = COALESCE(${lastname ?? null}, "Contact"."lastname"), "lastModifiedDate" = ${occurredAt}, + "deletedAt" = NULL, "updatedAt" = NOW() WHERE "Contact"."lastModifiedDate" IS NULL OR "Contact"."lastModifiedDate" < ${occurredAt} `; - if (result > 0) { + if (result > 0 && event.action === 'RESTORE') { + logger.info(`Restored contact ${hsObjectId} for portal ${portalId}`); + } else if (result > 0) { logger.info(`Upserted contact ${hsObjectId} for portal ${portalId} (action: ${event.action})`); } else { logger.debug(`Skipping stale event for contact ${hsObjectId} (last-write-wins)`); @@ -57,17 +68,23 @@ async function deleteContact(event: CrmObjectEvent, tx: Prisma.TransactionClient const portalId = String(event.portalId); const occurredAt = new Date(event.occurredAt); + // Soft delete so a later RESTORE can bring the row's data back. For a contact + // we've never seen, write a tombstone so an older out-of-order CREATE/UPDATE + // processed afterwards is rejected by last-write-wins instead of resurrecting it. const result = await tx.$executeRaw` - DELETE FROM "Contact" - WHERE "hsObjectId" = ${hsObjectId} - AND "portalId" = ${portalId} - AND ("lastModifiedDate" IS NULL OR "lastModifiedDate" <= ${occurredAt}) + INSERT INTO "Contact" ("hsObjectId", "portalId", "lastModifiedDate", "deletedAt", "createdAt", "updatedAt") + VALUES (${hsObjectId}, ${portalId}, ${occurredAt}, ${occurredAt}, NOW(), NOW()) + ON CONFLICT ("hsObjectId", "portalId") DO UPDATE SET + "deletedAt" = ${occurredAt}, + "lastModifiedDate" = ${occurredAt}, + "updatedAt" = NOW() + WHERE "Contact"."lastModifiedDate" IS NULL OR "Contact"."lastModifiedDate" <= ${occurredAt} `; if (result > 0) { - logger.info(`Deleted contact ${hsObjectId} from portal ${portalId}`); + logger.info(`Soft-deleted contact ${hsObjectId} from portal ${portalId}`); } else { - logger.debug(`Contact ${hsObjectId} not found or has newer data, skipping delete`); + logger.debug(`Contact ${hsObjectId} has newer data, skipping delete`); } } @@ -92,7 +109,7 @@ async function handleMerge(event: CrmObjectEvent, tx: Prisma.TransactionClient): await upsertContact(event, tx); } -async function processEvent(event: CrmObjectEvent, tx: Prisma.TransactionClient): Promise { +export async function processEvent(event: CrmObjectEvent, tx: Prisma.TransactionClient): Promise { if (event.objectTypeId !== '0-1') { logger.debug(`Skipping non-contact event (objectTypeId: ${event.objectTypeId})`); return; diff --git a/src/routes/contactRoutes.ts b/src/routes/contactRoutes.ts index 2cc0e15..40edb7e 100644 --- a/src/routes/contactRoutes.ts +++ b/src/routes/contactRoutes.ts @@ -11,7 +11,7 @@ router.get('/contacts', async (req: Request, res: Response) => { const offset = Math.max(Number(req.query.offset) || 0, 0); const portalId = req.query.portalId as string | undefined; - const where = portalId && portalId !== 'all' ? { portalId } : {}; + const where = portalId && portalId !== 'all' ? { portalId, deletedAt: null } : { deletedAt: null }; const [contacts, total] = await Promise.all([ prisma.contact.findMany({ diff --git a/src/types/common.d.ts b/src/types/common.d.ts index d861a76..abb97ed 100644 --- a/src/types/common.d.ts +++ b/src/types/common.d.ts @@ -85,6 +85,7 @@ export interface ContactData { firstname: string | null; lastname: string | null; lastModifiedDate: Date | null; + deletedAt: Date | null; createdAt: Date; updatedAt: Date; }