Skip to content
Open
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
47 changes: 39 additions & 8 deletions backend/controllers/admin.controller.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import { debug } from "debug";
import expressAsyncHandler from "express-async-handler";
import { validationResult } from "express-validator";
import { param, validationResult } from "express-validator";
import { FilterQuery } from "mongoose";
import { PostStatus } from "../constants";
import { AuthorizationError } from "../errors";
import { AuthorizationError, ValidationError } from "../errors";
import { PostDto } from "../models/posts";
import { ReportDto } from "../models/reports";
import { UserDto } from "../models/users";
import { PostService, ResendService, UserService } from "../services";
import {
PostService,
ReportService,
ResendService,
UserService,
} from "../services";
import { PaginatedResponse, PostDocument, UserDocument } from "../types";
import {
tryParsePaginationQuery,
Expand All @@ -31,6 +37,7 @@ export class AdminController {
private postService: PostService,
private userService: UserService,
private resendService: ResendService,
private reportService: ReportService,
) {}

pre = (req) => {
Expand Down Expand Up @@ -94,7 +101,6 @@ export class AdminController {
res.json(response);
});


getUserById = expressAsyncHandler(async (req, res, next) => {
this.pre(req);

Expand All @@ -111,14 +117,39 @@ export class AdminController {
const { id } = req.params;

const user = await this.userService.getUserById(id);
const reports = await this.reportService.getUserReports(id);

if (!user) {
res.status(404).json({ error: `User ${id} not found.` });
return;
}

if (!reports) {
res.status(404).json({ error: `Reports from ${id} not found.` });
return;
}

const userDto = UserDto.fromDocument(user);
res.json(userDto);
const reportDtos = reports.map((report) => ReportDto.fromAggregate(report));

res.json({ user: userDto, reports: reportDtos });
});

getUserReportsById = expressAsyncHandler(async (req, res, next) => {
await param("userId").notEmpty().run(req);

const errors = validationResult(req);
if (!errors.isEmpty()) {
throw new ValidationError(errors.array());
}

const { userId } = req.params;

const reports = await this.reportService.getUserReports(userId);

res
.status(200)
.json(reports.map((report) => ReportDto.fromDocument(report)));
});

getUsersToVerify = expressAsyncHandler(async (req, res, next) => {
Expand Down Expand Up @@ -150,13 +181,13 @@ export class AdminController {
{ updatedAt: -1, createdAt: -1 },
);

let userDtos : UserDto[];
let userDtos: UserDto[];
if (reported_user) {
userDtos = users.map((user) => UserDto.fromAggregate(user));
}else {
} else {
userDtos = users.map((user) => UserDto.fromDocument(user));
}

const response: PaginatedResponse<UserDto> = {
data: userDtos || [],
page: page,
Expand Down
1 change: 0 additions & 1 deletion backend/controllers/report.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,6 @@ export class ReportController {
const { userId } = req.params;

const reports = await this.reportService.getUserReports(userId);

res
.status(200)
.json(reports.map((report) => ReportDto.fromDocument(report)));
Expand Down
6 changes: 5 additions & 1 deletion backend/models/reports/report.dto.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Document } from "mongoose";
import { PostDocument, Report, UserDocument } from "../../types";
import { PostDocument, Report, UserDocument, ReportDocument } from "../../types";
import { PostDto } from "../posts";
import { UserDto } from "../users";

Expand All @@ -25,6 +25,10 @@ export class ReportDto {
const report = document.toObject() as Report;
return new ReportDto(document.id, report);
}
static fromAggregate(document: ReportDocument): ReportDto {
return new ReportDto(document._id, document);
}

}

export class ReportedPostDto {
Expand Down
4 changes: 3 additions & 1 deletion backend/routes/admin.routes.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
import { Router } from "express";
import { AdminController } from "../controllers/admin.controller";
import { ensureAdmin, ensureAuthenticated } from "../middlewares";
import { PostService, ResendService, UserService } from "../services";
import { PostService, ResendService, UserService, ReportService } from "../services";

// * middleware function to create route handlers
const router = Router();

const postService = new PostService();
const userService = new UserService();
const resendService = new ResendService();
const reportService = new ReportService();
const adminController = new AdminController(
postService,
userService,
resendService,
reportService,
);

// * wire up routes with controller
Expand Down
10 changes: 7 additions & 3 deletions backend/seeder/seed.reports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,16 @@ import { PostDocument, ReportDocument, UserDocument } from "../types.js";

export const fakeReport = (
reporter: UserDocument,
post: PostDocument
post: PostDocument,
): ReportDocument => {
// 80% chance of being resolved
const status =
Math.random() <= 0.8 ? ReportStatus.RESOLVED : ReportStatus.UNRESOLVED;

const report = new ReportModel({
reporter: reporter,
post: post,
status: ReportStatus.UNRESOLVED,
status: status,
notes: faker.word.words({ count: { min: 5, max: 100 } }),
});

Expand All @@ -20,7 +24,7 @@ export const fakeReport = (
export const seedReports = async (
destroy: boolean,
reporter: UserDocument,
posts: PostDocument[]
posts: PostDocument[],
): Promise<ReportDocument[]> => {
if (destroy) {
console.log("🚀 ~ file: seed.reports.ts ~ seedReports ~ destroy:", destroy);
Expand Down
55 changes: 52 additions & 3 deletions backend/services/report.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { ObjectId } from "mongodb";
import { PipelineStage, Types } from "mongoose";
import { ReportModel } from "../models/reports";
import { UserModel } from "../models/users";
import { PostDocument, Report, ReportDocument } from "../types";

export class ReportService {
async createReport(report: Partial<Report>) {
const newReport = new ReportModel({
Expand All @@ -20,7 +21,7 @@ export class ReportService {

async getReportedPosts(
page: number,
limit: number
limit: number,
): Promise<
[{ _id: string; outstanding_reports: number; post: PostDocument }[], number]
> {
Expand Down Expand Up @@ -123,7 +124,55 @@ export class ReportService {
}

async getUserReports(userId: string): Promise<ReportDocument[]> {
const reports = await ReportModel.find({ userId: userId });
const pipeline: PipelineStage[] = [
{
$lookup: {
from: "posts",
localField: "post",
foreignField: "_id",
as: "post",
},
},
{ $unwind: "$post" },
{
$match: {
"post.author": new Types.ObjectId(userId),
},
},
{
$group: {
_id: "$status",
reports: { $push: "$$ROOT" },
count: { $sum: 1 },
},
},
{
$sort: {
count: -1,
updatedAt: -1,
createdAt: -1,
},
},
{
$project: {
_id: 0,
reports: 1,
},
},
{
$unwind: "$reports",
},
{
$replaceRoot: {
newRoot: "$reports",
},
},
];

const reports = await ReportModel.aggregate<ReportDocument>(pipeline);

await UserModel.populate(reports, { path: "reporter" });
await UserModel.populate(reports, { path: "resolver" });

return reports;
}
Expand Down
2 changes: 2 additions & 0 deletions frontend/public/locales/en/common.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"title": "Title",
"open": "Open",
"add": "Add",
"edit": "Edit",
"delete": "Delete",
Expand Down Expand Up @@ -277,6 +278,7 @@
"active": "Active",
"inactive": "Inactive",
"location_information": "Location information",
"report_information": "Report information",
"postal_code": "Postal code",
"organization_information": "Organization information",
"phone_number": "Phone number",
Expand Down
2 changes: 2 additions & 0 deletions frontend/public/locales/fr/common.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"title": "Titre",
"open": "Ouvrir",
"add": "Ajouter",
"edit": "Modifier",
"delete": "Supprimer",
Expand Down Expand Up @@ -277,6 +278,7 @@
"active": "Actif",
"inactive": "Inactif",
"location_information": "Informations de localisation",
"report_information": "Informations sur les rapports",
"postal_code": "Code postal",
"organization_information": "Informations sur l'organisation",
"phone_number": "Numéro de téléphone",
Expand Down
Loading