ibrahimn9 / E-Learn-Platform

A web-based platform for distance learning, providing tools for teachers, students, and administrators to manage courses, resources, and assessments.
MIT License
0 stars 0 forks source link

Controllers #8

Open lokmanzeddoun opened 4 months ago

lokmanzeddoun commented 4 months ago
const ApiError = require("../utils/ApiError");
const asyncHandler = require("express-async-handler");
const Submission = require("../model/submission.model.js");
const File = require("../model/file.model.js");
const { uploadFile } = require("../utils/documentCloud.js");
const submitAssignment = asyncHandler(async (req, res, next) => {
    const fileType = "submission";
    // save the files
    const file = req.file;
    const submission = new Submission(req.params.assignmentId, req.user.id, 1);
    await submission.save();
    const uploadedLink = await uploadFile(file);

    const newFile = new File(
        req.user.id,
        req.params.assignmentId,
        file.originalname,
        uploadedLink,
        fileType
    );
    await newFile.save();
    res.status(200).json({ msg: "submission Added" });
});
const showUserSubmission = asyncHandler(async (req, res, next) => {
    // show the user submission
    const [result] = await Submission.findByStudentId(req.user.id);
    res.status(200).json({ data: result });
});
const showAssignmentSubmission = asyncHandler(async (req, res, next) => {
    // show the user submission
    const [result] = await Submission.findByStudentId(req.params.assignmentId);
    res.status(200).json({ data: result });
});
module.exports = {
    submitAssignment,
    showUserSubmission,
    showAssignmentSubmission,
};
const asyncHandler = require("express-async-handler");
const ApiError = require("../utils/ApiError.js");
const Assignment = require("../model/assignment.model.js");
const multer = require("multer");
const File = require("../model/file.model.js");
const { v4: uuidv4 } = require("uuid");
const { uploadFile } = require("../utils/documentCloud.js");
const createAssignment = asyncHandler(async (req, res, next) => {
    // save into assignment table
    const { moduleId, name, timeEnd, description } = req.body;
    const assignment = new Assignment(
        name,
        description,
        req.user.id,
        moduleId,
        timeEnd
    );
    const fileType = "assignment";
    const result = await assignment.save();
    // save the files
    const file = req.file;
    const uploadedLink = await uploadFile(file);

    const newFile = new File(
        null,
        result[0].insertId,
        file.originalname,
        uploadedLink,
        fileType
    );
    await newFile.save();
    res.status(201).json({ msg: `Assignment Created Successfully` });
});

const deleteAssignment = asyncHandler(async (req, res, next) => {
    const [[document]] = await Assignment.findById(req.params.assignmentId);
    if (!document) {
        return next(
            new ApiError(`No Assignment for this id ${req.params.assignmentId}`, 404)
        );
    }
    await Assignment.deleteById(req.params.assignmentId);
    res.status(204).send();
});
const updateAssignment = asyncHandler(async (req, res, next) => {
    const { name, description, moduleId, timeEnd } = req.body;
    if (timeEnd) {
        const endDate = new Date(timeEnd);
        if (endDate.getTime() < new Date().getTime() + duration) {
            return next(new ApiError(`Invalid End Time `, 400));
        }
    }
    let result;
    try {
        [result] = await Assignment.updateAssignment(
            req.params.assignmentId,
            name,
            description,
            moduleId,
            timeEnd
        );
    } catch (err) {
        return next(new ApiError(err.message, 400));
    }
    res.status(200).json({ msg: "Assignment Updated" });
});
const getAssignment = asyncHandler(async (req, res, next) => {
    const [[document]] = await Assignment.findById(req.params.assignmentId);
    if (!document) {
        return next(new ApiError(`There is no Assignment For this Id`, 404));
    }
    res.status(200).json({ data: document });
});
const getAssignments = asyncHandler(async (req, res, next) => {
    const { teacherId, moduleId } = req.query;
    const [result] = await Assignment.fetchAll(teacherId, moduleId);
    res.status(200).json({ data: result });
});
const getAssignmentFile = asyncHandler(async (req, res, next) => {
    try {
        const fileId = req.params.fileId;
        const [file] = await File.findById(fileId);
        const data = await downloadFile(file[0].fileUrl);
        res.setHeader(
            "Content-Disposition",
            `attachment; filename="${data.result.name}"`
        );
        res.setHeader("Content-Type", "application/octet-stream");
        res.end(Buffer.from(data.result.fileBinary), "binary");
    } catch (error) {
        console.error(error);
        res.status(500).send("Error fetching file from Dropbox");
    }
});
module.exports = {
    createAssignment,
    getAssignmentFile,
    getAssignment,
    getAssignments,
    updateAssignment,
    deleteAssignment,
};
const ApiError = require("../utils/ApiError");
const asyncHandler = require("express-async-handler");
const AssignmentResult = require("../model/assignmentResult.model");
const Submission = require("../model/submission.model");
const evaluateSubmission = asyncHandler(async (req, res, next) => {
    const { status, studentId } = req.body;
    // check if the pair (studentId, assignmentId exists in submission Table)
    const [[submission]] = await Submission.findByStudentIdAndAssignmentId(
        req.params.assignmentId,
        studentId
  );
    if (!submission) {
        return next(new ApiError(`There is no submission For That`, 404));
    }
    const evaluation = new AssignmentResult(
        req.params.assignmentId,
        studentId,
        status
    );
    await evaluation.save();
    res.status(201).json({ msg: "Evaluation Added" });
});
const getAssignmentEvaluation = asyncHandler(async (req, res, next) => {
    const [result] =await  AssignmentResult.findByAssignmentId(req.params.assignmentId);
    res.status(200).json({ data: result });
});

