Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
feat(api): implement delete functionality for companies, contacts, and deals
Lewis Carhart4457f7348a22
diff --git a/apps/api/src/companies/companies.router.ts b/apps/api/src/companies/companies.router.tsindex 6acd2d4d..d7d29a9d 100644--- a/apps/api/src/companies/companies.router.ts+++ b/apps/api/src/companies/companies.router.ts@@ -52,6 +52,11 @@ export class CompaniesRouter {return this.companies.update(input.id, input.data);}+ @Mutation({ input: companyIdInput })+ async delete(@Input("id") id: string) {+ return this.companies.delete(id);+ }+@Mutation({ input: companyIdInput })async enrich(@Input("id") id: string) {return this.companies.enrich(id);diff --git a/apps/api/src/companies/companies.service.ts b/apps/api/src/companies/companies.service.tsindex 7705a2a3..222c4962 100644--- a/apps/api/src/companies/companies.service.ts+++ b/apps/api/src/companies/companies.service.ts@@ -14,6 +14,7 @@ import {} from "@nestjs/common";import { AgentQueueService } from "../agent/agent-queue.service";import { AgentTriggerService } from "../agent/agent-trigger.service";+import { ActivityStampService } from "../crm/activity-stamp.service";import { blankToNull, toCents } from "../crm/values";import { InjectDatabase } from "../database/database.constants";import { OPEN_DEAL_STAGES } from "../deals/deal-stage";@@ -89,6 +90,7 @@ export class CompaniesService {private readonly agent: AgentTriggerService,private readonly queue: AgentQueueService,private readonly favicon: FaviconService,+ private readonly stamp: ActivityStampService,) {}async list(input: CompanyListInput): Promise<ListResult<CompanyRow>> {@@ -365,6 +367,32 @@ export class CompaniesService {}}+ async delete(id: string): Promise<{ id: string; name: string }> {+ const company = await this.db.company.findUnique({+ where: { id },+ select: { id: true, name: true },+ });++ if (!company) {+ 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 } }),+ ]);++ await this.stamp.recomputeAll();++ this.logger.log({+ message: "Company deleted",+ companyId: id,+ name: company.name,+ });++ return company;+ }+async enrich(id: string): Promise<{ id: string; queued: boolean }> {const company = await this.db.company.findUnique({where: { id },diff --git a/apps/api/src/contacts/contacts.router.ts b/apps/api/src/contacts/contacts.router.tsindex d47e1a02..eee33954 100644--- a/apps/api/src/contacts/contacts.router.ts+++ b/apps/api/src/contacts/contacts.router.ts@@ -46,6 +46,11 @@ export class ContactsRouter {return this.contacts.update(input.id, input.data);}+ @Mutation({ input: contactIdInput })+ async delete(@Input("id") id: string) {+ return this.contacts.delete(id);+ }+@Mutation({ input: contactIdInput })async enrich(@Input("id") id: string) {return this.contacts.enrich(id);diff --git a/apps/api/src/contacts/contacts.service.ts b/apps/api/src/contacts/contacts.service.tsindex 5fc7e8e3..7c3768e3 100644--- a/apps/api/src/contacts/contacts.service.ts+++ b/apps/api/src/contacts/contacts.service.ts@@ -16,6 +16,7 @@ import {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 { InjectDatabase } from "../database/database.constants";import {@@ -108,6 +109,7 @@ export class ContactsService {private readonly companies: CompanyDirectoryService,private readonly agent: AgentTriggerService,private readonly queue: AgentQueueService,+ private readonly stamp: ActivityStampService,) {}async list(input: ContactListInput): Promise<ListResult<ContactRow>> {@@ -290,6 +292,8 @@ export class ContactsService {select: { id: true, firstName: true, lastName: true },});+ await this.allowAgain(email);+this.logger.log({ message: "Contact created", contactId: contact.id });await this.agent.contactCreated(@@ -300,6 +304,49 @@ export class ContactsService {return contact;}+ async delete(id: string): Promise<{ id: string; name: string }> {+ const contact = await this.db.contact.findUnique({+ where: { id },+ select: { id: true, firstName: true, lastName: true, email: true },+ });++ if (!contact) {+ throw new NotFoundException(`No contact with id ${id}.`);+ }++ const name = [contact.firstName, contact.lastName]+ .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 } }),+ ]);++ await this.stamp.recomputeAll();++ this.logger.log({+ message: "Contact deleted",+ contactId: id,+ suppressed: contact.email !== null,+ });++ return { id, name };+ }+async update(id: string, input: ContactUpdateInput) {const data: Prisma.ContactUpdateInput = {};@@ -330,16 +377,25 @@ export class ContactsService {}try {- return await this.db.contact.update({+ const updated = await this.db.contact.update({where: { id },data,select: { id: true, firstName: true, lastName: true },});++ if (typeof data.email === "string") await this.allowAgain(data.email);++ return updated;} catch (error) {throw this.translate(error, id);}}+ private async allowAgain(email: string | null): Promise<void> {+ if (!email) return;+ await this.db.suppressedContact.deleteMany({ where: { email } });+ }+private async relationship(contactId: string, companyId: string | null) {const now = new Date();diff --git a/apps/api/src/deals/deals.router.ts b/apps/api/src/deals/deals.router.tsindex 6d916548..148e7ac1 100644--- a/apps/api/src/deals/deals.router.ts+++ b/apps/api/src/deals/deals.router.ts@@ -44,6 +44,11 @@ export class DealsRouter {return this.deals.update(input.id, input.data);}+ @Mutation({ input: dealIdInput })+ async delete(@Input("id") id: string) {+ return this.deals.delete(id);+ }+@Mutation({ input: setStageInput })async setStage(@Ctx() ctx: AuthedTrpcContext,diff --git a/apps/api/src/deals/deals.service.ts b/apps/api/src/deals/deals.service.tsindex 6ac88467..53acaf67 100644--- a/apps/api/src/deals/deals.service.ts+++ b/apps/api/src/deals/deals.service.ts@@ -244,6 +244,24 @@ export class DealsService {}}+ async delete(id: string): Promise<{ id: string; name: string }> {+ const deal = await this.db.deal.findUnique({+ where: { id },+ select: { id: true, name: true },+ });++ if (!deal) {+ throw new NotFoundException(`No deal with id ${id}.`);+ }++ await this.db.deal.delete({ where: { id } });+ await this.stamp.recomputeAll();++ this.logger.log({ message: "Deal deleted", dealId: id, name: deal.name });++ return deal;+ }+async setStage(input: SetStageInput, actingUserId: string) {const deal = await this.db.deal.findUnique({where: { id: input.id },diff --git a/apps/api/src/generated/server.ts b/apps/api/src/generated/server.tsindex c9b01f60..6719a1f0 100644--- a/apps/api/src/generated/server.ts+++ b/apps/api/src/generated/server.ts@@ -70,6 +70,9 @@ const appRouter = t.router({update: publicProcedure.input(companyUpdateArgs).mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CompaniesRouter["update"]>>),+ delete: publicProcedure+ .input(companyIdInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CompaniesRouter["delete"]>>),enrich: publicProcedure.input(companyIdInput).mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CompaniesRouter["enrich"]>>),@@ -93,6 +96,9 @@ const appRouter = t.router({update: publicProcedure.input(contactUpdateArgs).mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["update"]>>),+ delete: publicProcedure+ .input(contactIdInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["delete"]>>),enrich: publicProcedure.input(contactIdInput).mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["enrich"]>>),@@ -132,6 +138,9 @@ const appRouter = t.router({update: publicProcedure.input(dealUpdateArgs).mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["update"]>>),+ delete: publicProcedure+ .input(dealIdInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["delete"]>>),setStage: publicProcedure.input(setStageInput).mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["setStage"]>>)diff --git a/apps/api/src/google/calendar-sync.service.ts b/apps/api/src/google/calendar-sync.service.tsindex 965c1bb4..2e120e9b 100644--- a/apps/api/src/google/calendar-sync.service.ts+++ b/apps/api/src/google/calendar-sync.service.ts@@ -71,15 +71,17 @@ export class CalendarSyncService {await this.state.markRunning(row.id);- const [internal, suppressedDomains] = await Promise.all([+ const [internal, suppressedDomains, suppressedEmails] = await Promise.all([this.match.internalIdentity(),this.match.suppressedDomains(),+ this.match.suppressedEmails(),]);const context = {ourAddresses: internal.addresses,ourDomains: internal.domains,suppressedDomains,+ suppressedEmails,};let pageToken: string | undefined;diff --git a/apps/api/src/google/gmail-sync.service.ts b/apps/api/src/google/gmail-sync.service.tsindex b27d971e..eccfcc92 100644--- a/apps/api/src/google/gmail-sync.service.ts+++ b/apps/api/src/google/gmail-sync.service.ts@@ -223,15 +223,17 @@ export class GmailSyncService {if (batch.length === 0) return { written: 0, remaining };- const [internal, suppressedDomains] = await Promise.all([+ const [internal, suppressedDomains, suppressedEmails] = await Promise.all([this.match.internalIdentity(),this.match.suppressedDomains(),+ this.match.suppressedEmails(),]);const context = {ourAddresses: internal.addresses,ourDomains: internal.domains,suppressedDomains,+ suppressedEmails,};let written = 0;diff --git a/apps/api/src/google/google-match.service.ts b/apps/api/src/google/google-match.service.tsindex af5ef48b..fe8d5e80 100644--- a/apps/api/src/google/google-match.service.ts+++ b/apps/api/src/google/google-match.service.ts@@ -28,6 +28,7 @@ export type MatchContext = {ourAddresses: ReadonlySet<string>;ourDomains: ReadonlySet<string>;suppressedDomains: ReadonlySet<string>;+ suppressedEmails: ReadonlySet<string>;};export type MatchRequest = {@@ -75,6 +76,13 @@ export class GoogleMatchService {return new Set(rows.map((row) => row.domain));}+ async suppressedEmails(): Promise<Set<string>> {+ const rows = await this.db.suppressedContact.findMany({+ select: { email: true },+ });+ return new Set(rows.map((row) => row.email));+ }+async resolve(request: MatchRequest,context: MatchContext,@@ -83,6 +91,7 @@ export class GoogleMatchService {ourDomains: context.ourDomains,ourAddresses: context.ourAddresses,suppressedDomains: context.suppressedDomains,+ suppressedEmails: context.suppressedEmails,});if (external.length === 0) {diff --git a/apps/api/src/google/participants.ts b/apps/api/src/google/participants.tsindex ce3c506f..a87497ed 100644--- a/apps/api/src/google/participants.ts+++ b/apps/api/src/google/participants.ts@@ -123,6 +123,7 @@ export type ExternalFilterOptions = {ourDomains: ReadonlySet<string>;ourAddresses: ReadonlySet<string>;suppressedDomains: ReadonlySet<string>;+ suppressedEmails: ReadonlySet<string>;};export function externalParticipants(@@ -131,6 +132,7 @@ export function externalParticipants(): Participant[] {return participants.filter((participant) => {if (options.ourAddresses.has(participant.email)) return false;+ if (options.suppressedEmails.has(participant.email)) return false;const domain = workDomain(participant.email);if (!domain) return false;diff --git a/apps/api/test/google-participants.spec.ts b/apps/api/test/google-participants.spec.tsindex ab5ee316..fef0ca08 100644--- a/apps/api/test/google-participants.spec.ts+++ b/apps/api/test/google-participants.spec.ts@@ -96,6 +96,7 @@ describe("externalParticipants", () => {ourDomains: new Set(["trycomp.ai"]),ourAddresses: new Set(["[email protected]"]),suppressedDomains: new Set(["greenhouse.io"]),+ suppressedEmails: new Set(["[email protected]"]),};it("keeps only the other side of the conversation", () => {@@ -130,6 +131,24 @@ describe("externalParticipants", () => {externalParticipants([person("[email protected]")], options),).toEqual([]);});++ it("never brings back a contact a rep deleted", () => {+ const result = externalParticipants(+ [person("[email protected]", "Deleted Person"), person("[email protected]")],+ options,+ );++ expect(result).toEqual([person("[email protected]")]);+ });++ it("leaves nothing to file when the deleted contact is the only outsider", () => {+ expect(+ externalParticipants(+ [person("[email protected]"), person("[email protected]")],+ options,+ ),+ ).toEqual([]);+ });});describe("dominantDomain", () => {diff --git a/apps/api/test/record-delete.spec.ts b/apps/api/test/record-delete.spec.tsnew file mode 100644index 00000000..554279da--- /dev/null+++ b/apps/api/test/record-delete.spec.ts@@ -0,0 +1,190 @@+import { afterAll, beforeAll, describe, expect, it } from "bun:test";+import { db, RecordSource } from "@crm/db";+import { AgentQueueService } from "../src/agent/agent-queue.service";+import { AgentTriggerService } from "../src/agent/agent-trigger.service";+import { CompaniesService } from "../src/companies/companies.service";+import { CompanyDirectoryService } from "../src/companies/company-directory.service";+import { FaviconService } from "../src/companies/favicon.service";+import { ContactsService } from "../src/contacts/contacts.service";+import { ActivityStampService } from "../src/crm/activity-stamp.service";+import { EnrichmentLogService } from "../src/crm/enrichment-log.service";+import { GoogleMatchService } from "../src/google/google-match.service";++const suffix = process.env.TEST_RUN_ID ?? "record-delete-spec";+const domain = `delete-${suffix}.test`;+const doomedDomain = `doomed-${suffix}.test`;+const email = `gone@${domain}`;+const colleague = `stays@${domain}`;+const userId = `user-${suffix}`;++const stamp = new ActivityStampService(db);+const agent = new AgentTriggerService(db);+const directory = new CompanyDirectoryService(db, agent);+const log = new EnrichmentLogService(db, stamp);+const queue = new AgentQueueService(db);++const contacts = new ContactsService(db, directory, agent, queue, stamp);+const companies = new CompaniesService(+ db,+ agent,+ queue,+ { backfill: async () => undefined } as unknown as FaviconService,+ stamp,+);+const match = new GoogleMatchService(db, directory, agent, log);++async function matchContext() {+ const internal = await match.internalIdentity();+ return {+ ourAddresses: internal.addresses,+ ourDomains: internal.domains,+ suppressedDomains: await match.suppressedDomains(),+ suppressedEmails: await match.suppressedEmails(),+ };+}++async function clean() {+ const domains = [domain, doomedDomain];+ await db.contact.deleteMany({+ where: { OR: domains.map((host) => ({ email: { endsWith: `@${host}` } })) },+ });+ await db.company.deleteMany({ where: { domain: { in: domains } } });+ await db.suppressedContact.deleteMany({+ where: { OR: domains.map((host) => ({ email: { endsWith: `@${host}` } })) },+ });+ await db.user.deleteMany({ where: { id: userId } });+}++beforeAll(async () => {+ await clean();+ await db.user.create({+ data: { id: userId, name: "Test Rep", email: `${userId}@example.test` },+ });+});++afterAll(clean);++describe("deleting a contact", () => {+ let contactId: string;++ it("takes the record, its queued research and its transcript with it", async () => {+ const created = await contacts.create({+ firstName: "Gone",+ lastName: "Person",+ email,+ ownerId: userId,+ });+ contactId = created.id;++ await db.agentEvent.create({+ data: {+ id: `evt-${suffix}`,+ sessionId: `ses-${suffix}`,+ contactId,+ type: "session.started",+ data: {},+ emittedAt: new Date(),+ },+ });++ expect(await contacts.delete(contactId)).toEqual({+ id: contactId,+ name: "Gone Person",+ });++ expect(+ await db.contact.findUnique({ where: { id: contactId } }),+ ).toBeNull();+ expect(await db.agentTask.count({ where: { contactId } })).toBe(0);+ expect(await db.agentEvent.count({ where: { contactId } })).toBe(0);+ });++ it("remembers the address so the sync cannot bring them back", async () => {+ const suppressed = await db.suppressedContact.findUnique({+ where: { email },+ });+ expect(suppressed).not.toBeNull();++ const result = await match.resolve(+ {+ participants: [{ email, name: "Gone Person" }],+ allowCreate: true,+ source: RecordSource.EMAIL,+ ownerId: userId,+ },+ await matchContext(),+ );++ expect(result.external).toEqual([]);+ expect(result.contactId).toBeNull();+ expect(await db.contact.findFirst({ where: { email } })).toBeNull();+ });++ it("still files the colleagues who were not deleted", async () => {+ const result = await match.resolve(+ {+ participants: [+ { email, name: "Gone Person" },+ { email: colleague, name: "Stays Here" },+ ],+ allowCreate: true,+ source: RecordSource.EMAIL,+ ownerId: userId,+ },+ await matchContext(),+ );++ expect(result.external.map((person) => person.email)).toEqual([colleague]);++ const created = await db.contact.findFirst({ where: { email: colleague } });+ expect(created?.id).toBe(result.contactId ?? undefined);+ });++ it("lets a rep add them back by hand, which lifts the suppression", async () => {+ const readded = await contacts.create({ firstName: "Gone", email });++ expect(+ await db.suppressedContact.findUnique({ where: { email } }),+ ).toBeNull();++ await db.contact.delete({ where: { id: readded.id } });+ await db.suppressedContact.deleteMany({ where: { email } });+ });+});++describe("deleting a company", () => {+ it("takes its deals and leaves its people without a company", async () => {+ const company = await companies.create({+ name: "Doomed",+ domain: doomedDomain,+ });+ const contact = await contacts.create({+ firstName: "Left",+ lastName: "Behind",+ email: `left@${doomedDomain}`,+ companyId: company.id,+ });+ const deal = await db.deal.create({+ data: { name: "Doomed deal", companyId: company.id, ownerId: userId },+ select: { id: true },+ });++ expect(await companies.delete(company.id)).toEqual({+ id: company.id,+ name: "Doomed",+ });++ expect(await db.deal.findUnique({ where: { id: deal.id } })).toBeNull();+ expect(await db.agentTask.count({ where: { companyId: company.id } })).toBe(+ 0,+ );++ const survivor = await db.contact.findUnique({+ where: { id: contact.id },+ select: { companyId: true },+ });+ expect(survivor?.companyId).toBeNull();++ await db.contact.delete({ where: { id: contact.id } });+ });+});diff --git a/apps/api/test/workspace.spec.ts b/apps/api/test/workspace.spec.tsindex 85a96839..7e419127 100644--- a/apps/api/test/workspace.spec.ts+++ b/apps/api/test/workspace.spec.ts@@ -67,6 +67,7 @@ describe("internal addresses never become leads", () => {ourDomains: new Set(["acme.com"]),ourAddresses: new Set<string>(),suppressedDomains: new Set<string>(),+ suppressedEmails: new Set<string>(),};it("drops colleagues even when they are not users", () => {diff --git a/apps/app/components/crm/record-sheet/company-sheet.tsx b/apps/app/components/crm/record-sheet/company-sheet.tsxindex 6125afdc..12f3a2dc 100644--- a/apps/app/components/crm/record-sheet/company-sheet.tsx+++ b/apps/app/components/crm/record-sheet/company-sheet.tsx@@ -58,6 +58,7 @@ import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";import { QuickAddContact, QuickAddDeal } from "./quick-add";+import { RecordActions } from "./record-actions";import {DealAmount,DomainLink,@@ -79,6 +80,23 @@ function pendingFields(company: Company): string[] {return missing;}+function companyConsequence(company: Company): string {+ const deals = company.deals.length;+ const contacts = company.contacts.length;++ const gone =+ deals > 0+ ? `${deals === 1 ? "Its one deal" : `All ${deals} of its deals`} and everything filed against the account go too.`+ : "Everything filed against the account goes too.";++ const kept =+ contacts > 0+ ? ` ${contacts === 1 ? "The one person" : `The ${contacts} people`} who work there stay in the CRM, without a company.`+ : "";++ return gone + kept;+}+const CONTACT_COLUMNS = [{ srLabel: "Primary", width: "w-10", className: "pl-5" },{ header: "Name", width: "w-[28%]" },@@ -265,10 +283,17 @@ export function CompanySheet({ companyId }: { companyId: string }) {}actions={company ? (- <EnrichmentActions- companyId={company.id}- hasDomain={company.domain !== null}- />+ <>+ <EnrichmentActions+ companyId={company.id}+ hasDomain={company.domain !== null}+ />+ <RecordActions+ record={{ kind: "company", id: company.id }}+ name={company.name}+ consequence={companyConsequence(company)}+ />+ </>) : null}stats={diff --git a/apps/app/components/crm/record-sheet/contact-sheet.tsx b/apps/app/components/crm/record-sheet/contact-sheet.tsxindex ce319f3c..4e14e1cd 100644--- a/apps/app/components/crm/record-sheet/contact-sheet.tsx+++ b/apps/app/components/crm/record-sheet/contact-sheet.tsx@@ -58,6 +58,7 @@ import {import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";+import { RecordActions } from "./record-actions";import { DealAmount, MetaLine, RecordSheetFrame } from "./record-parts";import { useOpenRecord, useRecordSheetView } from "./record-stack";@@ -197,6 +198,11 @@ export function ContactSheet({ contactId }: { contactId: string }) {<span className="hidden sm:inline">Make primary</span></Button>) : null}+ <RecordActions+ record={{ kind: "contact", id: contact.id }}+ name={contactName(contact)}+ consequence={`Their notes, agent conversations and everything the agent found go too; emails and meetings stay filed against the company.${contact.email ? ` The sync will not bring ${contact.email} back — only adding them yourself will.` : ""}`}+ /></>) : null}diff --git a/apps/app/components/crm/record-sheet/deal-sheet.tsx b/apps/app/components/crm/record-sheet/deal-sheet.tsxindex fe81a614..09b5d646 100644--- a/apps/app/components/crm/record-sheet/deal-sheet.tsx+++ b/apps/app/components/crm/record-sheet/deal-sheet.tsx@@ -40,6 +40,7 @@ import {import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";+import { RecordActions } from "./record-actions";import { RecordSheetFrame } from "./record-parts";import { useOpenRecord, useRecordSheetView } from "./record-stack";@@ -122,11 +123,18 @@ export function DealSheet({ dealId }: { dealId: string }) {}actions={deal ? (- <DealStageMenu- dealId={deal.id}- stage={deal.stage}- variant="control"- />+ <>+ <DealStageMenu+ dealId={deal.id}+ stage={deal.stage}+ variant="control"+ />+ <RecordActions+ record={{ kind: "deal", id: deal.id }}+ name={deal.name}+ consequence={`Its stage history, notes and agent conversations go too. ${deal.company.name} and the ${deal.contacts.length === 1 ? "person" : "people"} on it stay in the CRM.`}+ />+ </>) : null}stats={diff --git a/apps/app/components/crm/record-sheet/record-actions.tsx b/apps/app/components/crm/record-sheet/record-actions.tsxnew file mode 100644index 00000000..1e13c630--- /dev/null+++ b/apps/app/components/crm/record-sheet/record-actions.tsx@@ -0,0 +1,118 @@+"use client";++import OverflowMenuVertical from "@carbon/icons-react/es/OverflowMenuVertical";+import TrashCan from "@carbon/icons-react/es/TrashCan";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@crm/ui/components/alert-dialog";+import { Button } from "@crm/ui/components/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@crm/ui/components/dropdown-menu";+import { Icon } from "@crm/ui/components/icon";+import { useMutation } from "@tanstack/react-query";+import { useState } from "react";+import { toast } from "sonner";+import { useCrmCache } from "@/lib/trpc/cache";+import { useTRPC } from "@/lib/trpc/client";+import {+ type RecordKind,+ type RecordRef,+ useRecordStack,+} from "./record-stack";++const NOUN: Record<RecordKind, string> = {+ company: "company",+ contact: "contact",+ deal: "deal",+};++function useDeleteRecord(record: RecordRef) {+ const trpc = useTRPC();+ const cache = useCrmCache();+ const { close } = useRecordStack();++ const handlers = {+ onSuccess: (deleted: { name: string }) => {+ toast.success(+ `${deleted.name || `The ${NOUN[record.kind]}`} was deleted.`,+ );+ void cache.removed(record);+ close();+ },+ onError: (error: { message: string }) => toast.error(error.message),+ };++ const options =+ record.kind === "contact"+ ? trpc.contacts.delete.mutationOptions(handlers)+ : record.kind === "company"+ ? trpc.companies.delete.mutationOptions(handlers)+ : trpc.deals.delete.mutationOptions(handlers);++ return useMutation(options);+}++export function RecordActions({+ record,+ name,+ consequence,+}: {+ record: RecordRef;+ name: string;+ consequence: string;+}) {+ const [confirming, setConfirming] = useState(false);+ const remove = useDeleteRecord(record);++ return (+ <>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="icon-sm" disabled={remove.isPending}>+ <Icon icon={OverflowMenuVertical} />+ <span className="sr-only">More actions</span>+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="min-w-44">+ <DropdownMenuItem+ variant="destructive"+ onSelect={() => setConfirming(true)}+ >+ <Icon icon={TrashCan} />+ Delete {NOUN[record.kind]}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>++ <AlertDialog open={confirming} onOpenChange={setConfirming}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete {name}?</AlertDialogTitle>+ <AlertDialogDescription>{consequence}</AlertDialogDescription>+ </AlertDialogHeader>++ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() => remove.mutate({ id: record.id })}+ >+ Delete+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ );+}diff --git a/apps/app/lib/trpc/cache.ts b/apps/app/lib/trpc/cache.tsindex b2a94a7c..b0302344 100644--- a/apps/app/lib/trpc/cache.ts+++ b/apps/app/lib/trpc/cache.ts@@ -9,10 +9,13 @@ type Options = {settle?: Settle;};+type RemovedRecord = { kind: "company" | "contact" | "deal"; id: string };+export type CrmCache = {company(id?: string, options?: Options): Promise<void>;contact(id?: string, options?: Options): Promise<void>;deal(id?: string, options?: Options): Promise<void>;+ removed(record: RemovedRecord): Promise<void>;activity(options?: Options): Promise<void>;google(options?: Options): Promise<void>;settings(options?: Options): Promise<void>;@@ -99,6 +102,32 @@ export function useCrmCache(): CrmCache {options,),+ removed: ({ kind, id }) => {+ const gone = JSON.stringify(+ {+ company: trpc.companies.byId,+ contact: trpc.contacts.byId,+ deal: trpc.deals.byId,+ }[kind].queryKey({ id }),+ );++ for (const record of [+ trpc.companies.byId,+ trpc.contacts.byId,+ trpc.deals.byId,+ ]) {+ void queryClient.invalidateQueries({+ queryKey: record.queryKey(),+ predicate: (query) => JSON.stringify(query.queryKey) !== gone,+ });+ }++ return run(+ [...listKeys(), ...activityKeys(), trpc.dashboard.summary.queryKey()],+ [],+ );+ },+activity: (options) =>run(activityKeys(),diff --git a/apps/app/proxy.ts b/apps/app/proxy.tsindex fc3f0006..dddaab83 100644--- a/apps/app/proxy.ts+++ b/apps/app/proxy.ts@@ -1,3 +1,4 @@+import { AUTH_COOKIE_PREFIX } from "@crm/auth/cookies";import { getSessionCookie } from "better-auth/cookies";import { type NextRequest, NextResponse } from "next/server";import {@@ -14,7 +15,9 @@ const UNGATED = [SIGN_IN_PATH, "/grant-access", "/eve"];export async function proxy(request: NextRequest) {const { pathname } = request.nextUrl;- if (getSessionCookie(request) === null) {+ if (+ getSessionCookie(request, { cookiePrefix: AUTH_COOKIE_PREFIX }) === null+ ) {return pathname === SIGN_IN_PATH? NextResponse.next(): NextResponse.redirect(new URL(SIGN_IN_PATH, request.nextUrl));diff --git a/apps/app/test/onboarding-gate.spec.ts b/apps/app/test/onboarding-gate.spec.tsindex f463b79e..a242041d 100644--- a/apps/app/test/onboarding-gate.spec.ts+++ b/apps/app/test/onboarding-gate.spec.ts@@ -1,9 +1,10 @@import { afterEach, describe, expect, it } from "bun:test";+import { AUTH_COOKIE_PREFIX } from "@crm/auth/cookies";import { NextRequest } from "next/server";import { ONBOARDING_COOKIE, readOnboardingGate } from "../lib/onboarding";import { proxy } from "../proxy";-const SESSION_COOKIE = "better-auth.session_token=abc.def";+const SESSION_COOKIE = `${AUTH_COOKIE_PREFIX}.session_token=abc.def`;const realFetch = globalThis.fetch;@@ -84,6 +85,18 @@ describe("proxy", () => {expect(redirectedTo(await proxy(request("/sign-in")))).toBeNull();});+ it("ignores a neighbour's cookie from the parent domain", async () => {+ answerWith(workspace({ onboarded: true, canRename: true }));++ expect(+ redirectedTo(+ await proxy(+ request("/companies", ["better-auth.session_token=someone.else"]),+ ),+ ),+ ).toBe("/sign-in");+ });+it("gates a signed-in rep who has not answered the form", async () => {answerWith(workspace({ onboarded: false, canRename: true }));diff --git a/docs/api.md b/docs/api.mdindex 79d071e5..516aefc9 100644--- a/docs/api.md+++ b/docs/api.md@@ -285,6 +285,53 @@ Everything the app reads or writes goes through `nestjs-trpc` routers underrun the generator. Regenerate locally and commit the result with the routerchange that caused it.+## Deleting a record is a decision the sync has to respect++Each of the three records can be deleted from the three-dot menu in its sheet —+`contacts.delete`, `companies.delete`, `deals.delete`, one confirm dialog each.+There is no soft delete and no archive: a row a rep meant to be gone that is+still in every list, facet and count is worse than either.++**A deleted contact is remembered by address.** Deleting the row is not enough,+because the Gmail and Calendar sync creates contacts from whoever is on a thread+— so the next message from that person put them straight back, with a fresh+`identify` task behind them, and the rep's only recourse was to delete them+again every few days. `ContactsService.delete` writes a `SuppressedContact` row+keyed on the email, and `externalParticipants`+(`apps/api/src/google/participants.ts`) drops that address exactly as it drops a+domain in `SuppressedDomain` — one filter, one place, so the address is+invisible to contact creation, company auto-creation and thread attribution at+once.++- **It suppresses the address, not the person.** A contact with no email cannot+ be recreated by the sync in the first place — the sync only knows people by+ address — so there is nothing to write down.+- **The colleagues are untouched.** Only the deleted address is filtered, so a+ thread with three other people at that company still files against them. A+ thread 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.+ The rule is *not added back automatically* — somebody typing the address in is+ not the inbox making the decision for them.+- **Deleting a company does not suppress its domain.** Its people survive the+ delete with no company, and a domain-wide suppression would silently stop+ filing their email too. Turning off a whole domain stays the explicit control+ on Settings → Connections, where it says what it does.++**What the database does not cascade, the service does.** `AgentTask` and+`AgentEvent` carry a `contactId` and a `companyId` as plain columns with no+foreign key — they outlive the records they name on purpose, so the queue+survives a redeploy — which means a delete has to clear them itself. Leaving+them behind queues research about a person who no longer exists, and the+dispatcher 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.+## Freshness: invalidate the query, don't disable the cacheThere is no HTTP response cache in front of tRPC. Freshness is TanStack Query's@@ -298,6 +345,17 @@ job: a mutation invalidates the query keys it affected, and the list refetches.timeline entry it writes, creating a deal did not refresh the board, and nothingrefreshed the overview, so a rep could close a deal and watch their own numbersnot move. **A new mutation adds a call there, not a new list of keys.**+- **A deletion is `cache.removed(ref)`, and it is the one call that skips a+ key.** Everything a deletion can reach is refreshed together — the lists, the+ timeline, the dashboard, and the other records that named this one, since a+ colleague 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.- **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);diff --git a/docs/environment.md b/docs/environment.mdindex e0e264dd..a89ca8d8 100644--- a/docs/environment.md+++ b/docs/environment.md@@ -122,6 +122,32 @@ Live in `packages/auth/src/workspace.ts`.- **`AUTH_COOKIE_DOMAIN`** only when the API and the app are on differentsubdomains of one parent — then `.example.com`, so one cookie covers both. Onlocalhost the shared cookie already works, because cookies ignore ports.++### The session cookie is named after this app, not after the library++`AUTH_COOKIE_PREFIX` in [`@crm/auth/cookies`](../packages/auth/src/cookies.ts)+is the literal string `crm`, so the session cookie is+`__Secure-crm.session_token` rather than Better Auth's default+`__Secure-better-auth.session_token`.++The default is a hazard for any install whose app shares a parent domain with+something else — `crm.example.com` beside an existing `app.example.com`. A+cookie set with `Domain=.example.com` by the neighbour is sent to *us* too,+under a name identical to ours, and `parseCookies` keeps one value per name. The+failure is silent and reads as a deployment problem rather than a naming one:+sign-in completes, the `session` row is written with a week's expiry, the+browser holds a cookie, and then every reader — the API that minted it and the+app alike — resolves it to `null` and bounces to `/sign-in`. Nothing logs an+error, because nothing has errored.++Two things follow. It is set on the **server config and the proxy's read**+together: `advanced.cookiePrefix` in `auth.ts` names the cookie and+`getSessionCookie(request, { cookiePrefix: AUTH_COOKIE_PREFIX })` in+`apps/app/proxy.ts` looks for it, and a prefix changed in one place only is a+gate that redirects every signed-in request. And **changing it signs everybody+out** — the old cookies stop matching. That is a one-time cost paid on deploy,+not a loop: a stale `better-auth`-prefixed cookie no longer matches, so the+proxy sends the reader to `/sign-in`, which is where they need to be.- **`AGENT_URL`** is the research agent, which is its own deployment. The appreads it to proxy the bridge and the API reads it to poke the dispatcher, bothserver-side only: the browser never learns the agent has an origin of its own.diff --git a/packages/auth/package.json b/packages/auth/package.jsonindex 92f6c0c5..30f82321 100644--- a/packages/auth/package.json+++ b/packages/auth/package.json@@ -6,6 +6,7 @@"exports": {".": "./src/index.ts","./client": "./src/client.ts",+ "./cookies": "./src/cookies.ts","./scopes": "./src/scopes.ts","./workspace": "./src/workspace.ts"},diff --git a/packages/auth/src/auth.ts b/packages/auth/src/auth.tsindex a6ca05f3..edb54197 100644--- a/packages/auth/src/auth.ts+++ b/packages/auth/src/auth.ts@@ -4,6 +4,7 @@ import { type BetterAuthOptions, betterAuth } from "better-auth";import { prismaAdapter } from "better-auth/adapters/prisma";import { APIError } from "better-auth/api";import { organization } from "better-auth/plugins/organization";+import { AUTH_COOKIE_PREFIX } from "./cookies";import { env } from "./env";import { ensureWorkspaceMembership } from "./organization";import { SYNC_SCOPES } from "./scopes";@@ -63,6 +64,8 @@ export const auth = betterAuth({},advanced: {+ cookiePrefix: AUTH_COOKIE_PREFIX,+useSecureCookies: env.isProduction,...(env.cookieDomain && {crossSubDomainCookies: {diff --git a/packages/auth/src/cookies.ts b/packages/auth/src/cookies.tsnew file mode 100644index 00000000..0b00c295--- /dev/null+++ b/packages/auth/src/cookies.ts@@ -0,0 +1 @@+export const AUTH_COOKIE_PREFIX = "crm";diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.tsindex b1ab4761..19f9426e 100644--- a/packages/auth/src/index.ts+++ b/packages/auth/src/index.ts@@ -1,4 +1,5 @@export { type Auth, auth, type Session, type SessionUser } from "./auth";+export { AUTH_COOKIE_PREFIX } from "./cookies";export { isGoogleConfigured } from "./env";export {canChangeRole,diff --git a/packages/db/prisma/migrations/20260803210000_suppressed_contact/migration.sql b/packages/db/prisma/migrations/20260803210000_suppressed_contact/migration.sqlnew file mode 100644index 00000000..e480fb19--- /dev/null+++ b/packages/db/prisma/migrations/20260803210000_suppressed_contact/migration.sql@@ -0,0 +1,8 @@+-- CreateTable+CREATE TABLE "suppressedContact" (+ "email" TEXT NOT NULL,+ "reason" TEXT,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "suppressedContact_pkey" PRIMARY KEY ("email")+);diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prismaindex 551b64e6..ee9a3ed7 100644--- a/packages/db/prisma/schema.prisma+++ b/packages/db/prisma/schema.prisma@@ -603,6 +603,14 @@ model SuppressedDomain {@@map("suppressedDomain")}+model SuppressedContact {+ email String @id+ reason String?+ createdAt DateTime @default(now())++ @@map("suppressedContact")+}+model AppSetting {id String @id