Skip to content

The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.

7.0 KB
Raw Blame
// New call (N on the Outbound calls page): whom the assistant phones, what it should reach, the first thing it
// says when they pick up, whether to try again when nobody answers and, in a workspace with more than one assistant,
// which one calls. Start call sends call.dial; a refusal (a number abroad, outbound calls not set up) shows in the
// dialog.
import {
  DIAL_FIRST_SENTENCE_MAX,
  DIAL_GOAL_MAX,
  RETRY_QUIET_FROM_HOUR,
  RETRY_QUIET_UNTIL_HOUR,
} from '@linedesk/actions'
import { useT } from '@linedesk/i18n/react'
import { type FormEvent, type KeyboardEvent, useRef, useState } from 'react'
import { useDefaultPhoneCountry } from '../phoneCountry.ts'
import { useAssistants } from '../store.tsx'
import { Select } from '../ui/controls.tsx'
import { Dialog, FormField, Input, Textarea } from '../ui/form.tsx'
import { confirmErrorText } from '../ui/DangerConfirmDialog.tsx'
import { Button, Note } from '../ui/kit.tsx'
import { NO_PASSWORD_MANAGER } from '../ui/passwordManager.ts'
import { PhoneInput } from '../ui/PhoneInput.tsx'
import { formatDate } from '../time.ts'
import { type DialForm, type DialProblem, dialInput, RETRY_CHOICES, retryPresetLabel } from './model.ts'
import { dial } from './outbound-api.ts'

type Props = {
  workspaceName: string
  onClose: () => void
  /** The call is on its way: the room it will be in, and the number. */
  onDialled: (room: string, to: string) => void
}

/** An hour as a clock time in the reader's language ("9 PM", "21:00"). */
const formatHour = (hour: number) => formatDate(new Date(2026, 0, 1, hour), { hour: 'numeric', minute: '2-digit' })

/** Enter in the goal starts the call like in every other field; Shift+Enter starts a new line. */
function submitOnEnter(e: KeyboardEvent<HTMLTextAreaElement>) {
  if (e.key !== 'Enter' || e.shiftKey || e.nativeEvent.isComposing) return
  e.preventDefault()
  e.currentTarget.form?.requestSubmit()
}

export function NewOutboundCall({ workspaceName, onClose, onDialled }: Props) {
  const t = useT()
  const assistants = useAssistants()
  const defaultCountry = useDefaultPhoneCountry()
  const [form, setForm] = useState<DialForm>(() => ({
    to: '',
    goal: '',
    firstSentence: t('call.outbound.new.firstSentenceDefault', {
      assistant: assistants[0]?.name ?? '',
      business: workspaceName,
    }),
    assistantId: '',
    retry: 'none',
  }))
  const [problem, setProblem] = useState<DialProblem | null>(null)
  const [refused, setRefused] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)
  const phoneInput = useRef<HTMLInputElement>(null)
  const set = <K extends keyof DialForm>(field: K, value: DialForm[K]) => {
    setForm(f => ({ ...f, [field]: value }))
    if (problem?.field === field) setProblem(null)
    setRefused(null)
  }

  async function submit(e: FormEvent) {
    e.preventDefault()
    if (busy) return
    const result = dialInput(form)
    if ('problem' in result) {
      setProblem(result.problem)
      if (result.problem.field === 'to') phoneInput.current?.focus()
      else document.getElementById(`oc-new-${result.problem.field}`)?.focus()
      return
    }
    setBusy(true)
    try {
      const dialled = await dial(result.input)
      onDialled(dialled.room, dialled.to)
    } catch (err) {
      setRefused(confirmErrorText(err))
      setBusy(false)
    }
  }

  const errorOf = (field: DialProblem['field']) => (problem?.field === field ? problem.text : null)
  const assistantOptions = [
    { value: '', label: t('call.outbound.new.assistantDefault', { assistant: assistants[0]?.name ?? '' }) },
    ...assistants.slice(1).map(a => ({ value: a.id, label: a.name })),
  ]
  return (
    <Dialog
      title={t('call.outbound.new.title')}
      description={t('call.outbound.new.description', { assistant: assistants[0]?.name ?? '' })}
      onClose={busy ? () => {} : onClose}
      onSubmit={submit}
      footer={
        <>
          <Button variant="ghost" onClick={onClose} disabled={busy}>
            {t('common.action.cancel')}
          </Button>
          <Button
            type="submit"
            variant="primary"
            icon="phone-out"
            busy={busy}
            title={t('common.withKey', { label: t('call.outbound.new.start'), key: '⏎' })}
          >
            {t('call.outbound.new.start')}
          </Button>
        </>
      }
    >
      <div className="oc-new">
        <FormField
          id="oc-new-to"
          label={t('call.outbound.new.to')}
          description={t('call.outbound.new.toHint')}
          error={errorOf('to')}
        >
          <PhoneInput
            id="oc-new-to"
            value={form.to}
            defaultCountry={defaultCountry}
            autoComplete="off"
            autoFocus
            inputRef={phoneInput}
            invalid={!!errorOf('to')}
            onChange={to => set('to', to)}
          />
        </FormField>
        {assistants.length > 1 && (
          <FormField id="oc-new-assistant" label={t('call.outbound.new.assistant')}>
            <Select
              id="oc-new-assistant"
              value={form.assistantId}
              options={assistantOptions}
              label={t('call.outbound.new.assistant')}
              onChange={id => set('assistantId', id)}
            />
          </FormField>
        )}
        <FormField
          id="oc-new-goal"
          label={t('call.outbound.new.goal')}
          description={t('call.outbound.new.goalHint')}
          error={errorOf('goal')}
        >
          <Textarea
            id="oc-new-goal"
            rows={4}
            value={form.goal}
            maxLength={DIAL_GOAL_MAX}
            invalid={!!errorOf('goal')}
            placeholder={t('call.outbound.new.goalPlaceholder')}
            onChange={e => set('goal', e.target.value)}
            onKeyDown={submitOnEnter}
          />
        </FormField>
        <FormField
          id="oc-new-firstSentence"
          label={t('call.outbound.new.firstSentence')}
          description={t('call.outbound.new.firstSentenceHint')}
          error={errorOf('firstSentence')}
        >
          <Input
            id="oc-new-firstSentence"
            {...NO_PASSWORD_MANAGER}
            value={form.firstSentence}
            maxLength={DIAL_FIRST_SENTENCE_MAX}
            invalid={!!errorOf('firstSentence')}
            onChange={e => set('firstSentence', e.target.value)}
          />
        </FormField>
        <FormField
          id="oc-new-retry"
          label={t('call.outbound.new.retry')}
          description={t('call.outbound.new.retryHint', {
            from: formatHour(RETRY_QUIET_FROM_HOUR),
            until: formatHour(RETRY_QUIET_UNTIL_HOUR),
          })}
        >
          <Select
            id="oc-new-retry"
            value={form.retry}
            options={RETRY_CHOICES.map(value => ({ value, label: retryPresetLabel(value) }))}
            label={t('call.outbound.new.retry')}
            onChange={retry => set('retry', retry)}
          />
        </FormField>
        {refused && (
          <Note tone="danger" role="alert">
            {refused}
          </Note>
        )}
      </div>
    </Dialog>
  )
}