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.

8.3 KB
Raw Blame
import { throwOnErr } from '@core/util/result';
import { Telemetry } from '@macro-inc/observability';
import { refreshActiveGraphqlSoupQueries } from '@queries/soup/graphql/active-queries';
import { soupKeys } from '@queries/soup/keys';
import { invalidateCachedCrmContacts } from '@service-storage/crm-contacts';
import { prepareCrmVisibilityWrite } from '@service-storage/crm-visibility';
import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';
import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import type { CrmRecordDependencies } from './dependencies';
import { crmKeys } from './keys';
import { listCanIncludeCrmContacts } from './list-refresh';
import {
  updateVisibilityDetails,
  visibilityDetailsFilter,
  visibilityQueryFilter,
} from './visibility-refresh';

const CONTACT_STALE_TIME = 60 * 1000;

function crmContactByEmailQueryOptions(
  deps: CrmRecordDependencies,
  teamId: string,
  email: string
) {
  const normalizedEmail = email.trim().toLowerCase();
  return queryOptions({
    queryKey: crmKeys.contactByEmail(teamId, normalizedEmail).queryKey,
    queryFn: async ({ signal }) => {
      const { contact } = await throwOnErr(() =>
        deps.storage.getContactByEmail({
          email: normalizedEmail,
          signal,
        })
      );
      if (contact && !signal.aborted) {
        deps.client.setQueryData(crmKeys.contact(contact.id).queryKey, contact);
      }
      return contact;
    },
    staleTime: CONTACT_STALE_TIME,
  });
}

/** Resolves a team CRM contact by email and primes its detail cache. */
export function useCrmContactByEmailQuery(
  deps: CrmRecordDependencies,
  teamId: Accessor<string>,
  email: Accessor<string>,
  enabled: Accessor<boolean>
) {
  return useQuery(
    () => ({
      ...crmContactByEmailQueryOptions(deps, teamId(), email()),
      enabled: enabled() && !!teamId() && !!email(),
    }),
    () => deps.client
  );
}

function contactQueryOptions(deps: CrmRecordDependencies, contactId: string) {
  return queryOptions({
    queryKey: crmKeys.contact(contactId).queryKey,
    queryFn: () => {
      if (!contactId) {
        throw new Error('contact id is required to fetch contact');
      }
      return throwOnErr(() => deps.storage.getContact({ contactId }));
    },
    staleTime: CONTACT_STALE_TIME,
    enabled: !!contactId,
  });
}

/**
 * Fetches a single CRM contact by id via `GET /crm/contacts/{id}`.
 * The endpoint is role-aware: admins/owners see hidden contacts too,
 * non-admins get 404 on hidden rows. The frontend doesn't branch — it
 * just calls the endpoint and trusts the response.
 */
export function useContactQuery(
  deps: CrmRecordDependencies,
  contactId: Accessor<string>
) {
  return useQuery(
    () => contactQueryOptions(deps, contactId()),
    () => deps.client
  );
}

/**
 * Renames a contact via `PUT /crm/contacts/{id}/name`. Unlike company names
 * there is no global directory involved — `crm_contacts.name` is already
 * team-scoped, so the write is a plain overwrite. Optimistically updates the
 * contact detail cache (with rollback on error) so the title flips
 * immediately, then invalidates it plus the parent company (whose response
 * embeds the contact list) and soup so every listing picks up the new name.
 */
