Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/dev' into feature-organisation
Browse files Browse the repository at this point in the history
feat: update organisation details
  • Loading branch information
oderahub committed Jul 24, 2024
2 parents 2480eb8 + a4f73b2 commit dbdf6ae
Show file tree
Hide file tree
Showing 17 changed files with 138 additions and 42 deletions.
2 changes: 1 addition & 1 deletion docs/sendEmail.md
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ export class EmailService {
}

async sendEmail(payload: EmailQueuePayload): Promise<void> {
console.log(`Sending email to ${payload.recipient} using template ${payload.templateId} with variables:`, payload.variables);


try {
// Actual email sending logic here
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"scripts": {
"start:dev": "ts-node-dev --respawn --transpile-only ./src/index",
"start": "ts-node --transpile-only src/index.ts",
"test": "jest ",
"test": "jest --forceExit",
"test:email": "jest views/email/tests",
"typeorm": "typeorm-ts-node-commonjs",
"build": "tsc",
Expand Down
71 changes: 69 additions & 2 deletions src/controllers/AdminController.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { Request, Response } from "express";
import { AdminOrganisationService, AdminUserService } from "../services";
import {
AdminOrganisationService,
AdminUserService,
AdminLogService,
} from "../services";
import { HttpError } from "../middleware";
import { check, param, validationResult } from "express-validator";
import { UserRole } from "../enums/userRoles";
Expand Down Expand Up @@ -390,4 +394,67 @@ class AdminUserController {
}
}

export default { AdminOrganisationController, AdminUserController };
// Get activities log
class AdminLogController {
private adminLogService: AdminLogService;

constructor() {
this.adminLogService = new AdminLogService();
}

async getLogs(req: Request, res: Response): Promise<void> {
try {
await check("page")
.optional()
.isInt({ min: 1 })
.withMessage("Page must be a positive integer.")
.run(req);
await check("limit")
.optional()
.isInt({ min: 1 })
.withMessage("Limit must be a positive integer.")
.run(req);
await check("sort")
.optional()
.isIn(["asc", "desc"])
.withMessage('Sort must be either "asc" or "desc".')
.run(req);
await check("offset")
.optional()
.isInt({ min: 0 })
.withMessage("Offset must be a non-negative integer.")
.run(req);

const errors = validationResult(req);
if (!errors.isEmpty()) {
res.status(422).json({
status: "unsuccessful",
status_code: 422,
message: errors.array()[0].msg,
});
return;
}

const data = await this.adminLogService.getPaginatedLogs(req);
res.status(200).json({
status: "success",
status_code: 200,
data,
});
} catch (error) {
if (error instanceof HttpError) {
res.status(error.status_code).json({ message: error.message });
} else {
res
.status(500)
.json({ message: error.message || "Internal Server Error" });
}
}
}
}

export default {
AdminOrganisationController,
AdminUserController,
AdminLogController,
};
1 change: 0 additions & 1 deletion src/controllers/NotificationController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,6 @@ const CreateNotification = async (req: Request, res: Response) => {
});
}
} catch (error) {
console.log(error);
res.status(500).json({
status: "error",
code: 500,
Expand Down
15 changes: 4 additions & 11 deletions src/controllers/ProductController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,6 @@ export class ProductController {
message: err.message,
status_code: 500,
});
console.error(err);
}
}
}
Expand Down Expand Up @@ -251,26 +250,24 @@ export class ProductController {
*/

async fetchProductById(req: Request, res: Response) {

const productId = req.params.product_id;

if(isNaN(Number(productId))){
if (isNaN(Number(productId))) {
return res.status(400).json({
status: "Bad Request",
message: "Invalid Product Id",
status_code: 400,
})
});
}

try {
const product = await this.productService.getOneProduct(productId)
const product = await this.productService.getOneProduct(productId);
if (!product) {
return res.status(404).json({
status: "Not found",
message: "Product not found",
status_code: 404,
});

}
return res.status(200).json(product);
} catch (error) {
Expand All @@ -280,7 +277,6 @@ export class ProductController {
status_code: 500,
});
}

}

/**
Expand Down Expand Up @@ -565,10 +561,7 @@ export class ProductController {
* type: string
* example: Product not found
*/
async deleteProduct(req: Request, res: Response) {


}
async deleteProduct(req: Request, res: Response) {}
}

