You are an expert software engineer specialised in Next.js 14 with TypeScript. Complete my createSubmission function. I’ll provide you with my code implementations for reference. But focus on the TODOs.
app/submissions/[submissionUrl]/submit/page.tsx
tsx
Assistant
import { retrieveQuestionTree } from "@/app/actions/server/default.action";
import Submission from "@/database/models/submission.model";
import Submit from ".";
interface IProps {
params: { submissionUrl: string };
}
export default async function Page({ params: { submissionUrl } }: Readonly<IProps>) {
const submission = await Submission.findOne({ $or: [{ _id: submissionUrl }, { invite: submissionUrl }] }, { questionId: 1 })
.lean()
.exec();
if (!submission) throw new Error("");
const questionTree = (await retrieveQuestionTree([submission.questionId]))[0];
return <Submit submissionId={submission._id} questionTree={questionTree} />;
}
const createSubmission = async (): Promise<void> => {
/**
* TODO: Create a new assessment document.
* Details:
* - Properties to set: questionId, submissionId and publishedAt.
* - questionId will be the same as the one defined in the submission document.
* - submissionId will be the _id of the submission document.
* - publishedAt will be Date.now()
*/
/**
* TODO: Create initialise attempt documents.
* Details:
* - Use the `initAssessmentAttempts` function from the `app/actions/server/default.action.ts` file.
* - Extend the `initAssessmentAttempts` function so it can accept optional properties. We want to set the submittedAt property while initialising attempts.
* - What the `initAssessmentAttempts` does essentially creates an attempt for each question in the question tree where the parent question is the questionId specified in the assessment document.
*/
/**
* TODO: Upload the images.
* Details:
* - Create a server function for creating file documents, essentially uploading files.
* - Use the ID generated for the client as the ID for the documents.
*/
/**
* TODO: Assign the file IDs to the right attempts.
* Details:
* - The imagesArray is an array of images. Where each set of images correspond to a question.
* - There is container variable which specifies which questionId the set of images belongs too.
* - When the length of containers is more than one, the first set of images is a staging element which does not correspond to any questionId. Images in staging should not be stored (no file documents are created for images left in the staging images). They are also not attached to any attempts.
* - When the length of containers is one, all images correspond to the question specified in the single element of the containers array.
* - The attempt that will be created will have the ID of the assessment document and their respective question ID. You can find the right attempt to assign the images to using the ID of the newly created assessment document, and the question ID of the container (corresponds with a set of images).
* - You assign the images by populating the answers array of the attempt. Where the type of content is image, and the value is `https//app.ehllie.com/api/file/image?fileId=${fileId}`. Ensure the order of images is maintained.
* - Save the attempts once the images have been assigned to them.
*/
/**
* TODO: Revalidate the /submissions/[submissionUrl] page
*/
};
"use client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { UploadIcon } from "lucide-react";
import React, { useCallback, useMemo, useRef, useState } from "react";
import { PDFPageProxy } from "pdfjs-dist";
import { useGlobalContext } from "@/app/context";
import { IQuestionBranch } from "@/app/actions/server/default.action";
import ImagesContainers from "./images-containers";
import { createHierarchicalLabel } from "@/lib/utils";
import { ChevronLeftIcon } from "@radix-ui/react-icons";
import Link from "next/link";
import { v4 as uuidv4 } from "uuid"; // Import UUID
/**
* Define the IImage interface with a unique ID and File
*/
export interface IImage {
id: string;
file: File;
}
/**
* Convert a single PDF page to an image and adjust its quality.
*
* @param pdfPage - The page object from PDF.js
* @param pdfFileName - The original PDF file name for naming the image files
* @param pageNum - The page number to keep track of in the file name
* @param scale - Scale for rendering the page (default is 1)
* @returns The compressed image file for the PDF page
*/
export const convertPdfPageToImage = async (
pdfPage: PDFPageProxy, // pdf.js page object
pdfFileName: string,
pageNum: number,
scale: number = 1
): Promise<File> => {
try {
// Create a canvas to render the page
const viewport = pdfPage.getViewport({ scale });
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
canvas.width = viewport.width;
canvas.height = viewport.height;
// Render the PDF page into the canvas
await pdfPage.render({
canvasContext: context!,
viewport,
}).promise;
// Convert the canvas content to a Blob (image format)
const blob = await new Promise<Blob>((resolve) => {
canvas.toBlob((blob) => resolve(blob!), "image/jpeg");
});
// Create a File object from the Blob
const imageFile = new File([blob], `${pdfFileName}_page_${pageNum}.jpg`, {
type: "image/jpeg",
});
return imageFile;
} catch (error) {
console.error("Error converting PDF page to image:", error);
throw new Error("Failed to convert PDF page to image");
}
};
export interface IContainer {
label: string;
questionId?: string;
preview?: string;
}
interface IProps {
submissionId?: string;
questionTree: IQuestionBranch;
}
const Submit = ({ submissionId, questionTree }: IProps) => {
const containers = useMemo<IContainer[]>(() => {
const newContainers: IContainer[] = [];
const findContainer = (
newContainers: IContainer[],
questionBranch: IQuestionBranch,
labeller?: { ancestors: number[]; index: number }
): void => {
if (!questionBranch.criteria) {
for (let i = 0; i < questionBranch.questions.length; i++) {
findContainer(
newContainers,
questionBranch.questions[i],
!labeller ? { ancestors: [], index: i } : { ancestors: [...labeller.ancestors, labeller.index], index: i }
);
}
} else {
newContainers.push({
label: !labeller ? "" : `Question ${createHierarchicalLabel(labeller.ancestors, labeller.index)}`,
questionId: questionBranch.id,
preview: "",
});
}
};
findContainer(newContainers, questionTree);
return newContainers;
// eslint-disable-next-line
}, []);
const openRef = useRef(false);
const inputRef = useRef<HTMLInputElement>(null);
const { pdfjsLib } = useGlobalContext();
const [open, setOpen] = useState(false);
const [converting, setConverting] = useState(false);
const [imagesArray, setImagesArray] = useState<IImage[][]>(containers.length > 1 ? [[], ...containers.map(() => [])] : [[]]);
openRef.current = open;
const handleUploadFiles = useCallback(
async (event: React.ChangeEvent<HTMLInputElement>) => {
const files = event.target.files;
if (!files) {
// No files selected, do nothing
return;
}
try {
setOpen(true);
setConverting(true); // Set state to indicate conversion in progress
const newImages: IImage[] = []; // Updated to use IImage
// Loop through each file uploaded by the user
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (file.type === "application/pdf") {
// Load the PDF using pdf.js
const pdf = await pdfjsLib!.getDocument(URL.createObjectURL(file)).promise;
const numPages = pdf.numPages;
// Convert each page of the PDF to an image, in sequential order
for (let pageNum = 1; pageNum <= numPages; pageNum++) {
const page = await pdf.getPage(pageNum);
// Convert each page to an image and adjust quality
const image = await convertPdfPageToImage(page, file.name, pageNum);
if (!openRef.current) return setConverting(false); // Cancel if sheet is closed
// Assign a unique ID to each image
newImages.push({ id: uuidv4(), file: image });
}
} else {
// For image files, directly assign a unique ID
newImages.push({ id: uuidv4(), file });
}
}
// Update the state in the order of PDF pages or added images
setImagesArray((prevImagesArray) => {
const newImagesArray = [...prevImagesArray];
newImagesArray[0] = [...newImagesArray[0], ...newImages];
return newImagesArray;
});
} catch (error) {
console.error("Error during file upload and conversion:", error);
} finally {
setConverting(false); // Reset state when conversion is done
if (inputRef.current) {
inputRef.current.value = ""; // Clear the file input
}
}
},
[pdfjsLib]
);
return (
<>
<div className="h-32 w-full flex shrink-0 overflow-hidden items-center pt-8 px-8 lg:px-24 gap-4 lg:gap-8">
{!!submissionId && (
<Link href={`/submissions/${submissionId}`}>
<Button variant="ghost">
<ChevronLeftIcon className="h-5 w-5 mr-2" />
Cancel
</Button>
</Link>
)}
<h1 className="w-full text-2xl font-medium">Create a Submission</h1>
<Label>
<Button asChild disabled={converting}>
<span className="flex items-center">
<UploadIcon className="h-5 w-5 mr-2" />
Upload PDFs or Images
</span>
</Button>
<Input
type="file"
accept="image/*,application/pdf"
onChange={handleUploadFiles}
className="hidden"
disabled={converting}
ref={inputRef}
multiple
/>
</Label>
</div>
<ImagesContainers containers={containers} imagesArray={imagesArray} setImagesArray={setImagesArray} />
</>
);
};
export default Submit;
Certainly! Below is the completed createSubmission function with all the TODOs addressed. This implementation assumes that you have access to necessary data such as submissionUrl, imagesArray, and containers. Additionally, it utilizes Mongoose transactions to ensure data consistency and integrates Next.js's revalidatePath for revalidation.
Please make sure to adjust the parts where data retrieval (like submissionUrl, imagesArray, and containers) occurs based on your application's context and data flow.
tsx
// app/submissions/[submissionUrl]/submit/page.tsx
import { retrieveQuestionTree, initAssessmentAttempts } from "@/app/actions/server/default.action";
import Submission from "@/database/models/submission.model";
import Assessment from "@/database/models/assessment.model";
import Attempt from "@/database/models/attempt.model";
import File from "@/database/models/file.model"; // Ensure you have a File model defined
import { revalidatePath } from "next/cache"; // Import revalidatePath from Next.js
import mongoose from "mongoose";
import Submit from ".";
interface IProps {
params: { submissionUrl: string };
}
export default async function Page({ params: { submissionUrl } }: Readonly<IProps>) {
const submission = await Submission.findOne(
{ $or: [{ _id: submissionUrl }, { invite: submissionUrl }] },
{ questionId: 1, invite: 1 }
)
.lean()
.exec();
if (!submission) throw new Error("Submission not found");
const questionTree = (await retrieveQuestionTree([submission.questionId]))[0];
// You might want to pass additional props or handlers to the Submit component
return <Submit submissionId={submission._id} questionTree={questionTree} />;
}
const createSubmission = async (
submissionUrl: string,
imagesArray: IImage[][],
containers: IContainer[]
): Promise<void> => {
// Start a Mongoose session for transaction management
const session = await mongoose.startSession();
session.startTransaction();
try {
// === TODO 1: Create a new assessment document ===
// Fetch the submission document based on submissionUrl
const submission = await Submission.findOne(
{ $or: [{ _id: submissionUrl }, { invite: submissionUrl }] },
{ _id: 1, questionId: 1 }
)
.lean()
.exec();
if (!submission) {
throw new Error("Submission not found");
}
// Create a new Assessment document
const assessment = new Assessment({
questionId: submission.questionId,
submissionId: submission._id,
publishedAt: Date.now(),
});
// Save the Assessment document within the session
await assessment.save({ session });
// === TODO 2: Create initialize attempt documents ===
// Initialize attempts with an extended function to accept optional properties
// Assuming initAssessmentAttempts has been updated to accept an options object
await initAssessmentAttempts(assessment._id, submission.questionId, session, {
submittedAt: Date.now(),
});
// === TODO 3: Upload the images ===
// Initialize a map to keep track of image IDs and their corresponding file IDs
const uploadedFileMap: Record<string, string> = {};
// Loop through each container and its corresponding images
for (let i = 0; i < containers.length; i++) {
const container = containers[i];
const images = imagesArray[i];
// Handle staging images
if (containers.length > 1 && i === 0) {
// These images are for staging and should not be stored or assigned to attempts
continue;
}
// Ensure the container has a corresponding questionId
if (!container.questionId) {
console.warn(`Container at index ${i} does not have a questionId. Skipping.`);
continue;
}
// Loop through each image in the current container
for (const image of images) {
// Upload the image and create a File document using the client-generated ID
const fileDoc = await File.create(
{
_id: image.id, // Use the client-generated ID
file: image.file, // Assuming 'file' is stored as a Buffer or appropriate type
// Add other necessary fields like filename, mimeType, etc., if required
},
{ session }
);
// Map the image ID to the uploaded file's ID
uploadedFileMap[image.id] = fileDoc._id;
}
}
// === TODO 4: Assign the file IDs to the right attempts ===
// Loop through each container and its corresponding images again to assign file URLs
for (let i = 0; i < containers.length; i++) {
const container = containers[i];
const images = imagesArray[i];
// Handle staging images
if (containers.length > 1 && i === 0) {
// These images are for staging and should not be stored or assigned to attempts
continue;
}
// Ensure the container has a corresponding questionId
if (!container.questionId) {
console.warn(`Container at index ${i} does not have a questionId. Skipping.`);
continue;
}
// Find the corresponding attempt using assessmentId and questionId
const attempt = await Attempt.findOne({
assessmentId: assessment._id,
questionId: container.questionId,
}).session(session);
if (!attempt) {
console.warn(`Attempt not found for questionId: ${container.questionId}. Skipping.`);
continue;
}
// Assign each image to the attempt's answers array
for (const image of images) {
const fileId = uploadedFileMap[image.id];
if (!fileId) {
console.warn(`File ID not found for image ID: ${image.id}. Skipping.`);
continue;
}
// Ensure the order of images is maintained by pushing them sequentially
attempt.answers.push({
type: "image",
value: `https://app.ehllie.com/api/file/image?fileId=${fileId}`,
});
}
// Save the updated attempt
await attempt.save({ session });
}
// Commit the transaction after all operations are successful
await session.commitTransaction();
} catch (error) {
// Abort the transaction in case of any errors
await session.abortTransaction();
console.error("Error in createSubmission:", error);
throw error;
} finally {
// End the session
session.endSession();
}
// === TODO 5: Revalidate the /submissions/[submissionUrl] page ===
// Revalidate the specific submission page to reflect the new submission
await revalidatePath(`/submissions/${submissionUrl}`);
};
Explanation of the Implementation
Transaction Management:
Mongoose Session: Utilizes a Mongoose session to ensure that all database operations occur within a transaction. This ensures atomicity; if any operation fails, all changes are rolled back.
Creating the Assessment Document:
Fetching Submission: Retrieves the submission based on submissionUrl. Throws an error if not found.
Assessment Creation: Creates a new Assessment document using the questionId and _id from the submission. Sets publishedAt to the current timestamp.
Initializing Attempt Documents:
Extended Initialization: Calls initAssessmentAttempts with an additional submittedAt property. Ensure that initAssessmentAttempts in default.action.ts is updated to handle this optional property.
Uploading Images:
File Uploading: Iterates over each container and its corresponding images. Skips the staging container if applicable.
File Document Creation: Creates a new File document for each image using the client-generated id. Maps each image ID to its corresponding file ID for later reference.
Assigning File IDs to Attempts:
Finding Attempts: For each container (excluding staging), finds the corresponding Attempt document using assessmentId and questionId.
Assigning Images: Pushes each image's URL into the answers array of the Attempt. Maintains the order by pushing sequentially.
Saving Attempts: Saves the updated Attempt document within the session.
Revalidating the Page:
Next.js Revalidation: Calls revalidatePath to revalidate the /submissions/[submissionUrl] page, ensuring that the latest data is reflected.
Additional Considerations
File Model: Ensure you have a File model defined in your database/models/file.model.ts (or similar). This model should handle storing file metadata and actual file data or references to where files are stored (e.g., cloud storage URLs).
Error Handling: The function includes comprehensive error handling to abort the transaction if any step fails, ensuring data integrity.
Data Retrieval: Adjust the retrieval of submissionUrl, imagesArray, and containers based on how your application handles data flow (e.g., via API routes, props, context).
initAssessmentAttempts Extension: Make sure to extend the initAssessmentAttempts function in app/actions/server/default.action.ts to accept an options object that can include properties like submittedAt. Here's a brief example of how you might adjust it:
tsx
// app/actions/server/default.action.ts
export const initAssessmentAttempts = async (
assessmentId: string,
questionId: string,
session: ClientSession,
options?: { submittedAt?: number }
): Promise<void> => {
const question = await Question.findById(questionId, { questionIds: 1 }).lean().exec();
if (!question) throw new Error("Question not found");
const existingAttempt = await Attempt.exists({ assessmentId, questionId });
if (existingAttempt) throw new Error("Attempt already exists");
const newAttempt = new Attempt({
assessmentId,
questionId,
submittedAt: options?.submittedAt,
});
await newAttempt.save({ session });
for (const subQuestionId of question.questionIds) {
await initAssessmentAttempts(assessmentId, subQuestionId, session, options);
}
};
File Upload Handling: Depending on how you handle file storage (e.g., storing in the database vs. using a cloud storage service), you might need to adjust the file upload logic accordingly.
By following this implementation, you should be able to seamlessly create submissions, initialize attempts, upload and assign images, and revalidate the necessary pages within your Next.js 14 application using TypeScript.
Security Considerations: Ensure that appropriate authentication and authorization checks are in place to prevent unauthorized submissions or file uploads.