export function useSetContactNameMutation(deps: CrmRecordDependencies) {
  return useMutation(
    () => ({
      mutationFn: ({
        contactId,
        name,
      }: {
        contactId: string;
        companyId?: string | null;
        name: string;
      }) => throwOnErr(() => deps.storage.setContactName({ contactId, name })),
      onMutate: async ({ contactId, name }) => {
        const queryKey = crmKeys.contact(contactId).queryKey;
        await deps.client.cancelQueries({ queryKey });
        const previous = deps.client.getQueryData<CrmContactResponse>(queryKey);
        if (previous) {
          deps.client.setQueryData<CrmContactResponse>(queryKey, {
            ...previous,
            name,
          });
        }
        return { previous, optimisticName: name };
      },
      // Roll back only if the cache still holds this mutation's optimistic
      // name — a stale failure must not clobber a newer rename's update.
      onError: (_err, { contactId }, context) => {
        if (context?.previous) {
          deps.client.setQueryData<CrmContactResponse>(
            crmKeys.contact(contactId).queryKey,
            (current) =>
              current?.name === context.optimisticName
                ? context.previous
                : current
          );
        }
      },
      onSettled: async (_data, _err, { contactId, companyId }) => {
        await invalidateCachedCrmContacts(contactId);
        return Promise.all([
          deps.client.invalidateQueries({
            queryKey: crmKeys.contact(contactId).queryKey,
          }),
          companyId &&
            deps.client.invalidateQueries({
              queryKey: crmKeys.company(companyId).queryKey,
            }),
          deps.client.invalidateQueries({ queryKey: soupKeys._def }),
        ]);
      },
    }),
    () => deps.client
  );
}

/**
 * Toggles `crm_contacts.hidden` via `PUT /crm/contacts/{id}/hidden`.
 * Hidden contacts disappear from normal company Team lists for every role
 * and from any soup surface that filters them. Authorized detail reads still
 * include hidden contacts for restoration.
 *
 * Awaits cache invalidation in the visibility trace so the mutation
 * stays pending until active contact, company and soup queries refetch.
 * Inactive company queries become stale and reload when revisited.
 */
export function useSetContactHiddenMutation(deps: CrmRecordDependencies) {
  return useMutation(
    () => ({
      mutationFn: ({
        contactId,
        hidden,
      }: {
        contactId: string;
        hidden: boolean;
      }) =>
        Telemetry.span('crm.visibility_change', async (span) => {
          span.setAttr('crm.record_type', 'contact');
          span.setAttr('crm.record_id', contactId);
          span.setAttr('crm.hidden', hidden);
          try {
            const cacheWrite = prepareCrmVisibilityWrite();
            const result = await throwOnErr(() =>
              deps.storage.setContactHidden({ contactId, hidden })
            );
            if (!cacheWrite.isCurrent()) return result;
            await span.span(
              'crm.visibility_change.refresh',
              async (refresh) => {
                try {
                  const change = {
                    kind: 'contact' as const,
                    id: contactId,
                    hidden,
                  };
                  await Promise.all([
                    cacheWrite.commit({ contactIds: [contactId], hidden }),
                    updateVisibilityDetails(
                      deps.client,
                      change,
                      cacheWrite.isCurrent
                    ),
                  ]);
                  if (!cacheWrite.isCurrent()) return;
                  await Promise.all([
                    refreshActiveGraphqlSoupQueries({
                      where: listCanIncludeCrmContacts,
                      unmaintainedOnly: true,
                    }),
                    deps.client.invalidateQueries({
                      predicate: visibilityQueryFilter(change),
                    }),
                    deps.client.invalidateQueries({
                      predicate: visibilityDetailsFilter(change),
                      // Confirmed flags are already patched; refresh on the next visit.
                      refetchType: 'none',
                    }),
                    deps.client.refetchQueries({
                      type: 'active',
                      predicate: (query) =>
                        query.state.data === undefined &&
                        visibilityDetailsFilter(change)(query),
                    }),
                  ]);
                } catch (error) {
                  refresh.error('Contact visibility refresh failed');
                  Telemetry.error(error);
                }
              }
            );
            span.setAttr('crm.visibility.outcome', 'success');
            return result;
          } catch (error) {
            span.setAttr('crm.visibility.outcome', 'error');
            span.error('Contact visibility update failed');
            throw error;
          }
        }),
    }),
    () => deps.client
  );
}