feat: add translations for emails and type error fixes overall (#994)

* feat: add translations for forgot password email and misc

* fix: type fixes

* feat: translate invitation email

* fix: e2e tests

* fix: lint

* feat: type fixes and i18n for emails

* Merge main

* fix: jest import on server path

* Merge

* fix: playwright tests

* fix: lint

Co-authored-by: Bailey Pumfleet <[email protected]>
This commit is contained in:
Mihai CandBailey Pumfleet authored and GitHub committed 2021-10-25 14:05:21 +01:00
1 parent 356d470e16
commit 8d6fec79d3
35 files changed
+680 -461

No files matched your search

+10 -5
View File
@@ -1,17 +1,21 @@
import { User, ResetPasswordRequest } from "@prisma/client";
import { ResetPasswordRequest } from "@prisma/client";
import dayjs from "dayjs";
import timezone from "dayjs/plugin/timezone";
import utc from "dayjs/plugin/utc";
import { NextApiRequest, NextApiResponse } from "next";
import sendEmail from "../../../lib/emails/sendMail";
import { buildForgotPasswordMessage } from "../../../lib/forgot-password/messaging/forgot-password";
import prisma from "../../../lib/prisma";
import sendEmail from "@lib/emails/sendMail";
import { buildForgotPasswordMessage } from "@lib/forgot-password/messaging/forgot-password";
import prisma from "@lib/prisma";
import { getTranslation } from "@server/lib/i18n";
dayjs.extend(utc);
dayjs.extend(timezone);
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const t = await getTranslation(req.body.language ?? "en", "common");
if (req.method !== "POST") {
return res.status(405).json({ message: "" });
}
@@ -19,7 +23,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
try {
const rawEmail = req.body?.email;
const maybeUser: User = await prisma.user.findUnique({
const maybeUser = await prisma.user.findUnique({
where: {
email: rawEmail,
},
@@ -59,6 +63,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
const passwordResetLink = `${process.env.BASE_URL}/auth/forgot-password/${passwordRequest.id}`;
const { subject, message } = buildForgotPasswordMessage({
language: t,
user: {
name: maybeUser.name,
},
+15 -5
View File
@@ -6,12 +6,15 @@ import { getSession } from "@lib/auth";
import { CalendarEvent } from "@lib/calendarClient";
import EventRejectionMail from "@lib/emails/EventRejectionMail";
import EventManager from "@lib/events/EventManager";
import prisma from "@lib/prisma";
import prisma from "../../../lib/prisma";
import { getTranslation } from "@server/lib/i18n";
export default async function handler(req: NextApiRequest, res: NextApiResponse): Promise<void> {
const t = await getTranslation(req.body.language ?? "en", "common");
const session = await getSession({ req: req });
if (!session) {
if (!session?.user?.id) {
return res.status(401).json({ message: "Not authenticated" });
}
@@ -33,6 +36,10 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
},
});
if (!currentUser) {
return res.status(404).json({ message: "User not found" });
}
if (req.method == "PATCH") {
const booking = await prisma.booking.findFirst({
where: {
@@ -66,14 +73,16 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
description: booking.description,
startTime: booking.startTime.toISOString(),
endTime: booking.endTime.toISOString(),
organizer: { email: currentUser.email, name: currentUser.name, timeZone: currentUser.timeZone },
organizer: { email: currentUser.email, name: currentUser.name!, timeZone: currentUser.timeZone },
attendees: booking.attendees,
location: booking.location,
uid: booking.uid,
language: t,
};
if (req.body.confirmed) {
const eventManager = new EventManager(currentUser.credentials);
const scheduleResult = await eventManager.create(evt, booking.uid);
const scheduleResult = await eventManager.create(evt);
await prisma.booking.update({
where: {
@@ -99,8 +108,9 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
rejected: true,
},
});
const attendeeMail = new EventRejectionMail(evt, booking.uid);
const attendeeMail = new EventRejectionMail(evt);
await attendeeMail.sendEmail();
res.status(204).json({ message: "ok" });
}
}
+10 -4
View File
@@ -6,7 +6,6 @@ import isBetween from "dayjs/plugin/isBetween";
import timezone from "dayjs/plugin/timezone";
import utc from "dayjs/plugin/utc";
import type { NextApiRequest, NextApiResponse } from "next";
import { getErrorFromUnknown } from "pages/_error";
import short from "short-uuid";
import { v5 as uuidv5 } from "uuid";
@@ -14,6 +13,7 @@ import { handlePayment } from "@ee/lib/stripe/server";
import { CalendarEvent, getBusyCalendarTimes } from "@lib/calendarClient";
import EventOrganizerRequestMail from "@lib/emails/EventOrganizerRequestMail";
import { getErrorFromUnknown } from "@lib/errors";
import { getEventName } from "@lib/event";
import EventManager, { CreateUpdateResult, EventResult, PartialReference } from "@lib/events/EventManager";
import logger from "@lib/logger";
@@ -23,6 +23,8 @@ import { getBusyVideoTimes } from "@lib/videoClient";
import sendPayload from "@lib/webhooks/sendPayload";
import getSubscriberUrls from "@lib/webhooks/subscriberUrls";
import { getTranslation } from "@server/lib/i18n";
export interface DailyReturnType {
name: string;
url: string;
@@ -126,6 +128,7 @@ function isOutOfBounds(
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const reqBody = req.body as BookingCreateBody;
const eventTypeId = reqBody.eventTypeId;
const t = await getTranslation(reqBody.language ?? "en", "common");
log.debug(`Booking eventType ${eventTypeId} started`);
@@ -273,6 +276,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
},
attendees: attendeesList,
location: reqBody.location, // Will be processed by the EventManager later.
language: t,
uid,
};
if (eventType.schedulingType === SchedulingType.COLLECTIVE) {
@@ -425,7 +430,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if (rescheduleUid) {
// Use EventManager to conditionally use all needed integrations.
const updateResults: CreateUpdateResult = await eventManager.update(evt, rescheduleUid);
const eventManagerCalendarEvent = { ...evt, uid: rescheduleUid };
const updateResults: CreateUpdateResult = await eventManager.update(eventManagerCalendarEvent);
results = updateResults.results;
referencesToCreate = updateResults.referencesToCreate;
@@ -440,7 +446,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
}
} else if (!eventType.requiresConfirmation && !eventType.price) {
// Use EventManager to conditionally use all needed integrations.
const createResults: CreateUpdateResult = await eventManager.create(evt, uid);
const createResults: CreateUpdateResult = await eventManager.create(evt);
results = createResults.results;
referencesToCreate = createResults.referencesToCreate;
@@ -496,7 +502,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
}
if (eventType.requiresConfirmation && !rescheduleUid) {
await new EventOrganizerRequestMail(evt, uid).sendEmail();
await new EventOrganizerRequestMail({ ...evt, uid }).sendEmail();
}
if (typeof eventType.price === "number" && eventType.price > 0) {
+18 -11
View File
@@ -2,11 +2,14 @@ import { randomBytes } from "crypto";
import type { NextApiRequest, NextApiResponse } from "next";
import { getSession } from "@lib/auth";
import { createInvitationEmail } from "@lib/emails/invitation";
import prisma from "@lib/prisma";
import { createInvitationEmail } from "../../../../lib/emails/invitation";
import prisma from "../../../../lib/prisma";
import { getTranslation } from "@server/lib/i18n";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const t = await getTranslation(req.body.language ?? "en", "common");
if (req.method !== "POST") {
return res.status(400).json({ message: "Bad request" });
}
@@ -18,7 +21,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
const team = await prisma.team.findFirst({
where: {
id: parseInt(req.query.team),
id: parseInt(req.query.team as string),
},
});
@@ -68,12 +71,15 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
},
});
createInvitationEmail({
toEmail: req.body.usernameOrEmail,
from: session.user.name,
teamName: team.name,
token,
});
if (session?.user?.name && team?.name) {
createInvitationEmail({
language: t,
toEmail: req.body.usernameOrEmail,
from: session.user.name,
teamName: team.name,
token,
});
}
return res.status(201).json({});
}
@@ -87,7 +93,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
role: req.body.role,
},
});
} catch (err) {
} catch (err: any) {
if (err.code === "P2002") {
// unique constraint violation
return res.status(409).json({
@@ -99,8 +105,9 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
}
// inform user of membership by email
if (req.body.sendEmailInvitation) {
if (req.body.sendEmailInvitation && session?.user?.name && team?.name) {
createInvitationEmail({
language: t,
toEmail: invitee.email,
from: session.user.name,
teamName: team.name,
+12 -10
View File
@@ -1,29 +1,31 @@
import debounce from "lodash/debounce";
import { GetServerSidePropsContext } from "next";
import { getCsrfToken } from "next-auth/client";
import Link from "next/link";
import React from "react";
import React, { SyntheticEvent } from "react";
import { getSession } from "@lib/auth";
import { useLocale } from "@lib/hooks/useLocale";
import { HeadSeo } from "@components/seo/head-seo";
export default function ForgotPassword({ csrfToken }) {
const { t } = useLocale();
export default function ForgotPassword({ csrfToken }: { csrfToken: string }) {
const { t, i18n } = useLocale();
const [loading, setLoading] = React.useState(false);
const [error, setError] = React.useState(null);
const [error, setError] = React.useState<{ message: string } | null>(null);
const [success, setSuccess] = React.useState(false);
const [email, setEmail] = React.useState("");
const handleChange = (e) => {
setEmail(e.target.value);
const handleChange = (e: SyntheticEvent) => {
const target = e.target as typeof e.target & { value: string };
setEmail(target.value);
};
const submitForgotPasswordRequest = async ({ email }) => {
const submitForgotPasswordRequest = async ({ email }: { email: string }) => {
try {
const res = await fetch("/api/auth/forgot-password", {
method: "POST",
body: JSON.stringify({ email: email }),
body: JSON.stringify({ email: email, language: i18n.language }),
headers: {
"Content-Type": "application/json",
},
@@ -46,7 +48,7 @@ export default function ForgotPassword({ csrfToken }) {
const debouncedHandleSubmitPasswordRequest = debounce(submitForgotPasswordRequest, 250);
const handleSubmit = async (e) => {
const handleSubmit = async (e: SyntheticEvent) => {
e.preventDefault();
if (!email) {
@@ -157,7 +159,7 @@ export default function ForgotPassword({ csrfToken }) {
);
}
ForgotPassword.getInitialProps = async (context) => {
ForgotPassword.getInitialProps = async (context: GetServerSidePropsContext) => {
const { req, res } = context;
const session = await getSession({ req });
+30 -30
View File
@@ -63,32 +63,35 @@ import * as RadioArea from "@components/ui/form/radio-area";
dayjs.extend(utc);
dayjs.extend(timezone);
const PERIOD_TYPES = [
{
type: "rolling",
suffix: "into the future",
},
{
type: "range",
prefix: "Within a date range",
},
{
type: "unlimited",
prefix: "Indefinitely into the future",
},
];
const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
const { t } = useLocale();
const PERIOD_TYPES = [
{
type: "rolling",
suffix: t("into_the_future"),
},
{
type: "range",
prefix: t("within_date_range"),
},
{
type: "unlimited",
prefix: t("indefinitely_into_future"),
},
];
const { eventType, locationOptions, availability, team, teamMembers, hasPaymentIntegration, currency } =
props;
locationOptions.push(
{ value: LocationType.InPerson, label: t("in_person_meeting") },
{ value: LocationType.Phone, label: t("phone_call") }
);
const { t } = useLocale();
const router = useRouter();
const updateMutation = useMutation(updateEventType, {
onSuccess: async ({ eventType }) => {
await router.push("/event-types");
showToast(`${eventType.title} event type updated successfully`, "success");
showToast(t("event_type_updated_successfully", { eventTypeTitle: eventType.title }), "success");
},
onError: (err: HttpError) => {
const message = `${err.statusCode}: ${err.message}`;
@@ -99,7 +102,7 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
const deleteMutation = useMutation(deleteEventType, {
onSuccess: async () => {
await router.push("/event-types");
showToast("Event type deleted successfully", "success");
showToast(t("event_type_deleted_successfully"), "success");
},
onError: (err: HttpError) => {
const message = `${err.statusCode}: ${err.message}`;
@@ -274,13 +277,13 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
const schedulingTypeOptions: { value: SchedulingType; label: string; description: string }[] = [
{
value: SchedulingType.COLLECTIVE,
label: "Collective",
description: "Schedule meetings when all selected team members are available.",
label: t("collective"),
description: t("collective_description"),
},
{
value: SchedulingType.ROUND_ROBIN,
label: "Round Robin",
description: "Cycle meetings between multiple team members.",
label: t("round_robin"),
description: t("round_robin_description"),
},
];
@@ -311,7 +314,7 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
<div>
<Shell
centered
title={`${eventType.title} | Event Type`}
title={t("event_type_title", { eventTypeTitle: eventType.title })}
heading={
<div className="relative -mb-2 group" onClick={() => setEditIcon(false)}>
<input
@@ -321,7 +324,7 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
id="title"
required
className="w-full pl-0 text-xl font-bold text-gray-900 bg-transparent border-none cursor-pointer focus:text-black hover:text-gray-700 focus:ring-0 focus:outline-none"
placeholder="Quick Chat"
placeholder={t("quick_chat")}
defaultValue={eventType.title}
/>
{editIcon && (
@@ -491,7 +494,7 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
fillRule="evenodd"></path>
</g>
</svg>
<span className="ml-2 text-sm"> Daily.co Video</span>
<span className="ml-2 text-sm">Daily.co Video</span>
</div>
)}
{location.type === LocationType.Zoom && (
@@ -682,7 +685,7 @@ const EventTypePage = (props: inferSSRProps<typeof getServerSideProps>) => {
</div>
<div>
<span className="ml-2 text-sm">
{customInput.required ? "Required" : "Optional"}
{customInput.required ? t("required") : t("optional")}
</span>
</div>
</div>
@@ -1228,10 +1231,7 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
const integrations = getIntegrations(credentials);
const locationOptions: OptionTypeBase[] = [
{ value: LocationType.InPerson, label: "Link or In-person meeting" },
{ value: LocationType.Phone, label: "Phone call" },
];
const locationOptions: OptionTypeBase[] = [];
if (hasIntegration(integrations, "zoom_video")) {
locationOptions.push({ value: LocationType.Zoom, label: "Zoom Video", disabled: true });
+1 -1
View File
@@ -344,7 +344,7 @@ const CreateNewEventButton = ({ profiles, canAddEvents }: CreateEventTypeProps)
const createMutation = useMutation(createEventType, {
onSuccess: async ({ eventType }) => {
await router.push("/event-types/" + eventType.id);
showToast(`${eventType.title} event type created successfully`, "success");
showToast(t("event_type_created_successfully", { eventTypeTitle: eventType.title }), "success");
},
onError: (err: HttpError) => {
const message = `${err.statusCode}: ${err.message}`;