ENCOA-274
This commit is contained in:
@@ -8,6 +8,7 @@ import { Module } from "@/interfaces";
|
||||
interface GeneratorConfig {
|
||||
method: 'GET' | 'POST';
|
||||
queryParams?: Record<string, string>;
|
||||
files?: Record<string, string>;
|
||||
body?: Record<string, any>;
|
||||
}
|
||||
|
||||
@@ -66,18 +67,60 @@ export function generate(
|
||||
|
||||
const url = `/api/exam/generate/${module}/${sectionId}${queryString ? `?${queryString}` : ''}`;
|
||||
|
||||
const request = config.method === 'POST'
|
||||
? axios.post(url, config.body)
|
||||
: axios.get(url);
|
||||
let body = null;
|
||||
console.log(config.files);
|
||||
if (config.files && Object.keys(config.files).length > 0 && config.method === 'POST') {
|
||||
const formData = new FormData();
|
||||
|
||||
request
|
||||
.then((result) => {
|
||||
playSound("check");
|
||||
setGeneratedResult(level ? levelSectionId! : sectionId, type, mapData(result.data), level);
|
||||
})
|
||||
.catch((error) => {
|
||||
setGenerating(sectionId, undefined, level, true);
|
||||
playSound("error");
|
||||
toast.error("Something went wrong! Try to generate again.");
|
||||
})
|
||||
const buildForm = async () => {
|
||||
await Promise.all(
|
||||
Object.entries(config.files ?? {}).map(async ([key, blobUrl]) => {
|
||||
const response = await fetch(blobUrl);
|
||||
const blob = await response.blob();
|
||||
const file = new File([blob], key, { type: blob.type });
|
||||
formData.append(key, file);
|
||||
})
|
||||
);
|
||||
|
||||
if (config.body) {
|
||||
Object.entries(config.body).forEach(([key, value]) => {
|
||||
formData.append(key, value as string);
|
||||
});
|
||||
}
|
||||
return formData;
|
||||
};
|
||||
|
||||
buildForm().then(form => {
|
||||
body = form;
|
||||
|
||||
const request = axios.post(url, body, { headers: { 'Content-Type': 'multipart/form-data' } });
|
||||
request
|
||||
.then((result) => {
|
||||
playSound("check");
|
||||
setGeneratedResult(level ? levelSectionId! : sectionId, type, mapData(result.data), level);
|
||||
})
|
||||
.catch((error) => {
|
||||
setGenerating(sectionId, undefined, level, true);
|
||||
playSound("error");
|
||||
toast.error("Something went wrong! Try to generate again.");
|
||||
});
|
||||
});
|
||||
} else {
|
||||
body = config.body;
|
||||
|
||||
const request = config.method === 'POST'
|
||||
? axios.post(url, body, { headers: { 'Content-Type': 'application/json' } })
|
||||
: axios.get(url);
|
||||
|
||||
request
|
||||
.then((result) => {
|
||||
playSound("check");
|
||||
setGeneratedResult(level ? levelSectionId! : sectionId, type, mapData(result.data), level);
|
||||
})
|
||||
.catch((error) => {
|
||||
setGenerating(sectionId, undefined, level, true);
|
||||
playSound("error");
|
||||
toast.error("Something went wrong! Try to generate again.");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback, useState } from "react";
|
||||
import React, { useCallback, useRef, useState } from "react";
|
||||
import Dropdown from "../Shared/SettingsDropdown";
|
||||
import Input from "@/components/Low/Input";
|
||||
import { generate } from "../Shared/Generate";
|
||||
@@ -6,6 +6,8 @@ import GenerateBtn from "../Shared/GenerateBtn";
|
||||
import { LevelSectionSettings, WritingSectionSettings } from "@/stores/examEditor/types";
|
||||
import useExamEditorStore from "@/stores/examEditor";
|
||||
import { WritingExercise } from "@/interfaces/exam";
|
||||
import clsx from "clsx";
|
||||
import { FaFileUpload } from "react-icons/fa";
|
||||
|
||||
|
||||
interface Props {
|
||||
@@ -15,69 +17,155 @@ interface Props {
|
||||
level?: boolean;
|
||||
}
|
||||
|
||||
const WritingComponents: React.FC<Props> = ({localSettings, updateLocalAndScheduleGlobal, level}) => {
|
||||
const { currentModule } = useExamEditorStore();
|
||||
const WritingComponents: React.FC<Props> = ({ localSettings, updateLocalAndScheduleGlobal, level }) => {
|
||||
const { currentModule, dispatch } = useExamEditorStore();
|
||||
const {
|
||||
difficulty,
|
||||
focusedSection,
|
||||
type,
|
||||
academic_url
|
||||
} = useExamEditorStore((store) => store.modules["writing"]);
|
||||
|
||||
const generatePassage = useCallback((sectionId: number) => {
|
||||
generate(
|
||||
sectionId,
|
||||
currentModule,
|
||||
"writing",
|
||||
{
|
||||
method: 'GET',
|
||||
queryParams: {
|
||||
difficulty,
|
||||
...(localSettings.writingTopic && { topic: localSettings.writingTopic })
|
||||
}
|
||||
},
|
||||
(data: any) => [{
|
||||
prompt: data.question
|
||||
}]
|
||||
);
|
||||
if (type === "academic" && academic_url !== undefined && sectionId == 1) {
|
||||
generate(
|
||||
sectionId,
|
||||
currentModule,
|
||||
"writing",
|
||||
{
|
||||
method: 'POST',
|
||||
queryParams: {
|
||||
difficulty,
|
||||
type: type!
|
||||
},
|
||||
files: {
|
||||
file: academic_url!,
|
||||
}
|
||||
},
|
||||
(data: any) => [{
|
||||
prompt: data.question
|
||||
}]
|
||||
)
|
||||
} else {
|
||||
generate(
|
||||
sectionId,
|
||||
currentModule,
|
||||
"writing",
|
||||
{
|
||||
method: 'GET',
|
||||
queryParams: {
|
||||
difficulty,
|
||||
type: type!,
|
||||
...(localSettings.writingTopic && { topic: localSettings.writingTopic })
|
||||
}
|
||||
},
|
||||
(data: any) => [{
|
||||
prompt: data.question
|
||||
}]
|
||||
);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [localSettings.writingTopic, difficulty]);
|
||||
}, [localSettings.writingTopic, difficulty, academic_url]);
|
||||
|
||||
const onTopicChange = useCallback((writingTopic: string) => {
|
||||
updateLocalAndScheduleGlobal({ writingTopic });
|
||||
}, [updateLocalAndScheduleGlobal]);
|
||||
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const triggerFileInput = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (file) {
|
||||
const blobUrl = URL.createObjectURL(file);
|
||||
if (academic_url !== undefined) {
|
||||
URL.revokeObjectURL(academic_url);
|
||||
}
|
||||
dispatch({ type: "UPDATE_MODULE", payload: { updates: { academic_url: blobUrl } } });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dropdown
|
||||
title="Generate Instructions"
|
||||
{type === "academic" && focusedSection === 1 && <Dropdown
|
||||
title="Upload Image"
|
||||
module={"writing"}
|
||||
open={localSettings.isWritingTopicOpen}
|
||||
setIsOpen={(isOpen: boolean) => updateLocalAndScheduleGlobal({ isWritingTopicOpen: isOpen }, false)}
|
||||
contentWrapperClassName={level ? `border border-ielts-writing`: ''}
|
||||
open={localSettings.isImageUploadOpen}
|
||||
setIsOpen={(isOpen: boolean) => updateLocalAndScheduleGlobal({ isImageUploadOpen: isOpen }, false)}
|
||||
contentWrapperClassName={level ? `border border-ielts-writing` : ''}
|
||||
>
|
||||
|
||||
<div className="flex flex-row gap-2 items-center px-2 pb-4">
|
||||
<div className="flex flex-col flex-grow gap-4 px-2">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Topic (Optional)</label>
|
||||
<Input
|
||||
|
||||
<div className="flex flex-row p-2 gap-4">
|
||||
<span className="bg-gray-100 px-3.5 py-2.5 rounded-lg border border-gray-300 text-mti-gray-dim">
|
||||
Upload a graph, chart or diagram
|
||||
</span>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/png, image/jpeg"
|
||||
onChange={handleFileUpload}
|
||||
style={{ display: 'none' }}
|
||||
ref={fileInputRef}
|
||||
/>
|
||||
<button
|
||||
key={`section-${focusedSection}`}
|
||||
type="text"
|
||||
placeholder="Topic"
|
||||
name="category"
|
||||
onChange={onTopicChange}
|
||||
roundness="full"
|
||||
value={localSettings.writingTopic}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex self-end h-16 mb-1">
|
||||
<GenerateBtn
|
||||
genType="writing"
|
||||
module={"writing"}
|
||||
sectionId={focusedSection}
|
||||
generateFnc={generatePassage}
|
||||
/>
|
||||
className={clsx(
|
||||
"flex items-center w-[140px] px-4 py-2 text-white rounded-xl transition-colors duration-300 text-lg disabled:cursor-not-allowed",
|
||||
`bg-ielts-writing/70 border border-ielts-writing hover:bg-ielts-writing disabled:bg-ielts-writing/40`,
|
||||
)}
|
||||
onClick={triggerFileInput}
|
||||
>
|
||||
<div className="flex flex-row">
|
||||
<FaFileUpload className="mr-2" size={24} />
|
||||
<span>Upload</span>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Dropdown>
|
||||
</Dropdown>}
|
||||
{
|
||||
type !== "academic" || (type === "academic" && academic_url !== undefined) && <Dropdown
|
||||
title="Generate Instructions"
|
||||
module={"writing"}
|
||||
open={localSettings.isWritingTopicOpen}
|
||||
setIsOpen={(isOpen: boolean) => updateLocalAndScheduleGlobal({ isWritingTopicOpen: isOpen }, false)}
|
||||
contentWrapperClassName={level ? `border border-ielts-writing` : ''}
|
||||
>
|
||||
|
||||
<div className="flex flex-row gap-2 items-center px-2 pb-4">
|
||||
{type !== "academic" ?
|
||||
<div className="flex flex-col flex-grow gap-4 px-2">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Topic (Optional)</label>
|
||||
<Input
|
||||
key={`section-${focusedSection}`}
|
||||
type="text"
|
||||
placeholder="Topic"
|
||||
name="category"
|
||||
onChange={onTopicChange}
|
||||
roundness="full"
|
||||
value={localSettings.writingTopic}
|
||||
/>
|
||||
</div>
|
||||
:
|
||||
<div className="flex flex-col flex-grow gap-4 px-2">
|
||||
<span className="bg-gray-100 px-3.5 py-2.5 rounded-lg border border-gray-300 text-mti-gray-dim">
|
||||
Generate instructions based on the uploaded image.
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
<div className="flex self-end h-16 mb-1">
|
||||
<GenerateBtn
|
||||
genType="writing"
|
||||
module={"writing"}
|
||||
sectionId={focusedSection}
|
||||
generateFnc={generatePassage}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Dropdown>
|
||||
}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -8,7 +8,6 @@ import { useRouter } from "next/router";
|
||||
import { usePersistentExamStore } from "@/stores/exam";
|
||||
import openDetachedTab from "@/utils/popout";
|
||||
import { WritingExam, WritingExercise } from "@/interfaces/exam";
|
||||
import { v4 } from "uuid";
|
||||
import axios from "axios";
|
||||
import { playSound } from "@/utils/sound";
|
||||
import { toast } from "react-toastify";
|
||||
@@ -25,7 +24,8 @@ const WritingSettings: React.FC = () => {
|
||||
isPrivate,
|
||||
sections,
|
||||
focusedSection,
|
||||
type
|
||||
type,
|
||||
academic_url
|
||||
} = useExamEditorStore((store) => store.modules["writing"]);
|
||||
|
||||
const states = sections.flatMap((s) => s.state) as WritingExercise[];
|
||||
@@ -58,8 +58,16 @@ const WritingSettings: React.FC = () => {
|
||||
|
||||
const openTab = () => {
|
||||
setExam({
|
||||
exercises: sections.map((s) => {
|
||||
exercises: sections.map((s, index) => {
|
||||
const exercise = s.state as WritingExercise;
|
||||
if (type === "academic" && index == 0 && academic_url) {
|
||||
console.log("Added the URL");
|
||||
exercise["attachment"] = {
|
||||
url: academic_url,
|
||||
description: "Visual Information"
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...exercise,
|
||||
intro: s.settings.currentIntro,
|
||||
@@ -79,36 +87,68 @@ const WritingSettings: React.FC = () => {
|
||||
openDetachedTab("popout?type=Exam&module=writing", router)
|
||||
}
|
||||
|
||||
const submitWriting = () => {
|
||||
const exam: WritingExam = {
|
||||
exercises: sections.map((s) => {
|
||||
const exercise = s.state as WritingExercise;
|
||||
return {
|
||||
...exercise,
|
||||
intro: localSettings.currentIntro,
|
||||
category: localSettings.category
|
||||
};
|
||||
}),
|
||||
minTimer,
|
||||
module: "writing",
|
||||
id: title,
|
||||
isDiagnostic: false,
|
||||
variant: undefined,
|
||||
difficulty,
|
||||
private: isPrivate,
|
||||
type: type!
|
||||
};
|
||||
const submitWriting = async () => {
|
||||
if (title === "") {
|
||||
toast.error("Enter a title for the exam!");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
let firebase_url = undefined;
|
||||
if (type === "academic" && academic_url) {
|
||||
const formData = new FormData();
|
||||
const sectionMap = new Map<number, string>();
|
||||
const fetchedBlob = await fetch(academic_url);
|
||||
const blob = await fetchedBlob.blob();
|
||||
formData.append('file', blob);
|
||||
sectionMap.set(1, academic_url);
|
||||
|
||||
axios
|
||||
.post(`/api/exam/reading`, exam)
|
||||
.then((result) => {
|
||||
playSound("sent");
|
||||
toast.success(`Submitted Exam ID: ${result.data.id}`);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error);
|
||||
toast.error(error.response.data.error || "Something went wrong while submitting, please try again later.");
|
||||
})
|
||||
const response = await axios.post('/api/storage', formData, {
|
||||
params: {
|
||||
directory: 'writing_attachments'
|
||||
},
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
}
|
||||
});
|
||||
firebase_url = response.data.urls[1];
|
||||
}
|
||||
|
||||
const exam: WritingExam = {
|
||||
exercises: sections.map((s) => {
|
||||
const exercise = s.state as WritingExercise;
|
||||
if (exercise.sectionId == 1 && firebase_url) {
|
||||
exercise["attachment"] = {
|
||||
url: firebase_url,
|
||||
description: "Visual Information"
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...exercise,
|
||||
intro: localSettings.currentIntro,
|
||||
category: localSettings.category
|
||||
};
|
||||
}),
|
||||
minTimer,
|
||||
module: "writing",
|
||||
id: title,
|
||||
isDiagnostic: false,
|
||||
variant: undefined,
|
||||
difficulty,
|
||||
private: isPrivate,
|
||||
type: type!
|
||||
};
|
||||
|
||||
const result = await axios.post(`/api/exam/writing`, exam)
|
||||
playSound("sent");
|
||||
toast.success(`Submitted Exam ID: ${result.data.id}`);
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('Error submitting exam:', error);
|
||||
toast.error(
|
||||
"Something went wrong while submitting, please try again later."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
Reference in New Issue
Block a user