Updated the demographic input to work more as expected

This commit is contained in:
Tiago Ribeiro
2023-09-16 10:27:17 +01:00
parent dc8682e1c3
commit 05ca96e476
7 changed files with 219 additions and 165 deletions

View File

@@ -0,0 +1,153 @@
import {EmploymentStatus, EMPLOYMENT_STATUS, Gender, User} from "@/interfaces/user";
import {FormEvent, useState} from "react";
import countryCodes from "country-codes-list";
import {RadioGroup} from "@headlessui/react";
import Input from "./Low/Input";
import clsx from "clsx";
import Button from "./Low/Button";
import {BsArrowRepeat} from "react-icons/bs";
import axios from "axios";
import {toast} from "react-toastify";
import {KeyedMutator} from "swr";
interface Props {
mutateUser: KeyedMutator<User>;
}
export default function DemographicInformationInput({mutateUser}: Props) {
const [country, setCountry] = useState<string>();
const [phone, setPhone] = useState<string>();
const [gender, setGender] = useState<Gender>();
const [employment, setEmployment] = useState<EmploymentStatus>();
const [isLoading, setIsLoading] = useState(false);
const save = (e?: FormEvent) => {
if (e) e.preventDefault();
setIsLoading(true);
axios
.patch("/api/users/update", {
demographicInformation: {
country,
phone: `+${countryCodes.findOne("countryCode" as any, country!).countryCallingCode}${phone}`,
gender,
employment,
},
})
.then((response) => mutateUser((response.data as {user: User}).user))
.catch(() => {
toast.error("Something went wrong, please try again later!", {toastId: "user-update-error"});
})
.finally(() => setIsLoading(false));
};
return (
<div className="flex flex-col items-center justify-center gap-12 w-full">
<h2 className="font-semibold text-center text-xl max-w-[800px]">
Welcome to EnCoach, the ultimate platform dedicated to helping you master the IELTS ! We are thrilled that you have chosen us as your
learning companion on this journey towards achieving your desired IELTS score.
<br />
<br />
To make the most of your learning experience, we kindly request you to complete your profile. By providing some essential information
about yourself.
</h2>
<form className="flex flex-col items-center justify-items-center gap-6 w-full h-full -lg:px-8 lg:w-1/2 mb-32" onSubmit={save}>
<div className="relative flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Country *</label>
<select
name="country"
className="px-8 py-6 text-sm font-normal placeholder:text-mti-gray-cool bg-white rounded-full border border-mti-gray-platinum focus:outline-none"
onChange={(e) => {
setCountry(e.target.value);
}}
defaultValue={country}>
<option value={undefined} disabled selected>
Select a country
</option>
{countryCodes.all().map((x) => (
<option key={x.countryCode} value={x.countryCode}>
{x.flag} {x.countryNameLocal}
</option>
))}
</select>
</div>
<Input type="tel" name="phone" label="Phone number" onChange={(e) => setPhone(e)} placeholder="Enter phone number" required />
<div className="relative flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Gender *</label>
<RadioGroup value={gender} onChange={setGender} className="flex flex-row justify-between">
<RadioGroup.Option value="male">
{({checked}) => (
<span
className={clsx(
"px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"transition duration-300 ease-in-out",
!checked ? "bg-white border-mti-gray-platinum" : "bg-mti-purple-light border-mti-purple-dark text-white",
)}>
Male
</span>
)}
</RadioGroup.Option>
<RadioGroup.Option value="female">
{({checked}) => (
<span
className={clsx(
"px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"transition duration-300 ease-in-out",
!checked ? "bg-white border-mti-gray-platinum" : "bg-mti-purple-light border-mti-purple-dark text-white",
)}>
Female
</span>
)}
</RadioGroup.Option>
<RadioGroup.Option value="other">
{({checked}) => (
<span
className={clsx(
"px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"transition duration-300 ease-in-out",
!checked ? "bg-white border-mti-gray-platinum" : "bg-mti-purple-light border-mti-purple-dark text-white",
)}>
Other
</span>
)}
</RadioGroup.Option>
</RadioGroup>
</div>
<div className="relative flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Employment Status *</label>
<RadioGroup value={employment} onChange={setEmployment} className="grid grid-cols-2 items-center gap-4 place-items-center">
{EMPLOYMENT_STATUS.map(({status, label}) => (
<RadioGroup.Option value={status} key={status}>
{({checked}) => (
<span
className={clsx(
"px-6 py-4 w-48 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"transition duration-300 ease-in-out",
!checked ? "bg-white border-mti-gray-platinum" : "bg-mti-purple-light border-mti-purple-dark text-white",
)}>
{label}
</span>
)}
</RadioGroup.Option>
))}
</RadioGroup>
</div>
</form>
<div className="self-end flex justify-end w-full gap-8 absolute bottom-8 left-0 px-8">
<Button
className="lg:mt-8 max-w-[400px] w-full self-end"
color="purple"
onClick={save}
disabled={isLoading || !country || !phone || !gender || !employment}>
{!isLoading && "Save information"}
{isLoading && (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
)}
</Button>
</div>
</div>
);
}

