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.

21.2 KB
Raw Blame
import {
  type CombinedRecipientItem,
  recipientEntityMapper,
  type WithCustomUserInput,
} from '@core/user/combinedRecipient';
import { parseLocalDate } from '@core/util/local-date';
import { TZDateMini } from '@date-fns/tz';
import type { CalendarCapabilities } from '@service-calendar/generated/schemas/calendarCapabilities';
import type { CalendarProvider } from '@service-calendar/generated/schemas/calendarProvider';
import type { ConferenceChange } from '@service-calendar/generated/schemas/conferenceChange';
import type { EventTime } from '@service-calendar/generated/schemas/eventTime';
import type { OutOfOfficeProperties } from '@service-calendar/generated/schemas/outOfOfficeProperties';
import type { EventReminderOverride } from '@service-storage/generated/schemas/eventReminderOverride';
import type { EventReminders } from '@service-storage/generated/schemas/eventReminders';
import type { EventType } from '@service-storage/generated/schemas/eventType';
import type { GuestPolicy } from '@service-storage/generated/schemas/guestPolicy';
import {
  addDays,
  addHours,
  endOfDay,
  format,
  parseISO,
  startOfHour,
} from 'date-fns';
import { type Accessor, batch, createMemo, createSignal } from 'solid-js';
import type { CalendarEvent } from '../../types';
import { isTimedPointEvent } from '../../utils/calendar-date';
import {
  calendarMacroCallUrl,
  removeCalendarMacroCall,
} from '../../utils/macro-call-link';
import {
  buildRecurrenceLines,
  defaultCustomConfig,
  formatRecurrenceDescription,
  parseRecurrenceConfig,
  type RecurrenceConfig,
  recurrenceConfigsEqual,
  recurrencePresetsFor,
  WEEKDAY_CODES,
  type WeekdayCode,
} from '../../utils/recurrence';
import type { EventEditorOutOfOffice } from './out-of-office';

/** `<input type="date">` value. */
const DATE_VALUE = 'yyyy-MM-dd';
/** `<input type="datetime-local">` value. */
const DATETIME_VALUE = "yyyy-MM-dd'T'HH:mm";

const isDateOnly = (value: string) => parseLocalDate(value) !== undefined;

/** Option displayed by an event editor recurrence selector. */
export interface EventEditorRecurrenceOption {
  value: string;
  label: string;
}

function shiftDateValue(value: string, days: number) {
  return format(addDays(parseISO(value), days), DATE_VALUE);
}

/** Local midnight of a `yyyy-MM-dd` date, as a UTC ISO instant. */
function localMidnightIso(date: string): string {
  return new Date(`${date}T00:00`).toISOString();
}

/** Default editor slot: the next full hour, one hour long. */
function defaultEditorTimes(reference: Date) {
  const start = addHours(startOfHour(reference), 1);
  return { start, end: addHours(start, 1) };
}

/** Conferencing displayed by the editor before it is submitted. */
export type EventEditorConferenceChoice =
  | 'none'
  | 'macro'
  | 'google_meet'
  | 'microsoft_teams'
  | 'existing';

/** Values used to initialize the shared event editor form. */
export interface EventEditorInitialValues {
  title: string;
  allDay: boolean;
  /** `datetime-local` value, or `date` value in all-day mode. */
  start: string;
  /** Inclusive end shown to the user; all-day submissions add the exclusive day. */
  end: string;
  /** Exact provider instant, preserved only for an unchanged imported point. */
  importedPointTime?: Extract<EventTime, { kind: 'timed' }>;
  recurrenceLines: string[];
  calendarId?: string;
  guests: string;
  location: string;
  description: string;
  /** What conferencing the saved event should carry. */
  conference: EventEditorConferenceChoice;
  /** Per-user reminder configuration; absent means the calendar default. */
  reminders?: EventReminders;
  /** Provider event type of the edited event; absent for new events. */
  eventType?: EventType;
  /**
   * Out-of-office decline behavior. Absent while the event is not out of
   * office, and on an edited out-of-office event until the user picks decline
   * settings — the provider readback does not expose the stored ones.
   */
  outOfOffice?: EventEditorOutOfOffice;
  /** Event type of the copy `reminders` belong to. Absent for new events. */
  reminderEventType?: EventType;
  /** What guests may do; absent means Google's defaults. */
  guestPolicy?: GuestPolicy;
}