export default ProductController;
1 change: 0 additions & 1 deletion src/controllers/exportController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ class exportController {
try {
const format = req.query.format as string;
const userId = req.user.id;
console.log(`Requested format: ${format}`);

const user = await ExportService.getUserById(userId);
if (!user) {
Expand Down
6 changes: 0 additions & 6 deletions src/controllers/updateBlogController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@ export const updateBlogController = async (req: Request, res: Response) => {
const { id } = req.params;
const { title, content, published_at, image_url } = req.body;

console.log("Controller - updateBlogController called with id:", id);
console.log("Controller - Request body:", req.body);

try {
const updatedBlog = await updateBlogPost(
id,
Expand All @@ -16,7 +13,6 @@ export const updateBlogController = async (req: Request, res: Response) => {
published_at,
image_url,
);
console.log("Controller - Blog post updated successfully:", updatedBlog);

return res.status(200).json({
status: "success",
Expand All @@ -25,8 +21,6 @@ export const updateBlogController = async (req: Request, res: Response) => {
data: updatedBlog,
});
} catch (error) {
console.error("Controller - Error updating blog post:", error);

return res.status(500).json({
status: "unsuccessful",
status_code: 500,
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,6 @@ AppDataSource.initialize()
log.info(`Server is listening on port ${port}`);
});
})
.catch((error) => console.error(error));
.catch((error) => log.error(error));

export default server;
2 changes: 1 addition & 1 deletion src/middleware/testimonial.validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const validateTestimonial = [
body("testimonial").notEmpty().withMessage("Testimonial is required"),
(req: Request, res: Response, next: NextFunction) => {
const errors = validationResult(req);
console.log(errors);

if (!errors.isEmpty()) {
throw new InvalidInput("Validation failed");
}
Expand Down
1 change: 1 addition & 0 deletions src/models/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ export * from "./emailQueue";
export * from "./comment";
export * from "./category";
export * from "./payment";
export * from "./log";
19 changes: 19 additions & 0 deletions src/models/log.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";

@Entity()
export class Log {
@PrimaryGeneratedColumn("uuid")
id: string;

@Column()
user_id: string;

@Column()
action: string;

@Column()
details: string;

@Column()
timestamp: Date;
}
1 change: 1 addition & 0 deletions src/routes/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const adminRouter = Router();

const adminOrganisationController = new admin.AdminOrganisationController();
const adminUserController = new admin.AdminUserController();
const adminLogController = new admin.AdminLogController();

// Organisation
adminRouter.patch(
Expand Down
39 changes: 36 additions & 3 deletions src/services/admin.services.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// / src/services/AdminOrganisationService.ts
import { NextFunction, Request, Response } from "express";
// import { getRepository, Repository } from 'typeorm';
import { User, Organization } from "../models";
import { User, Organization, Log } from "../models";
import AppDataSource from "../data-source";
import { HttpError } from "../middleware";
import { hashPassword } from "../utils/index";
Expand Down Expand Up @@ -37,7 +37,6 @@ export class AdminOrganisationService {
});
return newOrg;
} catch (error) {
console.error(error);
throw new HttpError(error.status || 500, error.message || error);
}
}
Expand Down Expand Up @@ -117,7 +116,41 @@ export class AdminUserService {
});
return updatedUser!;
} catch (error) {
console.error(error);
throw new HttpError(error.status || 500, error.message || error);
}
}
}

export class AdminLogService {
public async getPaginatedLogs(req: Request): Promise<{
logs: Log[];
totalLogs: number;
totalPages: number;
currentPage: number;
}> {
try {
const { page = 1, limit = 10, sort = "desc", offset = 0 } = req.query;
const logRepository = AppDataSource.getRepository(Log);

const [logs, totalLogs] = await logRepository.findAndCount({
order: { id: sort === "asc" ? "ASC" : "DESC" },
skip: Number(offset),
take: Number(limit),
});

const totalPages = Math.ceil(totalLogs / Number(limit));

if (!logs.length) {
throw new HttpError(404, "Logs not found");
}

return {
logs,
totalLogs,
totalPages,
currentPage: Number(page),
};
} catch (error) {
throw new HttpError(error.status || 500, error.message || error);
}
}
Expand Down
1 change: 0 additions & 1 deletion src/services/blog.services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ export class BlogService {
const result = await this.blogRepository.delete(id);
return result.affected !== 0;
} catch (error) {
//console.error('Error deleting blog post:', error);
throw new Error("Error deleting blog post");
}
}
Expand Down
8 changes: 3 additions & 5 deletions src/services/help.services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class HelpService {
if (!title || !content || !author) {
throw new HttpError(
422,
"Validation failed: Title, content, and author are required"
"Validation failed: Title, content, and author are required",
);
}

Expand Down Expand Up @@ -67,7 +67,6 @@ export class HelpService {
});
return newArticle;
} catch (error) {
console.error(error);
throw new HttpError(error.status || 500, error.message || error);
}
}
Expand All @@ -76,7 +75,7 @@ export class HelpService {
export const authMiddleware = (
req: Request,
res: Response,
next: NextFunction
next: NextFunction,
) => {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
Expand Down Expand Up @@ -106,7 +105,7 @@ export const authMiddleware = (
export const verifyAdmin = async (
req: Request,
res: Response,
next: NextFunction
next: NextFunction,
) => {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
Expand All @@ -125,7 +124,6 @@ export const verifyAdmin = async (
const user = await userRepository.findOne({
where: { id: decodedToken.userId },
});
console.log(user.role);

if (user.role !== "admin") {
return res.status(403).json({
Expand Down
5 changes: 0 additions & 5 deletions src/services/sendEmail.services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,6 @@ export class EmailService {
}

async sendEmail(payload: EmailQueuePayload): Promise<void> {
console.log(
`Sending email to ${payload.recipient} using template ${payload.templateId} with variables:`,
payload.variables,
);

try {
} catch (error) {
throw new ServerError("Internal server error");
Expand Down
4 changes: 1 addition & 3 deletions src/services/updateBlog.services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ export const updateBlogPost = async (

try {
await blogRepository.save(blog);
} catch (error) {
console.error("Service - Error saving blog post:", error);
}
} catch (error) {}

return blog;
};

0 comments on commit dbdf6ae

Please sign in to comment.