Merge branch 'develop' into faeture/payment-history

This commit is contained in:
Tiago Ribeiro
2023-11-30 15:52:16 +00:00
18 changed files with 571 additions and 114 deletions

View File

@@ -37,6 +37,7 @@
"formidable": "^3.5.0", "formidable": "^3.5.0",
"formidable-serverless": "^1.1.1", "formidable-serverless": "^1.1.1",
"framer-motion": "^9.0.2", "framer-motion": "^9.0.2",
"howler": "^2.2.4",
"iron-session": "^6.3.1", "iron-session": "^6.3.1",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"moment": "^2.29.4", "moment": "^2.29.4",
@@ -73,6 +74,7 @@
}, },
"devDependencies": { "devDependencies": {
"@types/formidable": "^3.4.0", "@types/formidable": "^3.4.0",
"@types/howler": "^2.2.11",
"@types/lodash": "^4.14.191", "@types/lodash": "^4.14.191",
"@types/nodemailer": "^6.4.11", "@types/nodemailer": "^6.4.11",
"@types/nodemailer-express-handlebars": "^4.0.3", "@types/nodemailer-express-handlebars": "^4.0.3",

BIN
public/audio/check.mp3 Normal file

Binary file not shown.

BIN
public/audio/sent.mp3 Normal file

Binary file not shown.

View File

@@ -21,6 +21,7 @@ export default function DemographicInformationInput({user, mutateUser}: Props) {
const [phone, setPhone] = useState<string>(); const [phone, setPhone] = useState<string>();
const [gender, setGender] = useState<Gender>(); const [gender, setGender] = useState<Gender>();
const [employment, setEmployment] = useState<EmploymentStatus>(); const [employment, setEmployment] = useState<EmploymentStatus>();
const [position, setPosition] = useState<string>();
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [companyName, setCompanyName] = useState<string>(); const [companyName, setCompanyName] = useState<string>();
@@ -36,7 +37,8 @@ export default function DemographicInformationInput({user, mutateUser}: Props) {
country, country,
phone: `+${countryCodes.findOne("countryCode" as any, country!).countryCallingCode}${phone}`, phone: `+${countryCodes.findOne("countryCode" as any, country!).countryCallingCode}${phone}`,
gender, gender,
employment, employment: user.type === "corporate" ? undefined : employment,
position: user.type === "corporate" ? position : undefined,
}, },
agentInformation: user.type === "agent" ? {companyName, commercialRegistration} : undefined, agentInformation: user.type === "agent" ? {companyName, commercialRegistration} : undefined,
}) })
@@ -116,6 +118,10 @@ export default function DemographicInformationInput({user, mutateUser}: Props) {
</RadioGroup.Option> </RadioGroup.Option>
</RadioGroup> </RadioGroup>
</div> </div>
{user.type === "corporate" && (
<Input name="position" onChange={setPosition} type="text" label="Position" placeholder="CEO, Head of Marketing..." required />
)}
{user.type !== "corporate" && (
<div className="relative flex flex-col gap-3 w-full"> <div className="relative flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Employment Status *</label> <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"> <RadioGroup value={employment} onChange={setEmployment} className="grid grid-cols-2 items-center gap-4 place-items-center">
@@ -126,7 +132,9 @@ export default function DemographicInformationInput({user, mutateUser}: Props) {
className={clsx( className={clsx(
"px-6 py-4 w-44 md:w-48 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer", "px-6 py-4 w-44 md:w-48 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"transition duration-300 ease-in-out", "transition duration-300 ease-in-out",
!checked ? "bg-white border-mti-gray-platinum" : "bg-mti-purple-light border-mti-purple-dark text-white", !checked
? "bg-white border-mti-gray-platinum"
: "bg-mti-purple-light border-mti-purple-dark text-white",
)}> )}>
{label} {label}
</span> </span>
@@ -135,6 +143,7 @@ export default function DemographicInformationInput({user, mutateUser}: Props) {
))} ))}
</RadioGroup> </RadioGroup>
</div> </div>
)}
</form> </form>
<div className="self-end flex justify-end w-full gap-8 absolute bottom-8 left-0 px-8"> <div className="self-end flex justify-end w-full gap-8 absolute bottom-8 left-0 px-8">
@@ -147,7 +156,7 @@ export default function DemographicInformationInput({user, mutateUser}: Props) {
!country || !country ||
!phone || !phone ||
!gender || !gender ||
!employment || (user.type === "corporate" ? !position : !employment) ||
(user.type === "agent" ? !companyName || !commercialRegistration : false) (user.type === "agent" ? !companyName || !commercialRegistration : false)
}> }>
{!isLoading && "Save information"} {!isLoading && "Save information"}

View File

