Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
refactor(api): improve email normalization and enhance record deletion handling
Lewis Carhart277afef311bd
diff --git a/apps/api/scripts/dev-session.ts b/apps/api/scripts/dev-session.tsindex 421f6e80..8df9b3dd 100644--- a/apps/api/scripts/dev-session.ts+++ b/apps/api/scripts/dev-session.ts@@ -1,6 +1,7 @@+import { AUTH_COOKIE_PREFIX } from "@crm/auth/cookies";import { db } from "@crm/db";-const COOKIE_NAME = "better-auth.session_token";+const COOKIE_NAME = `${AUTH_COOKIE_PREFIX}.session_token`;const SESSION_DAYS = 7;if (process.env.NODE_ENV === "production") {diff --git a/apps/api/src/companies/companies.service.ts b/apps/api/src/companies/companies.service.tsindex 222c4962..6a2e62a0 100644--- a/apps/api/src/companies/companies.service.ts+++ b/apps/api/src/companies/companies.service.ts@@ -377,12 +377,16 @@ export class CompaniesService {throw new NotFoundException(`No company with id ${id}.`);}- await this.db.$transaction([- this.db.agentTask.deleteMany({ where: { companyId: id } }),- this.db.company.delete({ where: { id } }),- ]);+ try {+ await this.db.$transaction([+ this.db.agentTask.deleteMany({ where: { companyId: id } }),+ this.db.company.delete({ where: { id } }),+ ]);+ } catch (error) {+ throw this.translate(error, id);+ }- await this.stamp.recomputeAll();+ await this.stamp.recomputeAllAfterDelete({ companyId: id });this.logger.log({message: "Company deleted",diff --git a/apps/api/src/contacts/contacts.service.ts b/apps/api/src/contacts/contacts.service.tsindex 7c3768e3..24f98e86 100644--- a/apps/api/src/contacts/contacts.service.ts+++ b/apps/api/src/contacts/contacts.service.ts@@ -17,7 +17,7 @@ import { AgentQueueService } from "../agent/agent-queue.service";import { AgentTriggerService } from "../agent/agent-trigger.service";import { CompanyDirectoryService } from "../companies/company-directory.service";import { ActivityStampService } from "../crm/activity-stamp.service";-import { blankToNull, toCents } from "../crm/values";+import { blankToNull, normalizeEmail, toCents } from "../crm/values";import { InjectDatabase } from "../database/database.constants";import {countsByKey,@@ -257,11 +257,11 @@ export class ContactsService {}async create(input: ContactCreateInput) {- const email = blankToNull(input.email ?? "");+ const email = normalizeEmail(input.email ?? "");if (email) {- const existing = await this.db.contact.findUnique({- where: { email },+ const existing = await this.db.contact.findFirst({+ where: { email: { equals: email, mode: "insensitive" } },select: { id: true, firstName: true, lastName: true },});if (existing) {@@ -279,20 +279,22 @@ export class ContactsService {}): null);- const contact = await this.db.contact.create({- data: {- firstName: input.firstName.trim(),- lastName: blankToNull(input.lastName ?? ""),- email,- phone: blankToNull(input.phone ?? ""),- title: blankToNull(input.title ?? ""),- companyId,- ownerId: input.ownerId ?? null,- },- select: { id: true, firstName: true, lastName: true },- });+ const contact = await this.db.$transaction(async (tx) => {+ await this.allowAgain(tx, email);- await this.allowAgain(email);+ return tx.contact.create({+ data: {+ firstName: input.firstName.trim(),+ lastName: blankToNull(input.lastName ?? ""),+ email,+ phone: blankToNull(input.phone ?? ""),+ title: blankToNull(input.title ?? ""),+ companyId,+ ownerId: input.ownerId ?? null,+ },+ select: { id: true, firstName: true, lastName: true },+ });+ });this.logger.log({ message: "Contact created", contactId: contact.id });@@ -318,30 +320,36 @@ export class ContactsService {.filter(Boolean).join(" ");- await this.db.$transaction([- ...(contact.email- ? [- this.db.suppressedContact.upsert({- where: { email: contact.email },- create: {- email: contact.email,- reason: `Deleted from the CRM (${name})`,- },- update: {},- }),- ]- : []),- this.db.agentTask.deleteMany({ where: { contactId: id } }),- this.db.agentEvent.deleteMany({ where: { contactId: id } }),- this.db.contact.delete({ where: { id } }),- ]);+ const suppress = normalizeEmail(contact.email ?? "");- await this.stamp.recomputeAll();+ try {+ await this.db.$transaction([+ ...(suppress+ ? [+ this.db.suppressedContact.upsert({+ where: { email: suppress },+ create: {+ email: suppress,+ reason: `Deleted from the CRM (${name})`,+ },+ update: {},+ }),+ ]+ : []),+ this.db.agentTask.deleteMany({ where: { contactId: id } }),+ this.db.agentEvent.deleteMany({ where: { contactId: id } }),+ this.db.contact.delete({ where: { id } }),+ ]);+ } catch (error) {+ throw this.translate(error, id);+ }++ await this.stamp.recomputeAllAfterDelete({ contactId: id });this.logger.log({message: "Contact deleted",contactId: id,- suppressed: contact.email !== null,+ suppressed: suppress !== null,});return { id, name };@@ -353,7 +361,7 @@ export class ContactsService {if (input.firstName !== undefined) data.firstName = input.firstName.trim();if (input.lastName !== undefined)data.lastName = blankToNull(input.lastName);- if (input.email !== undefined) data.email = blankToNull(input.email);+ if (input.email !== undefined) data.email = normalizeEmail(input.email);if (input.phone !== undefined) data.phone = blankToNull(input.phone);if (input.title !== undefined) data.title = blankToNull(input.title);if (input.linkedinUrl !== undefined) {@@ -377,23 +385,32 @@ export class ContactsService {}try {- const updated = await this.db.contact.update({- where: { id },- data,- select: { id: true, firstName: true, lastName: true },- });+ return await this.db.$transaction(async (tx) => {+ const updated = await tx.contact.update({+ where: { id },+ data,+ select: { id: true, firstName: true, lastName: true },+ });- if (typeof data.email === "string") await this.allowAgain(data.email);+ if (typeof data.email === "string") {+ await this.allowAgain(tx, data.email);+ }- return updated;+ return updated;+ });} catch (error) {throw this.translate(error, id);}}- private async allowAgain(email: string | null): Promise<void> {+ private async allowAgain(+ tx: Prisma.TransactionClient,+ email: string | null,+ ): Promise<void> {if (!email) return;- await this.db.suppressedContact.deleteMany({ where: { email } });+ await tx.suppressedContact.deleteMany({+ where: { email: { equals: email, mode: "insensitive" } },+ });}private async relationship(contactId: string, companyId: string | null) {diff --git a/apps/api/src/crm/activity-stamp.service.ts b/apps/api/src/crm/activity-stamp.service.tsindex 83f0ee1f..0c48b06c 100644--- a/apps/api/src/crm/activity-stamp.service.ts+++ b/apps/api/src/crm/activity-stamp.service.ts@@ -1,5 +1,5 @@import type { Db } from "@crm/db";-import { Injectable } from "@nestjs/common";+import { Injectable, Logger } from "@nestjs/common";import { InjectDatabase } from "../database/database.constants";export type ActivityTarget = {@@ -10,6 +10,8 @@ export type ActivityTarget = {@Injectable()export class ActivityStampService {+ private readonly logger = new Logger(ActivityStampService.name);+constructor(@InjectDatabase() private readonly db: Db) {}async touch(target: ActivityTarget, at: Date): Promise<void> {@@ -74,6 +76,21 @@ export class ActivityStampService {}}+ async recomputeAllAfterDelete(deleted: ActivityTarget): Promise<void> {+ try {+ await this.recomputeAll();+ } catch (error) {+ this.logger.error(+ {+ message:+ "A record was deleted but its activity stamps were not recomputed",+ ...deleted,+ },+ error instanceof Error ? error.stack : String(error),+ );+ }+ }+async recomputeAll(): Promise<void> {await this.db.$transaction([this.db.$executeRaw`diff --git a/apps/api/src/crm/values.ts b/apps/api/src/crm/values.tsindex 94393bd2..c49013ee 100644--- a/apps/api/src/crm/values.ts+++ b/apps/api/src/crm/values.ts@@ -12,3 +12,7 @@ export function blankToNull(value: string): string | null {const trimmed = value.trim();return trimmed === "" ? null : trimmed;}++export function normalizeEmail(value: string): string | null {+ return blankToNull(value)?.toLowerCase() ?? null;+}diff --git a/apps/api/src/deals/deals.service.ts b/apps/api/src/deals/deals.service.tsindex 53acaf67..ef7e7805 100644--- a/apps/api/src/deals/deals.service.ts+++ b/apps/api/src/deals/deals.service.ts@@ -254,8 +254,13 @@ export class DealsService {throw new NotFoundException(`No deal with id ${id}.`);}- await this.db.deal.delete({ where: { id } });- await this.stamp.recomputeAll();+ try {+ await this.db.deal.delete({ where: { id } });+ } catch (error) {+ throw this.translate(error, id);+ }++ await this.stamp.recomputeAllAfterDelete({ dealId: id });this.logger.log({ message: "Deal deleted", dealId: id, name: deal.name });diff --git a/apps/api/src/google/google-match.service.ts b/apps/api/src/google/google-match.service.tsindex fe8d5e80..e65c7cfd 100644--- a/apps/api/src/google/google-match.service.ts+++ b/apps/api/src/google/google-match.service.ts@@ -80,7 +80,7 @@ export class GoogleMatchService {const rows = await this.db.suppressedContact.findMany({select: { email: true },});- return new Set(rows.map((row) => row.email));+ return new Set(rows.map((row) => row.email.toLowerCase()));}async resolve(diff --git a/apps/api/test/record-delete.spec.ts b/apps/api/test/record-delete.spec.tsindex 7941c22b..0db90526 100644--- a/apps/api/test/record-delete.spec.ts+++ b/apps/api/test/record-delete.spec.ts@@ -191,6 +191,41 @@ describe("deleting a contact", () => {await db.contact.delete({ where: { id: readded.id } });await db.suppressedContact.deleteMany({ where: { email } });});++ it("suppresses an address a rep typed in caps as the sync will see it", async () => {+ const typed = `Mixed.Case@${domain.toUpperCase()}`;+ const asSynced = typed.toLowerCase();++ const created = await contacts.create({ firstName: "Mixed", email: typed });++ expect(+ await db.contact.findUnique({+ where: { id: created.id },+ select: { email: true },+ }),+ ).toEqual({ email: asSynced });++ await contacts.delete(created.id);++ expect(+ await db.suppressedContact.findUnique({ where: { email: asSynced } }),+ ).not.toBeNull();++ const result = await match.resolve(+ {+ participants: [{ email: asSynced, name: "Mixed Case" }],+ allowCreate: true,+ source: RecordSource.EMAIL,+ ownerId: userId,+ },+ await matchContext(),+ );++ expect(result.external).toEqual([]);+ expect(+ await db.contact.findFirst({ where: { email: asSynced } }),+ ).toBeNull();+ });});describe("deleting a company", () => {diff --git a/apps/app/lib/trpc/cache.ts b/apps/app/lib/trpc/cache.tsindex b0302344..2c6b39fc 100644--- a/apps/app/lib/trpc/cache.ts+++ b/apps/app/lib/trpc/cache.ts@@ -103,13 +103,12 @@ export function useCrmCache(): CrmCache {),removed: ({ kind, id }) => {- const gone = JSON.stringify(- {- company: trpc.companies.byId,- contact: trpc.contacts.byId,- deal: trpc.deals.byId,- }[kind].queryKey({ id }),- );+ const goneKey = {+ company: trpc.companies.byId,+ contact: trpc.contacts.byId,+ deal: trpc.deals.byId,+ }[kind].queryKey({ id });+ const gone = JSON.stringify(goneKey);for (const record of [trpc.companies.byId,@@ -122,6 +121,12 @@ export function useCrmCache(): CrmCache {});}+ void queryClient.invalidateQueries({+ queryKey: goneKey,+ exact: true,+ refetchType: "none",+ });+return run([...listKeys(), ...activityKeys(), trpc.dashboard.summary.queryKey()],[],diff --git a/apps/app/test/onboarding-gate.spec.ts b/apps/app/test/onboarding-gate.spec.tsindex a242041d..993ab1ad 100644--- a/apps/app/test/onboarding-gate.spec.ts+++ b/apps/app/test/onboarding-gate.spec.ts@@ -86,6 +86,7 @@ describe("proxy", () => {});it("ignores a neighbour's cookie from the parent domain", async () => {+ expect(AUTH_COOKIE_PREFIX).not.toBe("better-auth");answerWith(workspace({ onboarded: true, canRename: true }));expect(diff --git a/docs/api.md b/docs/api.mdindex 437554b5..d9115407 100644--- a/docs/api.md+++ b/docs/api.md@@ -352,12 +352,25 @@ once.- **It suppresses the address, not the person.** A contact with no email cannotbe recreated by the sync in the first place — the sync only knows people byaddress — so there is nothing to write down.+- **The key is the address as the sync will see it: lower case.**+ `parseAddress` lower-cases everything Google hands us, so a rep who typed+ `[email protected]` into the quick-add form and then deleted the+ contact left a suppression nothing would ever match, and the next thread put+ them straight back — the exact loop the row exists to break. `normalizeEmail`+ (`apps/api/src/crm/values.ts`) is the one canonicaliser, applied where a rep's+ typing enters the system: `contacts.create`, `contacts.update` and the+ suppression written by `contacts.delete`. The conflict check on create and+ `allowAgain` both match case-insensitively so a row written before this rule+ still answers.- **The colleagues are untouched.** Only the deleted address is filtered, so athread with three other people at that company still files against them. Athread where the deleted person was the *only* outsider files against nobody,which is the correct reading of "we do not track this person".- **A rep can always add them back, and doing so lifts the suppression.**- `allowAgain` runs on `contacts.create` and on an `update` that sets the email.+ `allowAgain` runs on `contacts.create` and on an `update` that sets the email,+ **inside the same transaction as the write**. Outside it, a database blip+ between the two left a contact the sync still ignores, and the retry hit the+ "already uses that email" conflict — a record a rep can see and cannot fix.The rule is *not added back automatically* — somebody typing the address in isnot the inbox making the decision for them.- **Deleting a company does not suppress its domain.** Its people survive the@@ -372,11 +385,20 @@ survives a redeploy — which means a delete has to clear them itself. Leavingthem behind queues research about a person who no longer exists, and thedispatcher spends a session finding that out.-Every delete then calls `ActivityStampService.recomputeAll()`. Deleting a record-deletes its activities, and `lastActivityAt` on whatever else those activities-touched is a cached maximum that nothing else recomputes — a company whose only-recent activity was on a deleted deal would sort as though the work were still-fresh, forever.+Every delete then calls `ActivityStampService.recomputeAllAfterDelete()`.+Deleting a record deletes its activities, and `lastActivityAt` on whatever else+those activities touched is a cached maximum that nothing else recomputes — a+company whose only recent activity was on a deleted deal would sort as though+the work were still fresh, forever.++**It runs after the delete has committed, so it logs rather than throws.** The+row is already gone by the time the stamps are rebuilt; letting that failure out+reports a completed destructive action as a failure, the browser never+invalidates its caches, and the rep's retry answers `No contact with id …`. A+stale sort order is a smaller wrong than that, and the next delete or+reconnection recomputes it. The delete itself is still translated: a record+removed between the pre-check and the delete is the documented 404, not a P2025+escaping as a 500.## Freshness: invalidate the query, don't disable the cache@@ -395,13 +417,16 @@ job: a mutation invalidates the query keys it affected, and the list refetches.key.** Everything a deletion can reach is refreshed together — the lists, thetimeline, the dashboard, and the other records that named this one, since acolleague list and a deal's attendees both go stale the moment a contact goes.- The deleted record's *own* `byId` entry is deliberately left alone: its query is- still mounted for the moment it takes the sheet to animate shut, so- invalidating it asks the API for a row that no longer exists and the sheet- reads the 404 as "this record could not be loaded" on its way out. Nothing- observes that entry once the sheet is gone, so it expires on its own. One wide- fan-out is right here because deleting is rare and touches more than any edit- does.+ The deleted record's *own* `byId` entry is invalidated with+ `refetchType: "none"`, which is the one place that option is right: its query+ is still mounted for the moment it takes the sheet to animate shut, so a+ refetch asks the API for a row that no longer exists and the sheet reads the+ 404 as "this record could not be loaded" on its way out. Marking it stale+ without refetching keeps the closing sheet quiet *and* stops the entry being+ served from cache — `staleTime` is 30 seconds, so leaving it untouched meant a+ rep who reopened the record from a stale link or the back button read half a+ minute of a record that no longer exists. One wide fan-out is right here+ because deleting is rare and touches more than any edit does.- **Pass `{ settle: "record" }`** when the caller is an inline editor. Thedefault waits for every affected view to refetch, which is right when the pointof the action *is* the view changing (a card moving between board columns);