Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
Lewis/contact and currencies (#56)
Lewis Carhartc04e4b2e9ea0
diff --git a/README.md b/README.mdindex 4a43086b..43744443 100644--- a/README.md+++ b/README.md@@ -14,8 +14,8 @@<h1 align="center">CRM</h1><p align="center">- <strong>An open-source, agentic-first CRM.</strong><br>- A durable research agent is the product. The database is just where it writes things down.+ <strong>Comp AI CRM is an open source, CRM designed for AI agents.</strong><br>+ Agentic-first CRM.</p><p align="center">diff --git a/apps/agent/agent/lib/fields.ts b/apps/agent/agent/lib/fields.tsnew file mode 100644index 00000000..39d2b97d--- /dev/null+++ b/apps/agent/agent/lib/fields.ts@@ -0,0 +1,200 @@+import { db } from "@crm/db";+import type { FieldEntity, FieldType } from "@crm/db/enums";+import {+ attachValues,+ type FieldDefinitionWithOptions,+ FieldValueError,+ fieldKeyFromLabel,+ type RecordField,+ recordColumn,+ type SerializedField,+ serializeField,+ usesOptions,+ writeValues,+} from "@crm/db/fields";++const WITH_OPTIONS = { options: { orderBy: { position: "asc" } } } as const;++export type { FieldEntity, FieldType, RecordField, SerializedField };++async function definitionsFor(+ entity: FieldEntity,+): Promise<FieldDefinitionWithOptions[]> {+ return db.fieldDefinition.findMany({+ where: { entity, archivedAt: null },+ include: WITH_OPTIONS,+ orderBy: { position: "asc" },+ });+}++export async function listFields(+ entity: FieldEntity,+): Promise<SerializedField[]> {+ const definitions = await definitionsFor(entity);+ return definitions.map(serializeField);+}++export async function readFields(+ entity: FieldEntity,+ recordId: string,+): Promise<RecordField[]> {+ const column = recordColumn(entity);++ const [definitions, rows] = await Promise.all([+ definitionsFor(entity),+ db.fieldValue.findMany({ where: { [column]: recordId } }),+ ]);++ return attachValues(definitions, rows);+}++export type WriteResult =+ | { written: true; key: string; value: unknown }+ | { written: false; reason: string };++export async function writeField(input: {+ entity: FieldEntity;+ recordId: string;+ key: string;+ value: unknown;+}): Promise<WriteResult> {+ const definitions = await definitionsFor(input.entity);+ const definition = definitions.find((entry) => entry.key === input.key);++ if (!definition) {+ return {+ written: false,+ reason: `There is no field called "${input.key}" on ${input.entity.toLowerCase()}s. Call list_fields to see what exists.`,+ };+ }++ if (!definition.agentFilled) {+ return {+ written: false,+ reason: `"${input.key}" is marked manual only, so a rep keeps it by hand.`,+ };+ }++ try {+ await writeValues(db, input.entity, input.recordId, definitions, {+ [input.key]: input.value,+ });+ } catch (error) {+ if (error instanceof FieldValueError) {+ return { written: false, reason: error.message };+ }++ throw error;+ }++ return { written: true, key: input.key, value: input.value };+}++export async function createField(input: {+ entity: FieldEntity;+ label: string;+ type: FieldType;+ options?: string[];+ agentBrief?: string;+}): Promise<SerializedField | { created: false; reason: string }> {+ const key = fieldKeyFromLabel(input.label);++ if (!key) {+ return { created: false, reason: "That label does not make a usable key." };+ }++ const taken = await db.fieldDefinition.findUnique({+ where: { entity_key: { entity: input.entity, key } },+ select: { id: true },+ });++ if (taken) {+ return {+ created: false,+ reason: `There is already a field called "${key}" on ${input.entity.toLowerCase()}s.`,+ };+ }++ if (usesOptions(input.type) && (input.options ?? []).length === 0) {+ return { created: false, reason: "A select needs at least one option." };+ }++ const last = await db.fieldDefinition.findFirst({+ where: { entity: input.entity },+ orderBy: { position: "desc" },+ select: { position: true },+ });++ const definition = await db.fieldDefinition.create({+ data: {+ entity: input.entity,+ key,+ label: input.label,+ type: input.type,+ agentBrief: input.agentBrief ?? null,+ position: (last?.position ?? -1) + 1,+ options: usesOptions(input.type)+ ? {+ create: (input.options ?? []).map((label, index) => ({+ label,+ position: index,+ })),+ }+ : undefined,+ },+ include: WITH_OPTIONS,+ });++ return serializeField(definition);+}++export async function updateFieldBrief(input: {+ entity: FieldEntity;+ key: string;+ agentBrief: string | null;+ agentFilled?: boolean;+}): Promise<SerializedField | { updated: false; reason: string }> {+ const existing = await db.fieldDefinition.findUnique({+ where: { entity_key: { entity: input.entity, key: input.key } },+ select: { id: true },+ });++ if (!existing) {+ return {+ updated: false,+ reason: `There is no field called "${input.key}".`,+ };+ }++ const definition = await db.fieldDefinition.update({+ where: { id: existing.id },+ data: { agentBrief: input.agentBrief, agentFilled: input.agentFilled },+ include: WITH_OPTIONS,+ });++ return serializeField(definition);+}++export async function archiveField(input: {+ entity: FieldEntity;+ key: string;+}): Promise<{ archived: boolean; reason?: string }> {+ const existing = await db.fieldDefinition.findUnique({+ where: { entity_key: { entity: input.entity, key: input.key } },+ select: { id: true },+ });++ if (!existing) {+ return {+ archived: false,+ reason: `There is no field called "${input.key}".`,+ };+ }++ await db.fieldDefinition.update({+ where: { id: existing.id },+ data: { archivedAt: new Date() },+ });++ return { archived: true };+}diff --git a/apps/agent/agent/tools/archive_field.ts b/apps/agent/agent/tools/archive_field.tsnew file mode 100644index 00000000..a4326527--- /dev/null+++ b/apps/agent/agent/tools/archive_field.ts@@ -0,0 +1,19 @@+import { defineTool } from "eve/tools";+import { z } from "zod";+import { sensitiveWrite } from "../lib/approval";+import { archiveField } from "../lib/fields";++export default defineTool({+ description:+ "Archive a custom field. It leaves every sheet and table and stops being filled; the values already recorded are kept. A schema change every rep will see, so it needs a person.",+ inputSchema: z.object({+ entity: z.enum(["COMPANY", "CONTACT", "DEAL"]),+ key: z.string().describe("The field's key, as list_fields reports it."),+ }),+ approval: sensitiveWrite(+ "Say which field you would archive and let a rep do it from the Fields sheet.",+ ),+ async execute(input) {+ return archiveField(input);+ },+});diff --git a/apps/agent/agent/tools/list_fields.ts b/apps/agent/agent/tools/list_fields.tsnew file mode 100644index 00000000..669f40ae--- /dev/null+++ b/apps/agent/agent/tools/list_fields.ts@@ -0,0 +1,31 @@+import { defineTool } from "eve/tools";+import { z } from "zod";+import { listFields } from "../lib/fields";++export default defineTool({+ description:+ "List the custom fields a workspace has added to companies, contacts or deals — their key, type, options, and the brief saying what would count as an answer. Free. Read this before setting any custom value, and before telling a rep a field does not exist.",+ inputSchema: z.object({+ entity: z+ .enum(["COMPANY", "CONTACT", "DEAL"])+ .describe("Which record type the fields belong to."),+ }),+ async execute({ entity }) {+ const fields = await listFields(entity);++ return {+ fields: fields.map((field) => ({+ key: field.key,+ label: field.label,+ type: field.type,+ agentFilled: field.agentFilled,+ brief: field.agentBrief,+ options: field.options.map((option) => option.label),+ })),+ note:+ fields.length === 0+ ? "This workspace has no custom fields on this record type yet."+ : "Fields marked agentFilled false are the rep's to keep — do not write to them.",+ };+ },+});diff --git a/apps/agent/agent/tools/manage_fields.ts b/apps/agent/agent/tools/manage_fields.tsnew file mode 100644index 00000000..0eb2d562--- /dev/null+++ b/apps/agent/agent/tools/manage_fields.ts@@ -0,0 +1,81 @@+import { defineTool } from "eve/tools";+import { z } from "zod";+import { createField, updateFieldBrief } from "../lib/fields";++export default defineTool({+ description:+ "Add a custom field to a record type, or change what a field's brief tells you to look for. Use it when a rep asks the CRM to start tracking something it has no field for. The brief is the whole instruction you will be working from later, so write it the way you would want to read it.",+ inputSchema: z.object({+ action: z.enum(["create", "update-brief"]),+ entity: z.enum(["COMPANY", "CONTACT", "DEAL"]),+ label: z+ .string()+ .optional()+ .describe("What a rep should see. Required when creating."),+ key: z+ .string()+ .optional()+ .describe("Which field to change. Required when updating a brief."),+ type: z+ .enum([+ "TEXT",+ "LONG_TEXT",+ "NUMBER",+ "DATE",+ "CHECKBOX",+ "SELECT",+ "URL",+ "EMAIL",+ "PHONE",+ "USER",+ ])+ .optional()+ .describe("Required when creating."),+ options: z+ .array(z.string())+ .optional()+ .describe("The fixed list, when the type is SELECT."),+ agentBrief: z+ .string()+ .optional()+ .describe(+ "What would count as an answer, and where to look. Empty means you work from the label and type alone.",+ ),+ agentFilled: z+ .boolean()+ .optional()+ .describe("False hands the field back to the rep entirely."),+ }),+ async execute(input) {+ if (input.action === "create") {+ if (!input.label || !input.type) {+ return {+ created: false,+ reason: "Creating a field needs both a label and a type.",+ };+ }++ return createField({+ entity: input.entity,+ label: input.label,+ type: input.type,+ options: input.options,+ agentBrief: input.agentBrief,+ });+ }++ if (!input.key) {+ return {+ updated: false,+ reason: "Changing a brief needs the field key.",+ };+ }++ return updateFieldBrief({+ entity: input.entity,+ key: input.key,+ agentBrief: input.agentBrief ?? null,+ agentFilled: input.agentFilled,+ });+ },+});diff --git a/apps/agent/agent/tools/set_field_value.ts b/apps/agent/agent/tools/set_field_value.tsnew file mode 100644index 00000000..ccccd23a--- /dev/null+++ b/apps/agent/agent/tools/set_field_value.ts@@ -0,0 +1,27 @@+import { defineTool } from "eve/tools";+import { z } from "zod";+import { writeField } from "../lib/fields";+import { focusOn } from "../lib/focus";++export default defineTool({+ description:+ "Set one custom field on one record, when you have read the answer from a source rather than guessed it. The field's brief says what would count — follow it. Call list_fields first if you do not know the key. A field the rep marked manual will refuse.",+ inputSchema: z.object({+ entity: z.enum(["COMPANY", "CONTACT", "DEAL"]),+ recordId: z.string().describe("The id of the company, contact or deal."),+ key: z+ .string()+ .describe("The field's key, exactly as list_fields reports it."),+ value: z+ .union([z.string(), z.number(), z.boolean(), z.null()])+ .describe(+ "The value. A select takes the option's label, a date takes YYYY-MM-DD, and null clears it.",+ ),+ }),+ async execute({ entity, recordId, key, value }) {+ if (entity === "COMPANY") focusOn({ companyId: recordId });+ if (entity === "CONTACT") focusOn({ contactId: recordId });++ return writeField({ entity, recordId, key, value });+ },+});diff --git a/apps/api/src/agent/agent-trigger.service.ts b/apps/api/src/agent/agent-trigger.service.tsindex e82b6d23..df8eca6e 100644--- a/apps/api/src/agent/agent-trigger.service.ts+++ b/apps/api/src/agent/agent-trigger.service.ts@@ -70,6 +70,44 @@ export class AgentTriggerService {});}+ async fieldBackfill(key: string, reason: string): Promise<void> {+ try {+ const pending = await this.db.agentTask.findFirst({+ where: {+ kind: "field-backfill",+ finishedAt: null,+ reason: { startsWith: `${key}: ` },+ },+ select: { id: true },+ });++ if (pending) return;++ await this.db.agentTask.create({+ data: {+ kind: "field-backfill",+ reason: `${key}: ${reason}`,+ priority: PRIORITY.fieldBackfill,+ budget: 8,+ dueAt: new Date(),+ },+ });++ this.logger.log({+ message: "Agent task queued",+ kind: "field-backfill",+ key,+ });++ this.poke();+ } catch (error) {+ this.logger.error(+ { message: "Could not queue agent task", kind: "field-backfill", key },+ error instanceof Error ? error.stack : String(error),+ );+ }+ }+async meetingSoon(contactId: string, when: Date): Promise<void> {await this.enqueue({contactId,diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.tsindex 4b7b31d7..7487b45f 100644--- a/apps/api/src/app.module.ts+++ b/apps/api/src/app.module.ts@@ -15,6 +15,7 @@ import { CurrencyModule } from "./currency/currency.module";import { DashboardModule } from "./dashboard/dashboard.module";import { DatabaseModule } from "./database/database.module";import { DealsModule } from "./deals/deals.module";+import { FieldsModule } from "./fields/fields.module";import { GoogleModule } from "./google/google.module";import { HealthModule } from "./health/health.module";import { LoggingModule } from "./logging/logging.module";@@ -48,6 +49,7 @@ import { WorkspaceModule } from "./workspace/workspace.module";ConversationsModule,CurrencyModule,DealsModule,+ FieldsModule,ActivitiesModule,DashboardModule,SearchModule,diff --git a/apps/api/src/companies/companies.contracts.ts b/apps/api/src/companies/companies.contracts.tsindex de7d8b45..bbd3b67b 100644--- a/apps/api/src/companies/companies.contracts.ts+++ b/apps/api/src/companies/companies.contracts.ts@@ -1,4 +1,6 @@import { z } from "zod";+import { bulkIdsInput } from "../crm/bulk";+import { recordFieldValues } from "../fields/fields.contracts";import { listInput } from "../trpc/list-input";export const companyListInput = listInput.extend({@@ -31,6 +33,7 @@ const companyUpdateInput = z.object({email: z.string().optional(),linkedinUrl: z.string().optional(),ownerId: z.string().nullable().optional(),+ fields: recordFieldValues.optional(),});export type CompanyUpdateInput = z.infer<typeof companyUpdateInput>;@@ -50,3 +53,11 @@ export const setPrimaryContactInput = z.object({export const companyOptionsInput = z.object({q: z.string().default(""),});++export const companyBulkInput = bulkIdsInput;++export const companyBulkOwnerInput = bulkIdsInput.extend({+ ownerId: z.string().nullable(),+});++export type CompanyBulkOwnerInput = z.infer<typeof companyBulkOwnerInput>;diff --git a/apps/api/src/companies/companies.module.ts b/apps/api/src/companies/companies.module.tsindex 40625ecb..6d1d0c7e 100644--- a/apps/api/src/companies/companies.module.ts+++ b/apps/api/src/companies/companies.module.ts@@ -1,6 +1,7 @@import { Module } from "@nestjs/common";import { AgentModule } from "../agent/agent.module";import { CurrencyModule } from "../currency/currency.module";+import { FieldsModule } from "../fields/fields.module";import { TrpcModule } from "../trpc/trpc.module";import { CompaniesRouter } from "./companies.router";import { CompaniesService } from "./companies.service";@@ -8,7 +9,7 @@ import { CompanyDirectoryService } from "./company-directory.service";import { FaviconService } from "./favicon.service";@Module({- imports: [TrpcModule, AgentModule, CurrencyModule],+ imports: [FieldsModule, TrpcModule, AgentModule, CurrencyModule],providers: [CompaniesService,CompanyDirectoryService,diff --git a/apps/api/src/companies/companies.router.ts b/apps/api/src/companies/companies.router.tsindex d7d29a9d..42f0c68f 100644--- a/apps/api/src/companies/companies.router.ts+++ b/apps/api/src/companies/companies.router.ts@@ -11,6 +11,8 @@ import type { z } from "zod";import type { AuthedTrpcContext } from "../trpc/context.types";import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";import {+ companyBulkInput,+ companyBulkOwnerInput,companyCreateInput,companyIdInput,companyListInput,@@ -57,6 +59,21 @@ export class CompaniesRouter {return this.companies.delete(id);}+ @Mutation({ input: companyBulkOwnerInput })+ async bulkAssignOwner(@Input() input: z.infer<typeof companyBulkOwnerInput>) {+ return this.companies.bulkAssignOwner(input);+ }++ @Mutation({ input: companyBulkInput })+ async bulkEnrich(@Input("ids") ids: string[]) {+ return this.companies.bulkEnrich(ids);+ }++ @Mutation({ input: companyBulkInput })+ async bulkDelete(@Input("ids") ids: string[]) {+ return this.companies.bulkDelete(ids);+ }+@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 df589aa9..198e2344 100644--- a/apps/api/src/companies/companies.service.ts+++ b/apps/api/src/companies/companies.service.ts@@ -18,10 +18,12 @@ import {ActivityStampService,type StampTargets,} from "../crm/activity-stamp.service";+import { type BulkResult, requireOwner, runBulk } from "../crm/bulk";import { blankToNull, toCents } from "../crm/values";import { ConversionService } from "../currency/conversion.service";import { InjectDatabase } from "../database/database.constants";import { OPEN_DEAL_STAGES } from "../deals/deal-stage";+import { FieldsService } from "../fields/fields.service";import {countsByKey,FACET_ALL,@@ -32,6 +34,7 @@ import {resolveOrderBy,} from "../trpc/list-input";import type {+ CompanyBulkOwnerInput,CompanyCreateInput,CompanyListInput,CompanyUpdateInput,@@ -69,6 +72,7 @@ export type CompanyRow = {openDealCount: number;lastActivityAt: string | null;createdAt: string;+ fields: Record<string, string | number | boolean | null>;};const SORTABLE: Record<@@ -96,6 +100,7 @@ export class CompaniesService {private readonly favicon: FaviconService,private readonly stamp: ActivityStampService,private readonly conversion: ConversionService,+ private readonly fields: FieldsService,) {}async list(input: CompanyListInput): Promise<ListResult<CompanyRow>> {@@ -137,7 +142,11 @@ export class CompaniesService {this.facetCounts(input),]);- const queued = await this.queue.queuedCompanies(rows.map((row) => row.id));+ const ids = rows.map((row) => row.id);+ const [queued, tableFields] = await Promise.all([+ this.queue.queuedCompanies(ids),+ this.fields.tableValuesFor("COMPANY", ids),+ ]);return {rows: rows.map((row) => ({@@ -158,6 +167,7 @@ export class CompaniesService {openDealCount: row._count.deals,lastActivityAt: row.lastActivityAt?.toISOString() ?? null,createdAt: row.createdAt.toISOString(),+ fields: tableFields.get(row.id) ?? {},})),total,facetCounts,@@ -244,6 +254,7 @@ export class CompaniesService {return {...rest,+ fields: await this.fields.valuesFor("COMPANY", id),queued: await this.queue.isQueued({ companyId: id }),createdAt: createdAt.toISOString(),enrichedAt: enrichedAt?.toISOString() ?? null,@@ -309,6 +320,10 @@ 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();@@ -410,6 +425,37 @@ export class CompaniesService {return { id, name: deleted.name };}+ async bulkAssignOwner(input: CompanyBulkOwnerInput): Promise<BulkResult> {+ await requireOwner(this.db, input.ownerId);++ const ids = [...new Set(input.ids)];+ const { count } = await this.db.company.updateMany({+ where: { id: { in: ids } },+ data: { ownerId: input.ownerId },+ });++ this.logger.log({+ message: "Companies reassigned",+ count,+ ownerId: input.ownerId,+ });++ return {+ requested: ids.length,+ succeeded: count,+ failed: ids.length - count,+ message: null,+ };+ }++ async bulkEnrich(ids: string[]): Promise<BulkResult> {+ return runBulk(ids, (id) => this.enrich(id));+ }++ async bulkDelete(ids: string[]): Promise<BulkResult> {+ return runBulk(ids, (id) => this.delete(id));+ }+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.contracts.ts b/apps/api/src/contacts/contacts.contracts.tsindex 6230debf..295dce93 100644--- a/apps/api/src/contacts/contacts.contracts.ts+++ b/apps/api/src/contacts/contacts.contracts.ts@@ -1,4 +1,6 @@import { z } from "zod";+import { bulkIdsInput } from "../crm/bulk";+import { recordFieldValues } from "../fields/fields.contracts";import { listInput } from "../trpc/list-input";export const contactListInput = listInput.extend({@@ -32,6 +34,7 @@ const contactUpdateInput = z.object({githubUrl: z.string().optional(),companyId: z.string().nullable().optional(),ownerId: z.string().nullable().optional(),+ fields: recordFieldValues.optional(),});export type ContactUpdateInput = z.infer<typeof contactUpdateInput>;@@ -43,6 +46,20 @@ export const contactUpdateArgs = z.object({export const contactIdInput = z.object({ id: z.string() });+export const contactBulkInput = bulkIdsInput;++export const contactBulkOwnerInput = bulkIdsInput.extend({+ ownerId: z.string().nullable(),+});++export type ContactBulkOwnerInput = z.infer<typeof contactBulkOwnerInput>;++export const contactBulkCompanyInput = bulkIdsInput.extend({+ companyId: z.string().nullable(),+});++export type ContactBulkCompanyInput = z.infer<typeof contactBulkCompanyInput>;+export const factDecisionInput = z.object({factId: z.string(),decision: z.enum(["accept", "dismiss"]),diff --git a/apps/api/src/contacts/contacts.module.ts b/apps/api/src/contacts/contacts.module.tsindex 8a508085..790fbf93 100644--- a/apps/api/src/contacts/contacts.module.ts+++ b/apps/api/src/contacts/contacts.module.ts@@ -1,12 +1,13 @@import { Module } from "@nestjs/common";import { AgentModule } from "../agent/agent.module";import { CompaniesModule } from "../companies/companies.module";+import { FieldsModule } from "../fields/fields.module";import { TrpcModule } from "../trpc/trpc.module";import { ContactsRouter } from "./contacts.router";import { ContactsService } from "./contacts.service";@Module({- imports: [TrpcModule, AgentModule, CompaniesModule],+ imports: [FieldsModule, TrpcModule, AgentModule, CompaniesModule],providers: [ContactsService, ContactsRouter],exports: [ContactsService],})diff --git a/apps/api/src/contacts/contacts.router.ts b/apps/api/src/contacts/contacts.router.tsindex eee33954..d87f5a81 100644--- a/apps/api/src/contacts/contacts.router.ts+++ b/apps/api/src/contacts/contacts.router.ts@@ -11,6 +11,9 @@ import type { z } from "zod";import type { AuthedTrpcContext } from "../trpc/context.types";import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";import {+ contactBulkCompanyInput,+ contactBulkInput,+ contactBulkOwnerInput,contactCreateInput,contactIdInput,contactListInput,@@ -56,6 +59,28 @@ export class ContactsRouter {return this.contacts.enrich(id);}+ @Mutation({ input: contactBulkOwnerInput })+ async bulkAssignOwner(@Input() input: z.infer<typeof contactBulkOwnerInput>) {+ return this.contacts.bulkAssignOwner(input);+ }++ @Mutation({ input: contactBulkCompanyInput })+ async bulkSetCompany(+ @Input() input: z.infer<typeof contactBulkCompanyInput>,+ ) {+ return this.contacts.bulkSetCompany(input);+ }++ @Mutation({ input: contactBulkInput })+ async bulkEnrich(@Input("ids") ids: string[]) {+ return this.contacts.bulkEnrich(ids);+ }++ @Mutation({ input: contactBulkInput })+ async bulkDelete(@Input("ids") ids: string[]) {+ return this.contacts.bulkDelete(ids);+ }+@Mutation({ input: factDecisionInput })async decideFact(@Ctx() ctx: AuthedTrpcContext,diff --git a/apps/api/src/contacts/contacts.service.ts b/apps/api/src/contacts/contacts.service.tsindex 9b0d2c8d..cd9e9566 100644--- a/apps/api/src/contacts/contacts.service.ts+++ b/apps/api/src/contacts/contacts.service.ts@@ -20,8 +20,10 @@ import {ActivityStampService,type StampTargets,} from "../crm/activity-stamp.service";+import { type BulkResult, requireOwner, runBulk } from "../crm/bulk";import { blankToNull, normalizeEmail, toCents } from "../crm/values";import { InjectDatabase } from "../database/database.constants";+import { FieldsService } from "../fields/fields.service";import {countsByKey,FACET_ALL,@@ -32,6 +34,8 @@ import {resolveOrderBy,} from "../trpc/list-input";import type {+ ContactBulkCompanyInput,+ ContactBulkOwnerInput,ContactCreateInput,ContactListInput,ContactUpdateInput,@@ -88,6 +92,7 @@ export type ContactRow = {} | null;lastActivityAt: string | null;createdAt: string;+ fields: Record<string, string | number | boolean | null>;};const SORTABLE: Record<@@ -113,6 +118,7 @@ export class ContactsService {private readonly agent: AgentTriggerService,private readonly queue: AgentQueueService,private readonly stamp: ActivityStampService,+ private readonly fields: FieldsService,) {}async list(input: ContactListInput): Promise<ListResult<ContactRow>> {@@ -143,11 +149,17 @@ export class ContactsService {this.facetCounts(input),]);+ const tableFields = await this.fields.tableValuesFor(+ "CONTACT",+ rows.map((row) => row.id),+ );+return {rows: rows.map((row) => ({...row,lastActivityAt: row.lastActivityAt?.toISOString() ?? null,createdAt: row.createdAt.toISOString(),+ fields: tableFields.get(row.id) ?? {},})),total,facetCounts,@@ -233,6 +245,7 @@ export class ContactsService {return {...rest,company,+ fields: await this.fields.valuesFor("CONTACT", id),queued: await this.queue.isQueued({ contactId: id }),createdAt: createdAt.toISOString(),brief: brief@@ -362,6 +375,10 @@ 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 +426,68 @@ export class ContactsService {}}+ async bulkAssignOwner(input: ContactBulkOwnerInput): Promise<BulkResult> {+ await requireOwner(this.db, input.ownerId);++ const ids = [...new Set(input.ids)];+ const { count } = await this.db.contact.updateMany({+ where: { id: { in: ids } },+ data: { ownerId: input.ownerId },+ });++ this.logger.log({+ message: "Contacts reassigned",+ count,+ ownerId: input.ownerId,+ });++ return {+ requested: ids.length,+ succeeded: count,+ failed: ids.length - count,+ message: null,+ };+ }++ async bulkSetCompany(input: ContactBulkCompanyInput): Promise<BulkResult> {+ if (input.companyId) {+ const company = await this.db.company.findUnique({+ where: { id: input.companyId },+ select: { id: true },+ });+ if (!company) {+ throw new NotFoundException(`No company with id ${input.companyId}.`);+ }+ }++ const ids = [...new Set(input.ids)];+ const { count } = await this.db.contact.updateMany({+ where: { id: { in: ids } },+ data: { companyId: input.companyId },+ });++ this.logger.log({+ message: "Contacts moved",+ count,+ companyId: input.companyId,+ });++ return {+ requested: ids.length,+ succeeded: count,+ failed: ids.length - count,+ message: null,+ };+ }++ async bulkEnrich(ids: string[]): Promise<BulkResult> {+ return runBulk(ids, (id) => this.enrich(id));+ }++ async bulkDelete(ids: string[]): Promise<BulkResult> {+ return runBulk(ids, (id) => this.delete(id));+ }+private async allowAgain(tx: Prisma.TransactionClient,email: string | null,diff --git a/apps/api/src/crm/bulk.ts b/apps/api/src/crm/bulk.tsnew file mode 100644index 00000000..086da599--- /dev/null+++ b/apps/api/src/crm/bulk.ts@@ -0,0 +1,61 @@+import type { Db } from "@crm/db";+import { BadRequestException } from "@nestjs/common";+import { z } from "zod";++export const MAX_BULK_IDS = 100;++export const bulkIdsInput = z.object({+ ids: z+ .array(z.string())+ .min(1, "Nothing was selected.")+ .max(MAX_BULK_IDS, "Too many records at once — select a page at a time."),+});++export type BulkResult = {+ requested: number;+ succeeded: number;+ failed: number;+ message: string | null;+};++export async function requireOwner(+ db: Db,+ ownerId: string | null,+): Promise<void> {+ if (!ownerId) return;++ const owner = await db.user.findUnique({+ where: { id: ownerId },+ select: { id: true },+ });++ if (!owner) {+ throw new BadRequestException("That owner does not work here any more.");+ }+}++export async function runBulk(+ ids: string[],+ act: (id: string) => Promise<unknown>,+): Promise<BulkResult> {+ const unique = [...new Set(ids)];+ let succeeded = 0;+ let message: string | null = null;++ for (const id of unique) {+ try {+ await act(id);+ succeeded += 1;+ } catch (error) {+ message ??=+ error instanceof Error ? error.message : "Something went wrong.";+ }+ }++ return {+ requested: unique.length,+ succeeded,+ failed: unique.length - succeeded,+ message,+ };+}diff --git a/apps/api/src/deals/deals.contracts.ts b/apps/api/src/deals/deals.contracts.tsindex 1ff83a98..ef8ee432 100644--- a/apps/api/src/deals/deals.contracts.ts+++ b/apps/api/src/deals/deals.contracts.ts@@ -1,6 +1,8 @@import { DealStage } from "@crm/db";import { z } from "zod";+import { bulkIdsInput } from "../crm/bulk";import { currencyCode } from "../currency/currency.contracts";+import { recordFieldValues } from "../fields/fields.contracts";import { listInput } from "../trpc/list-input";export const MAX_AMOUNT_CENTS = 99_999_999_999_999;@@ -56,6 +58,7 @@ const dealUpdateInput = z.object({amountCents,currency: currencyCode.optional(),expectedCloseDate: z.string().nullable().optional(),+ fields: recordFieldValues.optional(),});export type DealUpdateInput = z.infer<typeof dealUpdateInput>;@@ -74,3 +77,49 @@ export const setStageInput = z.object({});export type SetStageInput = z.infer<typeof setStageInput>;++const dealContactRole = z+ .string()+ .trim()+ .max(80, "That role is too long.")+ .nullable();++export const dealContactsInput = z.object({ dealId: z.string() });++export const dealAttachContactInput = z.object({+ dealId: z.string(),+ contactId: z.string().min(1, "Choose somebody to bring onto the deal."),+ role: dealContactRole.optional(),+});++export type DealAttachContactInput = z.infer<typeof dealAttachContactInput>;++export const dealDetachContactInput = z.object({+ dealId: z.string(),+ contactId: z.string(),+});++export type DealDetachContactInput = z.infer<typeof dealDetachContactInput>;++export const dealContactRoleInput = z.object({+ dealId: z.string(),+ contactId: z.string(),+ role: dealContactRole,+});++export type DealContactRoleInput = z.infer<typeof dealContactRoleInput>;++export const dealBulkInput = bulkIdsInput;++export const dealBulkOwnerInput = bulkIdsInput.extend({+ ownerId: z.string().min(1, "A deal needs an owner."),+});++export type DealBulkOwnerInput = z.infer<typeof dealBulkOwnerInput>;++export const dealBulkStageInput = bulkIdsInput.extend({+ stage: stageEnum,+ closedReason: z.string().trim().optional(),+});++export type DealBulkStageInput = z.infer<typeof dealBulkStageInput>;diff --git a/apps/api/src/deals/deals.module.ts b/apps/api/src/deals/deals.module.tsindex a75081e4..97c1ac84 100644--- a/apps/api/src/deals/deals.module.ts+++ b/apps/api/src/deals/deals.module.ts@@ -1,11 +1,12 @@import { Module } from "@nestjs/common";import { CurrencyModule } from "../currency/currency.module";+import { FieldsModule } from "../fields/fields.module";import { TrpcModule } from "../trpc/trpc.module";import { DealsRouter } from "./deals.router";import { DealsService } from "./deals.service";@Module({- imports: [TrpcModule, CurrencyModule],+ imports: [FieldsModule, TrpcModule, CurrencyModule],providers: [DealsService, DealsRouter],exports: [DealsService],})diff --git a/apps/api/src/deals/deals.router.ts b/apps/api/src/deals/deals.router.tsindex 148e7ac1..ccb3f850 100644--- a/apps/api/src/deals/deals.router.ts+++ b/apps/api/src/deals/deals.router.ts@@ -11,7 +11,14 @@ import type { z } from "zod";import type { AuthedTrpcContext } from "../trpc/context.types";import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";import {+ dealAttachContactInput,+ dealBulkInput,+ dealBulkOwnerInput,+ dealBulkStageInput,+ dealContactRoleInput,+ dealContactsInput,dealCreateInput,+ dealDetachContactInput,dealIdInput,dealListInput,dealUpdateArgs,@@ -56,4 +63,42 @@ export class DealsRouter {) {return this.deals.setStage(input, ctx.user.id);}++ @Query({ input: dealContactsInput })+ async contactOptions(@Input("dealId") dealId: string) {+ return this.deals.contactOptions(dealId);+ }++ @Mutation({ input: dealAttachContactInput })+ async attachContact(@Input() input: z.infer<typeof dealAttachContactInput>) {+ return this.deals.attachContact(input);+ }++ @Mutation({ input: dealDetachContactInput })+ async detachContact(@Input() input: z.infer<typeof dealDetachContactInput>) {+ return this.deals.detachContact(input);+ }++ @Mutation({ input: dealContactRoleInput })+ async setContactRole(@Input() input: z.infer<typeof dealContactRoleInput>) {+ return this.deals.setContactRole(input);+ }++ @Mutation({ input: dealBulkOwnerInput })+ async bulkAssignOwner(@Input() input: z.infer<typeof dealBulkOwnerInput>) {+ return this.deals.bulkAssignOwner(input);+ }++ @Mutation({ input: dealBulkStageInput })+ async bulkSetStage(+ @Ctx() ctx: AuthedTrpcContext,+ @Input() input: z.infer<typeof dealBulkStageInput>,+ ) {+ return this.deals.bulkSetStage(input, ctx.user.id);+ }++ @Mutation({ input: dealBulkInput })+ async bulkDelete(@Input("ids") ids: string[]) {+ return this.deals.bulkDelete(ids);+ }}diff --git a/apps/api/src/deals/deals.service.ts b/apps/api/src/deals/deals.service.tsindex 610234ee..c604baba 100644--- a/apps/api/src/deals/deals.service.ts+++ b/apps/api/src/deals/deals.service.ts@@ -16,6 +16,7 @@ import {ActivityStampService,type StampTargets,} from "../crm/activity-stamp.service";+import { type BulkResult, requireOwner, runBulk } from "../crm/bulk";import {blankToNull,decimalFromCents,@@ -24,6 +25,7 @@ import {} from "../crm/values";import { ConversionService } from "../currency/conversion.service";import { InjectDatabase } from "../database/database.constants";+import { FieldsService } from "../fields/fields.service";import {countsByKey,FACET_ALL,@@ -40,7 +42,12 @@ import {} from "./deal-stage";import type {ClosingWindow,+ DealAttachContactInput,+ DealBulkOwnerInput,+ DealBulkStageInput,+ DealContactRoleInput,DealCreateInput,+ DealDetachContactInput,DealListInput,DealUpdateInput,SetStageInput,@@ -64,6 +71,15 @@ const COMPANY_SELECT = {logoUrl: true,} as const;+const CONTACT_SELECT = {+ id: true,+ firstName: true,+ lastName: true,+ email: true,+ title: true,+ imageUrl: true,+} as const;+const LOSING = new Set<DealStage>(LOSING_DEAL_STAGES);const SORTABLE: Record<@@ -88,6 +104,7 @@ export class DealsService {@InjectDatabase() private readonly db: Db,private readonly stamp: ActivityStampService,private readonly conversion: ConversionService,+ private readonly fields: FieldsService,) {}async list(input: DealListInput) {@@ -128,6 +145,11 @@ export class DealsService {this.conversion.unconverted(openWhere),]);+ const tableFields = await this.fields.tableValuesFor(+ "DEAL",+ rows.map((row) => row.id),+ );+return {rows: rows.map(({@@ -146,6 +168,7 @@ export class DealsService {closedAt: closedAt?.toISOString() ?? null,lastActivityAt: lastActivityAt?.toISOString() ?? null,createdAt: createdAt.toISOString(),+ fields: tableFields.get(row.id) ?? {},}),),total,@@ -181,19 +204,8 @@ export class DealsService {company: { select: { ...COMPANY_SELECT, industry: true } },owner: { select: OWNER_SELECT },contacts: {- select: {- role: true,- contact: {- select: {- id: true,- firstName: true,- lastName: true,- email: true,- title: true,- imageUrl: true,- },- },- },+ select: { role: true, contact: { select: CONTACT_SELECT } },+ orderBy: { contact: { firstName: "asc" } },},},});@@ -206,6 +218,7 @@ export class DealsService {return {...rest,+ fields: await this.fields.valuesFor("DEAL", id),amountCents: toCents(amount),baseAmountCents: toCents(baseAmount),reportingCurrency: await this.conversion.reportingCurrency(),@@ -258,6 +271,10 @@ 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();@@ -407,6 +424,156 @@ export class DealsService {return { ...updated, changed: true };}+ async contactOptions(dealId: string) {+ const deal = await this.db.deal.findUnique({+ where: { id: dealId },+ select: { companyId: true, contacts: { select: { contactId: true } } },+ });++ if (!deal) {+ throw new NotFoundException(`No deal with id ${dealId}.`);+ }++ return this.db.contact.findMany({+ where: {+ companyId: deal.companyId,+ id: { notIn: deal.contacts.map((row) => row.contactId) },+ },+ select: CONTACT_SELECT,+ orderBy: [{ firstName: "asc" }, { lastName: "asc" }],+ take: 100,+ });+ }++ async attachContact(input: DealAttachContactInput) {+ const company = await this.companyOf(input.dealId);+ const contact = await this.db.contact.findUnique({+ where: { id: input.contactId },+ select: { companyId: true },+ });++ if (!contact) {+ throw new NotFoundException(`No contact with id ${input.contactId}.`);+ }++ if (contact.companyId !== company.id) {+ throw new BadRequestException(+ `That contact does not work at ${company.name}.`,+ );+ }++ const role = roleOrNull(input.role ?? null);++ await this.db.dealContact.upsert({+ where: {+ dealId_contactId: {+ dealId: input.dealId,+ contactId: input.contactId,+ },+ },+ create: { dealId: input.dealId, contactId: input.contactId, role },+ update: role === null ? {} : { role },+ });++ this.logger.log({+ message: "Contact attached to deal",+ dealId: input.dealId,+ contactId: input.contactId,+ });++ return { dealId: input.dealId, contactId: input.contactId };+ }++ async detachContact(input: DealDetachContactInput) {+ const { count } = await this.db.dealContact.deleteMany({+ where: { dealId: input.dealId, contactId: input.contactId },+ });++ if (count === 0) {+ throw new NotFoundException("That contact is not on this deal.");+ }++ this.logger.log({+ message: "Contact detached from deal",+ dealId: input.dealId,+ contactId: input.contactId,+ });++ return { dealId: input.dealId, contactId: input.contactId };+ }++ async setContactRole(input: DealContactRoleInput) {+ const role = roleOrNull(input.role);++ const { count } = await this.db.dealContact.updateMany({+ where: { dealId: input.dealId, contactId: input.contactId },+ data: { role },+ });++ if (count === 0) {+ throw new NotFoundException("That contact is not on this deal.");+ }++ return { dealId: input.dealId, contactId: input.contactId, role };+ }++ async bulkAssignOwner(input: DealBulkOwnerInput): Promise<BulkResult> {+ await requireOwner(this.db, input.ownerId);++ const ids = [...new Set(input.ids)];+ const { count } = await this.db.deal.updateMany({+ where: { id: { in: ids } },+ data: { ownerId: input.ownerId },+ });++ this.logger.log({+ message: "Deals reassigned",+ count,+ ownerId: input.ownerId,+ });++ return {+ requested: ids.length,+ succeeded: count,+ failed: ids.length - count,+ message: null,+ };+ }++ async bulkSetStage(+ input: DealBulkStageInput,+ actingUserId: string,+ ): Promise<BulkResult> {+ const closedReason = input.closedReason?.trim();++ if (LOSING.has(input.stage) && !closedReason) {+ throw new BadRequestException(+ "Say why they were lost — a closed-lost deal with no reason teaches nobody anything.",+ );+ }++ return runBulk(input.ids, (id) =>+ this.setStage({ id, stage: input.stage, closedReason }, actingUserId),+ );+ }++ async bulkDelete(ids: string[]): Promise<BulkResult> {+ return runBulk(ids, (id) => this.delete(id));+ }++ private async companyOf(dealId: string) {+ const deal = await this.db.deal.findUnique({+ where: { id: dealId },+ select: { company: { select: { id: true, name: true } } },+ });++ if (!deal) {+ throw new NotFoundException(`No deal with id ${dealId}.`);+ }++ return deal.company;+ }+private searchFilter(q: string): Prisma.DealWhereInput {const term = q.trim();if (!term) return {};@@ -528,6 +695,10 @@ function closingFilter(window: ClosingWindow): Prisma.DealWhereInput {}}+function roleOrNull(value: string | null): string | null {+ return value === null ? null : blankToNull(value);+}+function parseDate(value: string | null | undefined): Date | null {if (value === null || value === undefined || value === "") return null;const date = new Date(value);diff --git a/apps/api/src/fields/fields.contracts.ts b/apps/api/src/fields/fields.contracts.tsnew file mode 100644index 00000000..a3f6e9e4--- /dev/null+++ b/apps/api/src/fields/fields.contracts.ts@@ -0,0 +1,64 @@+import { FIELD_ENTITIES, FIELD_TYPES } from "@crm/db/fields";+import { z } from "zod";++export const fieldEntity = z.enum(FIELD_ENTITIES);++export const fieldListInput = z.object({+ entity: fieldEntity,+ includeArchived: z.boolean().default(false),+});++export type FieldListInput = z.infer<typeof fieldListInput>;++export const fieldByKeyInput = z.object({+ entity: fieldEntity,+ key: z.string().trim().min(1),+});++const fieldOptionInput = z.object({+ id: z.string().optional(),+ label: z.string().trim().min(1, "An option needs a label."),+});++export const fieldCreateInput = z.object({+ entity: fieldEntity,+ label: z.string().trim().min(1, "A field needs a label."),+ type: z.enum(FIELD_TYPES),+ options: z.array(fieldOptionInput).default([]),+ agentFilled: z.boolean().default(true),+ agentBrief: z.string().trim().nullable().default(null),+ required: z.boolean().default(false),+ showOnSheet: z.boolean().default(true),+ showOnTable: z.boolean().default(false),+});++export type FieldCreateInput = z.infer<typeof fieldCreateInput>;++const fieldUpdateData = z.object({+ label: z.string().trim().min(1).optional(),+ type: z.enum(FIELD_TYPES).optional(),+ options: z.array(fieldOptionInput).optional(),+ agentFilled: z.boolean().optional(),+ agentBrief: z.string().trim().nullable().optional(),+ required: z.boolean().optional(),+ showOnSheet: z.boolean().optional(),+ showOnTable: z.boolean().optional(),+});++export type FieldUpdateData = z.infer<typeof fieldUpdateData>;++export const fieldUpdateArgs = z.object({+ id: z.string(),+ data: fieldUpdateData,+});++export const fieldIdInput = z.object({ id: z.string() });++export const fieldReorderInput = z.object({+ entity: fieldEntity,+ ids: z.array(z.string()).min(1),+});++export type FieldReorderInput = z.infer<typeof fieldReorderInput>;++export const recordFieldValues = z.record(z.string(), z.unknown());diff --git a/apps/api/src/fields/fields.module.ts b/apps/api/src/fields/fields.module.tsnew file mode 100644index 00000000..e7acc4b5--- /dev/null+++ b/apps/api/src/fields/fields.module.ts@@ -0,0 +1,12 @@+import { Module } from "@nestjs/common";+import { AgentModule } from "../agent/agent.module";+import { TrpcModule } from "../trpc/trpc.module";+import { FieldsRouter } from "./fields.router";+import { FieldsService } from "./fields.service";++@Module({+ imports: [TrpcModule, AgentModule],+ providers: [FieldsService, FieldsRouter],+ exports: [FieldsService],+})+export class FieldsModule {}diff --git a/apps/api/src/fields/fields.router.ts b/apps/api/src/fields/fields.router.tsnew file mode 100644index 00000000..a92ae4e6--- /dev/null+++ b/apps/api/src/fields/fields.router.ts@@ -0,0 +1,69 @@+import { Inject } from "@nestjs/common";+import { Input, Mutation, Query, Router, UseMiddlewares } from "nestjs-trpc";+import type { z } from "zod";+import { AuthMiddleware } from "../trpc/middlewares/auth.middleware";+import {+ fieldByKeyInput,+ fieldCreateInput,+ fieldIdInput,+ fieldListInput,+ fieldReorderInput,+ fieldUpdateArgs,+} from "./fields.contracts";+import { FieldsService } from "./fields.service";++@Router({ alias: "fields" })+@UseMiddlewares(AuthMiddleware)+export class FieldsRouter {+ constructor(@Inject(FieldsService) private readonly fields: FieldsService) {}++ @Query({ input: fieldListInput })+ async list(@Input() input: z.infer<typeof fieldListInput>) {+ return this.fields.list(input.entity, input.includeArchived);+ }++ @Query({ input: fieldByKeyInput })+ async byKey(@Input() input: z.infer<typeof fieldByKeyInput>) {+ return this.fields.byKey(input.entity, input.key);+ }++ @Query({ input: fieldIdInput })+ async coverage(@Input("id") id: string) {+ return this.fields.coverage(id);+ }++ @Mutation({ input: fieldCreateInput })+ async create(@Input() input: z.infer<typeof fieldCreateInput>) {+ return this.fields.create(input);+ }++ @Mutation({ input: fieldUpdateArgs })+ async update(@Input() input: z.infer<typeof fieldUpdateArgs>) {+ return this.fields.update(input.id, input.data);+ }++ @Mutation({ input: fieldReorderInput })+ async reorder(@Input() input: z.infer<typeof fieldReorderInput>) {+ return this.fields.reorder(input);+ }++ @Mutation({ input: fieldIdInput })+ async archive(@Input("id") id: string) {+ return this.fields.archive(id);+ }++ @Mutation({ input: fieldIdInput })+ async restore(@Input("id") id: string) {+ return this.fields.restore(id);+ }++ @Mutation({ input: fieldIdInput })+ async delete(@Input("id") id: string) {+ return this.fields.delete(id);+ }++ @Mutation({ input: fieldIdInput })+ async backfill(@Input("id") id: string) {+ return this.fields.backfill(id);+ }+}diff --git a/apps/api/src/fields/fields.service.ts b/apps/api/src/fields/fields.service.tsnew file mode 100644index 00000000..6c521dfc--- /dev/null+++ b/apps/api/src/fields/fields.service.ts@@ -0,0 +1,391 @@+import type { Db, FieldEntity, Prisma } from "@crm/db";+import {+ attachValues,+ type FieldDefinitionWithOptions,+ FieldValueError,+ type FieldValueJson,+ fieldKeyFromLabel,+ type RecordField,+ readValue,+ recordColumn,+ type SerializedField,+ serializeField,+ usesOptions,+ writeValues,+} from "@crm/db/fields";+import {+ BadRequestException,+ ConflictException,+ Injectable,+ NotFoundException,+} from "@nestjs/common";+import { AgentTriggerService } from "../agent/agent-trigger.service";+import { InjectDatabase } from "../database/database.constants";+import type {+ FieldCreateInput,+ FieldReorderInput,+ FieldUpdateData,+} from "./fields.contracts";++const WITH_OPTIONS = {+ options: { orderBy: { position: "asc" } },+} as const satisfies Prisma.FieldDefinitionInclude;++@Injectable()+export class FieldsService {+ constructor(+ @InjectDatabase() private readonly db: Db,+ private readonly agent: AgentTriggerService,+ ) {}++ async list(+ entity: FieldEntity,+ includeArchived: boolean,+ ): Promise<SerializedField[]> {+ const definitions = await this.db.fieldDefinition.findMany({+ where: { entity, ...(includeArchived ? {} : { archivedAt: null }) },+ include: WITH_OPTIONS,+ orderBy: { position: "asc" },+ });++ return definitions.map(serializeField);+ }++ async byKey(entity: FieldEntity, key: string): Promise<SerializedField> {+ const definition = await this.db.fieldDefinition.findUnique({+ where: { entity_key: { entity, key } },+ include: WITH_OPTIONS,+ });++ if (!definition) throw new NotFoundException("That field does not exist.");++ return serializeField(definition);+ }++ async create(input: FieldCreateInput): Promise<SerializedField> {+ const key = fieldKeyFromLabel(input.label);++ if (!key) {+ throw new BadRequestException("That label does not make a usable key.");+ }++ const taken = await this.db.fieldDefinition.findUnique({+ where: { entity_key: { entity: input.entity, key } },+ select: { id: true },+ });++ if (taken) {+ throw new ConflictException(`There is already a field called "${key}".`);+ }++ if (usesOptions(input.type) && input.options.length === 0) {+ throw new BadRequestException("A select needs at least one option.");+ }++ const last = await this.db.fieldDefinition.findFirst({+ where: { entity: input.entity },+ orderBy: { position: "desc" },+ select: { position: true },+ });++ const definition = await this.db.fieldDefinition.create({+ data: {+ entity: input.entity,+ key,+ label: input.label,+ type: input.type,+ agentFilled: input.agentFilled,+ agentBrief: input.agentBrief,+ required: input.required,+ showOnSheet: input.showOnSheet,+ showOnTable: input.showOnTable,+ position: (last?.position ?? -1) + 1,+ options: usesOptions(input.type)+ ? {+ create: input.options.map((option, index) => ({+ label: option.label,+ position: index,+ })),+ }+ : undefined,+ },+ include: WITH_OPTIONS,+ });++ if (definition.agentFilled) {+ await this.agent.fieldBackfill(definition.key, "New field");+ }++ return serializeField(definition);+ }++ async update(id: string, data: FieldUpdateData): Promise<SerializedField> {+ const existing = await this.db.fieldDefinition.findUnique({+ where: { id },+ include: WITH_OPTIONS,+ });++ if (!existing) throw new NotFoundException("That field does not exist.");++ const type = data.type ?? existing.type;++ if (data.type && data.type !== existing.type) {+ const values = await this.db.fieldValue.count({+ where: { fieldId: id },+ });++ if (values > 0) {+ throw new ConflictException(+ "This field already holds values, so its type cannot change. Archive it and make a new one.",+ );+ }+ }++ if (usesOptions(type) && data.options && data.options.length === 0) {+ throw new BadRequestException("A select needs at least one option.");+ }++ const definition = await this.db.$transaction(async (tx) => {+ if (data.options && usesOptions(type)) {+ const keep = new Set(+ data.options+ .map((option) => option.id)+ .filter((value): value is string => Boolean(value)),+ );++ await tx.fieldOption.updateMany({+ where: { fieldId: id, id: { notIn: [...keep] }, archivedAt: null },+ data: { archivedAt: new Date() },+ });++ for (const [index, option] of data.options.entries()) {+ if (option.id) {+ await tx.fieldOption.update({+ where: { id: option.id },+ data: { label: option.label, position: index },+ });+ continue;+ }++ await tx.fieldOption.create({+ data: { fieldId: id, label: option.label, position: index },+ });+ }+ }++ return tx.fieldDefinition.update({+ where: { id },+ data: {+ label: data.label,+ type: data.type,+ agentFilled: data.agentFilled,+ agentBrief: data.agentBrief,+ required: data.required,+ showOnSheet: data.showOnSheet,+ showOnTable: data.showOnTable,+ },+ include: WITH_OPTIONS,+ });+ });++ const briefChanged =+ data.agentBrief !== undefined && data.agentBrief !== existing.agentBrief;+ const turnedOn = data.agentFilled === true && !existing.agentFilled;++ if (definition.agentFilled && (briefChanged || turnedOn)) {+ await this.agent.fieldBackfill(definition.key, "Brief changed");+ }++ return serializeField(definition);+ }++ async reorder(input: FieldReorderInput): Promise<SerializedField[]> {+ const owned = await this.db.fieldDefinition.findMany({+ where: { id: { in: input.ids }, entity: input.entity },+ select: { id: true },+ });++ if (owned.length !== input.ids.length) {+ throw new BadRequestException(+ "That order names a field which is not on this record type.",+ );+ }++ await this.db.$transaction(+ input.ids.map((id, index) =>+ this.db.fieldDefinition.update({+ where: { id },+ data: { position: index },+ }),+ ),+ );++ return this.list(input.entity, false);+ }++ async archive(id: string): Promise<SerializedField> {+ 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);+ }++ async restore(id: string): Promise<SerializedField> {+ 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);+ }++ async delete(id: string): Promise<{ id: string }> {+ await this.db.fieldDefinition.delete({ where: { id } }).catch(() => {+ throw new NotFoundException("That field does not exist.");+ });++ return { id };+ }++ async backfill(id: string): Promise<{ queued: boolean }> {+ const definition = await this.db.fieldDefinition.findUnique({+ where: { id },+ select: { key: true, agentFilled: true, archivedAt: true },+ });++ if (!definition) throw new NotFoundException("That field does not exist.");++ if (!definition.agentFilled || definition.archivedAt !== null) {+ throw new BadRequestException(+ "Your agents do not fill this field, so there is nothing to run.",+ );+ }++ await this.agent.fieldBackfill(definition.key, "Asked to fill the rest");++ return { queued: true };+ }++ async coverage(id: string): Promise<{ filled: number; total: number }> {+ const definition = await this.db.fieldDefinition.findUnique({+ where: { id },+ select: { entity: true },+ });++ if (!definition) throw new NotFoundException("That field does not exist.");++ const column = recordColumn(definition.entity);++ const [filled, total] = await Promise.all([+ this.db.fieldValue.count({+ where: { fieldId: id, [column]: { not: null } },+ }),+ definition.entity === "COMPANY"+ ? this.db.company.count()+ : definition.entity === "CONTACT"+ ? this.db.contact.count()+ : this.db.deal.count(),+ ]);++ return { filled, total };+ }++ async definitionsFor(+ entity: FieldEntity,+ ): Promise<FieldDefinitionWithOptions[]> {+ return this.db.fieldDefinition.findMany({+ where: { entity, archivedAt: null },+ include: WITH_OPTIONS,+ orderBy: { position: "asc" },+ });+ }++ async valuesFor(+ entity: FieldEntity,+ recordId: string,+ ): Promise<RecordField[]> {+ const column = recordColumn(entity);++ const [definitions, rows] = await Promise.all([+ this.definitionsFor(entity),+ this.db.fieldValue.findMany({ where: { [column]: recordId } }),+ ]);++ return attachValues(definitions, rows);+ }++ async tableValuesFor(+ entity: FieldEntity,+ recordIds: string[],+ ): Promise<Map<string, Record<string, FieldValueJson>>> {+ const byRecord = new Map<string, Record<string, FieldValueJson>>();++ if (recordIds.length === 0) return byRecord;++ const definitions = await this.db.fieldDefinition.findMany({+ where: { entity, archivedAt: null, showOnTable: true },+ include: WITH_OPTIONS,+ orderBy: { position: "asc" },+ });++ if (definitions.length === 0) return byRecord;++ const column = recordColumn(entity);++ const rows = await this.db.fieldValue.findMany({+ where: {+ [column]: { in: recordIds },+ fieldId: { in: definitions.map((definition) => definition.id) },+ },+ });++ const byId = new Map(definitions.map((entry) => [entry.id, entry]));++ for (const row of rows) {+ const recordId = row[column];+ if (!recordId) continue;++ const definition = byId.get(row.fieldId);+ if (!definition) continue;++ const current = byRecord.get(recordId) ?? {};+ current[definition.key] = readValue(definition, row);+ byRecord.set(recordId, current);+ }++ return byRecord;+ }++ async applyValues(+ tx: Db | Prisma.TransactionClient,+ entity: FieldEntity,+ recordId: string,+ values: Record<string, unknown>,+ ): Promise<void> {+ if (Object.keys(values).length === 0) return;++ const definitions = await this.definitionsFor(entity);++ try {+ await writeValues(tx, entity, recordId, definitions, values);+ } catch (error) {+ if (error instanceof FieldValueError) {+ throw new BadRequestException(error.message);+ }++ throw error;+ }+ }+}diff --git a/apps/api/src/generated/server.ts b/apps/api/src/generated/server.tsindex 69becaec..11d0e60b 100644--- a/apps/api/src/generated/server.ts+++ b/apps/api/src/generated/server.ts@@ -14,12 +14,13 @@ import { z } from "zod";const t = initTRPC.create();const publicProcedure = t.procedure;import { timelineInput, timelineCountsInput, myTasksInput, activityCreateInput, completeInput } from "../activities/activities.contracts";-import { companyListInput, companyIdInput, companyOptionsInput, companyCreateInput, companyUpdateArgs, setPrimaryContactInput } from "../companies/companies.contracts";-import { contactListInput, contactIdInput, contactCreateInput, contactUpdateArgs, factDecisionInput } from "../contacts/contacts.contracts";+import { companyListInput, companyIdInput, companyOptionsInput, companyCreateInput, companyUpdateArgs, companyBulkOwnerInput, companyBulkInput, setPrimaryContactInput } from "../companies/companies.contracts";+import { contactListInput, contactIdInput, contactCreateInput, contactUpdateArgs, contactBulkOwnerInput, contactBulkCompanyInput, contactBulkInput, factDecisionInput } from "../contacts/contacts.contracts";import { conversationListInput, conversationEventsInput, conversationSaveInput, conversationIdInput } from "../conversations/conversations.contracts";import { setReportingCurrencyInput, setManualRateInput, removeManualRateInput } from "../currency/currency.contracts";import { dashboardSummaryInput } from "../dashboard/dashboard.contracts";-import { dealListInput, dealIdInput, dealCreateInput, dealUpdateArgs, setStageInput } from "../deals/deals.contracts";+import { dealListInput, dealIdInput, dealCreateInput, dealUpdateArgs, setStageInput, dealContactsInput, dealAttachContactInput, dealDetachContactInput, dealContactRoleInput, dealBulkOwnerInput, dealBulkStageInput, dealBulkInput } from "../deals/deals.contracts";+import { fieldListInput, fieldByKeyInput, fieldIdInput, fieldCreateInput, fieldUpdateArgs, fieldReorderInput } from "../fields/fields.contracts";import { setAutoCreateInput, suppressDomainInput, threadInput, calendarEventInput } from "../google/google.contracts";import { setAgentModelInput, setResearchKeyInput } from "../settings/settings.contracts";import { ssoProviderListInput, registerSsoProviderInput, deleteSsoProviderInput } from "../sso/sso.contracts";@@ -31,6 +32,7 @@ import type { ConversationsRouter } from "../conversations/conversations.router"import type { CurrencyRouter } from "../currency/currency.router";import type { DashboardRouter } from "../dashboard/dashboard.router";import type { DealsRouter } from "../deals/deals.router";+import type { FieldsRouter } from "../fields/fields.router";import type { GoogleRouter } from "../google/google.router";import type { SearchRouter } from "../search/search.router";import type { SettingsRouter } from "../settings/settings.router";@@ -75,6 +77,15 @@ const appRouter = t.router({delete: publicProcedure.input(companyIdInput).mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CompaniesRouter["delete"]>>),+ bulkAssignOwner: publicProcedure+ .input(companyBulkOwnerInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CompaniesRouter["bulkAssignOwner"]>>),+ bulkEnrich: publicProcedure+ .input(companyBulkInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CompaniesRouter["bulkEnrich"]>>),+ bulkDelete: publicProcedure+ .input(companyBulkInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CompaniesRouter["bulkDelete"]>>),enrich: publicProcedure.input(companyIdInput).mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<CompaniesRouter["enrich"]>>),@@ -104,6 +115,18 @@ const appRouter = t.router({enrich: publicProcedure.input(contactIdInput).mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["enrich"]>>),+ bulkAssignOwner: publicProcedure+ .input(contactBulkOwnerInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["bulkAssignOwner"]>>),+ bulkSetCompany: publicProcedure+ .input(contactBulkCompanyInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["bulkSetCompany"]>>),+ bulkEnrich: publicProcedure+ .input(contactBulkInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["bulkEnrich"]>>),+ bulkDelete: publicProcedure+ .input(contactBulkInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["bulkDelete"]>>),decideFact: publicProcedure.input(factDecisionInput).mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<ContactsRouter["decideFact"]>>)@@ -160,7 +183,60 @@ const appRouter = t.router({.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"]>>)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["setStage"]>>),+ contactOptions: publicProcedure+ .input(dealContactsInput)+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["contactOptions"]>>),+ attachContact: publicProcedure+ .input(dealAttachContactInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["attachContact"]>>),+ detachContact: publicProcedure+ .input(dealDetachContactInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["detachContact"]>>),+ setContactRole: publicProcedure+ .input(dealContactRoleInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["setContactRole"]>>),+ bulkAssignOwner: publicProcedure+ .input(dealBulkOwnerInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["bulkAssignOwner"]>>),+ bulkSetStage: publicProcedure+ .input(dealBulkStageInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["bulkSetStage"]>>),+ bulkDelete: publicProcedure+ .input(dealBulkInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<DealsRouter["bulkDelete"]>>)+ }),+ fields: t.router({+ list: publicProcedure+ .input(fieldListInput)+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<FieldsRouter["list"]>>),+ byKey: publicProcedure+ .input(fieldByKeyInput)+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<FieldsRouter["byKey"]>>),+ coverage: publicProcedure+ .input(fieldIdInput)+ .query(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<FieldsRouter["coverage"]>>),+ create: publicProcedure+ .input(fieldCreateInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<FieldsRouter["create"]>>),+ update: publicProcedure+ .input(fieldUpdateArgs)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<FieldsRouter["update"]>>),+ reorder: publicProcedure+ .input(fieldReorderInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<FieldsRouter["reorder"]>>),+ archive: publicProcedure+ .input(fieldIdInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<FieldsRouter["archive"]>>),+ restore: publicProcedure+ .input(fieldIdInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<FieldsRouter["restore"]>>),+ delete: publicProcedure+ .input(fieldIdInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<FieldsRouter["delete"]>>),+ backfill: publicProcedure+ .input(fieldIdInput)+ .mutation(async () => "PLACEHOLDER_DO_NOT_REMOVE" as unknown as Awaited<ReturnType<FieldsRouter["backfill"]>>)}),google: t.router({status: publicProcedurediff --git a/apps/api/test/bulk.spec.ts b/apps/api/test/bulk.spec.tsnew file mode 100644index 00000000..27fd7146--- /dev/null+++ b/apps/api/test/bulk.spec.ts@@ -0,0 +1,281 @@+import { afterAll, beforeAll, describe, expect, it } from "bun:test";+import { db } from "@crm/db";+import { AgentQueueService } from "../src/agent/agent-queue.service";+import type { 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 ?? "bulk-spec";+const domain = `bulk-${suffix}.test`;+const ownerId = `owner-${suffix}`;+const secondOwnerId = `second-owner-${suffix}`;+const ours = { OR: [{ email: { endsWith: `@${domain}` } }] };++const agent = {+ contactCreated: async () => undefined,+ companyCreated: async () => undefined,+ companyRequested: async () => undefined,+} as unknown as AgentTriggerService;++const stamp = new ActivityStampService(db);+const queue = new AgentQueueService(db);+const conversion = new ConversionService(db);+const directory = new CompanyDirectoryService(db, agent);++const fields = new FieldsService(db, agent);+const contacts = new ContactsService(+ db,+ directory,+ agent,+ queue,+ stamp,+ fields,+);+const companies = new CompaniesService(+ db,+ agent,+ queue,+ { backfill: async () => undefined } as unknown as FaviconService,+ stamp,+ conversion,+ fields,+);+const deals = new DealsService(db, stamp, conversion, fields);++let companyId: string;++async function clean() {+ const owned = await db.company.findMany({+ where: { domain },+ select: { id: true },+ });+ const companyIds = owned.map((row) => row.id);++ await db.deal.deleteMany({ where: { companyId: { in: companyIds } } });+ await db.activity.deleteMany({ where: { companyId: { in: companyIds } } });+ 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.user.deleteMany({ where: { id: { in: [ownerId, secondOwnerId] } } });+}++beforeAll(async () => {+ await clean();++ await db.user.createMany({+ data: [+ { id: ownerId, name: "First Rep", email: `first@${domain}` },+ { id: secondOwnerId, name: "Second Rep", email: `second@${domain}` },+ ],+ });++ const company = await db.company.create({+ data: { name: `Bulk Co ${suffix}`, domain },+ select: { id: true },+ });+ companyId = company.id;+});++afterAll(clean);++describe("assigning an owner to a selection", () => {+ it("moves every record it was given", async () => {+ const first = await contacts.create({+ firstName: "Ada",+ email: `ada@${domain}`,+ ownerId,+ });+ const second = await contacts.create({+ firstName: "Grace",+ email: `grace@${domain}`,+ ownerId,+ });++ expect(+ await contacts.bulkAssignOwner({+ ids: [first.id, second.id],+ ownerId: secondOwnerId,+ }),+ ).toEqual({ requested: 2, succeeded: 2, failed: 0, message: null });++ expect(+ await db.contact.count({+ where: { id: { in: [first.id, second.id] }, ownerId: secondOwnerId },+ }),+ ).toBe(2);+ });++ it("counts the same record once, however many times it was sent", async () => {+ const only = await contacts.create({+ firstName: "Edsger",+ email: `edsger@${domain}`,+ });++ expect(+ await contacts.bulkAssignOwner({+ ids: [only.id, only.id],+ ownerId,+ }),+ ).toEqual({ requested: 1, succeeded: 1, failed: 0, message: null });+ });++ it("refuses an owner who does not work here", async () => {+ const contact = await contacts.create({+ firstName: "Alan",+ email: `alan@${domain}`,+ });++ await expect(+ contacts.bulkAssignOwner({+ ids: [contact.id],+ ownerId: `nobody-${suffix}`,+ }),+ ).rejects.toThrow(/does not work here/);++ expect(+ await db.contact.findUnique({+ where: { id: contact.id },+ select: { ownerId: true },+ }),+ ).toEqual({ ownerId: null });+ });+});++describe("deleting a selection", () => {+ it("suppresses every address, exactly as deleting them one by one would", async () => {+ const first = await contacts.create({+ firstName: "Gone",+ email: `gone@${domain}`,+ });+ const second = await contacts.create({+ firstName: "Also Gone",+ email: `also-gone@${domain}`,+ });++ expect(await contacts.bulkDelete([first.id, second.id])).toEqual({+ requested: 2,+ succeeded: 2,+ failed: 0,+ message: null,+ });++ expect(+ await db.suppressedContact.count({+ where: { email: { in: [`gone@${domain}`, `also-gone@${domain}`] } },+ }),+ ).toBe(2);+ });++ it("finishes the rest and says what it could not do", async () => {+ const survivor = await contacts.create({+ firstName: "Doomed",+ email: `doomed@${domain}`,+ });++ const result = await contacts.bulkDelete([+ survivor.id,+ `missing-${suffix}`,+ ]);++ expect(result.succeeded).toBe(1);+ expect(result.failed).toBe(1);+ expect(result.message).toMatch(/No contact with id/);+ expect(+ await db.contact.findUnique({ where: { id: survivor.id } }),+ ).toBeNull();+ });++ it("takes a company's deals with it", async () => {+ const doomed = await companies.create({+ name: `Doomed Co ${suffix}`,+ domain: `doomed-${domain}`,+ });+ const deal = await deals.create({+ name: `Doomed deal ${suffix}`,+ companyId: doomed.id,+ ownerId,+ });++ expect(await companies.bulkDelete([doomed.id])).toEqual({+ requested: 1,+ succeeded: 1,+ failed: 0,+ message: null,+ });++ expect(await db.deal.findUnique({ where: { id: deal.id } })).toBeNull();+ });+});++describe("moving a selection of deals to a stage", () => {+ it("will not close them as lost without a reason", async () => {+ const deal = await deals.create({+ name: `Unreasoned ${suffix}`,+ companyId,+ ownerId,+ });++ await expect(+ deals.bulkSetStage({ ids: [deal.id], stage: "CLOSED_LOST" }, ownerId),+ ).rejects.toThrow(/teaches nobody anything/);++ expect(+ await db.deal.findUnique({+ where: { id: deal.id },+ select: { stage: true },+ }),+ ).toEqual({ stage: "DEMO_BOOKED" });+ });++ it("writes the one reason onto every deal's timeline", async () => {+ const first = await deals.create({+ name: `Lost one ${suffix}`,+ companyId,+ ownerId,+ });+ const second = await deals.create({+ name: `Lost two ${suffix}`,+ companyId,+ ownerId,+ });++ expect(+ await deals.bulkSetStage(+ {+ ids: [first.id, second.id],+ stage: "CLOSED_LOST",+ closedReason: "Budget pulled",+ },+ ownerId,+ ),+ ).toEqual({ requested: 2, succeeded: 2, failed: 0, message: null });++ const closed = await db.deal.findMany({+ where: { id: { in: [first.id, second.id] } },+ select: { stage: true, closedReason: true, closedAt: true },+ });++ expect(closed.every((deal) => deal.stage === "CLOSED_LOST")).toBe(true);+ expect(closed.every((deal) => deal.closedReason === "Budget pulled")).toBe(+ true,+ );+ expect(closed.every((deal) => deal.closedAt !== null)).toBe(true);++ expect(+ await db.activity.count({+ where: {+ dealId: { in: [first.id, second.id] },+ type: "STAGE_CHANGE",+ body: "Budget pulled",+ },+ }),+ ).toBe(2);+ });+});diff --git a/apps/api/test/currency-totals.integration.spec.ts b/apps/api/test/currency-totals.integration.spec.tsindex 69d9cb28..6f063708 100644--- a/apps/api/test/currency-totals.integration.spec.ts+++ b/apps/api/test/currency-totals.integration.spec.ts@@ -6,13 +6,19 @@ import { ActivityStampService } from "../src/crm/activity-stamp.service";import { ConversionService } from "../src/currency/conversion.service";import { DashboardService } from "../src/dashboard/dashboard.service";import { DealsService } from "../src/deals/deals.service";+import { FieldsService } from "../src/fields/fields.service";const suffix = process.env.TEST_RUN_ID ?? "currency-totals-spec";const userId = `user-${suffix}`;const domain = `money-${suffix}.test`;const conversion = new ConversionService(db);-const deals = new DealsService(db, new ActivityStampService(db), conversion);+const deals = new DealsService(+ db,+ new ActivityStampService(db),+ conversion,+ new FieldsService(db, { fieldBackfill: async () => undefined } as never),+);const dashboard = new DashboardService(db, conversion);let companyId: string;diff --git a/apps/api/test/deal-contacts.spec.ts b/apps/api/test/deal-contacts.spec.tsnew file mode 100644index 00000000..4fb704d8--- /dev/null+++ b/apps/api/test/deal-contacts.spec.ts@@ -0,0 +1,165 @@+import { afterAll, beforeAll, describe, expect, it } from "bun:test";+import { db } from "@crm/db";+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 ?? "deal-contacts-spec";+const userId = `user-${suffix}`;+const domain = `dealpeople-${suffix}.test`;+const otherDomain = `elsewhere-${suffix}.test`;++const deals = new DealsService(+ db,+ new ActivityStampService(db),+ new ConversionService(db),+ new FieldsService(db, { fieldBackfill: async () => undefined } as never),+);++let companyId: string;+let dealId: string;+let championId: string;+let colleagueId: string;+let outsiderId: string;++async function clean() {+ await db.deal.deleteMany({ where: { company: { domain } } });+ await db.contact.deleteMany({+ where: { company: { domain: { in: [domain, otherDomain] } } },+ });+ await db.company.deleteMany({+ where: { domain: { in: [domain, otherDomain] } },+ });+ await db.user.deleteMany({ where: { id: userId } });+}++beforeAll(async () => {+ await clean();++ await db.user.create({+ data: {+ id: userId,+ name: "Deal Rep",+ email: `${userId}@example.test`,+ emailVerified: true,+ },+ });++ const company = await db.company.create({+ data: { name: `People Co ${suffix}`, domain },+ select: { id: true },+ });+ companyId = company.id;++ const other = await db.company.create({+ data: { name: `Other Co ${suffix}`, domain: otherDomain },+ select: { id: true },+ });++ const champion = await db.contact.create({+ data: { firstName: "Ada", lastName: "Champion", companyId },+ select: { id: true },+ });+ championId = champion.id;++ const colleague = await db.contact.create({+ data: { firstName: "Beau", lastName: "Colleague", companyId },+ select: { id: true },+ });+ colleagueId = colleague.id;++ const outsider = await db.contact.create({+ data: { firstName: "Cass", lastName: "Outsider", companyId: other.id },+ select: { id: true },+ });+ outsiderId = outsider.id;++ const deal = await deals.create({+ name: `Renewal ${suffix}`,+ companyId,+ ownerId: userId,+ });+ dealId = deal.id;+});++afterAll(clean);++describe("bringing a contact onto a deal", () => {+ it("offers the people at the deal's company and nobody else", async () => {+ const options = await deals.contactOptions(dealId);+ const ids = options.map((option) => option.id);++ expect(ids).toContain(championId);+ expect(ids).toContain(colleagueId);+ expect(ids).not.toContain(outsiderId);+ });++ it("attaches with a role and reads back on the deal", async () => {+ await deals.attachContact({+ dealId,+ contactId: championId,+ role: "Champion",+ });++ const deal = await deals.byId(dealId);++ expect(deal.contacts).toHaveLength(1);+ expect(deal.contacts[0]?.id).toBe(championId);+ expect(deal.contacts[0]?.role).toBe("Champion");+ });++ it("stops offering somebody already on it", async () => {+ const options = await deals.contactOptions(dealId);++ expect(options.map((option) => option.id)).not.toContain(championId);+ });++ it("attaching twice keeps the role it already has", async () => {+ await deals.attachContact({ dealId, contactId: championId });++ const deal = await deals.byId(dealId);++ expect(deal.contacts).toHaveLength(1);+ expect(deal.contacts[0]?.role).toBe("Champion");+ });++ it("refuses somebody who works somewhere else", async () => {+ await expect(+ deals.attachContact({ dealId, contactId: outsiderId }),+ ).rejects.toThrow(`That contact does not work at People Co ${suffix}.`);+ });++ it("blanks a role rather than storing an empty string", async () => {+ await deals.setContactRole({ dealId, contactId: championId, role: " " });++ const deal = await deals.byId(dealId);++ expect(deal.contacts[0]?.role).toBeNull();+ });++ it("will not set a role on somebody who is not on the deal", async () => {+ await expect(+ deals.setContactRole({+ dealId,+ contactId: colleagueId,+ role: "Blocker",+ }),+ ).rejects.toThrow("That contact is not on this deal.");+ });++ it("takes them off again, leaving the contact in the CRM", async () => {+ await deals.detachContact({ dealId, contactId: championId });++ const deal = await deals.byId(dealId);++ expect(deal.contacts).toHaveLength(0);+ expect(await db.contact.count({ where: { id: championId } })).toBe(1);+ });++ it("says so when they were never on it", async () => {+ await expect(+ deals.detachContact({ dealId, contactId: championId }),+ ).rejects.toThrow("That contact is not on this deal.");+ });+});diff --git a/apps/api/test/fields.spec.ts b/apps/api/test/fields.spec.tsnew file mode 100644index 00000000..cf7d0b85--- /dev/null+++ b/apps/api/test/fields.spec.ts@@ -0,0 +1,221 @@+import { afterAll, beforeAll, describe, expect, it } from "bun:test";+import { db } from "@crm/db";+import type { AgentTriggerService } from "../src/agent/agent-trigger.service";+import { FieldsService } from "../src/fields/fields.service";++const suffix = process.env.TEST_RUN_ID ?? "fields-spec";+const domain = `fields-${suffix}.test`;++const queued: { key: string; reason: string }[] = [];++const agent = {+ fieldBackfill: async (key: string, reason: string) => {+ queued.push({ key, reason });+ },+} as unknown as AgentTriggerService;++const fields = new FieldsService(db, agent);++let companyId: string;++async function clean() {+ const owned = await db.company.findMany({+ where: { domain },+ select: { id: true },+ });++ await db.fieldValue.deleteMany({+ where: { companyId: { in: owned.map((row) => row.id) } },+ });+ await db.fieldDefinition.deleteMany({+ where: { key: { startsWith: "spec_" } },+ });+ await db.company.deleteMany({ where: { domain } });+}++beforeAll(async () => {+ await clean();++ const company = await db.company.create({+ data: { name: `Fields Co ${suffix}`, domain },+ select: { id: true },+ });++ companyId = company.id;+});++afterAll(clean);++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",+ type: "SELECT",+ options: [{ label: "AWS" }, { label: "Azure" }],+ agentFilled: true,+ agentBrief: "Which cloud they run production on.",+ required: false,+ showOnSheet: true,+ showOnTable: false,+ });++ expect(field.key).toBe("spec_runs_on");+ expect(field.options.map((option) => option.label)).toEqual([+ "AWS",+ "Azure",+ ]);+ expect(queued).toEqual([{ key: "spec_runs_on", reason: "New field" }]);+ });++ it("refuses a duplicate key", async () => {+ await expect(+ fields.create({+ entity: "COMPANY",+ label: "Spec runs on",+ type: "TEXT",+ options: [],+ agentFilled: false,+ agentBrief: null,+ required: false,+ showOnSheet: true,+ showOnTable: false,+ }),+ ).rejects.toThrow(/already a field/);+ });++ it("keeps the same key when the label is renamed", async () => {+ const before = await fields.byKey("COMPANY", "spec_runs_on");++ const after = await fields.update(before.id, { label: "Spec cloud" });++ expect(after.key).toBe("spec_runs_on");+ expect(after.label).toBe("Spec cloud");+ });++ it("will not retype a field that already holds values", async () => {+ const field = await fields.byKey("COMPANY", "spec_runs_on");++ await fields.applyValues(db, "COMPANY", companyId, {+ spec_runs_on: "AWS",+ });++ await expect(+ fields.update(field.id, { type: "TEXT" }),+ ).rejects.toThrow(/cannot change/);+ });++ it("archives without losing values, and restores them", async () => {+ const field = await fields.byKey("COMPANY", "spec_runs_on");++ 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.restore(field.id);++ const back = await fields.valuesFor("COMPANY", companyId);+ expect(back).toHaveLength(1);+ expect(back[0]?.key).toBe("spec_runs_on");+ });++ it("reorders inside one entity only", async () => {+ const second = await fields.create({+ entity: "COMPANY",+ label: "Spec seats",+ type: "NUMBER",+ options: [],+ agentFilled: false,+ agentBrief: null,+ required: false,+ showOnSheet: true,+ showOnTable: false,+ });++ const first = await fields.byKey("COMPANY", "spec_runs_on");++ const reordered = await fields.reorder({+ entity: "COMPANY",+ ids: [second.id, first.id],+ });++ expect(reordered.map((field) => field.key)).toEqual([+ "spec_seats",+ "spec_runs_on",+ ]);++ await expect(+ fields.reorder({ entity: "CONTACT", ids: [first.id] }),+ ).rejects.toThrow(/not on this record type/);+ });+});++describe("field values", () => {+ it("round-trips each storage class", async () => {+ await fields.create({+ entity: "COMPANY",+ label: "Spec renewal",+ type: "DATE",+ options: [],+ agentFilled: false,+ agentBrief: null,+ required: false,+ showOnSheet: true,+ showOnTable: false,+ });++ await fields.applyValues(db, "COMPANY", companyId, {+ spec_seats: "240",+ spec_renewal: "2027-03-31",+ });++ const values = await fields.valuesFor("COMPANY", companyId);+ const byKey = new Map(values.map((field) => [field.key, field.value]));++ expect(byKey.get("spec_seats")).toBe(240);+ expect(byKey.get("spec_renewal")).toBe("2027-03-31T00:00:00.000Z");+ });++ it("rejects a value the type cannot hold", async () => {+ await expect(+ fields.applyValues(db, "COMPANY", companyId, { spec_seats: "loads" }),+ ).rejects.toThrow(/takes a number/);+ });++ it("rejects an unknown key", async () => {+ await expect(+ fields.applyValues(db, "COMPANY", companyId, { nope: "x" }),+ ).rejects.toThrow(/no field called/);+ });++ it("clears a value when it is blanked", async () => {+ await fields.applyValues(db, "COMPANY", companyId, { spec_seats: "" });++ const values = await fields.valuesFor("COMPANY", companyId);+ const seats = values.find((field) => field.key === "spec_seats");++ expect(seats?.value).toBeNull();+ });++ 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 },+ });++ await fields.applyValues(db, "COMPANY", doomed.id, {+ spec_renewal: "2027-01-01",+ });++ await db.company.delete({ where: { id: doomed.id } });++ expect(+ await db.fieldValue.count({ where: { companyId: doomed.id } }),+ ).toBe(0);+ });+});diff --git a/apps/api/test/record-delete.spec.ts b/apps/api/test/record-delete.spec.tsindex f8dfe6c4..76451e56 100644--- a/apps/api/test/record-delete.spec.ts+++ b/apps/api/test/record-delete.spec.ts@@ -9,6 +9,7 @@ import { ContactsService } from "../src/contacts/contacts.service";import { ActivityStampService } from "../src/crm/activity-stamp.service";import { EnrichmentLogService } from "../src/crm/enrichment-log.service";import { ConversionService } from "../src/currency/conversion.service";+import { FieldsService } from "../src/fields/fields.service";import { GoogleMatchService } from "../src/google/google-match.service";const suffix = process.env.TEST_RUN_ID ?? "record-delete-spec";@@ -33,7 +34,15 @@ const log = new EnrichmentLogService(db, stamp);const queue = new AgentQueueService(db);const conversion = new ConversionService(db);-const contacts = new ContactsService(db, directory, agent, queue, stamp);+const fields = new FieldsService(db, agent);+const contacts = new ContactsService(+ db,+ directory,+ agent,+ queue,+ stamp,+ fields,+);const companies = new CompaniesService(db,agent,@@ -41,6 +50,7 @@ const companies = new CompaniesService({ backfill: async () => undefined } as unknown as FaviconService,stamp,conversion,+ fields,);const match = new GoogleMatchService(db, directory, agent, log);diff --git a/apps/app/app/(app)/[slug]/companies/companies-bulk-actions.tsx b/apps/app/app/(app)/[slug]/companies/companies-bulk-actions.tsxnew file mode 100644index 00000000..9658fe74--- /dev/null+++ b/apps/app/app/(app)/[slug]/companies/companies-bulk-actions.tsx@@ -0,0 +1,115 @@+"use client";++import Renew from "@carbon/icons-react/es/Renew";+import TrashCan from "@carbon/icons-react/es/TrashCan";+import {+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuSeparator,+} from "@crm/ui/components/dropdown-menu";+import { formatCount } from "@crm/ui/lib/format";+import { useMutation, useQuery } from "@tanstack/react-query";+import { useState } from "react";+import { toast } from "sonner";+import {+ BulkActionsMenu,+ BulkDeleteDialog,+ BulkOwnerMenu,+ reportBulk,+} from "@/components/crm/bulk-actions";+import { useCrmCache } from "@/lib/trpc/cache";+import { useTRPC } from "@/lib/trpc/client";++function companies(count: number): string {+ return formatCount(count, "company", "companies");+}++export function CompaniesBulkActions({+ ids,+ onDone,+}: {+ ids: string[];+ onDone: () => void;+}) {+ const trpc = useTRPC();+ const cache = useCrmCache();+ const users = useQuery(trpc.users.list.queryOptions());+ const [confirming, setConfirming] = useState(false);++ const onError = (error: { message: string }) => toast.error(error.message);++ const assignOwner = useMutation(+ trpc.companies.bulkAssignOwner.mutationOptions({+ onSuccess: async (result) => {+ await cache.company();+ reportBulk(result, (count) => `${companies(count)} reassigned.`);+ onDone();+ },+ onError,+ }),+ );++ const enrich = useMutation(+ trpc.companies.bulkEnrich.mutationOptions({+ onSuccess: async (result) => {+ await cache.company();+ reportBulk(+ result,+ (count) => `Looking up ${companies(count)} — the table will update.`,+ );+ onDone();+ },+ onError,+ }),+ );++ const remove = useMutation(+ trpc.companies.bulkDelete.mutationOptions({+ onSuccess: async (result, variables) => {+ await cache.removedMany({ kind: "company", ids: variables.ids });+ reportBulk(result, (count) => `${companies(count)} deleted.`);+ setConfirming(false);+ onDone();+ },+ onError,+ }),+ );++ const pending = assignOwner.isPending || enrich.isPending || remove.isPending;++ return (+ <>+ <BulkActionsMenu pending={pending}>+ <BulkOwnerMenu+ users={users.data ?? []}+ unassignedLabel="Nobody"+ onSelect={(ownerId) => assignOwner.mutate({ ids, ownerId })}+ />+ <DropdownMenuGroup>+ <DropdownMenuItem onSelect={() => enrich.mutate({ ids })}>+ <Renew />+ Re-enrich+ </DropdownMenuItem>+ </DropdownMenuGroup>+ <DropdownMenuSeparator />+ <DropdownMenuGroup>+ <DropdownMenuItem+ variant="destructive"+ onSelect={() => setConfirming(true)}+ >+ <TrashCan />+ Delete+ </DropdownMenuItem>+ </DropdownMenuGroup>+ </BulkActionsMenu>++ <BulkDeleteDialog+ open={confirming}+ onOpenChange={setConfirming}+ title={`Delete ${companies(ids.length)}?`}+ description="Their contacts stay, with no company. Deals on these companies go with them, and none of it can be undone."+ onConfirm={() => remove.mutate({ ids })}+ />+ </>+ );+}diff --git a/apps/app/app/(app)/[slug]/companies/companies-table.tsx b/apps/app/app/(app)/[slug]/companies/companies-table.tsxindex b8715366..f3a6cce0 100644--- a/apps/app/app/(app)/[slug]/companies/companies-table.tsx+++ b/apps/app/app/(app)/[slug]/companies/companies-table.tsx@@ -10,14 +10,17 @@ import {EntityLogo,type EntityLogoTone,} from "@crm/ui/components/entity-logo";+import { useTableSelection } from "@crm/ui/hooks/use-table-selection";import { relativeTimeFromIso } from "@crm/ui/lib/format";import { useQuery } from "@tanstack/react-query";+import { useMemo } from "react";import {ENRICHMENT_FACET_OPTIONS,ENRICHMENT_POLL_MS,EnrichmentIndicator,isEnriching,} from "@/components/crm/enrichment-status";+import { useFieldColumns } from "@/components/crm/fields/field-columns";import { OwnerCell } from "@/components/crm/owner-cell";import { usePrefetchRecord } from "@/components/crm/record-sheet/record-prefetch";import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";@@ -25,6 +28,7 @@ import { ListSearch } from "@/components/data-table/list-search";import { useTableQuery } from "@/components/data-table/use-table-query";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";+import { CompaniesBulkActions } from "./companies-bulk-actions";import { companiesSearchParams } from "./companies-search-params";type CompanyRow = RouterOutputs["companies"]["list"]["rows"][number];@@ -157,6 +161,11 @@ export function CompaniesTable() {});const users = useQuery(trpc.users.list.queryOptions());+ const rows = companies.data?.rows ?? [];+ const selection = useTableSelection(+ useMemo(() => rows.map((row) => row.id), [rows]),+ );+const facetCounts = companies.data?.facetCounts;const facets: DataTableFacet[] = [@@ -187,15 +196,25 @@ export function CompaniesTable() {},];+ const fieldColumns = useFieldColumns<CompanyRow>("COMPANY");+ const columns = useMemo(() => [...COLUMNS, ...fieldColumns], [fieldColumns]);+return (<DataTablequery={query}search={<ListSearch placeholder="Search companies by name or domain…" />}- columns={COLUMNS}- rows={companies.data?.rows ?? []}+ columns={columns}+ rows={rows}total={companies.data?.total ?? 0}facetCounts={facetCounts}facets={facets}+ selection={{+ state: selection,+ actions: (+ <CompaniesBulkActions ids={selection.ids} onDone={selection.clear} />+ ),+ rowLabel: (row) => row.name,+ }}getRowId={(row) => row.id}loading={companies.isFetching}onRowHover={(row) => prefetchRecord({ kind: "company", id: row.id })}diff --git a/apps/app/app/(app)/[slug]/contacts/contacts-bulk-actions.tsx b/apps/app/app/(app)/[slug]/contacts/contacts-bulk-actions.tsxnew file mode 100644index 00000000..c992755b--- /dev/null+++ b/apps/app/app/(app)/[slug]/contacts/contacts-bulk-actions.tsx@@ -0,0 +1,161 @@+"use client";++import Renew from "@carbon/icons-react/es/Renew";+import TrashCan from "@carbon/icons-react/es/TrashCan";+import {+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+} from "@crm/ui/components/dropdown-menu";+import { formatCount } from "@crm/ui/lib/format";+import { useMutation, useQuery } from "@tanstack/react-query";+import { useState } from "react";+import { toast } from "sonner";+import {+ BulkActionsMenu,+ BulkDeleteDialog,+ BulkOwnerMenu,+ reportBulk,+} from "@/components/crm/bulk-actions";+import { useCrmCache } from "@/lib/trpc/cache";+import { useTRPC } from "@/lib/trpc/client";++function contacts(count: number): string {+ return formatCount(count, "contact");+}++export function ContactsBulkActions({+ ids,+ onDone,+}: {+ ids: string[];+ onDone: () => void;+}) {+ const trpc = useTRPC();+ const cache = useCrmCache();+ const users = useQuery(trpc.users.list.queryOptions());+ const companies = useQuery(trpc.companies.options.queryOptions({ q: "" }));+ const [confirming, setConfirming] = useState(false);++ const onError = (error: { message: string }) => toast.error(error.message);++ const assignOwner = useMutation(+ trpc.contacts.bulkAssignOwner.mutationOptions({+ onSuccess: async (result) => {+ await cache.contact();+ reportBulk(result, (count) => `${contacts(count)} reassigned.`);+ onDone();+ },+ onError,+ }),+ );++ const setCompany = useMutation(+ trpc.contacts.bulkSetCompany.mutationOptions({+ onSuccess: async (result) => {+ await cache.contact();+ reportBulk(result, (count) => `${contacts(count)} moved.`);+ onDone();+ },+ onError,+ }),+ );++ const enrich = useMutation(+ trpc.contacts.bulkEnrich.mutationOptions({+ onSuccess: async (result) => {+ await cache.contact();+ reportBulk(+ result,+ (count) => `Looking up ${contacts(count)} — the table will update.`,+ );+ onDone();+ },+ onError,+ }),+ );++ const remove = useMutation(+ trpc.contacts.bulkDelete.mutationOptions({+ onSuccess: async (result, variables) => {+ await cache.removedMany({ kind: "contact", ids: variables.ids });+ reportBulk(result, (count) => `${contacts(count)} deleted.`);+ setConfirming(false);+ onDone();+ },+ onError,+ }),+ );++ const pending =+ assignOwner.isPending ||+ setCompany.isPending ||+ enrich.isPending ||+ remove.isPending;++ return (+ <>+ <BulkActionsMenu pending={pending}>+ <BulkOwnerMenu+ users={users.data ?? []}+ unassignedLabel="Nobody"+ onSelect={(ownerId) => assignOwner.mutate({ ids, ownerId })}+ />+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>Move to company</DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-72 overflow-y-auto">+ <DropdownMenuGroup>+ <DropdownMenuItem+ onSelect={() => setCompany.mutate({ ids, companyId: null })}+ >+ No company+ </DropdownMenuItem>+ {companies.data?.length === 0 ? (+ <DropdownMenuLabel>No companies yet.</DropdownMenuLabel>+ ) : (+ companies.data?.map((company) => (+ <DropdownMenuItem+ key={company.id}+ onSelect={() =>+ setCompany.mutate({ ids, companyId: company.id })+ }+ >+ {company.name}+ </DropdownMenuItem>+ ))+ )}+ </DropdownMenuGroup>+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuGroup>+ <DropdownMenuItem onSelect={() => enrich.mutate({ ids })}>+ <Renew />+ Re-enrich+ </DropdownMenuItem>+ </DropdownMenuGroup>+ <DropdownMenuSeparator />+ <DropdownMenuGroup>+ <DropdownMenuItem+ variant="destructive"+ onSelect={() => setConfirming(true)}+ >+ <TrashCan />+ Delete+ </DropdownMenuItem>+ </DropdownMenuGroup>+ </BulkActionsMenu>++ <BulkDeleteDialog+ open={confirming}+ onOpenChange={setConfirming}+ title={`Delete ${contacts(ids.length)}?`}+ description="Their email addresses are suppressed, so the inbox sync will not file them again. This cannot be undone."+ onConfirm={() => remove.mutate({ ids })}+ />+ </>+ );+}diff --git a/apps/app/app/(app)/[slug]/contacts/contacts-table.tsx b/apps/app/app/(app)/[slug]/contacts/contacts-table.tsxindex e6148131..97b7ef54 100644--- a/apps/app/app/(app)/[slug]/contacts/contacts-table.tsx+++ b/apps/app/app/(app)/[slug]/contacts/contacts-table.tsx@@ -7,10 +7,13 @@ import {} from "@crm/ui/components/data-table";import { EmptyCellValue } from "@crm/ui/components/empty-cell";import { PersonAvatar } from "@crm/ui/components/person-avatar";+import { useTableSelection } from "@crm/ui/hooks/use-table-selection";import { relativeTimeFromIso } from "@crm/ui/lib/format";import { useQuery } from "@tanstack/react-query";+import { useMemo } from "react";import { CompanyCell } from "@/components/crm/company-cell";import { contactName } from "@/components/crm/contact-name";+import { useFieldColumns } from "@/components/crm/fields/field-columns";import { OwnerCell } from "@/components/crm/owner-cell";import { usePrefetchRecord } from "@/components/crm/record-sheet/record-prefetch";import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";@@ -18,6 +21,7 @@ import { ListSearch } from "@/components/data-table/list-search";import { useTableQuery } from "@/components/data-table/use-table-query";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";+import { ContactsBulkActions } from "./contacts-bulk-actions";import { contactsSearchParams } from "./contacts-search-params";type ContactRow = RouterOutputs["contacts"]["list"]["rows"][number];@@ -124,6 +128,11 @@ export function ContactsTable() {const users = useQuery(trpc.users.list.queryOptions());const companies = useQuery(trpc.companies.options.queryOptions({ q: "" }));+ const rows = contacts.data?.rows ?? [];+ const selection = useTableSelection(+ useMemo(() => rows.map((row) => row.id), [rows]),+ );+const facetCounts = contacts.data?.facetCounts;const facets: DataTableFacet[] = [@@ -151,15 +160,25 @@ export function ContactsTable() {},];+ const fieldColumns = useFieldColumns<ContactRow>("CONTACT");+ const columns = useMemo(() => [...COLUMNS, ...fieldColumns], [fieldColumns]);+return (<DataTablequery={query}search={<ListSearch placeholder="Search by name, email or company…" />}- columns={COLUMNS}- rows={contacts.data?.rows ?? []}+ columns={columns}+ rows={rows}total={contacts.data?.total ?? 0}facetCounts={facetCounts}facets={facets}+ selection={{+ state: selection,+ actions: (+ <ContactsBulkActions ids={selection.ids} onDone={selection.clear} />+ ),+ rowLabel: (row) => contactName(row),+ }}getRowId={(row) => row.id}loading={contacts.isFetching}onRowHover={(row) => prefetchRecord({ kind: "contact", id: row.id })}diff --git a/apps/app/app/(app)/[slug]/deals/deals-bulk-actions.tsx b/apps/app/app/(app)/[slug]/deals/deals-bulk-actions.tsxnew file mode 100644index 00000000..7fcade36--- /dev/null+++ b/apps/app/app/(app)/[slug]/deals/deals-bulk-actions.tsx@@ -0,0 +1,214 @@+"use client";++import TrashCan from "@carbon/icons-react/es/TrashCan";+import type { DealStage } from "@crm/db/enums";+import { Button } from "@crm/ui/components/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@crm/ui/components/dialog";+import {+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+} from "@crm/ui/components/dropdown-menu";+import { Field, FieldLabel } from "@crm/ui/components/field";+import { Spinner } from "@crm/ui/components/spinner";+import { Textarea } from "@crm/ui/components/textarea";+import { formatCount } from "@crm/ui/lib/format";+import { useMutation, useQuery } from "@tanstack/react-query";+import { useId, useState } from "react";+import { toast } from "sonner";+import {+ BulkActionsMenu,+ BulkDeleteDialog,+ BulkOwnerMenu,+ reportBulk,+} from "@/components/crm/bulk-actions";+import { DEAL_STAGE_OPTIONS, LOSING_STAGES } from "@/components/crm/deal-stage";+import { useCrmCache } from "@/lib/trpc/cache";+import { useTRPC } from "@/lib/trpc/client";++function deals(count: number): string {+ return formatCount(count, "deal");+}++export function DealsBulkActions({+ ids,+ onDone,+}: {+ ids: string[];+ onDone: () => void;+}) {+ const trpc = useTRPC();+ const cache = useCrmCache();+ const users = useQuery(trpc.users.list.queryOptions());+ const reasonId = useId();+ const [confirming, setConfirming] = useState(false);+ const [closing, setClosing] = useState<DealStage | null>(null);+ const [reason, setReason] = useState("");++ const onError = (error: { message: string }) => toast.error(error.message);++ const assignOwner = useMutation(+ trpc.deals.bulkAssignOwner.mutationOptions({+ onSuccess: async (result) => {+ await cache.deal();+ reportBulk(result, (count) => `${deals(count)} reassigned.`);+ onDone();+ },+ onError,+ }),+ );++ const setStage = useMutation(+ trpc.deals.bulkSetStage.mutationOptions({+ onSuccess: async (result) => {+ await cache.deal();+ reportBulk(result, (count) => `${deals(count)} moved.`);+ setClosing(null);+ setReason("");+ onDone();+ },+ onError,+ }),+ );++ const remove = useMutation(+ trpc.deals.bulkDelete.mutationOptions({+ onSuccess: async (result, variables) => {+ await cache.removedMany({ kind: "deal", ids: variables.ids });+ reportBulk(result, (count) => `${deals(count)} deleted.`);+ setConfirming(false);+ onDone();+ },+ onError,+ }),+ );++ const pending =+ assignOwner.isPending || setStage.isPending || remove.isPending;++ return (+ <>+ <BulkActionsMenu pending={pending}>+ <BulkOwnerMenu+ users={users.data ?? []}+ onSelect={(ownerId) =>+ ownerId && assignOwner.mutate({ ids, ownerId })+ }+ />+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>Change stage</DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-72 overflow-y-auto">+ <DropdownMenuGroup>+ {DEAL_STAGE_OPTIONS.map((option) => (+ <DropdownMenuItem+ key={option.value}+ onSelect={() => {+ if (LOSING_STAGES.includes(option.value)) {+ setClosing(option.value);+ return;+ }+ setStage.mutate({ ids, stage: option.value });+ }}+ >+ {option.label}+ </DropdownMenuItem>+ ))}+ </DropdownMenuGroup>+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuSeparator />+ <DropdownMenuGroup>+ <DropdownMenuItem+ variant="destructive"+ onSelect={() => setConfirming(true)}+ >+ <TrashCan />+ Delete+ </DropdownMenuItem>+ </DropdownMenuGroup>+ </BulkActionsMenu>++ <Dialog+ open={closing !== null}+ onOpenChange={(next) => {+ if (next) return;+ setClosing(null);+ setReason("");+ }}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle>+ {closing === "CLOSED_LOST"+ ? `Close ${deals(ids.length)} as lost`+ : `Mark ${deals(ids.length)} as unqualified`}+ </DialogTitle>+ <DialogDescription>+ The same reason goes on every one of them, so keep it to what they+ have in common.+ </DialogDescription>+ </DialogHeader>++ <form+ id="bulk-close-reason"+ className="px-4"+ onSubmit={(event) => {+ event.preventDefault();+ if (!closing) return;+ setStage.mutate({ ids, stage: closing, closedReason: reason });+ }}+ >+ <Field>+ <FieldLabel htmlFor={reasonId}>Reason</FieldLabel>+ <Textarea+ id={reasonId}+ value={reason}+ onChange={(event) => setReason(event.target.value)}+ placeholder="Budget pulled for the quarter"+ rows={3}+ />+ </Field>+ </form>++ <DialogFooter>+ <Button+ type="submit"+ form="bulk-close-reason"+ disabled={setStage.isPending || reason.trim() === ""}+ >+ {setStage.isPending ? <Spinner /> : null}+ Save+ </Button>+ <Button+ variant="outline"+ onClick={() => {+ setClosing(null);+ setReason("");+ }}+ >+ Cancel+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ <BulkDeleteDialog+ open={confirming}+ onOpenChange={setConfirming}+ title={`Delete ${deals(ids.length)}?`}+ description="Everything filed against them — activity, notes, the amounts in your pipeline — goes too. This cannot be undone."+ onConfirm={() => remove.mutate({ ids })}+ />+ </>+ );+}diff --git a/apps/app/app/(app)/[slug]/deals/deals-table.tsx b/apps/app/app/(app)/[slug]/deals/deals-table.tsxindex 7881c8dd..83c8ba20 100644--- a/apps/app/app/(app)/[slug]/deals/deals-table.tsx+++ b/apps/app/app/(app)/[slug]/deals/deals-table.tsx@@ -6,11 +6,14 @@ import {type DataTableFacet,} from "@crm/ui/components/data-table";import { EmptyCellValue } from "@crm/ui/components/empty-cell";+import { useTableSelection } from "@crm/ui/hooks/use-table-selection";import { formatMoney, relativeTimeFromIso } from "@crm/ui/lib/format";import { useQuery } from "@tanstack/react-query";+import { useMemo } from "react";import { CLOSING_OPTIONS } from "@/components/crm/closing-window";import { CompanyCell } from "@/components/crm/company-cell";import { DEAL_STAGE_OPTIONS } from "@/components/crm/deal-stage";+import { useFieldColumns } from "@/components/crm/fields/field-columns";import { OwnerCell } from "@/components/crm/owner-cell";import { usePrefetchRecord } from "@/components/crm/record-sheet/record-prefetch";import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";@@ -19,6 +22,7 @@ import { ListSearch } from "@/components/data-table/list-search";import { useTableQuery } from "@/components/data-table/use-table-query";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";+import { DealsBulkActions } from "./deals-bulk-actions";import { dealsSearchParams } from "./deals-search-params";type DealRow = RouterOutputs["deals"]["list"]["rows"][number];@@ -132,6 +136,11 @@ export function DealsTable() {});const users = useQuery(trpc.users.list.queryOptions());+ const rows = deals.data?.rows ?? [];+ const selection = useTableSelection(+ useMemo(() => rows.map((row) => row.id), [rows]),+ );+const facetCounts = deals.data?.facetCounts;const facets: DataTableFacet[] = [@@ -164,12 +173,15 @@ export function DealsTable() {const uncounted = unconverted?.count ?? 0;const openPipelineCents = openValueCents ?? (uncounted > 0 ? 0 : null);+ const fieldColumns = useFieldColumns<DealRow>("DEAL");+ const columns = useMemo(() => [...COLUMNS, ...fieldColumns], [fieldColumns]);+return (<DataTablequery={query}search={<ListSearch placeholder="Search deals by name or company…" />}- columns={COLUMNS}- rows={deals.data?.rows ?? []}+ columns={columns}+ rows={rows}total={deals.data?.total ?? 0}facetCounts={facetCounts}facets={facets}@@ -181,6 +193,13 @@ export function DealsTable() {{ value: "closed", label: "Closed" },],}}+ selection={{+ state: selection,+ actions: (+ <DealsBulkActions ids={selection.ids} onDone={selection.clear} />+ ),+ rowLabel: (row) => row.name,+ }}getRowId={(row) => row.id}loading={deals.isFetching}onRowHover={(row) => prefetchRecord({ kind: "deal", id: row.id })}diff --git a/apps/app/app/(app)/[slug]/settings/settings-sidebar.tsx b/apps/app/app/(app)/[slug]/settings/settings-sidebar.tsxindex 062c2bc6..3c561d1b 100644--- a/apps/app/app/(app)/[slug]/settings/settings-sidebar.tsx+++ b/apps/app/app/(app)/[slug]/settings/settings-sidebar.tsx@@ -16,10 +16,10 @@ const ROOT = "/settings";const ITEMS: SettingsNavItem[] = [{ title: "General", href: ROOT },+ { title: "Connections", href: `${ROOT}/connections` },{ title: "Currencies", href: `${ROOT}/currencies` },{ title: "Members", href: `${ROOT}/members` },{ title: "SSO", href: `${ROOT}/sso` },- { title: "Connections", href: `${ROOT}/connections` },];function isActive(href: string, root: string, pathname: string): boolean {diff --git a/apps/app/components/crm/bulk-actions.tsx b/apps/app/components/crm/bulk-actions.tsxnew file mode 100644index 00000000..a4f656e9--- /dev/null+++ b/apps/app/components/crm/bulk-actions.tsx@@ -0,0 +1,148 @@+"use client";++import ChevronDown from "@carbon/icons-react/es/ChevronDown";+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,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger,+} from "@crm/ui/components/dropdown-menu";+import { Spinner } from "@crm/ui/components/spinner";+import type { ReactNode } from "react";+import { toast } from "sonner";++export type BulkResult = {+ requested: number;+ succeeded: number;+ failed: number;+ message: string | null;+};++export function reportBulk(+ result: BulkResult,+ done: (count: number) => string,+): void {+ if (result.succeeded === 0) {+ toast.error(result.message ?? "Nothing changed.");+ return;+ }++ if (result.failed > 0) {+ toast.error(+ `${done(result.succeeded)} ${result.failed} were left alone${+ result.message ? ` — ${result.message}` : "."+ }`,+ );+ return;+ }++ toast.success(done(result.succeeded));+}++export function BulkActionsMenu({+ pending,+ children,+}: {+ pending?: boolean;+ children: ReactNode;+}) {+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="outline" size="sm" disabled={pending}>+ {pending ? <Spinner /> : null}+ Actions+ <ChevronDown data-icon="inline-end" className="opacity-60" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="min-w-52">+ {children}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++export function BulkOwnerMenu({+ users,+ onSelect,+ unassignedLabel,+}: {+ users: { id: string; name: string }[];+ onSelect: (ownerId: string | null) => void;+ unassignedLabel?: string;+}) {+ return (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>Assign owner</DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="max-h-72 overflow-y-auto">+ <DropdownMenuGroup>+ {unassignedLabel && (+ <DropdownMenuItem onSelect={() => onSelect(null)}>+ {unassignedLabel}+ </DropdownMenuItem>+ )}+ {users.length === 0 ? (+ <DropdownMenuLabel>Nobody else works here yet.</DropdownMenuLabel>+ ) : (+ users.map((user) => (+ <DropdownMenuItem+ key={user.id}+ onSelect={() => onSelect(user.id)}+ >+ {user.name}+ </DropdownMenuItem>+ ))+ )}+ </DropdownMenuGroup>+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ );+}++export function BulkDeleteDialog({+ open,+ onOpenChange,+ title,+ description,+ onConfirm,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ title: string;+ description: string;+ onConfirm: () => void;+}) {+ return (+ <AlertDialog open={open} onOpenChange={onOpenChange}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{title}</AlertDialogTitle>+ <AlertDialogDescription>{description}</AlertDialogDescription>+ </AlertDialogHeader>++ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction variant="destructive" onClick={onConfirm}>+ Delete+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}diff --git a/apps/app/components/crm/fields/field-columns.tsx b/apps/app/components/crm/fields/field-columns.tsxnew file mode 100644index 00000000..58b1623c--- /dev/null+++ b/apps/app/components/crm/fields/field-columns.tsx@@ -0,0 +1,61 @@+"use client";++import type { DataTableColumn } from "@crm/ui/components/data-table";+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 { useTRPC } from "@/lib/trpc/client";+import type { FieldEntity } from "./fields-entity";++type WithFields = { fields: Record<string, string | number | boolean | null> };++function render(+ type: string,+ value: string | number | boolean | null,+ options: { id: string; label: string }[],+) {+ 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 === "NUMBER") {+ return <span className="tabular-nums">{String(value)}</span>;+ }++ return String(value);+}++export function useFieldColumns<Row extends WithFields>(+ entity: FieldEntity,+): DataTableColumn<Row>[] {+ const trpc = useTRPC();+ const query = useQuery(+ trpc.fields.list.queryOptions({ entity, includeArchived: false }),+ );++ const fields = query.data;++ return useMemo(() => {+ if (!fields) return [];++ return fields+ .filter((field) => field.showOnTable)+ .map((field) => ({+ id: `field:${field.key}`,+ header: field.label,+ width: "w-[12%]",+ hideBelow: "lg" as const,+ cell: (row: Row) => (+ <span className="truncate">+ {render(field.type, row.fields[field.key] ?? null, field.options)}+ </span>+ ),+ }));+ }, [fields]);+}diff --git a/apps/app/components/crm/fields/field-editor.tsx b/apps/app/components/crm/fields/field-editor.tsxnew file mode 100644index 00000000..f86d573c--- /dev/null+++ b/apps/app/components/crm/fields/field-editor.tsx@@ -0,0 +1,434 @@+"use client";++import Add from "@carbon/icons-react/es/Add";+import Close from "@carbon/icons-react/es/Close";+import {+ FIELD_TYPES,+ fieldKeyFromLabel,+ typeLabel,+} from "@crm/db/fields-shape";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@crm/ui/components/alert-dialog";+import { Button } from "@crm/ui/components/button";+import { Checkbox } from "@crm/ui/components/checkbox";+import {+ Field,+ FieldDescription,+ FieldLabel,+ FieldTitle,+} from "@crm/ui/components/field";+import { Icon } from "@crm/ui/components/icon";+import { Input } from "@crm/ui/components/input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@crm/ui/components/select";+import { SortableItem, SortableList } from "@crm/ui/components/sortable-list";+import { StatusIndicator } from "@crm/ui/components/status-indicator";+import { Switch } from "@crm/ui/components/switch";+import { Textarea } from "@crm/ui/components/textarea";+import { useMutation, useQuery } from "@tanstack/react-query";+import { useId, useState } from "react";+import { toast } from "sonner";+import { useCrmCache } from "@/lib/trpc/cache";+import { useTRPC } from "@/lib/trpc/client";+import type { RouterOutputs } from "@/lib/trpc/types";+import {+ ADD_FIELD,+ ADD_OPTION,+ AGENT_HELP,+ AGENT_LABEL,+ ARCHIVE,+ BRIEF_HELP,+ BRIEF_LABEL,+ CANCEL,+ FILL_REST,+ KEY_HELP,+ KEY_LABEL,+ LABEL_LABEL,+ OPTIONS_LABEL,+ SAVE,+ sheetPlacement,+ TYPE_LABEL,+ tablePlacement,+} from "./fields-copy";+import type { FieldEntity } from "./fields-entity";++const COVERAGE_NOUN: Record<FieldEntity, string> = {+ COMPANY: "companies",+ CONTACT: "contacts",+ DEAL: "deals",+};++type FieldRecord = RouterOutputs["fields"]["list"][number];++type Draft = {+ label: string;+ type: (typeof FIELD_TYPES)[number];+ options: { id?: string; label: string }[];+ agentFilled: boolean;+ agentBrief: string;+ showOnSheet: boolean;+ showOnTable: boolean;+};++const TYPE_HINTS: Record<string, string> = {+ TEXT: "Text — a short line",+ LONG_TEXT: "Long text — a paragraph",+ NUMBER: "Number",+ DATE: "Date",+ CHECKBOX: "Checkbox — yes or no",+ SELECT: "Select — one of a fixed list",+ URL: "URL",+ EMAIL: "Email",+ PHONE: "Phone",+ USER: "User — someone in the workspace",+};++function optionId(option: { id?: string }, index: number): string {+ return option.id ?? `draft-${index}`;+}++const SECTION = "flex flex-col gap-4 border-b px-5 py-4";++function draftFrom(field: FieldRecord | undefined): Draft {+ return {+ label: field?.label ?? "",+ type: field?.type ?? "TEXT",+ options:+ field?.options.map((option) => ({+ id: option.id,+ label: option.label,+ })) ?? [],+ agentFilled: field?.agentFilled ?? true,+ agentBrief: field?.agentBrief ?? "",+ showOnSheet: field?.showOnSheet ?? true,+ showOnTable: field?.showOnTable ?? false,+ };+}++function Coverage({ field }: { field: FieldRecord }) {+ const trpc = useTRPC();+ 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."),+ onError: (error) => toast.error(error.message),+ }),+ );++ if (!field.agentFilled || !coverage.data) return null;++ const { filled, total } = coverage.data;+ const noun = COVERAGE_NOUN[field.entity as FieldEntity];++ return (+ <div className="shrink-0 border-t px-5 py-3">+ <div className="flex items-center gap-3 rounded-md bg-muted p-3">+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">+ <StatusIndicator+ tone="primary"+ className="font-medium text-foreground"+ label={`Filled on ${filled} of ${total} ${noun}`}+ />+ <span className="pl-4 text-muted-foreground text-xs">+ {total - filled} still to go+ </span>+ </div>+ <Button+ variant="outline"+ size="sm"+ disabled={backfill.isPending}+ onClick={() => backfill.mutate({ id: field.id })}+ >+ {FILL_REST}+ </Button>+ </div>+ </div>+ );+}++export function FieldEditor({+ entity,+ field,+ onDone,+}: {+ entity: FieldEntity;+ field: FieldRecord | undefined;+ onDone: () => void;+}) {+ const trpc = useTRPC();+ const cache = useCrmCache();+ const labelId = useId();+ const briefId = useId();++ const [draft, setDraft] = useState<Draft>(() => draftFrom(field));+ const [confirming, setConfirming] = useState(false);++ const patch = (next: Partial<Draft>) =>+ setDraft((current) => ({ ...current, ...next }));++ const settle = async () => {+ await cache.fields();+ onDone();+ };++ const create = useMutation(+ trpc.fields.create.mutationOptions({+ onSuccess: settle,+ onError: (error) => toast.error(error.message),+ }),+ );++ const update = useMutation(+ trpc.fields.update.mutationOptions({+ onSuccess: settle,+ onError: (error) => toast.error(error.message),+ }),+ );++ const archive = useMutation(+ trpc.fields.archive.mutationOptions({+ onSuccess: settle,+ onError: (error) => toast.error(error.message),+ }),+ );++ const key = field?.key ?? fieldKeyFromLabel(draft.label);+ const saving = create.isPending || update.isPending;++ const save = () => {+ const payload = {+ label: draft.label,+ type: draft.type,+ options: draft.options.filter((option) => option.label.trim() !== ""),+ agentFilled: draft.agentFilled,+ agentBrief: draft.agentBrief.trim() || null,+ showOnSheet: draft.showOnSheet,+ showOnTable: draft.showOnTable,+ };++ if (field) {+ update.mutate({ id: field.id, data: payload });+ return;+ }++ create.mutate({ ...payload, entity, required: false });+ };++ return (+ <>+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto">+ <div className={SECTION}>+ <Field>+ <FieldLabel htmlFor={labelId}>{LABEL_LABEL}</FieldLabel>+ <Input+ id={labelId}+ value={draft.label}+ onChange={(event) => patch({ label: event.target.value })}+ />+ </Field>++ <Field>+ <div className="flex items-baseline justify-between gap-2">+ <FieldTitle>{KEY_LABEL}</FieldTitle>+ <span className="font-mono text-muted-foreground text-xs">+ {key || "—"}+ </span>+ </div>+ <FieldDescription>{KEY_HELP}</FieldDescription>+ </Field>+ </div>++ <div className={SECTION}>+ <Field orientation="horizontal">+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">+ <FieldTitle>{AGENT_LABEL}</FieldTitle>+ <FieldDescription>{AGENT_HELP}</FieldDescription>+ </div>+ <Switch+ checked={draft.agentFilled}+ onCheckedChange={(agentFilled) => patch({ agentFilled })}+ />+ </Field>++ <Field>+ <FieldLabel htmlFor={briefId}>{BRIEF_LABEL}</FieldLabel>+ <Textarea+ id={briefId}+ rows={3}+ value={draft.agentBrief}+ onChange={(event) => patch({ agentBrief: event.target.value })}+ />+ <FieldDescription>{BRIEF_HELP}</FieldDescription>+ </Field>+ </div>++ <div className={SECTION}>+ <Field>+ <FieldTitle>{TYPE_LABEL}</FieldTitle>+ <Select+ value={draft.type}+ onValueChange={(value) => patch({ type: value as Draft["type"] })}+ >+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {FIELD_TYPES.map((type) => (+ <SelectItem key={type} value={type}>+ {TYPE_HINTS[type] ?? typeLabel(type)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>++ {draft.type === "SELECT" ? (+ <Field>+ <FieldTitle>{OPTIONS_LABEL}</FieldTitle>+ <SortableList+ ids={draft.options.map(optionId)}+ onReorder={(ids) =>+ patch({+ options: ids+ .map((id) =>+ draft.options.find(+ (option, at) => optionId(option, at) === id,+ ),+ )+ .filter((option): option is Draft["options"][number] =>+ Boolean(option),+ ),+ })+ }+ >+ <div className="flex flex-col gap-1.5">+ {draft.options.map((option, index) => (+ <SortableItem+ key={optionId(option, index)}+ id={optionId(option, index)}+ label={option.label || "option"}+ >+ <Input+ value={option.label}+ onChange={(event) =>+ patch({+ options: draft.options.map((entry, at) =>+ at === index+ ? { ...entry, label: event.target.value }+ : entry,+ ),+ })+ }+ />+ <Button+ variant="ghost"+ size="icon-xs"+ onClick={() =>+ patch({+ options: draft.options.filter(+ (_, at) => at !== index,+ ),+ })+ }+ >+ <Icon icon={Close} />+ <span className="sr-only">Remove option</span>+ </Button>+ </SortableItem>+ ))}+ </div>+ </SortableList>+ <Button+ variant="ghost"+ size="sm"+ className="self-start"+ onClick={() =>+ patch({ options: [...draft.options, { label: "" }] })+ }+ >+ <Icon icon={Add} data-icon="inline-start" />+ {ADD_OPTION}+ </Button>+ </Field>+ ) : null}+ </div>++ <div className="flex flex-col gap-2.5 border-b px-5 py-4">+ <FieldLabel className="items-center gap-2 font-normal">+ <Checkbox+ checked={draft.showOnSheet}+ onCheckedChange={(checked) =>+ patch({ showOnSheet: checked === true })+ }+ />+ {sheetPlacement(entity)}+ </FieldLabel>+ <FieldLabel className="items-center gap-2 font-normal">+ <Checkbox+ checked={draft.showOnTable}+ onCheckedChange={(checked) =>+ patch({ showOnTable: checked === true })+ }+ />+ {tablePlacement(entity)}+ </FieldLabel>+ </div>+ </div>++ {field ? <Coverage field={field} /> : null}++ <div className="flex shrink-0 items-center gap-2 border-t px-5 py-3">+ <Button disabled={saving || draft.label.trim() === ""} onClick={save}>+ {field ? SAVE : ADD_FIELD}+ </Button>+ {field ? (+ <Button variant="outline" onClick={() => setConfirming(true)}>+ {ARCHIVE}+ </Button>+ ) : (+ <Button variant="outline" onClick={onDone}>+ {CANCEL}+ </Button>+ )}+ </div>++ {field ? (+ <AlertDialog open={confirming} onOpenChange={setConfirming}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Archive {field.label}?</AlertDialogTitle>+ <AlertDialogDescription>+ Hidden everywhere. Its values are kept.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>{CANCEL}</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() => archive.mutate({ id: field.id })}+ >+ Archive field+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ ) : null}+ </>+ );+}diff --git a/apps/app/components/crm/fields/fields-copy.ts b/apps/app/components/crm/fields/fields-copy.tsnew file mode 100644index 00000000..21a0a568--- /dev/null+++ b/apps/app/components/crm/fields/fields-copy.ts@@ -0,0 +1,74 @@+import type { RecordKind } from "@/components/crm/record-sheet/record-stack";+import type { FieldEntity } from "./fields-entity";++export const SHEET_TITLE = "Fields";++const SUBTITLE: Record<RecordKind, string> = {+ company: "This shapes every company in your CRM.",+ contact: "This shapes every contact in your CRM.",+ deal: "This shapes every deal in your CRM.",+};++export function subtitleFor(kind: RecordKind): string {+ return SUBTITLE[kind];+}++export const STANDARD_ROW = "Standard fields";+export const STANDARD_NOTE = "reorder and hide only";+export const CUSTOM_GROUP = "Custom fields";+export const DRAG_NOTE = "Drag to order";+export const ARCHIVED_ROW = "Archived";+export const ARCHIVED_NOTE = "values kept, hidden everywhere";+export const NEW_FIELD = "New field";+export const ORDER_NOTE = "Order here is the order on the sheet";+export const MANUAL_ONLY = "Manual only";+export const TABLE_NOTE = "also a column on the table";++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 LABEL_LABEL = "Label";+export const KEY_LABEL = "Key";+export const KEY_HELP =+ "What the API and your agents call it. Set from the label, fixed once saved — renaming the label later never breaks a caller.";+export const AGENT_LABEL = "Let your agents fill this";+export const AGENT_HELP =+ "They propose a value with a source, and never overwrite yours.";+export const BRIEF_LABEL = "What counts as an answer";+export const BRIEF_HELP =+ "Leave it empty and your agents work from the label and type alone.";+export const TYPE_LABEL = "Type";+export const OPTIONS_LABEL = "Options";+export const ADD_OPTION = "Add option";+export const ADD_FIELD = "Create field";+export const CANCEL = "Cancel";+export const SAVE = "Save changes";+export const ARCHIVE = "Archive";+export const FILL_REST = "Fill the rest";++const SHEET_PLACEMENT: Record<FieldEntity, string> = {+ COMPANY: "Show on the company sheet",+ CONTACT: "Show on the contact sheet",+ DEAL: "Show on the deal sheet",+};++const TABLE_PLACEMENT: Record<FieldEntity, string> = {+ COMPANY: "Offer as a column on the Companies table",+ CONTACT: "Offer as a column on the Contacts table",+ DEAL: "Offer as a column on the Deals table",+};++export function sheetPlacement(entity: FieldEntity): string {+ return SHEET_PLACEMENT[entity];+}++export function tablePlacement(entity: FieldEntity): string {+ return TABLE_PLACEMENT[entity];+}++export const ENTITY_TABS = [+ { kind: "company", label: "Companies" },+ { kind: "contact", label: "Contacts" },+ { kind: "deal", label: "Deals" },+] as const satisfies readonly { kind: RecordKind; label: string }[];diff --git a/apps/app/components/crm/fields/fields-entity.ts b/apps/app/components/crm/fields/fields-entity.tsnew file mode 100644index 00000000..a7e1c88a--- /dev/null+++ b/apps/app/components/crm/fields/fields-entity.ts@@ -0,0 +1,23 @@+import type { RecordKind } from "@/components/crm/record-sheet/record-stack";++export type FieldEntity = "COMPANY" | "CONTACT" | "DEAL";++const TO_ENTITY: Record<RecordKind, FieldEntity> = {+ company: "COMPANY",+ contact: "CONTACT",+ deal: "DEAL",+};++const TO_KIND: Record<FieldEntity, RecordKind> = {+ COMPANY: "company",+ CONTACT: "contact",+ DEAL: "deal",+};++export function entityOf(kind: RecordKind): FieldEntity {+ return TO_ENTITY[kind];+}++export function kindOf(entity: FieldEntity): RecordKind {+ return TO_KIND[entity];+}diff --git a/apps/app/components/crm/fields/fields-list.tsx b/apps/app/components/crm/fields/fields-list.tsxnew file mode 100644index 00000000..a9e5da43--- /dev/null+++ b/apps/app/components/crm/fields/fields-list.tsx@@ -0,0 +1,295 @@+"use client";++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 { Badge } from "@crm/ui/components/badge";+import { Button } from "@crm/ui/components/button";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@crm/ui/components/collapsible";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@crm/ui/components/dropdown-menu";+import {+ Empty,+ EmptyContent,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+} from "@crm/ui/components/empty";+import { Icon } from "@crm/ui/components/icon";+import { SortableItem, SortableList } from "@crm/ui/components/sortable-list";+import { Spinner } from "@crm/ui/components/spinner";+import { useMutation, useQuery } from "@tanstack/react-query";+import { toast } from "sonner";+import { useCrmCache } from "@/lib/trpc/cache";+import { useTRPC } from "@/lib/trpc/client";+import type { RouterOutputs } from "@/lib/trpc/types";+import {+ ARCHIVED_NOTE,+ ARCHIVED_ROW,+ CUSTOM_GROUP,+ DRAG_NOTE,+ EMPTY_BODY,+ EMPTY_TITLE,+ MANUAL_ONLY,+ NEW_FIELD,+ ORDER_NOTE,+ STANDARD_NOTE,+ STANDARD_ROW,+ TABLE_NOTE,+} from "./fields-copy";+import type { FieldEntity } from "./fields-entity";+import { STANDARD_FIELDS } from "./standard-fields";++type Field = RouterOutputs["fields"]["list"][number];++const ROW = "flex items-center gap-2.5 border-b px-5 py-2";++function summaryOf(field: Field): string {+ const parts: string[] = [];++ if (field.agentFilled) {+ parts.push(+ field.agentBrief ??+ (field.options.length > 0+ ? `${field.options.length} options`+ : field.label),+ );+ } else {+ parts.push(MANUAL_ONLY);+ if (field.required) parts.push("required");+ }++ if (field.showOnTable) parts.push(TABLE_NOTE);++ return parts.join(" · ");+}++function DisclosureRow({+ title,+ note,+ children,+}: {+ title: string;+ note: string;+ children: React.ReactNode;+}) {+ return (+ <Collapsible>+ <CollapsibleTrigger asChild>+ <button+ type="button"+ className="flex w-full items-center gap-2 border-b px-5 py-2.5 text-left"+ >+ <Icon+ icon={ChevronRight}+ className="shrink-0 text-muted-foreground"+ />+ <span className="flex-1 font-medium text-foreground text-xs">+ {title}+ </span>+ <span className="shrink-0 text-muted-foreground text-xs">{note}</span>+ </button>+ </CollapsibleTrigger>+ <CollapsibleContent>{children}</CollapsibleContent>+ </Collapsible>+ );+}++export function FieldsList({+ entity,+ onEdit,+ onNew,+}: {+ entity: FieldEntity;+ onEdit: (key: string) => void;+ onNew: () => void;+}) {+ const trpc = useTRPC();+ const cache = useCrmCache();++ const query = useQuery(+ trpc.fields.list.queryOptions({ entity, includeArchived: true }),+ );++ const reorder = useMutation(+ trpc.fields.reorder.mutationOptions({+ onSuccess: () => cache.fields(),+ onError: (error) => toast.error(error.message),+ }),+ );++ const archive = useMutation(+ trpc.fields.archive.mutationOptions({+ onSuccess: () => cache.fields(),+ onError: (error) => toast.error(error.message),+ }),+ );++ const restore = useMutation(+ trpc.fields.restore.mutationOptions({+ onSuccess: () => cache.fields(),+ onError: (error) => toast.error(error.message),+ }),+ );++ const all = query.data ?? [];+ const live = all.filter((field) => !field.archived);+ const archived = all.filter((field) => field.archived);+ const standard = STANDARD_FIELDS[entity];++ return (+ <>+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto">+ <DisclosureRow+ title={STANDARD_ROW}+ note={`${standard.length} · ${STANDARD_NOTE}`}+ >+ <ul className="border-b bg-muted/40 py-1">+ {standard.map((field) => (+ <li+ key={field}+ className="px-5 py-1 text-muted-foreground text-xs"+ >+ {field}+ </li>+ ))}+ </ul>+ </DisclosureRow>++ {query.isPending ? (+ <div className="flex flex-1 items-center justify-center">+ <Spinner />+ </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}+ >+ <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>++ <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+ title={ARCHIVED_ROW}+ note={`${archived.length} · ${ARCHIVED_NOTE}`}+ >+ <ul className="border-b">+ {archived.map((field) => (+ <li+ key={field.id}+ className="flex items-center gap-2.5 px-5 py-2"+ >+ <span className="flex-1 truncate text-muted-foreground text-xs">+ {field.label}+ </span>+ <Button+ variant="outline"+ size="xs"+ onClick={() => restore.mutate({ id: field.id })}+ >+ Restore+ </Button>+ </li>+ ))}+ </ul>+ </DisclosureRow>+ ) : null}+ </>+ )}+ </div>++ {live.length > 0 ? (+ <div className="flex shrink-0 items-center justify-between gap-3 border-t px-5 py-3">+ <Button onClick={onNew}>+ <Icon icon={Add} data-icon="inline-start" />+ {NEW_FIELD}+ </Button>+ <span className="text-right text-muted-foreground text-xs">+ {ORDER_NOTE}+ </span>+ </div>+ ) : null}+ </>+ );+}diff --git a/apps/app/components/crm/fields/fields-sheet.tsx b/apps/app/components/crm/fields/fields-sheet.tsxnew file mode 100644index 00000000..5db37477--- /dev/null+++ b/apps/app/components/crm/fields/fields-sheet.tsx@@ -0,0 +1,136 @@+"use client";++import { Spinner } from "@crm/ui/components/spinner";+import { Tabs, TabsList, TabsTrigger } from "@crm/ui/components/tabs";+import { useQuery } from "@tanstack/react-query";+import {+ type RecordKind,+ useFieldsSheet,+} from "@/components/crm/record-sheet/record-stack";+import { DetailSheet, DetailSheetHeader } from "@/components/detail-sheet";+import { useTRPC } from "@/lib/trpc/client";+import { FieldEditor } from "./field-editor";+import {+ ENTITY_TABS,+ NEW_FIELD,+ SHEET_TITLE,+ subtitleFor,+} from "./fields-copy";+import { entityOf } from "./fields-entity";+import { FieldsList } from "./fields-list";++function FieldsSheetBody({+ kind,+ field,+ onEntity,+ onEdit,+ onClose,+}: {+ kind: RecordKind;+ field: string | null;+ onEntity: (kind: RecordKind) => void;+ onEdit: (key: string | null) => void;+ onClose: () => void;+}) {+ const trpc = useTRPC();+ const entity = entityOf(kind);++ const query = useQuery(+ trpc.fields.list.queryOptions({ entity, includeArchived: true }),+ );++ const editingKey = field && field !== "new" ? field : null;+ const editing = editingKey+ ? query.data?.find((entry) => entry.key === editingKey)+ : undefined;++ const coverage = useQuery({+ ...trpc.fields.coverage.queryOptions({ id: editing?.id ?? "" }),+ enabled: Boolean(editing?.agentFilled),+ });++ if (field) {+ const entityLabel = ENTITY_TABS.find((tab) => tab.kind === kind)?.label;+ const filled = coverage.data;++ return (+ <>+ <DetailSheetHeader+ title={editing?.label ?? (editingKey ? "" : NEW_FIELD)}+ description={+ filled+ ? `${entityLabel} · ${filled.filled} of ${filled.total} filled`+ : entityLabel+ }+ onBack={() => onEdit(null)}+ onClose={onClose}+ />+ {editingKey && query.isPending ? (+ <div className="flex min-h-0 flex-1 items-center justify-center">+ <Spinner />+ </div>+ ) : (+ <FieldEditor+ key={editing?.id ?? "new"}+ entity={entity}+ field={editing}+ onDone={() => onEdit(null)}+ />+ )}+ </>+ );+ }++ return (+ <>+ <DetailSheetHeader+ title={SHEET_TITLE}+ description={subtitleFor(kind)}+ onClose={onClose}+ note={+ <Tabs+ value={kind}+ onValueChange={(next) => onEntity(next as RecordKind)}+ >+ <TabsList>+ {ENTITY_TABS.map((tab) => (+ <TabsTrigger key={tab.kind} value={tab.kind}>+ {tab.label}+ </TabsTrigger>+ ))}+ </TabsList>+ </Tabs>+ }+ />+ <FieldsList+ entity={entity}+ onEdit={(key) => onEdit(key)}+ onNew={() => onEdit("new")}+ />+ </>+ );+}++export function FieldsSheetHost() {+ const { entity, field, open, close, edit } = useFieldsSheet();++ return (+ <DetailSheet+ open={entity !== null}+ size="md"+ onOpenChange={(next) => {+ if (!next) close();+ }}+ >+ {entity ? (+ <FieldsSheetBody+ kind={entity}+ field={field}+ onEntity={open}+ onEdit={edit}+ onClose={close}+ />+ ) : null}+ </DetailSheet>+ );+}diff --git a/apps/app/components/crm/fields/record-fields.tsx b/apps/app/components/crm/fields/record-fields.tsxnew file mode 100644index 00000000..7df27f74--- /dev/null+++ b/apps/app/components/crm/fields/record-fields.tsx@@ -0,0 +1,149 @@+"use client";++import Settings from "@carbon/icons-react/es/Settings";+import { Button } from "@crm/ui/components/button";+import { Checkbox } from "@crm/ui/components/checkbox";+import { Icon } from "@crm/ui/components/icon";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@crm/ui/components/tooltip";+import {+ InlineDateField,+ InlineField,+ InlineSelectField,+ InlineTextArea,+} from "@/components/crm/inline-field";+import {+ type RecordKind,+ useFieldsSheet,+} from "@/components/crm/record-sheet/record-stack";+import { DetailSheetProperty } from "@/components/detail-sheet";++type RecordFieldValue = string | number | boolean | null;++type RecordFieldOption = { id: string; label: string };++export type RecordFieldEntry = {+ id: string;+ key: string;+ label: string;+ type: string;+ showOnSheet: boolean;+ options: RecordFieldOption[];+ value: RecordFieldValue;+};++const NONE = "__none__";++export function FieldsCog({ kind }: { kind: RecordKind }) {+ const { open } = useFieldsSheet();++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button variant="ghost" size="icon-sm" onClick={() => open(kind)}>+ <Icon icon={Settings} />+ <span className="sr-only">Fields</span>+ </Button>+ </TooltipTrigger>+ <TooltipContent>Fields</TooltipContent>+ </Tooltip>+ );+}++export function RecordFields({+ fields,+ saving,+ onSave,+}: {+ fields: RecordFieldEntry[];+ saving: (key: string) => boolean;+ onSave: (values: Record<string, unknown>) => void;+}) {+ return (+ <>+ {fields+ .filter((field) => field.showOnSheet)+ .map((field) => {+ const save = (value: unknown) => onSave({ [field.key]: value });+ const busy = saving(field.key);++ if (field.type === "CHECKBOX") {+ return (+ <DetailSheetProperty key={field.id} label={field.label}>+ <Checkbox+ checked={field.value === true}+ disabled={busy}+ onCheckedChange={(checked) => save(checked === true)}+ />+ </DetailSheetProperty>+ );+ }++ if (field.type === "LONG_TEXT") {+ return (+ <DetailSheetProperty key={field.id} label={field.label} wide>+ <InlineTextArea+ label={field.label}+ value={field.value === null ? null : String(field.value)}+ saving={busy}+ onSave={save}+ />+ </DetailSheetProperty>+ );+ }++ if (field.type === "DATE") {+ return (+ <InlineDateField+ key={field.id}+ label={field.label}+ value={field.value === null ? null : String(field.value)}+ saving={busy}+ onSave={save}+ />+ );+ }++ if (field.type === "SELECT") {+ return (+ <InlineSelectField+ key={field.id}+ label={field.label}+ value={field.value === null ? NONE : String(field.value)}+ options={[+ { value: NONE, label: "None" },+ ...field.options.map((option) => ({+ value: option.id,+ label: option.label,+ })),+ ]}+ onSave={(next) => save(next === NONE ? null : next)}+ />+ );+ }++ return (+ <InlineField+ key={field.id}+ label={field.label}+ type={+ field.type === "URL"+ ? "url"+ : field.type === "EMAIL"+ ? "email"+ : field.type === "PHONE"+ ? "tel"+ : "text"+ }+ value={field.value === null ? null : String(field.value)}+ saving={busy}+ onSave={save}+ />+ );+ })}+ </>+ );+}diff --git a/apps/app/components/crm/fields/standard-fields.ts b/apps/app/components/crm/fields/standard-fields.tsnew file mode 100644index 00000000..55774f5c--- /dev/null+++ b/apps/app/components/crm/fields/standard-fields.ts@@ -0,0 +1,34 @@+import type { FieldEntity } from "./fields-entity";++export const STANDARD_FIELDS: Record<FieldEntity, readonly string[]> = {+ COMPANY: [+ "Name",+ "Domain",+ "Website",+ "Phone",+ "Email",+ "City",+ "Country",+ "Owner",+ ],+ CONTACT: [+ "First name",+ "Last name",+ "Title",+ "Email",+ "Phone",+ "LinkedIn",+ "GitHub",+ "Company",+ "Owner",+ ],+ DEAL: [+ "Name",+ "Amount",+ "Currency",+ "Close date",+ "Company",+ "Owner",+ "Stage",+ ],+};diff --git a/apps/app/components/crm/inline-field.tsx b/apps/app/components/crm/inline-field.tsxindex c81e392a..4123eacb 100644--- a/apps/app/components/crm/inline-field.tsx+++ b/apps/app/components/crm/inline-field.tsx@@ -37,6 +37,14 @@ export function savingField(update: {return (field) => fields.includes(field);}+export function savingValue(update: {+ isPending: boolean;+ variables?: { data?: { fields?: Record<string, unknown> } } | undefined;+}): (key: string) => boolean {+ const fields = update.isPending ? (update.variables?.data?.fields ?? {}) : {};+ return (key) => key in fields;+}+export function InlineField({label,value,@@ -146,6 +154,78 @@ export function InlineField({);}+export function InlineTextCell({+ label,+ value,+ onSave,+ saving = false,+ placeholder,+}: {+ label: string;+ value: string | null;+ onSave: (next: string) => void;+ saving?: boolean;+ placeholder?: string;+}) {+ const [editing, setEditing] = useState(false);+ const [draft, setDraft] = useState(value ?? "");++ const commit = () => {+ setEditing(false);+ if (draft.trim() !== (value ?? "")) onSave(draft.trim());+ };++ if (editing) {+ return (+ <Input+ aria-label={label}+ autoFocus+ value={draft}+ placeholder={placeholder}+ onClick={(event) => event.stopPropagation()}+ onChange={(event) => setDraft(event.target.value)}+ onBlur={commit}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ event.preventDefault();+ commit();+ }+ if (event.key === "Escape") {+ setDraft(value ?? "");+ setEditing(false);+ }+ }}+ />+ );+ }++ const shown = saving ? draft.trim() : (value ?? "");++ return (+ <Button+ variant="ghost"+ size="sm"+ aria-label={label}+ className={CONTROL}+ disabled={saving}+ onClick={(event) => {+ event.stopPropagation();+ setDraft(value ?? "");+ setEditing(true);+ }}+ >+ {saving ? <Spinner /> : null}+ {shown ? (+ <span className="truncate">{shown}</span>+ ) : (+ <span className="truncate text-muted-foreground">+ {placeholder ?? <EmptyCellValue />}+ </span>+ )}+ </Button>+ );+}+export function InlineTextArea({label,value,diff --git a/apps/app/components/crm/record-sheet/company-sheet.tsx b/apps/app/components/crm/record-sheet/company-sheet.tsxindex d7150b58..09609639 100644--- a/apps/app/components/crm/record-sheet/company-sheet.tsx+++ b/apps/app/components/crm/record-sheet/company-sheet.tsx@@ -31,10 +31,12 @@ import {EnrichmentIndicator,isEnriching,} from "@/components/crm/enrichment-status";+import { FieldsCog, RecordFields } from "@/components/crm/fields/record-fields";import {InlineField,InlineSelectField,savingField,+ savingValue,} from "@/components/crm/inline-field";import { OwnerCell } from "@/components/crm/owner-cell";import { CompanySocials, hasCompanyLinks } from "@/components/crm/social-links";@@ -60,6 +62,7 @@ import type { RouterOutputs } from "@/lib/trpc/types";import { QuickAddContact, QuickAddDeal } from "./quick-add";import { RecordActions } from "./record-actions";import {+ AddRow,DealAmount,DomainLink,MetaLine,@@ -132,32 +135,6 @@ function nextClose(deals: CompanyDeal[]): string | null {return dates[0] ?? null;}-function AddRow({- label,- columns,- onClick,-}: {- label: string;- columns: number;- onClick: () => void;-}) {- return (- <SimpleTableRow>- <TableCell colSpan={columns} className="p-0">- <Button- variant="ghost"- size="sm"- onClick={onClick}- className="h-9 w-full justify-start px-5 font-normal text-muted-foreground"- >- <Icon icon={Add} data-icon="inline-start" />- {label}- </Button>- </TableCell>- </SimpleTableRow>- );-}-export function CompanySheet({ companyId }: { companyId: string }) {const trpc = useTRPC();const {@@ -358,7 +335,11 @@ function CompanyOverview({const save = (data: Record<string, string | null>) =>update.mutate({ id: company.id, data });+ const saveFields = (fields: Record<string, unknown>) =>+ update.mutate({ id: company.id, data: { fields } });+const isSaving = savingField(update);+ const isSavingField = savingValue(update);return (<DetailSheetBody>@@ -381,7 +362,10 @@ function CompanyOverview({</DetailSheetMain><DetailSheetRail>- <DetailSheetSection title="Details">+ <DetailSheetSection+ title="Details"+ action={<FieldsCog kind="company" />}+ ><DetailSheetProperties columns={1}><InlineFieldlabel="Name"@@ -445,6 +429,11 @@ function CompanyOverview({save({ ownerId: ownerId === UNASSIGNED ? null : ownerId })}/>+ <RecordFields+ fields={company.fields}+ saving={isSavingField}+ onSave={saveFields}+ /></DetailSheetProperties></DetailSheetSection>diff --git a/apps/app/components/crm/record-sheet/contact-sheet.tsx b/apps/app/components/crm/record-sheet/contact-sheet.tsxindex 4e14e1cd..0c87bcbc 100644--- a/apps/app/components/crm/record-sheet/contact-sheet.tsx+++ b/apps/app/components/crm/record-sheet/contact-sheet.tsx@@ -35,10 +35,12 @@ import {factsByField,provenanceFor,} from "@/components/crm/facts";+import { FieldsCog, RecordFields } from "@/components/crm/fields/record-fields";import {InlineField,InlineSelectField,savingField,+ savingValue,} from "@/components/crm/inline-field";import { OwnerCell } from "@/components/crm/owner-cell";import { ContactSocials, hasContactLinks } from "@/components/crm/social-links";@@ -305,6 +307,11 @@ function ContactOverview({ contact }: { contact: Contact }) {}),);+ const saveFields = (fields: Record<string, unknown>) =>+ update.mutate({ id: contact.id, data: { fields } });++ const isSavingField = savingValue(update);+const save = (data: Record<string, string | null>) =>update.mutate({ id: contact.id, data });@@ -312,7 +319,7 @@ function ContactOverview({ contact }: { contact: Contact }) {return (<DetailSheetBody>- <DetailSheetSection title="Details">+ <DetailSheetSection title="Details" action={<FieldsCog kind="contact" />}><DetailSheetProperties><InlineFieldlabel="First name"@@ -400,6 +407,11 @@ function ContactOverview({ contact }: { contact: Contact }) {save({ ownerId: ownerId === NONE ? null : ownerId })}/>+ <RecordFields+ fields={contact.fields}+ saving={isSavingField}+ onSave={saveFields}+ /></DetailSheetProperties></DetailSheetSection>diff --git a/apps/app/components/crm/record-sheet/deal-sheet.tsx b/apps/app/components/crm/record-sheet/deal-sheet.tsxindex 8d30e100..b6d2a321 100644--- a/apps/app/components/crm/record-sheet/deal-sheet.tsx+++ b/apps/app/components/crm/record-sheet/deal-sheet.tsx@@ -1,15 +1,24 @@"use client";+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 { Button } from "@crm/ui/components/button";import { EmptyCellValue } from "@crm/ui/components/empty-cell";import {EntityLogo,type EntityLogoTone,} from "@crm/ui/components/entity-logo";+import { Icon } from "@crm/ui/components/icon";import { PersonAvatar } from "@crm/ui/components/person-avatar";import { SimpleTable, SimpleTableRow } from "@crm/ui/components/simple-table";import { TableCell } from "@crm/ui/components/table";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@crm/ui/components/tooltip";import {formatDay,formatMoney,@@ -19,12 +28,15 @@ import { useMutation, useQuery } from "@tanstack/react-query";import { toast } from "sonner";import { AgentPanel } from "@/components/crm/agent-panel";import { contactName } from "@/components/crm/contact-name";+import { FieldsCog, RecordFields } from "@/components/crm/fields/record-fields";import {InlineDateField,InlineField,InlineSelectField,InlineTextArea,+ InlineTextCell,savingField,+ savingValue,} from "@/components/crm/inline-field";import { OwnerCell } from "@/components/crm/owner-cell";import { DealStageMenu } from "@/components/crm/stage-change";@@ -43,8 +55,9 @@ import {import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";import type { RouterOutputs } from "@/lib/trpc/types";+import { AttachDealContact } from "./quick-add";import { RecordActions } from "./record-actions";-import { RecordSheetFrame } from "./record-parts";+import { AddRow, RecordSheetFrame } from "./record-parts";import { useOpenRecord, useRecordSheetView } from "./record-stack";type Deal = RouterOutputs["deals"]["byId"];@@ -91,10 +104,11 @@ function ReportedValue({ deal }: { deal: Deal }) {}const CONTACT_COLUMNS = [- { header: "Name", width: "w-[30%]", className: "pl-5" },+ { header: "Name", width: "w-[28%]", className: "pl-5" },{ header: "Role", width: "w-[20%]" },- { header: "Title", width: "w-[25%]" },- { header: "Email", width: "w-[25%]" },+ { header: "Title", width: "w-[22%]" },+ { header: "Email", width: "w-[22%]" },+ { srLabel: "Remove", width: "w-10" },];const dateFormat = new Intl.DateTimeFormat(undefined, {@@ -106,7 +120,12 @@ const dateFormat = new Intl.DateTimeFormat(undefined, {export function DealSheet({ dealId }: { dealId: string }) {const trpc = useTRPC();const openRecord = useOpenRecord();- const { tab, setTab } = useRecordSheetView("overview");+ const {+ tab,+ setTab,+ form: adding,+ setForm: setAdding,+ } = useRecordSheetView("overview");const query = useQuery(trpc.deals.byId.queryOptions({ id: dealId }));const deal = query.data;@@ -122,7 +141,14 @@ export function DealSheet({ dealId }: { dealId: string }) {value: "contacts",label: "Contacts",count: deal.contacts.length,- content: <DealContacts deal={deal} />,+ content: (+ <DealContacts+ deal={deal}+ adding={adding === "contact"}+ onAdd={() => setAdding("contact")}+ onDone={() => setAdding(null)}+ />+ ),},{value: "activity",@@ -230,6 +256,11 @@ function DealOverview({ deal }: { deal: Deal }) {}),);+ const saveFields = (fields: Record<string, unknown>) =>+ update.mutate({ id: deal.id, data: { fields } });++ const isSavingField = savingValue(update);+const save = (data: Parameters<typeof update.mutate>[0]["data"]) =>update.mutate({ id: deal.id, data });@@ -243,7 +274,7 @@ function DealOverview({ deal }: { deal: Deal }) {<StageStepper dealId={deal.id} stage={deal.stage} /></DetailSheetSection>- <DetailSheetSection title="Details">+ <DetailSheetSection title="Details" action={<FieldsCog kind="deal" />}><DetailSheetProperties><InlineFieldlabel="Name"@@ -302,6 +333,11 @@ function DealOverview({ deal }: { deal: Deal }) {}))}onSave={(ownerId) => save({ ownerId })}/>+ <RecordFields+ fields={deal.fields}+ saving={isSavingField}+ onSave={saveFields}+ /></DetailSheetProperties></DetailSheetSection>@@ -379,49 +415,142 @@ function WhereItStands({ deal }: { deal: Deal }) {);}-function DealContacts({ deal }: { deal: Deal }) {+function DealContacts({+ deal,+ adding,+ onAdd,+ onDone,+}: {+ deal: Deal;+ adding: boolean;+ onAdd: () => void;+ onDone: () => void;+}) {+ const trpc = useTRPC();+ const cache = useCrmCache();const openRecord = useOpenRecord();+ const detach = useMutation(+ trpc.deals.detachContact.mutationOptions({+ onSuccess: () => cache.deal(deal.id, { settle: "record" }),+ onError: (error) => toast.error(error.message),+ }),+ );++ const setRole = useMutation(+ trpc.deals.setContactRole.mutationOptions({+ onSuccess: () => cache.deal(deal.id, { settle: "record" }),+ onError: (error) => toast.error(error.message),+ }),+ );++ const form = adding ? (+ <AttachDealContact+ dealId={deal.id}+ companyName={deal.company.name}+ onDone={onDone}+ />+ ) : null;+if (deal.contacts.length === 0) {return (- <DetailSheetEmpty- icon={UserMultiple}- title="No contacts on this deal"- description={`Nobody from ${deal.company.name} is attached yet. Add people to the company, then bring them onto the deal.`}- />+ <>+ {form}+ {adding ? null : (+ <DetailSheetEmpty+ icon={UserMultiple}+ title="No contacts on this deal"+ description={`Nobody from ${deal.company.name} is attached yet. Bring the people you are selling to onto the deal and it says who to chase.`}+ action={+ <Button variant="outline" size="sm" onClick={onAdd}>+ <Icon icon={Add} data-icon="inline-start" />+ Add contact+ </Button>+ }+ />+ )}+ </>);}return (- <SimpleTable variant="panel" columns={CONTACT_COLUMNS}>- {deal.contacts.map((contact) => (- <SimpleTableRow- key={contact.id}- clickable- onClick={() => openRecord({ kind: "contact", id: contact.id })}- >- <TableCell className="truncate py-2.5 pr-3 pl-5 font-medium">- <span className="flex min-w-0 items-center gap-2">- <PersonAvatar- src={contact.imageUrl}- name={contactName(contact)}- email={contact.email}- size="sm"+ <>+ {form}+ <SimpleTable variant="panel" columns={CONTACT_COLUMNS}>+ {deal.contacts.map((contact) => (+ <SimpleTableRow+ key={contact.id}+ clickable+ onClick={() => openRecord({ kind: "contact", id: contact.id })}+ >+ <TableCell className="truncate py-2.5 pr-3 pl-5 font-medium">+ <span className="flex min-w-0 items-center gap-2">+ <PersonAvatar+ src={contact.imageUrl}+ name={contactName(contact)}+ email={contact.email}+ size="sm"+ />+ <span className="truncate">{contactName(contact)}</span>+ </span>+ </TableCell>+ <TableCell className="truncate px-1 py-2.5">+ <InlineTextCell+ label={`Role on this deal for ${contactName(contact)}`}+ value={contact.role}+ placeholder="Champion"+ saving={+ setRole.isPending &&+ setRole.variables?.contactId === contact.id+ }+ onSave={(role) =>+ setRole.mutate({+ dealId: deal.id,+ contactId: contact.id,+ role: role || null,+ })+ }/>- <span className="truncate">{contactName(contact)}</span>- </span>- </TableCell>- <TableCell className="truncate px-3 py-2.5">- {contact.role ?? <EmptyCellValue />}- </TableCell>- <TableCell className="truncate px-3 py-2.5 text-muted-foreground">- {contact.title ?? <EmptyCellValue />}- </TableCell>- <TableCell className="truncate px-3 py-2.5 text-muted-foreground">- {contact.email ?? <EmptyCellValue />}- </TableCell>- </SimpleTableRow>- ))}- </SimpleTable>+ </TableCell>+ <TableCell className="truncate px-3 py-2.5 text-muted-foreground">+ {contact.title ?? <EmptyCellValue />}+ </TableCell>+ <TableCell className="truncate px-3 py-2.5 text-muted-foreground">+ {contact.email ?? <EmptyCellValue />}+ </TableCell>+ <TableCell className="px-3 py-2.5">+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="icon-xs"+ disabled={detach.isPending}+ onClick={(event) => {+ event.stopPropagation();+ detach.mutate({+ dealId: deal.id,+ contactId: contact.id,+ });+ }}+ >+ <Icon icon={Close} />+ <span className="sr-only">+ Take {contactName(contact)} off this deal+ </span>+ </Button>+ </TooltipTrigger>+ <TooltipContent>Take off this deal</TooltipContent>+ </Tooltip>+ </TableCell>+ </SimpleTableRow>+ ))}++ <AddRow+ label="Add contact"+ columns={CONTACT_COLUMNS.length}+ onClick={onAdd}+ />+ </SimpleTable>+ </>);}diff --git a/apps/app/components/crm/record-sheet/quick-add.tsx b/apps/app/components/crm/record-sheet/quick-add.tsxindex 9eba77aa..77a1f998 100644--- a/apps/app/components/crm/record-sheet/quick-add.tsx+++ b/apps/app/components/crm/record-sheet/quick-add.tsx@@ -4,10 +4,18 @@ import { Button } from "@crm/ui/components/button";import { DatePicker } from "@crm/ui/components/date-picker";import { Field, FieldLabel } from "@crm/ui/components/field";import { Input } from "@crm/ui/components/input";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@crm/ui/components/select";import { Spinner } from "@crm/ui/components/spinner";import { useMutation, useQuery } from "@tanstack/react-query";import { useId, useState } from "react";import { toast } from "sonner";+import { contactName } from "@/components/crm/contact-name";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";@@ -147,6 +155,93 @@ export function QuickAddContact({);}+export function AttachDealContact({+ dealId,+ companyName,+ onDone,+}: {+ dealId: string;+ companyName: string;+ onDone: () => void;+}) {+ const trpc = useTRPC();+ const cache = useCrmCache();++ const [contactId, setContactId] = useState("");+ const [role, setRole] = useState("");++ const personId = useId();+ const roleId = useId();++ const options = useQuery(trpc.deals.contactOptions.queryOptions({ dealId }));+ const candidates = options.data ?? [];++ const attach = useMutation(+ trpc.deals.attachContact.mutationOptions({+ onSuccess: async (attached) => {+ const person = candidates.find(+ (candidate) => candidate.id === attached.contactId,+ );+ await cache.deal(dealId);+ toast.success(+ person+ ? `${contactName(person)} is on the deal.`+ : "Added to the deal.",+ );+ onDone();+ },+ onError: (error) => toast.error(error.message),+ }),+ );++ const nobody = !options.isPending && candidates.length === 0;++ const placeholder = options.isPending+ ? "Loading…"+ : nobody+ ? `Everybody at ${companyName} is already on it`+ : "Choose somebody";++ return (+ <QuickAddForm+ submitLabel="Add to deal"+ pending={attach.isPending}+ ready={contactId !== ""}+ onCancel={onDone}+ onSubmit={() =>+ attach.mutate({ dealId, contactId, role: role.trim() || null })+ }+ >+ <Field>+ <FieldLabel htmlFor={personId}>Person</FieldLabel>+ <Select value={contactId} onValueChange={setContactId}>+ <SelectTrigger id={personId} className="w-full" disabled={nobody}>+ <SelectValue placeholder={placeholder} />+ </SelectTrigger>+ <SelectContent>+ {candidates.map((candidate) => (+ <SelectItem key={candidate.id} value={candidate.id}>+ {contactName(candidate)}+ {candidate.title ? ` · ${candidate.title}` : ""}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ <Field>+ <FieldLabel htmlFor={roleId}>Role</FieldLabel>+ <Input+ id={roleId}+ value={role}+ onChange={(event) => setRole(event.target.value)}+ placeholder="Champion"+ autoComplete="off"+ />+ </Field>+ </QuickAddForm>+ );+}+export function QuickAddDeal({companyId,companyName,diff --git a/apps/app/components/crm/record-sheet/record-parts.tsx b/apps/app/components/crm/record-sheet/record-parts.tsxindex 476eb4b4..eaf1c15a 100644--- a/apps/app/components/crm/record-sheet/record-parts.tsx+++ b/apps/app/components/crm/record-sheet/record-parts.tsx@@ -1,7 +1,12 @@"use client";+import Add from "@carbon/icons-react/es/Add";+import { Button } from "@crm/ui/components/button";import { EmptyCellValue } from "@crm/ui/components/empty-cell";+import { Icon } from "@crm/ui/components/icon";+import { SimpleTableRow } from "@crm/ui/components/simple-table";import { Spinner } from "@crm/ui/components/spinner";+import { TableCell } from "@crm/ui/components/table";import { formatMoney } from "@crm/ui/lib/format";import type { ReactNode } from "react";import {@@ -73,6 +78,32 @@ export function RecordSheetFrame({);}+export function AddRow({+ label,+ columns,+ onClick,+}: {+ label: string;+ columns: number;+ onClick: () => void;+}) {+ return (+ <SimpleTableRow>+ <TableCell colSpan={columns} className="p-0">+ <Button+ variant="ghost"+ size="sm"+ onClick={onClick}+ className="h-9 w-full justify-start px-5 font-normal text-muted-foreground"+ >+ <Icon icon={Add} data-icon="inline-start" />+ {label}+ </Button>+ </TableCell>+ </SimpleTableRow>+ );+}+export function DealAmount({amountCents,currency,diff --git a/apps/app/components/crm/record-sheet/record-sheet-host.tsx b/apps/app/components/crm/record-sheet/record-sheet-host.tsxindex b765d826..0b06c5dd 100644--- a/apps/app/components/crm/record-sheet/record-sheet-host.tsx+++ b/apps/app/components/crm/record-sheet/record-sheet-host.tsx@@ -1,6 +1,7 @@"use client";import { useState } from "react";+import { FieldsSheetHost } from "@/components/crm/fields/fields-sheet";import { CloseReasonDialog } from "@/components/crm/stage-change";import { DetailSheet } from "@/components/detail-sheet";import { CompanySheet } from "./company-sheet";@@ -37,6 +38,8 @@ export function RecordSheetHost() {) : null}</DetailSheet>+ <FieldsSheetHost />+<CloseReasonDialog /></>);diff --git a/apps/app/components/crm/record-sheet/record-stack.ts b/apps/app/components/crm/record-sheet/record-stack.tsindex 1a2b74a8..e4d8bec2 100644--- a/apps/app/components/crm/record-sheet/record-stack.ts+++ b/apps/app/components/crm/record-sheet/record-stack.ts@@ -32,6 +32,8 @@ const params = {tab: parseAsString,add: parseAsStringLiteral(RECORD_FORMS),thread: parseAsString,+ fields: parseAsStringLiteral(RECORD_KINDS),+ field: parseAsString,[TIMELINE_PARAM]: timelineTabParser,};@@ -64,6 +66,8 @@ export function useRecordStack() {tab: null,add: null,thread: null,+ fields: null,+ field: null,[TIMELINE_PARAM]: null,},{ history },@@ -103,6 +107,27 @@ export function useOpenRecord() {return useRecordStack().open;}+export function useFieldsSheet() {+ const [{ fields, field }, setParams] = useQueryStates(params);++ const open = useCallback(+ (kind: RecordKind) => void setParams({ fields: kind, field: null }),+ [setParams],+ );++ const close = useCallback(+ () => void setParams({ fields: null, field: null }),+ [setParams],+ );++ const edit = useCallback(+ (key: string | null) => void setParams({ field: key }),+ [setParams],+ );++ return { entity: fields, field, open, close, edit };+}+export function useRecordSheetView(fallbackTab: string) {const [{ tab, add, thread }, setParams] = useQueryStates(params);diff --git a/apps/app/lib/trpc/cache.ts b/apps/app/lib/trpc/cache.tsindex 4b14c377..faeb6f0e 100644--- a/apps/app/lib/trpc/cache.ts+++ b/apps/app/lib/trpc/cache.ts@@ -9,13 +9,19 @@ type Options = {settle?: Settle;};-type RemovedRecord = { kind: "company" | "contact" | "deal"; id: string };+type RecordKind = "company" | "contact" | "deal";++type RemovedRecord = { kind: RecordKind; id: string };++type RemovedRecords = { kind: RecordKind; ids: 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>;+ fields(entity?: RecordKind, options?: Options): Promise<void>;removed(record: RemovedRecord): Promise<void>;+ removedMany(records: RemovedRecords): Promise<void>;activity(options?: Options): Promise<void>;google(options?: Options): Promise<void>;settings(options?: Options): Promise<void>;@@ -59,7 +65,59 @@ export function useCrmCache(): CrmCache {trpc.search.quick.queryKey(),];+ const removeRecords = (kind: RecordKind, ids: string[]): Promise<void> => {+ const byId = {+ company: trpc.companies.byId,+ contact: trpc.contacts.byId,+ deal: trpc.deals.byId,+ }[kind];+ const goneKeys = ids.map((id) => byId.queryKey({ id }));+ const gone = new Set(goneKeys.map((key) => JSON.stringify(key)));++ for (const record of [+ trpc.companies.byId,+ trpc.contacts.byId,+ trpc.deals.byId,+ ]) {+ void queryClient.invalidateQueries({+ queryKey: record.queryKey(),+ predicate: (query) => !gone.has(JSON.stringify(query.queryKey)),+ });+ }++ for (const queryKey of goneKeys) {+ void queryClient.invalidateQueries({+ queryKey,+ exact: true,+ refetchType: "none",+ });+ }++ return run(+ [...listKeys(), ...activityKeys(), trpc.dashboard.summary.queryKey()],+ [],+ );+ };++ const RECORD_BY_ID = {+ company: () => trpc.companies.byId.queryKey(),+ contact: () => trpc.contacts.byId.queryKey(),+ deal: () => trpc.deals.byId.queryKey(),+ } as const;+return {+ fields: (entity, options) =>+ run(+ [trpc.fields.list.queryKey()],+ [+ ...(entity+ ? [RECORD_BY_ID[entity]()]+ : Object.values(RECORD_BY_ID).map((key) => key())),+ ...listKeys(),+ ],+ options,+ ),+company: (id, options) =>run([@@ -87,6 +145,7 @@ export function useCrmCache(): CrmCache {...listKeys(),trpc.companies.byId.queryKey(),trpc.deals.byId.queryKey(),+ trpc.deals.contactOptions.queryKey(),],options,),@@ -96,7 +155,9 @@ export function useCrmCache(): CrmCache {[id ? trpc.deals.byId.queryKey({ id }) : trpc.deals.byId.queryKey()],[...listKeys(),+ trpc.deals.contactOptions.queryKey(),trpc.companies.byId.queryKey(),+ trpc.contacts.byId.queryKey(),...activityKeys(),trpc.dashboard.summary.queryKey(),trpc.currency.settings.queryKey(),@@ -104,36 +165,9 @@ export function useCrmCache(): CrmCache {options,),- removed: ({ kind, id }) => {- const goneKey = {- company: trpc.companies.byId,- contact: trpc.contacts.byId,- deal: trpc.deals.byId,- }[kind].queryKey({ id });- const gone = JSON.stringify(goneKey);-- for (const record of [- trpc.companies.byId,- trpc.contacts.byId,- trpc.deals.byId,- ]) {- void queryClient.invalidateQueries({- queryKey: record.queryKey(),- predicate: (query) => JSON.stringify(query.queryKey) !== gone,- });- }+ removed: ({ kind, id }) => removeRecords(kind, [id]),- void queryClient.invalidateQueries({- queryKey: goneKey,- exact: true,- refetchType: "none",- });-- return run(- [...listKeys(), ...activityKeys(), trpc.dashboard.summary.queryKey()],- [],- );- },+ removedMany: ({ kind, ids }) => removeRecords(kind, ids),activity: (options) =>run(diff --git a/bun.lock b/bun.lockindex b85aff9e..0ef96d7d 100644--- a/bun.lock+++ b/bun.lock@@ -178,6 +178,10 @@"dependencies": {"@carbon/icons-react": "^11.82.0","@crm/db": "workspace:*",+ "@dnd-kit/core": "^6.3.1",+ "@dnd-kit/modifiers": "^9.0.0",+ "@dnd-kit/sortable": "^10.0.0",+ "@dnd-kit/utilities": "^3.2.2","@shadcn/react": "^0.2.1","class-variance-authority": "^0.7.1","clsx": "^2.1.1",@@ -373,6 +377,16 @@"@date-fns/tz": ["@date-fns/[email protected]", "", {}, "sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg=="],+ "@dnd-kit/accessibility": ["@dnd-kit/[email protected]", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw=="],++ "@dnd-kit/core": ["@dnd-kit/[email protected]", "", { "dependencies": { "@dnd-kit/accessibility": "^3.1.1", "@dnd-kit/utilities": "^3.2.2", "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ=="],++ "@dnd-kit/modifiers": ["@dnd-kit/[email protected]", "", { "dependencies": { "@dnd-kit/utilities": "^3.2.2", "tslib": "^2.0.0" }, "peerDependencies": { "@dnd-kit/core": "^6.3.0", "react": ">=16.8.0" } }, "sha512-ybiLc66qRGuZoC20wdSSG6pDXFikui/dCNGthxv4Ndy8ylErY0N3KVxY2bgo7AWwIbxDmXDg3ylAFmnrjcbVvw=="],++ "@dnd-kit/sortable": ["@dnd-kit/[email protected]", "", { "dependencies": { "@dnd-kit/utilities": "^3.2.2", "tslib": "^2.0.0" }, "peerDependencies": { "@dnd-kit/core": "^6.3.0", "react": ">=16.8.0" } }, "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg=="],++ "@dnd-kit/utilities": ["@dnd-kit/[email protected]", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg=="],+"@dotenvx/dotenvx": ["@dotenvx/[email protected]", "", { "dependencies": { "@dotenvx/primitives": "^0.8.0", "commander": "^11.1.0", "conf": "^10.2.0", "dotenv": "^17.2.1", "enquirer": "^2.4.1", "env-paths": "^2.2.1", "execa": "^5.1.1", "fdir": "^6.2.0", "ignore": "^5.3.0", "object-treeify": "1.1.33", "open": "^8.4.2", "picomatch": "^4.0.4", "systeminformation": "^5.22.11", "undici": "^7.11.0", "which": "^4.0.0", "yocto-spinner": "^1.1.0" }, "bin": { "dotenvx": "src/cli/dotenvx.js" } }, "sha512-/BITOC9dmS/edY2zQwZNicQ059O6RKabtQfyEafV0nGtfYRNHYy1DIPiYVcov40+tob9hfmBnbR963dS+EQ1DQ=="],"@dotenvx/primitives": ["@dotenvx/[email protected]", "", {}, "sha512-VYJy0uhFm9zTJ1TxBaW/pA8bjbOM/OttaNMwZ1RHG4JKyRG7DhSdiqD1ipQoAyoD22olUtxbP78W9xY3Wd11bg=="],diff --git a/docs/api.md b/docs/api.mdindex 2f6517e2..46008ff7 100644--- a/docs/api.md+++ b/docs/api.md@@ -157,6 +157,21 @@ self-hoster's admin cannot redeploy.- **`isAutomatedAddress` is a separate list about the local part** (`sales@`,`noreply@`), which is why `[email protected]` never becomes a lead.+## People on a deal++`DealContact` is the join, and `deals.attachContact` / `detachContact` /+`setContactRole` are the only ways to write it. `deals.contactOptions` is what the+picker reads.++- **A contact on a deal works at that deal's company**, enforced in the service and+ not merely by the picker — the same rule as `companies.setPrimaryContact`.+- **Attaching is an upsert and re-attaching keeps the role already there**, so a+ double click cannot blank what somebody typed.+- **Detaching removes the row, never the contact.** They stay in the CRM, on the+ company, with their history.+- **`role` is blanked to null, never stored as `""`** — `blankToNull`, as everywhere+ else.+## Deleting a record`contacts.delete`, `companies.delete`, `deals.delete`. No soft delete, no archive.@@ -189,7 +204,7 @@ self-hoster's admin cannot redeploy.A deal is sold in one currency and reported in another, and **only `baseAmount` mayever be summed**. The rules — `baseCurrency`, `countedWhere`/`pendingWhere`, frozen-rates, the ten supported currencies, the keyless feed, and why the fetcher is the one+rates, the supported currencies, the keyless feed, and why the fetcher is the onedocumented exception to *no intelligence in the API* — are in **`docs/currency.md`**.Read it before touching any amount, total, chart or rate.diff --git a/docs/currency.md b/docs/currency.mdindex 2917b73a..5bb0a40c 100644--- a/docs/currency.md+++ b/docs/currency.md@@ -44,10 +44,10 @@ inverts on ingest.- **Codes are validated against `isCurrencyCode` (`@crm/db/currency`), not a regex** —`z.string().length(3)` accepted `ZZZ`. `isWellFormedCurrency` is separate because`Intl` throws on non-three-letter input.-- **`CURRENCIES` is ten currencies and that is all this CRM supports** — USD, EUR, JPY,- GBP, CNY, AUD, CAD, CHF, HKD, SGD, in array order. `isCurrencyCode` is the single- gate for the picker, the feed filter and the stored setting. A refresh **prunes**- `FETCHED` rows outside the ten and leaves `MANUAL` alone.+- **`CURRENCIES` is eleven currencies and that is all this CRM supports** — USD, EUR,+ JPY, GBP, CNY, AUD, CAD, CHF, HKD, SGD, ZAR, in array order. `isCurrencyCode` is the+ single gate for the picker, the feed filter and the stored setting. A refresh+ **prunes** `FETCHED` rows outside the list and leaves `MANUAL` alone.- **`applyRate` rounds to the *reporting* currency's `minorUnitsOf`**, not to two. The×100 cents transport cannot represent a three-decimal minor unit; nor can`Decimal(14, 2)`.diff --git a/docs/plan/dynamic-fields-build.md b/docs/plan/dynamic-fields-build.mdnew file mode 100644index 00000000..4f589eba--- /dev/null+++ b/docs/plan/dynamic-fields-build.md@@ -0,0 +1,352 @@+# Plan — Dynamic fields (build)++Build instructions for the agent implementing dynamic fields on companies,+contacts and deals.++[`dynamic-fields.md`](./dynamic-fields.md) is the **design record** — it owns the+schema and the reasoning behind every decision. This document is the **build+order**: what to type, where, and in what sequence. Where they disagree, the+design doc wins on *why* and this one wins on *how*.++Two constraints govern everything below.++1. **The Paper design is fixed.** Match it exactly. Do not improve it, round it,+ or reword it.+2. **shadcn components only.** No hand-rolled buttons, inputs, switches, chips or+ menus. If a component does not exist, add it to `packages/ui` with the shadcn+ CLI or add a variant there — never at the call site.++---++## 0. Read before you type, and say what you read++| Before touching | Read |+| --- | --- |+| Anything | [`AGENTS.md`](../../AGENTS.md), [`design.md`](../design.md), [`dynamic-fields.md`](./dynamic-fields.md) |+| `apps/api` | [`api.md`](../api.md), `.agents/skills/nestjs-trpc/SKILL.md` |+| `packages/db` | `.agents/skills/prisma-database-setup/SKILL.md` |+| `apps/app` | `apps/app/AGENTS.md` → then the relevant guide in `apps/app/node_modules/next/dist/docs/01-app/` |+| URL state | `.agents/skills/nuqs/SKILL.md` |+| Any UI | `.agents/skills/shadcn/SKILL.md` and `rules/styling.md`, `rules/composition.md`, `rules/forms.md` |+| `apps/agent` | `.agents/skills/eve/SKILL.md` → then `apps/agent/node_modules/eve/docs/README.md` |+| A telemetry event | [`telemetry.md`](../telemetry.md) |++## 1. The design++Paper file **CRM**, page **crm - lewis**:+`https://app.paper.design/file/01KZ72S23CM00WXN6S1MP68M03/5-1`++| Artboard | What it specifies |+| --- | --- |+| `/companies?record=company:abcd` | Cog in the DETAILS header; custom fields inline; a pending agent suggestion |+| `/contacts?record=contact:abcd` | Cog placement only |+| `/deals?record=deal:abcd` | Cog placement only |+| `…&fields=company` | The fields sheet — list state |+| `…&fields=company (first run)` | Empty state |+| `…&fields=company&field=new` | Create a field |+| `…&fields=company&field=runs_on` | Edit a field, with coverage |+| `…&fields=company&field=runs_on (archive)` | Archive confirmation |++**Take values from the file, not from screenshots.** `get_jsx`,+`get_computed_styles`, `get_node_info`. A screenshot will not tell you whether a+gap is 8 or 10.++Every user-visible string is in §7. They are final.++## 2. Schema++Copy the Prisma models from **[`dynamic-fields.md` §3](./dynamic-fields.md)**+verbatim — `FieldEntity`, `FieldType`, `FieldDefinition`, `FieldOption`,+`FieldValue`. That section also explains why values are typed columns rather than+JSON, why one value table carries three nullable FKs, and why `key` is immutable.+Do not redesign it; if you think it is wrong, say so before writing the+migration.++On top of that:++- Migration name: `dynamic_fields`. Run through `bun run db:migrate` in+ `packages/db` — never `db:push` for a schema that ships.+- Add the back-relations on `Company`, `Contact` and `Deal`+ (`fieldValues FieldValue[]`).+- `agentFilled Boolean @default(true)` — the default is the feature. See+ [`dynamic-fields.md` §5](./dynamic-fields.md).+- No `organizationId`. Single tenant.++## 3. `@crm/db/fields` — the shared core++Everything else in this plan is a caller of this module. It is what makes the+feature API-driven *and* agent-driven without two implementations drifting apart.++Create `packages/db/src/fields.ts` and add `"./fields": "./src/fields.ts"` to the+`exports` map in `packages/db/package.json` — the same shape as+`@crm/db/currency` and `@crm/db/workspace`, which are the precedents.++It owns:++- `FIELD_TYPES` and the type→storage-column map (`TEXT`→`text`, `NUMBER`→+ `number`, `DATE`→`date`, `CHECKBOX`→`bool`, `SELECT`→`optionId`, `USER`→+ `userId`, …).+- `fieldKeyFromLabel(label)` — slug, collision-checked by the caller against+ `@@unique([entity, key])`.+- `valueSchemaFor(definition)` — returns the Zod schema for one field's value.+- `readValues(entity, recordId)` / `writeValues(tx, entity, recordId, values)` —+ the only two functions that touch `FieldValue`.+- `serializeField(definition)` — the wire shape used by tRPC *and* by agent+ tools, so both see identical field metadata.++**Rule: no field logic anywhere else.** Not in a router, not in a service, not in+a component, not in an eve tool. A validator written twice is a bug with a+delay on it.++## 4. API — `apps/api/src/fields/`++Four files, mirroring `apps/api/src/companies/`:+`fields.contracts.ts`, `fields.router.ts`, `fields.service.ts`, `fields.module.ts`.+Register `FieldsModule` in `app.module.ts` imports; `FieldsRouter` **must** be in+the module's `providers` or it silently does not exist at runtime.++`@Router({ alias: "fields" })` + `@UseMiddlewares(AuthMiddleware)` on the class.+No middleware means public — there is no other guard.++| Procedure | Input | Notes |+| --- | --- | --- |+| `fields.list` | `{ entity, includeArchived? }` | Definitions with options, `position` order |+| `fields.byKey` | `{ entity, key }` | For the editor screen |+| `fields.create` | label, type, options, `agentFilled`, `agentBrief`, placement | Key derived from label |+| `fields.update` | id + same, minus key | Reject a `key` change with `BAD_REQUEST` |+| `fields.reorder` | `{ entity, ids }` | One transaction, positions rewritten from the array |+| `fields.archive` / `fields.restore` | `{ id }` | Archive is the normal path |+| `fields.delete` | `{ id }` | Loud, and separate from archive |+| `fields.backfill` | `{ id }` | Writes **one** `AgentTask`, `kind: "field-backfill"` — never one per record |++Rules that are not optional:++- **Routers are thin.** Zod in, service call out. Prisma lives in the service.+- **Values do not get their own router.** They ride the record procedures:+ `companies.byId` gains `fields`, `companies.update` accepts+ `fields: Record<key, value>`. Same for contacts and deals. One write, one+ invalidation, and the existing inline editors keep their mutation.+- Services throw Nest's `HttpException` family; `DomainErrorMiddleware` maps them.+- **Regenerate and commit** `src/generated/server.ts` (`bun run trpc:generate`).+ If the app cannot see `trpc.fields.*`, this is why.+- Tests: `apps/api/test/fields.spec.ts`, `bun:test`, modelled on+ `apps/api/test/bulk.spec.ts` (real database, `TEST_RUN_ID`-suffixed data,+ cleaned up in `afterAll`). Cover: key collision, key immutability, value+ coercion per type, archive keeps values, delete cascades, reorder is atomic.++## 5. Agents — `apps/agent`++The API is one caller of `@crm/db/fields`; the agent is the other. Add+`apps/agent/agent/lib/fields.ts` as a thin wrapper, in the shape of+`lib/facts.ts`, then these tools in `apps/agent/agent/tools/`:++| Tool | Does |+| --- | --- |+| `list_fields` | Every field for an entity with its key, type, options and brief — so the agent can discover the schema instead of being told it |+| `set_field_value` | Write a value the agent is certain of |+| `propose_field_value` | Offer a value with evidence — routes through the fact/proposal path, not a direct write |+| `create_field` / `update_field` | Manage definitions, so "add a field for X" works in chat |+| `archive_field` | Behind `lib/approval.ts`. Destructive schema changes get a human |++Constraints:++- The `agentBrief` is the instruction the agent works from. `list_fields` must+ return it.+- Tool descriptions carry the same voice as the existing tools — read+ `record_fact.ts` and `search_crm.ts` first.+- **Nest still writes rows, not intelligence.** `fields.backfill` writes an+ `AgentTask`; the agent decides fan-out, batching and priority.+- Missing capability ⇒ missing capability, never a throw.++**MCP later, for free.** Every capability is a tRPC procedure over+`@crm/db/fields`, and every tool is a thin call to the same module. An MCP server+is then a mechanical wrapper over `fields.*` with no new logic. That only stays+true if you keep logic out of the tools. Do not build MCP now.++## 6. App — `apps/app`++### URL state (nuqs)++Two params, added to the **existing shared parser object** in+`apps/app/components/crm/record-sheet/record-stack.ts` — do not start a second+parser file:++```ts+fields: parseAsStringLiteral(RECORD_KINDS), // which entity's fields are open+field: parseAsString, // "new" | a field key+```++- 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.+- The cog sets `fields` to the record's own kind, so the sheet opens on the+ entity you came from.++### Components — use these, build nothing++| Element in Paper | Use |+| --- | --- |+| Fields sheet shell | `DetailSheet` (`components/detail-sheet.tsx`) at a new `md` size |+| Sheet header, back + title + close | `DetailSheetHeader` — it already does back-at-left, close-at-right |+| Entity switcher | `Tabs` / `TabsList` / `TabsTrigger`, default variant |+| Standard / Archived disclosure rows | `Collapsible` — **add it**: `bunx --bun shadcn@latest add collapsible` in `packages/ui` |+| Type chip (`Select`, `Date`, `Number`, `Checkbox`) | `Badge` — **add it**, then add a `mono` variant in `packages/ui` |+| Row overflow menu | `Button variant="ghost" size="icon-xs"` + `DropdownMenu` |+| Drag handle | `Button variant="ghost" size="icon-xs"` carrying the dnd listeners, Carbon `Draggable` icon |+| Form labels and helper text | `Field`, `FieldLabel`, `FieldDescription`, `FieldGroup` (`packages/ui/src/components/field.tsx`) |+| Label / brief inputs | `Input`, `Textarea` |+| Type picker | `Select` |+| Option rows | `InputGroup` with a leading handle addon and a trailing remove `Button` |+| "Add option" | `Button variant="ghost" size="sm"` |+| Agent toggle | `Switch` |+| Placement toggles | `Checkbox` + `FieldLabel` |+| Footer actions | `Button` (primary) and `Button variant="outline"` |+| Coverage block | Mirror `DetailSheetPending`'s muted panel; dot is `StatusIndicator` |+| Archive confirm | `AlertDialog`, action button destructive |+| Empty state | `Empty` / `EmptyHeader` / `EmptyMedia` / `EmptyTitle` / `EmptyDescription` / `EmptyContent` |+| The cog itself | `Button variant="ghost" size="icon-sm"`, Carbon `Settings`, in `DetailSheetSection`'s existing `action` slot |++Three additions to `packages/ui`, because that is where they belong:++1. **`md` sheet size.** `sheetContentVariants` has `sm | lg | xl | 2xl` and+ nothing near 460px. Add `md: "data-[side=left]:sm:max-w-[460px] data-[side=right]:sm:max-w-[460px]"`.+ The width comes from the artboards, and 1:1 outranks landing on a Tailwind step.+2. **`Badge` + a `mono` variant** for the type chip.+3. **`SortableList`** over `@dnd-kit/core` + `@dnd-kit/sortable`. The repo has no+ drag-and-drop library today. The artboards show drag handles on both field+ rows and option rows, so dragging is in scope and a Move up / Move down menu+ is *not* an acceptable substitute here.++`EmptyDescription` also has no wrap class — add `text-balance` there so the empty+state does not orphan its last word. Fix it in the component, not at the call+site.++### Rendering fields on a record++In `company-sheet.tsx` (then contacts, then deals), custom fields render **inline+inside the existing `Details` section**, after the standard properties, in+`position` order. No "Custom fields" heading, no separate section.++One map from `FieldType` to the editor that already exists:++| Type | Component |+| --- | --- |+| `TEXT`, `URL`, `EMAIL`, `PHONE` | `InlineField` (with `type`) |+| `LONG_TEXT` | `InlineTextArea` |+| `NUMBER` | `InlineField` |+| `DATE` | `InlineDateField` |+| `SELECT`, `USER` | `InlineSelectField` |+| `CHECKBOX` | `Checkbox` in a `DetailSheetProperty` |++Agent-sourced values get `SOURCED_VALUE` (dotted underline) with `SourcedValue`+for the hover source. Pending proposals render with the existing `Suggestion`+component. Both are built — use them, do not restyle them.++### Table columns++`showOnTable` is opt-in per field. A workspace with thirty fields must not get a+thirty-column table. Wire it into the existing column definitions in+`companies-table.tsx` and friends.++### Cache++Add `fields(entity?)` to `CrmCache` in `apps/app/lib/trpc/cache.ts`. A definition+change invalidates `fields.list` plus every list and record query for that+entity. Value edits keep `{ settle: "record" }` so the inline spinner clears+without waiting for the table. **A new mutation adds a call there, not a new list+of keys at the call site.**++## 7. Copy — verbatim++**Fields sheet**++- Title `Fields`+- Subtitle `This shapes every company in your CRM.` (company / contact / deal)+- Tabs `Companies` `Contacts` `Deals`+- `Standard fields` · `8 · reorder and hide only`+- `Custom fields` · `Drag to order`+- `Archived` · `2 · values kept, hidden everywhere`+- Footer `New field` · `Order here is the order on the sheet`++**Empty state**++- `No custom fields yet`+- `Create dynamic fields that your agents can research and pre-fill.`+- `New field`++**Editor**++- `Label`+- `Key` · `What the API and your agents call it. Set from the label, fixed once saved — renaming the label later never breaks a caller.`+- `Let your agents fill this` · `They propose a value with a source, and never overwrite yours.`+- `What counts as an answer` · `Leave it empty and your agents work from the label and type alone.`+- `Type` · `Select — one of a fixed list`+- `Options` · `Add option`+- `Show on the company sheet` · `Offer as a column on the Companies table`+- `Create field` · `Cancel` · `Save changes` · `Archive`++**Coverage**++- `Filled on 41 of 64 companies`+- `Last looked 2 days ago · you accepted 38 of 41`+- `Fill the rest`++**Archive dialog**++- `Archive Runs on?`+- `Hidden everywhere. Its 41 values are kept.`+- `Cancel` · `Archive field`++Never "eve" in the product. It is *your agents*.++## 8. Order of work++Each phase ends green — typecheck, lint, tests — before the next begins.++1. **Schema.** Models, migration, back-relations. `bun run db:migrate`.+2. **`@crm/db/fields`.** Types, key derivation, value schemas, read/write. Unit+ tests here; it is pure and cheap to test.+3. **API.** Contracts, service, router, module, registration. Regenerate and+ commit `server.ts`. `fields.spec.ts` green.+4. **Values on records.** `byId` returns `fields`, `update` accepts them, all+ three entities.+5. **`packages/ui` additions.** Sheet `md`, `Badge` + mono, `Collapsible`,+ `SortableList`, `EmptyDescription` balance.+6. **The sheet.** List → empty → create → edit → archive, in that order,+ checking each against its artboard before moving on.+7. **The cog and the record rendering.** Companies first, then contacts and+ deals.+8. **Table columns.**+9. **Agent lib and tools.**++## 9. Do not++- Do not deviate from the artboards, including the copy.+- Do not write a custom button, input, chip, switch or menu.+- Do not override component colours or typography with `className`. Layout only.+- Do not put field logic in a router, a component or a tool — it goes in+ `@crm/db/fields`.+- Do not put a vendor client, scoring or enrichment in `apps/api`.+- Do not add code comments.+- Do not add a `Co-Authored-By` trailer.+- Do not add a per-package `.env`.+- Do not hand-edit `apps/api/src/generated/server.ts` — regenerate it.+- Do not build the MCP server. Keep the seam clean so it stays a wrapper.+- Do not make the agent toggle default off.++## 10. Decisions already made — do not relitigate++- Agent-first: `agentFilled` defaults true, the brief sits above the type in the+ editor, and only manual fields are badged. [`dynamic-fields.md` §5](./dynamic-fields.md).+- Archive over delete for definitions, with delete kept as a separate loud action.+- Standard fields appear in the list, reorderable and hideable, never deletable.+- Custom fields render inline in DETAILS with no grouping of their own.++## 11. Open — decide with Lewis, do not guess++**Generalising `ContactFact` to `RecordFact`** (three nullable FKs plus an+optional `fieldId`) so agent proposals work for custom fields on all three+entities, instead of a parallel proposal table. `ContactFact` is contact-only and+keys on `field String`. Agent-first makes this load-bearing rather than optional,+and it is the one decision that gets more expensive after launch. Raise it before+phase 9 — earlier if phase 1 would touch it.diff --git a/docs/plan/dynamic-fields.md b/docs/plan/dynamic-fields.mdnew file mode 100644index 00000000..669673c5--- /dev/null+++ b/docs/plan/dynamic-fields.md@@ -0,0 +1,281 @@+# Plan — Dynamic fields++Fields a workspace defines for itself, on companies, contacts and deals, edited+from one sheet that opens from any record.++The visual design is in Paper, file **CRM**, page **crm - lewis**, artboards+`Dynamic fields — cog placement`, `/companies?record=company:abcd&fields=company`,+`Dynamic fields — new field & empty` and `Dynamic fields — on the record`. This+document is the half Paper cannot hold: the model, the API and the agent.++This document is the design record — what we decided and why. The build order —+files, procedures, component mapping, phases — is+[`dynamic-fields-build.md`](./dynamic-fields-build.md), which points back here+for the schema in §3 rather than copying it.++Read it with [`AGENTS.md`](../../AGENTS.md), [`api.md`](../api.md) and+[`design.md`](../design.md).++---++## 1. One sheet, one cog++The cog goes in the **DETAILS section header**, on all three sheets. That is the+`action` slot `DetailSheetSection` already has, so no new primitive and no+per-sheet variation — the same element in the same place whether DETAILS is the+full width of the contact sheet or the 320px rail of the company sheet.++Not the header bar beside Re-enrich and Close: that bar is about *this record*,+and the cog is not. It changes every company at once.++Which is the one thing the sheet has to say out loud. It opens with **"This+shapes every company in your CRM"**, because a control reached from Northwind+Labs' sheet will otherwise be read as belonging to Northwind Labs.++The sheet stacks over the record sheet at 460px, dimming it, and carries an+entity switcher — Companies / Contacts / Deals — so the same sheet reached from a+deal can still fix a contact field without closing anything.++State lives in the URL beside `record`, in `record-stack.ts`:++```+/companies?record=company:abcd&fields=company+```++so it is shareable, Escape and Back close it in the right order, and the record+underneath survives a refresh.++## 2. Standard fields are in the list++The sheet shows two groups: **Standard** (Name, Domain, Website, Phone, Email,+City, Country, Owner) and **Custom fields**. Standard fields are real rows — they+can be reordered and hidden, never deleted or retyped. A rep who opens the sheet+looking for "Domain" finds it and learns the rule in the same second, which is+cheaper than any explanation of why it is missing.++Custom fields then render **inline in DETAILS**, in the order set here. No+"Custom fields" box. A field is a field; the grouping was an implementation+detail and does not belong on the record.++## 3. The model++```prisma+enum FieldEntity { COMPANY CONTACT DEAL }++enum FieldType {+ TEXT LONG_TEXT NUMBER DATE CHECKBOX SELECT URL EMAIL PHONE USER+}++model FieldDefinition {+ id String @id @default(cuid())+ entity FieldEntity+ key String+ label String+ type FieldType++ agentFilled Boolean @default(true)+ agentBrief String?++ required Boolean @default(false)+ showOnSheet Boolean @default(true)+ showOnTable Boolean @default(false)+ position Int++ archivedAt DateTime?++ options FieldOption[]+ values FieldValue[]++ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@unique([entity, key])+ @@index([entity, position])+ @@map("fieldDefinition")+}++model FieldOption {+ id String @id @default(cuid())+ fieldId String+ field FieldDefinition @relation(fields: [fieldId], references: [id], onDelete: Cascade)+ label String+ position Int++ archivedAt DateTime?+ values FieldValue[]++ @@index([fieldId, position])+ @@map("fieldOption")+}++model FieldValue {+ id String @id @default(cuid())+ fieldId String+ field FieldDefinition @relation(fields: [fieldId], references: [id], onDelete: Cascade)++ companyId String?+ company Company? @relation(fields: [companyId], references: [id], onDelete: Cascade)+ contactId String?+ contact Contact? @relation(fields: [contactId], references: [id], onDelete: Cascade)+ dealId String?+ deal Deal? @relation(fields: [dealId], references: [id], onDelete: Cascade)++ text String?+ number Decimal? @db.Decimal(24, 4)+ date DateTime?+ bool Boolean?+ optionId String?+ option FieldOption? @relation(fields: [optionId], references: [id], onDelete: SetNull)+ userId String?++ updatedAt DateTime @updatedAt++ @@unique([fieldId, companyId])+ @@unique([fieldId, contactId])+ @@unique([fieldId, dealId])+ @@index([fieldId, text])+ @@index([fieldId, number])+ @@index([fieldId, date])+ @@map("fieldValue")+}+```++Four 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+ someone wants the pipeline sorted by *Renewal date* the answer would be to pull+ the table into the browser. One column per storage class keeps that promise;+ the type on the definition says which one is live.+- **One value table with three nullable FKs, not three tables.** Every FK+ cascades, so deleting a company takes its values with it. `AgentTask` carries+ `contactId`/`companyId` with no FK and `api.md` documents the chore that+ creates — "clear `AgentTask` and `AgentEvent` yourself". Not repeating it.+- **Options are rows.** Renaming "Google Cloud" must not orphan every record+ pointing at it, and a JSON array of strings makes rename indistinguishable from+ delete-plus-create.+- **`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.++**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.+Archiving keeps the values and hides the field everywhere; a true delete stays+available behind a separate destructive confirm that names the count.++No `organizationId`, on any of the three. Single tenant.++## 4. The API++A new module, `apps/api/src/fields/`, one router as the codegen glob expects:++| Procedure | Notes |+| --- | --- |+| `fields.list({ entity, includeArchived })` | Definitions with options, in `position` order. |+| `fields.create` / `fields.update` | Key derived from label on create, rejected on update. |+| `fields.reorder({ entity, ids })` | One transaction, positions rewritten from the array. |+| `fields.archive` / `fields.restore` / `fields.delete` | Delete is the loud one. |++**Values do not get their own router.** They ride the record procedures that+already exist: `companies.byId` returns `fields`, `companies.update` accepts+`fields: Record<key, value>`. One write per record, one invalidation, and the+inline editors keep using the mutation they already use.++The value validator is derived from the definition at runtime — a shared+`crm/fields.ts` that both the router's zod schema and the service use, so a+`NUMBER` field cannot be written a string by either path.++`useCrmCache()` gains `cache.fields(entity)`. A definition change is a schema+change: it fans out to every list and record query for that entity. Rare enough+that the width does not matter, and `{ settle: "record" }` still covers the+inline value edits.++`src/generated/server.ts` is regenerated by `dev`/`check-types` and committed, or+the app cannot see any of this.++## 5. Agent-first, and what that costs++This was the open question, and the answer is **agent-first**: `agentFilled`+defaults to **true**. A new field is something your agents keep up to date unless+you say otherwise, and "Manual only" is the exception a rep opts into.++That is a real difference, not a default flipped for effect. It changes three+things:++- **Order in the editor.** The brief — *What counts as an answer* — sits directly+ under the label, **above** the type. The second thing you write is the+ instruction, not the shape.+- **What the list shows.** Each row's subtitle is its brief, truncated. Agent+ upkeep is the unmarked normal case; only the exceptions read "Manual only".+ Nothing is badged for doing the expected thing.+- **What an empty brief means.** Not "never touched" — that was the old,+ opt-in reading. Agents work from the label and the type alone; the brief+ sharpens what would count. Opting out is `agentFilled: false`, one switch.++**Never "eve" in the product.** UI copy says *your agents*. `eve` is the runtime+in `apps/agent`, an implementation detail a rep should never have to learn, and+a self-hoster may well point this at their own. The word appears in this+document and in the code; it does not appear on screen.++Nest still writes rows and fills nothing. Creating or editing a definition with+`agentFilled` writes **one** `AgentTask` (`kind: "field-backfill"`, `reason` =+the key) — one row per field, not one per record. The agent leases it and decides+the fan-out, batching and priority itself, which is the point of the rule in+`api.md` and the reason a workspace with 5,000 companies does not get 5,000 rows+from one click.++`agentBrief` is the whole instruction, in the rep's words:++> Which cloud they run production on. Their docs, status page or engineering job+> ads say it outright — infer nothing from a logo on a customer wall.++The self-hoster's answer is unchanged and still needs no special case: with no+agent running, nothing leases the task, nothing proposes, and every field is one+you type into. A missing capability removes a capability. It does not throw.++**Proposed, not written** — and this is what makes agent-first safe to default+on. A value an agent finds arrives the way a `ContactFact` arrives: `PROPOSED`,+with a score, a band and evidence, rendered by the `Suggestion` component that+already exists, accepted or dismissed by a human. A dotted underline+(`SOURCED_VALUE`) then marks what an agent put there, and hover gives the source.+Nothing a rep typed is ever overwritten.++Turning this on by default would be reckless if agents wrote straight into the+field. They do not, so the cost of a wrong default is a suggestion someone+dismisses — against a rep never discovering the feature at all, which is the cost+of the opt-in version.++That behaviour is already built; the fork is that `ContactFact` is contact-only+and keys on `field String`.++Recommendation: **generalise `ContactFact` to `RecordFact`** with the same three+nullable FKs and an optional `fieldId`, rather than growing a parallel proposal+table for custom fields. It is the larger migration and the smaller system. This+is the one decision in this plan that should be made before any of it is built,+because it is the only one that gets more expensive later — and agent-first makes+it load-bearing rather than optional.++## 6. What the UI needs that does not exist++Everything in the design is already in `packages/ui` — Sheet, Input, Select,+Switch, Checkbox, Button, Suggestion, the Inline\* editors — with one exception.++**There is no drag-and-drop library in the repo.** The design shows a drag handle+on every row. Either:++1. add `@dnd-kit/core` + `@dnd-kit/sortable` to `packages/ui` and build a+ `SortableList` there, which is where a shared interaction belongs; or+2. ship reordering as Move up / Move down in the row's overflow menu, and add+ dragging later.++Option 2 is a smaller first cut and the ordering it produces is identical. Option+1 is what the artboards show. Worth deciding explicitly rather than by accident.++## 7. Deliberately out of scope++- **Filtering and sorting the tables by a custom field.** The columns exist+ (`showOnTable`), the indexes support it, `resolveOrderBy` would need to learn+ about field keys. Phase two.+- **Quick-add.** New fields do not appear in quick-add unless `required`.+- **Per-record fields.** A field belongs to an entity, never to one company.+- **Formula, rollup and relation types.** Not in the first cut.diff --git a/packages/db/package.json b/packages/db/package.jsonindex 490bc356..03165419 100644--- a/packages/db/package.json+++ b/packages/db/package.json@@ -11,6 +11,8 @@"./currency": "./src/currency.ts","./enums": "./src/generated/prisma/enums.ts","./favicon": "./src/favicon.ts",+ "./fields": "./src/fields.ts",+ "./fields-shape": "./src/fields-shape.ts","./fx": "./src/fx.ts","./images": "./src/images.ts","./safe-fetch": "./src/safe-fetch.ts",diff --git a/packages/db/prisma/migrations/20260806140000_dynamic_fields/migration.sql b/packages/db/prisma/migrations/20260806140000_dynamic_fields/migration.sqlnew file mode 100644index 00000000..5d7a41ae--- /dev/null+++ b/packages/db/prisma/migrations/20260806140000_dynamic_fields/migration.sql@@ -0,0 +1,102 @@+-- CreateEnum+CREATE TYPE "FieldEntity" AS ENUM ('COMPANY', 'CONTACT', 'DEAL');++-- CreateEnum+CREATE TYPE "FieldType" AS ENUM ('TEXT', 'LONG_TEXT', 'NUMBER', 'DATE', 'CHECKBOX', 'SELECT', 'URL', 'EMAIL', 'PHONE', 'USER');++-- CreateTable+CREATE TABLE "fieldDefinition" (+ "id" TEXT NOT NULL,+ "entity" "FieldEntity" NOT NULL,+ "key" TEXT NOT NULL,+ "label" TEXT NOT NULL,+ "type" "FieldType" NOT NULL,+ "agentFilled" BOOLEAN NOT NULL DEFAULT true,+ "agentBrief" TEXT,+ "required" BOOLEAN NOT NULL DEFAULT false,+ "showOnSheet" BOOLEAN NOT NULL DEFAULT true,+ "showOnTable" BOOLEAN NOT NULL DEFAULT false,+ "position" INTEGER NOT NULL,+ "archivedAt" TIMESTAMP(3),+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "fieldDefinition_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "fieldOption" (+ "id" TEXT NOT NULL,+ "fieldId" TEXT NOT NULL,+ "label" TEXT NOT NULL,+ "position" INTEGER NOT NULL,+ "archivedAt" TIMESTAMP(3),++ CONSTRAINT "fieldOption_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "fieldValue" (+ "id" TEXT NOT NULL,+ "fieldId" TEXT NOT NULL,+ "companyId" TEXT,+ "contactId" TEXT,+ "dealId" TEXT,+ "text" TEXT,+ "number" DECIMAL(24,4),+ "date" TIMESTAMP(3),+ "bool" BOOLEAN,+ "optionId" TEXT,+ "userId" TEXT,+ "updatedAt" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "fieldValue_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE INDEX "fieldDefinition_entity_position_idx" ON "fieldDefinition"("entity", "position");++-- CreateIndex+CREATE UNIQUE INDEX "fieldDefinition_entity_key_key" ON "fieldDefinition"("entity", "key");++-- CreateIndex+CREATE INDEX "fieldOption_fieldId_position_idx" ON "fieldOption"("fieldId", "position");++-- CreateIndex+CREATE INDEX "fieldValue_fieldId_text_idx" ON "fieldValue"("fieldId", "text");++-- CreateIndex+CREATE INDEX "fieldValue_fieldId_number_idx" ON "fieldValue"("fieldId", "number");++-- CreateIndex+CREATE INDEX "fieldValue_fieldId_date_idx" ON "fieldValue"("fieldId", "date");++-- CreateIndex+CREATE INDEX "fieldValue_optionId_idx" ON "fieldValue"("optionId");++-- CreateIndex+CREATE UNIQUE INDEX "fieldValue_fieldId_companyId_key" ON "fieldValue"("fieldId", "companyId");++-- CreateIndex+CREATE UNIQUE INDEX "fieldValue_fieldId_contactId_key" ON "fieldValue"("fieldId", "contactId");++-- CreateIndex+CREATE UNIQUE INDEX "fieldValue_fieldId_dealId_key" ON "fieldValue"("fieldId", "dealId");++-- AddForeignKey+ALTER TABLE "fieldOption" ADD CONSTRAINT "fieldOption_fieldId_fkey" FOREIGN KEY ("fieldId") REFERENCES "fieldDefinition"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "fieldValue" ADD CONSTRAINT "fieldValue_fieldId_fkey" FOREIGN KEY ("fieldId") REFERENCES "fieldDefinition"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "fieldValue" ADD CONSTRAINT "fieldValue_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "fieldValue" ADD CONSTRAINT "fieldValue_contactId_fkey" FOREIGN KEY ("contactId") REFERENCES "contact"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "fieldValue" ADD CONSTRAINT "fieldValue_dealId_fkey" FOREIGN KEY ("dealId") REFERENCES "deal"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "fieldValue" ADD CONSTRAINT "fieldValue_optionId_fkey" FOREIGN KEY ("optionId") REFERENCES "fieldOption"("id") ON DELETE SET NULL ON UPDATE CASCADE;diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prismaindex 91dc6edf..bd139517 100644--- a/packages/db/prisma/schema.prisma+++ b/packages/db/prisma/schema.prisma@@ -1,4 +1,3 @@-datasource db {provider = "postgresql"}@@ -184,6 +183,7 @@ model Company {activities Activity[]emailThreads EmailThread[]calendarEvents CalendarEvent[]+ fieldValues FieldValue[]createdAt DateTime @default(now())updatedAt DateTime @updatedAt@@ -240,6 +240,7 @@ model Contact {emailThreads EmailThread[]calendarEvents CalendarEvent[]eventAttendance CalendarAttendee[]+ fieldValues FieldValue[]createdAt DateTime @default(now())updatedAt DateTime @updatedAt@@ -404,10 +405,11 @@ model Deal {lastActivityAt DateTime?- contacts DealContact[]- activities Activity[]- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt+ contacts DealContact[]+ activities Activity[]+ fieldValues FieldValue[]+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt@@index([companyId])@@index([ownerId])@@ -452,6 +454,99 @@ model DealContact {@@map("dealContact")}+enum FieldEntity {+ COMPANY+ CONTACT+ DEAL+}++enum FieldType {+ TEXT+ LONG_TEXT+ NUMBER+ DATE+ CHECKBOX+ SELECT+ URL+ PHONE+ USER+}++model FieldDefinition {+ id String @id @default(cuid())+ entity FieldEntity+ key String+ label String+ type FieldType++ agentFilled Boolean @default(true)+ agentBrief String?++ required Boolean @default(false)+ showOnSheet Boolean @default(true)+ showOnTable Boolean @default(false)+ position Int++ archivedAt DateTime?++ options FieldOption[]+ values FieldValue[]++ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@unique([entity, key])+ @@index([entity, position])+ @@map("fieldDefinition")+}++model FieldOption {+ id String @id @default(cuid())+ fieldId String+ field FieldDefinition @relation(fields: [fieldId], references: [id], onDelete: Cascade)+ label String+ position Int++ archivedAt DateTime?+ values FieldValue[]++ @@index([fieldId, position])+ @@map("fieldOption")+}++model FieldValue {+ id String @id @default(cuid())+ fieldId String+ field FieldDefinition @relation(fields: [fieldId], references: [id], onDelete: Cascade)++ companyId String?+ company Company? @relation(fields: [companyId], references: [id], onDelete: Cascade)+ contactId String?+ contact Contact? @relation(fields: [contactId], references: [id], onDelete: Cascade)+ dealId String?+ deal Deal? @relation(fields: [dealId], references: [id], onDelete: Cascade)++ text String?+ number Decimal? @db.Decimal(24, 4)+ date DateTime?+ bool Boolean?+ optionId String?+ option FieldOption? @relation(fields: [optionId], references: [id], onDelete: SetNull)+ userId String?++ updatedAt DateTime @updatedAt++ @@unique([fieldId, companyId])+ @@unique([fieldId, contactId])+ @@unique([fieldId, dealId])+ @@index([fieldId, text])+ @@index([fieldId, number])+ @@index([fieldId, date])+ @@index([optionId])+ @@map("fieldValue")+}+model Activity {id String @id @default(cuid())type ActivityTypediff --git a/packages/db/src/agent-tasks.ts b/packages/db/src/agent-tasks.tsindex 85c8b0de..19773af3 100644--- a/packages/db/src/agent-tasks.ts+++ b/packages/db/src/agent-tasks.ts@@ -7,6 +7,7 @@ export const TASK_KINDS = ["recheck","company-profile","workspace-profile",+ "field-backfill",] as const;export type TaskKind = (typeof TASK_KINDS)[number];@@ -32,5 +33,6 @@ export const PRIORITY = {identify: 100,sweep: 50,companyProfile: 40,+ fieldBackfill: 20,recheck: 0,} as const;diff --git a/packages/db/src/currency.ts b/packages/db/src/currency.tsindex e9471525..af53f60f 100644--- a/packages/db/src/currency.ts+++ b/packages/db/src/currency.ts@@ -17,6 +17,7 @@ const CURRENCY_LIST: readonly CurrencyMeta[] = [{ code: "CHF", name: "Swiss Franc", minorUnits: 2 },{ code: "HKD", name: "Hong Kong Dollar", minorUnits: 2 },{ code: "SGD", name: "Singapore Dollar", minorUnits: 2 },+ { code: "ZAR", name: "South African Rand", minorUnits: 2 },] as const;export const CURRENCIES = CURRENCY_LIST;diff --git a/packages/db/src/fields-shape.ts b/packages/db/src/fields-shape.tsnew file mode 100644index 00000000..3172f6b4--- /dev/null+++ b/packages/db/src/fields-shape.ts@@ -0,0 +1,111 @@+export const FIELD_ENTITIES = ["COMPANY", "CONTACT", "DEAL"] as const;++export type FieldEntityName = (typeof FIELD_ENTITIES)[number];++export const FIELD_TYPES = [+ "TEXT",+ "LONG_TEXT",+ "NUMBER",+ "DATE",+ "CHECKBOX",+ "SELECT",+ "URL",+ "EMAIL",+ "PHONE",+ "USER",+] as const;++export type FieldTypeName = (typeof FIELD_TYPES)[number];++export type FieldValueColumn =+ | "text"+ | "number"+ | "date"+ | "bool"+ | "optionId"+ | "userId";++const COLUMNS: Record<FieldTypeName, FieldValueColumn> = {+ TEXT: "text",+ LONG_TEXT: "text",+ URL: "text",+ EMAIL: "text",+ PHONE: "text",+ NUMBER: "number",+ DATE: "date",+ CHECKBOX: "bool",+ SELECT: "optionId",+ USER: "userId",+};++const TYPE_LABELS: Record<FieldTypeName, string> = {+ TEXT: "Text",+ LONG_TEXT: "Long text",+ NUMBER: "Number",+ DATE: "Date",+ CHECKBOX: "Checkbox",+ SELECT: "Select",+ URL: "URL",+ EMAIL: "Email",+ PHONE: "Phone",+ USER: "User",+};++export function columnFor(type: FieldTypeName): FieldValueColumn {+ return COLUMNS[type];+}++export function typeLabel(type: FieldTypeName): string {+ return TYPE_LABELS[type];+}++export function usesOptions(type: FieldTypeName): boolean {+ return type === "SELECT";+}++export const RECORD_ID_COLUMNS = {+ COMPANY: "companyId",+ CONTACT: "contactId",+ DEAL: "dealId",+} as const satisfies Record<FieldEntityName, string>;++export type RecordIdColumn =+ (typeof RECORD_ID_COLUMNS)[keyof typeof RECORD_ID_COLUMNS];++export function recordColumn(entity: FieldEntityName): RecordIdColumn {+ return RECORD_ID_COLUMNS[entity];+}++const RESERVED_KEYS = new Set([+ "id",+ "createdat",+ "updatedat",+ "fields",+ "owner",+ "ownerid",+]);++export function fieldKeyFromLabel(label: string): string {+ const key = label+ .trim()+ .toLowerCase()+ .replace(/['’]/g, "")+ .replace(/[^a-z0-9]+/g, "_")+ .replace(/^_+|_+$/g, "")+ .replace(/^([0-9])/, "f_$1")+ .slice(0, 60);++ return RESERVED_KEYS.has(key) ? `${key}_field` : key;+}++export class FieldValueError extends Error {+ readonly key: string;++ constructor(key: string, message: string) {+ super(message);+ this.name = "FieldValueError";+ this.key = key;+ }+}++export type FieldValueJson = string | number | boolean | null;diff --git a/packages/db/src/fields.ts b/packages/db/src/fields.tsnew file mode 100644index 00000000..1aa53a7e--- /dev/null+++ b/packages/db/src/fields.ts@@ -0,0 +1,253 @@+import {+ columnFor,+ type FieldValueColumn,+ FieldValueError,+ type FieldValueJson,+ recordColumn,+ typeLabel,+} from "./fields-shape";+import { Prisma } from "./generated/prisma/client";+import type { FieldEntity, FieldType } from "./generated/prisma/enums";+import type {+ FieldDefinitionModel,+ FieldOptionModel,+ FieldValueModel,+} from "./generated/prisma/models";++export * from "./fields-shape";++export type FieldDefinitionWithOptions = FieldDefinitionModel & {+ options: FieldOptionModel[];+};++export type SerializedFieldOption = {+ id: string;+ label: string;+ position: number;+};++export type SerializedField = {+ id: string;+ entity: FieldEntity;+ key: string;+ label: string;+ type: FieldType;+ typeLabel: string;+ agentFilled: boolean;+ agentBrief: string | null;+ required: boolean;+ showOnSheet: boolean;+ showOnTable: boolean;+ position: number;+ archived: boolean;+ options: SerializedFieldOption[];+};++export function serializeField(+ definition: FieldDefinitionWithOptions,+): SerializedField {+ return {+ id: definition.id,+ entity: definition.entity,+ key: definition.key,+ label: definition.label,+ type: definition.type,+ typeLabel: typeLabel(definition.type),+ agentFilled: definition.agentFilled,+ agentBrief: definition.agentBrief,+ required: definition.required,+ showOnSheet: definition.showOnSheet,+ showOnTable: definition.showOnTable,+ position: definition.position,+ archived: definition.archivedAt !== null,+ options: definition.options+ .filter((option) => option.archivedAt === null)+ .sort((left, right) => left.position - right.position)+ .map((option) => ({+ id: option.id,+ label: option.label,+ position: option.position,+ })),+ };+}++const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;++export function coerceValue(+ definition: FieldDefinitionWithOptions,+ input: unknown,+): Partial<Record<FieldValueColumn, unknown>> {+ const blank =+ input === null ||+ input === undefined ||+ (typeof input === "string" && input.trim() === "");++ if (blank) {+ if (definition.required) {+ throw new FieldValueError(+ definition.key,+ `${definition.label} cannot be empty.`,+ );+ }++ return { [columnFor(definition.type)]: null };+ }++ switch (definition.type) {+ case "CHECKBOX": {+ if (typeof input === "boolean") return { bool: input };+ if (input === "true" || input === "false") {+ return { bool: input === "true" };+ }+ throw new FieldValueError(+ definition.key,+ `${definition.label} takes true or false.`,+ );+ }++ case "NUMBER": {+ const parsed =+ typeof input === "number" ? input : Number(String(input).trim());++ if (!Number.isFinite(parsed)) {+ throw new FieldValueError(+ definition.key,+ `${definition.label} takes a number.`,+ );+ }++ return { number: new Prisma.Decimal(parsed) };+ }++ case "DATE": {+ const raw = String(input).trim();+ const parsed = ISO_DATE.test(raw)+ ? new Date(`${raw}T00:00:00.000Z`)+ : new Date(raw);++ if (Number.isNaN(parsed.getTime())) {+ throw new FieldValueError(+ definition.key,+ `${definition.label} takes a date.`,+ );+ }++ return { date: parsed };+ }++ case "SELECT": {+ const raw = String(input).trim();+ const option = definition.options.find(+ (entry) =>+ entry.archivedAt === null &&+ (entry.id === raw || entry.label.toLowerCase() === raw.toLowerCase()),+ );++ if (!option) {+ throw new FieldValueError(+ definition.key,+ `${definition.label} has no option "${raw}".`,+ );+ }++ return { optionId: option.id };+ }++ case "USER":+ return { userId: String(input).trim() };++ default:+ return { text: String(input).trim() };+ }+}++export function readValue(+ definition: FieldDefinitionWithOptions,+ row: FieldValueModel | undefined,+): FieldValueJson {+ if (!row) return null;++ switch (definition.type) {+ case "CHECKBOX":+ return row.bool ?? null;+ case "NUMBER":+ return row.number === null ? null : Number(row.number);+ case "DATE":+ return row.date === null ? null : row.date.toISOString();+ case "SELECT":+ return row.optionId ?? null;+ case "USER":+ return row.userId ?? null;+ default:+ return row.text ?? null;+ }+}++export type RecordField = SerializedField & { value: FieldValueJson };++export function attachValues(+ definitions: FieldDefinitionWithOptions[],+ rows: FieldValueModel[],+): RecordField[] {+ const byField = new Map(rows.map((row) => [row.fieldId, row]));++ 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)),+ }));+}++export type FieldWriter = {+ fieldValue: {+ deleteMany(args: { where: Record<string, unknown> }): Promise<unknown>;+ upsert(args: {+ where: Record<string, unknown>;+ create: Record<string, unknown>;+ update: Record<string, unknown>;+ }): Promise<unknown>;+ };+};++export async function writeValues(+ tx: FieldWriter,+ entity: FieldEntity,+ recordId: string,+ definitions: FieldDefinitionWithOptions[],+ values: Record<string, unknown>,+): Promise<void> {+ const column = recordColumn(entity);+ const byKey = new Map(+ definitions+ .filter((definition) => definition.archivedAt === null)+ .map((definition) => [definition.key, definition]),+ );++ for (const [key, input] of Object.entries(values)) {+ const definition = byKey.get(key);++ if (!definition) {+ throw new FieldValueError(key, `There is no field called "${key}".`);+ }++ const data = coerceValue(definition, input);+ const stored = data[columnFor(definition.type)];++ if (stored === null || stored === undefined) {+ await tx.fieldValue.deleteMany({+ where: { fieldId: definition.id, [column]: recordId },+ });+ continue;+ }++ await tx.fieldValue.upsert({+ where: {+ [`fieldId_${column}`]: { fieldId: definition.id, [column]: recordId },+ },+ create: { fieldId: definition.id, [column]: recordId, ...data },+ update: data,+ });+ }+}diff --git a/packages/db/test/currency.spec.ts b/packages/db/test/currency.spec.tsindex 0a5a8ab7..9fec3349 100644--- a/packages/db/test/currency.spec.ts+++ b/packages/db/test/currency.spec.ts@@ -60,7 +60,7 @@ describe("normalizeCurrency and isCurrencyCode", () => {}});- it("offers only the ten currencies most of the world trades in", () => {+ it("offers only the eleven currencies most of the world trades in", () => {expect(CURRENCIES.map((entry) => entry.code)).toEqual(["USD","EUR",@@ -72,6 +72,7 @@ describe("normalizeCurrency and isCurrencyCode", () => {"CHF","HKD","SGD",+ "ZAR",]);});diff --git a/packages/db/test/fields.spec.ts b/packages/db/test/fields.spec.tsnew file mode 100644index 00000000..3b387260--- /dev/null+++ b/packages/db/test/fields.spec.ts@@ -0,0 +1,228 @@+import { describe, expect, it } from "bun:test";+import {+ attachValues,+ coerceValue,+ columnFor,+ type FieldDefinitionWithOptions,+ FieldValueError,+ fieldKeyFromLabel,+ readValue,+ recordColumn,+ serializeField,+} from "../src/fields";+import type { FieldValueModel } from "../src/generated/prisma/models";++function definition(+ over: Partial<FieldDefinitionWithOptions> = {},+): FieldDefinitionWithOptions {+ return {+ id: "def-1",+ entity: "COMPANY",+ key: "runs_on",+ label: "Runs on",+ type: "TEXT",+ agentFilled: true,+ agentBrief: null,+ required: false,+ showOnSheet: true,+ showOnTable: false,+ position: 0,+ archivedAt: null,+ createdAt: new Date("2026-01-01T00:00:00.000Z"),+ updatedAt: new Date("2026-01-01T00:00:00.000Z"),+ options: [],+ ...over,+ } as FieldDefinitionWithOptions;+}++function value(over: Partial<FieldValueModel> = {}): FieldValueModel {+ return {+ id: "val-1",+ fieldId: "def-1",+ companyId: "company-1",+ contactId: null,+ dealId: null,+ text: null,+ number: null,+ date: null,+ bool: null,+ optionId: null,+ userId: null,+ updatedAt: new Date("2026-01-01T00:00:00.000Z"),+ ...over,+ } as FieldValueModel;+}++describe("fieldKeyFromLabel", () => {+ it("slugs a label", () => {+ expect(fieldKeyFromLabel("Runs on")).toBe("runs_on");+ expect(fieldKeyFromLabel(" ICP Tier ")).toBe("icp_tier");+ expect(fieldKeyFromLabel("Who's signing?")).toBe("whos_signing");+ });++ it("never starts with a digit", () => {+ expect(fieldKeyFromLabel("2026 renewal")).toBe("f_2026_renewal");+ });++ it("steps around keys the record shape already uses", () => {+ expect(fieldKeyFromLabel("id")).toBe("id_field");+ expect(fieldKeyFromLabel("Owner")).toBe("owner_field");+ });+});++describe("columnFor", () => {+ it("routes every type to one storage column", () => {+ expect(columnFor("TEXT")).toBe("text");+ expect(columnFor("LONG_TEXT")).toBe("text");+ expect(columnFor("EMAIL")).toBe("text");+ expect(columnFor("NUMBER")).toBe("number");+ expect(columnFor("DATE")).toBe("date");+ expect(columnFor("CHECKBOX")).toBe("bool");+ expect(columnFor("SELECT")).toBe("optionId");+ expect(columnFor("USER")).toBe("userId");+ });+});++describe("recordColumn", () => {+ it("maps an entity to its foreign key", () => {+ expect(recordColumn("COMPANY")).toBe("companyId");+ expect(recordColumn("CONTACT")).toBe("contactId");+ expect(recordColumn("DEAL")).toBe("dealId");+ });+});++describe("coerceValue", () => {+ it("trims text", () => {+ expect(coerceValue(definition(), " AWS ")).toEqual({ text: "AWS" });+ });++ it("clears an optional field when the value is blank", () => {+ expect(coerceValue(definition(), " ")).toEqual({ text: null });+ expect(coerceValue(definition(), null)).toEqual({ text: null });+ });++ it("refuses to clear a required field", () => {+ expect(() => coerceValue(definition({ required: true }), "")).toThrow(+ FieldValueError,+ );+ });++ it("takes numbers as numbers or strings", () => {+ const numeric = definition({ type: "NUMBER" });+ expect(Number(coerceValue(numeric, "240").number)).toBe(240);+ expect(Number(coerceValue(numeric, 240).number)).toBe(240);+ expect(() => coerceValue(numeric, "many")).toThrow(FieldValueError);+ });++ it("reads a plain date as UTC midnight", () => {+ const dated = definition({ type: "DATE" });+ const parsed = coerceValue(dated, "2027-03-31").date as Date;+ expect(parsed.toISOString()).toBe("2027-03-31T00:00:00.000Z");+ expect(() => coerceValue(dated, "whenever")).toThrow(FieldValueError);+ });++ it("takes a checkbox as a boolean or its string", () => {+ const checkbox = definition({ type: "CHECKBOX" });+ expect(coerceValue(checkbox, true)).toEqual({ bool: true });+ expect(coerceValue(checkbox, "false")).toEqual({ bool: false });+ expect(() => coerceValue(checkbox, "maybe")).toThrow(FieldValueError);+ });++ it("resolves a select by id or by label, and rejects anything else", () => {+ const select = definition({+ type: "SELECT",+ options: [+ {+ id: "opt-aws",+ fieldId: "def-1",+ label: "AWS",+ position: 0,+ archivedAt: null,+ },+ ],+ } as Partial<FieldDefinitionWithOptions>);++ expect(coerceValue(select, "opt-aws")).toEqual({ optionId: "opt-aws" });+ expect(coerceValue(select, "aws")).toEqual({ optionId: "opt-aws" });+ expect(() => coerceValue(select, "Fly.io")).toThrow(FieldValueError);+ });+});++describe("readValue", () => {+ it("reads each type back out of its column", () => {+ expect(readValue(definition(), value({ text: "AWS" }))).toBe("AWS");+ expect(+ readValue(definition({ type: "CHECKBOX" }), value({ bool: true })),+ ).toBe(true);+ expect(+ readValue(+ definition({ type: "DATE" }),+ value({ date: new Date("2027-03-31T00:00:00.000Z") }),+ ),+ ).toBe("2027-03-31T00:00:00.000Z");+ });++ it("is null when the record has no row", () => {+ expect(readValue(definition(), undefined)).toBeNull();+ });+});++describe("serializeField", () => {+ it("drops archived options and orders the rest", () => {+ const serialized = serializeField(+ definition({+ type: "SELECT",+ options: [+ {+ id: "b",+ fieldId: "def-1",+ label: "Azure",+ position: 1,+ archivedAt: null,+ },+ {+ id: "a",+ fieldId: "def-1",+ label: "AWS",+ position: 0,+ archivedAt: null,+ },+ {+ id: "c",+ fieldId: "def-1",+ label: "Heroku",+ position: 2,+ archivedAt: new Date(),+ },+ ],+ } as Partial<FieldDefinitionWithOptions>),+ );++ expect(serialized.options.map((option) => option.label)).toEqual([+ "AWS",+ "Azure",+ ]);+ });+});++describe("attachValues", () => {+ it("orders by position, hides archived fields and fills in values", () => {+ const fields = attachValues(+ [+ definition({ id: "second", key: "seats", position: 1 }),+ definition({ id: "first", key: "runs_on", position: 0 }),+ definition({+ id: "gone",+ key: "old",+ position: 2,+ archivedAt: new Date(),+ }),+ ],+ [value({ fieldId: "first", text: "AWS" })],+ );++ expect(fields.map((field) => field.key)).toEqual(["runs_on", "seats"]);+ expect(fields[0]?.value).toBe("AWS");+ expect(fields[1]?.value).toBeNull();+ });+});diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 3a65efce..fbb368a8 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -19,6 +19,10 @@"dependencies": {"@carbon/icons-react": "^11.82.0","@crm/db": "workspace:*",+ "@dnd-kit/core": "^6.3.1",+ "@dnd-kit/modifiers": "^9.0.0",+ "@dnd-kit/sortable": "^10.0.0",+ "@dnd-kit/utilities": "^3.2.2","@shadcn/react": "^0.2.1","class-variance-authority": "^0.7.1","clsx": "^2.1.1",diff --git a/packages/ui/src/components/badge.tsx b/packages/ui/src/components/badge.tsxnew file mode 100644index 00000000..ca36ed7c--- /dev/null+++ b/packages/ui/src/components/badge.tsx@@ -0,0 +1,50 @@+import * as React from "react"+import { cva, type VariantProps } from "class-variance-authority"+import { Slot } from "radix-ui"++import { cn } from "@crm/ui/lib/utils"++const badgeVariants = cva(+ "group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",+ {+ variants: {+ variant: {+ default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",+ secondary:+ "bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",+ destructive:+ "bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",+ outline:+ "border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",+ ghost:+ "hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",+ link: "text-primary underline-offset-4 hover:underline",+ mono: "rounded-sm bg-muted font-mono font-normal text-muted-foreground",+ },+ },+ defaultVariants: {+ variant: "default",+ },+ }+)++function Badge({+ className,+ variant = "default",+ asChild = false,+ ...props+}: React.ComponentProps<"span"> &+ VariantProps<typeof badgeVariants> & { asChild?: boolean }) {+ const Comp = asChild ? Slot.Root : "span"++ return (+ <Comp+ data-slot="badge"+ data-variant={variant}+ className={cn(badgeVariants({ variant }), className)}+ {...props}+ />+ )+}++export { Badge, badgeVariants }diff --git a/packages/ui/src/components/checkbox.tsx b/packages/ui/src/components/checkbox.tsxindex 4b3afdc3..9f017e9c 100644--- a/packages/ui/src/components/checkbox.tsx+++ b/packages/ui/src/components/checkbox.tsx@@ -1,7 +1,7 @@"use client";import { cn } from "@crm/ui/lib/utils";-import { CheckIcon } from "lucide-react";+import { CheckIcon, MinusIcon } from "lucide-react";import { Checkbox as CheckboxPrimitive } from "radix-ui";import type * as React from "react";@@ -13,7 +13,7 @@ function Checkbox({<CheckboxPrimitive.Rootdata-slot="checkbox"className={cn(- "peer relative flex size-4 shrink-0 items-center justify-center rounded-sm border border-input transition-colors outline-none group-has-disabled/field:opacity-50 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-2 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-muted dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary",+ "peer relative flex size-4 shrink-0 items-center justify-center rounded-sm border border-input transition-colors outline-none group-has-disabled/field:opacity-50 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-2 aria-invalid:ring-destructive/20 aria-invalid:aria-checked:border-primary dark:bg-muted dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary data-[state=indeterminate]:border-primary data-[state=indeterminate]:bg-primary data-[state=indeterminate]:text-primary-foreground",className,)}{...props}@@ -22,7 +22,7 @@ function Checkbox({data-slot="checkbox-indicator"className="grid place-content-center text-current transition-none [&>svg]:size-3.5">- <CheckIcon />+ {props.checked === "indeterminate" ? <MinusIcon /> : <CheckIcon />}</CheckboxPrimitive.Indicator></CheckboxPrimitive.Root>);diff --git a/packages/ui/src/components/collapsible.tsx b/packages/ui/src/components/collapsible.tsxnew file mode 100644index 00000000..2f7a4e7f--- /dev/null+++ b/packages/ui/src/components/collapsible.tsx@@ -0,0 +1,33 @@+"use client"++import { Collapsible as CollapsiblePrimitive } from "radix-ui"++function Collapsible({+ ...props+}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {+ return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />+}++function CollapsibleTrigger({+ ...props+}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {+ return (+ <CollapsiblePrimitive.CollapsibleTrigger+ data-slot="collapsible-trigger"+ {...props}+ />+ )+}++function CollapsibleContent({+ ...props+}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {+ return (+ <CollapsiblePrimitive.CollapsibleContent+ data-slot="collapsible-content"+ {...props}+ />+ )+}++export { Collapsible, CollapsibleTrigger, CollapsibleContent }diff --git a/packages/ui/src/components/data-table.tsx b/packages/ui/src/components/data-table.tsxindex 612f8eb0..03b31b52 100644--- a/packages/ui/src/components/data-table.tsx+++ b/packages/ui/src/components/data-table.tsx@@ -8,6 +8,7 @@ import ChevronRight from "@carbon/icons-react/es/ChevronRight";import Column from "@carbon/icons-react/es/Column";import Filter from "@carbon/icons-react/es/Filter";import { Button } from "@crm/ui/components/button";+import { Checkbox } from "@crm/ui/components/checkbox";import {DropdownMenu,DropdownMenuCheckboxItem,@@ -28,6 +29,7 @@ import {TableHeader,TableRow,} from "@crm/ui/components/table";+import type { TableSelection } from "@crm/ui/hooks/use-table-selection";import { ROW_ACCENT, ROW_ACCENT_EXPANDABLE } from "@crm/ui/lib/row-accent";import type { TableQueryState } from "@crm/ui/lib/table-query";import { cn } from "@crm/ui/lib/utils";@@ -76,6 +78,12 @@ export type DataTableExpandable<TRow, TSub> = {onSubRowClick?: (sub: TSub, row: TRow) => void;};+export type DataTableSelection<TRow> = {+ state: TableSelection;+ actions: ReactNode;+ rowLabel?: (row: TRow) => string;+};+export type DataTableProps<TRow, TSub> = {query: TableQueryState;columns: DataTableColumn<TRow>[];@@ -89,6 +97,7 @@ export type DataTableProps<TRow, TSub> = {onRowClick?: (row: TRow) => void;onRowHover?: (row: TRow) => void;expandable?: DataTableExpandable<TRow, TSub>;+ selection?: DataTableSelection<TRow>;actions?: ReactNode;leadingActions?: ReactNode;search?: ReactNode;@@ -150,6 +159,7 @@ export function DataTable<TRow, TSub = unknown>({onRowClick,onRowHover,expandable,+ selection,actions,leadingActions,search,@@ -193,7 +203,7 @@ export function DataTable<TRow, TSub = unknown>({const anyExpandable =expandable != null &&deferredRows.some((row) => expandable.isExpandable(row));- const colCount = visibleColumns.length + (anyExpandable ? 1 : 0);+ const selecting = selection != null && selection.state.count > 0;const pageSize = query.pageSize;const totalPages = Math.max(1, Math.ceil(total / pageSize));@@ -213,7 +223,32 @@ export function DataTable<TRow, TSub = unknown>({return (<div className={cn("flex min-h-0 flex-1 flex-col gap-3", className)}>- <div className="flex flex-col gap-2 lg:flex-row lg:flex-wrap lg:items-center lg:justify-between">+ {selecting && selection ? (+ <div className="flex h-8 items-center gap-2">+ <span className="truncate text-xs text-muted-foreground">+ <span className="font-medium text-foreground tabular-nums">+ {selection.state.count}+ </span>{" "}+ selected+ </span>+ <div className="ml-auto flex items-center gap-2">+ {selection.actions}+ <Button+ variant="ghost"+ size="sm"+ onClick={() => selection.state.clear()}+ >+ Clear+ </Button>+ </div>+ </div>+ ) : null}+ <div+ className={cn(+ "flex flex-col gap-2 lg:flex-row lg:flex-wrap lg:items-center lg:justify-between",+ selecting && "hidden",+ )}+ >{search}{hasFilterControls && (<Button@@ -426,9 +461,34 @@ export function DataTable<TRow, TSub = unknown>({tableClassName,)}containerClassName="min-h-0 flex-1 overflow-auto rounded-lg border bg-card"+ overlay={+ deferredRows.length === 0 ? (+ <div className="absolute inset-x-0 top-11 bottom-0 flex items-center justify-center px-4 py-8 text-center text-muted-foreground">+ {loading ? <Spinner /> : (empty ?? "No results found.")}+ </div>+ ) : null+ }><TableHeader className="sticky top-0 z-10 bg-muted [&_th]:bg-muted [&_tr]:border-0 [&_tr]:shadow-[inset_0_-1px_0_var(--border)]"><TableRow>+ {selection && (+ <TableHead className={cn("h-11 w-10 px-3", HIDE_BELOW_CLASS.sm)}>+ <Checkbox+ checked={+ selection.state.allSelected+ ? true+ : selection.state.someSelected+ ? "indeterminate"+ : false+ }+ onCheckedChange={(checked) =>+ selection.state.toggleAll(checked === true)+ }+ disabled={deferredRows.length === 0}+ aria-label="Select every row on this page"+ />+ </TableHead>+ )}{anyExpandable && (<TableHead className="h-11 w-10 px-3"><span className="sr-only">Detail</span>@@ -477,122 +537,137 @@ export function DataTable<TRow, TSub = unknown>({</TableRow></TableHeader><TableBody>- {deferredRows.length === 0 ? (- <TableRow className="hover:bg-transparent">- <TableCell- colSpan={colCount}- className="h-32 whitespace-normal py-8 text-center align-middle text-muted-foreground"- >- {loading ? <Spinner /> : (empty ?? "No results found.")}- </TableCell>- </TableRow>- ) : (- deferredRows.map((row) => {- const id = getRowId(row);- const canExpand = expandable?.isExpandable(row) ?? false;- const isOpen = canExpand && expanded.has(id);- const clickable = canExpand || !!onRowClick;- const handleClick = () => {- if (canExpand) {- setExpandedIds((prev) => {- const set = new Set(prev ?? []);- if (set.has(id)) set.delete(id);- else set.add(id);- const next = [...set];- return next.length > 0 ? next : null;- });- } else {- onRowClick?.(row);- }- };- return (- <Fragment key={id}>- <TableRow- onClick={clickable ? handleClick : undefined}- onMouseEnter={- onRowHover ? () => onRowHover(row) : undefined- }- onFocus={onRowHover ? () => onRowHover(row) : undefined}- className={- clickable- ? anyExpandable- ? ROW_ACCENT_EXPANDABLE- : ROW_ACCENT- : undefined- }- >- {anyExpandable && (- <TableCell className="w-10 px-3 py-3 text-center text-muted-foreground">- {canExpand && (- <ChevronRight- size={12}+ {deferredRows.map((row) => {+ const id = getRowId(row);+ const canExpand = expandable?.isExpandable(row) ?? false;+ const isOpen = canExpand && expanded.has(id);+ const isSelected = selection?.state.has(id) ?? false;+ const clickable = canExpand || !!onRowClick;+ const handleClick = () => {+ if (canExpand) {+ setExpandedIds((prev) => {+ const set = new Set(prev ?? []);+ if (set.has(id)) set.delete(id);+ else set.add(id);+ const next = [...set];+ return next.length > 0 ? next : null;+ });+ } else {+ onRowClick?.(row);+ }+ };+ return (+ <Fragment key={id}>+ <TableRow+ data-state={isSelected ? "selected" : undefined}+ onClick={clickable ? handleClick : undefined}+ onMouseEnter={onRowHover ? () => onRowHover(row) : undefined}+ onFocus={onRowHover ? () => onRowHover(row) : undefined}+ className={+ clickable+ ? anyExpandable+ ? ROW_ACCENT_EXPANDABLE+ : ROW_ACCENT+ : undefined+ }+ >+ {selection && (+ <TableCell+ className={cn("w-10 px-3 py-3", HIDE_BELOW_CLASS.sm)}+ onClick={(event) => event.stopPropagation()}+ >+ <Checkbox+ checked={isSelected}+ onCheckedChange={(checked) =>+ selection.state.toggle(id, checked === true)+ }+ aria-label={+ selection.rowLabel+ ? `Select ${selection.rowLabel(row)}`+ : "Select row"+ }+ />+ </TableCell>+ )}+ {anyExpandable && (+ <TableCell className="w-10 px-3 py-3 text-center text-muted-foreground">+ {canExpand && (+ <ChevronRight+ size={12}+ className={cn(+ "inline-block transition-transform",+ isOpen && "rotate-90",+ )}+ />+ )}+ </TableCell>+ )}+ {visibleColumns.map((column) => (+ <TableCell+ key={column.id}+ className={cn(+ "overflow-hidden px-3 py-3",+ column.width,+ ALIGN_CLASS[column.align ?? "left"],+ column.hideBelow && HIDE_BELOW_CLASS[column.hideBelow],+ column.cellClassName,+ )}+ >+ {column.cell(row)}+ </TableCell>+ ))}+ </TableRow>+ {isOpen &&+ expandable?.getSubRows(row).map((sub) => {+ const subClickable = !!expandable.onSubRowClick;+ return (+ <TableRow+ key={expandable.getSubRowId(sub, row)}+ onClick={+ subClickable+ ? () => expandable.onSubRowClick?.(sub, row)+ : undefined+ }+ className={cn(+ "bg-muted/30",+ subClickable &&+ (anyExpandable+ ? ROW_ACCENT_EXPANDABLE+ : ROW_ACCENT),+ )}+ >+ {selection && (+ <TableCellclassName={cn(- "inline-block transition-transform",- isOpen && "rotate-90",+ "w-10 px-3 py-2.5",+ HIDE_BELOW_CLASS.sm,)}/>)}- </TableCell>- )}- {visibleColumns.map((column) => (- <TableCell- key={column.id}- className={cn(- "overflow-hidden px-3 py-3",- column.width,- ALIGN_CLASS[column.align ?? "left"],- column.hideBelow && HIDE_BELOW_CLASS[column.hideBelow],- column.cellClassName,+ {anyExpandable && (+ <TableCell className="w-10 px-3 py-2.5" />)}- >- {column.cell(row)}- </TableCell>- ))}- </TableRow>- {isOpen &&- expandable?.getSubRows(row).map((sub) => {- const subClickable = !!expandable.onSubRowClick;- return (- <TableRow- key={expandable.getSubRowId(sub, row)}- onClick={- subClickable- ? () => expandable.onSubRowClick?.(sub, row)- : undefined- }- className={cn(- "bg-muted/30",- subClickable &&- (anyExpandable- ? ROW_ACCENT_EXPANDABLE- : ROW_ACCENT),- )}- >- {anyExpandable && (- <TableCell className="w-10 px-3 py-2.5" />- )}- {visibleColumns.map((column) => (- <TableCell- key={column.id}- className={cn(- "overflow-hidden px-3 py-2.5 align-top",- column.width,- ALIGN_CLASS[column.align ?? "left"],- column.hideBelow &&- HIDE_BELOW_CLASS[column.hideBelow],- column.cellClassName,- )}- >- {expandable.renderSubCell(sub, column.id, row)}- </TableCell>- ))}- </TableRow>- );- })}- </Fragment>- );- })- )}+ {visibleColumns.map((column) => (+ <TableCell+ key={column.id}+ className={cn(+ "overflow-hidden px-3 py-2.5 align-top",+ column.width,+ ALIGN_CLASS[column.align ?? "left"],+ column.hideBelow &&+ HIDE_BELOW_CLASS[column.hideBelow],+ column.cellClassName,+ )}+ >+ {expandable.renderSubCell(sub, column.id, row)}+ </TableCell>+ ))}+ </TableRow>+ );+ })}+ </Fragment>+ );+ })}</TableBody></Table>diff --git a/packages/ui/src/components/empty.tsx b/packages/ui/src/components/empty.tsxindex 2cf239d5..053a9180 100644--- a/packages/ui/src/components/empty.tsx+++ b/packages/ui/src/components/empty.tsx@@ -90,7 +90,7 @@ function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) {<divdata-slot="empty-description"className={cn(- "text-xs/relaxed text-muted-foreground [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",+ "text-balance text-xs/relaxed text-muted-foreground [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",className,)}{...props}diff --git a/packages/ui/src/components/sheet.tsx b/packages/ui/src/components/sheet.tsxindex 78cfd131..db98a2b2 100644--- a/packages/ui/src/components/sheet.tsx+++ b/packages/ui/src/components/sheet.tsx@@ -13,6 +13,7 @@ const sheetContentVariants = cva(variants: {size: {sm: "data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm",+ md: "data-[side=left]:sm:max-w-[460px] data-[side=right]:sm:max-w-[460px]",lg: "data-[side=left]:sm:max-w-3xl data-[side=right]:sm:max-w-3xl",xl: "data-[side=left]:sm:max-w-4xl data-[side=right]:sm:max-w-4xl","2xl":diff --git a/packages/ui/src/components/sortable-list.tsx b/packages/ui/src/components/sortable-list.tsxnew file mode 100644index 00000000..7deef0a2--- /dev/null+++ b/packages/ui/src/components/sortable-list.tsx@@ -0,0 +1,116 @@+"use client";++import Draggable from "@carbon/icons-react/es/Draggable";+import {+ closestCenter,+ DndContext,+ type DragEndEvent,+ KeyboardSensor,+ PointerSensor,+ useSensor,+ useSensors,+} from "@dnd-kit/core";+import {+ restrictToParentElement,+ restrictToVerticalAxis,+} from "@dnd-kit/modifiers";+import {+ arrayMove,+ SortableContext,+ sortableKeyboardCoordinates,+ useSortable,+ verticalListSortingStrategy,+} from "@dnd-kit/sortable";+import { CSS } from "@dnd-kit/utilities";+import type { ReactNode } from "react";+import { Button } from "@crm/ui/components/button";+import { Icon } from "@crm/ui/components/icon";+import { cn } from "@crm/ui/lib/utils";++export function SortableList({+ ids,+ onReorder,+ children,+}: {+ ids: string[];+ onReorder: (ids: string[]) => void;+ children: ReactNode;+}) {+ const sensors = useSensors(+ useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),+ useSensor(KeyboardSensor, {+ coordinateGetter: sortableKeyboardCoordinates,+ }),+ );++ const onDragEnd = (event: DragEndEvent) => {+ 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));+ if (from === -1 || to === -1) return;++ onReorder(arrayMove(ids, from, to));+ };++ return (+ <DndContext+ sensors={sensors}+ collisionDetection={closestCenter}+ modifiers={[restrictToVerticalAxis, restrictToParentElement]}+ onDragEnd={onDragEnd}+ >+ <SortableContext items={ids} strategy={verticalListSortingStrategy}>+ {children}+ </SortableContext>+ </DndContext>+ );+}++export function SortableItem({+ id,+ label,+ className,+ children,+}: {+ id: string;+ label: string;+ className?: string;+ children: ReactNode;+}) {+ const {+ attributes,+ listeners,+ setNodeRef,+ setActivatorNodeRef,+ transform,+ transition,+ isDragging,+ } = useSortable({ id });++ return (+ <div+ ref={setNodeRef}+ style={{ transform: CSS.Transform.toString(transform), transition }}+ className={cn(+ "flex items-center gap-2.5",+ isDragging && "relative z-10 bg-background",+ className,+ )}+ >+ <Button+ ref={setActivatorNodeRef}+ variant="ghost"+ size="icon-xs"+ className="cursor-grab text-muted-foreground"+ {...attributes}+ {...listeners}+ >+ <Icon icon={Draggable} />+ <span className="sr-only">Reorder {label}</span>+ </Button>+ {children}+ </div>+ );+}diff --git a/packages/ui/src/components/status-indicator.tsx b/packages/ui/src/components/status-indicator.tsxindex bd41e6ed..008e8022 100644--- a/packages/ui/src/components/status-indicator.tsx+++ b/packages/ui/src/components/status-indicator.tsx@@ -3,7 +3,13 @@ import { type Bloom, bloomClass } from "@crm/ui/lib/dither";import { cn } from "@crm/ui/lib/utils";import type * as React from "react";-export type StatusTone = "neutral" | "info" | "success" | "warning" | "error";+export type StatusTone =+ | "neutral"+ | "primary"+ | "info"+ | "success"+ | "warning"+ | "error";export type StatusSize = "default" | "sm";@@ -14,6 +20,7 @@ const SIZE_CLASS: Record<StatusSize, string> = {const TONE_COLOR: Record<StatusTone, string> = {neutral: "var(--color-muted-foreground)",+ primary: "var(--color-primary)",info: "var(--color-info)",success: "var(--color-success)",warning: "var(--color-warning)",diff --git a/packages/ui/src/components/table.tsx b/packages/ui/src/components/table.tsxindex 9611a4f9..a45b59b5 100644--- a/packages/ui/src/components/table.tsx+++ b/packages/ui/src/components/table.tsx@@ -6,8 +6,12 @@ import type * as React from "react";function Table({className,containerClassName,+ overlay,...props-}: React.ComponentProps<"table"> & { containerClassName?: string }) {+}: React.ComponentProps<"table"> & {+ containerClassName?: string;+ overlay?: React.ReactNode;+}) {return (<divdata-slot="table-container"@@ -18,6 +22,7 @@ function Table({className={cn("w-full caption-bottom text-xs", className)}{...props}/>+ {overlay}</div>);}diff --git a/packages/ui/src/hooks/use-table-selection.ts b/packages/ui/src/hooks/use-table-selection.tsnew file mode 100644index 00000000..fb2a8bbe--- /dev/null+++ b/packages/ui/src/hooks/use-table-selection.ts@@ -0,0 +1,63 @@+"use client";++import { useCallback, useMemo, useState } from "react";++const EMPTY: ReadonlySet<string> = new Set();++export type TableSelection = {+ ids: string[];+ count: number;+ has: (id: string) => boolean;+ toggle: (id: string, selected: boolean) => void;+ toggleAll: (selected: boolean) => void;+ clear: () => void;+ allSelected: boolean;+ someSelected: boolean;+};++export function useTableSelection(rowIds: string[]): TableSelection {+ const [picked, setPicked] = useState<ReadonlySet<string>>(EMPTY);++ const ids = useMemo(+ () => rowIds.filter((id) => picked.has(id)),+ [rowIds, picked],+ );++ const has = useCallback((id: string) => picked.has(id), [picked]);++ const toggle = useCallback((id: string, selected: boolean) => {+ setPicked((prev) => {+ const next = new Set(prev);+ if (selected) next.add(id);+ else next.delete(id);+ return next;+ });+ }, []);++ const toggleAll = useCallback(+ (selected: boolean) => {+ setPicked((prev) => {+ const next = new Set(prev);+ for (const id of rowIds) {+ if (selected) next.add(id);+ else next.delete(id);+ }+ return next;+ });+ },+ [rowIds],+ );++ const clear = useCallback(() => setPicked(EMPTY), []);++ return {+ ids,+ count: ids.length,+ has,+ toggle,+ toggleAll,+ clear,+ allSelected: rowIds.length > 0 && ids.length === rowIds.length,+ someSelected: ids.length > 0 && ids.length < rowIds.length,+ };+}diff --git a/packages/ui/src/lib/format.ts b/packages/ui/src/lib/format.tsindex 7deb910a..b58a5abc 100644--- a/packages/ui/src/lib/format.ts+++ b/packages/ui/src/lib/format.ts@@ -1,5 +1,9 @@-export function formatCount(count: number, noun: string): string {- return `${count} ${count === 1 ? noun : `${noun}s`}`;+export function formatCount(+ count: number,+ noun: string,+ plural = `${noun}s`,+): string {+ return `${count} ${count === 1 ? noun : plural}`;}const WELL_FORMED_CURRENCY_CODE = /^[A-Za-z]{3}$/;