Repository navigation
Implement fields management features - #55
Conversation
- Added new fields module with CRUD operations for custom fields. - Introduced tools for creating, updating, archiving, and listing fields. - Integrated field management into existing entities (companies, contacts, deals) for enhanced data handling. - Updated contracts and services to support bulk operations for fields. - Enhanced error handling and validation for field operations.
There was a problem hiding this comment.
36 issues found and verified against the latest diff
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="apps/api/src/agent/agent-trigger.service.ts">
<violation number="1" location="apps/api/src/agent/agent-trigger.service.ts:79">
P2: The dedup guard for field-backfill tasks matches only on the field key and ignores the record type. Field keys are unique per entity, not globally, so a pending backfill for a COMPANY field like "website" will suppress the backfill for a same-key CONTACT field, which then never gets filled. Consider including the entity in the task's reason (and the dedup prefix) so backfills are distinguished across record types.</violation>
</file>
<file name="apps/app/components/crm/fields/fields-entity.ts">
<violation number="1" location="apps/app/components/crm/fields/fields-entity.ts:21">
P3: kindOf is exported but never called anywhere in the repository, making it dead code. It pairs with entityOf (used in fields-sheet.tsx), so either wire up its eventual consumer or drop it until then to keep the fields module surface free of unused exports.</violation>
</file>
<file name="packages/ui/src/components/data-table.tsx">
<violation number="1" location="packages/ui/src/components/data-table.tsx:475">
P2: Bulk selection is unavailable below the `sm` breakpoint because the header, row, and subrow selection cells all use `hidden sm:table-cell`, leaving mobile users with no way to select records or invoke the new bulk actions. Keep the selection column visible on mobile, or provide an equivalent mobile selection control.</violation>
</file>
<file name="apps/app/components/crm/bulk-actions.tsx">
<violation number="1" location="apps/app/components/crm/bulk-actions.tsx:48">
P3: Partial bulk results display incorrect grammar when exactly one item fails (`1 were left alone`); make the failed-record wording singular/plural-aware.</violation>
</file>
<file name="apps/app/components/crm/fields/fields-list.tsx">
<violation number="1" location="apps/app/components/crm/fields/fields-list.tsx:145">
P2: A failed fields-list request is presented as “No custom fields yet,” which can hide existing fields and offers creation while the data is unavailable. Render the query error with a retry path before treating an empty successful response as an empty configuration.</violation>
<violation number="2" location="apps/app/components/crm/fields/fields-list.tsx:173">
P2: When the last live custom field is archived, `live.length` drops to 0 and the empty state renders, but the `ARCHIVED_ROW` disclosure (the only place Restore buttons live) is nested inside the `live.length > 0` branch. The result: once the final field of an entity is archived, archived fields become unreachable from the list UI — the user can never restore them through this panel (only by creating another live field). Move the archived disclosure outside the `live.length === 0` conditional so Restore remains accessible regardless of how many live fields remain.</violation>
</file>
<file name="apps/agent/agent/tools/list_fields.ts">
<violation number="1" location="apps/agent/agent/tools/list_fields.ts:5">
P2: Adding this tool makes `apps/app`'s “every tool has a line of English” test fail because `list_fields` has no entry in `TOOL_VERBS`. Adding the corresponding human-readable verb in `apps/app/lib/agent-transcript.ts` would keep the transcript contract and test passing.</violation>
</file>
<file name="apps/app/components/crm/fields/record-fields.tsx">
<violation number="1" location="apps/app/components/crm/fields/record-fields.tsx:112">
P2: A SELECT field remains interactive with no pending indicator while its update is in flight, so rapid changes can enqueue multiple mutations and leave an earlier choice persisted after responses complete out of order. Extend `InlineSelectField` with a saving/disabled prop and pass `busy` here before allowing another selection.</violation>
<violation number="2" location="apps/app/components/crm/fields/record-fields.tsx:132">
P2: USER custom fields render as a free-form text input and show opaque workspace user IDs, so users cannot select or identify the member assigned to the field. Add a USER-specific picker backed by workspace user options, or explicitly make USER fields read-only instead of sending them through the generic text fallback.</violation>
</file>
<file name="apps/app/app/(app)/[slug]/contacts/contacts-table.tsx">
<violation number="1" location="apps/app/app/(app)/[slug]/contacts/contacts-table.tsx:163">
P2: A USER custom field configured to appear in the contacts table displays an opaque workspace-user ID instead of the member's name because this integration routes it through a renderer with no USER-specific display handling. Resolving the ID to a workspace user and rendering the member label would make the new column usable.</violation>
</file>
<file name="apps/api/src/deals/deals.service.ts">
<violation number="1" location="apps/api/src/deals/deals.service.ts:274">
P1: A failed deal update can still change its custom fields because this call is not part of the later `deal.update` transaction, and `writeValues` commits values one at a time. Passing a transaction client and performing the field writes together with the deal update would keep the update atomic.</violation>
</file>
<file name="apps/api/src/contacts/contacts.contracts.ts">
<violation number="1" location="apps/api/src/contacts/contacts.contracts.ts:58">
P2: Empty-string company IDs are accepted by this bulk contract but become a foreign-key database error instead of a client validation error. Requiring a non-empty string when the value is not `null` would preserve `null` as the clear value and reject malformed requests early.</violation>
</file>
<file name="packages/db/prisma/schema.prisma">
<violation number="1" location="packages/db/prisma/schema.prisma:540">
P2: Record detail reads will scan `fieldValue` by company/contact/deal ID because each new unique index puts `fieldId` first; adding standalone indexes for the three record-ID columns would keep custom-field reads bounded as data grows.</violation>
<violation number="2" location="packages/db/prisma/schema.prisma:546">
P3: The `@@index([optionId])` index on `FieldValue` is present in the schema and migration but is not in the design document's model definition in `docs/plan/dynamic-fields.md §3`, which says to copy the models verbatim. While a useful index for FK lookups, any intentional addition to the canonical model should be reflected in the design record so the two sources of truth don't drift.</violation>
</file>
<file name="apps/app/components/crm/inline-field.tsx">
<violation number="1" location="apps/app/components/crm/inline-field.tsx:45">
P3: Prefer `Object.keys(fields).includes(key)` over `key in fields` for consistency with `savingField`. The `in` operator also matches inherited Object.prototype properties, so a custom field named e.g. "toString" or "constructor" would be incorrectly reported as saving.</violation>
</file>
<file name="apps/app/lib/trpc/cache.ts">
<violation number="1" location="apps/app/lib/trpc/cache.ts:116">
P2: An entity-scoped field change invalidates every CRM list and search query because `listKeys()` is unconditional here. Selecting only the corresponding entity list when `entity` is provided would avoid unrelated active tables and quick-switcher requests while retaining the all-entity behavior for `cache.fields()`.</violation>
</file>
<file name="packages/db/prisma/migrations/20260806140000_dynamic_fields/migration.sql">
<violation number="1" location="packages/db/prisma/migrations/20260806140000_dynamic_fields/migration.sql:50">
P2: `USER` custom fields can contain nonexistent or deleted user IDs, so records can display stale/unresolvable assignments. A foreign key to `user(id)` with the appropriate delete behavior, or equivalent existence validation, would preserve the meaning of this field type.</violation>
</file>
<file name="packages/db/src/fields.ts">
<violation number="1" location="packages/db/src/fields.ts:64">
P2: Removing a select option makes existing selected values unreadable: serialization drops the archived option, but `readValue` still returns its ID, so record and table renderers cannot find a label. Preserve the selected archived option for reads while rejecting it in `coerceValue`, or resolve its label separately.</violation>
<violation number="2" location="packages/db/src/fields.ts:125">
P2: `coerceValue` falls through to `new Date(raw)` for any non-ISO date string (anything that doesn't match `/^\d{4}-\d{2}-\d{2}$/`). The behavior of `Date.parse` / `new Date(string)` for non-standard formats like `"2027/03/31"`, `"03-31-2027"`, or `"31/03/2027"` is explicitly implementation-dependent per the ECMAScript spec and differs across Node, Bun, and browser runtimes. A value that parses cleanly in development could silently give a wrong date (or `Invalid Date`) in production. The `DATE` field type should only accept ISO 8601 date strings (`YYYY-MM-DD`) and reject anything that doesn't match, rather than hoping the runtime agrees with whatever format arrives.</violation>
<violation number="3" location="packages/db/src/fields.ts:228">
P1: Bulk record updates can leave custom-field changes committed even when a later field or the parent record update fails. Coerce and validate the complete batch before writing, then run field writes in the same transaction as the entity update.</violation>
</file>
<file name="apps/app/components/crm/fields/field-editor.tsx">
<violation number="1" location="apps/app/components/crm/fields/field-editor.tsx:129">
P2: After the "Fill the rest" backfill succeeds, nothing invalidates or refetches the coverage query, so the "Filled on X of Y" counters stay stale for the rest of the open session (they only refresh on remount/window-focus). Backfill is asynchronous on the server (`backfill()` returns `{ queued: true }` and the agent does the work in the background), so the number legitimately lags — but the UI should at least be given a chance to update after the mutation completes rather than never being invalidated. Consider calling `cache.fields()` (or navigating the coverage query key) in the backfill `onSuccess` alongside the toast.</violation>
<violation number="2" location="apps/app/components/crm/fields/field-editor.tsx:155">
P2: Fully covered fields still offer an active `Fill the rest` action, and clicking it queues an agent backfill despite there being no records left to fill. Disable the button when `filled >= total` so the action and queue state match the coverage shown.</violation>
<violation number="3" location="apps/app/components/crm/fields/field-editor.tsx:263">
P2: Screen-reader users cannot identify the agent-fill switch, type picker, or individual option inputs because their visible text is not associated with the controls. Associating each control with its visible label, or supplying an equivalent accessible name, would make the editor operable without sight.</violation>
</file>
<file name="apps/api/src/fields/fields.contracts.ts">
<violation number="1" location="apps/api/src/fields/fields.contracts.ts:64">
P2: Record updates accept objects and arrays and can persist them as misleading scalar text such as `[object Object]`. Restrict field values to the supported scalar union before the definition-specific coercion runs.</violation>
</file>
<file name="docs/plan/dynamic-fields-build.md">
<violation number="1" location="docs/plan/dynamic-fields-build.md:175">
P3: The nuqs snippet contains inline code comments, but AGENTS.md ("Never add code comments. Not to new code, not to code you edit.") and §9 ("Do not add code comments") both forbid them. Since §0 tells the agent to follow AGENTS.md and the snippet is copied into `record-stack.ts`, the plan instructs an action that conflicts with its own rules — drop the trailing comments from the pasted lines.</violation>
<violation number="2" location="docs/plan/dynamic-fields-build.md:176">
P3: The `field` URL param reuses `"new"` as the create sentinel while §4 derives field keys from the label via `fieldKeyFromLabel`. A custom field labeled e.g. "New" would slug to key `new`, so its editor screen could never open — `field=new` always routes to the create form instead. Reserve a non-colliding sentinel (e.g. `field=__new__` or a separate `mode` param) or exclude the reserved key from auto-derivation.</violation>
</file>
<file name="apps/api/src/contacts/contacts.service.ts">
<violation number="1" location="apps/api/src/contacts/contacts.service.ts:379">
P1: Contact updates can leave custom field values behind when the standard contact update fails. Applying values through the root database before the existing transaction makes both multi-field validation and contact changes non-atomic; move `applyValues` inside that transaction and pass it `tx`.</violation>
<violation number="2" location="apps/api/src/contacts/contacts.service.ts:435">
P2: Bulk owner assignment returns a server error for an empty-string owner ID instead of treating it as unassigned or rejecting it cleanly: `requireOwner` skips validation, then this line writes `ownerId: ""` and violates the user foreign key. Normalizing the value to `null` here would match the single-record update behavior.</violation>
</file>
<file name="apps/api/test/fields.spec.ts">
<violation number="1" location="apps/api/test/fields.spec.ts:9">
P3: The suite is order-dependent and shares mutable state (companyId, `queued`, and field values) across tests, so a failure or reorder in an earlier case cascades into confusing downstream failures and individual tests can't run in isolation. Consider isolating state per test (e.g. fresh company per `it`) or making the shared fixture explicit so the dependency is visible; a non-shared approach makes the suite more robust and self-contained for future edits.</violation>
</file>
<file name="packages/ui/src/hooks/use-table-selection.ts">
<violation number="1" location="packages/ui/src/hooks/use-table-selection.ts:22">
P2: The selection state is inconsistent between what is persisted and what is surfaced to consumers: `picked` retains selections across page changes (so `clear()` and `has()` operate on the full set), but `ids`, `count`, `allSelected`, and `someSelected` are all derived by filtering `picked` against the *current* `rowIds`. As a result, after a user selects rows on page 1 and moves to page 2, `count` drops to 0, the selection toolbar disappears, and the bulk-actions `ids` passed to mutations (e.g. `selection.ids` in the company/deal/contact bulk-action components) only cover the currently rendered page — even though the page-1 rows silently remain in `picked`. This makes it impossible to run a bulk operation over a multi-page selection and lets the reported count diverge from what the user actually selected. Consider either exposing the full `picked` set (and scoping only the header's `allSelected` to the current page) or explicitly dropping cross-page persistence so `ids`/`count` always reflect exactly what a bulk action will operate on.</violation>
</file>
<file name="apps/app/app/(app)/[slug]/companies/companies-bulk-actions.tsx">
<violation number="1" location="apps/app/app/(app)/[slug]/companies/companies-bulk-actions.tsx:78">
P3: The two new bulk-action files for companies and contacts are near-identical, and the deals file repeats the same bulk scaffolding (owner mutation, delete dialog, pending flag, onSuccess pointing at the cache). Since the common pieces (BulkActionsMenu, BulkOwnerMenu, BulkDeleteDialog, reportBulk) already live in components/crm/bulk-actions.tsx, the repeated per-entity wiring is now duplicated in three places. Any fix to the delete/enrich/owner flow will have to be applied three times, and the near-copy files drift easily. Consider extracting a small per-kind helper (e.g. a hook that wires bulkDelete + confirming/BulkDeleteDialog + pending given a cache kind) to keep the three menus focused on their one or two distinct actions.</violation>
</file>
<file name="apps/api/src/fields/fields.service.ts">
<violation number="1" location="apps/api/src/fields/fields.service.ts:144">
P2: update can produce an unusable SELECT field. `create` requires at least one option for a SELECT type (`input.options.length === 0` throws), but `update` only validates when `data.options` is explicitly present. If a caller switches an existing TEXT/NUMBER field to `type: "SELECT"` without passing options, the update is accepted and leaves a select field with zero options — which then rejects every value write via coerceValue ("...has no option"). Align the update guard with create so switching to SELECT without any option fails, e.g. treat a missing/empty `options` array when the merged type is SELECT as an error.</violation>
<violation number="2" location="apps/api/src/fields/fields.service.ts:233">
P2: archive/restore/delete convert every Prisma failure into a 404. The `.catch(() => { throw new NotFoundException(...) })` swallows all errors, not just "record not found" (P2025), so a transient DB/connection or constraint error is reported to the client as "That field does not exist." This hides real backend failures and makes them indistinguishable from a genuine missing record. Consider checking for the specific P2025 error code (or Prisma's not-found result) and letting other errors propagate so they reach logs/monitoring.</violation>
</file>
<file name="apps/api/test/bulk.spec.ts">
<violation number="1" location="apps/api/test/bulk.spec.ts:53">
P3: The doomed company is created with domain `doomed-${domain}`, which clean()'s exact-domain filter never matches, so if that test fails before bulkDelete removes it, an orphan company (and its deals/activities) persists and accumulates across runs. Suggest deleting companies by domain endsWith or listing ids from `doomed-${domain}` too.</violation>
</file>
<file name="packages/ui/src/components/sortable-list.tsx">
<violation number="1" location="packages/ui/src/components/sortable-list.tsx:54">
P2: After a drag, the list snaps back to the prop order while the reorder mutation is pending because this component does not retain the new order locally. Keeping local ordered IDs and syncing them when the `ids` prop changes would preserve the dragged order during the request.</violation>
<violation number="2" location="packages/ui/src/components/sortable-list.tsx:102">
P2: The drag handle can submit a containing form instead of only initiating a drag because it is a native button without `type="button"`. Setting the handle type explicitly prevents this reusable component from triggering unrelated form submission.</violation>
</file>
Tip: instead of fixing issues one by one fix them all with cubic
Re-trigger cubic
| .map((definition) => [definition.key, definition]), | ||
| ); | ||
|
|
||
| for (const [key, input] of Object.entries(values)) { |
There was a problem hiding this comment.
P1: Bulk record updates can leave custom-field changes committed even when a later field or the parent record update fails. Coerce and validate the complete batch before writing, then run field writes in the same transaction as the entity update.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/db/src/fields.ts, line 228:
<comment>Bulk record updates can leave custom-field changes committed even when a later field or the parent record update fails. Coerce and validate the complete batch before writing, then run field writes in the same transaction as the entity update.</comment>
<file context>
@@ -0,0 +1,253 @@
+ .map((definition) => [definition.key, definition]),
+ );
+
+ for (const [key, input] of Object.entries(values)) {
+ const definition = byKey.get(key);
+
</file context>
| const suffix = process.env.TEST_RUN_ID ?? "fields-spec"; | ||
| const domain = `fields-${suffix}.test`; | ||
|
|
||
| const queued: { key: string; reason: string }[] = []; |
There was a problem hiding this comment.
P3: The suite is order-dependent and shares mutable state (companyId, queued, and field values) across tests, so a failure or reorder in an earlier case cascades into confusing downstream failures and individual tests can't run in isolation. Consider isolating state per test (e.g. fresh company per it) or making the shared fixture explicit so the dependency is visible; a non-shared approach makes the suite more robust and self-contained for future edits.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/api/test/fields.spec.ts, line 9:
<comment>The suite is order-dependent and shares mutable state (companyId, `queued`, and field values) across tests, so a failure or reorder in an earlier case cascades into confusing downstream failures and individual tests can't run in isolation. Consider isolating state per test (e.g. fresh company per `it`) or making the shared fixture explicit so the dependency is visible; a non-shared approach makes the suite more robust and self-contained for future edits.</comment>
<file context>
@@ -0,0 +1,221 @@
+const suffix = process.env.TEST_RUN_ID ?? "fields-spec";
+const domain = `fields-${suffix}.test`;
+
+const queued: { key: string; reason: string }[] = [];
+
+const agent = {
</file context>
| }), | ||
| ); | ||
|
|
||
| const pending = assignOwner.isPending || enrich.isPending || remove.isPending; |
There was a problem hiding this comment.
P3: The two new bulk-action files for companies and contacts are near-identical, and the deals file repeats the same bulk scaffolding (owner mutation, delete dialog, pending flag, onSuccess pointing at the cache). Since the common pieces (BulkActionsMenu, BulkOwnerMenu, BulkDeleteDialog, reportBulk) already live in components/crm/bulk-actions.tsx, the repeated per-entity wiring is now duplicated in three places. Any fix to the delete/enrich/owner flow will have to be applied three times, and the near-copy files drift easily. Consider extracting a small per-kind helper (e.g. a hook that wires bulkDelete + confirming/BulkDeleteDialog + pending given a cache kind) to keep the three menus focused on their one or two distinct actions.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/app/app/(app)/[slug]/companies/companies-bulk-actions.tsx, line 78:
<comment>The two new bulk-action files for companies and contacts are near-identical, and the deals file repeats the same bulk scaffolding (owner mutation, delete dialog, pending flag, onSuccess pointing at the cache). Since the common pieces (BulkActionsMenu, BulkOwnerMenu, BulkDeleteDialog, reportBulk) already live in components/crm/bulk-actions.tsx, the repeated per-entity wiring is now duplicated in three places. Any fix to the delete/enrich/owner flow will have to be applied three times, and the near-copy files drift easily. Consider extracting a small per-kind helper (e.g. a hook that wires bulkDelete + confirming/BulkDeleteDialog + pending given a cache kind) to keep the three menus focused on their one or two distinct actions.</comment>
<file context>
@@ -0,0 +1,115 @@
+ }),
+ );
+
+ const pending = assignOwner.isPending || enrich.isPending || remove.isPending;
+
+ return (
</file context>
| @@index([fieldId, text]) | ||
| @@index([fieldId, number]) | ||
| @@index([fieldId, date]) | ||
| @@index([optionId]) |
There was a problem hiding this comment.
P3: The @@index([optionId]) index on FieldValue is present in the schema and migration but is not in the design document's model definition in docs/plan/dynamic-fields.md §3, which says to copy the models verbatim. While a useful index for FK lookups, any intentional addition to the canonical model should be reflected in the design record so the two sources of truth don't drift.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/db/prisma/schema.prisma, line 546:
<comment>The `@@index([optionId])` index on `FieldValue` is present in the schema and migration but is not in the design document's model definition in `docs/plan/dynamic-fields.md §3`, which says to copy the models verbatim. While a useful index for FK lookups, any intentional addition to the canonical model should be reflected in the design record so the two sources of truth don't drift.</comment>
<file context>
@@ -452,6 +454,99 @@ model DealContact {
+ @@index([fieldId, text])
+ @@index([fieldId, number])
+ @@index([fieldId, date])
+ @@index([optionId])
+ @@map("fieldValue")
+}
</file context>
- Updated AgentTriggerService to include entity in field backfill method for improved logging and task management. - Refactored CompaniesService, ContactsService, and DealsService to utilize transactions for field updates, ensuring consistency and error handling. - Modified field handling in FieldsService to support new field value types and improved error translation. - Enhanced test cases to cover new field management features and ensure robust functionality. - Updated UI components to reflect changes in field management and improve user experience.
There was a problem hiding this comment.
2 issues found across 30 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="apps/app/components/crm/fields/field-columns.tsx">
<violation number="1" location="apps/app/components/crm/fields/field-columns.tsx:63">
P2: Select custom-field columns now display their stored option IDs instead of the configured labels because the renderer's option lookup was replaced by the user map. Preserve the SELECT option lookup while adding the USER lookup.</violation>
</file>
<file name="apps/api/src/deals/deals.service.ts">
<violation number="1" location="apps/api/src/deals/deals.service.ts:319">
P2: Deal field updates are not fully transaction-consistent because `applyValues(tx, ...)` reads definitions through the base database client rather than the transaction client. Passing `tx` through the definition lookup would prevent concurrent field metadata changes from racing validation and value persistence.</violation>
</file>
Tip: instead of fixing issues one by one fix them all with cubic
Re-trigger cubic
| hideBelow: "lg" as const, | ||
| cell: (row: Row) => ( | ||
| <span className="truncate"> | ||
| {render(field.type, row.fields[field.key] ?? null, byId)} |
There was a problem hiding this comment.
P2: Select custom-field columns now display their stored option IDs instead of the configured labels because the renderer's option lookup was replaced by the user map. Preserve the SELECT option lookup while adding the USER lookup.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/app/components/crm/fields/field-columns.tsx, line 63:
<comment>Select custom-field columns now display their stored option IDs instead of the configured labels because the renderer's option lookup was replaced by the user map. Preserve the SELECT option lookup while adding the USER lookup.</comment>
<file context>
@@ -53,9 +60,9 @@ export function useFieldColumns<Row extends WithFields>(
cell: (row: Row) => (
<span className="truncate">
- {render(field.type, row.fields[field.key] ?? null, field.options)}
+ {render(field.type, row.fields[field.key] ?? null, byId)}
</span>
),
</file context>
| where: { id }, | ||
| data, | ||
| select: { id: true, name: true }, | ||
| return await this.db.$transaction(async (tx) => { |
There was a problem hiding this comment.
P2: Deal field updates are not fully transaction-consistent because applyValues(tx, ...) reads definitions through the base database client rather than the transaction client. Passing tx through the definition lookup would prevent concurrent field metadata changes from racing validation and value persistence.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/api/src/deals/deals.service.ts, line 319:
<comment>Deal field updates are not fully transaction-consistent because `applyValues(tx, ...)` reads definitions through the base database client rather than the transaction client. Passing `tx` through the definition lookup would prevent concurrent field metadata changes from racing validation and value persistence.</comment>
<file context>
@@ -320,10 +316,16 @@ export class DealsService {
- where: { id },
- data,
- select: { id: true, name: true },
+ return await this.db.$transaction(async (tx) => {
+ if (input.fields) {
+ await this.fields.applyValues(tx, "DEAL", id, input.fields);
</file context>
# Conflicts: # apps/api/src/agent/agent-trigger.service.ts # apps/api/src/companies/companies.service.ts # apps/api/src/contacts/contacts.service.ts # apps/api/src/deals/deals.contracts.ts # apps/api/src/deals/deals.router.ts # apps/api/src/deals/deals.service.ts # apps/api/src/fields/fields.contracts.ts # apps/api/src/fields/fields.service.ts # apps/api/src/generated/server.ts # apps/api/test/bulk.spec.ts # apps/api/test/fields.spec.ts # apps/app/components/crm/bulk-actions.tsx # apps/app/components/crm/fields/field-columns.tsx # apps/app/components/crm/fields/field-editor.tsx # apps/app/components/crm/fields/fields-copy.ts # apps/app/components/crm/fields/fields-list.tsx # apps/app/components/crm/fields/record-fields.tsx # apps/app/components/crm/inline-field.tsx # apps/app/components/crm/record-sheet/company-sheet.tsx # apps/app/components/crm/record-sheet/contact-sheet.tsx # apps/app/components/crm/record-sheet/deal-sheet.tsx # apps/app/lib/trpc/cache.ts # docs/plan/dynamic-fields-build.md # docs/plan/dynamic-fields.md # packages/db/prisma/schema.prisma # packages/db/src/fields-shape.ts # packages/db/src/fields.ts # packages/db/test/fields.spec.ts # packages/ui/src/components/data-table.tsx # packages/ui/src/components/sortable-list.tsx # packages/ui/src/hooks/use-table-selection.ts
* Implement currency conversion features and enhance deal handling - Introduced a new CurrencyModule to manage currency conversion and rates. - Added ConversionService for handling currency conversions and fetching rates. - Updated DealsService to support base amounts and currency conversion logic. - Enhanced Deal and Dashboard functionalities to include reporting currency and unconverted deals. - Implemented new currency-related contracts and routes for setting reporting currency and manual rates. - Added integration tests to ensure correct handling of currency conversions and deal totals. * Refactor currency rates service to use open.er-api.com - Updated the currency rates service to fetch exchange rates from open.er-api.com, replacing the previous provider frankfurter.dev. - Enhanced error handling to check for unsupported base currencies in the response. - Implemented retry logic for fetching rates with a maximum of two attempts and a reduced timeout. - Cleaned up stale exchange rates for unsupported currencies during the refresh process. - Updated documentation to reflect the new exchange rate provider and its implications. * Enhance currency handling and conversion logic - Introduced baseCurrency to the Deal model to track the currency of baseAmount. - Updated ConversionService to streamline currency conversion processes and improve deal field handling. - Enhanced CurrencyService to enforce permissions for managing currency settings based on user roles. - Refactored DealsService to incorporate base currency logic in deal aggregations and reporting. - Improved DashboardService to accurately reflect open deal values based on the current reporting currency. - Updated integration tests to validate new currency handling features and ensure correct behavior across services. * Enhance currency conversion logic and improve deal handling - Updated `pendingWhere` method in `ConversionService` to explicitly match null `baseCurrency`, ensuring no deals are excluded from totals. - Added integration test to verify that deals with missing currency are correctly handled and updated. - Modified seeding logic to ensure `baseCurrency` is set alongside `baseAmount` for newly created deals, preventing issues with unconverted figures. - Updated documentation to clarify changes in currency handling and the implications for deal visibility. * Refine currency conversion logic and enhance deal handling - Updated `ConversionService` to conditionally clear rates only when `onlyMissing` is false, improving efficiency in handling missing currencies. - Enhanced integration tests to verify correct behavior when dealing with unconverted figures and missing currency rates. - Introduced a new utility function in the deal sheet component to manage currency options, ensuring proper display of unsupported currencies. * Revise agent and API documentation for clarity and structure - Updated AGENTS.md to emphasize the importance of reviewing relevant documentation before starting work, including a new index table for quick reference. - Refined API rules in api.md to clarify logging practices and the separation of intelligence from the API. - Consolidated environment setup instructions into a new setup.md file for better organization and ease of access. - Enhanced currency handling in DashboardService and related tests to ensure accurate reporting and conversion logic. - Improved integration tests to validate new currency handling features and ensure correct behavior across services. * Enhance documentation and introduce new currency handling guidelines - Updated AGENTS.md to include new references for the Agent panel and local setup instructions. - Added a new docs/agent-panel.md file detailing the Agent panel's functionality and usage. - Introduced docs/currency.md to clarify currency handling rules and reporting practices. - Revised environment setup instructions in docs/environment.md for better clarity and organization. * Add anonymous usage telemetry documentation and enhance currency handling in DealSheet * Implement anonymous usage telemetry and enhance related documentation - Added telemetry functionality to track anonymous usage data, including installation metrics and tool usage. - Introduced new environment variables for telemetry configuration in `.env.example`. - Updated `AGENTS.md` to reference the new telemetry documentation. - Created a `TelemetryModule` with services and controllers for managing telemetry data. - Added a settings page for telemetry configuration in the application. - Enhanced error handling and logging for telemetry events across various services. - Removed outdated ADR on telemetry usage from the repository. * Remove telemetry-related components and references from the application - Deleted the TelemetryRouter and its associated service, removing the telemetry status query. - Updated the settings sidebar to eliminate the Telemetry option. - Removed the TelemetrySettingsPage and its related components, including the TelemetryStatus display. - Cleaned up unused imports and references to telemetry throughout the codebase. * Enhance telemetry functionality and improve budget management - Added an 'exhausted' state to the focus management to track when the research budget is depleted. - Updated the spend function to prevent multiple budget exhaustion events from being recorded. - Refactored the rollup service to handle telemetry rollup claims and restore counters more effectively. - Improved error handling in telemetry events to ensure proper reporting and recovery from failures. - Enhanced documentation to clarify the behavior of telemetry when disabled and the implications for data integrity. * Add telemetry support and enhance landing page analytics - Introduced `@crm/telemetry` package to manage telemetry configurations and constants. - Integrated `posthog-js` for analytics on the landing page, ensuring it only runs on allowed domains. - Updated the `LandingAnalytics` component to initialize analytics tracking based on hostname. - Enhanced the `audit` hook to exclude specific event types from archiving. - Improved agent session handling by implementing offline thread management. - Added utility functions for analytics host validation and created tests for the new functionality. - Updated documentation to reflect changes in telemetry usage and landing page analytics. * Update agent panel to use SETTLED_TTL_MS for archive stale time and enhance documentation - Changed the `staleTime` for the archive query in the agent panel from `Infinity` to `SETTLED_TTL_MS` to ensure proper session management. - Updated documentation to clarify the behavior of the archive in relation to session state and stale time handling. * Enhance landing page analytics with CTA event tracking - Introduced `captureLanding` function to track user interactions with the setup prompt and GitHub star buttons. - Updated `SetupPromptButton` and `GitHubStarButton` components to accept a `location` prop for distinguishing between 'hero' and 'closing' CTAs. - Modified `LandingAnalytics` to include new event types for clipboard actions and button clicks. - Enhanced documentation to reflect the new telemetry events and their usage. * Update README with new images and remove outdated ones - Replaced outdated images with new visuals for the landing page, showcasing agents and capabilities. - Removed references to deleted images related to deals, contacts, and companies to streamline documentation. * Refactor README to improve layout of screenshots - Converted individual screenshot sections into a table format for better visual organization. - Updated captions for clarity and conciseness, enhancing the overall presentation of the landing page visuals. * Update README and images for landing page - Removed outdated captions from the README for agents and capabilities images to streamline content. - Updated binary images for agents, capabilities, and hero sections to enhance visual quality on the landing page. * Update README and replace landing hero image - Updated the README to reflect the new image caption for the companies list. - Replaced the outdated landing hero image with a new product shot to enhance visual appeal. - Removed the old landing hero image from the repository. * Update landing page images for agents and capabilities - Replaced existing binary images for agents and capabilities on the landing page to improve visual quality and consistency. - Ensured that the new images align with the recent updates to the README and overall landing page design. * Update landing page images for agents and capabilities to enhance visual quality * Refactor AddButton component in multiple sheets to use ComponentProps for better type safety - Updated the AddButton function in create-company-sheet, create-contact-sheet, create-deal-sheet, and add-sso-provider-sheet to accept props of type ComponentProps from the Button component. - This change enhances type safety and allows for more flexible button properties across different sheets. * Refactor TelemetryService to integrate RollupService for telemetry rollups - Replaced FunnelService with RollupService in TelemetryService to handle telemetry rollups. - Implemented a timer to run rollups hourly, enhancing telemetry data collection. - Updated documentation to reflect changes in telemetry rollup processes and clarify the in-process execution without cron dependencies. * Report installs without a cron, and stop double counting them The install count was reading 1 while 20 databases had migrated. Every "Active installs" tile is built on install_daily, which only ever fired from POST /internal/telemetry/rollup — a route that refuses to run without CRON_SECRET. An install that never configures a cron reported nothing at all, however much it was used. TelemetryService now rolls up in-process, on boot and hourly. The existing row lock on install makes all but the first of those a no-op, and it short-circuits before the aggregation runs, so it is still one set of grouped queries per install per day. The route stays, still behind CRON_SECRET, for a platform cron that would rather drive it; nothing depends on it now. Two ways the same event could arrive twice, both of which the hourly timer would have made more frequent: A rollup wrongly read as failed hands the day back and is re-sent. posthog-node does not reject on a failed send, so the client inferred failure from a module-global error counter that any other capture could move. It now enqueues and awaits flush(), which does throw, and treats either signal as a failure — erring toward a re-send, which is free, over consuming a day whose event never left. A milestone sent before it was recorded, so both the boot sweep and the rollup sweep could send the same step. One install sent first_fact_applied six times. The insert is now the claim: of two sweeps exactly one is told it landed the row, and only that one sends. A failed send deletes the row so the step is retried. Both events also carry a deterministic uuid derived from the install and the day (or the step), so a duplicate that does get out is ingested once. Installs and active installs were always safe — PostHog's unique math is per install per day — but the summed agent-usage properties were not. * Derive the dedupe id with SHA-256 in a v8 uuid CodeQL flags a weak algorithm reached by the install identity, and it is right that the two do not belong in one expression. SHA-1 was there only because RFC 4122 defines v5 that way; nothing depends on being a v5, so this is a SHA-256 digest in a v8 uuid, the slot RFC 9562 leaves for a derivation of one's own. * CMP-1 chore: enrich agentic experience * ci: open pull requests, gate titles and promote releases automatically (trycompai#53) * Lewis/contact and currencies (trycompai#56) * Implement fields management features (trycompai#55) * Lewis/dynamic field fix (trycompai#70) * Refactor query prefetching in Companies, Contacts, and Deals pages to… (trycompai#71) * chore: release main (trycompai#72) * feat(api): add microsoft sign-in and outlook mailbox sync (trycompai#73) Co-authored-by: Lewis Carhart <[email protected]> * chore: release release * ci: run release-please on main and document merge order (trycompai#76) Co-authored-by: Lewis Carhart <[email protected]> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * chore: release main (trycompai#78) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * feat(db): CMP-1 persist durable custom agents (trycompai#67) * feat(agent): CMP-1 add sandboxed builder and runner runtimes (trycompai#60) * refactor(app): CMP-59 harden CRM UI foundations (trycompai#61) * feat(app): CMP-46 add the private agent builder workspace (trycompai#62) * feat(app): CMP-12 review agent drafts before deployment (trycompai#63) * fix(app): CMP-47 consolidate agent builder presentation (trycompai#64) * feat(app): CMP-47 add inline composer context * fix(app): move chat beneath overview in icon rail (trycompai#83) Co-authored-by: grim <[email protected]> * fix(ci): tag releases automatically and keep previews off the production schema (trycompai#82) Co-authored-by: Lewis Carhart <[email protected]> * chore(main): release 1.4.0 (trycompai#86) * feat(agent): bound agent builder retries and improve chat scrolling (trycompai#89) * fix(app): render agent transcript chronologically with anchored tool results (trycompai#92) Co-authored-by: grim <[email protected]> Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> * fix(agent): declare granted write actions in draft access summary (trycompai#93) Co-authored-by: grim <[email protected]> * chore(main): release 1.5.0 (trycompai#91) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * fix(api): warn when the deployed schema does not match schema.prisma (trycompai#88) Co-authored-by: Lewis Carhart <[email protected]> * CMP-62 chore: add gh-stack skill (trycompai#96) * chore(main): release 1.5.1 (trycompai#97) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * fix(ci): make the release guard reject only genuinely untagged pull requests (trycompai#105) Co-authored-by: Lewis Carhart <[email protected]> * fix(ci): stop the auto-titler downgrading a release The titler regenerated the title on every push once it had written one, so a pull request's subject was whatever its *last* commits looked like. trycompai#105 carried the whole website-tracking feature and was retitled `fix(ci)` by its final push, squashed onto main under that subject, and released as a patch whose notes mention none of it. A generated title is now left alone unless it stops being a conventional commit or stops covering the branch, and no title — generated or typed — may release less than the commits behind it: `floor_of` takes the strongest bump on the branch and `generate` raises its proposal to meet it. A branch holding a `feat` cannot ship as a `fix`, and one holding a breaking change cannot ship without the `!`. Over-releasing is the safe direction; losing a feature out of the changelog is not. * feat(tracking): add website tracking with form capture and attribution A first-party script on the marketing site, a collector in the API, and one rule: a form submission becomes a contact. Page views, click labels and first/last-touch attribution hang off that, with a 90-day retention sweep, an hourly contact cap and a per-minute event budget. The work landed in 815a832. The auto-titler had retitled its pull request `fix(ci)` on the last push, so it squashed onto main under that subject and released as a patch whose notes describe only the guard fix. This commit carries no code — it exists so the changelog and the version say what actually shipped. See docs/tracking.md. * chore(main): release 1.6.0 (trycompai#106) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * fix(ci): make a release one pull request instead of two Shipping was a release pull request into `main` and a promotion pull request into `release`, open at the same time, with a warning on the promotion telling you to merge the other one first. Merge them the wrong way round and you shipped untagged code and left the version behind for the next promotion. Nobody should have to hold that rule in their head to deploy. The tag and the code have to travel together, so the release workflow now does it in one step: when release-please cuts the tag it merges that exact commit into `release` through the merges API. One pull request, no order to remember, and the tag is by construction an ancestor of what shipped. `promote.yml` is gone. A conflict is the one case a human still has to see, and it can only mean somebody committed to `release` directly, so it fails the run and says so rather than quietly leaving production behind. Non-releasable commits now wait for the next release rather than riding a promotion, which is the trade: `release` moves when a tag is cut and at no other time. * fix(ci): fall back to the pushed commit when release-please reports no sha * chore(main): release 1.6.1 (trycompai#108) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * feat(db): add peek script for inspecting database contents (trycompai#110) Co-authored-by: Lewis Carhart <[email protected]> * chore(main): release 1.7.0 (trycompai#111) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * feat(agent): apply sourced facts to empty fields automatically (trycompai#112) Co-authored-by: Lewis Carhart <[email protected]> * chore(main): release 1.8.0 (trycompai#113) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * fix(ci): ship releases by opening a pull request into release (trycompai#114) Co-authored-by: Lewis Carhart <[email protected]> * chore(main): release 1.8.1 (trycompai#115) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * fix(agent): fill blank fields on the dispatch tick instead of sign-in (trycompai#117) Co-authored-by: Lewis Carhart <[email protected]> * chore(main): release 1.8.2 (trycompai#118) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * feat(agent): stop suggesting a URL that already matches the field (trycompai#120) Co-authored-by: Lewis Carhart <[email protected]> * chore(main): release 1.9.0 (trycompai#121) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * feat(tracking): support installing the tracking tag via Google Tag Manager (trycompai#124) Co-authored-by: Lewis Carhart <[email protected]> * chore(main): release 1.10.0 (trycompai#126) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * feat(app): copy the tracking snippet for the selected install method (trycompai#128) Co-authored-by: Lewis Carhart <[email protected]> * chore(main): release 1.11.0 (trycompai#129) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * feat: edit a deployed agent, and show what Slack actually granted (CMP-77) (trycompai#109) * chore(main): release 1.12.0 (trycompai#132) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * feat(app): search company dropdowns instead of scrolling them (trycompai#125) * fix(app): show select field values in record tables (trycompai#133) * fix(agent): let the assistant chat read the deal list it is told to use (CMP-77) (trycompai#139) * chore(main): release 1.13.0 (trycompai#136) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * chore: add anti-slop lint rules, dead-code checks and stricter Biome constraints (CMP-80) (trycompai#145) * refactor: clear anti-slop type assertions and conditional object spreads (CMP-81) (trycompai#146) * docs: propose an i18n layer (trycompai#143) * refactor: parse every remaining I/O boundary into a domain type (CMP-82) (trycompai#151) * fix: unblock the test suite and actually install the git hooks (CMP-83) (trycompai#152) * ci: run anti-slop lint in CI and pre-push (CMP-84) (trycompai#153) Co-authored-by: grim <[email protected]> * feat: enrichment queue widget (CMP-92) (trycompai#159) * feat(agent): read people from Context.dev instead of RapidAPI (CMP-86) (trycompai#158) Co-authored-by: grim <[email protected]> * feat: page the enrichment queue (CMP-92) (trycompai#160) Co-authored-by: grim <[email protected]> * chore(main): release 1.14.0 (trycompai#147) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * feat(agent): scope field backfill tasks to records missing values (trycompai#163) Co-authored-by: Lewis Carhart <[email protected]> * chore(main): release 1.15.0 (trycompai#164) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * fix(api): serve openapi.json and bundle swagger deps in function build (trycompai#166) Co-authored-by: Lewis Carhart <[email protected]> * chore(main): release 1.15.1 (trycompai#167) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * Lewis/openapi json (trycompai#169) * docs(api): explain runtime openapi document and vendoring rules (trycompai#170) Co-authored-by: Lewis Carhart <[email protected]> * chore(main): release 1.15.2 (trycompai#171) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * fix(app): prevent url param collision between fields sheet and table filter (trycompai#175) Co-authored-by: Lewis Carhart <[email protected]> * fix: stop a finished enrichment reading as failed (trycompai#173) * chore(main): release 1.15.3 (trycompai#176) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * ci: add Vercel deploy workflow Deploys to Vercel on push to main/release branches. Also supports manual trigger via workflow_dispatch with environment selection (preview/production). Uses secrets: VERCEL_API_KEY, VERCEL_ORG_ID, VERCEL_PROJECT_ID --------- Co-authored-by: Lewis Carhart <[email protected]> Co-authored-by: grim <[email protected]> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> Co-authored-by: Guzman Pintos <[email protected]> Co-authored-by: twinprime19 <[email protected]> Co-authored-by: Kiro Agent <[email protected]>
Summary by cubic
Adds dynamic custom fields across companies, contacts, and deals with stricter validation, transactional record updates, and an improved UI. Select backfills are now queued per entity, tables show select labels, and inline editing supports the
USERfield.New Features
recordFieldValuesinput; ISO 8601 date parsing;USERfield validates workspace members; tables return select labels; archive/restore/delete translate not-found errors; record updates writefieldsinside a transaction; backfill usesAgentTriggerService.fieldBackfill(entity, key, reason).USERselect with loading; table columns renderUSERvia Owner cells; smoother drag reordering and selection persistence.fields(entity)invalidates record lists and detail queries; addedfieldCoveragecache.newkey added; rationale for new indexes anduserIdFK; expanded tests for dates, user validation, retired select options, and transactional rollbacks.Migration
fieldValuerecord indexes and auserIdFK; includes cleanup of invaliduserIdvalues.@dnd-kit/core,@dnd-kit/sortable,@dnd-kit/modifiers,@dnd-kit/utilitiesand rebuild.Written for commit 68c5711. Summary will update on new commits.