@@ -42,6 +42,7 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers}:
const [type, setType] = useState(user.type); const [type, setType] = useState(user.type);
const [status, setStatus] = useState(user.status); const [status, setStatus] = useState(user.status);
const [referralAgentLabel, setReferralAgentLabel] = useState<string>(); const [referralAgentLabel, setReferralAgentLabel] = useState<string>();
const [position, setPosition] = useState<string | undefined>(user.type === "corporate" ? user.demographicInformation?.position : undefined);
const [referralAgent, setReferralAgent] = useState(user.type === "corporate" ? user.corporateInformation?.referralAgent : undefined); const [referralAgent, setReferralAgent] = useState(user.type === "corporate" ? user.corporateInformation?.referralAgent : undefined);
const [companyName, setCompanyName] = useState( const [companyName, setCompanyName] = useState(
@@ -177,11 +178,11 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers}:
defaultValue={companyName} defaultValue={companyName}
/> />
<Input <Input
label="Amount of Users" label="Number of Users"
type="number" type="number"
name="userAmount" name="userAmount"
onChange={(e) => setUserAmount(e ? parseInt(e) : undefined)} onChange={(e) => setUserAmount(e ? parseInt(e) : undefined)}
placeholder="Enter amount of users" placeholder="Enter number of users"
defaultValue={userAmount} defaultValue={userAmount}
/> />
<Input <Input
@@ -190,7 +191,7 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers}:
name="monthlyDuration" name="monthlyDuration"
onChange={(e) => setMonthlyDuration(e ? parseInt(e) : undefined)} onChange={(e) => setMonthlyDuration(e ? parseInt(e) : undefined)}
placeholder="Enter monthly duration" placeholder="Enter monthly duration"
defaultValue={userAmount} defaultValue={monthlyDuration}
/> />
<div className="flex flex-col gap-3 w-full"> <div className="flex flex-col gap-3 w-full">
@@ -292,6 +293,7 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers}:
</div> </div>
<div className="flex flex-col md:flex-row gap-8 w-full"> <div className="flex flex-col md:flex-row gap-8 w-full">
{user.type !== "corporate" && (
<div className="relative flex flex-col gap-3 w-full"> <div className="relative flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Employment Status</label> <label className="font-normal text-base text-mti-gray-dim">Employment Status</label>
<RadioGroup <RadioGroup
@@ -315,6 +317,19 @@ const UserCard = ({user, loggedInUser, onClose, onViewStudents, onViewTeachers}:
))} ))}
</RadioGroup> </RadioGroup>
</div> </div>
)}
{user.type === "corporate" && (
<Input
name="position"
onChange={setPosition}
type="text"
label="Position"
defaultValue={position}
placeholder="CEO, Head of Marketing..."
disabled
required
/>
)}
<div className="flex flex-col gap-8 w-full"> <div className="flex flex-col gap-8 w-full">
<div className="relative flex flex-col gap-3 w-full"> <div className="relative flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Gender</label> <label className="font-normal text-base text-mti-gray-dim">Gender</label>

View File

