Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
Lewis/dynamic field fix (#70)
Lewis Carharte025651fbe03
diff --git a/apps/api/src/fields/fields.service.ts b/apps/api/src/fields/fields.service.tsindex 856f81ac..ceb09a81 100644--- a/apps/api/src/fields/fields.service.ts+++ b/apps/api/src/fields/fields.service.ts@@ -332,8 +332,9 @@ export class FieldsService {async definitionsFor(entity: FieldEntity,+ client: Prisma.TransactionClient = this.db,): Promise<FieldDefinitionWithOptions[]> {- return this.db.fieldDefinition.findMany({+ return client.fieldDefinition.findMany({where: { entity, archivedAt: null },include: WITH_OPTIONS,orderBy: { position: "asc" },@@ -400,14 +401,14 @@ export class FieldsService {}async applyValues(- tx: Db | Prisma.TransactionClient,+ tx: 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);+ const definitions = await this.definitionsFor(entity, tx);try {await writeValues(tx, entity, recordId, definitions, values);diff --git a/apps/app/components/crm/fields/field-columns.tsx b/apps/app/components/crm/fields/field-columns.tsxindex f46b2797..00ef3e76 100644--- a/apps/app/components/crm/fields/field-columns.tsx+++ b/apps/app/components/crm/fields/field-columns.tsx@@ -14,12 +14,18 @@ type WithFields = { fields: Record<string, string | number | boolean | null> };function render(type: string,value: string | number | boolean | null,+ options: { id: string; label: string }[],users: Map<string, Owner>,) {if (value === null || value === "") return <EmptyCellValue />;if (type === "CHECKBOX") return value === true ? "Yes" : "No";if (type === "DATE") return formatDay(String(value));+ if (type === "SELECT") {+ return (+ options.find((option) => option.id === value)?.label ?? <EmptyCellValue />+ );+ }if (type === "USER") {const user = users.get(String(value));return user ? <OwnerCell owner={user} /> : <EmptyCellValue />;@@ -60,7 +66,12 @@ export function useFieldColumns<Row extends WithFields>(hideBelow: "lg" as const,cell: (row: Row) => (<span className="truncate">- {render(field.type, row.fields[field.key] ?? null, byId)}+ {render(+ field.type,+ row.fields[field.key] ?? null,+ field.options,+ byId,+ )}</span>),}));diff --git a/apps/app/components/crm/fields/fields-list.tsx b/apps/app/components/crm/fields/fields-list.tsxindex b4007e5c..b95b18c0 100644--- a/apps/app/components/crm/fields/fields-list.tsx+++ b/apps/app/components/crm/fields/fields-list.tsx@@ -30,7 +30,7 @@ import {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 { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { toast } from "sonner";import { useCrmCache } from "@/lib/trpc/cache";import { useTRPC } from "@/lib/trpc/client";@@ -79,6 +79,20 @@ function summaryOf(field: Field): string {return parts.join(" · ");}+function reordered(fields: Field[], ids: string[]): Field[] {+ const live = fields.filter((field) => !field.archived);+ const byId = new Map(live.map((field) => [field.id, field]));+ const queue = ids+ .map((id) => byId.get(id))+ .filter((field): field is Field => field !== undefined);++ if (queue.length !== live.length) return fields;++ return fields.map((field) =>+ field.archived ? field : (queue.shift() ?? field),+ );+}+function DisclosureRow({title,note,@@ -121,6 +135,9 @@ export function FieldsList({}) {const trpc = useTRPC();const cache = useCrmCache();+ const queryClient = useQueryClient();++ const listKey = trpc.fields.list.queryKey({ entity, includeArchived: true });const query = useQuery(trpc.fields.list.queryOptions({ entity, includeArchived: true }),@@ -128,11 +145,21 @@ export function FieldsList({const reorder = useMutation(trpc.fields.reorder.mutationOptions({- onSuccess: () => cache.fields(kindOf(entity)),- onError: (error) => {+ onMutate: async ({ ids }) => {+ await queryClient.cancelQueries({ queryKey: listKey });+ const previous = queryClient.getQueryData(listKey);+ if (previous) {+ queryClient.setQueryData(listKey, reordered(previous, ids));+ }+ return { previous };+ },+ onError: (error, _input, context) => {+ if (context?.previous) {+ queryClient.setQueryData(listKey, context.previous);+ }toast.error(error.message);- return cache.fields(kindOf(entity));},+ onSettled: () => cache.fields(kindOf(entity)),}),);diff --git a/packages/ui/src/components/sortable-list.tsx b/packages/ui/src/components/sortable-list.tsxindex a691c2dd..bb215f10 100644--- a/packages/ui/src/components/sortable-list.tsx+++ b/packages/ui/src/components/sortable-list.tsx@@ -22,28 +22,11 @@ import {verticalListSortingStrategy,} from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";-import { Children, type ReactNode, useState } from "react";+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";-function inOrder(- children: ReactNode,- ids: string[],- order: string[],-): ReactNode {- const slots = Children.toArray(children);- if (slots.length !== ids.length) return children;-- const arranged: ReactNode[] = [];- for (const id of order) {- const at = ids.indexOf(id);- if (at === -1) return children;- arranged.push(slots[at]);- }- return arranged;-}-export function SortableList({ids,onReorder,@@ -53,17 +36,6 @@ export function SortableList({onReorder: (ids: string[]) => void;children: ReactNode;}) {- const propKey = ids.join(" ");- const [syncedKey, setSyncedKey] = useState(propKey);- const [dragged, setDragged] = useState(ids);-- let order = dragged;- if (syncedKey !== propKey) {- setSyncedKey(propKey);- setDragged(ids);- order = ids;- }-const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),useSensor(KeyboardSensor, {@@ -75,13 +47,11 @@ export function SortableList({const { active, over } = event;if (!over || active.id === over.id) return;- const from = order.indexOf(String(active.id));- const to = order.indexOf(String(over.id));+ const from = ids.indexOf(String(active.id));+ const to = ids.indexOf(String(over.id));if (from === -1 || to === -1) return;- const next = arrayMove(order, from, to);- setDragged(next);- onReorder(next);+ onReorder(arrayMove(ids, from, to));};return (@@ -91,8 +61,8 @@ export function SortableList({modifiers={[restrictToVerticalAxis, restrictToParentElement]}onDragEnd={onDragEnd}>- <SortableContext items={order} strategy={verticalListSortingStrategy}>- {inOrder(children, ids, order)}+ <SortableContext items={ids} strategy={verticalListSortingStrategy}>+ {children}</SortableContext></DndContext>);diff --git a/packages/ui/src/hooks/use-table-selection.ts b/packages/ui/src/hooks/use-table-selection.tsindex bd8dc7f2..9cd290a6 100644--- a/packages/ui/src/hooks/use-table-selection.ts+++ b/packages/ui/src/hooks/use-table-selection.ts@@ -17,7 +17,7 @@ export type TableSelection = {export function useTableSelection(rowIds: string[]): TableSelection {const [picked, setPicked] = useState<ReadonlySet<string>>(EMPTY);- const pageKey = rowIds.join(" ");+ const pageKey = [...rowIds].sort().join(" ");const [syncedKey, setSyncedKey] = useState(pageKey);if (syncedKey !== pageKey) {