View File

@@ -4,7 +4,7 @@ import {Module} from "@/interfaces";
import clsx from "clsx";
import {User} from "@/interfaces/user";
import ProgressBar from "@/components/Low/ProgressBar";
import {BsBook, BsCheckCircle, BsHeadphones, BsMegaphone, BsPen} from "react-icons/bs";
import {BsBook, BsCheck, BsCheckCircle, BsHeadphones, BsMegaphone, BsPen} from "react-icons/bs";
import {totalExamsByModule} from "@/utils/stats";
import useStats from "@/hooks/useStats";
import Button from "@/components/Low/Button";
@@ -19,6 +19,7 @@ interface Props {
export default function Selection({user, onStart, disableSelection = false}: Props) {
const [selectedModules, setSelectedModules] = useState<Module[]>([]);
const [avoidRepeatedExams, setAvoidRepeatedExams] = useState(true);
const {stats} = useStats(user?.id);
const toggleModule = (module: Module) => {
@@ -181,15 +182,31 @@ export default function Selection({user, onStart, disableSelection = false}: Pro
)}
</div>
</section>
<Button
onClick={() =>
onStart(!disableSelection ? selectedModules.sort(sortByModuleName) : ["reading", "listening", "writing", "speaking"])
}
color="purple"
className="px-12 w-full max-w-xs self-end"
disabled={selectedModules.length === 0 && !disableSelection}>
Start Exam
</Button>
<div className="flex w-full justify-between items-center">
<div
className="flex gap-3 items-center text-mti-gray-dim text-sm cursor-pointer"
onClick={() => setAvoidRepeatedExams((prev) => !prev)}>
<input type="checkbox" className="hidden" />
<div
className={clsx(
"w-6 h-6 rounded-sm flex items-center justify-center border border-mti-purple-light bg-white",
"transition duration-300 ease-in-out",
avoidRepeatedExams && "!bg-mti-purple-light ",
)}>
<BsCheck color="white" className="w-full h-full" />
</div>
<span>Avoid Repeated Questions</span>
</div>
<Button
onClick={() =>
onStart(!disableSelection ? selectedModules.sort(sortByModuleName) : ["reading", "listening", "writing", "speaking"])
}
color="purple"
className="px-12 w-full max-w-xs self-end"
disabled={selectedModules.length === 0 && !disableSelection}>
Start Exam
</Button>
</div>
</div>
</>
);

View File

@@ -16,9 +16,9 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
return;
}
const {module} = req.query as {module: string};
const {module, avoidRepeated} = req.query as {module: string; avoidRepeated: string};
const moduleRef = collection(db, module);
const q = query(moduleRef, where("isDiagnostic", "==", false));
const q = query(moduleRef, where("isDiagnostic", "==", true));
const snapshot = await getDocs(q);

View File

