* feat: add 5 new workflow triggers for booking events
- Add BOOKING_REJECTED, BOOKING_REQUESTED, BOOKING_PAYMENT_INITIATED, BOOKING_PAID, BOOKING_NO_SHOW_UPDATED to WorkflowTriggerEvents enum
- Update workflow constants to include new trigger options
- Implement workflow trigger logic for booking rejected and requested events
- Add translations for new workflow triggers following {enum}_trigger format
- Generate updated Prisma types for new schema changes
Co-Authored-By: [email protected] <[email protected]>
* fix: type check, remove as any
* feat: add workflow trigger for BOOKING_REQUESTED in handleNewBooking.ts
- Add WorkflowTriggerEvents import to handleNewBooking.ts
- Implement workflow trigger logic for BOOKING_REQUESTED in else block
- Filter workflows by BOOKING_REQUESTED trigger and call scheduleWorkflowReminders
- Use proper calendar event object construction without type casting
- Add error handling for workflow reminder scheduling
Co-Authored-By: [email protected] <[email protected]>
* fix: resolve type errors in workflow trigger implementations
- Add proper database includes for user information in handleConfirmation.ts
- Fix ExtendedCalendarEvent type structure with correct hosts mapping
- Add missing properties to calendar event objects in handleMarkNoShow.ts
- Ensure all workflow triggers follow proper type patterns
Co-Authored-By: [email protected] <[email protected]>
* feat: add workflow test configurations for new booking triggers
- Add workflow configurations for BOOKING_REQUESTED and BOOKING_PAYMENT_INITIATED in fresh-booking.test.ts
- Add workflow configuration for BOOKING_REJECTED in confirm.handler.test.ts
- Enable previously skipped confirm.handler.test.ts
- Remove workflow test assertions temporarily until triggers are fully functional
- Maintain webhook test coverage while adding workflow test infrastructure
Co-Authored-By: [email protected] <[email protected]>
* fix: add missing mockSuccessfulVideoMeetingCreation import to confirm.handler.test.ts
- Import mockSuccessfulVideoMeetingCreation from bookingScenario utils
- Add mock call to BOOKING_REJECTED workflow test case
- Resolves ReferenceError that was causing unit test CI failure
Co-Authored-By: [email protected] <[email protected]>
* add new triggers
* refactor: improve _scheduleWorkflowReminders readability and add missing booking trigger events
- Extract complex conditional logic into helper functions (isImmediateTrigger, isTimeBased, shouldProcessWorkflow)
- Add missing workflow trigger events with immediate execution logic
- Update test workflows to use different actions (EMAIL_ATTENDEE, SMS_ATTENDEE) for better differentiation
- Fix translation function mock in confirm.handler.test.ts using mockNoTranslations utility
- Maintain existing functionality while improving code maintainability
Co-Authored-By: [email protected] <[email protected]>
* only show customt emplate for form triggers
* filter outside scheduleWorkflowReminder
* fix type check
* chore: add more tests
* test: add comprehensive unit tests for handleMarkNoShow with webhook and workflow coverage
- Create handleMarkNoShow.test.ts following confirm.handler.test.ts pattern
- Add expectBookingNoShowUpdatedWebhookToHaveBeenFired utility function
- Test both webhook and workflow triggers for BOOKING_NO_SHOW_UPDATED
- Cover attendee/host no-show scenarios, multiple attendees, and error cases
- All 6 unit tests pass with proper mocking of external dependencies
Co-Authored-By: [email protected] <[email protected]>
* Revert "test: add comprehensive unit tests for handleMarkNoShow with webhook and workflow coverage"
This reverts commit 764299220279f0c012392dec24d3150246bfc4ad.
* fix: add new workflow triggers to api/v2
* update swagger docs
* fix: e2e
* fix type check
* fix tests, add test for before after events
* fix unit tests
* revert confirm.handler.test
* fix: unit tests
* dummy form variables
* add routing forms to active on dropdown
* add migration file
* Ui fixes for variables dropdown
* remove other translation keys
* review fixes
* allow routing forms for activeOn
* use repository function to get routing forms
* remove unnecessary code
* adjust logic in update handler
* add triggers to api v2
* remvoe unused file
* rename to getAcitveOnOptions handler
* remove routingFormOptions handler
* clean up getActiveOnOptions
* refactor WorkflowService
* remove logs
* remove unused
* fix: type check
* fix: missed before after events for recurring
* fix: calendarEvent handleMarkNoShow
* fix error message
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
* don't query disabled routing forms
* create tasker function
* add tasker code
* move isFormTrigger function
* small adjustments + todo comments
* remove email to host action for form triggers
* throw trpc error if email to host is added as step
* fix dialog on how to use form responses as variables
* remove add variable dropdown for form triggers
* remove form workfows in event workflows tab
* improvements for workflow logic on form submission
* review fixes
* base setup for seperate schedule functions (evt and form)
* add missing BOOKING_PAID workflow trigger
* fix pathname
* fix: test for BOOKING_REQUESTED
* fix activeOn ids
* pass hideBranding and smsReminderNumber
* adjustments to reminderScheduler
* create empty scheduelForForm functions
* pass locale and timezone with form user
* pass formData instead of responses
* pass timeFormat and locale
* reusable function for email sending and reminder creation
* implement scheduleEmailReminderForForm
* remove added editor field from merge conflict
* don't support cal.ai action with form triggers
* throw bad request if form trigger and cal.ai is combined
* add tests for scheduleFormWorkflows
* add form submission tests
* remove form response varibe info
* clean up workflow actions
* fixes for getting template options
* pass triggerType to getAllWorkflows
* move reusable logic to scheduleSMSReminder
* add formdata to param type
* type fixes for text reminder managers
* implement scheduleSMSReminderForForm
* fix import
* fix isAuthorizedToAddActiveOnIds
* disble whatsapp action
* implement triggerFormSubmittedNoEventWorkflow
* code clean up
* Merge branch 'devin/1755107037-add-workflow-triggers' into feat/routing-form-workflow-triggers
* fix type errors
* remove async from getSubmitterEmail
* fix type errors
* revert cal.ai changes
* fix type error
* add sublogger
* code clean up
* fix type errors
* remove label for attendee whatsapp action
* code clean up
* fixes saving teams on org workflows
* fix type error
* code improvements for activeOn ids
* Revert "code improvements for activeOn ids"
This reverts commit 0a3590a4e2ce541b17d63483ad86ed458795a6a3.
* improve variable name
* fix unit tests
* small fixes
* type fixes
* remove unused translation keys
* fix merge conflict issues
* code clean up
* remove SMS action support
* remove more SMS code
* add missing imports
* set custom template for form action
* type fixes
* fix tasker endpoint
* fix duplicate check
* fix workfows.test.ts
* use repository funciton to getHideBranding
* code clean up
* fix hasDuplicateSubmission
* code clean up
* select only needed properties
* remove repository functions
* Revert "remove repository functions"
This reverts commit 7aa47b1c59c9abd7f964ebf26f746934c53a44f4.
* add scheduleWorkflows function
* Revert "add scheduleWorkflows function"
This reverts commit fe5db4fe3b65e2743c95475d585300cab98beed7.
* move type to /types
* Revert "move type to /types"
This reverts commit 91e0152154594b3772a801a426260068a8ccea54.
* revert changes causing type errors
* remove import
* remove unused import
* Revert "remove unused import"
This reverts commit 1916768c875ea5d0ac5598ccb8f9c796c5622dc9.
* revert changed from attempt to fix type errors
* pass object to gt all workflows
* fix isAuthorized check
* trigger filtering
* remove form submitted no event booked code
* remove form submitted no event from schema
* remove more code
* remove test
* fixes
* add getSubmitterEmail function
* add missing workflow DTOs
* small fixes
* use activeOnWithChildren
* fix active on when switching trigger type
* remove add variable dropdown
* add getAllWorkflowsFromRoutingForm to WorkflowService
* fix error caused by undefined evt
* fix type error
* fix type error
* fix tests
* code clean up
* remove console.log
* remove template text form from triggers
* add routing form repoditory function
* fix bug with key
* add missing trigger in update-workflow.input.ts
* ForEvt and ForForm function for aiPhoneCallManager
* chore: add support for form workflows on api v2
* fixup! chore: add support for form workflows on api v2
* use only repository functions in update handler
* move all prisma queries from list.handler
* review suggestions
* chore: handle workflows api v2
* chore: handle workflows api v2, split in 2 endpoints
* fix workflow step creation
* remove connect agent and fixes types
* add type to workflow
* chore: use workflow type in apiv2 WorkflowsOutputService
* update worklfow type on update
* chore: use workflow type in apiv2 WorkflowsOutputService
* fix template body for torm trigger
* some UI fixes for email subject/body
* resetting email body when changing form triggers
* use type field to query workflows
* clean up all old active on values
* remove responseId from all funciton calls
* remove undefined from updateTemplate
* refactor: split routing form and event-type workflows code
* refactor: split routing form and event-type workflows code
* fix template text when adding action
* chore: don't rename WorkflowActivationDto to avoid ci blocking
* refine update schedule to use only allowed actions
* fix type error
* don't allow whatsapp action with form trigger
* fix type error
* return early if activeOn array is empty
* fix: from step type in BaseFormWorkflowStepDto
* fixup! fix: from step type in BaseFormWorkflowStepDto
* move all prisma calls to repository (service/workflows.ts)
* use FORM_TRIGGER_WORKFLOW_EVENTS for form queries
* use userRepository
* use FORM_TRIGGER_WORKFLOW_EVENTS in isFormTrigger
* code clean up
* code clean up
* add back trpc import
* fix agent repository functions
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: [email protected] <[email protected]>
Co-authored-by: Amit Sharma <[email protected]>
Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Benny Joo <[email protected]>
Co-authored-by: cal.com <[email protected]>
Co-authored-by: Morgan <[email protected]>
This commit is contained in:
69 files changed
+5401
-2034
No files matched your search
@@ -6,6 +6,7 @@ import { buildDryRunBooking } from "../../handleNewBooking";
|
||||
|
||||
vi.mock("@calcom/prisma", () => ({
|
||||
default: {}, // empty object as default export
|
||||
prisma: {},
|
||||
}));
|
||||
|
||||
describe("buildDryRunBooking", () => {
|
||||
|
||||
+1
@@ -12,6 +12,7 @@ vi.mock("@calcom/lib/server/i18n", () => ({
|
||||
vi.mock("@calcom/prisma", () => {
|
||||
return {
|
||||
default: vi.fn(),
|
||||
prisma: {},
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ import PhoneInput from "@calcom/features/components/phone-input";
|
||||
import { SENDER_ID, SENDER_NAME } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { WorkflowActions } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { DialogContent, DialogFooter, DialogClose } from "@calcom/ui/components/dialog";
|
||||
import { EmailField } from "@calcom/ui/components/form";
|
||||
@@ -35,6 +34,13 @@ interface IAddActionDialog {
|
||||
senderId?: string,
|
||||
senderName?: string
|
||||
) => void;
|
||||
actionOptions: {
|
||||
label: string;
|
||||
value: WorkflowActions;
|
||||
needsCredits: boolean;
|
||||
creditsTeamId?: number;
|
||||
isOrganization?: boolean;
|
||||
}[];
|
||||
}
|
||||
|
||||
interface ISelectActionOption {
|
||||
@@ -52,11 +58,10 @@ type AddActionFormValues = {
|
||||
|
||||
export const AddActionDialog = (props: IAddActionDialog) => {
|
||||
const { t } = useLocale();
|
||||
const { isOpenDialog, setIsOpenDialog, addAction } = props;
|
||||
const { isOpenDialog, setIsOpenDialog, addAction, actionOptions } = props;
|
||||
const [isPhoneNumberNeeded, setIsPhoneNumberNeeded] = useState(false);
|
||||
const [isSenderIdNeeded, setIsSenderIdNeeded] = useState(false);
|
||||
const [isEmailAddressNeeded, setIsEmailAddressNeeded] = useState(false);
|
||||
const { data: actionOptions } = trpc.viewer.workflows.getWorkflowActionOptions.useQuery();
|
||||
|
||||
const formSchema = z.object({
|
||||
action: z.enum(WORKFLOW_ACTIONS),
|
||||
@@ -165,9 +170,7 @@ export const AddActionDialog = (props: IAddActionDialog) => {
|
||||
menuPlacement="bottom"
|
||||
defaultValue={actionOptions[0]}
|
||||
onChange={handleSelectAction}
|
||||
options={actionOptions.map((option) => ({
|
||||
...option,
|
||||
}))}
|
||||
options={actionOptions}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
|
||||
@@ -6,16 +6,20 @@ import type { UseFormReturn } from "react-hook-form";
|
||||
import { SENDER_ID, SENDER_NAME, SCANNING_WORKFLOW_STEPS } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { WorkflowPermissions } from "@calcom/lib/server/repository/workflow-permissions";
|
||||
import type { WorkflowActions } from "@calcom/prisma/enums";
|
||||
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
|
||||
import { WorkflowActions } from "@calcom/prisma/enums";
|
||||
import { WorkflowTemplates } from "@calcom/prisma/enums";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { FormCard, FormCardBody } from "@calcom/ui/components/card";
|
||||
import type { MultiSelectCheckboxesOptionType as Option } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
|
||||
import { useAgentsData } from "../hooks/useAgentsData";
|
||||
import { isCalAIAction, isSMSAction } from "../lib/actionHelperFunctions";
|
||||
import { isCalAIAction, isFormTrigger, isSMSAction } from "../lib/actionHelperFunctions";
|
||||
import { ALLOWED_FORM_WORKFLOW_ACTIONS } from "../lib/constants";
|
||||
import emailReminderTemplate from "../lib/reminders/templates/emailReminderTemplate";
|
||||
import type { FormValues } from "../pages/workflow";
|
||||
import { AddActionDialog } from "./AddActionDialog";
|
||||
import WorkflowStepContainer from "./WorkflowStepContainer";
|
||||
@@ -38,16 +42,56 @@ interface Props {
|
||||
export default function WorkflowDetailsPage(props: Props) {
|
||||
const { form, workflowId, selectedOptions, setSelectedOptions, teamId, isOrg, allOptions, permissions } =
|
||||
props;
|
||||
const { t } = useLocale();
|
||||
const { t, i18n } = useLocale();
|
||||
|
||||
const [isAddActionDialogOpen, setIsAddActionDialogOpen] = useState(false);
|
||||
const [isDeleteStepDialogOpen, setIsDeleteStepDialogOpen] = useState(false);
|
||||
|
||||
const [reload, setReload] = useState(false);
|
||||
const [updateTemplate, setUpdateTemplate] = useState(false);
|
||||
|
||||
const searchParams = useSearchParams();
|
||||
const eventTypeId = searchParams?.get("eventTypeId");
|
||||
|
||||
// Get base action options and transform them for form triggers
|
||||
const { data: baseActionOptions } = trpc.viewer.workflows.getWorkflowActionOptions.useQuery();
|
||||
|
||||
const transformedActionOptions = baseActionOptions
|
||||
? baseActionOptions
|
||||
.filter((option) => {
|
||||
const isFormWorkflowWithInvalidSteps =
|
||||
isFormTrigger(form.getValues("trigger")) &&
|
||||
!ALLOWED_FORM_WORKFLOW_ACTIONS.some((action) => action === option.value);
|
||||
|
||||
const isSelectAllCalAiAction = isCalAIAction(option.value) && form.watch("selectAll");
|
||||
|
||||
const isOrgCalAiAction = isCalAIAction(option.value) && isOrg;
|
||||
|
||||
if (isFormWorkflowWithInvalidSteps || isSelectAllCalAiAction || isOrgCalAiAction) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.map((option) => {
|
||||
let label = option.label;
|
||||
|
||||
// Transform labels for form triggers
|
||||
if (isFormTrigger(form.getValues("trigger"))) {
|
||||
if (option.value === WorkflowActions.EMAIL_ATTENDEE) {
|
||||
label = t("email_attendee_action_form");
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...option,
|
||||
label,
|
||||
creditsTeamId: teamId,
|
||||
isOrganization: isOrg,
|
||||
isCalAi: isCalAIAction(option.value),
|
||||
};
|
||||
})
|
||||
: [];
|
||||
|
||||
useEffect(() => {
|
||||
const matchingOption = allOptions.find((option) => option.value === eventTypeId);
|
||||
if (matchingOption && !selectedOptions.find((option) => option.value === eventTypeId)) {
|
||||
@@ -55,7 +99,6 @@ export default function WorkflowDetailsPage(props: Props) {
|
||||
setSelectedOptions(newOptions);
|
||||
form.setValue("activeOn", newOptions);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [eventTypeId]);
|
||||
|
||||
const addAction = (
|
||||
@@ -73,6 +116,23 @@ export default function WorkflowDetailsPage(props: Props) {
|
||||
})[0].id - 1
|
||||
: 0;
|
||||
|
||||
const timeFormat = getTimeFormatStringFromUserTimeFormat(props.user.timeFormat);
|
||||
|
||||
const template = isFormTrigger(form.getValues("trigger"))
|
||||
? WorkflowTemplates.CUSTOM
|
||||
: WorkflowTemplates.REMINDER;
|
||||
|
||||
const { emailBody: reminderBody, emailSubject } =
|
||||
template !== WorkflowTemplates.CUSTOM
|
||||
? emailReminderTemplate({
|
||||
isEditingMode: true,
|
||||
locale: i18n.language,
|
||||
t,
|
||||
action,
|
||||
timeFormat,
|
||||
})
|
||||
: { emailBody: null, emailSubject: null };
|
||||
|
||||
const step = {
|
||||
id: id > 0 ? 0 : id, //id of new steps always <= 0
|
||||
action,
|
||||
@@ -84,9 +144,9 @@ export default function WorkflowDetailsPage(props: Props) {
|
||||
: 1,
|
||||
sendTo: sendTo || null,
|
||||
workflowId: workflowId,
|
||||
reminderBody: null,
|
||||
emailSubject: null,
|
||||
template: WorkflowTemplates.REMINDER,
|
||||
reminderBody,
|
||||
emailSubject,
|
||||
template,
|
||||
numberRequired: numberRequired || false,
|
||||
sender: isSMSAction(action) ? sender || SENDER_ID : SENDER_ID,
|
||||
senderName: !isSMSAction(action) ? senderName || SENDER_NAME : SENDER_NAME,
|
||||
@@ -128,6 +188,9 @@ export default function WorkflowDetailsPage(props: Props) {
|
||||
isOrganization={isOrg}
|
||||
allOptions={allOptions}
|
||||
onSaveWorkflow={props.onSaveWorkflow}
|
||||
actionOptions={transformedActionOptions}
|
||||
updateTemplate={updateTemplate}
|
||||
setUpdateTemplate={setUpdateTemplate}
|
||||
/>
|
||||
</FormCardBody>
|
||||
</FormCard>
|
||||
@@ -205,6 +268,9 @@ export default function WorkflowDetailsPage(props: Props) {
|
||||
inboundAgentData={inboundAgentData}
|
||||
isInboundAgentLoading={isInboundAgentLoading}
|
||||
allOptions={allOptions}
|
||||
actionOptions={transformedActionOptions}
|
||||
updateTemplate={updateTemplate}
|
||||
setUpdateTemplate={setUpdateTemplate}
|
||||
/>
|
||||
</FormCardBody>
|
||||
</FormCard>
|
||||
@@ -234,6 +300,7 @@ export default function WorkflowDetailsPage(props: Props) {
|
||||
isOpenDialog={isAddActionDialogOpen}
|
||||
setIsOpenDialog={setIsAddActionDialogOpen}
|
||||
addAction={addAction}
|
||||
actionOptions={transformedActionOptions}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useParams, useRouter, useSearchParams } from "next/navigation";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useEffect, useRef, useState, useCallback } from "react";
|
||||
import type { UseFormReturn } from "react-hook-form";
|
||||
import { Controller } from "react-hook-form";
|
||||
import { Controller, useWatch } from "react-hook-form";
|
||||
import "react-phone-number-input/style.css";
|
||||
|
||||
import type { RetellAgentWithDetails } from "@calcom/features/calAIPhone/providers/retellAI";
|
||||
@@ -60,6 +60,8 @@ import {
|
||||
shouldScheduleEmailReminder,
|
||||
isSMSOrWhatsappAction,
|
||||
isCalAIAction,
|
||||
isFormTrigger,
|
||||
hasCalAIAction,
|
||||
} from "../lib/actionHelperFunctions";
|
||||
import { DYNAMIC_TEXT_VARIABLES } from "../lib/constants";
|
||||
import { getWorkflowTemplateOptions, getWorkflowTriggerOptions } from "../lib/getOptions";
|
||||
@@ -92,6 +94,16 @@ type WorkflowStepProps = {
|
||||
isDeleteStepDialogOpen?: boolean;
|
||||
agentData?: RetellAgentWithDetails;
|
||||
isAgentLoading?: boolean;
|
||||
actionOptions: {
|
||||
label: string;
|
||||
value: WorkflowActions;
|
||||
needsCredits: boolean;
|
||||
creditsTeamId?: number;
|
||||
isOrganization: boolean;
|
||||
isCalAi: boolean;
|
||||
}[];
|
||||
updateTemplate: boolean;
|
||||
setUpdateTemplate: Dispatch<SetStateAction<boolean>>;
|
||||
inboundAgentData?: RetellAgentWithDetails;
|
||||
isInboundAgentLoading?: boolean;
|
||||
};
|
||||
@@ -103,26 +115,24 @@ const getTimeSectionText = (trigger: WorkflowTriggerEvents, t: TFunction) => {
|
||||
[WorkflowTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW]: "how_long_after_hosts_no_show",
|
||||
[WorkflowTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW]: "how_long_after_guests_no_show",
|
||||
};
|
||||
if (!triggerMap[trigger]) return null;
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
return t(triggerMap[trigger]!);
|
||||
return triggerMap[trigger] ? t(triggerMap[trigger]) : null;
|
||||
};
|
||||
|
||||
const CalAIAgentDataSkeleton = () => {
|
||||
return (
|
||||
<div className="bg-muted mt-4 rounded-lg p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="p-4 mt-4 rounded-lg bg-muted">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<SkeletonText className="h-5 w-28" />
|
||||
<div className="mt-2 flex items-center gap-2">
|
||||
<SkeletonText className="h-4 w-4" />
|
||||
<SkeletonText className="h-4 w-32" />
|
||||
<SkeletonText className="h-5 w-12" />
|
||||
<SkeletonText className="w-28 h-5" />
|
||||
<div className="flex gap-2 items-center mt-2">
|
||||
<SkeletonText className="w-4 h-4" />
|
||||
<SkeletonText className="w-32 h-4" />
|
||||
<SkeletonText className="w-12 h-5" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<SkeletonText className="h-8 w-24" />
|
||||
<SkeletonText className="h-8 w-8" />
|
||||
<div className="flex gap-1 items-center">
|
||||
<SkeletonText className="w-24 h-8" />
|
||||
<SkeletonText className="w-8 h-8" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -164,6 +174,9 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
isDeleteStepDialogOpen,
|
||||
setIsDeleteStepDialogOpen,
|
||||
onSaveWorkflow,
|
||||
actionOptions,
|
||||
updateTemplate,
|
||||
setUpdateTemplate,
|
||||
} = props;
|
||||
const { data: _verifiedNumbers } = trpc.viewer.workflows.getVerifiedNumbers.useQuery(
|
||||
{ teamId },
|
||||
@@ -258,7 +271,6 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
WorkflowActions.SMS_NUMBER === action || WorkflowActions.WHATSAPP_NUMBER === action;
|
||||
const [isPhoneNumberNeeded, setIsPhoneNumberNeeded] = useState(requirePhoneNumber);
|
||||
|
||||
const [updateTemplate, setUpdateTemplate] = useState(false);
|
||||
const [firstRender, setFirstRender] = useState(true);
|
||||
|
||||
const senderNeeded =
|
||||
@@ -278,14 +290,18 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
: false
|
||||
);
|
||||
|
||||
const [timeSectionText, setTimeSectionText] = useState(getTimeSectionText(form.getValues("trigger"), t));
|
||||
const trigger = useWatch({
|
||||
control: form.control,
|
||||
name: "trigger",
|
||||
});
|
||||
|
||||
const [timeSectionText, setTimeSectionText] = useState(getTimeSectionText(trigger, t));
|
||||
const isCreatingAgent = useRef(false);
|
||||
const hasAutoCreated = useRef(false);
|
||||
|
||||
const handleCreateAgent = useCallback(
|
||||
async (templateWorkflowId?: string) => {
|
||||
if (isCreatingAgent.current || createAgentMutation.isPending) {
|
||||
console.log("Agent creation already in progress, skipping...");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -354,39 +370,24 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
handleCreateAgent,
|
||||
]);
|
||||
|
||||
const { data: actionOptions } = trpc.viewer.workflows.getWorkflowActionOptions.useQuery();
|
||||
const triggerOptions = getWorkflowTriggerOptions(t);
|
||||
const templateOptions = getWorkflowTemplateOptions(t, step?.action, hasActiveTeamPlan);
|
||||
if (step && !form.getValues(`steps.${step.stepNumber - 1}.reminderBody`)) {
|
||||
const action = form.getValues(`steps.${step.stepNumber - 1}.action`);
|
||||
const templateOptions = getWorkflowTemplateOptions(t, step?.action, hasActiveTeamPlan, trigger);
|
||||
|
||||
// Skip setting reminderBody for CAL_AI actions since they don't need email templates
|
||||
if (!isCalAIAction(action)) {
|
||||
const template = getTemplateBodyForAction({
|
||||
action,
|
||||
locale: i18n.language,
|
||||
t,
|
||||
template: step.template ?? WorkflowTemplates.REMINDER,
|
||||
timeFormat,
|
||||
});
|
||||
form.setValue(`steps.${step.stepNumber - 1}.reminderBody`, template);
|
||||
}
|
||||
}
|
||||
const steps = useWatch({
|
||||
control: form.control,
|
||||
name: "steps",
|
||||
});
|
||||
|
||||
if (step && !form.getValues(`steps.${step.stepNumber - 1}.emailSubject`)) {
|
||||
const action = form.getValues(`steps.${step.stepNumber - 1}.action`);
|
||||
// Skip setting emailSubject for CAL_AI actions since they don't need email subjects
|
||||
if (!isCalAIAction(action)) {
|
||||
const subjectTemplate = emailReminderTemplate({
|
||||
isEditingMode: true,
|
||||
locale: i18n.language,
|
||||
t,
|
||||
action: action,
|
||||
timeFormat,
|
||||
}).emailSubject;
|
||||
form.setValue(`steps.${step.stepNumber - 1}.emailSubject`, subjectTemplate);
|
||||
}
|
||||
}
|
||||
const hasAiAction = hasCalAIAction(steps);
|
||||
const hasSMSAction = steps.some((s) => isSMSAction(s.action));
|
||||
const hasWhatsappAction = steps.some((s) => isWhatsappAction(s.action));
|
||||
const hasEmailToHostAction = steps.some((s) => s.action === WorkflowActions.EMAIL_HOST);
|
||||
|
||||
const disallowFormTriggers = hasAiAction || hasSMSAction || hasEmailToHostAction || hasWhatsappAction;
|
||||
|
||||
const filteredTriggerOptions = triggerOptions.filter(
|
||||
(option) => !(isFormTrigger(option.value) && disallowFormTriggers)
|
||||
);
|
||||
|
||||
const { ref: emailSubjectFormRef, ...restEmailSubjectForm } = step
|
||||
? form.register(`steps.${step.stepNumber - 1}.emailSubject`)
|
||||
@@ -407,9 +408,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
const [numberVerified, setNumberVerified] = useState(getNumberVerificationStatus());
|
||||
const [emailVerified, setEmailVerified] = useState(getEmailVerificationStatus());
|
||||
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
useEffect(() => setNumberVerified(getNumberVerificationStatus()), [verifiedNumbers.length]);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
useEffect(() => setEmailVerified(getEmailVerificationStatus()), [verifiedEmails.length]);
|
||||
|
||||
const addVariableEmailSubject = (variable: string) => {
|
||||
@@ -465,11 +464,6 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
},
|
||||
});
|
||||
|
||||
const hasCalAIAction = () => {
|
||||
const steps = form.getValues("steps") || [];
|
||||
return steps.some((step) => isCalAIAction(step.action));
|
||||
};
|
||||
|
||||
const verifyEmailCodeMutation = trpc.viewer.workflows.verifyEmailCode.useMutation({
|
||||
onSuccess: (isVerified) => {
|
||||
showToast(isVerified ? t("verified_successfully") : t("wrong_code"), "success");
|
||||
@@ -513,7 +507,6 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
|
||||
//trigger
|
||||
if (!step) {
|
||||
const trigger = form.getValues("trigger");
|
||||
const triggerString = t(`${trigger.toLowerCase()}_trigger`);
|
||||
|
||||
const selectedTrigger = {
|
||||
@@ -524,7 +517,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
return (
|
||||
<>
|
||||
<div className="mb-3">
|
||||
<Label className="text-default text-sm leading-none">{t("when")}</Label>
|
||||
<Label className="text-sm leading-none text-default">{t("when")}</Label>
|
||||
<Controller
|
||||
name="trigger"
|
||||
control={form.control}
|
||||
@@ -538,7 +531,21 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
isDisabled={props.readOnly}
|
||||
onChange={(val) => {
|
||||
if (val) {
|
||||
const currentTrigger = form.getValues("trigger");
|
||||
const isCurrentFormTrigger = isFormTrigger(currentTrigger);
|
||||
const isNewFormTrigger = isFormTrigger(val.value);
|
||||
|
||||
form.setValue("trigger", val.value);
|
||||
|
||||
// Reset activeOn when switching between form and non-form triggers
|
||||
if (isCurrentFormTrigger !== isNewFormTrigger) {
|
||||
form.setValue("activeOn", []);
|
||||
if (setSelectedOptions) {
|
||||
setSelectedOptions([]);
|
||||
}
|
||||
form.setValue("selectAll", false);
|
||||
}
|
||||
|
||||
const newTimeSectionText = getTimeSectionText(val.value, t);
|
||||
if (newTimeSectionText) {
|
||||
setTimeSectionText(newTimeSectionText);
|
||||
@@ -557,10 +564,27 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
form.unregister("time");
|
||||
form.unregister("timeUnit");
|
||||
}
|
||||
if (isFormTrigger(val.value)) {
|
||||
const steps = form.getValues("steps");
|
||||
if (steps?.length) {
|
||||
const updatedSteps = steps.map((step) =>
|
||||
step.template === WorkflowTemplates.CUSTOM
|
||||
? step
|
||||
: {
|
||||
...step,
|
||||
reminderBody: " ",
|
||||
emailSubject: " ",
|
||||
template: WorkflowTemplates.CUSTOM,
|
||||
}
|
||||
);
|
||||
form.setValue("steps", updatedSteps);
|
||||
setUpdateTemplate(!updateTemplate);
|
||||
}
|
||||
}
|
||||
}
|
||||
}}
|
||||
defaultValue={selectedTrigger}
|
||||
options={triggerOptions}
|
||||
options={filteredTriggerOptions}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
@@ -568,8 +592,8 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
<div>
|
||||
{!!timeSectionText && (
|
||||
<div className="mb-3 mt-3">
|
||||
<Label className="text-default mb-0">{timeSectionText}</Label>
|
||||
<div className="mt-3 mb-3">
|
||||
<Label className="mb-0 text-default">{timeSectionText}</Label>
|
||||
<TimeTimeUnitInput disabled={props.readOnly} />
|
||||
</div>
|
||||
)}
|
||||
@@ -577,14 +601,16 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
{selectedOptions && setSelectedOptions && allOptions && (
|
||||
<div className={classNames(!!timeSectionText && "mb-3")}>
|
||||
{isOrganization ? (
|
||||
<div className="text-default flex items-center gap-2">
|
||||
<div className="flex gap-2 items-center text-default">
|
||||
<Label>{t("which_team_apply")}</Label>
|
||||
<div className="mb-2">
|
||||
<InfoBadge content={t("team_select_info")} />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<Label className="text-default mb-2 block">{t("which_event_type_apply")}</Label>
|
||||
<Label>
|
||||
{isFormTrigger(trigger) ? t("which_routing_form_apply") : t("which_event_type_apply")}
|
||||
</Label>
|
||||
)}
|
||||
<Controller
|
||||
name="activeOn"
|
||||
@@ -600,18 +626,30 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
setValue={(s: Option[]) => {
|
||||
form.setValue("activeOn", s);
|
||||
}}
|
||||
countText={isOrganization ? "count_team" : "nr_event_type"}
|
||||
countText={
|
||||
isOrganization
|
||||
? "count_team"
|
||||
: isFormTrigger(form.getValues("trigger"))
|
||||
? "nr_routing_form"
|
||||
: "nr_event_type"
|
||||
}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
{!hasCalAIAction() && (
|
||||
{!hasCalAIAction(steps) && (
|
||||
<div className="mt-1">
|
||||
<Controller
|
||||
name="selectAll"
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<CheckboxField
|
||||
description={isOrganization ? t("apply_to_all_teams") : t("apply_to_all_event_types")}
|
||||
description={
|
||||
isOrganization
|
||||
? t("apply_to_all_teams")
|
||||
: isFormTrigger(form.getValues("trigger"))
|
||||
? t("apply_to_all_routing_forms")
|
||||
: t("apply_to_all_event_types")
|
||||
}
|
||||
disabled={props.readOnly}
|
||||
descriptionClassName="ml-0"
|
||||
onChange={(e) => {
|
||||
@@ -630,7 +668,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
)}
|
||||
{!!timeSectionText && (
|
||||
<div className="mt-1 flex text-gray-500">
|
||||
<div className="flex mt-1 text-gray-500">
|
||||
<Icon name="info" className="mr-1 mt-0.5 h-4 w-4" />
|
||||
<p className="text-sm">{t("testing_sms_workflow_info_message")}</p>
|
||||
</div>
|
||||
@@ -750,21 +788,10 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
}
|
||||
}}
|
||||
defaultValue={selectedAction}
|
||||
options={actionOptions
|
||||
?.filter((option) => {
|
||||
if (
|
||||
(isCalAIAction(option.value) && form.watch("selectAll")) ||
|
||||
(isCalAIAction(option.value) && props.isOrganization)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
?.map((option) => ({
|
||||
...option,
|
||||
creditsTeamId: teamId ?? creditsTeamId,
|
||||
isOrganization: props.isOrganization,
|
||||
}))}
|
||||
options={actionOptions.map((option) => ({
|
||||
...option,
|
||||
creditsTeamId: teamId ?? creditsTeamId,
|
||||
}))}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
@@ -788,12 +815,12 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
/>
|
||||
<div className="mt-1.5 flex items-center gap-1">
|
||||
<Icon name="info" size="10" className="text-gray-500" />
|
||||
<div className="text-subtle text-xs">{t("sender_id_info")}</div>
|
||||
<div className="text-xs text-subtle">{t("sender_id_info")}</div>
|
||||
</div>
|
||||
</div>
|
||||
{form.formState.errors.steps &&
|
||||
form.formState?.errors?.steps[step.stepNumber - 1]?.sender && (
|
||||
<p className="text-error mt-1 text-xs">{t("sender_id_error_message")}</p>
|
||||
<p className="mt-1 text-xs text-error">{t("sender_id_error_message")}</p>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
@@ -812,23 +839,23 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
)}
|
||||
{isCalAIAction(form.getValues(`steps.${step.stepNumber - 1}.action`)) && !stepAgentId && (
|
||||
<div className="bg-muted border-muted mt-2 rounded-2xl border p-3">
|
||||
<div className="flex flex-col justify-between gap-4 sm:flex-row sm:items-center sm:gap-0">
|
||||
<div className="p-3 mt-2 rounded-2xl border bg-muted border-muted">
|
||||
<div className="flex flex-col gap-4 justify-between sm:flex-row sm:items-center sm:gap-0">
|
||||
<div>
|
||||
<h2 className="text-emphasis text-sm font-medium leading-none">
|
||||
<h2 className="text-sm font-medium leading-none text-emphasis">
|
||||
{t("cal_ai_agent")}
|
||||
<Badge startIcon="info" className="ms-2 rounded-md" variant="warning">
|
||||
<Badge startIcon="info" className="rounded-md ms-2" variant="warning">
|
||||
{t("set_up_required")}
|
||||
</Badge>
|
||||
</h2>
|
||||
<p className="text-muted mt-1 text-sm font-medium leading-none">
|
||||
<p className="mt-1 text-sm font-medium leading-none text-muted">
|
||||
{t("no_phone_number_connected")}.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
color="primary"
|
||||
disabled={props.readOnly || isCreatingAgent.current || hasAutoCreated.current}
|
||||
className="flex items-center justify-center"
|
||||
className="flex justify-center items-center"
|
||||
onClick={() => handleCreateAgent()}
|
||||
loading={createAgentMutation.isPending || isCreatingAgent.current}>
|
||||
{t("set_up_agent")}
|
||||
@@ -839,9 +866,9 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
|
||||
{stepAgentId && isAgentLoading && <CalAIAgentDataSkeleton />}
|
||||
{stepAgentId && agentData && (
|
||||
<div className="bg-muted mt-4 rounded-lg p-4">
|
||||
<div className="p-4 mt-4 rounded-lg bg-muted">
|
||||
<div
|
||||
className="flex cursor-pointer items-center justify-between"
|
||||
className="flex justify-between items-center cursor-pointer"
|
||||
onClick={(e) => {
|
||||
const target = e.target as HTMLElement;
|
||||
if (
|
||||
@@ -856,11 +883,11 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
}
|
||||
}}>
|
||||
<div>
|
||||
<h3 className="text-emphasis text-base font-medium">{t("cal_ai_agent")}</h3>
|
||||
<h3 className="text-base font-medium text-emphasis">{t("cal_ai_agent")}</h3>
|
||||
{arePhoneNumbersActive.length > 0 ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon name="phone" className="text-emphasis h-4 w-4" />
|
||||
<span className="text-emphasis text-sm">
|
||||
<div className="flex gap-2 items-center">
|
||||
<Icon name="phone" className="w-4 h-4 text-emphasis" />
|
||||
<span className="text-sm text-emphasis">
|
||||
{formatPhoneNumber(arePhoneNumbersActive[0].phoneNumber)}
|
||||
</span>
|
||||
<Badge variant="green" size="sm" withDot>
|
||||
@@ -868,12 +895,12 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</Badge>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-subtle text-sm">{t("no_phone_number_connected")}</span>
|
||||
<div className="flex gap-1 items-center">
|
||||
<span className="text-sm text-subtle">{t("no_phone_number_connected")}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="flex gap-1 items-center" onClick={(e) => e.stopPropagation()}>
|
||||
{arePhoneNumbersActive.length > 0 ? (
|
||||
<Dropdown>
|
||||
<DropdownMenuTrigger asChild>
|
||||
@@ -983,7 +1010,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
)}
|
||||
{isPhoneNumberNeeded && (
|
||||
<div className="bg-muted mt-2 rounded-md p-4 pt-0">
|
||||
<div className="p-4 pt-0 mt-2 rounded-md bg-muted">
|
||||
<Label className="pt-4">{t("custom_phone_number")}</Label>
|
||||
<div className="block sm:flex">
|
||||
<Controller
|
||||
@@ -1023,7 +1050,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
|
||||
{form.formState.errors.steps && form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo && (
|
||||
<p className="text-error mt-1 text-xs">
|
||||
<p className="mt-1 text-xs text-error">
|
||||
{form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo?.message || ""}
|
||||
</p>
|
||||
)}
|
||||
@@ -1034,9 +1061,9 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
) : (
|
||||
!props.readOnly && (
|
||||
<>
|
||||
<div className="mt-6 flex w-full flex-col">
|
||||
<div className="flex flex-col mt-6 w-full">
|
||||
<Label className="">{t("verification_code")}</Label>
|
||||
<div className="flex w-full items-center">
|
||||
<div className="flex items-center w-full">
|
||||
<TextField
|
||||
containerClassName="w-full"
|
||||
className="h-8 rounded-xl"
|
||||
@@ -1066,7 +1093,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
{form.formState.errors.steps &&
|
||||
form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo && (
|
||||
<p className="text-error mt-1 text-xs">
|
||||
<p className="mt-1 text-xs text-error">
|
||||
{form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo?.message || ""}
|
||||
</p>
|
||||
)}
|
||||
@@ -1096,9 +1123,9 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
)}
|
||||
{isEmailAddressNeeded && !isCalAIAction(form.getValues(`steps.${step.stepNumber - 1}.action`)) && (
|
||||
<div className="bg-muted border-muted mt-5 rounded-2xl border p-4">
|
||||
<div className="p-4 mt-5 rounded-2xl border bg-muted border-muted">
|
||||
<Label>{t("email_address")}</Label>
|
||||
<div className="block items-center gap-2 sm:flex">
|
||||
<div className="block gap-2 items-center sm:flex">
|
||||
<Controller
|
||||
name={`steps.${step.stepNumber - 1}.sendTo`}
|
||||
render={({ field: { value, onChange } }) => (
|
||||
@@ -1124,7 +1151,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
size="sm"
|
||||
disabled={emailVerified || props.readOnly || false}
|
||||
className={classNames(
|
||||
"min-w-fit text-sm font-medium",
|
||||
"text-sm font-medium min-w-fit",
|
||||
emailVerified ? "hidden" : "mt-3 sm:mt-0"
|
||||
)}
|
||||
onClick={() => {
|
||||
@@ -1138,7 +1165,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</Button>
|
||||
</div>
|
||||
{form.formState.errors.steps && form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo && (
|
||||
<p className="text-error mt-1 text-xs">
|
||||
<p className="mt-1 text-xs text-error">
|
||||
{form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo?.message || ""}
|
||||
</p>
|
||||
)}
|
||||
@@ -1149,9 +1176,9 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
) : (
|
||||
!props.readOnly && (
|
||||
<>
|
||||
<div className="mt-3 flex w-full flex-col">
|
||||
<div className="flex flex-col mt-3 w-full">
|
||||
<Label className="">{t("verification_code")}</Label>
|
||||
<div className="flex w-full items-center">
|
||||
<div className="flex items-center w-full">
|
||||
<TextField
|
||||
containerClassName="w-full"
|
||||
className="h-8 rounded-xl"
|
||||
@@ -1181,7 +1208,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
{form.formState.errors.steps &&
|
||||
form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo && (
|
||||
<p className="text-error mt-1 text-xs">
|
||||
<p className="mt-1 text-xs text-error">
|
||||
{form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo?.message || ""}
|
||||
</p>
|
||||
)}
|
||||
@@ -1205,19 +1232,20 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
onChange={(val) => {
|
||||
if (val) {
|
||||
const action = form.getValues(`steps.${step.stepNumber - 1}.action`);
|
||||
const value = val.value as WorkflowTemplates;
|
||||
|
||||
const template = getTemplateBodyForAction({
|
||||
action,
|
||||
locale: i18n.language,
|
||||
t,
|
||||
template: val.value ?? WorkflowTemplates.REMINDER,
|
||||
template: value ?? WorkflowTemplates.REMINDER,
|
||||
timeFormat,
|
||||
});
|
||||
|
||||
form.setValue(`steps.${step.stepNumber - 1}.reminderBody`, template);
|
||||
|
||||
if (shouldScheduleEmailReminder(action)) {
|
||||
if (val.value === WorkflowTemplates.REMINDER) {
|
||||
if (value === WorkflowTemplates.REMINDER) {
|
||||
form.setValue(
|
||||
`steps.${step.stepNumber - 1}.emailSubject`,
|
||||
emailReminderTemplate({
|
||||
@@ -1228,7 +1256,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
timeFormat,
|
||||
}).emailSubject
|
||||
);
|
||||
} else if (val.value === WorkflowTemplates.RATING) {
|
||||
} else if (value === WorkflowTemplates.RATING) {
|
||||
form.setValue(
|
||||
`steps.${step.stepNumber - 1}.emailSubject`,
|
||||
emailRatingTemplate({
|
||||
@@ -1241,8 +1269,8 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
);
|
||||
}
|
||||
}
|
||||
field.onChange(val.value);
|
||||
form.setValue(`steps.${step.stepNumber - 1}.template`, val.value);
|
||||
field.onChange(value);
|
||||
form.setValue(`steps.${step.stepNumber - 1}.template`, value);
|
||||
setUpdateTemplate(!updateTemplate);
|
||||
}
|
||||
}}
|
||||
@@ -1255,10 +1283,11 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
option.needsTeamsUpgrade &&
|
||||
!isSMSAction(form.getValues(`steps.${step.stepNumber - 1}.action`)),
|
||||
}))}
|
||||
//eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
isOptionDisabled={(option: { label: string; value: any; needsTeamsUpgrade: boolean }) =>
|
||||
option.needsTeamsUpgrade
|
||||
}
|
||||
isOptionDisabled={(option: {
|
||||
label: string;
|
||||
value: string;
|
||||
needsTeamsUpgrade: boolean;
|
||||
}) => option.needsTeamsUpgrade}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
@@ -1266,14 +1295,18 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
)}
|
||||
{!isCalAIAction(form.getValues(`steps.${step.stepNumber - 1}.action`)) && (
|
||||
<div className="bg-muted border-muted mt-3 rounded-2xl border p-3">
|
||||
<div className="p-3 mt-3 rounded-2xl border bg-muted border-muted">
|
||||
{isEmailSubjectNeeded && (
|
||||
<div className="mb-6">
|
||||
<div className="flex items-center">
|
||||
<Label className={classNames("flex-none", props.readOnly ? "mb-2" : "mb-0")}>
|
||||
<Label
|
||||
className={classNames(
|
||||
"flex-none",
|
||||
props.readOnly || isFormTrigger(trigger) ? "mb-2" : "mb-0"
|
||||
)}>
|
||||
{t("email_subject")}
|
||||
</Label>
|
||||
{!props.readOnly && (
|
||||
{!props.readOnly && !isFormTrigger(trigger) && (
|
||||
<div className="flex-grow text-right">
|
||||
<AddVariablesDropdown
|
||||
addVariable={addVariableEmailSubject}
|
||||
@@ -1295,26 +1328,24 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
/>
|
||||
{form.formState.errors.steps &&
|
||||
form.formState?.errors?.steps[step.stepNumber - 1]?.emailSubject && (
|
||||
<p className="text-error mt-1 text-xs">
|
||||
<p className="mt-1 text-xs text-error">
|
||||
{form.formState?.errors?.steps[step.stepNumber - 1]?.emailSubject?.message || ""}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="mb-2 flex items-center pb-1">
|
||||
<Label className="mb-0 flex-none">
|
||||
<div className="flex items-center pb-1 mb-2">
|
||||
<Label className="flex-none mb-0">
|
||||
{isEmailSubjectNeeded ? t("email_body") : t("text_message")}
|
||||
</Label>
|
||||
</div>
|
||||
<Editor
|
||||
getText={() => {
|
||||
return props.form.getValues(`steps.${step.stepNumber - 1}.reminderBody`) || "";
|
||||
}}
|
||||
getText={() => props.form.getValues(`steps.${step.stepNumber - 1}.reminderBody`) || ""}
|
||||
setText={(text: string) => {
|
||||
props.form.setValue(`steps.${step.stepNumber - 1}.reminderBody`, text);
|
||||
props.form.clearErrors();
|
||||
}}
|
||||
variables={DYNAMIC_TEXT_VARIABLES}
|
||||
variables={!isFormTrigger(trigger) ? DYNAMIC_TEXT_VARIABLES : undefined}
|
||||
addVariableButtonTop={isSMSAction(step.action)}
|
||||
height="200px"
|
||||
updateTemplate={updateTemplate}
|
||||
@@ -1333,7 +1364,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
|
||||
{form.formState.errors.steps &&
|
||||
form.formState?.errors?.steps[step.stepNumber - 1]?.reminderBody && (
|
||||
<p className="text-error mt-1 text-sm">
|
||||
<p className="mt-1 text-sm text-error">
|
||||
{form.formState?.errors?.steps[step.stepNumber - 1]?.reminderBody?.message || ""}
|
||||
</p>
|
||||
)}
|
||||
@@ -1358,12 +1389,12 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{!props.readOnly && (
|
||||
<div className="ml-1 mt-2">
|
||||
{!props.readOnly && !isFormTrigger(trigger) && (
|
||||
<div className="mt-2 ml-1">
|
||||
<button type="button" onClick={() => setIsAdditionalInputsDialogOpen(true)}>
|
||||
<div className="text-subtle ml-1 flex items-center gap-2">
|
||||
<Icon name="circle-help" className="h-3 w-3" />
|
||||
<p className="text-left text-xs">{t("using_booking_questions_as_variables")}</p>
|
||||
<div className="flex gap-2 items-center ml-1 text-subtle">
|
||||
<Icon name="circle-help" className="w-3 h-3" />
|
||||
<p className="text-xs text-left">{t("using_booking_questions_as_variables")}</p>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
@@ -1472,23 +1503,23 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
<DialogContent enableOverflow type="creation" className="sm:max-w-[610px]">
|
||||
<div>
|
||||
<h1 className="w-full text-xl font-semibold">{t("how_booking_questions_as_variables")}</h1>
|
||||
<div className="bg-muted-3 mb-6 rounded-md sm:p-4">
|
||||
<p className="test-sm font-medium">{t("format")}</p>
|
||||
<ul className="text-emphasis ml-5 mt-2 list-disc">
|
||||
<div className="mb-6 rounded-md bg-muted-3 sm:p-4">
|
||||
<p className="font-medium test-sm">{t("format")}</p>
|
||||
<ul className="mt-2 ml-5 list-disc text-emphasis">
|
||||
<li>{t("uppercase_for_letters")}</li>
|
||||
<li>{t("replace_whitespaces_underscores")}</li>
|
||||
<li>{t("ignore_special_characters_booking_questions")}</li>
|
||||
</ul>
|
||||
<div className="mt-4">
|
||||
<p className="test-sm w-full font-medium">{t("example_1")}</p>
|
||||
<div className="mt-2 grid grid-cols-12">
|
||||
<div className="test-sm text-default col-span-5 ltr:mr-2 rtl:ml-2">
|
||||
<p className="w-full font-medium test-sm">{t("example_1")}</p>
|
||||
<div className="grid grid-cols-12 mt-2">
|
||||
<div className="col-span-5 test-sm text-default ltr:mr-2 rtl:ml-2">
|
||||
{t("booking_question_identifier")}
|
||||
</div>
|
||||
<div className="test-sm text-emphasis col-span-7">{t("company_size")}</div>
|
||||
<div className="test-sm text-default col-span-5 w-full">{t("variable")}</div>
|
||||
<div className="col-span-7 test-sm text-emphasis">{t("company_size")}</div>
|
||||
<div className="col-span-5 w-full test-sm text-default">{t("variable")}</div>
|
||||
|
||||
<div className="test-sm text-emphasis col-span-7 break-words">
|
||||
<div className="col-span-7 break-words test-sm text-emphasis">
|
||||
{" "}
|
||||
{`{${t("company_size")
|
||||
.replace(/[^a-zA-Z0-9 ]/g, "")
|
||||
@@ -1499,14 +1530,14 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
<p className="test-sm w-full font-medium">{t("example_2")}</p>
|
||||
<div className="mt-2 grid grid-cols-12">
|
||||
<div className="test-sm text-default col-span-5 ltr:mr-2 rtl:ml-2">
|
||||
<p className="w-full font-medium test-sm">{t("example_2")}</p>
|
||||
<div className="grid grid-cols-12 mt-2">
|
||||
<div className="col-span-5 test-sm text-default ltr:mr-2 rtl:ml-2">
|
||||
{t("booking_question_identifier")}
|
||||
</div>
|
||||
<div className="test-sm text-emphasis col-span-7">{t("what_help_needed")}</div>
|
||||
<div className="test-sm text-default col-span-5">{t("variable")}</div>
|
||||
<div className="test-sm text-emphasis col-span-7 break-words">
|
||||
<div className="col-span-7 test-sm text-emphasis">{t("what_help_needed")}</div>
|
||||
<div className="col-span-5 test-sm text-default">{t("variable")}</div>
|
||||
<div className="col-span-7 break-words test-sm text-emphasis">
|
||||
{" "}
|
||||
{`{${t("what_help_needed")
|
||||
.replace(/[^a-zA-Z0-9 ]/g, "")
|
||||
@@ -1576,17 +1607,17 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
<Dialog open={isUnsubscribeDialogOpen} onOpenChange={setIsUnsubscribeDialogOpen}>
|
||||
<DialogContent type="creation" title={t("unsubscribe_phone_number")}>
|
||||
<div className="space-y-4">
|
||||
<p className="text-default text-sm">{t("do_you_still_want_to_unsubscribe")}</p>
|
||||
<p className="text-sm text-default">{t("do_you_still_want_to_unsubscribe")}</p>
|
||||
{getActivePhoneNumbers(
|
||||
agentData?.outboundPhoneNumbers?.map((phone) => ({
|
||||
...phone,
|
||||
subscriptionStatus: phone.subscriptionStatus ?? undefined,
|
||||
}))
|
||||
).length > 0 && (
|
||||
<div className="bg-muted rounded-lg p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon name="phone" className="text-emphasis h-4 w-4" />
|
||||
<span className="text-emphasis text-sm font-medium">
|
||||
<div className="p-3 rounded-lg bg-muted">
|
||||
<div className="flex gap-2 items-center">
|
||||
<Icon name="phone" className="w-4 h-4 text-emphasis" />
|
||||
<span className="text-sm font-medium text-emphasis">
|
||||
{formatPhoneNumber(
|
||||
getActivePhoneNumbers(
|
||||
agentData?.outboundPhoneNumbers?.map((phone) => ({
|
||||
@@ -1599,7 +1630,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-subtle text-sm">{t("the_action_will_disconnect_phone_number")}</p>
|
||||
<p className="text-sm text-subtle">{t("the_action_will_disconnect_phone_number")}</p>
|
||||
</div>
|
||||
<DialogFooter showDivider>
|
||||
<Button type="button" color="secondary" onClick={() => setIsUnsubscribeDialogOpen(false)}>
|
||||
@@ -1634,7 +1665,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
<Dialog open={isDeleteStepDialogOpen} onOpenChange={setIsDeleteStepDialogOpen}>
|
||||
<DialogContent type="confirmation" title={t("delete_workflow_step")}>
|
||||
<div className="space-y-4">
|
||||
<p className="text-default text-sm">{t("are_you_sure_you_want_to_delete_workflow_step")}</p>
|
||||
<p className="text-sm text-default">{t("are_you_sure_you_want_to_delete_workflow_step")}</p>
|
||||
{(() => {
|
||||
const relevantPhoneNumbers =
|
||||
agentData?.outboundPhoneNumbers?.filter(
|
||||
@@ -1644,12 +1675,12 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
return (
|
||||
relevantPhoneNumbers.length > 0 && (
|
||||
<>
|
||||
<div className="bg-attention rounded-lg p-3">
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="p-3 rounded-lg bg-attention">
|
||||
<div className="flex gap-2 items-start">
|
||||
<Icon name="info" className="text-attention mt-0.5 h-4 w-4" />
|
||||
<div className="space-y-2">
|
||||
<p className="text-attention text-sm font-medium">{t("this_action_will_also")}</p>
|
||||
<ul className="text-attention list-inside list-disc space-y-1 text-sm">
|
||||
<p className="text-sm font-medium text-attention">{t("this_action_will_also")}</p>
|
||||
<ul className="space-y-1 text-sm list-disc list-inside text-attention">
|
||||
{relevantPhoneNumbers.some(
|
||||
(phone) => phone.subscriptionStatus === PhoneNumberSubscriptionStatus.ACTIVE
|
||||
) && <li>{t("cancel_your_phone_number_subscription")}</li>}
|
||||
@@ -1659,10 +1690,10 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
</div>
|
||||
</div>
|
||||
{relevantPhoneNumbers.map((phone) => (
|
||||
<div key={phone.phoneNumber} className="bg-muted rounded-lg p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon name="phone" className="text-emphasis h-4 w-4" />
|
||||
<span className="text-emphasis text-sm font-medium">
|
||||
<div key={phone.phoneNumber} className="p-3 rounded-lg bg-muted">
|
||||
<div className="flex gap-2 items-center">
|
||||
<Icon name="phone" className="w-4 h-4 text-emphasis" />
|
||||
<span className="text-sm font-medium text-emphasis">
|
||||
{formatPhoneNumber(phone.phoneNumber)}
|
||||
</span>
|
||||
{phone.subscriptionStatus === PhoneNumberSubscriptionStatus.ACTIVE && (
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
import type { TimeFormat } from "@calcom/lib/timeFormat";
|
||||
import type { WorkflowTriggerEvents } from "@calcom/prisma/client";
|
||||
import { WorkflowActions, WorkflowTemplates } from "@calcom/prisma/enums";
|
||||
import { WorkflowActions, WorkflowTemplates, WorkflowTriggerEvents } from "@calcom/prisma/enums";
|
||||
|
||||
import {
|
||||
whatsappEventCancelledTemplate,
|
||||
@@ -10,9 +9,11 @@ import {
|
||||
whatsappEventRescheduledTemplate,
|
||||
whatsappReminderTemplate,
|
||||
} from "../lib/reminders/templates/whatsapp";
|
||||
import { FORM_TRIGGER_WORKFLOW_EVENTS } from "./constants";
|
||||
import emailRatingTemplate from "./reminders/templates/emailRatingTemplate";
|
||||
import emailReminderTemplate from "./reminders/templates/emailReminderTemplate";
|
||||
import smsReminderTemplate from "./reminders/templates/smsReminderTemplate";
|
||||
import type { WorkflowStep } from "./types";
|
||||
|
||||
export function shouldScheduleEmailReminder(action: WorkflowActions) {
|
||||
return action === WorkflowActions.EMAIL_ATTENDEE || action === WorkflowActions.EMAIL_HOST;
|
||||
@@ -141,3 +142,11 @@ export function getTemplateBodyForAction({
|
||||
const templateFunction = getEmailTemplateFunction(template);
|
||||
return templateFunction({ isEditingMode: true, locale, t, action, timeFormat }).emailBody;
|
||||
}
|
||||
|
||||
export function isFormTrigger(trigger: WorkflowTriggerEvents) {
|
||||
return FORM_TRIGGER_WORKFLOW_EVENTS.includes(trigger);
|
||||
}
|
||||
|
||||
export function hasCalAIAction(steps: WorkflowStep[]) {
|
||||
return steps.some((step) => isCalAIAction(step.action));
|
||||
}
|
||||
@@ -8,6 +8,7 @@ export const WORKFLOW_TRIGGER_EVENTS = [
|
||||
WorkflowTriggerEvents.RESCHEDULE_EVENT,
|
||||
WorkflowTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW,
|
||||
WorkflowTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW,
|
||||
WorkflowTriggerEvents.FORM_SUBMITTED,
|
||||
WorkflowTriggerEvents.BOOKING_REJECTED,
|
||||
WorkflowTriggerEvents.BOOKING_REQUESTED,
|
||||
WorkflowTriggerEvents.BOOKING_PAYMENT_INITIATED,
|
||||
@@ -94,4 +95,12 @@ export const IMMEDIATE_WORKFLOW_TRIGGER_EVENTS: WorkflowTriggerEvents[] = [
|
||||
WorkflowTriggerEvents.BOOKING_PAYMENT_INITIATED,
|
||||
WorkflowTriggerEvents.BOOKING_REJECTED,
|
||||
WorkflowTriggerEvents.BOOKING_REQUESTED,
|
||||
WorkflowTriggerEvents.FORM_SUBMITTED,
|
||||
];
|
||||
|
||||
export const FORM_TRIGGER_WORKFLOW_EVENTS: WorkflowTriggerEvents[] = [WorkflowTriggerEvents.FORM_SUBMITTED];
|
||||
|
||||
export const ALLOWED_FORM_WORKFLOW_ACTIONS = [
|
||||
WorkflowActions.EMAIL_ATTENDEE,
|
||||
WorkflowActions.EMAIL_ADDRESS,
|
||||
] as const;
|
||||
@@ -1,4 +1,5 @@
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { WorkflowType } from "@calcom/prisma/client";
|
||||
|
||||
import type { Workflow } from "./types";
|
||||
|
||||
@@ -27,20 +28,31 @@ export const workflowSelect = {
|
||||
},
|
||||
};
|
||||
|
||||
export const getAllWorkflows = async (
|
||||
eventTypeWorkflows: Workflow[],
|
||||
userId?: number | null,
|
||||
teamId?: number | null,
|
||||
orgId?: number | null,
|
||||
workflowsLockedForUser = true
|
||||
) => {
|
||||
const allWorkflows = eventTypeWorkflows;
|
||||
export const getAllWorkflows = async ({
|
||||
entityWorkflows,
|
||||
userId,
|
||||
teamId,
|
||||
orgId,
|
||||
workflowsLockedForUser = true,
|
||||
type,
|
||||
}: {
|
||||
entityWorkflows: Workflow[];
|
||||
userId?: number | null;
|
||||
teamId?: number | null;
|
||||
orgId?: number | null;
|
||||
workflowsLockedForUser?: boolean;
|
||||
type: WorkflowType;
|
||||
}) => {
|
||||
const allWorkflows = entityWorkflows;
|
||||
|
||||
if (orgId) {
|
||||
if (teamId) {
|
||||
const orgTeamWorkflowsRel = await prisma.workflowsOnTeams.findMany({
|
||||
where: {
|
||||
teamId: teamId,
|
||||
workflow: {
|
||||
type,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
workflow: {
|
||||
@@ -54,6 +66,9 @@ export const getAllWorkflows = async (
|
||||
} else if (userId) {
|
||||
const orgUserWorkflowsRel = await prisma.workflowsOnTeams.findMany({
|
||||
where: {
|
||||
workflow: {
|
||||
type,
|
||||
},
|
||||
team: {
|
||||
members: {
|
||||
some: {
|
||||
@@ -79,6 +94,7 @@ export const getAllWorkflows = async (
|
||||
where: {
|
||||
teamId: orgId,
|
||||
isActiveOnAll: true,
|
||||
type,
|
||||
},
|
||||
select: workflowSelect,
|
||||
});
|
||||
@@ -90,6 +106,7 @@ export const getAllWorkflows = async (
|
||||
where: {
|
||||
teamId,
|
||||
isActiveOnAll: true,
|
||||
type,
|
||||
},
|
||||
select: workflowSelect,
|
||||
});
|
||||
@@ -102,6 +119,7 @@ export const getAllWorkflows = async (
|
||||
userId,
|
||||
teamId: null,
|
||||
isActiveOnAll: true,
|
||||
type,
|
||||
},
|
||||
select: workflowSelect,
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
isWhatsappAction,
|
||||
isEmailToAttendeeAction,
|
||||
isCalAIAction,
|
||||
isFormTrigger,
|
||||
} from "./actionHelperFunctions";
|
||||
import {
|
||||
WHATSAPP_WORKFLOW_TEMPLATES,
|
||||
@@ -45,22 +46,36 @@ export function getWorkflowTriggerOptions(t: TFunction) {
|
||||
});
|
||||
}
|
||||
|
||||
function convertToTemplateOptions(
|
||||
t: TFunction,
|
||||
hasPaidPlan: boolean,
|
||||
templates: readonly WorkflowTemplates[]
|
||||
) {
|
||||
return templates.map((template) => {
|
||||
return {
|
||||
label: t(`${template.toLowerCase()}`),
|
||||
value: template,
|
||||
needsTeamsUpgrade: !hasPaidPlan,
|
||||
} as { label: string; value: any; needsTeamsUpgrade: boolean };
|
||||
});
|
||||
}
|
||||
|
||||
export function getWorkflowTemplateOptions(
|
||||
t: TFunction,
|
||||
action: WorkflowActions | undefined,
|
||||
hasPaidPlan: boolean
|
||||
hasPaidPlan: boolean,
|
||||
trigger: WorkflowTriggerEvents
|
||||
) {
|
||||
if (isFormTrigger(trigger)) {
|
||||
return convertToTemplateOptions(t, hasPaidPlan, [WorkflowTemplates.CUSTOM]);
|
||||
}
|
||||
|
||||
const TEMPLATES =
|
||||
action && isWhatsappAction(action)
|
||||
? WHATSAPP_WORKFLOW_TEMPLATES
|
||||
: action && isEmailToAttendeeAction(action)
|
||||
? ATTENDEE_WORKFLOW_TEMPLATES
|
||||
: BASIC_WORKFLOW_TEMPLATES;
|
||||
return TEMPLATES.map((template) => {
|
||||
return {
|
||||
label: t(`${template.toLowerCase()}`),
|
||||
value: template,
|
||||
needsTeamsUpgrade: !hasPaidPlan && template == WorkflowTemplates.CUSTOM,
|
||||
};
|
||||
}) as { label: string; value: any; needsTeamsUpgrade: boolean }[];
|
||||
|
||||
return convertToTemplateOptions(t, hasPaidPlan, TEMPLATES);
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import tasker from "@calcom/features/tasker";
|
||||
import { WEBSITE_URL } from "@calcom/lib/constants";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { TimeUnit } from "@calcom/prisma/enums";
|
||||
import {
|
||||
@@ -20,6 +21,7 @@ import { bookingMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { getWorkflowRecipientEmail } from "../getWorkflowReminders";
|
||||
import { sendOrScheduleWorkflowEmails } from "./providers/emailProvider";
|
||||
import type { FormSubmissionData } from "./reminderScheduler";
|
||||
import type { AttendeeInBookingInfo, BookingInfo, timeUnitLowerCase } from "./smsReminderManager";
|
||||
import type { VariablesType } from "./templates/customTemplate";
|
||||
import customTemplate from "./templates/customTemplate";
|
||||
@@ -33,8 +35,7 @@ type ScheduleEmailReminderAction = Extract<
|
||||
"EMAIL_HOST" | "EMAIL_ATTENDEE" | "EMAIL_ADDRESS"
|
||||
>;
|
||||
|
||||
export interface ScheduleReminderArgs {
|
||||
evt: BookingInfo;
|
||||
export type ScheduleReminderArgs = {
|
||||
triggerEvent: WorkflowTriggerEvents;
|
||||
timeSpan: {
|
||||
time: number | null;
|
||||
@@ -44,10 +45,15 @@ export interface ScheduleReminderArgs {
|
||||
sender?: string | null;
|
||||
workflowStepId?: number;
|
||||
seatReferenceUid?: string;
|
||||
}
|
||||
} & (
|
||||
| { evt: BookingInfo; formData?: never }
|
||||
| {
|
||||
evt?: never;
|
||||
formData: FormSubmissionData;
|
||||
}
|
||||
);
|
||||
|
||||
interface scheduleEmailReminderArgs extends ScheduleReminderArgs {
|
||||
evt: BookingInfo;
|
||||
type scheduleEmailReminderArgs = ScheduleReminderArgs & {
|
||||
sendTo: string[];
|
||||
action: ScheduleEmailReminderAction;
|
||||
emailSubject?: string;
|
||||
@@ -55,9 +61,64 @@ interface scheduleEmailReminderArgs extends ScheduleReminderArgs {
|
||||
hideBranding?: boolean;
|
||||
includeCalendarEvent?: boolean;
|
||||
verifiedAt: Date | null;
|
||||
}
|
||||
};
|
||||
|
||||
type SendEmailReminderParams = {
|
||||
mailData: {
|
||||
subject: string;
|
||||
html: string;
|
||||
replyTo?: string;
|
||||
attachments?: any[];
|
||||
sender?: string | null;
|
||||
};
|
||||
sendTo: string[];
|
||||
triggerEvent: WorkflowTriggerEvents;
|
||||
scheduledDate?: dayjs.Dayjs | null;
|
||||
uid?: string;
|
||||
workflowStepId?: number;
|
||||
seatReferenceUid?: string;
|
||||
};
|
||||
|
||||
const sendOrScheduleWorkflowEmailWithReminder = async (params: SendEmailReminderParams) => {
|
||||
const { mailData, sendTo, scheduledDate, uid, workflowStepId } = params;
|
||||
|
||||
let reminderUid = undefined;
|
||||
if (scheduledDate) {
|
||||
const reminder = await prisma.workflowReminder.create({
|
||||
data: {
|
||||
bookingUid: uid,
|
||||
workflowStepId,
|
||||
method: WorkflowMethods.EMAIL,
|
||||
scheduledDate: scheduledDate.toDate(),
|
||||
scheduled: true,
|
||||
},
|
||||
});
|
||||
reminderUid = reminder.uuid;
|
||||
}
|
||||
|
||||
await sendOrScheduleWorkflowEmails({
|
||||
...mailData,
|
||||
to: sendTo,
|
||||
sendAt: scheduledDate?.toDate(),
|
||||
referenceUid: reminderUid ?? undefined,
|
||||
});
|
||||
};
|
||||
|
||||
export const scheduleEmailReminder = async (args: scheduleEmailReminderArgs) => {
|
||||
const { verifiedAt, workflowStepId } = args;
|
||||
if (!verifiedAt) {
|
||||
log.warn(`Workflow step ${workflowStepId} not yet verified`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (args.evt) {
|
||||
await scheduleEmailReminderForEvt(args);
|
||||
} else {
|
||||
await scheduleEmailReminderForForm(args);
|
||||
}
|
||||
};
|
||||
|
||||
const scheduleEmailReminderForEvt = async (args: scheduleEmailReminderArgs & { evt: BookingInfo }) => {
|
||||
const {
|
||||
evt,
|
||||
triggerEvent,
|
||||
@@ -72,14 +133,8 @@ export const scheduleEmailReminder = async (args: scheduleEmailReminderArgs) =>
|
||||
hideBranding,
|
||||
includeCalendarEvent,
|
||||
action,
|
||||
verifiedAt,
|
||||
} = args;
|
||||
|
||||
if (!verifiedAt) {
|
||||
log.warn(`Workflow step ${workflowStepId} not yet verified`);
|
||||
return;
|
||||
}
|
||||
|
||||
const { startTime, endTime } = evt;
|
||||
const uid = evt.uid as string;
|
||||
const timeUnit: timeUnitLowerCase | undefined = timeSpan.timeUnit?.toLocaleLowerCase() as timeUnitLowerCase;
|
||||
@@ -274,25 +329,67 @@ export const scheduleEmailReminder = async (args: scheduleEmailReminderArgs) =>
|
||||
|
||||
const mailData = await prepareEmailData();
|
||||
|
||||
let reminderUid = undefined;
|
||||
if (scheduledDate) {
|
||||
const reminder = await prisma.workflowReminder.create({
|
||||
data: {
|
||||
bookingUid: uid,
|
||||
workflowStepId,
|
||||
method: WorkflowMethods.EMAIL,
|
||||
scheduledDate: scheduledDate.toDate(),
|
||||
scheduled: true,
|
||||
},
|
||||
});
|
||||
reminderUid = reminder.uuid;
|
||||
await sendOrScheduleWorkflowEmailWithReminder({
|
||||
mailData,
|
||||
sendTo,
|
||||
triggerEvent,
|
||||
scheduledDate,
|
||||
uid,
|
||||
workflowStepId,
|
||||
seatReferenceUid,
|
||||
});
|
||||
};
|
||||
|
||||
const scheduleEmailReminderForForm = async (
|
||||
args: scheduleEmailReminderArgs & {
|
||||
formData: FormSubmissionData;
|
||||
}
|
||||
) => {
|
||||
const {
|
||||
formData,
|
||||
triggerEvent,
|
||||
sender,
|
||||
workflowStepId,
|
||||
sendTo,
|
||||
emailSubject = "",
|
||||
emailBody = "",
|
||||
hideBranding,
|
||||
} = args;
|
||||
|
||||
const emailContent = {
|
||||
emailSubject,
|
||||
emailBody: `<body style="white-space: pre-wrap;">${emailBody}</body>`,
|
||||
};
|
||||
|
||||
if (emailBody) {
|
||||
const timeFormat = getTimeFormatStringFromUserTimeFormat(formData.user.timeFormat);
|
||||
//todo: add variables
|
||||
const emailSubjectTemplate = customTemplate(emailSubject, {}, formData.user.locale, timeFormat);
|
||||
emailContent.emailSubject = emailSubjectTemplate.text;
|
||||
emailContent.emailBody = customTemplate(
|
||||
emailBody,
|
||||
{},
|
||||
formData.user.locale,
|
||||
timeFormat,
|
||||
hideBranding
|
||||
).html;
|
||||
}
|
||||
|
||||
await sendOrScheduleWorkflowEmails({
|
||||
...mailData,
|
||||
to: sendTo,
|
||||
sendAt: scheduledDate?.toDate(),
|
||||
referenceUid: reminderUid ?? undefined,
|
||||
// Allows debugging generated email content without waiting for sendgrid to send emails
|
||||
log.debug(`Sending Email for trigger ${triggerEvent}`, JSON.stringify(emailContent));
|
||||
|
||||
const mailData = {
|
||||
subject: emailContent.emailSubject,
|
||||
html: emailContent.emailBody,
|
||||
sender,
|
||||
};
|
||||
|
||||
await sendOrScheduleWorkflowEmailWithReminder({
|
||||
mailData,
|
||||
sendTo,
|
||||
triggerEvent,
|
||||
workflowStepId,
|
||||
scheduledDate: null,
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { FORM_SUBMITTED_WEBHOOK_RESPONSES } from "@calcom/app-store/routing-forms/lib/formSubmissionUtils";
|
||||
import {
|
||||
isAttendeeAction,
|
||||
isSMSAction,
|
||||
@@ -8,11 +9,13 @@ import {
|
||||
import { sendOrScheduleWorkflowEmails } from "@calcom/features/ee/workflows/lib/reminders/providers/emailProvider";
|
||||
import * as twilio from "@calcom/features/ee/workflows/lib/reminders/providers/twilioProvider";
|
||||
import type { Workflow, WorkflowStep } from "@calcom/features/ee/workflows/lib/types";
|
||||
import { getSubmitterEmail } from "@calcom/features/tasker/tasks/triggerFormSubmittedNoEvent/triggerFormSubmittedNoEventWebhook";
|
||||
import { checkSMSRateLimit } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
import { SENDER_NAME } from "@calcom/lib/constants";
|
||||
import { formatCalEventExtended } from "@calcom/lib/formatCalendarEvent";
|
||||
import { withReporting } from "@calcom/lib/sentryWrapper";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
import { WorkflowActions, WorkflowMethods, WorkflowTriggerEvents } from "@calcom/prisma/enums";
|
||||
@@ -20,10 +23,19 @@ import type { CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
import { scheduleAIPhoneCall } from "./aiPhoneCallManager";
|
||||
import { scheduleEmailReminder } from "./emailReminderManager";
|
||||
import { scheduleSMSReminder } from "./smsReminderManager";
|
||||
import type { ScheduleTextReminderAction } from "./smsReminderManager";
|
||||
import type { BookingInfo } from "./smsReminderManager";
|
||||
import { scheduleSMSReminder, type ScheduleTextReminderAction } from "./smsReminderManager";
|
||||
import { scheduleWhatsappReminder } from "./whatsappReminderManager";
|
||||
|
||||
export type FormSubmissionData = {
|
||||
responses: FORM_SUBMITTED_WEBHOOK_RESPONSES;
|
||||
user: {
|
||||
email: string;
|
||||
timeFormat: number | null;
|
||||
locale: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type ExtendedCalendarEvent = Omit<CalendarEvent, "bookerUrl"> & {
|
||||
metadata?: { videoCallUrl: string | undefined };
|
||||
eventType: {
|
||||
@@ -36,18 +48,23 @@ export type ExtendedCalendarEvent = Omit<CalendarEvent, "bookerUrl"> & {
|
||||
bookerUrl: string;
|
||||
};
|
||||
|
||||
type ProcessWorkflowStepParams = {
|
||||
type ProcessWorkflowStepParams = (
|
||||
| { calendarEvent: ExtendedCalendarEvent; formData?: never }
|
||||
| {
|
||||
calendarEvent?: never;
|
||||
formData: FormSubmissionData;
|
||||
}
|
||||
) & {
|
||||
smsReminderNumber: string | null;
|
||||
calendarEvent: ExtendedCalendarEvent;
|
||||
emailAttendeeSendToOverride?: string;
|
||||
hideBranding?: boolean;
|
||||
seatReferenceUid?: string;
|
||||
};
|
||||
|
||||
export interface ScheduleWorkflowRemindersArgs extends ProcessWorkflowStepParams {
|
||||
export type ScheduleWorkflowRemindersArgs = ProcessWorkflowStepParams & {
|
||||
workflows: Workflow[];
|
||||
isDryRun?: boolean;
|
||||
}
|
||||
};
|
||||
|
||||
const processWorkflowStep = async (
|
||||
workflow: Workflow,
|
||||
@@ -58,11 +75,21 @@ const processWorkflowStep = async (
|
||||
emailAttendeeSendToOverride,
|
||||
hideBranding,
|
||||
seatReferenceUid,
|
||||
formData,
|
||||
}: ProcessWorkflowStepParams
|
||||
) => {
|
||||
if (!step?.verifiedAt) return;
|
||||
|
||||
const evt = formatCalEventExtended(calendarEvent);
|
||||
const evt = calendarEvent ? formatCalEventExtended(calendarEvent) : undefined;
|
||||
|
||||
if (!evt && !formData) return;
|
||||
|
||||
const contextData:
|
||||
| { evt: BookingInfo; formData?: never }
|
||||
| {
|
||||
evt?: never;
|
||||
formData: FormSubmissionData;
|
||||
} = evt ? { evt } : { formData: formData as FormSubmissionData };
|
||||
|
||||
if (isSMSOrWhatsappAction(step.action)) {
|
||||
await checkSMSRateLimit({
|
||||
@@ -71,26 +98,36 @@ const processWorkflowStep = async (
|
||||
});
|
||||
}
|
||||
|
||||
// Common parameters for all scheduling functions
|
||||
const scheduleFunctionParams = {
|
||||
triggerEvent: workflow.trigger,
|
||||
timeSpan: {
|
||||
time: workflow.time,
|
||||
timeUnit: workflow.timeUnit,
|
||||
},
|
||||
workflowStepId: step.id,
|
||||
template: step.template,
|
||||
userId: workflow.userId,
|
||||
teamId: workflow.teamId,
|
||||
seatReferenceUid,
|
||||
verifiedAt: step.verifiedAt,
|
||||
};
|
||||
|
||||
if (isSMSAction(step.action)) {
|
||||
if (!evt) {
|
||||
// SMS action not not yet supported for form triggers
|
||||
return;
|
||||
}
|
||||
const sendTo = step.action === WorkflowActions.SMS_ATTENDEE ? smsReminderNumber : step.sendTo;
|
||||
|
||||
await scheduleSMSReminder({
|
||||
evt,
|
||||
...scheduleFunctionParams,
|
||||
reminderPhone: sendTo,
|
||||
triggerEvent: workflow.trigger,
|
||||
action: step.action as ScheduleTextReminderAction,
|
||||
timeSpan: {
|
||||
time: workflow.time,
|
||||
timeUnit: workflow.timeUnit,
|
||||
},
|
||||
message: step.reminderBody || "",
|
||||
workflowStepId: step.id,
|
||||
template: step.template,
|
||||
sender: step.sender,
|
||||
userId: workflow.userId,
|
||||
teamId: workflow.teamId,
|
||||
isVerificationPending: step.numberVerificationPending,
|
||||
seatReferenceUid,
|
||||
verifiedAt: step.verifiedAt,
|
||||
evt,
|
||||
});
|
||||
} else if (
|
||||
step.action === WorkflowActions.EMAIL_ATTENDEE ||
|
||||
@@ -103,7 +140,12 @@ const processWorkflowStep = async (
|
||||
case WorkflowActions.EMAIL_ADDRESS:
|
||||
sendTo = [step.sendTo || ""];
|
||||
break;
|
||||
case WorkflowActions.EMAIL_HOST:
|
||||
case WorkflowActions.EMAIL_HOST: {
|
||||
if (!evt) {
|
||||
// EMAIL_HOST is not supported for form triggers
|
||||
return;
|
||||
}
|
||||
|
||||
sendTo = [evt.organizer?.email || ""];
|
||||
|
||||
const schedulingType = evt.eventType.schedulingType;
|
||||
@@ -113,74 +155,71 @@ const processWorkflowStep = async (
|
||||
sendTo = sendTo.concat(evt.team.members.map((member) => member.email));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case WorkflowActions.EMAIL_ATTENDEE:
|
||||
const attendees = !!emailAttendeeSendToOverride
|
||||
? [emailAttendeeSendToOverride]
|
||||
: evt.attendees?.map((attendee) => attendee.email);
|
||||
if (evt) {
|
||||
const attendees = emailAttendeeSendToOverride
|
||||
? [emailAttendeeSendToOverride]
|
||||
: evt.attendees?.map((attendee) => attendee.email);
|
||||
|
||||
const limitGuestsDate = new Date("2025-01-13");
|
||||
const limitGuestsDate = new Date("2025-01-13");
|
||||
|
||||
if (workflow.userId) {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: workflow.userId,
|
||||
},
|
||||
select: {
|
||||
createdDate: true,
|
||||
},
|
||||
});
|
||||
if (user?.createdDate && user.createdDate > limitGuestsDate) {
|
||||
sendTo = attendees.slice(0, 1);
|
||||
if (workflow.userId) {
|
||||
const userRepository = new UserRepository(prisma);
|
||||
const user = await userRepository.findById({ id: workflow.userId });
|
||||
if (user?.createdDate && user.createdDate > limitGuestsDate) {
|
||||
sendTo = attendees.slice(0, 1);
|
||||
} else {
|
||||
sendTo = attendees;
|
||||
}
|
||||
} else {
|
||||
sendTo = attendees;
|
||||
}
|
||||
} else {
|
||||
sendTo = attendees;
|
||||
}
|
||||
|
||||
break;
|
||||
if (formData) {
|
||||
const submitterEmail = getSubmitterEmail(formData.responses);
|
||||
if (submitterEmail) {
|
||||
sendTo = [submitterEmail];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await scheduleEmailReminder({
|
||||
evt,
|
||||
triggerEvent: workflow.trigger,
|
||||
const emailParams = {
|
||||
...scheduleFunctionParams,
|
||||
action: step.action,
|
||||
timeSpan: {
|
||||
time: workflow.time,
|
||||
timeUnit: workflow.timeUnit,
|
||||
},
|
||||
sendTo,
|
||||
emailSubject: step.emailSubject || "",
|
||||
emailBody: step.reminderBody || "",
|
||||
template: step.template,
|
||||
sender: step.sender || SENDER_NAME,
|
||||
workflowStepId: step.id,
|
||||
hideBranding,
|
||||
seatReferenceUid,
|
||||
includeCalendarEvent: step.includeCalendarEvent,
|
||||
...contextData,
|
||||
verifiedAt: step.verifiedAt,
|
||||
});
|
||||
} as const;
|
||||
|
||||
await scheduleEmailReminder(emailParams);
|
||||
} else if (isWhatsappAction(step.action)) {
|
||||
if (!evt) {
|
||||
// Whatsapp action not not yet supported for form triggers
|
||||
return;
|
||||
}
|
||||
|
||||
const sendTo = step.action === WorkflowActions.WHATSAPP_ATTENDEE ? smsReminderNumber : step.sendTo;
|
||||
|
||||
await scheduleWhatsappReminder({
|
||||
evt,
|
||||
...scheduleFunctionParams,
|
||||
reminderPhone: sendTo,
|
||||
triggerEvent: workflow.trigger,
|
||||
action: step.action as ScheduleTextReminderAction,
|
||||
timeSpan: {
|
||||
time: workflow.time,
|
||||
timeUnit: workflow.timeUnit,
|
||||
},
|
||||
message: step.reminderBody || "",
|
||||
workflowStepId: step.id,
|
||||
template: step.template,
|
||||
userId: workflow.userId,
|
||||
teamId: workflow.teamId,
|
||||
isVerificationPending: step.numberVerificationPending,
|
||||
seatReferenceUid,
|
||||
verifiedAt: step.verifiedAt,
|
||||
evt,
|
||||
});
|
||||
} else if (isCalAIAction(step.action)) {
|
||||
if (!evt) {
|
||||
// cal.ai not yet supported for form triggers
|
||||
return;
|
||||
}
|
||||
await scheduleAIPhoneCall({
|
||||
evt,
|
||||
triggerEvent: workflow.trigger,
|
||||
@@ -206,6 +245,7 @@ const _scheduleWorkflowReminders = async (args: ScheduleWorkflowRemindersArgs) =
|
||||
hideBranding,
|
||||
seatReferenceUid,
|
||||
isDryRun = false,
|
||||
formData,
|
||||
} = args;
|
||||
if (isDryRun || !workflows.length) return;
|
||||
|
||||
@@ -214,11 +254,11 @@ const _scheduleWorkflowReminders = async (args: ScheduleWorkflowRemindersArgs) =
|
||||
|
||||
for (const step of workflow.steps) {
|
||||
await processWorkflowStep(workflow, step, {
|
||||
calendarEvent: evt,
|
||||
emailAttendeeSendToOverride,
|
||||
smsReminderNumber,
|
||||
hideBranding,
|
||||
seatReferenceUid,
|
||||
...(evt ? { calendarEvent: evt } : { formData }),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,7 +76,8 @@ export type ScheduleTextReminderAction = Extract<
|
||||
WorkflowActions,
|
||||
"SMS_ATTENDEE" | "SMS_NUMBER" | "WHATSAPP_ATTENDEE" | "WHATSAPP_NUMBER"
|
||||
>;
|
||||
export interface ScheduleTextReminderArgs extends ScheduleReminderArgs {
|
||||
|
||||
export type ScheduleTextReminderArgs = ScheduleReminderArgs & {
|
||||
reminderPhone: string | null;
|
||||
message: string;
|
||||
action: ScheduleTextReminderAction;
|
||||
@@ -85,9 +86,8 @@ export interface ScheduleTextReminderArgs extends ScheduleReminderArgs {
|
||||
isVerificationPending?: boolean;
|
||||
prisma?: PrismaClient;
|
||||
verifiedAt: Date | null;
|
||||
}
|
||||
|
||||
export const scheduleSMSReminder = async (args: ScheduleTextReminderArgs) => {
|
||||
};
|
||||
export const scheduleSMSReminder = async (args: ScheduleTextReminderArgs & { evt: BookingInfo }) => {
|
||||
const {
|
||||
evt,
|
||||
reminderPhone,
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
getContentVariablesForTemplate,
|
||||
} from "../reminders/templates/whatsapp/ContentSidMapping";
|
||||
import { scheduleSmsOrFallbackEmail, sendSmsOrFallbackEmail } from "./messageDispatcher";
|
||||
import type { ScheduleTextReminderArgs, timeUnitLowerCase } from "./smsReminderManager";
|
||||
import type { BookingInfo, ScheduleTextReminderArgs, timeUnitLowerCase } from "./smsReminderManager";
|
||||
import {
|
||||
whatsappEventCancelledTemplate,
|
||||
whatsappEventCompletedTemplate,
|
||||
@@ -26,7 +26,7 @@ import {
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["[whatsappReminderManager]"] });
|
||||
|
||||
export const scheduleWhatsappReminder = async (args: ScheduleTextReminderArgs) => {
|
||||
export const scheduleWhatsappReminder = async (args: ScheduleTextReminderArgs & { evt: BookingInfo }) => {
|
||||
const {
|
||||
evt,
|
||||
reminderPhone,
|
||||
|
||||
@@ -31,4 +31,20 @@ export class WorkflowReminderRepository {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findWorkflowRemindersByStepId(workflowStepId: number) {
|
||||
return await prisma.workflowReminder.findMany({
|
||||
where: { workflowStepId },
|
||||
select: {
|
||||
id: true,
|
||||
referenceId: true,
|
||||
method: true,
|
||||
booking: {
|
||||
select: {
|
||||
eventTypeId: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { useForm, useWatch } from "react-hook-form";
|
||||
import { Toaster } from "sonner";
|
||||
|
||||
import { SENDER_ID } from "@calcom/lib/constants";
|
||||
@@ -31,7 +31,12 @@ import LicenseRequired from "../../common/components/LicenseRequired";
|
||||
import { DeleteDialog } from "../components/DeleteDialog";
|
||||
import SkeletonLoader from "../components/SkeletonLoaderEdit";
|
||||
import WorkflowDetailsPage from "../components/WorkflowDetailsPage";
|
||||
import { isSMSAction, isSMSOrWhatsappAction, isCalAIAction } from "../lib/actionHelperFunctions";
|
||||
import {
|
||||
isSMSAction,
|
||||
isSMSOrWhatsappAction,
|
||||
isCalAIAction,
|
||||
isFormTrigger,
|
||||
} from "../lib/actionHelperFunctions";
|
||||
import { formSchema } from "../lib/schema";
|
||||
import { getTranslatedText, translateVariablesToEnglish } from "../lib/variableTranslations";
|
||||
|
||||
@@ -80,6 +85,11 @@ function WorkflowPage({
|
||||
|
||||
const utils = trpc.useUtils();
|
||||
|
||||
const watchedTrigger = useWatch({
|
||||
control: form.control,
|
||||
name: "trigger",
|
||||
});
|
||||
|
||||
const userQuery = useMeQuery();
|
||||
const user = userQuery.data;
|
||||
|
||||
@@ -119,12 +129,13 @@ function WorkflowPage({
|
||||
|
||||
const teamId = workflow?.teamId ?? undefined;
|
||||
|
||||
const { data, isPending: isPendingEventTypes } = trpc.viewer.eventTypes.getTeamAndEventTypeOptions.useQuery(
|
||||
const { data, isPending: isPendingEventTypes } = trpc.viewer.eventTypes.getActiveOnOptions.useQuery(
|
||||
{ teamId, isOrg },
|
||||
{ enabled: !isPendingWorkflow }
|
||||
);
|
||||
|
||||
const teamOptions = data?.teamOptions ?? [];
|
||||
const routingFormOptions = data?.routingFormOptions ?? [];
|
||||
|
||||
let allEventTypeOptions = data?.eventTypeOptions ?? [];
|
||||
const distinctEventTypes = new Set();
|
||||
@@ -223,7 +234,11 @@ function WorkflowPage({
|
||||
let activeOn;
|
||||
|
||||
if (workflowData.isActiveOnAll) {
|
||||
activeOn = isOrg ? teamOptions : allEventTypeOptions;
|
||||
activeOn = isOrg
|
||||
? teamOptions
|
||||
: isFormTrigger(workflowData.trigger)
|
||||
? routingFormOptions
|
||||
: allEventTypeOptions;
|
||||
} else {
|
||||
if (isOrg) {
|
||||
activeOn = workflowData.activeOnTeams.flatMap((active) => {
|
||||
@@ -233,6 +248,14 @@ function WorkflowPage({
|
||||
};
|
||||
});
|
||||
setSelectedOptions(activeOn || []);
|
||||
} else if (isFormTrigger(workflowData.trigger)) {
|
||||
activeOn = workflowData.activeOnRoutingForms?.flatMap((active) => {
|
||||
return {
|
||||
value: String(active.routingForm.id) || "",
|
||||
label: active.routingForm.name || "",
|
||||
};
|
||||
});
|
||||
setSelectedOptions(activeOn || []);
|
||||
} else {
|
||||
setSelectedOptions(
|
||||
workflowData.activeOn?.flatMap((active) => {
|
||||
@@ -309,7 +332,6 @@ function WorkflowPage({
|
||||
});
|
||||
|
||||
const validateAndSubmitWorkflow = async (values: FormValues): Promise<void> => {
|
||||
let activeOnIds: number[] = [];
|
||||
let isEmpty = false;
|
||||
let isVerified = true;
|
||||
|
||||
@@ -367,18 +389,26 @@ function WorkflowPage({
|
||||
});
|
||||
|
||||
if (!isEmpty && isVerified) {
|
||||
if (values.activeOn) {
|
||||
activeOnIds = values.activeOn
|
||||
let activeOnEventTypeOrTeamIds: number[] = [];
|
||||
let activeOnRoutingFormIds: string[] = [];
|
||||
if (isOrg || !isFormTrigger(values.trigger)) {
|
||||
activeOnEventTypeOrTeamIds = values.activeOn
|
||||
.filter((option) => option.value !== "all")
|
||||
.map((option) => {
|
||||
return parseInt(option.value, 10);
|
||||
});
|
||||
} else {
|
||||
// Form triggers, activeOn contains routing form IDs (strings)
|
||||
activeOnRoutingFormIds = values.activeOn
|
||||
.filter((option) => option.value !== "all")
|
||||
.map((option) => option.value);
|
||||
}
|
||||
|
||||
await updateMutation.mutateAsync({
|
||||
id: workflowId,
|
||||
name: values.name,
|
||||
activeOn: activeOnIds,
|
||||
activeOnEventTypeIds: activeOnEventTypeOrTeamIds,
|
||||
activeOnRoutingFormIds,
|
||||
steps: values.steps,
|
||||
trigger: values.trigger,
|
||||
time: values.time || null,
|
||||
@@ -497,7 +527,7 @@ function WorkflowPage({
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-default min-h-screen w-full px-2 sm:p-0">
|
||||
<div className="mx-auto my-8 max-w-4xl ">
|
||||
<div className="mx-auto my-8 max-w-4xl">
|
||||
{!isError ? (
|
||||
<>
|
||||
{isAllDataLoaded && user ? (
|
||||
@@ -510,7 +540,13 @@ function WorkflowPage({
|
||||
setSelectedOptions={setSelectedOptions}
|
||||
teamId={workflow ? workflow.teamId || undefined : undefined}
|
||||
isOrg={isOrg}
|
||||
allOptions={isOrg ? teamOptions : allEventTypeOptions}
|
||||
allOptions={
|
||||
isOrg
|
||||
? teamOptions
|
||||
: isFormTrigger(watchedTrigger)
|
||||
? routingFormOptions
|
||||
: allEventTypeOptions
|
||||
}
|
||||
onSaveWorkflow={handleSaveWorkflow}
|
||||
permissions={permissions}
|
||||
/>
|
||||
|
||||
@@ -100,14 +100,14 @@ const WorkflowListItem = (props: ItemProps) => {
|
||||
|
||||
return (
|
||||
<div className="border-subtle w-full overflow-hidden rounded-md border p-6 px-3 md:p-6">
|
||||
<div className="flex items-center ">
|
||||
<div className="flex items-center">
|
||||
<div className="bg-subtle mr-4 flex h-10 w-10 items-center justify-center rounded-full text-xs font-medium">
|
||||
{getActionIcon(
|
||||
workflow.steps,
|
||||
isActive ? "h-6 w-6 stroke-[1.5px] text-default" : "h-6 w-6 stroke-[1.5px] text-muted"
|
||||
)}
|
||||
</div>
|
||||
<div className=" grow">
|
||||
<div className="grow">
|
||||
<div
|
||||
className={classNames(
|
||||
"text-emphasis mb-1 w-full truncate text-base font-medium leading-4 md:max-w-max",
|
||||
@@ -122,7 +122,7 @@ const WorkflowListItem = (props: ItemProps) => {
|
||||
<>
|
||||
<div
|
||||
className={classNames(
|
||||
" flex w-fit items-center whitespace-nowrap rounded-sm text-sm leading-4",
|
||||
"flex w-fit items-center whitespace-nowrap rounded-sm text-sm leading-4",
|
||||
isActive ? "text-default" : "text-muted"
|
||||
)}>
|
||||
<span className="mr-1">{t("to")}:</span>
|
||||
@@ -191,6 +191,7 @@ function EventWorkflowsTab(props: Props) {
|
||||
const { data, isPending } = trpc.viewer.workflows.list.useQuery({
|
||||
teamId: eventType.team?.id,
|
||||
userId: !isChildrenManagedEventType ? eventType.userId || undefined : undefined,
|
||||
includeOnlyEventTypeWorkflows: true,
|
||||
});
|
||||
const router = useRouter();
|
||||
const [sortedWorkflows, setSortedWorkflows] = useState<Array<WorkflowType>>([]);
|
||||
|
||||
+8
-7
@@ -15,6 +15,13 @@ export type ResponseData = {
|
||||
};
|
||||
};
|
||||
|
||||
export function getSubmitterEmail(responses: any) {
|
||||
return Object.values(responses).find((response): response is { value: string; label: string } => {
|
||||
const value = typeof response === "object" && response && "value" in response ? response.value : response;
|
||||
return typeof value === "string" && value.includes("@");
|
||||
})?.value;
|
||||
}
|
||||
|
||||
export const ZTriggerFormSubmittedNoEventWebhookPayloadSchema = z.object({
|
||||
webhook: z.object({
|
||||
subscriberUrl: z.string().url(),
|
||||
@@ -70,13 +77,7 @@ export async function triggerFormSubmittedNoEventWebhook(payload: string): Promi
|
||||
},
|
||||
})) ?? [];
|
||||
|
||||
const emailValue = Object.values(responses).find(
|
||||
(response): response is { value: string; label: string } => {
|
||||
const value =
|
||||
typeof response === "object" && response && "value" in response ? response.value : response;
|
||||
return typeof value === "string" && value.includes("@");
|
||||
}
|
||||
)?.value;
|
||||
const emailValue = getSubmitterEmail(responses);
|
||||
// Check for duplicate email in recent responses
|
||||
const hasDuplicate =
|
||||
emailValue &&
|
||||
|
||||
Reference in new issue
Block a user