module.exports = { getAssignmentEvaluation, evaluateSubmission };
lokmanzeddoun commented 4 months ago
const db = require("../config/database");
class AssignmentResult {
    // constructor
    constructor(assignmentId, studentId, status) {
        this.assignmentId = assignmentId;
        this.studentId = studentId;
        this.status = status;
    }
    save() {
        return db.execute(
            `INSERT INTO assignmentResult (assignmentId,studentId,status) VALUES (?,?,?,?) `,
            [this.assignmentId, this.studentId, this.status]
        );
    }

    static findById(id) {
        return db.execute("SELECT * FROM assignmentResult  WHERE id = ?", [id]);
    }

    static deleteById(id) {
        return db.execute("DELETE FROM  assignmentResult WHERE id = ?", [id]);
    }
    static findByAssignmentId(id) {
        return db.execute(
            "SELECT ar.status,ass.name,ass.description,ass.timeBegin,ass.timeEnd,s.fullName FROM assignmentResult AS ar LEFT JOIN students AS s ON s.id = ar.studentId LEFT JOIN assignments AS ass ON ar.assignmentId = ass.id  WHERE ar.assignmentId = ? ",
            [id]
        );
    }
}

module.exports = AssignmentResult;
lokmanzeddoun commented 4 months ago
const db = require("../config/database");
class Assignment {
    // constructor
    constructor(name, description, teacherId, moduleId, timeEnd) {
        this.name = name;
        this.description = description;
        this.teacherId = teacherId;
        this.moduleId = moduleId;
        this.timeEnd = timeEnd || null;
    }
    save() {
        return db.execute(
            `INSERT INTO assignments (name,description,teacherId,moduleId,timeEnd) VALUES (?,?,?,?,COALESCE(?, timeEnd))`,
            [this.name, this.description, this.teacherId, this.moduleId, this.timeEnd]
        );
    }
    static fetchAll(teacherId, moduleId) {
        teacherId = teacherId || null;
        moduleId = moduleId || null;
        return db.execute(
            "SELECT ass.name ,ass.description ,ass.timeEnd,ass.timeBegin,modules.name AS ModuleName ,modules.semester,teachers.fullName AS TeacherName FROM assignments AS ass LEFT JOIN modules ON ass.moduleId =modules.id  LEFT JOIN teachers ON  teachers.id = ass.teacherId  WHERE  (ass.teacherId  LIKE ? OR ? IS NULL) AND (ass.moduleId = ? OR ? IS NULL)",
            [teacherId, teacherId, moduleId, moduleId]
        );
    }

    static findById(id) {
        return db.execute(
            "SELECT ass.name ,ass.description ,ass.timeEnd,ass.timeBegin,modules.name AS ModuleName ,modules.semester,teachers.fullName AS TeacherName FROM assignments AS ass LEFT JOIN modules ON ass.moduleId =modules.id  LEFT JOIN teachers ON  teachers.id = ass.teacherId  WHERE ass.id = ?",
            [id]
        );
    }

    static deleteById(id) {
        return db.execute("DELETE FROM  assignments WHERE id = ?", [id]);
    }
    static updateAssignment(id, name, description, moduleId, endTime) {
        name = name || null;
        endTime = endTime || null;
        description = description || null;
        moduleId = moduleId || null;
        return db.execute(
            "UPDATE assignments SET name = IFNULL(?, name),  timeEnd = IFNULL(?, timeEnd),description = IFNULL(?, description) ,moduleId = IFNULL(?, moduleId) WHERE id = ?",
            [name, endTime, description, moduleId, id]
        );
    }
}

module.exports = Assignment;
lokmanzeddoun commented 4 months ago
const db = require("../config/database");
class File {
    // constructor
    constructor(studentId, assignmentId, fileName, fileUrl, fileType) {
        this.studentId = studentId || null;
        this.assignmentId = assignmentId;
        this.fileName = fileName;
        this.fileUrl = fileUrl;
        this.fileType = fileType;
    }
    save() {
        console.log(
            this.fileType,
            this.fileName,
            this.assignmentId,
            this.fileUrl,
            this.studentId
        );
        return db.execute(
            `INSERT INTO file (fileType, assignmentId, fileName, fileUrl, studentId) VALUES (?, ?, ?, ?, ?)`,
            [
                this.fileType,
                this.assignmentId,
                this.fileName,
                this.fileUrl,
                this.studentId ? this.studentId : null, // Use null if studentId is not provided
            ]
        );
    }

    static findById(id) {
        return db.execute("SELECT * FROM file  WHERE id = ?", [id]);
    }

