feat(controllers): add rent controller
- Implemented functionality for creating, updating, and getting rent information. - Created `createRent`, `updateRent`, `getAllAssigned`, and `getAssignedToUser` functions in the `rent.controller.ts` file. - These functions handle all the interactions related to renting vehicles. Issue: #25 Signed-off-by: Mathis <yidhra@tuta.io>
This commit is contained in:
parent
30c6f2e3f1
commit
bdba2f6e29
150
src/controllers/rent.controller.ts
Normal file
150
src/controllers/rent.controller.ts
Normal file
@ -0,0 +1,150 @@
|
||||
import { isDebugMode } from "@utils/debugState";
|
||||
import type { Request, Response } from "express";
|
||||
import { Logger } from "tslog";
|
||||
import RentService from "@services/rent.service";
|
||||
import {HttpStatusCode} from "@interfaces/requests/HttpStatusCode";
|
||||
import type IDbRent from "@interfaces/database/IDbRent";
|
||||
import JwtService from "@services/jwt.service";
|
||||
import UserService from "@services/user.service";
|
||||
|
||||
|
||||
const logger = new Logger({
|
||||
name: "RentController",
|
||||
});
|
||||
|
||||
async function createRent(req: Request, res: Response): Promise<Response> {
|
||||
try {
|
||||
const rentData: IDbRent = req.body;
|
||||
if (!rentData.active || !rentData.need_survey || !rentData.eat || !rentData.iat || !rentData.user_id || !rentData.vehicle_id || !rentData.km_at_start || !rentData.active) {
|
||||
logger.error("Invalid rent data");
|
||||
return res.status(HttpStatusCode.BadRequest).json({
|
||||
error: "Invalid rent data",
|
||||
});
|
||||
}
|
||||
const rent = await RentService.create(rentData);
|
||||
logger.info(`\n\n> Rent created successfully! (ID: ${rentData.vehicle_id})\n`);
|
||||
return res.status(201).json({
|
||||
message: "Rent created successfully",
|
||||
rent,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(`\n\n> Failed to create rent !\n${error}\n`);
|
||||
return res.status(500).json({
|
||||
error: "Failed to create rent",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function updateRent(req: Request, res: Response): Promise<Response> {
|
||||
const body: IDbRent = req.body;
|
||||
if (!body.vehicle_id || !body.user_id || !body.active || !body.need_survey || !body.eat || !body.iat || !body.km_at_start) {
|
||||
logger.error("Invalid rent data");
|
||||
return res.status(HttpStatusCode.BadRequest).json({
|
||||
error: "Invalid rent data",
|
||||
});
|
||||
}
|
||||
const rentId = req.params["rentId"];
|
||||
if (!rentId || rentId.length !== 36) {
|
||||
logger.error("Invalid rent ID");
|
||||
return res.status(HttpStatusCode.BadRequest).json({
|
||||
error: "Invalid rent ID",
|
||||
});
|
||||
}
|
||||
const result = await RentService.update({
|
||||
id: rentId,
|
||||
vehicle_id: ``,
|
||||
user_id: ``,
|
||||
active: !!body.active,
|
||||
need_survey: !!body.need_survey,
|
||||
eat: body.eat,
|
||||
iat: body.iat,
|
||||
km_at_start: body.km_at_start,
|
||||
})
|
||||
if (!result) {
|
||||
logger.error(`Failed to update rent with ID: ${rentId}`);
|
||||
return res.status(HttpStatusCode.InternalServerError).json({
|
||||
error: `Failed to update rent with ID: ${rentId}`,
|
||||
});
|
||||
}
|
||||
logger.info(`Rent with ID: ${rentId} updated successfully`);
|
||||
return res.status(HttpStatusCode.Ok).json({
|
||||
message: `Rent with ID: ${rentId} updated successfully`,
|
||||
});
|
||||
}
|
||||
|
||||
async function getAllAssigned(res: Response): Promise<Response> {
|
||||
const rents = await RentService.getAll();
|
||||
if (rents.length === 0) {
|
||||
return res.status(HttpStatusCode.NotFound).json({
|
||||
error: "No assigned rents found",
|
||||
});
|
||||
}
|
||||
return res.status(HttpStatusCode.Ok).json({
|
||||
iat: Date.now(),
|
||||
rents: rents,
|
||||
total: rents.length
|
||||
});
|
||||
}
|
||||
|
||||
async function getAssignedToUser(req: Request, res: Response): Promise<Response> {
|
||||
const authHeader = req.headers.authorization;
|
||||
const bearerToken = authHeader?.split(" ")[1];
|
||||
if (!bearerToken) {
|
||||
logger.warn(`Bearer token not provided (${req.ip})`);
|
||||
return res
|
||||
.type("application/json")
|
||||
.status(HttpStatusCode.Unauthorized)
|
||||
.json({
|
||||
error: "Unauthorized",
|
||||
});
|
||||
}
|
||||
const payload = await JwtService.verify(bearerToken);
|
||||
if (!payload || !payload.sub) {
|
||||
logger.warn(`Unauthorized access attempt (${req.ip})`);
|
||||
return res
|
||||
.type("application/json")
|
||||
.status(HttpStatusCode.Unauthorized)
|
||||
.json({
|
||||
error: "Unauthorized",
|
||||
});
|
||||
}
|
||||
const sourceUser = await UserService.getFromId(payload.sub);
|
||||
if (!sourceUser) {
|
||||
return res.type("application/json").status(HttpStatusCode.ImATeapot).json({
|
||||
error: "You dont exist anymore",
|
||||
});
|
||||
}
|
||||
const userId: string = payload.sub;
|
||||
if (!userId || userId.length !== 36) {
|
||||
logger.error("Invalid user ID");
|
||||
return res.status(HttpStatusCode.BadRequest).json({
|
||||
error: "Invalid user ID",
|
||||
});
|
||||
}
|
||||
let targetId = userId
|
||||
if ("is_admin" in sourceUser && sourceUser.is_admin) {
|
||||
targetId = req.body.targetId || userId
|
||||
}
|
||||
const rents = await RentService.getUserRent(targetId);
|
||||
if (!rents) {
|
||||
return res.status(HttpStatusCode.NotFound).json({
|
||||
error: "No assigned rents found for the user",
|
||||
});
|
||||
}
|
||||
return res.status(HttpStatusCode.Ok).json({
|
||||
iat: Date.now(),
|
||||
rents: rents,
|
||||
total: rents.length,
|
||||
});
|
||||
}
|
||||
|
||||
if (isDebugMode()) logger.debug("\nController loaded.");
|
||||
|
||||
const RentController = {
|
||||
create: createRent,
|
||||
update: updateRent,
|
||||
getAll: getAllAssigned,
|
||||
getAssignedToUser,
|
||||
};
|
||||
|
||||
export default RentController;
|
Loading…
x
Reference in New Issue
Block a user