/** Calendar option displayed by the event editor. */
export interface EventEditorCalendarOption {
  provider?: CalendarProvider;
  capabilities?: CalendarCapabilities;
  id: string;
  label: string;
  color: string;
  /** Provider defaults shown until the event's reminders are customized. */
  defaultReminders?: EventReminderOverride[];
  /** Whether this is its account's primary calendar, the only kind Google
   * accepts out-of-office events on. */
  isPrimary?: boolean;
}

/** Editable fields that a create/edit owner may disable. */
type EventEditorField =
  | 'title'
  | 'allDay'
  | 'start'
  | 'end'
  | 'recurrence'
  | 'calendar'
  | 'guests'
  | 'location'
  | 'description'
  | 'conference'
  | 'reminders'
  | 'outOfOffice';

/** Field-level disabled state supplied by a create/edit owner. */
export type EventEditorDisabledFields = Partial<
  Record<EventEditorField, boolean>
>;

/** Validated values emitted by the shared event editor form. */
export interface EventEditorSubmitValues {
  title: string;
  time: EventTime;
  recurrenceLines?: string[];
  calendarId?: string;
  guestEmails: string[];
  location: string;
  description: string;
  /** Selected conferencing, including client-managed Macro call links. */
  conferenceChoice: EventEditorConferenceChoice;
  /** Present only when provider conferencing should change. */
  conference?: ConferenceChange;
  /** Present only when the user changed the event's reminder configuration. */
  reminders?: EventReminders;
  /**
   * Present when the save is out of office: on create its presence marks the
   * event as out of office, on edit it patches the decline behavior of an
   * event that already is.
   */
  outOfOffice?: OutOfOfficeProperties;
  /** Present only when the user changed what guests may do. */
  guestPolicy?: GuestPolicy;
}

export function defaultEditorInitialValues(
  reference = new Date(),
  macroCallsEnabled = false
): EventEditorInitialValues {
  const { start, end } = defaultEditorTimes(reference);
  return {
    title: '',
    allDay: false,
    start: format(start, DATETIME_VALUE),
    end: format(end, DATETIME_VALUE),
    recurrenceLines: [],
    calendarId: undefined,
    guests: '',
    location: '',
    description: '',
    conference: macroCallsEnabled ? 'macro' : 'none',
    reminders: undefined,
    eventType: undefined,
    outOfOffice: undefined,
  };
}

/** Converts a FullCalendar-style selected range into create-event values. */
export function calendarSelectionToEditorInitialValues(
  selection: {
    start: Date;
    end: Date;
    allDay: boolean;
  },
  macroCallsEnabled = false
): EventEditorInitialValues {
  const initialValues = defaultEditorInitialValues(
    selection.start,
    macroCallsEnabled
  );
  if (selection.allDay) {
    return {
      ...initialValues,
      allDay: true,
      start: format(selection.start, DATE_VALUE),
      end: format(addDays(selection.end, -1), DATE_VALUE),
    };
  }

  return {
    ...initialValues,
    start: format(selection.start, DATETIME_VALUE),
    end: format(selection.end, DATETIME_VALUE),
  };
}

function initialConferenceChoice(
  event: CalendarEvent
): EventEditorConferenceChoice {
  if (calendarMacroCallUrl(event)) return 'macro';
  if (!event.conferenceUrl) return 'none';
  return event.conferenceProvider === 'google_meet' ||
    event.conferenceProvider === 'microsoft_teams'
    ? event.conferenceProvider
    : 'existing';
}

/**
 * Guest emails an existing event seeds into the editor: every attendee except
 * the viewer when they are a mere guest. The organizer is kept even when it is
 * the viewer, so a replacement attendee list submitted by the organizer never
 * drops them. So is the viewer's own row on an event they organize through a
 * calendar Google names as the organizer, such as their secondary calendar,
 * which lists them only as a guest.
 */
export function eventGuestEmails(event: CalendarEvent): string[] {
  return event.attendees
    .filter(
      (attendee) =>
        attendee.isOrganizer || !attendee.isSelf || event.viewerCan.organize
    )
    .map((attendee) => attendee.email);
}

