Merge branch 'dev' of https://github.com/digitalsolutiongroup/amati into feat/forgot-password-frontend

This commit is contained in:
Sukma Gladys 2024-09-05 08:33:28 +07:00
commit 9edacd9a43
12 changed files with 1181 additions and 73 deletions

View File

@ -62,6 +62,48 @@ const permissionsData = [
{
code: "managementAspect.restore",
},
{
code: "assessmentResult.readAll",
},
{
code: "assessmentResult.read",
},
{
code: "assessmentResult.readAllQuestions",
},
{
code: "assessmentResult.create",
},
{
code: "assessmentRequest.read",
},
{
code: "assessmentRequest.create",
},
{
code: "assessments.readAssessmentScore",
},
{
code: "assessments.readAllQuestions",
},
{
code: "assessments.readAnswers",
},
{
code: "assessments.toggleFlag",
},
{
code: "assessments.checkAnswer",
},
{
code: "assessments.uploadFile",
},
{
code: "assessments.submitAnswer",
},
{
code: "assessments.updateAnswer",
},
] as const;
export type SpecificPermissionCode = (typeof permissionsData)[number]["code"];

View File

@ -4,7 +4,7 @@ import { relations } from "drizzle-orm";
import { respondents } from "./respondents";
import { users } from "./users";
const statusEnum = pgEnum("status", ["tertunda", "disetujui", "ditolak", "selesai"]);
const statusEnum = pgEnum("status", ["menunggu konfirmasi", "disetujui", "ditolak", "selesai"]);
export const assessments = pgTable("assessments", {
id: varchar("id", { length: 50 })
@ -14,10 +14,9 @@ export const assessments = pgTable("assessments", {
status: statusEnum("status"),
reviewedBy: varchar("reviewedBy"),
reviewedAt: timestamp("reviewedAt", { mode: "date" }),
validatedBy: varchar("validatedBy").notNull(),
validatedBy: varchar("validatedBy"),
validatedAt: timestamp("validatedAt", { mode: "date" }),
createdAt: timestamp("createdAt", { mode: "date" }).defaultNow(),
});
// Query Tools in PosgreSQL
// CREATE TYPE status AS ENUM ('tertunda', 'disetujui', 'ditolak', 'selesai');
// CREATE TYPE status AS ENUM ('menunggu konfirmasi', 'disetujui', 'ditolak', 'selesai');

View File

@ -18,7 +18,10 @@ import HonoEnv from "./types/HonoEnv";
import devRoutes from "./routes/dev/route";
import appEnv from "./appEnv";
import questionsRoute from "./routes/questions/route";
import assessmentResultRoute from "./routes/assessmentResult/route";
import assessmentRequestRoute from "./routes/assessmentRequest/route";
import forgotPasswordRoutes from "./routes/forgotPassword/route";
import assessmentsRoute from "./routes/assessments/route";
configDotenv();
@ -85,7 +88,10 @@ const routes = app
.route("/questions", questionsRoute)
.route("/management-aspect", managementAspectsRoute)
.route("/register", respondentsRoute)
.route("/assessmentResult", assessmentResultRoute)
.route("/assessmentRequest", assessmentRequestRoute)
.route("/forgot-password", forgotPasswordRoutes)
.route("/assessments", assessmentsRoute)
.onError((err, c) => {
if (err instanceof DashboardError) {
return c.json(

View File

@ -0,0 +1,105 @@
import { eq } from "drizzle-orm";
import { Hono } from "hono";
import { z } from "zod";
import db from "../../drizzle";
import { respondents } from "../../drizzle/schema/respondents";
import { assessments } from "../../drizzle/schema/assessments";
import { users } from "../../drizzle/schema/users";
import { rolesToUsers } from "../../drizzle/schema/rolesToUsers";
import { rolesSchema } from "../../drizzle/schema/roles";
import HonoEnv from "../../types/HonoEnv";
import authInfo from "../../middlewares/authInfo";
import { notFound } from "../../errors/DashboardError";
import checkPermission from "../../middlewares/checkPermission";
import requestValidator from "../../utils/requestValidator";
import { HTTPException } from "hono/http-exception";
import { createId } from "@paralleldrive/cuid2";
const assessmentRequestRoute = new Hono<HonoEnv>()
.use(authInfo)
// Get assessment request by user ID
.get(
"/:id",
checkPermission("assessmentRequest.read"),
requestValidator(
"query",
z.object({
includeTrashed: z.string().default("false"),
})
),
async (c) => {
const userId = c.req.param("id");
const queryResult = await db
.select({
userId: users.id,
createdAt: assessments.createdAt,
name: users.name,
code: rolesSchema.code,
status: assessments.status,
})
.from(users)
.leftJoin(rolesToUsers, eq(users.id, rolesToUsers.userId))
.leftJoin(rolesSchema, eq(rolesToUsers.roleId, rolesSchema.id))
.leftJoin(respondents, eq(users.id, respondents.userId))
.leftJoin(assessments, eq(respondents.id, assessments.respondentId))
.where(eq(users.id, userId));
if (!queryResult[0]) throw notFound();
const assessmentRequestData = {
...queryResult,
};
return c.json(assessmentRequestData);
}
)
// Post assessment request by user ID
.post(
"/:id",
checkPermission("assessmentRequest.create"),
requestValidator(
"json",
z.object({
respondentId: z.string().min(1),
})
),
async (c) => {
const { respondentId } = c.req.valid("json");
const userId = c.req.param("id");
// Make sure the userId exists
if (!userId) {
throw new HTTPException(400, { message: "User ID is required." });
}
// Validate if respondent exists
const respondent = await db
.select()
.from(respondents)
.where(eq(respondents.id, respondentId));
if (!respondent.length) {
throw new HTTPException(404, { message: "Respondent not found." });
}
// Create the assessment request
const newAssessment = await db
.insert(assessments)
.values({
id: createId(),
respondentId,
status: "menunggu konfirmasi",
validatedBy: null,
validatedAt: null,
createdAt: new Date(),
})
.returning();
return c.json({ message: "Successfully submitted the assessment request" }, 201);
}
);
export default assessmentRequestRoute;

View File

@ -0,0 +1,238 @@
import { and, eq, isNull, sql } from "drizzle-orm";
import { Hono } from "hono";
import { z } from "zod";
import db from "../../drizzle";
import { assessments } from "../../drizzle/schema/assessments";
import { respondents } from "../../drizzle/schema/respondents";
import { users } from "../../drizzle/schema/users";
import { aspects } from "../../drizzle/schema/aspects";
import { subAspects } from "../../drizzle/schema/subAspects";
import { questions } from "../../drizzle/schema/questions";
import { options } from "../../drizzle/schema/options";
import { answers } from "../../drizzle/schema/answers";
import { answerRevisions } from "../../drizzle/schema/answerRevisions";
import HonoEnv from "../../types/HonoEnv";
import authInfo from "../../middlewares/authInfo";
import checkPermission from "../../middlewares/checkPermission";
import requestValidator from "../../utils/requestValidator";
import { notFound } from "../../errors/DashboardError";
const assessmentRoute = new Hono<HonoEnv>()
.use(authInfo)
// Get All List of Assessment Results
.get(
"/",
checkPermission("assessmentResult.readAll"),
requestValidator(
"query",
z.object({
page: z.coerce.number().int().min(0).default(0),
limit: z.coerce.number().int().min(1).max(1000).default(40),
})
),
async (c) => {
const { page, limit } = c.req.valid("query");
const result = await db
.select({
id: assessments.id,
respondentName: users.name,
companyName: respondents.companyName,
statusAssessments: assessments.status,
statusVerification: sql<string>`
CASE
WHEN ${assessments.validatedAt} IS NOT NULL THEN 'sudah diverifikasi'
ELSE 'belum diverifikasi'
END`
.as("statusVerification"),
assessmentsResult: sql<number>`
(SELECT ROUND(AVG(${options.score}), 2)
FROM ${answers}
JOIN ${options} ON ${options.id} = ${answers.optionId}
JOIN ${questions} ON ${questions.id} = ${options.questionId}
JOIN ${subAspects} ON ${subAspects.id} = ${questions.subAspectId}
JOIN ${aspects} ON ${aspects.id} = ${subAspects.aspectId}
WHERE ${answers.assessmentId} = ${assessments.id})`
.as("assessmentsResult"),
})
.from(assessments)
.leftJoin(respondents, eq(assessments.respondentId, respondents.id))
.leftJoin(users, eq(respondents.userId, users.id))
.offset(page * limit)
.limit(limit);
const totalItems = await db
.select({
count: sql<number>`COUNT(*)`,
})
.from(assessments);
return c.json({
data: result,
_metadata: {
currentPage: page,
totalPages: Math.ceil(totalItems[0].count / limit),
totalItems: totalItems[0].count,
perPage: limit,
},
});
}
)
// Get Assessment Result by ID
.get(
"/:id",
checkPermission("assessmentResult.read"),
async (c) => {
const assessmentId = c.req.param("id");
const result = await db
.select({
respondentName: users.name,
position: respondents.position,
workExperience: respondents.workExperience,
email: users.email,
companyName: respondents.companyName,
address: respondents.address,
phoneNumber: respondents.phoneNumber,
username: users.username,
assessmentDate: assessments.createdAt,
statusAssessment: assessments.status,
assessmentsResult: sql<number>`
(SELECT ROUND(AVG(${options.score}), 2)
FROM ${answers}
JOIN ${options} ON ${options.id} = ${answers.optionId}
JOIN ${questions} ON ${questions.id} = ${options.questionId}
JOIN ${subAspects} ON ${subAspects.id} = ${questions.subAspectId}
JOIN ${aspects} ON ${aspects.id} = ${subAspects.aspectId}
WHERE ${answers.assessmentId} = ${assessments.id})`
.as("assessmentsResult"),
})
.from(assessments)
.leftJoin(respondents, eq(assessments.respondentId, respondents.id))
.leftJoin(users, eq(respondents.userId, users.id))
.where(eq(assessments.id, assessmentId));
if (!result.length) {
throw notFound({
message: "Assessment not found",
});
}
return c.json(result[0]);
}
)
// Get all Questions and Options that relate to Sub Aspects and Aspects based on Assessment ID
.get(
"getAllQuestion/:id",
checkPermission("assessmentResult.readAllQuestions"),
async (c) => {
const assessmentId = c.req.param("id");
if (!assessmentId) {
throw notFound({
message: "Assessment ID is missing",
});
}
// Total count of options related to the assessment
const totalCountQuery = sql<number>`
SELECT count(*)
FROM ${options}
LEFT JOIN ${questions} ON ${options.questionId} = ${questions.id}
LEFT JOIN ${subAspects} ON ${questions.subAspectId} = ${subAspects.id}
LEFT JOIN ${aspects} ON ${subAspects.aspectId} = ${aspects.id}
LEFT JOIN ${answers} ON ${options.id} = ${answers.optionId}
WHERE ${questions.deletedAt} IS NULL
AND ${answers.assessmentId} = ${assessmentId}
`;
// Query to get detailed information about options
const result = await db
.select({
optionId: options.id,
aspectsId: aspects.id,
aspectsName: aspects.name,
subAspectId: subAspects.id,
subAspectName: subAspects.name,
questionId: questions.id,
questionText: questions.question,
answerId: answers.id,
answerText: options.text,
answerScore: options.score,
})
.from(options)
.leftJoin(questions, eq(options.questionId, questions.id))
.leftJoin(subAspects, eq(questions.subAspectId, subAspects.id))
.leftJoin(aspects, eq(subAspects.aspectId, aspects.id))
.leftJoin(answers, eq(options.id, answers.optionId))
.where(sql`${questions.deletedAt} IS NULL AND ${answers.assessmentId} = ${assessmentId}`);
// Execute the total count query
const totalCountResult = await db.execute(totalCountQuery);
if (result.length === 0) {
throw notFound({
message: "Data does not exist",
});
}
return c.json({
data: result,
totalCount: totalCountResult[0]?.count || 0
});
}
)
// POST Endpoint for creating a new answer revision
.post(
"/answer-revisions",
checkPermission("assessmentResult.create"),
requestValidator(
"json",
z.object({
answerId: z.string(),
newOptionId: z.string(),
revisedBy: z.string(),
newValidationInformation: z.string(),
})
),
async (c) => {
const { answerId, newOptionId, revisedBy, newValidationInformation } = c.req.valid("json");
// Check if the answer exists
const existingAnswer = await db
.select()
.from(answers)
.where(eq(answers.id, answerId));
if (!existingAnswer.length) {
throw notFound({
message: "Answer not found",
});
}
// Insert new revision
const [newRevision] = await db
.insert(answerRevisions)
.values({
answerId,
newOptionId,
revisedBy,
newValidationInformation
})
.returning();
return c.json(
{
message: "Answer revision created successfully",
data: newRevision
},
201
);
}
);
export default assessmentRoute;

View File

@ -0,0 +1,536 @@
import { and, eq, ilike, or, sql } from "drizzle-orm";
import { Hono } from "hono";
import { z } from "zod";
import db from "../../drizzle";
import { answers } from "../../drizzle/schema/answers";
import { options } from "../../drizzle/schema/options";
import { questions } from "../../drizzle/schema/questions";
import { subAspects } from "../../drizzle/schema/subAspects";
import { aspects } from "../../drizzle/schema/aspects";
import { assessments } from "../../drizzle/schema/assessments";
import HonoEnv from "../../types/HonoEnv";
import requestValidator from "../../utils/requestValidator";
import authInfo from "../../middlewares/authInfo";
import checkPermission from "../../middlewares/checkPermission";
import path from "path";
import fs from 'fs';
import { notFound } from "../../errors/DashboardError";
export const answerFormSchema = z.object({
optionId: z.string().min(1),
assessmentId: z.string().min(1),
isFlagged: z.boolean().optional().default(false),
filename: z.string().optional(),
validationInformation: z.string().min(1),
});
export const answerUpdateSchema = answerFormSchema.partial();
// Helper function to save the file
async function saveFile(filePath: string, fileBuffer: Buffer): Promise<void> {
await fs.promises.writeFile(filePath, fileBuffer);
}
// Function to update the filename in the database
async function updateFilenameInDatabase(answerId: string, filename: string): Promise<void> {
await db.update(answers)
.set({ filename })
.where(eq(answers.id, answerId));
}
const assessmentsRoute = new Hono<HonoEnv>()
.use(authInfo)
// Get data for current Assessment Score from submitted options By Assessment Id
.get(
"/getCurrentAssessmentScore",
checkPermission("assessments.readAssessmentScore"),
requestValidator(
"query",
z.object({
assessmentId: z.string(),
})
),
async (c) => {
const { assessmentId } = c.req.valid("query");
// Query to sum the scores of selected options for the current assessment
const result = await db
.select({
totalScore: sql<number>`SUM(${options.score})`,
})
.from(answers)
.leftJoin(options, eq(answers.optionId, options.id))
.where(eq(answers.assessmentId, assessmentId))
.execute();
return c.json({
assessmentId,
totalScore: result[0]?.totalScore ?? 0, // Return 0 if no answers are found
});
}
)
// Get all Questions and Options that relate to Sub Aspects and Aspects
.get(
"/getAllQuestions",
checkPermission("assessments.readAllQuestions"),
async (c) => {
const totalCountQuery =
sql<number>`(SELECT count(*)
FROM ${options}
LEFT JOIN ${questions} ON ${options.questionId} = ${questions.id}
LEFT JOIN ${subAspects} ON ${questions.subAspectId} = ${subAspects.id}
LEFT JOIN ${aspects} ON ${subAspects.aspectId} = ${aspects.id}
WHERE ${questions.deletedAt} IS NULL
)`;
const result = await db
.select({
optionId: options.id,
aspectsId: aspects.id,
aspectsName: aspects.name,
subAspectId: subAspects.id,
subAspectName: subAspects.name,
questionId: questions.id,
questionText: questions.question,
optionText: options.text,
optionScore: options.score,
fullCount: totalCountQuery,
})
.from(options)
.leftJoin(questions, eq(options.questionId, questions.id))
.leftJoin(subAspects, eq(questions.subAspectId, subAspects.id))
.leftJoin(aspects, eq(subAspects.aspectId, aspects.id))
.where(sql`${questions.deletedAt} IS NULL`)
return c.json({
data: result.map((d) => (
{
...d,
fullCount: undefined
}
)),
});
}
)
// Get all Answers Data by Assessment Id
.get(
"/getAnswers",
checkPermission("assessments.readAnswers"),
requestValidator(
"query",
z.object({
assessmentId: z.string(), // Require assessmentId as a query parameter
withMetadata: z
.string()
.optional()
.transform((v) => v?.toLowerCase() === "true"),
page: z.coerce.number().int().min(0).default(0),
limit: z.coerce.number().int().min(1).max(1000).default(1000),
q: z.string().default(""),
})
),
async (c) => {
const { assessmentId, page, limit, q } = c.req.valid("query");
// Query to count total answers for the specific assessmentId
const totalCountQuery =
sql<number>`(SELECT count(*)
FROM ${answers}
WHERE ${answers.assessmentId} = ${assessmentId})`;
// Query to retrieve answers for the specific assessmentId
const result = await db
.select({
id: answers.id,
assessmentId: answers.assessmentId,
optionId: answers.optionId,
isFlagged: answers.isFlagged,
filename: answers.filename,
validationInformation: answers.validationInformation,
fullCount: totalCountQuery,
})
.from(answers)
.where(
and(
eq(answers.assessmentId, assessmentId), // Filter by assessmentId
q
? or(
ilike(answers.filename, q),
ilike(answers.validationInformation, q),
eq(answers.id, q)
)
: undefined
)
)
.offset(page * limit)
.limit(limit);
return c.json({
data: result.map((d) => ({ ...d, fullCount: undefined })),
_metadata: {
currentPage: page,
totalPages: Math.ceil(
(Number(result[0]?.fullCount) ?? 0) / limit
),
totalItems: Number(result[0]?.fullCount) ?? 0,
perPage: limit,
},
});
}
)
// Toggles the isFlagged field between true and false
.patch(
"/:id/toggleFlag",
checkPermission("assessments.toggleFlag"),
async (c) => {
const answerId = c.req.param("id");
// Retrieve the current state of isFlagged
const currentAnswer = await db
.select({
isFlagged: answers.isFlagged,
})
.from(answers)
.where(eq(answers.id, answerId))
.limit(1);
if (!currentAnswer.length) {
throw notFound(
{
message: "Answer not found",
}
)
}
// Toggle the isFlagged value
const newIsFlaggedValue = !currentAnswer[0].isFlagged;
// Update the answer with the toggled value
const updatedAnswer = await db
.update(answers)
.set({
isFlagged: newIsFlaggedValue,
})
.where(eq(answers.id, answerId))
.returning();
if (!updatedAnswer.length) {
throw notFound(
{
message: "Failed to update answer",
}
)
}
return c.json(
{
message: "Answer flag toggled successfully",
answer: updatedAnswer[0],
},
200
);
}
)
// Get data answers from table answers by optionId and assessmentId
.post(
"/checkDataAnswer",
checkPermission("assessments.checkAnswer"),
async (c) => {
const { optionId, assessmentId } = await c.req.json();
const result = await db
.select()
.from(answers)
.where(
and(eq(answers.optionId, optionId), eq(answers.assessmentId, assessmentId))
)
.execute();
const existingAnswer = result[0];
let response;
if (existingAnswer) {
response = {
exists: true,
answerId: existingAnswer.id
};
} else {
response = {
exists: false
};
}
return c.json(response);
}
)
// Upload filename to the table answers and save the file on the local storage
.post(
"/uploadFile",
checkPermission("assessments.uploadFile"),
async (c) => {
// Get the Content-Type header
const contentType = c.req.header('content-type');
if (!contentType || !contentType.includes('multipart/form-data')) {
throw notFound({
message: "Invalid Content-Type",
});
}
// Extract boundary
const boundary = contentType.split('boundary=')[1];
if (!boundary) {
throw notFound({
message: "Boundary not found",
});
}
// Get the raw body
const body = await c.req.arrayBuffer();
const bodyString = Buffer.from(body).toString();
// Split the body by the boundary
const parts = bodyString.split(`--${boundary}`);
let fileUrl = null;
for (const part of parts) {
if (part.includes('Content-Disposition: form-data;')) {
// Extract file name
const match = /filename="(.+?)"/.exec(part);
if (match) {
const fileName = match[1];
const fileContentStart = part.indexOf('\r\n\r\n') + 4;
const fileContentEnd = part.lastIndexOf('\r\n');
// Extract file content as Buffer
const fileBuffer = Buffer.from(part.slice(fileContentStart, fileContentEnd), 'binary');
// Define file path and save the file
const filePath = path.join('images', Date.now() + '-' + fileName);
await saveFile(filePath, fileBuffer);
// Assuming answerId is passed as a query parameter or in the form-data
const answerId = c.req.query('answerId');
if (!answerId) {
throw notFound({
message: "answerId is required",
});
}
await updateFilenameInDatabase(answerId, path.basename(filePath));
// Set the file URL for the final response
fileUrl = `/images/${path.basename(filePath)}`;
}
}
}
if (!fileUrl) {
throw notFound({
message: 'No file uploaded',
});
}
return c.json(
{
success: true,
imageUrl: fileUrl
}
);
}
)
// Submit option to table answers from use-form in frontend
.post(
"/submitAnswer",
checkPermission("assessments.submitAnswer"),
requestValidator("json", answerFormSchema),
async (c) => {
const answerData = c.req.valid("json");
const answer = await db
.insert(answers)
.values({
optionId: answerData.optionId,
assessmentId: answerData.assessmentId,
isFlagged: answerData.isFlagged,
filename: answerData.filename,
validationInformation: answerData.validationInformation,
})
.returning();
return c.json(
{
message: "Answer created successfully",
answer: answer[0],
},
201
);
}
)
// Update answer in table answers if answer changes
.patch(
"/:id/updateAnswer",
checkPermission("assessments.updateAnswer"),
requestValidator("json", answerUpdateSchema),
async (c) => {
const answerId = c.req.param("id");
const answerData = c.req.valid("json");
const updatedAnswer = await db
.update(answers)
.set({
optionId: answerData.optionId,
})
.where(eq(answers.id, answerId))
.returning();
if (!updatedAnswer.length) {
throw notFound({
message: "Answer not found or update failed"
})
}
return c.json({
message: "Answer updated successfully",
answer: updatedAnswer[0],
});
}
)
// Get data for One Sub Aspect average score By Sub Aspect Id and Assessment Id
.get(
'/average-score/sub-aspects/:subAspectId/assessments/:assessmentId',
// checkPermission("assessments.readAssessmentScore"),
async (c) => {
const { subAspectId, assessmentId } = c.req.param();
const averageScore = await db
.select({
subAspectName: subAspects.name,
average: sql`AVG(options.score)`
})
.from(answers)
.innerJoin(options, eq(answers.optionId, options.id))
.innerJoin(questions, eq(options.questionId, questions.id))
.innerJoin(subAspects, eq(questions.subAspectId, subAspects.id))
.innerJoin(assessments, eq(answers.assessmentId, assessments.id))
.where(
sql`sub_aspects.id = ${subAspectId} AND assessments.id = ${assessmentId}`
)
.groupBy(subAspects.id);
return c.json({
subAspectId,
subAspectName: averageScore[0].subAspectName,
assessmentId,
averageScore: averageScore.length > 0 ? averageScore[0].average : 0
});
}
)
// Get data for All Sub Aspects average score By Assessment Id
.get(
'/average-score/sub-aspects/assessments/:assessmentId',
// checkPermission("assessments.readAssessmentScore"),
async (c) => {
const { assessmentId } = c.req.param();
const averageScores = await db
.select({
subAspectId: subAspects.id,
subAspectName: subAspects.name,
average: sql`AVG(options.score)`
})
.from(answers)
.innerJoin(options, eq(answers.optionId, options.id))
.innerJoin(questions, eq(options.questionId, questions.id))
.innerJoin(subAspects, eq(questions.subAspectId, subAspects.id))
.innerJoin(assessments, eq(answers.assessmentId, assessments.id))
.where(eq(assessments.id, assessmentId))
.groupBy(subAspects.id);
return c.json({
assessmentId,
subAspects: averageScores.map(score => ({
subAspectId: score.subAspectId,
subAspectName: score.subAspectName,
averageScore: score.average
}))
});
}
)
// Get data for One Aspect average score By Aspect Id and Assessment Id
.get(
"/average-score/aspects/:aspectId/assessments/:assessmentId",
async (c) => {
const { aspectId, assessmentId } = c.req.param();
const averageScore = await db
.select({
aspectName: aspects.name,
average: sql`AVG(options.score)`
})
.from(answers)
.innerJoin(options, eq(answers.optionId, options.id))
.innerJoin(questions, eq(options.questionId, questions.id))
.innerJoin(subAspects, eq(questions.subAspectId, subAspects.id))
.innerJoin(aspects, eq(subAspects.aspectId, aspects.id))
.innerJoin(assessments, eq(answers.assessmentId, assessments.id))
.where(
sql`aspects.id = ${aspectId} AND assessments.id = ${assessmentId}`
)
.groupBy(aspects.id);
return c.json({
aspectId,
aspectName: averageScore[0].aspectName,
assessmentId,
averageScore: averageScore.length > 0 ? averageScore[0].average : 0
});
}
)
// Get data for All Aspects average score By Assessment Id
.get(
'/average-score/aspects/assessments/:assessmentId',
// checkPermission("assessments.readAssessmentScore"),
async (c) => {
const { assessmentId } = c.req.param();
const averageScores = await db
.select({
AspectId: aspects.id,
AspectName: aspects.name,
average: sql`AVG(options.score)`
})
.from(answers)
.innerJoin(options, eq(answers.optionId, options.id))
.innerJoin(questions, eq(options.questionId, questions.id))
.innerJoin(subAspects, eq(questions.subAspectId, subAspects.id))
.innerJoin(aspects, eq(subAspects.aspectId, aspects.id))
.innerJoin(assessments, eq(answers.assessmentId, assessments.id))
.where(eq(assessments.id, assessmentId))
.groupBy(aspects.id);
return c.json({
assessmentId,
aspects: averageScores.map(score => ({
AspectId: score.AspectId,
AspectName: score.AspectName,
averageScore: score.average
}))
});
}
)
export default assessmentsRoute;

Binary file not shown.

After

Width:  |  Height:  |  Size: 447 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

View File

@ -1,21 +1,24 @@
import { createLazyFileRoute, useNavigate } from "@tanstack/react-router";
import { useMutation } from "@tanstack/react-query";
import { Input } from '@/shadcn/components/ui/input.tsx';
import { Button } from '@/shadcn/components/ui/button.tsx';
import { Alert } from '@/shadcn/components/ui/alert.tsx';
import { Card } from '@/shadcn/components/ui/card.tsx';
import {
Paper,
PasswordInput,
Stack,
Text,
TextInput,
Group,
Button,
Alert,
} from "@mantine/core";
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage
} from '@/shadcn/components/ui/form.tsx';
import client from "../../honoClient";
import { useForm } from "@mantine/form";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "mantine-form-zod-resolver";
import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect, useState } from "react";
import useAuth from "@/hooks/useAuth";
import { TbArrowNarrowRight } from "react-icons/tb";
export const Route = createLazyFileRoute("/login/")({
component: LoginPage,
@ -38,11 +41,11 @@ export default function LoginPage() {
const { isAuthenticated, saveAuthData } = useAuth();
const form = useForm<FormSchema>({
initialValues: {
resolver: zodResolver(formSchema),
defaultValues: {
username: "",
password: "",
},
validate: zodResolver(formSchema),
});
useEffect(() => {
@ -94,63 +97,94 @@ export default function LoginPage() {
};
return (
<div className="w-screen h-screen flex items-center justify-center">
<Paper radius="md" p="xl" withBorder w={400}>
<Text size="lg" fw={500} mb={30}>
Welcome
</Text>
<form onSubmit={form.onSubmit(handleSubmit)}>
<Stack>
{errorMessage ? (
<Alert
variant="filled"
color="pink"
title=""
// icon={icon}
>
{errorMessage}
</Alert>
) : null}
<TextInput
label="Username or Email"
placeholder="Enter your username or email"
name="username"
autoComplete="username"
disabled={loginMutation.isPending}
{...form.getInputProps("username")}
/>
<PasswordInput
label="Password"
placeholder="Your password"
name="password"
autoComplete="password"
disabled={loginMutation.isPending}
{...form.getInputProps("password")}
/>
</Stack>
<Group justify="space-between" mt="xl">
{/* <Anchor
component="a"
type="button"
c="dimmed"
size="xs"
<div
className="flex items-center justify-center bg-contain bg-top lg:bg-right
bg-no-repeat bg-[url('../src/assets/backgrounds/backgroundLoginMobile.png')]
lg:bg-[url('../src/assets/backgrounds/backgroundLogin.png')]"
>
<div className="absolute top-[1.688rem] left-[1.875rem] text-base font-bold leading-[1.21rem]">
Amati
</div>
<div className="w-screen h-screen flex ml-0 lg:ml-[7.063rem] justify-center lg:justify-start items-center">
<Card className="w-[19.125rem] sm:w-[26.063rem] lg:w-[29.5rem] h-auto bg-transparent border-none">
<h1 className="mb-2 text-[2.625rem] font-bold leading-[3.177rem] tracking-tightest">Sign In</h1>
<p className="text-sm mb-10 leading-[1.059rem]">
New to this app?{' '}
<a
href="/register"
className="text-blue-500 font-bold hover:text-blue-800"
>
Don&apos;t have an account? Register
</Anchor> */}
<div />
<Button
type="submit"
radius="xl"
disabled={loginMutation.isPending}
>
Login
</Button>
</Group>
</form>
</Paper>
Register now
</a>
</p>
<Form {...form}>
<form onSubmit={form.handleSubmit(handleSubmit)}>
<div className="space-y-5">
{errorMessage && (
<Alert variant="destructive">
<p>{errorMessage}</p>
</Alert>
)}
<FormField
name="username"
render={({ field }) => (
<FormItem className="text-sm">
<FormLabel className="font-semibold leading-[1.059rem]">Email/Username</FormLabel>
<FormControl>
<Input
placeholder="eg; user@mail.com"
disabled={loginMutation.isPending}
className={form.formState.errors.username ? "border-red-500" : ""}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
name="password"
render={({ field }) => (
<FormItem className="text-sm">
<FormLabel className="font-semibold leading-[1.059rem]">Password</FormLabel>
<FormControl>
<Input
type="password"
placeholder="*****"
disabled={loginMutation.isPending}
className={form.formState.errors.password ? "border-red-500" : ""}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<p className="text-sm">
<a
href="/forgot-password"
className="text-blue-500 font-bold hover:text-blue-800 leading-[1.059rem]"
>
Forgot Password?
</a>
</p>
</div>
<div className="flex justify-between mt-10">
<Button
type="submit"
disabled={loginMutation.isPending}
variant="default"
className="w-full flex items-center justify-center space-x-[13.125rem] sm:space-x-[20rem]
lg:space-x-[23.125rem] bg-[#2555FF] text-white hover:bg-[#1e4ae0]"
>
<span className="leading-[1.25rem]">Sign In</span>
<TbArrowNarrowRight className="h-5 w-5" />
</Button>
</div>
</form>
</Form>
</Card>
</div>
</div>
);
}

View File

@ -0,0 +1,59 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
))
Alert.displayName = "Alert"
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
))
AlertTitle.displayName = "AlertTitle"
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
))
AlertDescription.displayName = "AlertDescription"
export { Alert, AlertTitle, AlertDescription }

View File

@ -0,0 +1,79 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-lg border bg-card text-card-foreground shadow-sm",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h3
ref={ref}
className={cn(
"text-2xl font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }

View File

@ -72,6 +72,16 @@ module.exports = {
"accordion-up": "accordion-up 0.2s ease-out",
},
},
letterSpacing: {
tightest: '-.075em',
tighter: '-.05em',
tight: '-.025em',
normal: '0',
wide: '.025em',
wider: '.05em',
widest: '.1em',
widest: '.25em',
},
},
plugins: [require("tailwindcss-animate")],
}