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.

4.0 KB
Raw Blame
/**
 * `/poll` (RFC 03 §3): a poll is a form with one required choice question.
 * Create the form (and its database), add the Select column with the options
 * under ids minted here, place it as the only question, and show its results
 * to respondents. An anonymous poll is anonymous from creation, so its table
 * never gets a Respondent column.
 */
import { createDatabaseColumn } from '@block-database/queries/columns';
import { createForm, putFormLayout, updateForm } from '@queries/storage/forms';
import { err, errAsync, ok, ResultAsync } from 'neverthrow';
import { v7 as uuidv7 } from 'uuid';
import type { FormWriteFailure } from '../context/form-context';
import { duplicatePollOptions } from '../core/poll-options';
import { columnWriteFailure } from './column-writes';
import { publicationMessage } from './form-publication';
import { writeFailureOf } from './form-sources';

export type PollDraft = {
  question: string;
  options: string[];
  multi: boolean;
  shareResponses: boolean;
  anonymous: boolean;
};

/** What a half-made poll leaves behind, for the caller to put in the trash. */
export type MadePoll = { formId: string; databaseId: string };

export function publishPoll(
  draft: PollDraft,
  discard: (made: MadePoll) => ResultAsync<void, unknown>
): ResultAsync<
  MadePoll & { name: string; optionCount: number },
  FormWriteFailure
> {
  const question = draft.question.trim();
  const labels = draft.options.map((option) => option.trim()).filter(Boolean);
  if (duplicatePollOptions(draft.options).size > 0)
    return errAsync({ message: 'Each option needs a different name.' });
  if (!question) return errAsync({ message: 'Ask a question.' });
  if (labels.length < 2)
    return errAsync({ message: 'Give at least two options.' });
  return createForm(
    {
      name: question,
      source: {
        kind: 'new',
        isHiddenInDrive: true,
        anonymous: draft.anonymous,
      },
    },
    'poll'
  )
    .mapErr(writeFailureOf)
    .andThen((detail) => {
      const { databaseId, tableId, id: formId } = detail.form;
      // A step refused after the form exists leaves nothing behind.
      const abandon = (failure: FormWriteFailure) =>
        new ResultAsync<never, FormWriteFailure>(
          discard({ formId, databaseId }).match(
            () => err(failure),
            () =>
              err({
                ...failure,
                message: `${failure.message} The unfinished poll could not be removed.`,
              })
          )
        );
      const section = detail.sections.find((item) => item.kind === 'questions');
      if (!section)
        return abandon({
          message: 'The new form has no section to hold the question.',
        });
      return createDatabaseColumn({
        databaseId,
        tableId,
        name: 'Answer',
        type: { type: 'select', multi: draft.multi },
        options: labels,
      })
        .mapErr(columnWriteFailure)
        .andThen((columnId) =>
          putFormLayout(formId, {
            sections: [
              {
                kind: 'questions',
                id: section.id,
                title: '',
                description: '',
                questions: [
                  {
                    id: uuidv7(),
                    column: columnId,
                    helpText: '',
                    required: true,
                    widget: draft.multi ? 'checkboxes' : 'choice',
                  },
                ],
              },
            ],
          })
            .mapErr(writeFailureOf)
            .andThen((saved) => {
              const message = publicationMessage(saved);
              return message ? err({ message }) : ok(saved.detail);
            })
        )
        .andThen(() =>
          updateForm(formId, {
            tallyVisible: true,
            responsesVisible: draft.shareResponses,
          }).mapErr(writeFailureOf)
        )
        .orElse(abandon)
        .map(() => ({
          formId,
          databaseId,
          name: question,
          optionCount: labels.length,
        }));
    });
}