/** Converts an existing event into values for the shared editor. */
export function calendarEventToEditorInitialValues(
  event: CalendarEvent
): EventEditorInitialValues {
  const guests = eventGuestEmails(event).join(', ');
  const content = removeCalendarMacroCall(event, calendarMacroCallUrl(event));

  if (event.allDay) {
    const start = isDateOnly(event.start)
      ? event.start
      : format(new Date(event.start), DATE_VALUE);
    const exclusiveEnd = isDateOnly(event.end)
      ? event.end
      : format(new Date(event.end), DATE_VALUE);
    return {
      title: event.title,
      allDay: true,
      start,
      end: shiftDateValue(exclusiveEnd, -1),
      recurrenceLines: [...event.recurrenceLines],
      calendarId: event.calendarId ?? event.calendar.id,
      guests,
      location: content.location,
      description: content.description,
      conference: initialConferenceChoice(event),
      reminders: event.reminders,
      eventType: event.eventType,
      reminderEventType: event.reminderEventType,
      guestPolicy: event.guestPolicy,
    };
  }

  return {
    title: event.title,
    allDay: false,
    start: format(new Date(event.start), DATETIME_VALUE),
    end: format(new Date(event.end), DATETIME_VALUE),
    importedPointTime: isTimedPointEvent(event)
      ? {
          kind: 'timed',
          startsAt: event.start,
          endsAt: event.end,
          timeZone: event.timeZone ?? null,
        }
      : undefined,
    recurrenceLines: [...event.recurrenceLines],
    calendarId: event.calendarId ?? event.calendar.id,
    guests,
    location: content.location,
    description: content.description,
    conference: initialConferenceChoice(event),
    reminders: event.reminders,
    eventType: event.eventType,
    reminderEventType: event.reminderEventType,
    guestPolicy: event.guestPolicy,
  };
}

export function buildEventTime(
  state: EventEditorInitialValues
): EventTime | undefined {
  if (state.allDay) {
    if (!state.start || !state.end || state.end < state.start) {
      return undefined;
    }
    // Google has no date-based out-of-office event, so encode an all-day one as
    // a timed span covering whole days in the editor's time zone. It then reads
    // and renders as a full-day timed block, the same as Google Calendar shows
    // its own all-day out-of-office events.
    if (state.eventType === 'out_of_office') {
      return {
        kind: 'timed',
        startsAt: localMidnightIso(state.start),
        endsAt: localMidnightIso(shiftDateValue(state.end, 1)),
        timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
      };
    }
    return {
      kind: 'allDay',
      startDate: state.start,
      endDate: shiftDateValue(state.end, 1),
    };
  }

  const start = new Date(state.start);
  const end = new Date(state.end);
  if (
    Number.isNaN(start.getTime()) ||
    Number.isNaN(end.getTime()) ||
    end <= start
  ) {
    return undefined;
  }
  return {
    kind: 'timed',
    startsAt: start.toISOString(),
    endsAt: end.toISOString(),
    timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
  };
}

/** Copy shown when guests would be invited to an event that already ended. */
export const PAST_EVENT_GUESTS_WARNING =
  'This event has already ended — guests will still be invited.';

/** When the edited range ends, or `undefined` while the range does not parse. */
export function eventEndsAt(state: EventEditorInitialValues): Date | undefined {
  if (state.allDay) {
    const end = parseLocalDate(state.end);
    return end ? endOfDay(end) : undefined;
  }
  const end = new Date(state.end);
  return Number.isNaN(end.getTime()) ? undefined : end;
}

/** Whether the edited range finished before `now`. In-progress events do not. */
export function eventHasEnded(
  state: EventEditorInitialValues,
  now = new Date()
) {
  const endsAt = eventEndsAt(state);
  return endsAt !== undefined && endsAt.getTime() < now.getTime();
}

function parseGuestEmails(value: string) {
  return [...new Set(value.split(/[\s,;]+/).filter((email) => email !== ''))];
}

type EventEditorGuestKind = 'user' | 'contact';
export type EventEditorGuestOption =
  CombinedRecipientItem<EventEditorGuestKind>;
export type SelectedEventEditorGuest =
  WithCustomUserInput<EventEditorGuestKind>;

export function guestEmail(option: SelectedEventEditorGuest) {
  return option.data.email;
}

export function initialGuestOptions(
  value: string,
  options: EventEditorGuestOption[]
): SelectedEventEditorGuest[] {
  return parseGuestEmails(value).map((email) => {
    const existing = options.find(
      (option) => guestEmail(option).toLowerCase() === email.toLowerCase()
    );
    return (
      existing ??
      recipientEntityMapper('custom')({
        id: `macro|${email}`,
        email,
        invalid: false,
      })
    );
  });
}

