Skip to content

armgit / crm

Public Imported from GitHub
0

Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.

TypeScript

Record an activity whenever something is enriched automatically

Lewis Carhart36323169176b
diff --git a/apps/api/src/crm/crm.module.ts b/apps/api/src/crm/crm.module.ts
index 95a59709..70494d54 100644
--- a/apps/api/src/crm/crm.module.ts
+++ b/apps/api/src/crm/crm.module.ts
@@ -1,5 +1,6 @@
import { Global, Module } from "@nestjs/common";
import { ActivityStampService } from "./activity-stamp.service";
+import { EnrichmentLogService } from "./enrichment-log.service";
/**
* Cross-cutting CRM concerns.
@@ -11,7 +12,7 @@ import { ActivityStampService } from "./activity-stamp.service";
*/
@Global()
@Module({
- providers: [ActivityStampService],
- exports: [ActivityStampService],
+ providers: [ActivityStampService, EnrichmentLogService],
+ exports: [ActivityStampService, EnrichmentLogService],
})
export class CrmModule {}
diff --git a/apps/api/src/crm/enrichment-log.service.ts b/apps/api/src/crm/enrichment-log.service.ts
new file mode 100644
index 00000000..35981f17
--- /dev/null
+++ b/apps/api/src/crm/enrichment-log.service.ts
@@ -0,0 +1,98 @@
+import { ActivityType, type Db } from "@crm/db";
+import { Injectable } from "@nestjs/common";
+import { InjectDatabase } from "../database/database.constants";
+import { ActivityStampService } from "./activity-stamp.service";
+
+export type EnrichmentEvent = {
+ companyId?: string | null;
+ contactId?: string | null;
+ subject: string;
+ body?: string | null;
+ /** Where the facts came from, and what changed. Rendered on the entry. */
+ meta?: Record<string, unknown>;
+};
+
+/**
+ * Writes an `ENRICHMENT` activity when something is created or filled in
+ * automatically.
+ *
+ * Without this the agents are invisible: a company appears with a logo and an
+ * industry nobody typed, a contact renames itself overnight, and the only way
+ * to find out when or why is to read the server logs. A record that changes on
+ * its own has to say so on its own timeline — that is the difference between an
+ * assistant and a haunted database.
+ *
+ * Deliberately the same `ENRICHMENT` type the research brief already uses, so
+ * one filter shows everything the machines did.
+ */
+@Injectable()
+export class EnrichmentLogService {
+ constructor(
+ @InjectDatabase() private readonly db: Db,
+ private readonly stamp: ActivityStampService,
+ ) {}
+
+ /**
+ * Records one event, attributed to a system author.
+ *
+ * `Activity.createdById` is required, so an automatic write borrows the
+ * record's owner and falls back to any user. `meta.automated` marks it, and
+ * the timeline renders that as "via …" rather than as something a person did.
+ */
+ async record(event: EnrichmentEvent): Promise<string | null> {
+ const author = await this.authorFor(event);
+ if (!author) return null;
+
+ const activity = await this.db.activity.create({
+ data: {
+ type: ActivityType.ENRICHMENT,
+ subject: event.subject,
+ body: event.body ?? null,
+ occurredAt: new Date(),
+ companyId: event.companyId ?? null,
+ contactId: event.contactId ?? null,
+ createdById: author,
+ meta: { ...event.meta, automated: true },
+ },
+ select: { id: true, createdAt: true },
+ });
+
+ await this.stamp.touch(
+ { companyId: event.companyId, contactId: event.contactId },
+ activity.createdAt,
+ );
+
+ return activity.id;
+ }
+
+ /** The owner of whatever this is about, or any user. */
+ private async authorFor(event: EnrichmentEvent): Promise<string | null> {
+ if (event.contactId) {
+ const contact = await this.db.contact.findUnique({
+ where: { id: event.contactId },
+ select: { ownerId: true },
+ });
+ if (contact?.ownerId) return contact.ownerId;
+ }
+
+ if (event.companyId) {
+ const company = await this.db.company.findUnique({
+ where: { id: event.companyId },
+ select: { ownerId: true },
+ });
+ if (company?.ownerId) return company.ownerId;
+ }
+
+ const anyUser = await this.db.user.findFirst({ select: { id: true } });
+ return anyUser?.id ?? null;
+ }
+}
+
+/** "logo, industry, description" — what a lookup actually filled in. */
+export function describeFilled(fields: readonly string[]): string | null {
+ if (fields.length === 0) return null;
+ if (fields.length === 1) return `Filled in ${fields[0]}.`;
+
+ const last = fields[fields.length - 1];
+ return `Filled in ${fields.slice(0, -1).join(", ")} and ${last}.`;
+}
diff --git a/apps/api/src/enrichment/contact-enrichment.service.ts b/apps/api/src/enrichment/contact-enrichment.service.ts
index 07e354a8..09b9bf71 100644
--- a/apps/api/src/enrichment/contact-enrichment.service.ts
+++ b/apps/api/src/enrichment/contact-enrichment.service.ts
@@ -1,6 +1,7 @@
import { type Db, RecordSource } from "@crm/db";
import { Injectable, Logger } from "@nestjs/common";
import { domainFromEmail } from "../companies/domain";
+import { EnrichmentLogService } from "../crm/enrichment-log.service";
import { InjectDatabase } from "../database/database.constants";
import { isDerivedName, splitName } from "../google/participants";
import { ContextDevClient } from "./context-dev.client";
@@ -42,6 +43,7 @@ export class ContactEnrichmentService {
private readonly context: ContextDevClient,
private readonly queue: EnrichmentQueue,
private readonly linkedin: LinkdapiClient,
+ private readonly log: EnrichmentLogService,
) {}
get enabled(): boolean {
@@ -119,6 +121,14 @@ export class ContactEnrichmentService {
},
});
+ await this.log.record({
+ contactId,
+ companyId: null,
+ subject: "Identified from LinkedIn",
+ body: `Matched to ${found.fullName}${found.title ? `, ${found.title}` : ""}.\n${found.sourceUrl}`,
+ meta: { source: "linkedin", sourceUrl: found.sourceUrl },
+ });
+
this.logger.log({
message: "Contact name resolved from the web",
contactId,
diff --git a/apps/api/src/enrichment/enrichment.service.ts b/apps/api/src/enrichment/enrichment.service.ts
index 1028f65a..b62b368a 100644
--- a/apps/api/src/enrichment/enrichment.service.ts
+++ b/apps/api/src/enrichment/enrichment.service.ts
@@ -2,6 +2,10 @@ import { ActivityType, type Db, EnrichmentStatus } from "@crm/db";
import { Injectable, Logger, NotFoundException } from "@nestjs/common";
import { domainFromEmail, normalizeDomain } from "../companies/domain";
import { ActivityStampService } from "../crm/activity-stamp.service";
+import {
+ describeFilled,
+ EnrichmentLogService,
+} from "../crm/enrichment-log.service";
import { InjectDatabase } from "../database/database.constants";
import { brandToUpdate, filledFields } from "./brand-mapping";
import { ContextDevClient } from "./context-dev.client";
@@ -51,6 +55,7 @@ export class EnrichmentService {
private readonly context: ContextDevClient,
private readonly queue: EnrichmentQueue,
private readonly stamp: ActivityStampService,
+ private readonly log: EnrichmentLogService,
) {}
/**
@@ -183,11 +188,20 @@ export class EnrichmentService {
}),
]);
+ const filled = filledFields(update);
+
+ await this.log.record({
+ companyId,
+ subject: "Enriched from Context.dev",
+ body: describeFilled(filled),
+ meta: { source: "context.dev", endpoint: "brand/retrieve", filled },
+ });
+
this.logger.log({
message: "Company enriched",
companyId,
domain,
- filled: filledFields(update),
+ filled,
});
}
@@ -246,6 +260,13 @@ export class EnrichmentService {
// the same brand twice.
this.enqueueCompany(company.id);
+ await this.log.record({
+ companyId: company.id,
+ subject: "Company added automatically",
+ body: `Created from the domain ${domain}. Looking up brand details.`,
+ meta: { source: "email-domain", domain },
+ });
+
this.logger.log({
message: "Company created from a contact's email domain",
companyId: company.id,
diff --git a/apps/api/src/google/google-match.service.ts b/apps/api/src/google/google-match.service.ts
index 64c56967..d5f520eb 100644
--- a/apps/api/src/google/google-match.service.ts
+++ b/apps/api/src/google/google-match.service.ts
@@ -1,5 +1,6 @@
import { type Db, RecordSource } from "@crm/db";
import { Injectable, Logger } from "@nestjs/common";
+import { EnrichmentLogService } from "../crm/enrichment-log.service";
import { InjectDatabase } from "../database/database.constants";
import { ContactEnrichmentService } from "../enrichment/contact-enrichment.service";
import { EnrichmentService } from "../enrichment/enrichment.service";
@@ -74,6 +75,7 @@ export class GoogleMatchService {
@InjectDatabase() private readonly db: Db,
private readonly enrichment: EnrichmentService,
private readonly contacts: ContactEnrichmentService,
+ private readonly log: EnrichmentLogService,
) {}
/**
@@ -236,6 +238,15 @@ export class GoogleMatchService {
request,
);
+ await this.log.record({
+ companyId,
+ subject: "Company added from your inbox",
+ body:
+ `Created because you ${request.source === "CALENDAR" ? "met" : "emailed"} ` +
+ `someone at ${domain}.`,
+ meta: { source: request.source, domain },
+ });
+
this.logger.log({
message: "Company auto-created from Google sync",
companyId,
@@ -262,6 +273,11 @@ export class GoogleMatchService {
// `Contact.email` is unique, so this is the race-safe form: two reps'
// syncs hitting the same new person resolve to one row.
+ const existing = await this.db.contact.findUnique({
+ where: { email: person.email },
+ select: { id: true },
+ });
+
const contact = await this.db.contact.upsert({
where: { email: person.email },
create: {
@@ -277,6 +293,16 @@ export class GoogleMatchService {
select: { id: true, firstName: true, lastName: true },
});
+ if (!existing) {
+ await this.log.record({
+ contactId: contact.id,
+ companyId,
+ subject: "Contact added from your inbox",
+ body: `${person.email} appeared in a ${request.source === "CALENDAR" ? "meeting" : "thread"}.`,
+ meta: { source: request.source },
+ });
+ }
+
// Google hands back an attendee with no `displayName` far more often than
// it hands back one with a name, so a contact is routinely created from the
// address alone and then met again later with a real name attached. Taking
diff --git a/apps/api/test/enrichment.integration.spec.ts b/apps/api/test/enrichment.integration.spec.ts
index 8642fdd6..7ca0f1a9 100644
--- a/apps/api/test/enrichment.integration.spec.ts
+++ b/apps/api/test/enrichment.integration.spec.ts
@@ -53,6 +53,9 @@ const { EnrichmentQueue } = await import("../src/enrichment/enrichment.queue");
const { ActivityStampService } = await import(
"../src/crm/activity-stamp.service"
);
+const { EnrichmentLogService } = await import(
+ "../src/crm/enrichment-log.service"
+);
const { EnrichmentService } = await import(
"../src/enrichment/enrichment.service"
);
@@ -120,6 +123,7 @@ beforeAll(async () => {
client,
new FastQueue(),
new ActivityStampService(db),
+ new EnrichmentLogService(db, new ActivityStampService(db)),
);
const user = await db.user.upsert({