Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
refactor(api): enhance deletion logic and activity stamp handling
Lewis Carhart68f6014eeb68
diff --git a/apps/api/src/companies/companies.service.ts b/apps/api/src/companies/companies.service.tsindex 6a2e62a0..92743993 100644--- a/apps/api/src/companies/companies.service.ts+++ b/apps/api/src/companies/companies.service.ts@@ -14,7 +14,10 @@ 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 {+ ActivityStampService,+ type StampTargets,+} 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";@@ -368,33 +371,37 @@ 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}.`);- }+ let deleted: { targets: StampTargets; name: string };try {- await this.db.$transaction([- this.db.agentTask.deleteMany({ where: { companyId: id } }),- this.db.company.delete({ where: { id } }),- ]);+ deleted = await this.db.$transaction(async (tx) => {+ const targets = await this.stamp.targetsOf(+ { OR: [{ companyId: id }, { deal: { companyId: id } }] },+ tx,+ );++ await tx.agentTask.deleteMany({ where: { companyId: id } });++ const company = await tx.company.delete({+ where: { id },+ select: { name: true },+ });++ return { targets, name: company.name };+ });} catch (error) {throw this.translate(error, id);}- await this.stamp.recomputeAllAfterDelete({ companyId: id });+ await this.stamp.recomputeAfterDelete(deleted.targets, { companyId: id });this.logger.log({message: "Company deleted",companyId: id,- name: company.name,+ name: deleted.name,});- return company;+ return { id, name: deleted.name };}async enrich(id: string): Promise<{ id: string; queued: boolean }> {diff --git a/apps/api/src/contacts/contacts.service.ts b/apps/api/src/contacts/contacts.service.tsindex 24f98e86..9b0d2c8d 100644--- a/apps/api/src/contacts/contacts.service.ts+++ b/apps/api/src/contacts/contacts.service.ts@@ -16,7 +16,10 @@ 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 {+ ActivityStampService,+ type StampTargets,+} from "../crm/activity-stamp.service";import { blankToNull, normalizeEmail, toCents } from "../crm/values";import { InjectDatabase } from "../database/database.constants";import {@@ -307,52 +310,55 @@ export class ContactsService {}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 },- });+ let deleted: {+ targets: StampTargets;+ name: string;+ suppressed: boolean;+ };- if (!contact) {- throw new NotFoundException(`No contact with id ${id}.`);- }+ try {+ deleted = await this.db.$transaction(async (tx) => {+ const targets = await this.stamp.targetsOf({ contactId: id }, tx);- const name = [contact.firstName, contact.lastName]- .filter(Boolean)- .join(" ");+ await tx.agentTask.deleteMany({ where: { contactId: id } });+ await tx.agentEvent.deleteMany({ where: { contactId: id } });- const suppress = normalizeEmail(contact.email ?? "");+ const contact = await tx.contact.delete({+ where: { id },+ select: { firstName: true, lastName: true, email: true },+ });- 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 } }),- ]);+ const name = [contact.firstName, contact.lastName]+ .filter(Boolean)+ .join(" ");+ const suppress = normalizeEmail(contact.email ?? "");++ if (suppress) {+ await tx.suppressedContact.upsert({+ where: { email: suppress },+ create: {+ email: suppress,+ reason: `Deleted from the CRM (${name})`,+ },+ update: {},+ });+ }++ return { targets, name, suppressed: suppress !== null };+ });} catch (error) {throw this.translate(error, id);}- await this.stamp.recomputeAllAfterDelete({ contactId: id });+ await this.stamp.recomputeAfterDelete(deleted.targets, { contactId: id });this.logger.log({message: "Contact deleted",contactId: id,- suppressed: suppress !== null,+ suppressed: deleted.suppressed,});- return { id, name };+ return { id, name: deleted.name };}async update(id: string, input: ContactUpdateInput) {diff --git a/apps/api/src/crm/activity-stamp.service.ts b/apps/api/src/crm/activity-stamp.service.tsindex 0c48b06c..63d83fb1 100644--- a/apps/api/src/crm/activity-stamp.service.ts+++ b/apps/api/src/crm/activity-stamp.service.ts@@ -1,4 +1,4 @@-import type { Db } from "@crm/db";+import { type Db, type Prisma, Prisma as PrismaNamespace } from "@crm/db";import { Injectable, Logger } from "@nestjs/common";import { InjectDatabase } from "../database/database.constants";@@ -8,6 +8,16 @@ export type ActivityTarget = {dealId?: string | null;};+export type StampTargets = {+ companyIds: string[];+ contactIds: string[];+ dealIds: string[];+};++function present(ids: (string | null)[]): string[] {+ return ids.filter((id): id is string => id !== null);+}+@Injectable()export class ActivityStampService {private readonly logger = new Logger(ActivityStampService.name);@@ -76,9 +86,41 @@ export class ActivityStampService {}}- async recomputeAllAfterDelete(deleted: ActivityTarget): Promise<void> {+ async targetsOf(+ where: Prisma.ActivityWhereInput,+ client: Prisma.TransactionClient = this.db,+ ): Promise<StampTargets> {+ const [companies, contacts, deals] = await Promise.all([+ client.activity.groupBy({ by: ["companyId"], where }),+ client.activity.groupBy({ by: ["contactId"], where }),+ client.activity.groupBy({ by: ["dealId"], where }),+ ]);++ return {+ companyIds: present(companies.map((row) => row.companyId)),+ contactIds: present(contacts.map((row) => row.contactId)),+ dealIds: present(deals.map((row) => row.dealId)),+ };+ }++ async recomputeMany(targets: StampTargets): Promise<void> {+ const statements = [+ this.restamp("company", "companyId", targets.companyIds),+ this.restamp("contact", "contactId", targets.contactIds),+ this.restamp("deal", "dealId", targets.dealIds),+ ].filter((statement) => statement !== null);++ if (statements.length === 0) return;++ await this.db.$transaction(statements);+ }++ async recomputeAfterDelete(+ targets: StampTargets,+ deleted: ActivityTarget,+ ): Promise<void> {try {- await this.recomputeAll();+ await this.recomputeMany(targets);} catch (error) {this.logger.error({@@ -91,6 +133,20 @@ export class ActivityStampService {}}+ private restamp(table: string, column: string, ids: string[]) {+ if (ids.length === 0) return null;++ const record = PrismaNamespace.raw(`"${table}"`);+ const key = PrismaNamespace.raw(`"${column}"`);++ return this.db.$executeRaw`+ UPDATE ${record} r+ SET "lastActivityAt" = (+ SELECT MAX(a."createdAt") FROM "activity" a WHERE a.${key} = r.id+ )+ WHERE r.id IN (${PrismaNamespace.join(ids)})`;+ }+async recomputeAll(): Promise<void> {await this.db.$transaction([this.db.$executeRaw`diff --git a/apps/api/src/deals/deals.service.ts b/apps/api/src/deals/deals.service.tsindex ef7e7805..c3af0c6c 100644--- a/apps/api/src/deals/deals.service.ts+++ b/apps/api/src/deals/deals.service.ts@@ -11,7 +11,10 @@ import {Logger,NotFoundException,} from "@nestjs/common";-import { ActivityStampService } from "../crm/activity-stamp.service";+import {+ ActivityStampService,+ type StampTargets,+} from "../crm/activity-stamp.service";import { fromCents, toCents } from "../crm/values";import { InjectDatabase } from "../database/database.constants";import {@@ -245,26 +248,32 @@ 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}.`);- }+ let deleted: { targets: StampTargets; name: string };try {- await this.db.deal.delete({ where: { id } });+ deleted = await this.db.$transaction(async (tx) => {+ const targets = await this.stamp.targetsOf({ dealId: id }, tx);++ const deal = await tx.deal.delete({+ where: { id },+ select: { name: true },+ });++ return { targets, name: deal.name };+ });} catch (error) {throw this.translate(error, id);}- await this.stamp.recomputeAllAfterDelete({ dealId: id });+ await this.stamp.recomputeAfterDelete(deleted.targets, { dealId: id });- this.logger.log({ message: "Deal deleted", dealId: id, name: deal.name });+ this.logger.log({+ message: "Deal deleted",+ dealId: id,+ name: deleted.name,+ });- return deal;+ return { id, name: deleted.name };}async setStage(input: SetStageInput, actingUserId: string) {diff --git a/apps/api/test/record-delete.spec.ts b/apps/api/test/record-delete.spec.tsindex 0db90526..8c567f7b 100644--- a/apps/api/test/record-delete.spec.ts+++ b/apps/api/test/record-delete.spec.ts@@ -13,6 +13,8 @@ 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 stampDomain = `stamped-${suffix}.test`;+const orphanDomain = `orphaned-${suffix}.test`;const email = `gone@${domain}`;const colleague = `stays@${domain}`;const userId = `user-${suffix}`;@@ -49,7 +51,7 @@ async function matchContext() {};}-const domains = [domain, doomedDomain];+const domains = [domain, doomedDomain, stampDomain, orphanDomain];const ours = {OR: domains.map((host) => ({ email: { endsWith: `@${host}` } })),};@@ -266,3 +268,93 @@ describe("deleting a company", () => {await db.contact.delete({ where: { id: contact.id } });});});++describe("the activity stamps a delete leaves behind", () => {+ it("are recomputed on every record the deleted one's activities touched", async () => {+ const company = await companies.create({+ name: "Stamped",+ domain: stampDomain,+ });+ const contact = await contacts.create({+ firstName: "Stamped",+ email: `stamped@${stampDomain}`,+ companyId: company.id,+ });+ const deal = await db.deal.create({+ data: { name: "Stamped deal", companyId: company.id, ownerId: userId },+ select: { id: true },+ });++ const at = new Date();+ await db.activity.create({+ data: {+ type: "NOTE",+ subject: "The only thing on this account",+ companyId: company.id,+ contactId: contact.id,+ dealId: deal.id,+ createdById: userId,+ createdAt: at,+ },+ });+ await stamp.touch(+ { companyId: company.id, contactId: contact.id, dealId: deal.id },+ at,+ );++ await contacts.delete(contact.id);++ expect(+ await db.company.findUnique({+ where: { id: company.id },+ select: { lastActivityAt: true },+ }),+ ).toEqual({ lastActivityAt: null });+ expect(+ await db.deal.findUnique({+ where: { id: deal.id },+ select: { lastActivityAt: true },+ }),+ ).toEqual({ lastActivityAt: null });+ });++ it("follow a deleted company through the deals it takes with it", async () => {+ const company = await companies.create({+ name: "Orphaner",+ domain: orphanDomain,+ });+ const contact = await contacts.create({+ firstName: "Orphaned",+ email: `orphaned@${orphanDomain}`,+ companyId: company.id,+ });+ const deal = await db.deal.create({+ data: { name: "Orphaned deal", companyId: company.id, ownerId: userId },+ select: { id: true },+ });++ const at = new Date();+ await db.activity.create({+ data: {+ type: "MEETING",+ subject: "Only ever attached to the deal",+ contactId: contact.id,+ dealId: deal.id,+ createdById: userId,+ createdAt: at,+ },+ });+ await stamp.touch({ contactId: contact.id, dealId: deal.id }, at);++ await companies.delete(company.id);++ expect(+ await db.contact.findUnique({+ where: { id: contact.id },+ select: { companyId: true, lastActivityAt: true },+ }),+ ).toEqual({ companyId: null, lastActivityAt: null });++ await db.contact.delete({ where: { id: contact.id } });+ });+});diff --git a/docs/api.md b/docs/api.mdindex d9115407..0a333d9d 100644--- a/docs/api.md+++ b/docs/api.md@@ -362,6 +362,16 @@ once.suppression written by `contacts.delete`. The conflict check on create and`allowAgain` both match case-insensitively so a row written before this rulestill answers.+- **The address is taken from the delete itself, not from a read before it.**+ `contacts.delete` runs `tx.contact.delete({ select: { email: true } })` inside+ the transaction and suppresses what comes back, so the row it writes down is+ the address the contact had at the moment it ceased to exist. A pre-check read+ is a different question asked earlier: a rep correcting the address in one tab+ while another deletes the record left the old address suppressed and the new+ one open, which is the same recreated-contact loop wearing a different hat.+ It is also what supplies the name in the `reason`, and the 404 — a missing+ contact is now the delete's own `P2025` through `translate`, rather than a+ pre-check that a concurrent delete could pass.- **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,@@ -385,13 +395,33 @@ 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.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+**The stamps are then recomputed on the records the delete actually reached,+and no others.** 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.++- **The affected set is read before the rows go, inside the delete's own+ transaction.** `ActivityStampService.targetsOf(where)` groups the activities a+ delete is about to destroy by each of their three foreign keys and hands back+ the ids; `recomputeMany` restamps exactly those rows, one `UPDATE … SET+ lastActivityAt = (SELECT MAX(…))` per table, which covers "has newer+ activities" and "has none left, so null" in the same statement. Reading it+ after the delete is not an option — the evidence is what was deleted.+- **A company's `where` follows the deals it takes with it**, `{ OR: [{+ companyId }, { deal: { companyId } }] }`. Deleting a company cascades to its+ deals and those cascade to their activities, so a surviving contact whose only+ activity hung off one of those deals would keep a stamp for work that no+ longer exists. `test/record-delete.spec.ts` pins that branch specifically.+- **`recomputeAll()` is still there and is still right for a purge.** It rebuilds+ every stamp in the CRM with six full-table statements, which is what+ disconnecting Google and dropping everything it synced needs. It is the wrong+ tool for deleting one record: it made the cost of removing a contact a+ function of the size of the entire CRM, and it repaired rows the rep's action+ never touched.++**Recomputing runs after the delete has committed, so it logs rather than+throws.** Therow is already gone by the time the stamps are rebuilt; letting that failure outreports a completed destructive action as a failure, the browser neverinvalidates its caches, and the rep's retry answers `No contact with id …`. A