/** Both editor times switch representation when all-day toggles. */
export function convertTimesForAllDay(
  state: EventEditorInitialValues,
  allDay: boolean
) {
  if (allDay === state.allDay) return state;
  if (allDay) {
    return {
      ...state,
      allDay,
      start: state.start.slice(0, 10),
      end: state.end.slice(0, 10),
    };
  }
  const { start, end } = defaultEditorTimes(parseISO(state.start));
  return {
    ...state,
    allDay,
    start: format(start, DATETIME_VALUE),
    end: format(end, DATETIME_VALUE),
  };
}

export interface CreateEventEditorStateOptions {
  initialValues: EventEditorInitialValues;
  state: Accessor<EventEditorInitialValues>;
  recurrenceTimeZone?: string;
  isEdit?: boolean;
}

/** When the event starts, in the zone its recurrence is expressed in. */
function recurrenceStartOf(
  values: Pick<EventEditorInitialValues, 'allDay' | 'start'>,
  timeZone?: string
) {
  const parsed = values.allDay
    ? parseISO(values.start)
    : new Date(values.start);
  if (Number.isNaN(parsed.getTime())) return undefined;
  return !values.allDay && timeZone ? TZDateMini.tz(timeZone, parsed) : parsed;
}

/**
 * The editable form of the event's rule, read at `start`. A weekly rule
 * without BYDAY repeats on the start's weekday (RFC 5545), so that weekday
 * is spelled out, as the weekly preset and the custom editor's day chips
 * show it.
 */
function recurrenceConfigFor(
  values: EventEditorInitialValues,
  timeZone?: string,
  start: Pick<EventEditorInitialValues, 'allDay' | 'start'> = values
) {
  if (values.recurrenceLines.length === 0) return undefined;
  const config = parseRecurrenceConfig(values.recurrenceLines, timeZone);
  if (config?.frequency !== 'WEEKLY' || config.byDay.length > 0) return config;
  const startsAt = recurrenceStartOf(start, timeZone);
  if (!startsAt) return config;
  return {
    ...config,
    byDay: [WEEKDAY_CODES[startsAt.getDay()] as WeekdayCode],
  };
}

function recurrenceChoiceFor(
  values: EventEditorInitialValues,
  timeZone?: string
) {
  if (values.recurrenceLines.length === 0) return 'none';
  const config = recurrenceConfigFor(values, timeZone);
  if (!config) return 'existing';
  const start = recurrenceStartOf(values, timeZone) ?? new Date();
  const preset = recurrencePresetsFor(start).find((candidate) =>
    recurrenceConfigsEqual(candidate.config, config)
  );
  return preset?.id ?? 'custom';
}

