import gql from "graphql-tag"; import { useMutation } from "react-apollo-hooks"; import { useCallback } from "react"; import { removeLeadFromUnscheduled, isDueToday, addActivityToWorklist } from "../../Worklist/worklist-store"; import { addActivityToLead } from "./usePersonActivitiesQuery"; import { get } from "lodash"; export function isEvent(when) { return !!when.tokens.find( t => t.type === "hour" || t.type === "minute" || (t.type === "unit" && (t.value === "minutes" || t.value === "hours")) ); } export const SCHEDULE_TASK_MUTATION = gql` mutation createTask($task: TaskInput!) { createTask(input: $task) { Id LeadId Type Subject ActivityDate ActivitySubtype } } `; const SCHEDULE_EVENT_MUTATION = gql` mutation createEvent($event: EventInput!) { createEvent(input: $event) { Id LeadId Type Subject StartDateTime ActivitySubtype } } `; export function useCreateTask(contactId) { const addTask = useMutation(SCHEDULE_TASK_MUTATION, { update: (cache, mutationResult) => { const task = mutationResult.data.createTask; const taskDate = get(task, "ActivityDate"); if (!taskDate) { console.warn("Somehow the taskdate did not come back"); } if (isDueToday(taskDate)) { addActivityToWorklist(cache, task); } removeLeadFromUnscheduled(cache, contactId); addActivityToLead(cache, contactId, task); } }); return addTask; } export default function useScheduleActivity(contactId) { const addTask = useCreateTask(contactId); const addEvent = useMutation(SCHEDULE_EVENT_MUTATION, { update: (cache, mutationResult) => { const event = mutationResult.data.createEvent; const date = get(event, "StartDateTime"); if (!date) { console.warn("Somehow the Event StartDateTime did not come back"); } if (isDueToday(date)) { addActivityToWorklist(cache, event); } removeLeadFromUnscheduled(cache, contactId); addActivityToLead(cache, contactId, event); } }); const action = useCallback( values => { const { when, channel, subject } = values; const base = { LeadId: contactId, Subject: subject, Type: channel && channel.value }; if (isEvent(when)) { const event = { ...base, StartDateTime: when.date, DurationInMinutes: 30 }; return addEvent({ variables: { event } }); } else { const task = { ...base, ActivityDate: when.date }; return addTask({ variables: { task } }); } }, [addEvent, addTask, contactId] ); return action; }