@@ -59,10 +59,13 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
delete updatedUser.newPassword;
await setDoc(userRef, updatedUser, {merge: true});
req.session.user = {...updatedUser, id: req.session.user.id};
const docUser = await getDoc(doc(db, "users", req.session.user.id));
const user = docUser.data() as User;
req.session.user = {...user, id: req.session.user.id};
await req.session.save();
res.status(200).json({ok: true});
res.status(200).json({user});
}
export const config = {

View File

@@ -17,6 +17,7 @@ import ProgressBar from "@/components/Low/ProgressBar";
import Layout from "@/components/High/Layout";
import {calculateAverageLevel} from "@/utils/score";
import axios from "axios";
import DemographicInformationInput from "@/components/DemographicInformationInput";
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
const user = req.session.user;
@@ -39,13 +40,36 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
export default function Home() {
const [showDiagnostics, setShowDiagnostics] = useState(false);
const {user} = useUser({redirectTo: "/login"});
const [showDemographicInput, setShowDemographicInput] = useState(false);
const {user, mutateUser} = useUser({redirectTo: "/login"});
const {stats} = useStats(user?.id);
useEffect(() => {
if (user) setShowDiagnostics(user.isFirstLogin);
if (user) {
setShowDemographicInput(!user.demographicInformation);
setShowDiagnostics(user.isFirstLogin);
}
}, [user]);
if (user && showDemographicInput) {
return (
<>
<Head>
<title>EnCoach | Muscat Training Institute</title>
<meta
name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Layout user={user} navDisabled>
<DemographicInformationInput mutateUser={mutateUser} />
</Layout>
</>
);
}
if (user && showDiagnostics) {
return (
<>

View File

@@ -1,30 +1,19 @@
/* eslint-disable @next/next/no-img-element */
import Head from "next/head";
import Navbar from "@/components/Navbar";
import {BsFileEarmarkText, BsPencil, BsStar, BsBook, BsHeadphones, BsPen, BsMegaphone, BsArrowRepeat} from "react-icons/bs";
import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {ChangeEvent, useEffect, useRef, useState} from "react";
import useStats from "@/hooks/useStats";
import {averageScore, totalExams} from "@/utils/stats";
import useUser from "@/hooks/useUser";
import Sidebar from "@/components/Sidebar";
import Diagnostic from "@/components/Diagnostic";
import {toast, ToastContainer} from "react-toastify";
import {capitalize} from "lodash";
import {Module} from "@/interfaces";
import ProgressBar from "@/components/Low/ProgressBar";
import Layout from "@/components/High/Layout";
import {calculateAverageLevel} from "@/utils/score";
import Input from "@/components/Low/Input";
import Button from "@/components/Low/Button";
import {useRouter} from "next/router";
import Link from "next/link";
import axios from "axios";
import {ErrorMessage} from "@/constants/errors";
import {RadioGroup} from "@headlessui/react";
import clsx from "clsx";
import {EmploymentStatus, EMPLOYMENT_STATUS, Gender} from "@/interfaces/user";
import {EmploymentStatus, EMPLOYMENT_STATUS, Gender, User} from "@/interfaces/user";
import countryCodes from "country-codes-list";
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
@@ -61,7 +50,6 @@ export default function Home() {
const [employment, setEmployment] = useState<EmploymentStatus>();
const profilePictureInput = useRef(null);
const router = useRouter();
const {user, mutateUser} = useUser({redirectTo: "/login"});
@@ -129,7 +117,7 @@ export default function Home() {
});
if (request.status === 200) {
toast.success("Your profile has been updated!");
mutateUser();
mutateUser((request.data as {user: User}).user);
setIsLoading(false);
return;
}

View File

@@ -11,22 +11,12 @@ import axios from "axios";
import {Divider} from "primereact/divider";
import {useRouter} from "next/router";
import clsx from "clsx";
import {EmploymentStatus, EMPLOYMENT_STATUS, Gender} from "@/interfaces/user";
import countryCodes from "country-codes-list";
import {RadioGroup} from "@headlessui/react";
export default function Register() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [country, setCountry] = useState<string>();
const [phone, setPhone] = useState<string>();
const [gender, setGender] = useState<Gender>();
const [employment, setEmployment] = useState<EmploymentStatus>();
const [step, setStep] = useState<0 | 1>(0);
const [isLoading, setIsLoading] = useState(false);
const router = useRouter();
@@ -41,7 +31,6 @@ export default function Register() {
if (confirmPassword !== password) {
toast.error("Your passwords do not match!", {toastId: "password-not-match"});
setStep(0);
return;
}
@@ -52,12 +41,6 @@ export default function Register() {
email,
password,
profilePicture: "/defaultAvatar.png",
demographicInformation: {
country,
phone,
gender,
employment,
},
})
.then((response) => {
mutateUser(response.data.user).then(sendEmailVerification);
@@ -67,7 +50,6 @@ export default function Register() {
if (error.response.status === 401) {
toast.error("There is already a user with that e-mail!");
setStep(0);
return;
}
toast.error("There was something wrong, please try again!");
@@ -94,12 +76,7 @@ export default function Register() {
const initialStep = () => (
<>
<form
className="flex flex-col items-center gap-6 w-full -lg:px-8 lg:w-1/2"
onSubmit={(e) => {
e.preventDefault();
setStep(1);
}}>
<form className="flex flex-col items-center gap-6 w-full -lg:px-8 lg:w-1/2" onSubmit={register}>
<Input type="text" name="name" onChange={(e) => setName(e)} placeholder="Enter your name" defaultValue={name} required />
<Input type="email" name="email" onChange={(e) => setEmail(e)} placeholder="Enter email address" defaultValue={email} required />
<Input
@@ -122,114 +99,7 @@ export default function Register() {
className="lg:mt-8 w-full"
color="purple"
disabled={isLoading || !email || !name || !password || !confirmPassword || password !== confirmPassword}>
Next
</Button>
</form>
</>
);
const demographicStep = () => (
<>
<form className="flex flex-col items-center gap-6 w-full -lg:px-8 lg:w-1/2" onSubmit={register}>
<div className="relative flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Country *</label>
<select
name="country"
className="px-8 py-6 text-sm font-normal placeholder:text-mti-gray-cool bg-white rounded-full border border-mti-gray-platinum focus:outline-none"
onChange={(e) => {
setCountry(e.target.value);
}}
defaultValue={country}>
<option value={undefined} disabled selected>
Select a country
</option>
{countryCodes.all().map((x) => (
<option key={x.countryCode} value={x.countryCode}>
{x.flag} {x.countryNameLocal}
</option>
))}
</select>
</div>
<Input
type="tel"
name="phone"
label="Phone number"
onChange={(e) => setPhone(e)}
placeholder="Enter phone number"
defaultValue={phone}
required
/>
<div className="relative flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Gender *</label>
<RadioGroup value={gender} onChange={setGender} className="flex flex-row justify-between">
<RadioGroup.Option value="male">
{({checked}) => (
<span
className={clsx(
"px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"transition duration-300 ease-in-out",
!checked ? "bg-white border-mti-gray-platinum" : "bg-mti-purple-light border-mti-purple-dark text-white",
)}>
Male
</span>
)}
</RadioGroup.Option>
<RadioGroup.Option value="female">
{({checked}) => (
<span
className={clsx(
"px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"transition duration-300 ease-in-out",
!checked ? "bg-white border-mti-gray-platinum" : "bg-mti-purple-light border-mti-purple-dark text-white",
)}>
Female
</span>
)}
</RadioGroup.Option>
<RadioGroup.Option value="other">
{({checked}) => (
<span
className={clsx(
"px-6 py-4 w-28 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"transition duration-300 ease-in-out",
!checked ? "bg-white border-mti-gray-platinum" : "bg-mti-purple-light border-mti-purple-dark text-white",
)}>
Other
</span>
)}
</RadioGroup.Option>
</RadioGroup>
</div>
<div className="relative flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Employment Status *</label>
<RadioGroup value={employment} onChange={setEmployment} className="grid grid-cols-2 items-center gap-4 place-items-center">
{EMPLOYMENT_STATUS.map(({status, label}) => (
<RadioGroup.Option value={status} key={status}>
{({checked}) => (
<span
className={clsx(
"px-6 py-4 w-48 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"transition duration-300 ease-in-out",
!checked ? "bg-white border-mti-gray-platinum" : "bg-mti-purple-light border-mti-purple-dark text-white",
)}>
{label}
</span>
)}
</RadioGroup.Option>
))}
</RadioGroup>
</div>
<Button className="lg:mt-8 w-full" color="purple" disabled={isLoading || !country || !phone || !gender || !employment}>
{!isLoading && "Create account"}
{isLoading && (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
)}
</Button>
<Button className="w-full" color="purple" variant="outline" type="button" onClick={() => setStep(0)} disabled={isLoading}>
Back
Create account
</Button>
</form>
</>
@@ -252,12 +122,11 @@ export default function Register() {
<section className="h-full w-full flex flex-col items-center justify-center gap-4">
<div className={clsx("flex flex-col gap-2 items-center relative", !user && "mb-4")}>
<img src="/logo_title.png" alt="EnCoach's Logo" className="w-36 lg:w-64 absolute -top-36 lg:-top-64" />
<h1 className="font-bold text-2xl lg:text-4xl">{step === 1 ? "Demographic Information" : "Create new account"}</h1>
<h1 className="font-bold text-2xl lg:text-4xl">Create new account</h1>
</div>
{!user && (
<>
{step === 0 && initialStep()}
{step === 1 && demographicStep()}
{initialStep()}
<Link className="text-mti-purple-light text-sm font-normal" href="/login">
Sign in instead
</Link>