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

Implement fields management features (#55)

Lewis Carhart15c614087911
diff --git a/apps/api/src/agent/agent-trigger.service.ts b/apps/api/src/agent/agent-trigger.service.ts
index df8eca6e..626edb15 100644
--- a/apps/api/src/agent/agent-trigger.service.ts
+++ b/apps/api/src/agent/agent-trigger.service.ts
@@ -1,4 +1,4 @@
-import type { Db } from "@crm/db";
+import type { Db, FieldEntity } from "@crm/db";
import { PRIORITY } from "@crm/db/agent-tasks";
import { Injectable, Logger } from "@nestjs/common";
import { InjectDatabase } from "../database/database.constants";
@@ -70,13 +70,19 @@ export class AgentTriggerService {
});
}
- async fieldBackfill(key: string, reason: string): Promise<void> {
+ async fieldBackfill(
+ entity: FieldEntity,
+ key: string,
+ reason: string,
+ ): Promise<void> {
+ const subject = `${entity.toLowerCase()}.${key}`;
+
try {
const pending = await this.db.agentTask.findFirst({
where: {
kind: "field-backfill",
finishedAt: null,
- reason: { startsWith: `${key}: ` },
+ reason: { startsWith: `${subject}: ` },
},
select: { id: true },
});
@@ -86,7 +92,7 @@ export class AgentTriggerService {
await this.db.agentTask.create({
data: {
kind: "field-backfill",
- reason: `${key}: ${reason}`,
+ reason: `${subject}: ${reason}`,
priority: PRIORITY.fieldBackfill,
budget: 8,
dueAt: new Date(),
@@ -96,13 +102,19 @@ export class AgentTriggerService {
this.logger.log({
message: "Agent task queued",
kind: "field-backfill",
+ entity,
key,
});
this.poke();
} catch (error) {
this.logger.error(
- { message: "Could not queue agent task", kind: "field-backfill", key },
+ {
+ message: "Could not queue agent task",
+ kind: "field-backfill",
+ entity,
+ key,
+ },
error instanceof Error ? error.stack : String(error),
);
}
diff --git a/apps/api/src/companies/companies.service.ts b/apps/api/src/companies/companies.service.ts
index 198e2344..108718bb 100644
--- a/apps/api/src/companies/companies.service.ts
+++ b/apps/api/src/companies/companies.service.ts
@@ -320,10 +320,6 @@ export class CompaniesService {
}
async update(id: string, input: CompanyUpdateInput) {
- if (input.fields) {
- await this.fields.applyValues(this.db, "COMPANY", id, input.fields);
- }
-
const data: Prisma.CompanyUpdateInput = {};
if (input.name !== undefined) data.name = input.name.trim();
@@ -371,10 +367,16 @@ export class CompaniesService {
}
try {
- const updated = await this.db.company.update({
- where: { id },
- data,
- select: { id: true, name: true, domain: true },
+ const updated = await this.db.$transaction(async (tx) => {
+ if (input.fields) {
+ await this.fields.applyValues(tx, "COMPANY", id, input.fields);
+ }
+
+ return tx.company.update({
+ where: { id },
+ data,
+ select: { id: true, name: true, domain: true },
+ });
});
if (data.enrichmentStatus === "PENDING") {
@@ -426,18 +428,20 @@ export class CompaniesService {
}
async bulkAssignOwner(input: CompanyBulkOwnerInput): Promise<BulkResult> {
- await requireOwner(this.db, input.ownerId);
+ const ownerId = input.ownerId || null;
+
+ await requireOwner(this.db, ownerId);
const ids = [...new Set(input.ids)];
const { count } = await this.db.company.updateMany({
where: { id: { in: ids } },
- data: { ownerId: input.ownerId },
+ data: { ownerId },
});
this.logger.log({
message: "Companies reassigned",
count,
- ownerId: input.ownerId,
+ ownerId,
});
return {
diff --git a/apps/api/src/contacts/contacts.service.ts b/apps/api/src/contacts/contacts.service.ts
index cd9e9566..9f7df4dd 100644
--- a/apps/api/src/contacts/contacts.service.ts
+++ b/apps/api/src/contacts/contacts.service.ts
@@ -375,10 +375,6 @@ export class ContactsService {
}
async update(id: string, input: ContactUpdateInput) {
- if (input.fields) {
- await this.fields.applyValues(this.db, "CONTACT", id, input.fields);
- }
-
const data: Prisma.ContactUpdateInput = {};
if (input.firstName !== undefined) data.firstName = input.firstName.trim();
@@ -409,6 +405,10 @@ export class ContactsService {
try {
return await this.db.$transaction(async (tx) => {
+ if (input.fields) {
+ await this.fields.applyValues(tx, "CONTACT", id, input.fields);
+ }
+
const updated = await tx.contact.update({
where: { id },
data,
@@ -427,18 +427,20 @@ export class ContactsService {
}
async bulkAssignOwner(input: ContactBulkOwnerInput): Promise<BulkResult> {
- await requireOwner(this.db, input.ownerId);
+ const ownerId = input.ownerId || null;
+
+ await requireOwner(this.db, ownerId);
const ids = [...new Set(input.ids)];
const { count } = await this.db.contact.updateMany({
where: { id: { in: ids } },
- data: { ownerId: input.ownerId },
+ data: { ownerId },
});
this.logger.log({
message: "Contacts reassigned",
count,
- ownerId: input.ownerId,
+ ownerId,
});
return {
@@ -450,26 +452,28 @@ export class ContactsService {
}
async bulkSetCompany(input: ContactBulkCompanyInput): Promise<BulkResult> {
- if (input.companyId) {
+ const companyId = input.companyId || null;
+
+ if (companyId) {
const company = await this.db.company.findUnique({
- where: { id: input.companyId },
+ where: { id: companyId },
select: { id: true },
});
if (!company) {
- throw new NotFoundException(`No company with id ${input.companyId}.`);
+ throw new NotFoundException(`No company with id ${companyId}.`);
}
}
const ids = [...new Set(input.ids)];
const { count } = await this.db.contact.updateMany({
where: { id: { in: ids } },
- data: { companyId: input.companyId },
+ data: { companyId },
});
this.logger.log({
message: "Contacts moved",
count,
- companyId: input.companyId,
+ companyId,
});
return {
diff --git a/apps/api/src/deals/deals.service.ts b/apps/api/src/deals/deals.service.ts
index c604baba..83480594 100644
--- a/apps/api/src/deals/deals.service.ts
+++ b/apps/api/src/deals/deals.service.ts
@@ -271,10 +271,6 @@ export class DealsService {
}
async update(id: string, input: DealUpdateInput) {
- if (input.fields) {
- await this.fields.applyValues(this.db, "DEAL", id, input.fields);
- }
-
const data: Prisma.DealUpdateInput = {};
if (input.name !== undefined) data.name = input.name.trim();
@@ -321,10 +317,16 @@ export class DealsService {
}
try {
- return await this.db.deal.update({
- where: { id },
- data,
- select: { id: true, name: true },
+ return await this.db.$transaction(async (tx) => {
+ if (input.fields) {
+ await this.fields.applyValues(tx, "DEAL", id, input.fields);
+ }
+
+ return tx.deal.update({
+ where: { id },
+ data,
+ select: { id: true, name: true },
+ });
});
} catch (error) {
throw this.translate(error, id);
diff --git a/apps/api/src/fields/fields.contracts.ts b/apps/api/src/fields/fields.contracts.ts
index a3f6e9e4..babdff01 100644
--- a/apps/api/src/fields/fields.contracts.ts
+++ b/apps/api/src/fields/fields.contracts.ts
@@ -61,4 +61,9 @@ export const fieldReorderInput = z.object({
export type FieldReorderInput = z.infer<typeof fieldReorderInput>;
-export const recordFieldValues = z.record(z.string(), z.unknown());
+const recordFieldValue = z.union(
+ [z.string(), z.number(), z.boolean(), z.null()],
+ { error: "A field holds text, a number, true or false, or nothing at all." },
+);
+
+export const recordFieldValues = z.record(z.string(), recordFieldValue);
diff --git a/apps/api/src/fields/fields.service.ts b/apps/api/src/fields/fields.service.ts
index 6c521dfc..856f81ac 100644
--- a/apps/api/src/fields/fields.service.ts
+++ b/apps/api/src/fields/fields.service.ts
@@ -1,4 +1,9 @@
-import type { Db, FieldEntity, Prisma } from "@crm/db";
+import {
+ type Db,
+ type FieldEntity,
+ type Prisma,
+ Prisma as PrismaNamespace,
+} from "@crm/db";
import {
attachValues,
type FieldDefinitionWithOptions,
@@ -113,7 +118,11 @@ export class FieldsService {
});
if (definition.agentFilled) {
- await this.agent.fieldBackfill(definition.key, "New field");
+ await this.agent.fieldBackfill(
+ definition.entity,
+ definition.key,
+ "New field",
+ );
}
return serializeField(definition);
@@ -141,7 +150,11 @@ export class FieldsService {
}
}
- if (usesOptions(type) && data.options && data.options.length === 0) {
+ const optionCount = data.options
+ ? data.options.length
+ : existing.options.filter((option) => option.archivedAt === null).length;
+
+ if (usesOptions(type) && optionCount === 0) {
throw new BadRequestException("A select needs at least one option.");
}
@@ -193,7 +206,11 @@ export class FieldsService {
const turnedOn = data.agentFilled === true && !existing.agentFilled;
if (definition.agentFilled && (briefChanged || turnedOn)) {
- await this.agent.fieldBackfill(definition.key, "Brief changed");
+ await this.agent.fieldBackfill(
+ definition.entity,
+ definition.key,
+ "Brief changed",
+ );
}
return serializeField(definition);
@@ -224,37 +241,39 @@ export class FieldsService {
}
async archive(id: string): Promise<SerializedField> {
- const definition = await this.db.fieldDefinition
- .update({
+ try {
+ const definition = await this.db.fieldDefinition.update({
where: { id },
data: { archivedAt: new Date() },
include: WITH_OPTIONS,
- })
- .catch(() => {
- throw new NotFoundException("That field does not exist.");
});
- return serializeField(definition);
+ return serializeField(definition);
+ } catch (error) {
+ throw this.translate(error);
+ }
}
async restore(id: string): Promise<SerializedField> {
- const definition = await this.db.fieldDefinition
- .update({
+ try {
+ const definition = await this.db.fieldDefinition.update({
where: { id },
data: { archivedAt: null },
include: WITH_OPTIONS,
- })
- .catch(() => {
- throw new NotFoundException("That field does not exist.");
});
- return serializeField(definition);
+ return serializeField(definition);
+ } catch (error) {
+ throw this.translate(error);
+ }
}
async delete(id: string): Promise<{ id: string }> {
- await this.db.fieldDefinition.delete({ where: { id } }).catch(() => {
- throw new NotFoundException("That field does not exist.");
- });
+ try {
+ await this.db.fieldDefinition.delete({ where: { id } });
+ } catch (error) {
+ throw this.translate(error);
+ }
return { id };
}
@@ -262,7 +281,12 @@ export class FieldsService {
async backfill(id: string): Promise<{ queued: boolean }> {
const definition = await this.db.fieldDefinition.findUnique({
where: { id },
- select: { key: true, agentFilled: true, archivedAt: true },
+ select: {
+ entity: true,
+ key: true,
+ agentFilled: true,
+ archivedAt: true,
+ },
});
if (!definition) throw new NotFoundException("That field does not exist.");
@@ -273,7 +297,11 @@ export class FieldsService {
);
}
- await this.agent.fieldBackfill(definition.key, "Asked to fill the rest");
+ await this.agent.fieldBackfill(
+ definition.entity,
+ definition.key,
+ "Asked to fill the rest",
+ );
return { queued: true };
}
@@ -361,7 +389,10 @@ export class FieldsService {
if (!definition) continue;
const current = byRecord.get(recordId) ?? {};
- current[definition.key] = readValue(definition, row);
+ current[definition.key] = tableValue(
+ definition,
+ readValue(definition, row),
+ );
byRecord.set(recordId, current);
}
@@ -388,4 +419,26 @@ export class FieldsService {
throw error;
}
}
+
+ private translate(error: unknown): unknown {
+ if (
+ error instanceof PrismaNamespace.PrismaClientKnownRequestError &&
+ error.code === "P2025"
+ ) {
+ return new NotFoundException("That field does not exist.");
+ }
+
+ return error;
+ }
+}
+
+function tableValue(
+ definition: FieldDefinitionWithOptions,
+ value: FieldValueJson,
+): FieldValueJson {
+ if (definition.type !== "SELECT" || typeof value !== "string") return value;
+
+ return (
+ definition.options.find((option) => option.id === value)?.label ?? null
+ );
}
diff --git a/apps/api/test/bulk.spec.ts b/apps/api/test/bulk.spec.ts
index 27fd7146..83e3afd6 100644
--- a/apps/api/test/bulk.spec.ts
+++ b/apps/api/test/bulk.spec.ts
@@ -52,7 +52,7 @@ let companyId: string;
async function clean() {
const owned = await db.company.findMany({
- where: { domain },
+ where: { domain: { endsWith: domain } },
select: { id: true },
});
const companyIds = owned.map((row) => row.id);
@@ -62,7 +62,7 @@ async function clean() {
await db.agentTask.deleteMany({ where: { companyId: { in: companyIds } } });
await db.contact.deleteMany({ where: ours });
await db.suppressedContact.deleteMany({ where: ours });
- await db.company.deleteMany({ where: { domain } });
+ await db.company.deleteMany({ where: { domain: { endsWith: domain } } });
await db.user.deleteMany({ where: { id: { in: [ownerId, secondOwnerId] } } });
}
diff --git a/apps/api/test/fields.spec.ts b/apps/api/test/fields.spec.ts
index cf7d0b85..b11997e3 100644
--- a/apps/api/test/fields.spec.ts
+++ b/apps/api/test/fields.spec.ts
@@ -1,55 +1,125 @@
-import { afterAll, beforeAll, describe, expect, it } from "bun:test";
-import { db } from "@crm/db";
-import type { AgentTriggerService } from "../src/agent/agent-trigger.service";
+import {
+ afterAll,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+} from "bun:test";
+import { db, type FieldEntity } 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 type { FaviconService } from "../src/companies/favicon.service";
+import { ContactsService } from "../src/contacts/contacts.service";
+import { ActivityStampService } from "../src/crm/activity-stamp.service";
+import { ConversionService } from "../src/currency/conversion.service";
+import { DealsService } from "../src/deals/deals.service";
import { FieldsService } from "../src/fields/fields.service";
const suffix = process.env.TEST_RUN_ID ?? "fields-spec";
const domain = `fields-${suffix}.test`;
+const ownerId = `owner-${suffix}`;
-const queued: { key: string; reason: string }[] = [];
+const queued: { entity: FieldEntity; key: string; reason: string }[] = [];
const agent = {
- fieldBackfill: async (key: string, reason: string) => {
- queued.push({ key, reason });
+ contactCreated: async () => undefined,
+ companyCreated: async () => undefined,
+ companyRequested: async () => undefined,
+ fieldBackfill: async (entity: FieldEntity, key: string, reason: string) => {
+ queued.push({ entity, key, reason });
},
} as unknown as AgentTriggerService;
+const stamp = new ActivityStampService(db);
+const queue = new AgentQueueService(db);
+const conversion = new ConversionService(db);
+
const fields = new FieldsService(db, agent);
+const companies = new CompaniesService(
+ db,
+ agent,
+ queue,
+ { backfill: async () => undefined } as unknown as FaviconService,
+ stamp,
+ conversion,
+ fields,
+);
+const contacts = new ContactsService(
+ db,
+ new CompanyDirectoryService(db, agent),
+ agent,
+ queue,
+ stamp,
+ fields,
+);
+const deals = new DealsService(db, stamp, conversion, fields);
let companyId: string;
+let bridgeSecret: string | undefined;
async function clean() {
const owned = await db.company.findMany({
- where: { domain },
+ where: { domain: { endsWith: domain } },
select: { id: true },
});
+ const companyIds = owned.map((row) => row.id);
+ await db.agentTask.deleteMany({
+ where: { kind: "field-backfill", reason: { contains: "spec_" } },
+ });
+ await db.deal.deleteMany({ where: { companyId: { in: companyIds } } });
+ await db.contact.deleteMany({ where: { companyId: { in: companyIds } } });
await db.fieldValue.deleteMany({
- where: { companyId: { in: owned.map((row) => row.id) } },
+ where: { companyId: { in: companyIds } },
});
await db.fieldDefinition.deleteMany({
where: { key: { startsWith: "spec_" } },
});
- await db.company.deleteMany({ where: { domain } });
+ await db.company.deleteMany({ where: { domain: { endsWith: domain } } });
+ await db.user.deleteMany({ where: { id: ownerId } });
+}
+
+async function makeCompany(name: string): Promise<string> {
+ const company = await db.company.create({
+ data: { name: `${name} ${suffix}`, domain: `${name}-${domain}` },
+ select: { id: true },
+ });
+
+ return company.id;
}
beforeAll(async () => {
+ bridgeSecret = process.env.AGENT_BRIDGE_SECRET;
+ process.env.AGENT_BRIDGE_SECRET = "";
+
await clean();
- const company = await db.company.create({
- data: { name: `Fields Co ${suffix}`, domain },
- select: { id: true },
+ await db.user.create({
+ data: { id: ownerId, name: "Fields Rep", email: `rep@${domain}` },
});
- companyId = company.id;
+ companyId = await makeCompany("fields-co");
});
-afterAll(clean);
+afterAll(async () => {
+ await clean();
+
+ if (bridgeSecret === undefined) {
+ delete process.env.AGENT_BRIDGE_SECRET;
+ } else {
+ process.env.AGENT_BRIDGE_SECRET = bridgeSecret;
+ }
+});
+
+beforeEach(() => {
+ queued.length = 0;
+});
describe("field definitions", () => {
it("derives a key from the label and queues a backfill", async () => {
- queued.length = 0;
-
const field = await fields.create({
entity: "COMPANY",
label: "Spec runs on",
@@ -67,7 +137,9 @@ describe("field definitions", () => {
"AWS",
"Azure",
]);
- expect(queued).toEqual([{ key: "spec_runs_on", reason: "New field" }]);
+ expect(queued).toEqual([
+ { entity: "COMPANY", key: "spec_runs_on", reason: "New field" },
+ ]);
});
it("refuses a duplicate key", async () => {
@@ -102,9 +174,27 @@ describe("field definitions", () => {
spec_runs_on: "AWS",
});
- await expect(
- fields.update(field.id, { type: "TEXT" }),
- ).rejects.toThrow(/cannot change/);
+ await expect(fields.update(field.id, { type: "TEXT" })).rejects.toThrow(
+ /cannot change/,
+ );
+ });
+
+ it("will not turn a field into a select with nothing to choose", async () => {
+ const field = await fields.create({
+ entity: "DEAL",
+ label: "Spec plain",
+ type: "TEXT",
+ options: [],
+ agentFilled: false,
+ agentBrief: null,
+ required: false,
+ showOnSheet: true,
+ showOnTable: false,
+ });
+
+ await expect(fields.update(field.id, { type: "SELECT" })).rejects.toThrow(
+ /at least one option/,
+ );
});
it("archives without losing values, and restores them", async () => {
@@ -112,16 +202,23 @@ describe("field definitions", () => {
await fields.archive(field.id);
- expect(await fields.valuesFor("COMPANY", companyId)).toEqual([]);
expect(
- await db.fieldValue.count({ where: { fieldId: field.id } }),
- ).toBe(1);
+ (await fields.valuesFor("COMPANY", companyId)).map((entry) => entry.key),
+ ).not.toContain("spec_runs_on");
+ expect(await db.fieldValue.count({ where: { fieldId: field.id } })).toBe(1);
await fields.restore(field.id);
const back = await fields.valuesFor("COMPANY", companyId);
- expect(back).toHaveLength(1);
- expect(back[0]?.key).toBe("spec_runs_on");
+ expect(back.map((entry) => entry.key)).toContain("spec_runs_on");
+ });
+
+ it("says a field is missing without swallowing other failures", async () => {
+ const missing = `missing-${suffix}`;
+
+ await expect(fields.archive(missing)).rejects.toThrow(/does not exist/);
+ await expect(fields.restore(missing)).rejects.toThrow(/does not exist/);
+ await expect(fields.delete(missing)).rejects.toThrow(/does not exist/);
});
it("reorders inside one entity only", async () => {
@@ -144,10 +241,12 @@ describe("field definitions", () => {
ids: [second.id, first.id],
});
- expect(reordered.map((field) => field.key)).toEqual([
- "spec_seats",
- "spec_runs_on",
- ]);
+ const keys = reordered.map((field) => field.key);
+
+ expect(keys).toContain("spec_seats");
+ expect(keys.indexOf("spec_seats")).toBeLessThan(
+ keys.indexOf("spec_runs_on"),
+ );
await expect(
fields.reorder({ entity: "CONTACT", ids: [first.id] }),
@@ -181,6 +280,30 @@ describe("field values", () => {
expect(byKey.get("spec_renewal")).toBe("2027-03-31T00:00:00.000Z");
});
+ it("takes a date as ISO 8601 and nothing else", async () => {
+ const record = await makeCompany("dates");
+
+ await fields.applyValues(db, "COMPANY", record, {
+ spec_renewal: "2027-03-31T12:30:00.000Z",
+ });
+
+ const values = await fields.valuesFor("COMPANY", record);
+ const renewal = values.find((field) => field.key === "spec_renewal");
+ expect(renewal?.value).toBe("2027-03-31T12:30:00.000Z");
+
+ for (const raw of ["2027/03/31", "03-31-2027", "31 March 2027"]) {
+ await expect(
+ fields.applyValues(db, "COMPANY", record, { spec_renewal: raw }),
+ ).rejects.toThrow(/takes a date/);
+ }
+
+ expect(
+ (await fields.valuesFor("COMPANY", record)).find(
+ (field) => field.key === "spec_renewal",
+ )?.value,
+ ).toBe("2027-03-31T12:30:00.000Z");
+ });
+
it("rejects a value the type cannot hold", async () => {
await expect(
fields.applyValues(db, "COMPANY", companyId, { spec_seats: "loads" }),
@@ -193,6 +316,54 @@ describe("field values", () => {
).rejects.toThrow(/no field called/);
});
+ it("writes none of a batch when one value in it is refused", async () => {
+ const record = await makeCompany("batch");
+
+ await expect(
+ fields.applyValues(db, "COMPANY", record, {
+ spec_seats: "12",
+ spec_renewal: "the spring",
+ }),
+ ).rejects.toThrow(/takes a date/);
+
+ expect(await db.fieldValue.count({ where: { companyId: record } })).toBe(0);
+ });
+
+ it("refuses a user who does not work here, and keeps the batch out", async () => {
+ const record = await makeCompany("people");
+
+ await fields.create({
+ entity: "COMPANY",
+ label: "Spec champion",
+ type: "USER",
+ options: [],
+ agentFilled: false,
+ agentBrief: null,
+ required: false,
+ showOnSheet: true,
+ showOnTable: false,
+ });
+
+ await expect(
+ fields.applyValues(db, "COMPANY", record, {
+ spec_seats: "12",
+ spec_champion: `nobody-${suffix}`,
+ }),
+ ).rejects.toThrow(/works here/);
+
+ expect(await db.fieldValue.count({ where: { companyId: record } })).toBe(0);
+
+ await fields.applyValues(db, "COMPANY", record, {
+ spec_champion: ownerId,
+ });
+
+ expect(
+ (await fields.valuesFor("COMPANY", record)).find(
+ (field) => field.key === "spec_champion",
+ )?.value,
+ ).toBe(ownerId);
+ });
+
it("clears a value when it is blanked", async () => {
await fields.applyValues(db, "COMPANY", companyId, { spec_seats: "" });
@@ -203,19 +374,190 @@ describe("field values", () => {
});
it("goes with the record when the record is deleted", async () => {
- const doomed = await db.company.create({
- data: { name: `Doomed ${suffix}`, domain: `doomed-${domain}` },
- select: { id: true },
- });
+ const doomed = await makeCompany("doomed");
- await fields.applyValues(db, "COMPANY", doomed.id, {
+ await fields.applyValues(db, "COMPANY", doomed, {
spec_renewal: "2027-01-01",
});
- await db.company.delete({ where: { id: doomed.id } });
+ await db.company.delete({ where: { id: doomed } });
+
+ expect(await db.fieldValue.count({ where: { companyId: doomed } })).toBe(0);
+ });
+});
+
+describe("a select option that was taken away", () => {
+ it("still labels what it left behind, but cannot be chosen again", async () => {
+ const record = await makeCompany("retired");
+
+ const field = await fields.create({
+ entity: "COMPANY",
+ label: "Spec tier",
+ type: "SELECT",
+ options: [{ label: "Gold" }, { label: "Silver" }],
+ agentFilled: false,
+ agentBrief: null,
+ required: false,
+ showOnSheet: true,
+ showOnTable: false,
+ });
+
+ const gold = field.options.find((option) => option.label === "Gold");
+ const silver = field.options.find((option) => option.label === "Silver");
+
+ await fields.applyValues(db, "COMPANY", record, { spec_tier: "Gold" });
+
+ await fields.update(field.id, {
+ options: [{ id: silver?.id, label: "Silver" }],
+ });
+
+ const [tier] = (await fields.valuesFor("COMPANY", record)).filter(
+ (entry) => entry.key === "spec_tier",
+ );
+
+ expect(tier?.value).toBe(gold?.id);
+ expect(tier?.options.find((option) => option.id === gold?.id)?.label).toBe(
+ "Gold",
+ );
expect(
- await db.fieldValue.count({ where: { companyId: doomed.id } }),
+ (await fields.byKey("COMPANY", "spec_tier")).options.map(
+ (option) => option.label,
+ ),
+ ).toEqual(["Silver"]);
+
+ await expect(
+ fields.applyValues(db, "COMPANY", record, { spec_tier: "Gold" }),
+ ).rejects.toThrow(/no option/);
+ });
+
+ it("still reads as a label in a table, not as an option id", async () => {
+ const record = await makeCompany("retired-table");
+
+ const field = await fields.create({
+ entity: "COMPANY",
+ label: "Spec plan",
+ type: "SELECT",
+ options: [{ label: "Pilot" }, { label: "Rollout" }],
+ agentFilled: false,
+ agentBrief: null,
+ required: false,
+ showOnSheet: true,
+ showOnTable: true,
+ });
+
+ const rollout = field.options.find((option) => option.label === "Rollout");
+
+ await fields.applyValues(db, "COMPANY", record, { spec_plan: "Pilot" });
+
+ await fields.update(field.id, {
+ options: [{ id: rollout?.id, label: "Rollout" }],
+ });
+
+ const table = await fields.tableValuesFor("COMPANY", [record]);
+
+ expect(table.get(record)?.spec_plan).toBe("Pilot");
+ });
+});
+
+describe("a record update that fails", () => {
+ it("leaves a company's field values as they were", async () => {
+ const record = await makeCompany("company-rollback");
+
+ await expect(
+ companies.update(record, {
+ name: "Renamed",
+ ownerId: `nobody-${suffix}`,
+ fields: { spec_seats: "99" },
+ }),
+ ).rejects.toThrow();
+
+ expect(await db.fieldValue.count({ where: { companyId: record } })).toBe(0);
+ });
+
+ it("leaves a contact's field values as they were", async () => {
+ await fields.create({
+ entity: "CONTACT",
+ label: "Spec note",
+ type: "TEXT",
+ options: [],
+ agentFilled: false,
+ agentBrief: null,
+ required: false,
+ showOnSheet: true,
+ showOnTable: false,
+ });
+
+ const contact = await db.contact.create({
+ data: {
+ firstName: "Ada",
+ email: `ada@${domain}`,
+ companyId,
+ },
+ select: { id: true },
+ });
+
+ await expect(
+ contacts.update(contact.id, {
+ companyId: `nobody-${suffix}`,
+ fields: { spec_note: "Reads the docs" },
+ }),
+ ).rejects.toThrow();
+
+ expect(
+ await db.fieldValue.count({ where: { contactId: contact.id } }),
).toBe(0);
});
+
+ it("leaves a deal's field values as they were", async () => {
+ await fields.create({
+ entity: "DEAL",
+ label: "Spec risk",
+ type: "TEXT",
+ options: [],
+ agentFilled: false,
+ agentBrief: null,
+ required: false,
+ showOnSheet: true,
+ showOnTable: false,
+ });
+
+ const deal = await db.deal.create({
+ data: { name: `Spec deal ${suffix}`, companyId, ownerId },
+ select: { id: true },
+ });
+
+ await expect(
+ deals.update(deal.id, {
+ companyId: `nobody-${suffix}`,
+ fields: { spec_risk: "Champion left" },
+ }),
+ ).rejects.toThrow();
+
+ expect(await db.fieldValue.count({ where: { dealId: deal.id } })).toBe(0);
+
+ await deals.update(deal.id, { fields: { spec_risk: "Champion left" } });
+
+ expect(await db.fieldValue.count({ where: { dealId: deal.id } })).toBe(1);
+ });
+});
+
+describe("queueing a backfill", () => {
+ it("keeps one entity's field apart from another's with the same key", async () => {
+ const trigger = new AgentTriggerService(db);
+
+ await trigger.fieldBackfill("COMPANY", "spec_website", "New field");
+ await trigger.fieldBackfill("CONTACT", "spec_website", "New field");
+ await trigger.fieldBackfill("COMPANY", "spec_website", "Brief changed");
+
+ const tasks = await db.agentTask.findMany({
+ where: { kind: "field-backfill", reason: { contains: "spec_website" } },
+ select: { reason: true },
+ });
+
+ expect(tasks.map((task) => task.reason).sort()).toEqual([
+ "company.spec_website: New field",
+ "contact.spec_website: New field",
+ ]);
+ });
});
diff --git a/apps/app/components/crm/bulk-actions.tsx b/apps/app/components/crm/bulk-actions.tsx
index a4f656e9..8aaa954b 100644
--- a/apps/app/components/crm/bulk-actions.tsx
+++ b/apps/app/components/crm/bulk-actions.tsx
@@ -45,9 +45,9 @@ export function reportBulk(
if (result.failed > 0) {
toast.error(
- `${done(result.succeeded)} ${result.failed} were left alone${
- result.message ? ` — ${result.message}` : "."
- }`,
+ `${done(result.succeeded)} ${result.failed} ${
+ result.failed === 1 ? "was" : "were"
+ } left alone${result.message ? ` — ${result.message}` : "."}`,
);
return;
}
diff --git a/apps/app/components/crm/fields/field-columns.tsx b/apps/app/components/crm/fields/field-columns.tsx
index 58b1623c..f46b2797 100644
--- a/apps/app/components/crm/fields/field-columns.tsx
+++ b/apps/app/components/crm/fields/field-columns.tsx
@@ -5,6 +5,7 @@ import { EmptyCellValue } from "@crm/ui/components/empty-cell";
import { formatDay } from "@crm/ui/lib/format";
import { useQuery } from "@tanstack/react-query";
import { useMemo } from "react";
+import { type Owner, OwnerCell } from "@/components/crm/owner-cell";
import { useTRPC } from "@/lib/trpc/client";
import type { FieldEntity } from "./fields-entity";
@@ -13,16 +14,15 @@ type WithFields = { fields: Record<string, string | number | boolean | null> };
function render(
type: string,
value: string | number | boolean | null,
- options: { id: string; label: string }[],
+ users: Map<string, Owner>,
) {
if (value === null || value === "") return <EmptyCellValue />;
if (type === "CHECKBOX") return value === true ? "Yes" : "No";
if (type === "DATE") return formatDay(String(value));
- if (type === "SELECT") {
- return (
- options.find((option) => option.id === value)?.label ?? <EmptyCellValue />
- );
+ if (type === "USER") {
+ const user = users.get(String(value));
+ return user ? <OwnerCell owner={user} /> : <EmptyCellValue />;
}
if (type === "NUMBER") {
return <span className="tabular-nums">{String(value)}</span>;
@@ -38,8 +38,15 @@ export function useFieldColumns<Row extends WithFields>(
const query = useQuery(
trpc.fields.list.queryOptions({ entity, includeArchived: false }),
);
+ const users = useQuery(trpc.users.list.queryOptions());
const fields = query.data;
+ const members = users.data;
+
+ const byId = useMemo(
+ () => new Map((members ?? []).map((user) => [user.id, user])),
+ [members],
+ );
return useMemo(() => {
if (!fields) return [];
@@ -53,9 +60,9 @@ export function useFieldColumns<Row extends WithFields>(
hideBelow: "lg" as const,
cell: (row: Row) => (
<span className="truncate">
- {render(field.type, row.fields[field.key] ?? null, field.options)}
+ {render(field.type, row.fields[field.key] ?? null, byId)}
</span>
),
}));
- }, [fields]);
+ }, [fields, byId]);
}
diff --git a/apps/app/components/crm/fields/field-editor.tsx b/apps/app/components/crm/fields/field-editor.tsx
index f86d573c..35ac13df 100644
--- a/apps/app/components/crm/fields/field-editor.tsx
+++ b/apps/app/components/crm/fields/field-editor.tsx
@@ -49,6 +49,7 @@ import {
ADD_OPTION,
AGENT_HELP,
AGENT_LABEL,
+ ALL_FILLED,
ARCHIVE,
BRIEF_HELP,
BRIEF_LABEL,
@@ -58,12 +59,13 @@ import {
KEY_LABEL,
LABEL_LABEL,
OPTIONS_LABEL,
+ optionLabel,
SAVE,
sheetPlacement,
TYPE_LABEL,
tablePlacement,
} from "./fields-copy";
-import type { FieldEntity } from "./fields-entity";
+import { type FieldEntity, kindOf } from "./fields-entity";
const COVERAGE_NOUN: Record<FieldEntity, string> = {
COMPANY: "companies",
@@ -120,13 +122,17 @@ function draftFrom(field: FieldRecord | undefined): Draft {
function Coverage({ field }: { field: FieldRecord }) {
const trpc = useTRPC();
+ const cache = useCrmCache();
const coverage = useQuery(
trpc.fields.coverage.queryOptions({ id: field.id }),
);
const backfill = useMutation(
trpc.fields.backfill.mutationOptions({
- onSuccess: () => toast.success("Your agents will pick this up."),
+ onSuccess: async () => {
+ toast.success("Your agents will pick this up.");
+ await cache.fieldCoverage(field.id);
+ },
onError: (error) => toast.error(error.message),
}),
);
@@ -135,6 +141,7 @@ function Coverage({ field }: { field: FieldRecord }) {
const { filled, total } = coverage.data;
const noun = COVERAGE_NOUN[field.entity as FieldEntity];
+ const covered = filled >= total;
return (
<div className="shrink-0 border-t px-5 py-3">
@@ -146,13 +153,13 @@ function Coverage({ field }: { field: FieldRecord }) {
label={`Filled on ${filled} of ${total} ${noun}`}
/>
<span className="pl-4 text-muted-foreground text-xs">
- {total - filled} still to go
+ {covered ? ALL_FILLED : `${total - filled} still to go`}
</span>
</div>
<Button
variant="outline"
size="sm"
- disabled={backfill.isPending}
+ disabled={backfill.isPending || covered}
onClick={() => backfill.mutate({ id: field.id })}
>
{FILL_REST}
@@ -175,6 +182,9 @@ export function FieldEditor({
const cache = useCrmCache();
const labelId = useId();
const briefId = useId();
+ const agentId = useId();
+ const typeId = useId();
+ const optionsId = useId();
const [draft, setDraft] = useState<Draft>(() => draftFrom(field));
const [confirming, setConfirming] = useState(false);
@@ -183,7 +193,7 @@ export function FieldEditor({
setDraft((current) => ({ ...current, ...next }));
const settle = async () => {
- await cache.fields();
+ await cache.fields(kindOf(entity));
onDone();
};
@@ -257,10 +267,11 @@ export function FieldEditor({
<div className={SECTION}>
<Field orientation="horizontal">
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
- <FieldTitle>{AGENT_LABEL}</FieldTitle>
+ <FieldLabel htmlFor={agentId}>{AGENT_LABEL}</FieldLabel>
<FieldDescription>{AGENT_HELP}</FieldDescription>
</div>
<Switch
+ id={agentId}
checked={draft.agentFilled}
onCheckedChange={(agentFilled) => patch({ agentFilled })}
/>
@@ -280,12 +291,12 @@ export function FieldEditor({
<div className={SECTION}>
<Field>
- <FieldTitle>{TYPE_LABEL}</FieldTitle>
+ <FieldLabel htmlFor={typeId}>{TYPE_LABEL}</FieldLabel>
<Select
value={draft.type}
onValueChange={(value) => patch({ type: value as Draft["type"] })}
>
- <SelectTrigger className="w-full">
+ <SelectTrigger id={typeId} className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -299,8 +310,8 @@ export function FieldEditor({
</Field>
{draft.type === "SELECT" ? (
- <Field>
- <FieldTitle>{OPTIONS_LABEL}</FieldTitle>
+ <Field aria-labelledby={optionsId}>
+ <FieldTitle id={optionsId}>{OPTIONS_LABEL}</FieldTitle>
<SortableList
ids={draft.options.map(optionId)}
onReorder={(ids) =>
@@ -325,6 +336,7 @@ export function FieldEditor({
label={option.label || "option"}
>
<Input
+ aria-label={optionLabel(index)}
value={option.label}
onChange={(event) =>
patch({
@@ -348,7 +360,9 @@ export function FieldEditor({
}
>
<Icon icon={Close} />
- <span className="sr-only">Remove option</span>
+ <span className="sr-only">
+ Remove {optionLabel(index)}
+ </span>
</Button>
</SortableItem>
))}
diff --git a/apps/app/components/crm/fields/fields-copy.ts b/apps/app/components/crm/fields/fields-copy.ts
index 21a0a568..4c809845 100644
--- a/apps/app/components/crm/fields/fields-copy.ts
+++ b/apps/app/components/crm/fields/fields-copy.ts
@@ -28,6 +28,11 @@ export const EMPTY_TITLE = "No custom fields yet";
export const EMPTY_BODY =
"Create dynamic fields that your agents can research and pre-fill.";
+export const ERROR_TITLE = "We could not load your fields";
+export const ERROR_BODY =
+ "Your fields are still there. Try again in a moment, before you create anything new.";
+export const RETRY = "Try again";
+
export const LABEL_LABEL = "Label";
export const KEY_LABEL = "Key";
export const KEY_HELP =
@@ -41,6 +46,11 @@ export const BRIEF_HELP =
export const TYPE_LABEL = "Type";
export const OPTIONS_LABEL = "Options";
export const ADD_OPTION = "Add option";
+export const ALL_FILLED = "Nothing left to fill";
+
+export function optionLabel(index: number): string {
+ return `Option ${index + 1}`;
+}
export const ADD_FIELD = "Create field";
export const CANCEL = "Cancel";
export const SAVE = "Save changes";
diff --git a/apps/app/components/crm/fields/fields-list.tsx b/apps/app/components/crm/fields/fields-list.tsx
index a9e5da43..b4007e5c 100644
--- a/apps/app/components/crm/fields/fields-list.tsx
+++ b/apps/app/components/crm/fields/fields-list.tsx
@@ -3,6 +3,8 @@
import Add from "@carbon/icons-react/es/Add";
import ChevronRight from "@carbon/icons-react/es/ChevronRight";
import OverflowMenuVertical from "@carbon/icons-react/es/OverflowMenuVertical";
+import Renew from "@carbon/icons-react/es/Renew";
+import Warning from "@carbon/icons-react/es/Warning";
import { Badge } from "@crm/ui/components/badge";
import { Button } from "@crm/ui/components/button";
import {
@@ -40,14 +42,17 @@ import {
DRAG_NOTE,
EMPTY_BODY,
EMPTY_TITLE,
+ ERROR_BODY,
+ ERROR_TITLE,
MANUAL_ONLY,
NEW_FIELD,
ORDER_NOTE,
+ RETRY,
STANDARD_NOTE,
STANDARD_ROW,
TABLE_NOTE,
} from "./fields-copy";
-import type { FieldEntity } from "./fields-entity";
+import { type FieldEntity, kindOf } from "./fields-entity";
import { STANDARD_FIELDS } from "./standard-fields";
type Field = RouterOutputs["fields"]["list"][number];
@@ -123,21 +128,24 @@ export function FieldsList({
const reorder = useMutation(
trpc.fields.reorder.mutationOptions({
- onSuccess: () => cache.fields(),
- onError: (error) => toast.error(error.message),
+ onSuccess: () => cache.fields(kindOf(entity)),
+ onError: (error) => {
+ toast.error(error.message);
+ return cache.fields(kindOf(entity));
+ },
}),
);
const archive = useMutation(
trpc.fields.archive.mutationOptions({
- onSuccess: () => cache.fields(),
+ onSuccess: () => cache.fields(kindOf(entity)),
onError: (error) => toast.error(error.message),
}),
);
const restore = useMutation(
trpc.fields.restore.mutationOptions({
- onSuccess: () => cache.fields(),
+ onSuccess: () => cache.fields(kindOf(entity)),
onError: (error) => toast.error(error.message),
}),
);
@@ -170,84 +178,112 @@ export function FieldsList({
<div className="flex flex-1 items-center justify-center">
<Spinner />
</div>
- ) : live.length === 0 ? (
+ ) : query.isError ? (
<Empty className="flex-1">
<EmptyHeader>
<EmptyMedia variant="icon">
- <Icon icon={Add} />
+ <Icon icon={Warning} />
</EmptyMedia>
- <EmptyTitle>{EMPTY_TITLE}</EmptyTitle>
- <EmptyDescription>{EMPTY_BODY}</EmptyDescription>
+ <EmptyTitle>{ERROR_TITLE}</EmptyTitle>
+ <EmptyDescription>{ERROR_BODY}</EmptyDescription>
</EmptyHeader>
<EmptyContent>
- <Button onClick={onNew}>
- <Icon icon={Add} data-icon="inline-start" />
- {NEW_FIELD}
+ <Button
+ variant="outline"
+ disabled={query.isFetching}
+ onClick={() => query.refetch()}
+ >
+ <Icon icon={Renew} data-icon="inline-start" />
+ {RETRY}
</Button>
</EmptyContent>
</Empty>
) : (
<>
- <div className="flex items-center justify-between gap-3 px-5 pt-3.5 pb-2">
- <span className="font-medium text-muted-foreground text-xs uppercase tracking-wider">
- {CUSTOM_GROUP}
- </span>
- <span className="text-muted-foreground text-xs">{DRAG_NOTE}</span>
- </div>
+ {live.length === 0 ? (
+ <Empty className="flex-1">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <Icon icon={Add} />
+ </EmptyMedia>
+ <EmptyTitle>{EMPTY_TITLE}</EmptyTitle>
+ <EmptyDescription>{EMPTY_BODY}</EmptyDescription>
+ </EmptyHeader>
+ <EmptyContent>
+ <Button onClick={onNew}>
+ <Icon icon={Add} data-icon="inline-start" />
+ {NEW_FIELD}
+ </Button>
+ </EmptyContent>
+ </Empty>
+ ) : (
+ <>
+ <div className="flex items-center justify-between gap-3 px-5 pt-3.5 pb-2">
+ <span className="font-medium text-muted-foreground text-xs uppercase tracking-wider">
+ {CUSTOM_GROUP}
+ </span>
+ <span className="text-muted-foreground text-xs">
+ {DRAG_NOTE}
+ </span>
+ </div>
- <SortableList
- ids={live.map((field) => field.id)}
- onReorder={(ids) => reorder.mutate({ entity, ids })}
- >
- {live.map((field) => (
- <SortableItem
- key={field.id}
- id={field.id}
- label={field.label}
- className={ROW}
+ <SortableList
+ ids={live.map((field) => field.id)}
+ onReorder={(ids) => reorder.mutate({ entity, ids })}
>
- <button
- type="button"
- onClick={() => onEdit(field.key)}
- className="flex min-w-0 flex-1 flex-col gap-px text-left"
- >
- <span className="w-full truncate font-medium text-foreground text-xs">
- {field.label}
- </span>
- <span className="w-full truncate text-muted-foreground text-xs">
- {summaryOf(field)}
- </span>
- </button>
-
- <Badge
- variant="mono"
- className="w-18 shrink-0 justify-center"
- >
- {field.typeLabel}
- </Badge>
+ {live.map((field) => (
+ <SortableItem
+ key={field.id}
+ id={field.id}
+ label={field.label}
+ className={ROW}
+ >
+ <button
+ type="button"
+ onClick={() => onEdit(field.key)}
+ className="flex min-w-0 flex-1 flex-col gap-px text-left"
+ >
+ <span className="w-full truncate font-medium text-foreground text-xs">
+ {field.label}
+ </span>
+ <span className="w-full truncate text-muted-foreground text-xs">
+ {summaryOf(field)}
+ </span>
+ </button>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="icon-xs">
- <Icon icon={OverflowMenuVertical} />
- <span className="sr-only">More for {field.label}</span>
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem onSelect={() => onEdit(field.key)}>
- Edit
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onSelect={() => archive.mutate({ id: field.id })}
+ <Badge
+ variant="mono"
+ className="w-18 shrink-0 justify-center"
>
- Archive
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </SortableItem>
- ))}
- </SortableList>
+ {field.typeLabel}
+ </Badge>
+
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon-xs">
+ <Icon icon={OverflowMenuVertical} />
+ <span className="sr-only">
+ More for {field.label}
+ </span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onSelect={() => onEdit(field.key)}>
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => archive.mutate({ id: field.id })}
+ >
+ Archive
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </SortableItem>
+ ))}
+ </SortableList>
+ </>
+ )}
{archived.length > 0 ? (
<DisclosureRow
diff --git a/apps/app/components/crm/fields/record-fields.tsx b/apps/app/components/crm/fields/record-fields.tsx
index 7df27f74..a5cea083 100644
--- a/apps/app/components/crm/fields/record-fields.tsx
+++ b/apps/app/components/crm/fields/record-fields.tsx
@@ -1,6 +1,7 @@
"use client";
import Settings from "@carbon/icons-react/es/Settings";
+import type { FieldValueJson } from "@crm/db/fields";
import { Button } from "@crm/ui/components/button";
import { Checkbox } from "@crm/ui/components/checkbox";
import { Icon } from "@crm/ui/components/icon";
@@ -9,6 +10,7 @@ import {
TooltipContent,
TooltipTrigger,
} from "@crm/ui/components/tooltip";
+import { useQuery } from "@tanstack/react-query";
import {
InlineDateField,
InlineField,
@@ -20,8 +22,7 @@ import {
useFieldsSheet,
} from "@/components/crm/record-sheet/record-stack";
import { DetailSheetProperty } from "@/components/detail-sheet";
-
-type RecordFieldValue = string | number | boolean | null;
+import { useTRPC } from "@/lib/trpc/client";
type RecordFieldOption = { id: string; label: string };
@@ -32,11 +33,15 @@ export type RecordFieldEntry = {
type: string;
showOnSheet: boolean;
options: RecordFieldOption[];
- value: RecordFieldValue;
+ value: FieldValueJson;
};
const NONE = "__none__";
+const UNASSIGNED = "Unassigned";
+
+const FORMER_MEMBER = "Former member";
+
export function FieldsCog({ kind }: { kind: RecordKind }) {
const { open } = useFieldsSheet();
@@ -60,14 +65,34 @@ export function RecordFields({
}: {
fields: RecordFieldEntry[];
saving: (key: string) => boolean;
- onSave: (values: Record<string, unknown>) => void;
+ onSave: (values: Record<string, FieldValueJson>) => void;
}) {
+ const trpc = useTRPC();
+ const users = useQuery(trpc.users.list.queryOptions());
+
+ const userOptionsFor = (value: string) => {
+ const options = [
+ { value: NONE, label: UNASSIGNED },
+ ...(users.data ?? []).map((user) => ({
+ value: user.id,
+ label: user.name,
+ })),
+ ];
+
+ if (users.data && !options.some((option) => option.value === value)) {
+ options.push({ value, label: FORMER_MEMBER });
+ }
+
+ return options;
+ };
+
return (
<>
{fields
.filter((field) => field.showOnSheet)
.map((field) => {
- const save = (value: unknown) => onSave({ [field.key]: value });
+ const save = (value: FieldValueJson) =>
+ onSave({ [field.key]: value });
const busy = saving(field.key);
if (field.type === "CHECKBOX") {
@@ -120,6 +145,23 @@ export function RecordFields({
label: option.label,
})),
]}
+ saving={busy}
+ onSave={(next) => save(next === NONE ? null : next)}
+ />
+ );
+ }
+
+ if (field.type === "USER") {
+ const current = field.value === null ? NONE : String(field.value);
+
+ return (
+ <InlineSelectField
+ key={field.id}
+ label={field.label}
+ value={current}
+ options={userOptionsFor(current)}
+ placeholder={UNASSIGNED}
+ saving={busy}
onSave={(next) => save(next === NONE ? null : next)}
/>
);
diff --git a/apps/app/components/crm/inline-field.tsx b/apps/app/components/crm/inline-field.tsx
index 4123eacb..ba53c6e8 100644
--- a/apps/app/components/crm/inline-field.tsx
+++ b/apps/app/components/crm/inline-field.tsx
@@ -335,12 +335,14 @@ export function InlineSelectField({
value,
options,
onSave,
+ saving = false,
placeholder = "None",
}: {
label: string;
value: string;
options: { value: string; label: string }[];
onSave: (next: string) => void;
+ saving?: boolean;
placeholder?: string;
}) {
const id = useId();
@@ -350,18 +352,21 @@ export function InlineSelectField({
<label htmlFor={id} className={LABEL}>
{label}
</label>
- <Select value={value} onValueChange={onSave}>
- <SelectTrigger id={id} variant="ghost" className="w-full">
- <SelectValue placeholder={placeholder} />
- </SelectTrigger>
- <SelectContent>
- {options.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ <div className="flex min-w-0 items-center gap-1.5">
+ <Select value={value} onValueChange={onSave} disabled={saving}>
+ <SelectTrigger id={id} variant="ghost" className="w-full">
+ <SelectValue placeholder={placeholder} />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {saving ? <Spinner /> : null}
+ </div>
</div>
);
}
diff --git a/apps/app/components/crm/record-sheet/company-sheet.tsx b/apps/app/components/crm/record-sheet/company-sheet.tsx
index 09609639..93f559e6 100644
--- a/apps/app/components/crm/record-sheet/company-sheet.tsx
+++ b/apps/app/components/crm/record-sheet/company-sheet.tsx
@@ -5,6 +5,7 @@ import Partnership from "@carbon/icons-react/es/Partnership";
import Star from "@carbon/icons-react/es/Star";
import StarFilled from "@carbon/icons-react/es/StarFilled";
import UserMultiple from "@carbon/icons-react/es/UserMultiple";
+import type { FieldValueJson } from "@crm/db/fields";
import { Button } from "@crm/ui/components/button";
import { EmptyCellValue } from "@crm/ui/components/empty-cell";
import {
@@ -335,7 +336,7 @@ function CompanyOverview({
const save = (data: Record<string, string | null>) =>
update.mutate({ id: company.id, data });
- const saveFields = (fields: Record<string, unknown>) =>
+ const saveFields = (fields: Record<string, FieldValueJson>) =>
update.mutate({ id: company.id, data: { fields } });
const isSaving = savingField(update);
diff --git a/apps/app/components/crm/record-sheet/contact-sheet.tsx b/apps/app/components/crm/record-sheet/contact-sheet.tsx
index 0c87bcbc..423eed3d 100644
--- a/apps/app/components/crm/record-sheet/contact-sheet.tsx
+++ b/apps/app/components/crm/record-sheet/contact-sheet.tsx
@@ -3,6 +3,7 @@
import Email from "@carbon/icons-react/es/Email";
import Partnership from "@carbon/icons-react/es/Partnership";
import Star from "@carbon/icons-react/es/Star";
+import type { FieldValueJson } from "@crm/db/fields";
import {
Accordion,
AccordionContent,
@@ -307,7 +308,7 @@ function ContactOverview({ contact }: { contact: Contact }) {
}),
);
- const saveFields = (fields: Record<string, unknown>) =>
+ const saveFields = (fields: Record<string, FieldValueJson>) =>
update.mutate({ id: contact.id, data: { fields } });
const isSavingField = savingValue(update);
diff --git a/apps/app/components/crm/record-sheet/deal-sheet.tsx b/apps/app/components/crm/record-sheet/deal-sheet.tsx
index b6d2a321..eade930f 100644
--- a/apps/app/components/crm/record-sheet/deal-sheet.tsx
+++ b/apps/app/components/crm/record-sheet/deal-sheet.tsx
@@ -4,6 +4,7 @@ import Add from "@carbon/icons-react/es/Add";
import Close from "@carbon/icons-react/es/Close";
import UserMultiple from "@carbon/icons-react/es/UserMultiple";
import { CURRENCIES, normalizeCurrency } from "@crm/db/currency";
+import type { FieldValueJson } from "@crm/db/fields";
import { Button } from "@crm/ui/components/button";
import { EmptyCellValue } from "@crm/ui/components/empty-cell";
import {
@@ -256,7 +257,7 @@ function DealOverview({ deal }: { deal: Deal }) {
}),
);
- const saveFields = (fields: Record<string, unknown>) =>
+ const saveFields = (fields: Record<string, FieldValueJson>) =>
update.mutate({ id: deal.id, data: { fields } });
const isSavingField = savingValue(update);
diff --git a/apps/app/lib/agent-transcript.ts b/apps/app/lib/agent-transcript.ts
index 662a955f..360bacff 100644
--- a/apps/app/lib/agent-transcript.ts
+++ b/apps/app/lib/agent-transcript.ts
@@ -40,6 +40,10 @@ const VERBS: Record<string, string> = {
schedule_recheck: "Decided when to look again",
record_job_change: "Raised a job change",
list_outstanding_work: "Looked for outstanding work",
+ list_fields: "Read what this workspace tracks",
+ set_field_value: "Filled in a custom field",
+ manage_fields: "Changed what the CRM tracks",
+ archive_field: "Asked to retire a field",
load_skill: "Read its instructions for this",
web_search: "Searched the web",
diff --git a/apps/app/lib/trpc/cache.ts b/apps/app/lib/trpc/cache.ts
index faeb6f0e..bdf462e2 100644
--- a/apps/app/lib/trpc/cache.ts
+++ b/apps/app/lib/trpc/cache.ts
@@ -20,6 +20,7 @@ export type CrmCache = {
contact(id?: string, options?: Options): Promise<void>;
deal(id?: string, options?: Options): Promise<void>;
fields(entity?: RecordKind, options?: Options): Promise<void>;
+ fieldCoverage(id?: string, options?: Options): Promise<void>;
removed(record: RemovedRecord): Promise<void>;
removedMany(records: RemovedRecords): Promise<void>;
activity(options?: Options): Promise<void>;
@@ -105,16 +106,30 @@ export function useCrmCache(): CrmCache {
deal: () => trpc.deals.byId.queryKey(),
} as const;
+ const RECORD_LIST = {
+ company: () => trpc.companies.list.queryKey(),
+ contact: () => trpc.contacts.list.queryKey(),
+ deal: () => trpc.deals.list.queryKey(),
+ } as const;
+
return {
fields: (entity, options) =>
run(
[trpc.fields.list.queryKey()],
+ entity
+ ? [RECORD_BY_ID[entity](), RECORD_LIST[entity]()]
+ : [...Object.values(RECORD_BY_ID).map((key) => key()), ...listKeys()],
+ options,
+ ),
+
+ fieldCoverage: (id, options) =>
+ run(
[
- ...(entity
- ? [RECORD_BY_ID[entity]()]
- : Object.values(RECORD_BY_ID).map((key) => key())),
- ...listKeys(),
+ id
+ ? trpc.fields.coverage.queryKey({ id })
+ : trpc.fields.coverage.queryKey(),
],
+ [],
options,
),
diff --git a/docs/plan/dynamic-fields-build.md b/docs/plan/dynamic-fields-build.md
index 4f589eba..d50b1174 100644
--- a/docs/plan/dynamic-fields-build.md
+++ b/docs/plan/dynamic-fields-build.md
@@ -172,10 +172,17 @@ Two params, added to the **existing shared parser object** in
parser file:
```ts
-fields: parseAsStringLiteral(RECORD_KINDS), // which entity's fields are open
-field: parseAsString, // "new" | a field key
+fields: parseAsStringLiteral(RECORD_KINDS),
+field: parseAsString,
```
+- `fields` is the entity whose fields are open; `field` is either the create
+ sentinel `new` or a field key. Add nothing else to the pasted lines — AGENTS.md
+ forbids code comments, and these go straight into `record-stack.ts`.
+- **`new` is a reserved key**, held back by `RESERVED_KEYS` in
+ `packages/db/src/fields-shape.ts`, so a field labelled *New* slugs to
+ `new_field` and its editor can still be opened. Never let the sentinel and a
+ derivable key collide.
- Both cleared by the existing `write()` alongside `tab`, `add`, `thread`.
- `useQueryStates` for the pair; `null` to clear; `history: "replace"` for sheet
state, matching what `record-stack.ts` already does.
diff --git a/docs/plan/dynamic-fields.md b/docs/plan/dynamic-fields.md
index 669673c5..40b1f584 100644
--- a/docs/plan/dynamic-fields.md
+++ b/docs/plan/dynamic-fields.md
@@ -127,6 +127,7 @@ model FieldValue {
optionId String?
option FieldOption? @relation(fields: [optionId], references: [id], onDelete: SetNull)
userId String?
+ user User? @relation("FieldValueUser", fields: [userId], references: [id], onDelete: SetNull)
updatedAt DateTime @updatedAt
@@ -136,11 +137,22 @@ model FieldValue {
@@index([fieldId, text])
@@index([fieldId, number])
@@index([fieldId, date])
+ @@index([companyId])
+ @@index([contactId])
+ @@index([dealId])
+ @@index([optionId])
+ @@index([userId])
@@map("fieldValue")
}
```
-Four decisions worth defending:
+`User` carries the other half of that relation:
+
+```prisma
+fieldValues FieldValue[] @relation("FieldValueUser")
+```
+
+Six decisions worth defending:
- **Typed columns, not a `Json` value.** `api.md` says filter, sort and paginate
in Prisma. A JSON blob cannot be indexed or ordered honestly, and the moment
@@ -157,6 +169,15 @@ Four decisions worth defending:
- **`key` is immutable, `label` is not.** The key is what the API and the agents
say; the label is what the rep reads. Renaming the label of a field an agent
has filled for a month cannot break the brief that taught it.
+- **The record columns are indexed on their own, not only inside the uniques.**
+ A record read is `where: { companyId }` with no `fieldId` —
+ `FieldsService.valuesFor` opens every sheet that way — and a unique starting
+ `fieldId` cannot serve it. The composite uniques stay for the one-value-per-
+ field-per-record rule; the standalone indexes are what the reads use.
+- **`userId` is a foreign key, like every other id on the row.** A `USER` field
+ holds a workspace user, so a deleted rep must not leave an id on the record
+ that resolves to nobody. `SetNull` matches `Company.owner` and
+ `Contact.owner`: the value empties, and it never blocks the delete.
**Archive, not delete.** A record delete is hard in this CRM by design, but a
*definition* delete destroys a column of typed data across every record at once.
diff --git a/packages/db/prisma/migrations/20260806150000_field_value_record_indexes_and_user_fk/migration.sql b/packages/db/prisma/migrations/20260806150000_field_value_record_indexes_and_user_fk/migration.sql
new file mode 100644
index 00000000..b5307323
--- /dev/null
+++ b/packages/db/prisma/migrations/20260806150000_field_value_record_indexes_and_user_fk/migration.sql
@@ -0,0 +1,18 @@
+-- CreateIndex
+CREATE INDEX "fieldValue_companyId_idx" ON "fieldValue"("companyId");
+
+-- CreateIndex
+CREATE INDEX "fieldValue_contactId_idx" ON "fieldValue"("contactId");
+
+-- CreateIndex
+CREATE INDEX "fieldValue_dealId_idx" ON "fieldValue"("dealId");
+
+-- CreateIndex
+CREATE INDEX "fieldValue_userId_idx" ON "fieldValue"("userId");
+
+UPDATE "fieldValue" SET "userId" = NULL
+WHERE "userId" IS NOT NULL
+ AND "userId" NOT IN (SELECT "id" FROM "user");
+
+-- AddForeignKey
+ALTER TABLE "fieldValue" ADD CONSTRAINT "fieldValue_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE SET NULL ON UPDATE CASCADE;
diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma
index bd139517..13b6579d 100644
--- a/packages/db/prisma/schema.prisma
+++ b/packages/db/prisma/schema.prisma
@@ -29,6 +29,7 @@ model User {
mailboxSyncs MailboxSync[]
factDecisions ContactFact[] @relation("FactDecider")
conversations AgentConversation[] @relation("ConversationOwner")
+ fieldValues FieldValue[] @relation("FieldValueUser")
members Member[]
invitations Invitation[]
@@ -534,6 +535,7 @@ model FieldValue {
optionId String?
option FieldOption? @relation(fields: [optionId], references: [id], onDelete: SetNull)
userId String?
+ user User? @relation("FieldValueUser", fields: [userId], references: [id], onDelete: SetNull)
updatedAt DateTime @updatedAt
@@ -543,7 +545,11 @@ model FieldValue {
@@index([fieldId, text])
@@index([fieldId, number])
@@index([fieldId, date])
+ @@index([companyId])
+ @@index([contactId])
+ @@index([dealId])
@@index([optionId])
+ @@index([userId])
@@map("fieldValue")
}
diff --git a/packages/db/src/fields-shape.ts b/packages/db/src/fields-shape.ts
index 3172f6b4..95c51095 100644
--- a/packages/db/src/fields-shape.ts
+++ b/packages/db/src/fields-shape.ts
@@ -83,6 +83,7 @@ const RESERVED_KEYS = new Set([
"fields",
"owner",
"ownerid",
+ "new",
]);
export function fieldKeyFromLabel(label: string): string {
diff --git a/packages/db/src/fields.ts b/packages/db/src/fields.ts
index 1aa53a7e..fcfc3b64 100644
--- a/packages/db/src/fields.ts
+++ b/packages/db/src/fields.ts
@@ -71,7 +71,30 @@ export function serializeField(
};
}
+export function serializeFieldFor(
+ definition: FieldDefinitionWithOptions,
+ value: FieldValueJson,
+): SerializedField {
+ const field = serializeField(definition);
+
+ if (definition.type !== "SELECT" || typeof value !== "string") return field;
+ if (field.options.some((option) => option.id === value)) return field;
+
+ const retired = definition.options.find((option) => option.id === value);
+ if (!retired) return field;
+
+ return {
+ ...field,
+ options: [
+ ...field.options,
+ { id: retired.id, label: retired.label, position: retired.position },
+ ].sort((left, right) => left.position - right.position),
+ };
+}
+
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
+const ISO_DATE_TIME =
+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?(Z|[+-]\d{2}:\d{2})?$/;
export function coerceValue(
definition: FieldDefinitionWithOptions,
@@ -121,14 +144,21 @@ export function coerceValue(
case "DATE": {
const raw = String(input).trim();
- const parsed = ISO_DATE.test(raw)
- ? new Date(`${raw}T00:00:00.000Z`)
- : new Date(raw);
+ const dateOnly = ISO_DATE.test(raw);
+
+ if (!dateOnly && !ISO_DATE_TIME.test(raw)) {
+ throw new FieldValueError(
+ definition.key,
+ `${definition.label} takes a date like 2027-03-31.`,
+ );
+ }
+
+ const parsed = new Date(dateOnly ? `${raw}T00:00:00.000Z` : raw);
if (Number.isNaN(parsed.getTime())) {
throw new FieldValueError(
definition.key,
- `${definition.label} takes a date.`,
+ `${definition.label} takes a date like 2027-03-31.`,
);
}
@@ -194,10 +224,11 @@ export function attachValues(
return definitions
.filter((definition) => definition.archivedAt === null)
.sort((left, right) => left.position - right.position)
- .map((definition) => ({
- ...serializeField(definition),
- value: readValue(definition, byField.get(definition.id)),
- }));
+ .map((definition) => {
+ const value = readValue(definition, byField.get(definition.id));
+
+ return { ...serializeFieldFor(definition, value), value };
+ });
}
export type FieldWriter = {
@@ -209,6 +240,12 @@ export type FieldWriter = {
update: Record<string, unknown>;
}): Promise<unknown>;
};
+ user: {
+ findMany(args: {
+ where: { id: { in: string[] } };
+ select: { id: true };
+ }): Promise<{ id: string }[]>;
+ };
};
export async function writeValues(
@@ -225,7 +262,7 @@ export async function writeValues(
.map((definition) => [definition.key, definition]),
);
- for (const [key, input] of Object.entries(values)) {
+ const writes = Object.entries(values).map(([key, input]) => {
const definition = byKey.get(key);
if (!definition) {
@@ -233,8 +270,13 @@ export async function writeValues(
}
const data = coerceValue(definition, input);
- const stored = data[columnFor(definition.type)];
+ return { definition, data, stored: data[columnFor(definition.type)] };
+ });
+
+ await assertUsersExist(tx, writes);
+
+ for (const { definition, data, stored } of writes) {
if (stored === null || stored === undefined) {
await tx.fieldValue.deleteMany({
where: { fieldId: definition.id, [column]: recordId },
@@ -251,3 +293,36 @@ export async function writeValues(
});
}
}
+
+type PendingWrite = {
+ definition: FieldDefinitionWithOptions;
+ stored: unknown;
+};
+
+async function assertUsersExist(
+ tx: FieldWriter,
+ writes: PendingWrite[],
+): Promise<void> {
+ const wanted = writes.filter(
+ (write): write is PendingWrite & { stored: string } =>
+ write.definition.type === "USER" && typeof write.stored === "string",
+ );
+
+ if (wanted.length === 0) return;
+
+ const known = await tx.user.findMany({
+ where: { id: { in: [...new Set(wanted.map((write) => write.stored))] } },
+ select: { id: true },
+ });
+
+ const found = new Set(known.map((row) => row.id));
+
+ for (const write of wanted) {
+ if (!found.has(write.stored)) {
+ throw new FieldValueError(
+ write.definition.key,
+ `${write.definition.label} takes someone who works here.`,
+ );
+ }
+ }
+}
diff --git a/packages/db/test/fields.spec.ts b/packages/db/test/fields.spec.ts
index 3b387260..a5e6b92e 100644
--- a/packages/db/test/fields.spec.ts
+++ b/packages/db/test/fields.spec.ts
@@ -68,6 +68,10 @@ describe("fieldKeyFromLabel", () => {
expect(fieldKeyFromLabel("id")).toBe("id_field");
expect(fieldKeyFromLabel("Owner")).toBe("owner_field");
});
+
+ it("steps around the sentinel the fields sheet opens the create form with", () => {
+ expect(fieldKeyFromLabel("New")).toBe("new_field");
+ });
});
describe("columnFor", () => {
diff --git a/packages/ui/src/components/sortable-list.tsx b/packages/ui/src/components/sortable-list.tsx
index 7deef0a2..a691c2dd 100644
--- a/packages/ui/src/components/sortable-list.tsx
+++ b/packages/ui/src/components/sortable-list.tsx
@@ -22,11 +22,28 @@ import {
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
-import type { ReactNode } from "react";
+import { Children, type ReactNode, useState } from "react";
import { Button } from "@crm/ui/components/button";
import { Icon } from "@crm/ui/components/icon";
import { cn } from "@crm/ui/lib/utils";
+function inOrder(
+ children: ReactNode,
+ ids: string[],
+ order: string[],
+): ReactNode {
+ const slots = Children.toArray(children);
+ if (slots.length !== ids.length) return children;
+
+ const arranged: ReactNode[] = [];
+ for (const id of order) {
+ const at = ids.indexOf(id);
+ if (at === -1) return children;
+ arranged.push(slots[at]);
+ }
+ return arranged;
+}
+
export function SortableList({
ids,
onReorder,
@@ -36,6 +53,17 @@ export function SortableList({
onReorder: (ids: string[]) => void;
children: ReactNode;
}) {
+ const propKey = ids.join(" ");
+ const [syncedKey, setSyncedKey] = useState(propKey);
+ const [dragged, setDragged] = useState(ids);
+
+ let order = dragged;
+ if (syncedKey !== propKey) {
+ setSyncedKey(propKey);
+ setDragged(ids);
+ order = ids;
+ }
+
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
useSensor(KeyboardSensor, {
@@ -47,11 +75,13 @@ export function SortableList({
const { active, over } = event;
if (!over || active.id === over.id) return;
- const from = ids.indexOf(String(active.id));
- const to = ids.indexOf(String(over.id));
+ const from = order.indexOf(String(active.id));
+ const to = order.indexOf(String(over.id));
if (from === -1 || to === -1) return;
- onReorder(arrayMove(ids, from, to));
+ const next = arrayMove(order, from, to);
+ setDragged(next);
+ onReorder(next);
};
return (
@@ -61,8 +91,8 @@ export function SortableList({
modifiers={[restrictToVerticalAxis, restrictToParentElement]}
onDragEnd={onDragEnd}
>
- <SortableContext items={ids} strategy={verticalListSortingStrategy}>
- {children}
+ <SortableContext items={order} strategy={verticalListSortingStrategy}>
+ {inOrder(children, ids, order)}
</SortableContext>
</DndContext>
);
@@ -101,6 +131,7 @@ export function SortableItem({
>
<Button
ref={setActivatorNodeRef}
+ type="button"
variant="ghost"
size="icon-xs"
className="cursor-grab text-muted-foreground"
diff --git a/packages/ui/src/hooks/use-table-selection.ts b/packages/ui/src/hooks/use-table-selection.ts
index fb2a8bbe..bd8dc7f2 100644
--- a/packages/ui/src/hooks/use-table-selection.ts
+++ b/packages/ui/src/hooks/use-table-selection.ts
@@ -17,6 +17,18 @@ export type TableSelection = {
export function useTableSelection(rowIds: string[]): TableSelection {
const [picked, setPicked] = useState<ReadonlySet<string>>(EMPTY);
+ const pageKey = rowIds.join(" ");
+ const [syncedKey, setSyncedKey] = useState(pageKey);
+
+ if (syncedKey !== pageKey) {
+ setSyncedKey(pageKey);
+ setPicked((prev) => {
+ if (prev.size === 0) return prev;
+ const next = new Set<string>();
+ for (const id of rowIds) if (prev.has(id)) next.add(id);
+ return next.size === prev.size ? prev : next;
+ });
+ }
const ids = useMemo(
() => rowIds.filter((id) => picked.has(id)),