feat: Workflow — Send Email to Specific Email (#14815)

* feat: Workflow — Send Email to Specific Email

* disable button when verifyEmail pending

* add verified emails table and routes

* fix: include teamId in verifyEmailCode

* fix: include email address in activate handler

* fix: check team before adding email

* feat: check verified email, add to team if only users

* remove logs

* fix: if statement

Co-authored-by: Carina Wollendorfer <[email protected]>

* change email to verify your email

* fix: show error if saving unverified email

* fix: show email in subject

* verify email when editing steps

* remove double calls from same block

* verify email when creating new step

---------

Co-authored-by: v0ltZzie <[email protected]>
Co-authored-by: Carina Wollendorfer <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-05-20 21:23:19 +00:00
1 parent 5ee3744015
commit bd6c471652
21 files changed
+491 -70

No files matched your search

+8 -1
View File
@@ -20,6 +20,7 @@ interface VerifyEmailType {
email: string;
language?: string;
secondaryEmailId?: number;
isVerifyingEmail?: boolean;
isPlatform?: boolean;
}
@@ -75,7 +76,12 @@ export const sendEmailVerification = async ({
return { ok: true, skipped: false };
};
export const sendEmailVerificationByCode = async ({ email, language, username }: VerifyEmailType) => {
export const sendEmailVerificationByCode = async ({
email,
language,
username,
isVerifyingEmail,
}: VerifyEmailType) => {
const translation = await getTranslation(language ?? "en", "common");
const secret = createHash("md5")
.update(email + process.env.CALENDSO_ENCRYPTION_KEY)
@@ -91,6 +97,7 @@ export const sendEmailVerificationByCode = async ({ email, language, username }:
email,
name: username,
},
isVerifyingEmail,
});
return { ok: true, skipped: false };
@@ -258,34 +258,30 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
if (emailContent.emailSubject.length > 0 && !emailBodyEmpty && sendTo) {
const batchId = await getBatchId();
if (reminder.workflowStep.action !== WorkflowActions.EMAIL_ADDRESS) {
sendEmailPromises.push(
sendSendgridMail(
{
to: sendTo,
subject: emailContent.emailSubject,
html: emailContent.emailBody,
batchId: batchId,
sendAt: dayjs(reminder.scheduledDate).unix(),
replyTo: reminder.booking?.userPrimaryEmail ?? reminder.booking.user?.email,
attachments: reminder.workflowStep.includeCalendarEvent
? [
{
content: Buffer.from(getiCalEventAsString(reminder.booking) || "").toString(
"base64"
),
filename: "event.ics",
type: "text/calendar; method=REQUEST",
disposition: "attachment",
contentId: uuidv4(),
},
]
: undefined,
},
{ sender: reminder.workflowStep.sender }
)
);
}
sendEmailPromises.push(
sendSendgridMail(
{
to: sendTo,
subject: emailContent.emailSubject,
html: emailContent.emailBody,
batchId: batchId,
sendAt: dayjs(reminder.scheduledDate).unix(),
replyTo: reminder.booking?.userPrimaryEmail ?? reminder.booking.user?.email,
attachments: reminder.workflowStep.includeCalendarEvent
? [
{
content: Buffer.from(getiCalEventAsString(reminder.booking) || "").toString("base64"),
filename: "event.ics",
type: "text/calendar; method=REQUEST",
disposition: "attachment",
contentId: uuidv4(),
},
]
: undefined,
},
{ sender: reminder.workflowStep.sender }
)
);
await prisma.workflowReminder.update({
where: {
@@ -78,9 +78,12 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
{ enabled: !!teamId }
);
const { data: _verifiedEmails } = trpc.viewer.workflows.getVerifiedEmails.useQuery({ teamId });
const timeFormat = getTimeFormatStringFromUserTimeFormat(props.user.timeFormat);
const verifiedNumbers = _verifiedNumbers?.map((number) => number.phoneNumber) || [];
const verifiedEmails = _verifiedEmails?.map((verified) => verified.email) || [];
const [isAdditionalInputsDialogOpen, setIsAdditionalInputsDialogOpen] = useState(false);
const [verificationCode, setVerificationCode] = useState("");
@@ -172,9 +175,15 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
(number: string) => number === form.getValues(`steps.${step.stepNumber - 1}.sendTo`)
);
const getEmailVerificationStatus = () =>
!!step &&
!!verifiedEmails.find((email: string) => email === form.getValues(`steps.${step.stepNumber - 1}.sendTo`));
const [numberVerified, setNumberVerified] = useState(getNumberVerificationStatus());
const [emailVerified, setEmailVerified] = useState(getEmailVerificationStatus());
useEffect(() => setNumberVerified(getNumberVerificationStatus()), [verifiedNumbers.length]);
useEffect(() => setEmailVerified(getEmailVerificationStatus()), [verifiedEmails.length]);
const addVariableBody = (variable: string) => {
if (step) {
@@ -231,6 +240,36 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
},
});
const sendEmailVerificationCodeMutation = trpc.viewer.auth.sendVerifyEmailCode.useMutation({
onSuccess() {
showToast(t("email_sent"), "success");
},
onError: () => {
showToast(t("email_not_sent"), "error");
},
});
const verifyEmailCodeMutation = trpc.viewer.workflows.verifyEmailCode.useMutation({
onSuccess: (isVerified) => {
showToast(isVerified ? t("verified_successfully") : t("wrong_code"), "success");
setEmailVerified(true);
if (
step &&
form?.formState?.errors?.steps &&
form.formState.errors.steps[step.stepNumber - 1]?.sendTo &&
isVerified
) {
form.clearErrors(`steps.${step.stepNumber - 1}.sendTo`);
}
utils.viewer.workflows.getVerifiedEmails.invalidate();
},
onError: (err) => {
if (err.message === "invalid_code") {
showToast(t("code_provided_invalid"), "error");
setEmailVerified(false);
}
},
});
/* const testActionMutation = trpc.viewer.workflows.testAction.useMutation({
onSuccess: async () => {
showToast(t("notification_sent"), "success");
@@ -687,12 +726,94 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
)}
{isEmailAddressNeeded && (
<div className="bg-muted mt-5 rounded-md p-4">
<EmailField
required
disabled={props.readOnly}
label={t("email_address")}
{...form.register(`steps.${step.stepNumber - 1}.sendTo`)}
/>
<Label>{t("email_address")}</Label>
<div className="block sm:flex">
<Controller
name={`steps.${step.stepNumber - 1}.sendTo`}
render={({ field: { value, onChange } }) => (
<EmailField
required
containerClassName="w-full"
className="h-10 min-w-fit sm:rounded-r-none sm:rounded-bl-md sm:rounded-tl-md"
placeholder={t("email_address")}
value={value}
disabled={props.readOnly}
onChange={(val) => {
const isAlreadyVerified = !!verifiedEmails
?.concat([])
.find((email) => email === val.target.value);
setEmailVerified(isAlreadyVerified);
onChange(val);
}}
/>
)}
/>
<Button
color="secondary"
disabled={emailVerified || props.readOnly || false}
className={classNames(
"-ml-[3px] h-[40px] min-w-fit sm:block sm:rounded-bl-none sm:rounded-tl-none",
emailVerified ? "hidden" : "mt-3 sm:mt-0"
)}
onClick={() => {
const email = form.getValues(`steps.${step.stepNumber - 1}.sendTo`) || "";
sendEmailVerificationCodeMutation.mutate({
email,
isVerifyingEmail: true,
});
}}>
{t("send_code")}
</Button>
</div>
{form.formState.errors.steps &&
form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo && (
<p className="mt-1 text-xs text-red-500">
{form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo?.message || ""}
</p>
)}
{emailVerified ? (
<div className="mt-1">
<Badge variant="green">{t("email_verified")}</Badge>
</div>
) : (
!props.readOnly && (
<>
<div className="mt-3 flex">
<TextField
className="rounded-r-none border-r-transparent"
placeholder="Verification code"
disabled={props.readOnly}
value={verificationCode}
onChange={(e) => {
setVerificationCode(e.target.value);
}}
required
/>
<Button
color="secondary"
className="-ml-[3px] h-[36px] min-w-fit py-0 sm:block sm:rounded-bl-none sm:rounded-tl-none "
disabled={verifyEmailCodeMutation.isPending || props.readOnly}
onClick={() => {
verifyEmailCodeMutation.mutate({
code: verificationCode,
email: form.getValues(`steps.${step.stepNumber - 1}.sendTo`) || "",
teamId,
});
}}>
{t("verify")}
</Button>
</div>
{form.formState.errors.steps &&
form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo && (
<p className="mt-1 text-xs text-red-500">
{form.formState?.errors?.steps[step.stepNumber - 1]?.sendTo?.message || ""}
</p>
)}
</>
)
)}
</div>
)}
<div className="mt-5">
@@ -1,6 +1,6 @@
import type { TFunction } from "next-i18next";
import { WorkflowActions } from "@calcom/prisma/enums";
import type { WorkflowActions } from "@calcom/prisma/enums";
import { isSMSOrWhatsappAction, isWhatsappAction, isEmailToAttendeeAction } from "./actionHelperFunctions";
import {
@@ -13,16 +13,15 @@ import {
} from "./constants";
export function getWorkflowActionOptions(t: TFunction, isTeamsPlan?: boolean, isOrgsPlan?: boolean) {
return WORKFLOW_ACTIONS.filter((action) => action !== WorkflowActions.EMAIL_ADDRESS) //removing EMAIL_ADDRESS for now due to abuse episode
.map((action) => {
const actionString = t(`${action.toLowerCase()}_action`);
return WORKFLOW_ACTIONS.map((action) => {
const actionString = t(`${action.toLowerCase()}_action`);
return {
label: actionString.charAt(0).toUpperCase() + actionString.slice(1),
value: action,
needsTeamsUpgrade: isSMSOrWhatsappAction(action) && !isTeamsPlan,
};
});
return {
label: actionString.charAt(0).toUpperCase() + actionString.slice(1),
value: action,
needsTeamsUpgrade: isSMSOrWhatsappAction(action) && !isTeamsPlan,
};
});
}
export function getWorkflowTriggerOptions(t: TFunction) {
@@ -120,7 +120,6 @@ export const scheduleEmailReminder = async (args: scheduleEmailReminderArgs) =>
isMandatoryReminder,
action,
} = args;
if (action === WorkflowActions.EMAIL_ADDRESS) return;
const { startTime, endTime } = evt;
const uid = evt.uid as string;
const currentDate = dayjs();
@@ -141,6 +140,12 @@ export const scheduleEmailReminder = async (args: scheduleEmailReminderArgs) =>
let timeZone = "";
switch (action) {
case WorkflowActions.EMAIL_ADDRESS:
name = "";
attendeeToBeUsedInMail = evt.attendees[0];
attendeeName = evt.attendees[0].name;
timeZone = evt.organizer.timeZone;
break;
case WorkflowActions.EMAIL_HOST:
attendeeToBeUsedInMail = evt.attendees[0];
name = evt.organizer.name;
@@ -77,10 +77,17 @@ const processWorkflowStep = async (
isVerificationPending: step.numberVerificationPending,
seatReferenceUid,
});
} else if (step.action === WorkflowActions.EMAIL_ATTENDEE || step.action === WorkflowActions.EMAIL_HOST) {
} else if (
step.action === WorkflowActions.EMAIL_ATTENDEE ||
step.action === WorkflowActions.EMAIL_HOST ||
step.action === WorkflowActions.EMAIL_ADDRESS
) {
let sendTo: string[] = [];
switch (step.action) {
case WorkflowActions.EMAIL_ADDRESS:
sendTo = [step.sendTo || ""];
break;
case WorkflowActions.EMAIL_HOST:
sendTo = [evt.organizer?.email || ""];
break;
@@ -124,6 +124,10 @@ function WorkflowPage() {
}
);
const { data: verifiedEmails } = trpc.viewer.workflows.getVerifiedEmails.useQuery({
teamId: workflow?.team?.id,
});
const readOnly =
workflow?.team?.members?.find((member) => member.userId === session.data?.user.id)?.role ===
MembershipRole.MEMBER;
@@ -252,6 +256,18 @@ function WorkflowPage() {
message: t("not_verified"),
});
}
if (
step.action === WorkflowActions.EMAIL_ADDRESS &&
!verifiedEmails?.find((verifiedEmail) => verifiedEmail.email === step.sendTo)
) {
isVerified = false;
form.setError(`steps.${step.stepNumber - 1}.sendTo`, {
type: "custom",
message: t("not_verified"),
});
}
});
if (!isEmpty && isVerified) {