Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(crm): restore saved-views menu, add default views, fix option value size limit (#4885)

Evan Hutnik9376299de308
diff --git a/apps/web/src/features/companies/crm/saved-views.ts b/apps/web/src/features/companies/crm/saved-views.ts
index cf141742d8..82637843ed 100644
--- a/apps/web/src/features/companies/crm/saved-views.ts
+++ b/apps/web/src/features/companies/crm/saved-views.ts
@@ -38,6 +38,8 @@ export type CrmViewConfig = {
/** Owner ids selected in the Owner filter. */
ownerFilter?: string[];
activeTab?: string;
+ /** Personal views only: applied by default when opening the Customers view. */
+ isDefault?: boolean;
};
export function isCrmViewConfig(value: unknown): value is CrmViewConfig {
@@ -98,6 +100,8 @@ export function usePersonalCrmViews() {
)
);
+ const defaultView = () => views().find((view) => view.config.isDefault);
+
const invalidate = () =>
queryClient.invalidateQueries({ queryKey: CRM_SAVED_VIEWS_QUERY_KEY });
@@ -146,12 +150,46 @@ export function usePersonalCrmViews() {
},
}));
+ // The backend PATCH shallow-merges into the stored config, so sending just
+ // `{isDefault}` flips the flag without touching the rest of the snapshot.
+ const setDefaultMutation = useMutation(() => ({
+ mutationFn: async (vars: { id: string | undefined }) => {
+ const { id } = vars;
+ const previous = defaultView();
+ if (previous && previous.id !== id) {
+ await throwOnErr(
+ async () =>
+ await storageServiceClient.views.patchView({
+ saved_view_id: previous.id,
+ config: { isDefault: false },
+ })
+ );
+ }
+ if (id !== undefined) {
+ await throwOnErr(
+ async () =>
+ await storageServiceClient.views.patchView({
+ saved_view_id: id,
+ config: { isDefault: true },
+ })
+ );
+ }
+ },
+ onSuccess: () => invalidate(),
+ onError: (error: Error) => {
+ console.error('Failed to set default view', error);
+ toast.failure('Failed to set default view');
+ },
+ }));
+
return {
views,
+ defaultView,
isLoading: () => viewsQuery.isLoading,
create: createMutation,
rename: renameMutation,
remove: deleteMutation,
+ setDefault: setDefaultMutation,
};
}
@@ -164,6 +202,19 @@ export function useTeamCrmViews() {
(config().teamViews ?? []).filter((view) => isCrmViewConfig(view.config))
);
+ const defaultViewId = () => config().defaultTeamViewId;
+
+ const defaultView = () => views().find((view) => view.id === defaultViewId());
+
+ const setDefault = (id: string | undefined) => {
+ update.mutate((current) => ({ ...current, defaultTeamViewId: id }), {
+ onError: (error: Error) => {
+ console.error('Failed to set default team view', error);
+ toast.failure('Failed to set default team view');
+ },
+ });
+ };
+
const add = (name: string, viewConfig: CrmViewConfig) => {
const view: TeamCrmSavedView = {
id: crypto.randomUUID(),
@@ -191,6 +242,11 @@ export function useTeamCrmViews() {
(current) => ({
...current,
teamViews: (current.teamViews ?? []).filter((view) => view.id !== id),
+ // A deleted view can't stay the team default.
+ defaultTeamViewId:
+ current.defaultTeamViewId === id
+ ? undefined
+ : current.defaultTeamViewId,
}),
{
onError: (error: Error) => {
@@ -201,5 +257,14 @@ export function useTeamCrmViews() {
);
};
- return { views, add, remove, isLoading, isSaving: () => update.isPending };
+ return {
+ views,
+ defaultViewId,
+ defaultView,
+ add,
+ remove,
+ setDefault,
+ isLoading,
+ isSaving: () => update.isPending,
+ };
}
diff --git a/apps/web/src/features/companies/crm/team-crm-config.ts b/apps/web/src/features/companies/crm/team-crm-config.ts
index 74f66d56ea..8bfc0cf755 100644
--- a/apps/web/src/features/companies/crm/team-crm-config.ts
+++ b/apps/web/src/features/companies/crm/team-crm-config.ts
@@ -66,6 +66,8 @@ export type TeamCrmConfig = {
*/
closedStageIds?: string[];
teamViews?: TeamCrmSavedView[];
+ /** Team view applied by default when a member opens the Customers view. */
+ defaultTeamViewId?: string;
};
export const DEFAULT_CRM_PERMISSIONS: CrmPermissions = {
diff --git a/apps/web/src/features/next-soup/soup-view/soup-view.tsx b/apps/web/src/features/next-soup/soup-view/soup-view.tsx
index 08cc1f8ac7..c8315f42b7 100644
--- a/apps/web/src/features/next-soup/soup-view/soup-view.tsx
+++ b/apps/web/src/features/next-soup/soup-view/soup-view.tsx
@@ -44,7 +44,11 @@ import {
import { CompanyKanban } from '@app/features/next-soup/soup-view/views/companies/CompanyKanban';
import { CompanyListEntity } from '@app/features/next-soup/soup-view/views/companies/CompanyListEntity';
import { ResponsiveCompanyListHeader } from '@app/features/next-soup/soup-view/views/companies/CompanyListHeader';
-import { CompanyDisplayMenu } from '@app/features/next-soup/soup-view/views/companies/CompanyViewsMenu';
+import {
+ CompanyDisplayMenu,
+ CompanyViewsMenu,
+} from '@app/features/next-soup/soup-view/views/companies/CompanyViewsMenu';
+import { CrmDefaultViewLoader } from '@app/features/next-soup/soup-view/views/companies/CrmDefaultView';
import { DateGroupHeader } from '@app/features/next-soup/soup-view/views/inbox/date-group-header';
import { InboxListEntity } from '@app/features/next-soup/soup-view/views/inbox/InboxListEntity';
import { TaskListEntity } from '@app/features/next-soup/soup-view/views/tasks/TaskListEntity';
@@ -400,6 +404,15 @@ export const SoupView = (props: SoupViewProps) => {
const initialCrmView =
contentId === 'companies' ? props.initialCrmView : undefined;
+ // A default saved view only applies to a fresh Customers entry: restored
+ // (back/forward) entries keep what the user was looking at, and share
+ // links carry their own state.
+ const applyDefaultCrmView =
+ contentId === 'companies' &&
+ initialCrmView === undefined &&
+ persistedFilters === undefined &&
+ persistedPredicates === undefined;
+
// We handle the restore of the persistence here instead of within the context
// because the context is no longer recreated for each soup view because we
// moved it within the `SplitPanel`.
@@ -690,6 +703,7 @@ export const SoupView = (props: SoupViewProps) => {
!narrowSearchExpanded() && isComponentListView('companies')
}
>
+ <CompanyViewsMenu />
<CompanyDisplayMenu />
</Show>
<Show
@@ -764,6 +778,9 @@ export const SoupView = (props: SoupViewProps) => {
</Show>
</div>
<SoupFiltersBar variant={props.filterBarVariant} />
+ <Show when={applyDefaultCrmView}>
+ <CrmDefaultViewLoader />
+ </Show>
<div class="relative grow min-h-1 flex max-sm:flex-col flex-row size-full">
<Suspense>
<Show when={!isBoardMode()} fallback={<CompanyKanban />}>
diff --git a/apps/web/src/features/next-soup/soup-view/views/companies/CompanyViewsMenu.tsx b/apps/web/src/features/next-soup/soup-view/views/companies/CompanyViewsMenu.tsx
index 7d108b84de..dd0b09680b 100644
--- a/apps/web/src/features/next-soup/soup-view/views/companies/CompanyViewsMenu.tsx
+++ b/apps/web/src/features/next-soup/soup-view/views/companies/CompanyViewsMenu.tsx
@@ -1,6 +1,6 @@
-import type { Query } from '@app/features/next-soup/filters/filter-store';
import { useSoupView } from '@app/features/next-soup/soup-view/soup-view-context';
import { useApplyPreset } from '@app/features/next-soup/soup-view/soup-view-tabs';
+import { useApplyCrmView } from '@app/features/next-soup/soup-view/views/companies/use-apply-crm-view';
import {
CRM_LIST_COLUMN_LABELS,
type CrmListColumnId,
@@ -17,12 +17,13 @@ import { toast } from '@core/component/Toast/Toast';
import { useUserId } from '@core/context/user';
import FloppyDiskIcon from '@phosphor/floppy-disk.svg';
import LinkIcon from '@phosphor/link.svg';
+import PushPinIcon from '@phosphor/push-pin.svg';
import SlidersIcon from '@phosphor/sliders-horizontal.svg';
import StackIcon from '@phosphor/stack.svg';
import TrashIcon from '@phosphor/trash.svg';
import { useIsTeamAdmin } from '@queries/team/teams';
import { Button, cn, Dropdown, SegmentedControl, Tooltip } from '@ui';
-import { batch, createSignal, For, type JSX, Show } from 'solid-js';
+import { createSignal, For, type JSX, Show } from 'solid-js';
import { unwrap } from 'solid-js/store';
/** Copy a view's share link, with a toast either way. */
@@ -34,13 +35,16 @@ const copyShareLink = (config: CrmViewConfig) => {
};
/**
- * Saved-view row: the name applies the view; trailing hover actions copy
- * its share link or delete it.
+ * Saved-view row: the name applies the view; trailing hover actions pin it
+ * as the default, copy its share link, or delete it. The pin stays visible
+ * on the current default.
*/
const SavedViewRow = (props: {
name: string;
+ isDefault?: boolean;
onApply: () => void;
onCopyLink: () => void;
+ onSetDefault?: () => void;
onDelete?: () => void;
}) => (
<div class="group rounded-lg w-full flex items-center gap-0.5 pl-2 pr-1 hover:bg-ink/5">
@@ -51,6 +55,28 @@ const SavedViewRow = (props: {
>
{props.name}
</button>
+ <Show when={props.isDefault && !props.onSetDefault}>
+ <PushPinIcon class="size-3.5 shrink-0 text-ink-muted" />
+ </Show>
+ <Show when={props.onSetDefault}>
+ {(onSetDefault) => (
+ <Tooltip label={props.isDefault ? 'Remove default' : 'Set as default'}>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ label={props.isDefault ? 'Remove default' : 'Set as default'}
+ class={cn(
+ 'size-6 shrink-0 rounded-md p-1 text-ink-muted',
+ !props.isDefault &&
+ 'opacity-0 group-hover:opacity-100 focus-visible:opacity-100'
+ )}
+ onClick={() => onSetDefault()()}
+ >
+ <PushPinIcon class="size-3.5" />
+ </Button>
+ </Tooltip>
+ )}
+ </Show>
<Tooltip label="Copy link">
<Button
variant="ghost"
@@ -95,15 +121,10 @@ export function CompanyViewsMenu() {
soup,
queryFilters,
searchText,
- setSearchText,
stageFilter,
- setStageFilter,
ownerFilter,
- setOwnerFilter,
activeTab,
- setActiveTab,
viewMode,
- setViewMode,
} = useSoupView();
const personal = usePersonalCrmViews();
const team = useTeamCrmViews();
@@ -134,36 +155,10 @@ export function CompanyViewsMenu() {
activeTab: activeTab(),
});
- // Mirrors the init/applyTabPreset path: replace filters + predicates
- // atomically, then re-derive the stage/owner predicate active state from
- // the saved sub-filter selections (same rule as handleStageChange /
- // handleOwnerChange in unified-filter-dropdown).
+ const applyCrmView = useApplyCrmView();
+
const applyView = (config: CrmViewConfig) => {
- batch(() => {
- queryFilters.replace((config.filters as Query | undefined) ?? null);
- soup.predicates.set(config.clientFilters ?? {});
- setSearchText(config.searchText ?? '');
- // `groupBy: null` records an explicit "no grouping"; the grouping
- // store expresses that as `undefined` (same as the init path).
- soup.grouping.setActiveGroupId(config.groupBy ?? undefined);
- soup.sort.setAll(
- (config.sort?.length ? config.sort : ['updated_at']) as Parameters<
- typeof soup.sort.setAll
- >[0]
- );
- const stages = config.stageFilter ?? [];
- setStageFilter(stages);
- if (stages.length > 0 !== soup.predicates.isActive('company-stage')) {
- soup.predicates.toggle({ and: ['company-stage'] });
- }
- const owners = config.ownerFilter ?? [];
- setOwnerFilter(owners);
- if (owners.length > 0 !== soup.predicates.isActive('company-owner')) {
- soup.predicates.toggle({ and: ['company-owner'] });
- }
- setViewMode(config.viewMode ?? 'board');
- if (config.activeTab !== undefined) setActiveTab(config.activeTab);
- });
+ applyCrmView(config);
setOpen(false);
};
@@ -210,8 +205,14 @@ export function CompanyViewsMenu() {
{(view) => (
<SavedViewRow
name={view.name}
+ isDefault={view.config.isDefault === true}
onApply={() => applyView(view.config)}
onCopyLink={() => copyShareLink(view.config)}
+ onSetDefault={() =>
+ personal.setDefault.mutate({
+ id: view.config.isDefault ? undefined : view.id,
+ })
+ }
onDelete={() => personal.remove.mutate({ id: view.id })}
/>
)}
@@ -227,8 +228,17 @@ export function CompanyViewsMenu() {
{(view) => (
<SavedViewRow
name={view.name}
+ isDefault={view.id === team.defaultViewId()}
onApply={() => applyView(view.config as CrmViewConfig)}
onCopyLink={() => copyShareLink(view.config as CrmViewConfig)}
+ onSetDefault={
+ canEditCrm()
+ ? () =>
+ team.setDefault(
+ view.id === team.defaultViewId() ? undefined : view.id
+ )
+ : undefined
+ }
onDelete={
canDeleteTeamView(view.createdBy)
? () => team.remove(view.id)
diff --git a/apps/web/src/features/next-soup/soup-view/views/companies/CrmDefaultView.tsx b/apps/web/src/features/next-soup/soup-view/views/companies/CrmDefaultView.tsx
new file mode 100644
index 0000000000..330cf3dc18
--- /dev/null
+++ b/apps/web/src/features/next-soup/soup-view/views/companies/CrmDefaultView.tsx
@@ -0,0 +1,32 @@
+import { useApplyCrmView } from '@app/features/next-soup/soup-view/views/companies/use-apply-crm-view';
+import {
+ type CrmViewConfig,
+ usePersonalCrmViews,
+ useTeamCrmViews,
+} from '@companies/crm/saved-views';
+import { createEffect } from 'solid-js';
+
+/**
+ * Applies the default saved view (personal wins over team) once its queries
+ * settle. Mounted only on a fresh Customers entry — never for restored
+ * (back/forward) entries or `?crmView=` share links, which carry their own
+ * state. One-shot: later refetches never re-apply, so a default set while
+ * the view is open doesn't yank the user's state out from under them.
+ */
+export function CrmDefaultViewLoader() {
+ const personal = usePersonalCrmViews();
+ const team = useTeamCrmViews();
+ const applyView = useApplyCrmView();
+
+ let applied = false;
+ createEffect(() => {
+ if (applied || personal.isLoading() || team.isLoading()) return;
+ applied = true;
+ const config =
+ personal.defaultView()?.config ??
+ (team.defaultView()?.config as CrmViewConfig | undefined);
+ if (config) applyView(config);
+ });
+
+ return null;
+}
diff --git a/apps/web/src/features/next-soup/soup-view/views/companies/use-apply-crm-view.ts b/apps/web/src/features/next-soup/soup-view/views/companies/use-apply-crm-view.ts
new file mode 100644
index 0000000000..4ca3d5991a
--- /dev/null
+++ b/apps/web/src/features/next-soup/soup-view/views/companies/use-apply-crm-view.ts
@@ -0,0 +1,51 @@
+import type { Query } from '@app/features/next-soup/filters/filter-store';
+import { useSoupView } from '@app/features/next-soup/soup-view/soup-view-context';
+import type { CrmViewConfig } from '@companies/crm/saved-views';
+import { batch } from 'solid-js';
+
+/**
+ * Applies a saved CRM view config to the current Customers view. Mirrors the
+ * init/applyTabPreset path: replace filters + predicates atomically, then
+ * re-derive the stage/owner predicate active state from the saved sub-filter
+ * selections (same rule as handleStageChange / handleOwnerChange in
+ * unified-filter-dropdown).
+ */
+export function useApplyCrmView() {
+ const {
+ soup,
+ queryFilters,
+ setSearchText,
+ setStageFilter,
+ setOwnerFilter,
+ setActiveTab,
+ setViewMode,
+ } = useSoupView();
+
+ return (config: CrmViewConfig) => {
+ batch(() => {
+ queryFilters.replace((config.filters as Query | undefined) ?? null);
+ soup.predicates.set(config.clientFilters ?? {});
+ setSearchText(config.searchText ?? '');
+ // `groupBy: null` records an explicit "no grouping"; the grouping
+ // store expresses that as `undefined` (same as the init path).
+ soup.grouping.setActiveGroupId(config.groupBy ?? undefined);
+ soup.sort.setAll(
+ (config.sort?.length ? config.sort : ['updated_at']) as Parameters<
+ typeof soup.sort.setAll
+ >[0]
+ );
+ const stages = config.stageFilter ?? [];
+ setStageFilter(stages);
+ if (stages.length > 0 !== soup.predicates.isActive('company-stage')) {
+ soup.predicates.toggle({ and: ['company-stage'] });
+ }
+ const owners = config.ownerFilter ?? [];
+ setOwnerFilter(owners);
+ if (owners.length > 0 !== soup.predicates.isActive('company-owner')) {
+ soup.predicates.toggle({ and: ['company-owner'] });
+ }
+ setViewMode(config.viewMode ?? 'board');
+ if (config.activeTab !== undefined) setActiveTab(config.activeTab);
+ });
+ };
+}
diff --git a/crates/macro_db_client/migrations/20260715203437_enable_pgcrypto.sql b/crates/macro_db_client/migrations/20260715203437_enable_pgcrypto.sql
new file mode 100644
index 0000000000..72ed4b82da
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260715203437_enable_pgcrypto.sql
@@ -0,0 +1,4 @@
+-- pgcrypto's digest() is IMMUTABLE, so it can back expression indexes
+-- (the built-in sha256() needs a text->bytea conversion, and convert_to()
+-- is only STABLE).
+CREATE EXTENSION IF NOT EXISTS pgcrypto;
diff --git a/crates/macro_db_client/migrations/20260715203445_add_property_option_string_value_sha256_unique_index.sql b/crates/macro_db_client/migrations/20260715203445_add_property_option_string_value_sha256_unique_index.sql
new file mode 100644
index 0000000000..925e96d012
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260715203445_add_property_option_string_value_sha256_unique_index.sql
@@ -0,0 +1,11 @@
+-- no-transaction
+
+-- The unique_property_options_string_value UNIQUE constraint is a btree index
+-- over the full string, and Postgres rejects index rows over ~2704 bytes. That
+-- caps option values at ~2.7KB, which breaks large values like the team CRM
+-- config JSON (stored in a single option). Enforce the same uniqueness on a
+-- sha256 of the value instead, which has no length limit. The old constraint
+-- stays in place until this index is built (dropped in the next migration).
+CREATE UNIQUE INDEX CONCURRENTLY unique_property_options_string_value_sha256
+ON property_options (property_definition_id, digest(string_value, 'sha256'))
+WHERE string_value IS NOT NULL;
diff --git a/crates/macro_db_client/migrations/20260715203452_drop_property_option_string_value_unique_constraint.sql b/crates/macro_db_client/migrations/20260715203452_drop_property_option_string_value_unique_constraint.sql
new file mode 100644
index 0000000000..8b17358f20
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260715203452_drop_property_option_string_value_unique_constraint.sql
@@ -0,0 +1,5 @@
+-- The sha256 expression index created in the previous migration now enforces
+-- uniqueness of (property_definition_id, string_value), so the size-capped
+-- btree constraint can go.
+ALTER TABLE property_options
+ DROP CONSTRAINT IF EXISTS unique_property_options_string_value;