@@ -14,7 +14,6 @@ export interface BasicUser {
type: Type; type: Type;
bio: string; bio: string;
isVerified: boolean; isVerified: boolean;
demographicInformation?: DemographicInformation;
subscriptionExpirationDate?: null | Date; subscriptionExpirationDate?: null | Date;
registrationDate?: Date; registrationDate?: Date;
status: "active" | "disabled" | "paymentDue"; status: "active" | "disabled" | "paymentDue";
@@ -22,28 +21,34 @@ export interface BasicUser {
export interface StudentUser extends BasicUser { export interface StudentUser extends BasicUser {
type: "student"; type: "student";
demographicInformation?: DemographicInformation;
} }
export interface TeacherUser extends BasicUser { export interface TeacherUser extends BasicUser {
type: "teacher"; type: "teacher";
demographicInformation?: DemographicInformation;
} }
export interface CorporateUser extends BasicUser { export interface CorporateUser extends BasicUser {
type: "corporate"; type: "corporate";
corporateInformation: CorporateInformation; corporateInformation: CorporateInformation;
demographicInformation?: DemographicCorporateInformation;
} }
export interface AgentUser extends BasicUser { export interface AgentUser extends BasicUser {
type: "agent"; type: "agent";
agentInformation: AgentInformation; agentInformation: AgentInformation;
demographicInformation?: DemographicInformation;
} }
export interface AdminUser extends BasicUser { export interface AdminUser extends BasicUser {
type: "admin"; type: "admin";
demographicInformation?: DemographicInformation;
} }
export interface DeveloperUser extends BasicUser { export interface DeveloperUser extends BasicUser {
type: "developer"; type: "developer";
demographicInformation?: DemographicInformation;
} }
export interface CorporateInformation { export interface CorporateInformation {
@@ -73,6 +78,13 @@ export interface DemographicInformation {
employment: EmploymentStatus; employment: EmploymentStatus;
} }
export interface DemographicCorporateInformation {
country: string;
phone: string;
gender: Gender;
position: string;
}
export type Gender = "male" | "female" | "other"; export type Gender = "male" | "female" | "other";
export type EmploymentStatus = "employed" | "student" | "self-employed" | "unemployed" | "retired" | "other"; export type EmploymentStatus = "employed" | "student" | "self-employed" | "unemployed" | "retired" | "other";
export const EMPLOYMENT_STATUS: {status: EmploymentStatus; label: string}[] = [ export const EMPLOYMENT_STATUS: {status: EmploymentStatus; label: string}[] = [

View File

@@ -242,14 +242,15 @@ export default function UserList({user, filter}: {user: User; filter?: (user: Us
cell: (info) => info.getValue() || "Not available", cell: (info) => info.getValue() || "Not available",
enableSorting: true, enableSorting: true,
}), }),
columnHelper.accessor("demographicInformation.employment", { columnHelper.accessor((x) => (x.type === "corporate" ? x.demographicInformation?.position : x.demographicInformation?.employment), {
id: "employment",
header: ( header: (
<button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "employment"))}> <button className="flex gap-2 items-center" onClick={() => setSorter((prev) => selectSorter(prev, "employment"))}>
<span>Employment</span> <span>Employment/Position</span>
<SorterArrow name="employment" /> <SorterArrow name="employment" />
</button> </button>
) as any, ) as any,
cell: (info) => capitalize(info.getValue()) || "Not available", cell: (info) => (info.row.original.type === "corporate" ? info.getValue() : capitalize(info.getValue())) || "Not available",
enableSorting: true, enableSorting: true,
}), }),
columnHelper.accessor("demographicInformation.gender", { columnHelper.accessor("demographicInformation.gender", {
@@ -419,13 +420,14 @@ export default function UserList({user, filter}: {user: User; filter?: (user: Us
} }
if (sorter === "employment" || sorter === reverseString("employment")) { if (sorter === "employment" || sorter === reverseString("employment")) {
if (!a.demographicInformation?.employment && b.demographicInformation?.employment) return sorter === "employment" ? -1 : 1; const aSortingItem = a.type === "corporate" ? a.demographicInformation?.position : a.demographicInformation?.employment;
if (a.demographicInformation?.employment && !b.demographicInformation?.employment) return sorter === "employment" ? 1 : -1; const bSortingItem = b.type === "corporate" ? b.demographicInformation?.position : b.demographicInformation?.employment;
if (!a.demographicInformation?.employment && !b.demographicInformation?.employment) return 0;
return sorter === "employment" if (!aSortingItem && bSortingItem) return sorter === "employment" ? -1 : 1;
? a.demographicInformation!.employment.localeCompare(b.demographicInformation!.employment) if (aSortingItem && !bSortingItem) return sorter === "employment" ? 1 : -1;
: b.demographicInformation!.employment.localeCompare(a.demographicInformation!.employment); if (!aSortingItem && !bSortingItem) return 0;
return sorter === "employment" ? aSortingItem!.localeCompare(bSortingItem!) : bSortingItem!.localeCompare(aSortingItem!);
} }
if (sorter === "gender" || sorter === reverseString("gender")) { if (sorter === "gender" || sorter === reverseString("gender")) {

View File

@@ -1,6 +1,7 @@
import {LevelExam, MultipleChoiceExercise} from "@/interfaces/exam"; import {LevelExam, MultipleChoiceExercise} from "@/interfaces/exam";
import useExamStore from "@/stores/examStore"; import useExamStore from "@/stores/examStore";
import {getExamById} from "@/utils/exams"; import {getExamById} from "@/utils/exams";
import {playSound} from "@/utils/sound";
import {Tab} from "@headlessui/react"; import {Tab} from "@headlessui/react";
import axios from "axios"; import axios from "axios";
import clsx from "clsx"; import clsx from "clsx";
@@ -18,6 +19,7 @@ const TaskTab = ({exam, setExam}: {exam?: LevelExam; setExam: (exam: LevelExam)
axios axios
.get(`/api/exam/level/generate/level`) .get(`/api/exam/level/generate/level`)
.then((result) => { .then((result) => {
playSound("check");
console.log(result.data); console.log(result.data);
setExam(result.data); setExam(result.data);
}) })
@@ -135,6 +137,7 @@ const LevelGeneration = () => {
axios axios
.post(`/api/exam/level`, exam) .post(`/api/exam/level`, exam)
.then((result) => { .then((result) => {
playSound("sent");
console.log(`Generated Exam ID: ${result.data.id}`); console.log(`Generated Exam ID: ${result.data.id}`);
toast.success("This new exam has been generated successfully! Check the ID in our browser's console."); toast.success("This new exam has been generated successfully! Check the ID in our browser's console.");
setResultingExam(result.data); setResultingExam(result.data);

View File

@@ -1,9 +1,13 @@
import Input from "@/components/Low/Input"; import Input from "@/components/Low/Input";
import {ListeningPart} from "@/interfaces/exam"; import {Exercise, ListeningExam} from "@/interfaces/exam";
import useExamStore from "@/stores/examStore";
import {getExamById} from "@/utils/exams";
import {playSound} from "@/utils/sound";
import {convertCamelCaseToReadable} from "@/utils/string"; import {convertCamelCaseToReadable} from "@/utils/string";
import {Tab} from "@headlessui/react"; import {Tab} from "@headlessui/react";
import axios from "axios"; import axios from "axios";
import clsx from "clsx"; import clsx from "clsx";
import {useRouter} from "next/router";
import {useState} from "react"; import {useState} from "react";
import {BsArrowRepeat} from "react-icons/bs"; import {BsArrowRepeat} from "react-icons/bs";
import {toast} from "react-toastify"; import {toast} from "react-toastify";
@@ -20,8 +24,11 @@ const PartTab = ({part, types, index, setPart}: {part?: ListeningPart; types: st
setPart(undefined); setPart(undefined);
setIsLoading(true); setIsLoading(true);
axios axios
.get(`/api/exam/listening/generate/listening_passage_${index}${topic || types ? `?${url.toString()}` : ""}`) .get(`/api/exam/listening/generate/listening_section_${index}${topic || types ? `?${url.toString()}` : ""}`)
.then((result) => setPart(result.data)) .then((result) => {
playSound("check");
setPart(result.data);
})
.catch((error) => { .catch((error) => {
console.log(error); console.log(error);
toast.error("Something went wrong!"); toast.error("Something went wrong!");
@@ -67,27 +74,101 @@ const PartTab = ({part, types, index, setPart}: {part?: ListeningPart; types: st
</span> </span>
))} ))}
</div> </div>
{typeof part.text === "string" && <span className="w-full h-96">{part.text.replaceAll("\n\n", " ")}</span>}
{typeof part.text !== "string" && (
<div className="w-full h-96 flex flex-col gap-2">
{part.text.conversation.map((x, index) => (
<span key={index} className="flex gap-1">
<span className="font-semibold">{x.name}:</span>
{x.text.replaceAll("\n\n", " ")}
</span>
))}
</div>
)}
</div> </div>
)} )}
</Tab.Panel> </Tab.Panel>
); );
}; };
interface ListeningPart {
exercises: Exercise[];
text:
| {
conversation: {
gender: string;
name: string;
text: string;
voice: string;
}[];
}
| string;
}
const ListeningGeneration = () => { const ListeningGeneration = () => {
const [part1, setPart1] = useState<ListeningPart>(); const [part1, setPart1] = useState<ListeningPart>();
const [part2, setPart2] = useState<ListeningPart>(); const [part2, setPart2] = useState<ListeningPart>();
const [part3, setPart3] = useState<ListeningPart>(); const [part3, setPart3] = useState<ListeningPart>();
const [part4, setPart4] = useState<ListeningPart>();
const [isLoading, setIsLoading] = useState(false);
const [resultingExam, setResultingExam] = useState<ListeningExam>();
const [types, setTypes] = useState<string[]>([]); const [types, setTypes] = useState<string[]>([]);
const availableTypes = [ const availableTypes = [
{type: "fillBlanks", label: "Fill the Blanks"},
{type: "multipleChoice", label: "Multiple Choice"}, {type: "multipleChoice", label: "Multiple Choice"},
{type: "trueFalse", label: "True or False"}, {type: "writeBlanksQuestions", label: "Write the Blanks: Questions"},
{type: "writeBlanks", label: "Write the Blanks"}, {type: "writeBlanksFill", label: "Write the Blanks: Fill"},
{type: "writeBlanksForm", label: "Write the Blanks: Form"},
]; ];
const router = useRouter();
const setExams = useExamStore((state) => state.setExams);
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
const toggleType = (type: string) => setTypes((prev) => (prev.includes(type) ? [...prev.filter((x) => x !== type)] : [...prev, type])); const toggleType = (type: string) => setTypes((prev) => (prev.includes(type) ? [...prev.filter((x) => x !== type)] : [...prev, type]));
const submitExam = () => {
if (!part1 || !part2 || !part3 || !part4) return toast.error("Please generate all for sections!");
setIsLoading(true);
axios
.post(`/api/exam/listening/generate/listening`, {parts: [part1, part2, part3, part4]})
.then((result) => {
playSound("sent");
console.log(`Generated Exam ID: ${result.data.id}`);
toast.success("This new exam has been generated successfully! Check the ID in our browser's console.");
setResultingExam(result.data);
setPart1(undefined);
setPart2(undefined);
setPart3(undefined);
setTypes([]);
})
.catch((error) => {
console.log(error);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
const loadExam = async (examId: string) => {
const exam = await getExamById("listening", examId.trim());
if (!exam) {
toast.error("Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID", {
toastId: "invalid-exam-id",
});
return;
}
setExams([exam]);
setSelectedModules(["listening"]);
router.push("/exercises");
};
return ( return (
<> <>
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3">
@@ -121,7 +202,7 @@ const ListeningGeneration = () => {
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening", selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening",
) )
}> }>
Passage 1 Section 1
</Tab> </Tab>
<Tab <Tab
className={({selected}) => className={({selected}) =>
@@ -132,7 +213,7 @@ const ListeningGeneration = () => {
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening", selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening",
) )
}> }>
Passage 2 Section 2
</Tab> </Tab>
<Tab <Tab
className={({selected}) => className={({selected}) =>
@@ -143,7 +224,18 @@ const ListeningGeneration = () => {
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening", selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening",
) )
}> }>
Passage 3 Section 3
</Tab>
<Tab
className={({selected}) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-listening/70",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening",
)
}>
Section 4
</Tab> </Tab>
</Tab.List> </Tab.List>
<Tab.Panels> <Tab.Panels>
@@ -151,22 +243,44 @@ const ListeningGeneration = () => {
{part: part1, setPart: setPart1}, {part: part1, setPart: setPart1},
{part: part2, setPart: setPart2}, {part: part2, setPart: setPart2},
{part: part3, setPart: setPart3}, {part: part3, setPart: setPart3},
{part: part4, setPart: setPart4},
].map(({part, setPart}, index) => ( ].map(({part, setPart}, index) => (
<PartTab part={part} types={types} index={index + 1} key={index} setPart={setPart} /> <PartTab part={part} types={types} index={index + 1} key={index} setPart={setPart} />
))} ))}
</Tab.Panels> </Tab.Panels>
</Tab.Group> </Tab.Group>
<div className="w-full flex justify-end gap-4">
{resultingExam && (
<button <button
disabled={!part1 || !part2 || !part3} disabled={isLoading}
data-tip="Please generate all three passages" onClick={() => loadExam(resultingExam.id)}
className={clsx( className={clsx(
"bg-ielts-listening/70 border border-ielts-listening text-white w-full max-w-[200px] px-6 py-6 rounded-xl h-[70px] self-end", "bg-white border border-ielts-listening text-ielts-listening w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-listening hover:text-white disabled:bg-ielts-listening/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
)}>
Perform Exam
</button>
)}
<button
disabled={!part1 || !part2 || !part3 || !part4 || isLoading}
data-tip="Please generate all three passages"
onClick={submitExam}
className={clsx(
"bg-ielts-listening/70 border border-ielts-listening text-white w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-listening disabled:bg-ielts-listening/40 disabled:cursor-not-allowed", "hover:bg-ielts-listening disabled:bg-ielts-listening/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300", "transition ease-in-out duration-300",
(!part1 || !part2 || !part3) && "tooltip", (!part1 || !part2 || !part3 || !part4) && "tooltip",
)}> )}>
Submit {isLoading ? (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
) : (
"Submit"
)}
</button> </button>
</div>
</> </>
); );
}; };

View File

@@ -2,6 +2,7 @@ import Input from "@/components/Low/Input";
import {ReadingExam, ReadingPart} from "@/interfaces/exam"; import {ReadingExam, ReadingPart} from "@/interfaces/exam";
import useExamStore from "@/stores/examStore"; import useExamStore from "@/stores/examStore";
import {getExamById} from "@/utils/exams"; import {getExamById} from "@/utils/exams";
import {playSound} from "@/utils/sound";
import {convertCamelCaseToReadable} from "@/utils/string"; import {convertCamelCaseToReadable} from "@/utils/string";
import {Tab} from "@headlessui/react"; import {Tab} from "@headlessui/react";
import axios from "axios"; import axios from "axios";
@@ -25,7 +26,10 @@ const PartTab = ({part, types, index, setPart}: {part?: ReadingPart; types: stri
setIsLoading(true); setIsLoading(true);
axios axios
.get(`/api/exam/reading/generate/reading_passage_${index}${topic || types ? `?${url.toString()}` : ""}`) .get(`/api/exam/reading/generate/reading_passage_${index}${topic || types ? `?${url.toString()}` : ""}`)
.then((result) => setPart(result.data)) .then((result) => {
playSound("check");
setPart(result.data);
})
.catch((error) => { .catch((error) => {
console.log(error); console.log(error);
toast.error("Something went wrong!"); toast.error("Something went wrong!");
@@ -136,6 +140,7 @@ const ReadingGeneration = () => {
axios axios
.post(`/api/exam/reading`, exam) .post(`/api/exam/reading`, exam)
.then((result) => { .then((result) => {
playSound("sent");
console.log(`Generated Exam ID: ${result.data.id}`); console.log(`Generated Exam ID: ${result.data.id}`);
toast.success("This new exam has been generated successfully! Check the ID in our browser's console."); toast.success("This new exam has been generated successfully! Check the ID in our browser's console.");
setResultingExam(result.data); setResultingExam(result.data);

View File

@@ -0,0 +1,234 @@
import Input from "@/components/Low/Input";
import {Exercise, SpeakingExam} from "@/interfaces/exam";
import useExamStore from "@/stores/examStore";
import {getExamById} from "@/utils/exams";
import {playSound} from "@/utils/sound";
import {convertCamelCaseToReadable} from "@/utils/string";
import {Tab} from "@headlessui/react";
import axios from "axios";
import clsx from "clsx";
import {useRouter} from "next/router";
import {useState} from "react";
import {BsArrowRepeat} from "react-icons/bs";
import {toast} from "react-toastify";
const PartTab = ({part, index, setPart}: {part?: SpeakingPart; index: number; setPart: (part?: SpeakingPart) => void}) => {
const [isLoading, setIsLoading] = useState(false);
const generate = () => {
setPart(undefined);
setIsLoading(true);
axios
.get(`/api/exam/speaking/generate/speaking_task_${index}`)
.then((result) => {
playSound("check");
setPart(result.data);
})
.catch((error) => {
console.log(error);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
return (
<Tab.Panel className="w-full bg-ielts-speaking/20 min-h-[600px] h-full rounded-xl p-6 flex flex-col gap-4">
<div className="flex gap-4 items-end">
<button
onClick={generate}
disabled={isLoading}
data-tip="The passage is currently being generated"
className={clsx(
"bg-ielts-speaking/70 border border-ielts-speaking text-white w-full rounded-xl h-[70px]",
"hover:bg-ielts-speaking disabled:bg-ielts-speaking/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
isLoading && "tooltip",
)}>
{isLoading ? (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
) : (
"Generate"
)}
</button>
</div>
{isLoading && (
<div className="w-fit h-fit mt-12 self-center animate-pulse flex flex-col gap-8 items-center">
<span className={clsx("loading loading-infinity w-32 text-ielts-speaking")} />
<span className={clsx("font-bold text-2xl text-ielts-speaking")}>Generating...</span>
</div>
)}
{part && (
<div className="flex flex-col gap-2 w-full overflow-y-scroll scrollbar-hide h-96">
<h3 className="text-xl font-semibold">{part.topic}</h3>
{part.question && <span className="w-full">{part.question}</span>}
{part.questions && (
<div className="flex flex-col gap-1">
{part.questions.map((question, index) => (
<span className="w-full" key={index}>
- {question}
</span>
))}
</div>
)}
{part.prompts && (
<div className="flex flex-col gap-1">
<span className="font-medium">You should talk about the following things:</span>
{part.prompts.map((prompt, index) => (
<span className="w-full" key={index}>
- {prompt}
</span>
))}
</div>
)}
</div>
)}
</Tab.Panel>
);
};
interface SpeakingPart {
prompts?: string[];
question?: string;
questions?: string[];
topic: string;
}
const SpeakingGeneration = () => {
const [part1, setPart1] = useState<SpeakingPart>();
const [part2, setPart2] = useState<SpeakingPart>();
const [part3, setPart3] = useState<SpeakingPart>();
const [isLoading, setIsLoading] = useState(false);
const [resultingExam, setResultingExam] = useState<SpeakingExam>();
const router = useRouter();
const setExams = useExamStore((state) => state.setExams);
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
const submitExam = () => {
if (!part1 || !part2 || !part3) return toast.error("Please generate all for tasks!");
setIsLoading(true);
axios
.post(`/api/exam/speaking/generate/speaking`, {exercises: [part1, part2, part3]})
.then((result) => {
playSound("sent");
console.log(`Generated Exam ID: ${result.data.id}`);
toast.success("This new exam has been generated successfully! Check the ID in our browser's console.");
setResultingExam(result.data);
setPart1(undefined);
setPart2(undefined);
setPart3(undefined);
})
.catch((error) => {
console.log(error);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
const loadExam = async (examId: string) => {
const exam = await getExamById("speaking", examId.trim());
if (!exam) {
toast.error("Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID", {
toastId: "invalid-exam-id",
});
return;
}
setExams([exam]);
setSelectedModules(["speaking"]);
router.push("/exercises");
};
return (
<>
<Tab.Group>
<Tab.List className="flex space-x-1 rounded-xl bg-ielts-speaking/20 p-1">
<Tab
className={({selected}) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/70",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-speaking",
)
}>
Task 1
</Tab>
<Tab
className={({selected}) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/70",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-speaking",
)
}>
Task 2
</Tab>
<Tab
className={({selected}) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/70",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-speaking",
)
}>
Task 3
</Tab>
</Tab.List>
<Tab.Panels>
{[
{part: part1, setPart: setPart1},
{part: part2, setPart: setPart2},
{part: part3, setPart: setPart3},
].map(({part, setPart}, index) => (
<PartTab part={part} index={index + 1} key={index} setPart={setPart} />
))}
</Tab.Panels>
</Tab.Group>
<div className="w-full flex justify-end gap-4">
{resultingExam && (
<button
disabled={isLoading}
onClick={() => loadExam(resultingExam.id)}
className={clsx(
"bg-white border border-ielts-speaking text-ielts-speaking w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-speaking hover:text-white disabled:bg-ielts-speaking/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
)}>
Perform Exam
</button>
)}
<button
disabled={!part1 || !part2 || !part3 || isLoading}
data-tip="Please generate all three passages"
onClick={submitExam}
className={clsx(
"bg-ielts-speaking/70 border border-ielts-speaking text-white w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-speaking disabled:bg-ielts-speaking/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
(!part1 || !part2 || !part3) && "tooltip",
)}>
{isLoading ? (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
) : (
"Submit"
)}
</button>
</div>
</>
);
};
export default SpeakingGeneration;

View File

@@ -2,6 +2,7 @@ import Input from "@/components/Low/Input";
import {WritingExam} from "@/interfaces/exam"; import {WritingExam} from "@/interfaces/exam";
import useExamStore from "@/stores/examStore"; import useExamStore from "@/stores/examStore";
import {getExamById} from "@/utils/exams"; import {getExamById} from "@/utils/exams";
import {playSound} from "@/utils/sound";
import {Tab} from "@headlessui/react"; import {Tab} from "@headlessui/react";
import axios from "axios"; import axios from "axios";
import clsx from "clsx"; import clsx from "clsx";
@@ -18,7 +19,10 @@ const TaskTab = ({task, index, setTask}: {task?: string; index: number; setTask:
setIsLoading(true); setIsLoading(true);
axios axios
.get(`/api/exam/writing/generate/writing_task${index}_general`) .get(`/api/exam/writing/generate/writing_task${index}_general`)
.then((result) => setTask(result.data.question)) .then((result) => {
playSound("check");
setTask(result.data.question);
})
.catch((error) => { .catch((error) => {
console.log(error); console.log(error);
toast.error("Something went wrong!"); toast.error("Something went wrong!");
@@ -132,6 +136,7 @@ const WritingGeneration = () => {
.post(`/api/exam/writing`, exam) .post(`/api/exam/writing`, exam)
.then((result) => { .then((result) => {
console.log(`Generated Exam ID: ${result.data.id}`); console.log(`Generated Exam ID: ${result.data.id}`);
playSound("sent");
toast.success("This new exam has been generated successfully! Check the ID in our browser's console."); toast.success("This new exam has been generated successfully! Check the ID in our browser's console.");
setResultingExam(result.data); setResultingExam(result.data);

View File

@@ -15,15 +15,15 @@ const db = getFirestore(app);
export default withIronSessionApiRoute(handler, sessionOptions); export default withIronSessionApiRoute(handler, sessionOptions);
async function handler(req: NextApiRequest, res: NextApiResponse) { async function handler(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) { if (req.method === "GET") return get(req, res);
res.status(401).json({ok: false}); if (req.method === "POST") return post(req, res);
return;
}
if (req.session.user.type !== "developer") { return res.status(404).json({ok: false});
res.status(403).json({ok: false}); }
return;
} async function get(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) return res.status(401).json({ok: false});
if (req.session.user.type !== "developer") return res.status(403).json({ok: false});
const {endpoint, topic, exercises} = req.query as {module: Module; endpoint: string; topic?: string; exercises?: string[]}; const {endpoint, topic, exercises} = req.query as {module: Module; endpoint: string; topic?: string; exercises?: string[]};
const url = `${process.env.BACKEND_URL}/${endpoint}`; const url = `${process.env.BACKEND_URL}/${endpoint}`;
@@ -34,3 +34,21 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json(result.data); res.status(200).json(result.data);
} }
async function post(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) return res.status(401).json({ok: false});
if (req.session.user.type !== "developer") return res.status(403).json({ok: false});
const {endpoint, topic, exercises} = req.query as {module: Module; endpoint: string; topic?: string; exercises?: string[]};
const url = `${process.env.BACKEND_URL}/${endpoint}`;
const result = await axios.post(
`${url}${topic && exercises ? `?topic=${topic.toLowerCase()}&exercises=${exercises.join("&exercises=")}` : ""}`,
req.body,
{
headers: {Authorization: `Bearer ${process.env.BACKEND_JWT}`},
},
);
res.status(200).json(result.data);
}

View File

@@ -20,6 +20,7 @@ import ReadingGeneration from "./(generation)/ReadingGeneration";
import ListeningGeneration from "./(generation)/ListeningGeneration"; import ListeningGeneration from "./(generation)/ListeningGeneration";
import WritingGeneration from "./(generation)/WritingGeneration"; import WritingGeneration from "./(generation)/WritingGeneration";
import LevelGeneration from "./(generation)/LevelGeneration"; import LevelGeneration from "./(generation)/LevelGeneration";
import SpeakingGeneration from "./(generation)/SpeakingGeneration";
export const getServerSideProps = withIronSessionSsr(({req, res}) => { export const getServerSideProps = withIronSessionSsr(({req, res}) => {
const user = req.session.user; const user = req.session.user;
@@ -115,6 +116,7 @@ export default function Generation() {
{module === "reading" && <ReadingGeneration />} {module === "reading" && <ReadingGeneration />}
{module === "listening" && <ListeningGeneration />} {module === "listening" && <ListeningGeneration />}
{module === "writing" && <WritingGeneration />} {module === "writing" && <WritingGeneration />}
{module === "speaking" && <SpeakingGeneration />}
{module === "level" && <LevelGeneration />} {module === "level" && <LevelGeneration />}
</Layout> </Layout>
)} )}

View File

@@ -68,7 +68,7 @@ export default function Home({envVariables}: {envVariables: {[key: string]: stri
useEffect(() => { useEffect(() => {
if (user) { if (user) {
setShowDemographicInput(!user.demographicInformation); setShowDemographicInput(!user.demographicInformation);
setShowDiagnostics(user.isFirstLogin); setShowDiagnostics(user.isFirstLogin && user.type === "student");
} }
}, [user]); }, [user]);

View File

@@ -63,6 +63,7 @@ export default function Home() {
const [phone, setPhone] = useState<string>(); const [phone, setPhone] = useState<string>();
const [gender, setGender] = useState<Gender>(); const [gender, setGender] = useState<Gender>();
const [employment, setEmployment] = useState<EmploymentStatus>(); const [employment, setEmployment] = useState<EmploymentStatus>();
const [position, setPosition] = useState<string>();
const profilePictureInput = useRef(null); const profilePictureInput = useRef(null);
@@ -86,7 +87,8 @@ export default function Home() {
setCountry(user.demographicInformation?.country); setCountry(user.demographicInformation?.country);
setPhone(user.demographicInformation?.phone); setPhone(user.demographicInformation?.phone);
setGender(user.demographicInformation?.gender); setGender(user.demographicInformation?.gender);
setEmployment(user.demographicInformation?.employment); setEmployment(user.type === "corporate" ? undefined : user.demographicInformation?.employment);
setPosition(user.type === "corporate" ? user.demographicInformation?.position : undefined);
} }
}, [user]); }, [user]);
@@ -135,7 +137,8 @@ export default function Home() {
demographicInformation: { demographicInformation: {
phone, phone,
country, country,
employment, employment: user?.type === "corporate" ? undefined : employment,
position: user?.type === "corporate" ? position : undefined,
gender, gender,
}, },
}); });
@@ -247,6 +250,18 @@ export default function Home() {
/> />
</div> </div>
<div className="flex flex-col md:flex-row gap-8 w-full"> <div className="flex flex-col md:flex-row gap-8 w-full">
{user.type === "corporate" && (
<Input
name="position"
onChange={setPosition}
defaultValue={position}
type="text"
label="Position"
placeholder="CEO, Head of Marketing..."
required
/>
)}
{user.type !== "corporate" && (
<div className="relative flex flex-col gap-3 w-full"> <div className="relative flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Employment Status *</label> <label className="font-normal text-base text-mti-gray-dim">Employment Status *</label>
<RadioGroup <RadioGroup
@@ -271,6 +286,7 @@ export default function Home() {
))} ))}
</RadioGroup> </RadioGroup>
</div> </div>
)}
<div className="flex flex-col gap-8 w-full"> <div className="flex flex-col gap-8 w-full">
<div className="relative flex flex-col gap-3 w-full"> <div className="relative flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Gender *</label> <label className="font-normal text-base text-mti-gray-dim">Gender *</label>

10
src/utils/sound.ts Normal file
View File

@@ -0,0 +1,10 @@
import {Howl, Howler} from "howler";
export type Sound = "check" | "sent";
export const playSound = (path: Sound) => {
const sound = new Howl({
src: [`audio/${path}.mp3`],
});
sound.play();
};

View File

@@ -1144,6 +1144,11 @@
"@types/minimatch" "^5.1.2" "@types/minimatch" "^5.1.2"
"@types/node" "*" "@types/node" "*"
"@types/howler@^2.2.11":
version "2.2.11"
resolved "https://registry.yarnpkg.com/@types/howler/-/howler-2.2.11.tgz#a75c4ab5666aee5fcfbd5de15d35dbaaa3d3f070"
integrity sha512-7aBoUL6RbSIrqKnpEgfa1wSNUBK06mn08siP2QI0zYk7MXfEJAaORc4tohamQYqCqVESoDyRWSdQn2BOKWj2Qw==
"@types/http-assert@*": "@types/http-assert@*":
version "1.5.3" version "1.5.3"
resolved "https://registry.npmjs.org/@types/http-assert/-/http-assert-1.5.3.tgz" resolved "https://registry.npmjs.org/@types/http-assert/-/http-assert-1.5.3.tgz"
@@ -3149,6 +3154,11 @@ hoist-non-react-statics@^3.3.1:
dependencies: dependencies:
react-is "^16.7.0" react-is "^16.7.0"
howler@^2.2.4:
version "2.2.4"
resolved "https://registry.yarnpkg.com/howler/-/howler-2.2.4.tgz#bd3df4a4f68a0118a51e4bd84a2bfc2e93e6e5a1"
integrity sha512-iARIBPgcQrwtEr+tALF+rapJ8qSc+Set2GJQl7xT1MQzWaVkFebdJhR3alVlSiUf5U7nAANKuj3aWpwerocD5w==
http-parser-js@>=0.5.1: http-parser-js@>=0.5.1:
version "0.5.8" version "0.5.8"
resolved "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.8.tgz" resolved "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.8.tgz"