/** Shared recurrence and validation state used by event editor layouts. */
export function createEventEditorState(options: CreateEventEditorStateOptions) {
  const [initialValues, setInitialValues] = createSignal(options.initialValues);
  const initialConfig = createMemo(() =>
    recurrenceConfigFor(initialValues(), options.recurrenceTimeZone)
  );
  const hasUnrepresentableRule = () =>
    initialValues().recurrenceLines.length > 0 && !initialConfig();

  const startForRecurrence = createMemo(() => {
    const state = options.state();
    const parsed = state.allDay ? parseISO(state.start) : new Date(state.start);
    if (Number.isNaN(parsed.getTime())) return new Date();
    return !state.allDay && options.recurrenceTimeZone
      ? TZDateMini.tz(options.recurrenceTimeZone, parsed)
      : parsed;
  });
  const presets = createMemo(() => recurrencePresetsFor(startForRecurrence()));
  const [recurrenceChoice, setRecurrenceChoice] = createSignal(
    recurrenceChoiceFor(options.initialValues, options.recurrenceTimeZone)
  );
  const recurrenceOptions = createMemo<EventEditorRecurrenceOption[]>(() => {
    const values = [
      { value: 'none', label: 'Does not repeat' },
      ...presets().map((preset) => ({
        value: preset.id,
        label: preset.label,
      })),
    ];
    if (hasUnrepresentableRule()) {
      values.push({
        value: 'existing',
        label: `Custom: ${
          formatRecurrenceDescription(initialValues().recurrenceLines) ??
          'existing rule'
        } (unchanged)`,
      });
    }
    values.push({ value: 'custom', label: 'Custom' });
    return values;
  });
  const selectedRecurrenceOption = () =>
    recurrenceOptions().find((option) => option.value === recurrenceChoice()) ??
    recurrenceOptions()[0];
  const [customConfig, setCustomConfig] = createSignal<RecurrenceConfig>(
    initialConfig() ?? defaultCustomConfig(startForRecurrence())
  );
  const changeRecurrenceChoice = (choice: string) => {
    if (choice === 'custom') {
      const seed =
        presets().find((preset) => preset.id === recurrenceChoice())?.config ??
        initialConfig() ??
        defaultCustomConfig(startForRecurrence());
      setCustomConfig(seed);
    }
    setRecurrenceChoice(choice);
  };
  const customValid = createMemo(() => {
    if (recurrenceChoice() !== 'custom') return true;
    const config = customConfig();
    if (!Number.isInteger(config.interval) || config.interval < 1) return false;
    if (config.frequency === 'WEEKLY' && config.byDay.length === 0) {
      return false;
    }
    if (config.ends.kind === 'on') return config.ends.date !== '';
    if (config.ends.kind === 'after') {
      return Number.isInteger(config.ends.count) && config.ends.count >= 1;
    }
    return true;
  });
  const recurrenceConfig = (): RecurrenceConfig | undefined => {
    const choice = recurrenceChoice();
    if (choice === 'none') return undefined;
    if (choice === 'existing') return initialConfig();
    return choice === 'custom'
      ? customConfig()
      : presets().find((candidate) => candidate.id === choice)?.config;
  };
  const recurrenceLines = (): string[] | undefined => {
    const choice = recurrenceChoice();
    if (choice === 'existing') return undefined;
    if (choice === 'none') return [];
    const config = recurrenceConfig();
    if (!config) return undefined;
    // What the stored rule means at the current start: a weekly rule without
    // BYDAY follows the start to another weekday.
    const originalConfig = recurrenceConfigFor(
      initialValues(),
      options.recurrenceTimeZone,
      options.state()
    );
    if (
      originalConfig &&
      options.state().allDay === initialValues().allDay &&
      recurrenceConfigsEqual(config, originalConfig)
    ) {
      // Rebuilding an untouched rule can reorder fields, drop provider details
      // like WKST, or change UNTIL precision. Preserve it so a private reminder
      // edit does not accidentally request an organizer-only series update.
      return initialValues().recurrenceLines;
    }
    return buildRecurrenceLines(
      config,
      options.state().allDay,
      options.recurrenceTimeZone
    );
  };
  const unchangedImportedPoint = () => {
    const initial = initialValues();
    const current = options.state();
    return options.isEdit === true &&
      initial.importedPointTime !== undefined &&
      !current.allDay &&
      current.start === initial.start &&
      current.end === initial.end
      ? initial.importedPointTime
      : undefined;
  };
  const dateRangeError = createMemo(() => {
    const current = options.state();
    if (!current.start || !current.end) return undefined;
    if (current.allDay) {
      return current.end < current.start
        ? 'End date cannot be before the start date.'
        : undefined;
    }
    const start = new Date(current.start);
    const end = new Date(current.end);
    if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) {
      return undefined;
    }
    return end <= start && !unchangedImportedPoint()
      ? 'End time must be after the start time.'
      : undefined;
  });
  const eventTime = createMemo(
    () => buildEventTime(options.state()) ?? unchangedImportedPoint()
  );
  const canSave = () =>
    options.state().title.trim() !== '' &&
    eventTime() !== undefined &&
    customValid();
  const replaceInitialValues = (next: EventEditorInitialValues) => {
    batch(() => {
      setInitialValues(() => next);
      setRecurrenceChoice(
        recurrenceChoiceFor(next, options.recurrenceTimeZone)
      );
      setCustomConfig(
        recurrenceConfigFor(next, options.recurrenceTimeZone) ??
          defaultCustomConfig(startForRecurrence())
      );
    });
  };

  return {
    startForRecurrence,
    recurrenceChoice,
    recurrenceOptions,
    selectedRecurrenceOption,
    customConfig,
    setCustomConfig,
    changeRecurrenceChoice,
    recurrenceLines,
    recurrenceConfig,
    dateRangeError,
    eventTime,
    canSave,
    replaceInitialValues,
  };
}