Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev -> Master: new features & bug fixes #188

Merged
merged 21 commits into from
May 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"vue.features.codeActions.enable": false
}
7 changes: 7 additions & 0 deletions src/apis/v1/admin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ router.post(
validationMiddleware(CreateDocumentRequestForAdmin, APP_CONSTANTS.body),
asyncRouteHandler(controller.createNewDocumentByAdmin)
);
router.post(
'/documents',
authMiddleware,
adminMiddleware,
validationMiddleware(CreateDocumentRequestForAdmin, APP_CONSTANTS.body),
asyncRouteHandler(controller.createNewDocumentByAdmin)
);
router.post('/login', asyncRouteHandler(controller.adminLogin));
router.patch(
'/exams/:id',
Expand Down
13 changes: 6 additions & 7 deletions src/apis/v1/documents/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ export const getDocuments = async (req: RequestWithUser, res: Response) => {
export const createDocument = async (req: RequestWithUser, res: Response) => {
const input: DocumentDto = req.body;
const author: string = req?.user?._id;

const result = await service.createDocument(input, author);

res.send(fmt.formatResponse(result, Date.now() - req.startTime, 'OK'));
};

Expand All @@ -27,7 +25,6 @@ export const updateDocumentByOwner = async (req: RequestWithUser, res: Response)
const input: UpdateDocumentByOwnerDto = req.body;
const author: string = req?.user?._id;
const result = await service.updateDocumentByOwner(input, params.id, author);

res.send(fmt.formatResponse(result, Date.now() - req.startTime, 'OK'));
};

Expand All @@ -46,13 +43,15 @@ export const getDocumentById = async (req: RequestWithUser, res: Response) => {
};

export const getDocumentsBySubjectId = async (req: RequestWithUser, res: Response) => {
const urlParams: URLParams = req.searchParams;
const input: ParamsDocumentDto = req.params;
const result = await service.getDocumentsBySubjectId(input.id);
res.send(fmt.formatResponse(result, Date.now() - req.startTime, 'OK'));
const { result, meta } = await service.getDocumentsBySubjectId(input.id, urlParams);
res.send(fmt.formatResponse(result, Date.now() - req.startTime, 'OK', meta.total, meta.currentPage, meta.pageSize));
};

export const getDocumentsByOwner = async (req: RequestWithUser, res: Response) => {
const urlParams: URLParams = req.searchParams;
const author: string = req?.user?._id;
const result = await service.getDocumentsByOwner(author);
res.send(fmt.formatResponse(result, Date.now() - req.startTime, 'OK'));
const { result, meta } = await service.getDocumentsByOwner(author, urlParams);
res.send(fmt.formatResponse(result, Date.now() - req.startTime, 'OK', meta.total, meta.currentPage, meta.pageSize));
};
53 changes: 42 additions & 11 deletions src/apis/v1/documents/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ export const getDocuments = async (urlParams: URLParams) => {
try {
const pageSize = urlParams.pageSize || DEFAULT_PAGING.limit;
const currentPage = urlParams.currentPage || DEFAULT_PAGING.skip;

const order = urlParams.order || 'DESC';

const count = DocumentModel.countDocuments({ is_approved: true });
Expand Down Expand Up @@ -126,6 +125,7 @@ export const getDocumentById = async (params: ParamsDocumentDto, userRank: strin

if (!checker) {
const user = await UserModel.findOne({ email: userEmail });

return {
notice: {
message: 'You do not have permission to view this document',
Expand Down Expand Up @@ -153,7 +153,6 @@ export const getDocumentsByAdmin = async (filter: DocumentFilter, urlParams: URL
try {
const pageSize = urlParams.pageSize || DEFAULT_PAGING.limit;
const currentPage = urlParams.currentPage || DEFAULT_PAGING.skip;

const order = urlParams.order || 'DESC';

const count = DocumentModel.countDocuments({ ...filter });
Expand Down Expand Up @@ -184,39 +183,71 @@ export const getDocumentsByAdmin = async (filter: DocumentFilter, urlParams: URL
}
};

export const getDocumentsBySubjectId = async (subjectId: string) => {
export const getDocumentsBySubjectId = async (subjectId: string, urlParams: URLParams) => {
try {
const pageSize = urlParams.pageSize || DEFAULT_PAGING.limit;
const currentPage = urlParams.currentPage || DEFAULT_PAGING.skip;
const order = urlParams.order || 'DESC';

const count = DocumentModel.countDocuments({ is_approved: true, subject: subjectId });
const results = DocumentModel.find({ is_approved: true, subject: subjectId })
.skip(pageSize * currentPage)
.limit(pageSize)
.sort({ created_at: order === 'DESC' ? -1 : 1 })
.populate('author', '-is_blocked -roles -created_at -updated_at -__v')
.populate('subject', '-is_deleted -created_at -updated_at -__v');

const subject = SubjectModel.findOne({ _id: subjectId });

const resultAll = await Promise.all([results, subject]);
const resultAll = await Promise.all([count, results, subject]);

logger.info(`Get all documents by subjectId successfully`);
return {
documents: resultAll[0].map((documents: any) => {
return { ...documents.toObject(), author: hideUserInfoIfRequired(documents?.author) };
}),
subject: resultAll[1],
result: {
documents: resultAll[1].map((document: any) => {
return { ...document.toObject(), author: hideUserInfoIfRequired(document?.author) };
}),
subject: resultAll[2],
},
meta: {
total: resultAll[0],
currentPage,
pageSize,
},
};
} catch (error) {
logger.error(`Error while get documents by subjectId: ${error}`);
throw new HttpException(400, ErrorCodes.BAD_REQUEST.MESSAGE, ErrorCodes.BAD_REQUEST.CODE);
}
};

export const getDocumentsByOwner = async (authorId: string) => {
export const getDocumentsByOwner = async (authorId: string, urlParams: URLParams) => {
try {
const results = await DocumentModel.find({ author: authorId })
const pageSize = urlParams.pageSize || DEFAULT_PAGING.limit;

const currentPage = urlParams.currentPage || DEFAULT_PAGING.skip;

const order = urlParams.order || 'DESC';

const count = DocumentModel.countDocuments({ author: authorId });

const results = DocumentModel.find({ author: authorId })
.skip(pageSize * currentPage)
.limit(pageSize)
.sort({ created_at: order === 'DESC' ? -1 : 1 })
.populate('author', '-is_blocked -roles -created_at -updated_at -__v')
.populate('subject', '-is_deleted -created_at -updated_at -__v');

const resolveAll = await Promise.all([count, results]);
return {
documents: results.map((document) => {
result: resolveAll[1].map((document: DocumentType) => {
return { ...document.toObject(), author: hideUserInfoIfRequired(document?.author) };
}),
meta: {
total: resolveAll[0],
currentPage,
pageSize,
},
};
} catch (error) {
logger.error(`Error while get documents by Owner: ${error}`);
Expand Down
8 changes: 5 additions & 3 deletions src/apis/v1/exam/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ export const getExams = async (req: RequestWithUser, res: Response) => {
export const getExamById = async (req: RequestWithUser, res: Response) => {
const input: ParamsExamDto = req.params;
const userRank = req?.user?.rank;
const userEmail = req?.user?.email;

const result = await service.getExamById(input.id, userRank);
const result = await service.getExamById(input.id, userRank, userEmail);

res.send(fmt.formatResponse(result, Date.now() - req.startTime, 'OK'));
};
Expand Down Expand Up @@ -62,8 +63,9 @@ export const getDraftExam = async (req: RequestWithUser, res: Response) => {
};

export const getExamsByOwner = async (req: RequestWithUser, res: Response) => {
const urlParams: URLParams = req.searchParams;
const author = req?.user?._id;
const result = await service.getExamsByOwner(String(author));
const { result, meta } = await service.getExamsByOwner(String(author), urlParams);

res.send(fmt.formatResponse(result, Date.now() - req.startTime, 'OK'));
res.send(fmt.formatResponse(result, Date.now() - req.startTime, 'OK', meta.total, meta.currentPage, meta.pageSize));
};
31 changes: 25 additions & 6 deletions src/apis/v1/exam/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ export const getExams = async (urlParams: URLParams) => {
try {
const pageSize = urlParams.pageSize || DEFAULT_PAGING.limit;
const currentPage = urlParams.currentPage || DEFAULT_PAGING.skip;

const order = urlParams.order || 'DESC';

const count = ExamModel.countDocuments();
Expand Down Expand Up @@ -88,7 +87,7 @@ export const getExams = async (urlParams: URLParams) => {
};

//Get a user's exam by id
export const getExamById = async (id: string, userRank: string) => {
export const getExamById = async (id: string, userRank: string, userEmail: string) => {
const _id = new ObjectId(id);
try {
const data = await ExamModel.aggregate([
Expand Down Expand Up @@ -131,6 +130,7 @@ export const getExamById = async (id: string, userRank: string) => {
title: 1,
description: 1,
is_approved: 1,
school_year: 1,
author: {
_id: '$author._id',
fullname: '$author.fullname',
Expand Down Expand Up @@ -165,13 +165,15 @@ export const getExamById = async (id: string, userRank: string) => {
const checker = checkRankCompatibility(userRank, data[0].rank);

if (!checker) {
const user = await UserModel.findOne({ email: userEmail });

return {
notice: {
message: 'You do not have permission to view this document',
code: 'PERMISSION_DENIED',
minimum_required_rank: data[0].rank,
your_rank: userRank,
your_dedication_score: data[0]?.dedication_score,
your_dedication_score: user?.dedication_score,
minimum_required_score: RANK_TYPE[data[0]?.rank].score,
},
};
Expand Down Expand Up @@ -271,8 +273,14 @@ export const getExamsBySubjectId = async (subjectId: string, urlParams: URLParam
throw new HttpException(400, ErrorCodes.BAD_REQUEST.MESSAGE, ErrorCodes.BAD_REQUEST.CODE);
}
};
export const getExamsByOwner = async (authorId: string) => {
export const getExamsByOwner = async (authorId: string, urlParams: URLParams) => {
try {
const pageSize = urlParams.pageSize || DEFAULT_PAGING.limit;

const currentPage = urlParams.currentPage || DEFAULT_PAGING.skip;

const order = urlParams.order || 'DESC';

const _id = new ObjectId(authorId);
const count = ExamModel.countDocuments({ author: authorId });
const data = ExamModel.aggregate([
Expand Down Expand Up @@ -320,14 +328,25 @@ export const getExamsByOwner = async (authorId: string) => {
},
},
{
$sort: { created_at: -1 },
$sort: { created_at: order === 'DESC' ? -1 : 1 },
},
{
$skip: Number(pageSize * currentPage),
},
{
$limit: Number(pageSize),
},
]);
const resolveAll = await Promise.all([count, data]);
return {
exams: resolveAll[1].map((exam: Exam) => {
result: resolveAll[1].map((exam: any) => {
return { ...exam, author: hideUserInfoIfRequired(exam?.author) };
}),
meta: {
total: resolveAll[0],
currentPage,
pageSize,
},
};
} catch (error) {
logger.error(`Error while get exam by Owner: ${error}`);
Expand Down
1 change: 1 addition & 0 deletions src/apis/v1/user/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ router.post(
);

router.get('/', authMiddleware, adminMiddleware, asyncRouteHandler(controller.getUsers));
router.get('/email', authMiddleware, adminMiddleware, asyncRouteHandler(controller.getUserByEmail));

router.get('/email', authMiddleware, adminMiddleware, asyncRouteHandler(controller.getUserByEmail));

Expand Down
3 changes: 2 additions & 1 deletion src/apis/v1/userExam/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ export const createUserExam = async (req: RequestWithUser, res: Response) => {
const input: UserExamDto = req.body;
const author: string = req?.user?._id;
const userRank = req?.user?.rank;
const userEmail = req?.user?.email;

const result = await service.createUserExam(input, author, userRank);
const result = await service.createUserExam(input, author, userRank, userEmail);
res.send(fmt.formatResponse(result, Date.now() - req.startTime, 'OK'));
};

Expand Down
Loading