    static deleteById(id) {
        return db.execute("DELETE FROM  file WHERE id = ?", [id]);
    }
}

module.exports = File;
lokmanzeddoun commented 4 months ago

const db = require("../config/database");
class Submission {
    // constructor
    constructor(assignmentId, studentId, taken) {
        this.assignmentId = assignmentId;
        this.studentId = studentId;
        this.taken = taken;
    }
    save() {
        return db.execute(
            `INSERT INTO submission (assignmentId,studentId,taken) VALUES (?,?,?) `,
            [this.assignmentId, this.studentId, this.taken]
        );
    }

    static findByAssignmentId(id) {
        return db.execute(
            "SELECT * FROM submission  WHERE submission.assignmentId = ?",
            [id]
        );
    }
    static findByStudentId(id) {
        return db.execute(
            "SELECT ass.name,ass.description,ass.timeBegin,ass.timeEnd,s.fullName,submission.taken FROM submission LEFT JOIN students AS s ON s.id = submission.studentId LEFT JOIN assignments AS ass ON submission.assignmentId = ass.id  WHERE submission.studentId = ? ",
            [id]
        );
    }
    static findByAssignmentId(id) {
        return db.execute(
            "SELECT ass.name,ass.description,ass.timeBegin,ass.timeEnd,s.fullName,submission.taken FROM submission LEFT JOIN students AS s ON s.id = submission.studentId LEFT JOIN assignments AS ass ON submission.assignmentId = ass.id  WHERE submission.assignmentId = ? ",
            [id]
        );
    }
    static findByStudentIdAndAssignmentId(id1, id2) {
        return db.execute(
            "SELECT * FROM submission AS s WHERE s.studentId = ? And s.assignmentId = ?",
            [id2, id1]
        );
    }
}

module.exports = Submission;
lokmanzeddoun commented 4 months ago
const express = require("express");
const router = express.Router();
const { upload } = require("../middlewares/multer");
const {
    createAssignment,
    getAssignment,
    getAssignmentFile,
    deleteAssignment,
    updateAssignment,
    getAssignments,
} = require("../controllers/assignmentController");
const submissionRoute = require("./submissionRoute");
const evaluationRoute = require("./evaluationRoute");
const authServices = require("../controllers/authController");
router.use(
    "/:assignmentId/submission",
    authServices.protect,
    authServices.allowedTo("student"),
    submissionRoute
);
router.use("/:assignmentId/evaluation", evaluationRoute);
router.get("/file/:fileId", getAssignmentFile);
// This route is Authorized For Admin
router.use(authServices.protect, authServices.allowedTo("teacher"));

router
    .route("/")
    .post(upload.single("file"), createAssignment)
    .get(getAssignments);
router
    .route("/:assignmentId")
    .get(getAssignment)
    .delete(deleteAssignment)
    .put(updateAssignment);
module.exports = router;
lokmanzeddoun commented 4 months ago
const express = require("express");
const router = express.Router({ mergeParams: true });
const {} = require("../middlewares/uploadFileMiddleware");
const {
    evaluateSubmission,
    getAssignmentEvaluation,
} = require("../controllers/evaluationController");

const authServices = require("../controllers/authController");
// This route is Authorized For Admin

router
    .route("/")
    .post(
        authServices.protect,
        authServices.allowedTo("teacher"),
        evaluateSubmission
    )
    .get(
        authServices.protect,
        authServices.allowedTo("teacher"),
        getAssignmentEvaluation
    );

router.route("/:evaluationId").get().delete().put();
module.exports = router;
lokmanzeddoun commented 4 months ago
const express = require("express");
const router = express.Router({ mergeParams: true });
const { upload } = require("../middlewares/multer");
const {
    submitAssignment,
    showUserSubmission,
    showAssignmentSubmission,
} = require("../controllers/submissionController");

const authServices = require("../controllers/authController");
// This route is Authorized For Admin

router
    .route("/")
    .post(
        authServices.protect,
        authServices.allowedTo("student"),
        upload.single("file"),
        submitAssignment
    )
    .get(
        authServices.protect,
        authServices.allowedTo("student"),
        showUserSubmission
    );
router.get(
    "/all",
    authServices.protect,
    authServices.allowedTo("teacher"),
    showAssignmentSubmission
);
router.use(authServices.protect, authServices.allowedTo("student"));
router.route("/:submissionId").get().delete().put();
module.exports = router;
lokmanzeddoun commented 4 months ago
DROPBOX_ACCESS_TOKEN=sl.B2kb-wWnh3d2AY196Hfeom4Zg_YNSRfj-nf6kR9x0Oqbf6JwEmn2ZVXry6uykDcU6iiWTClrPsNtwZOa1BLL0Io2Vr_lO3QFbRIYxQfE3Y289k007l_wnqCdB6zolyU1JUmRNz99LruKdrha6dV25co
lokmanzeddoun commented 4 months ago
const submissionRoute = require("./route/submissionRoute.js");
const assignmentRoute = require("./route/assignmentRoute.js");
app.use("/api/v1/assignment", assignmentRoute);
app.use("/api/v1/submission", submissionRoute);