Skip to content

Commit

Permalink
Merge pull request #151 from BackendsByMTT/dev-g
Browse files Browse the repository at this point in the history
remove thow
  • Loading branch information
MohitNegi007 authored Sep 10, 2024
2 parents 64c9b5e + fc0489c commit 672c1e3
Show file tree
Hide file tree
Showing 4 changed files with 144 additions and 112 deletions.
34 changes: 34 additions & 0 deletions src/bets/betController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,40 @@ class BetController {
}


// UPADTE OR RESOLVE BET
async resolveBet(req:Request, res: Response, next: NextFunction){
try {
const { betId } = req.params;
const { status } = req.body;
const parentBet = await Bet.findById(betId);
if(!parentBet){
throw createHttpError(404, "Parent Bet not found!")
}
const { data: betDetailsIds, possibleWinningAmount, player: playerId } = parentBet;
await Promise.all(
betDetailsIds.map((betDetailId) =>
BetDetail.findByIdAndUpdate(betDetailId, { status: status })
)
);

const updatedBet = await Bet.findByIdAndUpdate(betId, { status: status }, { new: true });

if(status === "won"){
const player = await PlayerModel.findById(playerId);
if(!player){
throw createHttpError(404, "Player not found")
}
player.credits+=possibleWinningAmount;
await player.save();
}

return res.status(200).json({ message: "Bet resolved successfully", updatedBet });
} catch (error) {
next(error);
}
}


}

export default new BetController();
2 changes: 2 additions & 0 deletions src/bets/betRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,7 @@ betRoutes.put(
checkBetCommision,
betController.redeemPlayerBet
);
betRoutes.put("/resolve/:betId", checkUser, betController.resolveBet)


export default betRoutes;
219 changes: 108 additions & 111 deletions src/notifications/notificationController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,122 +8,119 @@ import { NextFunction, Request, Response } from "express";
import { AuthRequest } from "../utils/utils";

class NotificationController {
public async createNotification(
initiatorId: mongoose.Types.ObjectId,
type: "error" | "success",
message: string,
reference: "bet" | "transaction",
referenceId: mongoose.Types.ObjectId,
action:string
): Promise<void> {
try {

const user:any =
(await User.findById(initiatorId)) ||
(await Player.findById(initiatorId));

if (!user) {
throw createHttpError(401, "User not found");
}

const initiatorModel = user.role !== "player"? 'User':'Player';

let targetId;
let targetModel;
if(user.role !=="admin"){
targetId= user.createdBy
const targetUser:any = (await User.findById(targetId)) ||
(await Player.findById(targetId));
if (!targetUser) {
throw createHttpError(401, "Target User not found");
}

targetModel = targetUser.role === "player"? 'Player':'User';

}else{
targetId=null;
targetModel=null;
}


const newNotification = new Notification({
initiatorId,
targetId,
initiatorModel,
targetModel,
type,
message,
reference,
referenceId,
status: "pending",
action: action
});

const savedNotification = await newNotification.save();

// let updateResult;
// if (targetModel === "Player") {
// updateResult = await Player.findByIdAndUpdate(
// targetId,
// { $push: { notifications: savedNotification._id } },
// { new: true, useFindAndModify: false }
// );
// } else if (targetModel === "User") {
// updateResult = await User.findByIdAndUpdate(
// targetId,
// { $push: { notifications: savedNotification._id } },
// { new: true, useFindAndModify: false }
// );
// }

// if (!updateResult) {
// throw new Error(`Failed to update ${targetModel} with id ${targetId}`);
// }

console.log("Notification created and target updated successfully.");
} catch (error) {
console.error("Error creating notification:", error);
throw new Error("Failed to create notification.");
}
public async createNotification(
initiatorId: mongoose.Types.ObjectId,
targetId: mongoose.Types.ObjectId,
type: "error" | "success",
message: string,
reference: "bet" | "transaction",
referenceId: mongoose.Types.ObjectId,
action: string
): Promise<void> {
try {

const user: any =
(await User.findById(initiatorId)) ||
(await Player.findById(initiatorId));

if (!user) {
throw createHttpError(401, "User not found");
}

async getUserNotification(req: Request, res: Response, next:NextFunction){
const _req = req as AuthRequest;
const { userId} = _req.user;
try {
const notifications = await Notification.find({ targetId: userId });
if (!notifications ) {
throw createHttpError(404, "No notifications found for user")
}
return res.status(200).json(
notifications,
);
} catch (error) {
next(error);
}
};

async resolveNotification(req:Request, res:Response, next:NextFunction){
try {
const { notificationId } = req.params;
const {status} = req.body;
const notificaion = await Notification.findById(notificationId);
if(!notificaion){
throw createHttpError(404, "Notification not found!");
}
notificaion.status = status;
await notificaion.save();
res.status(200).json({
message:"Notification Resolved"
})
} catch (error) {
next(error)

const initiatorModel = user.role !== "player" ? 'User' : 'Player';


let targetModel;

const targetUser: any = (await User.findById(targetId)) ||
(await Player.findById(targetId));
if (!targetUser) {
throw createHttpError(401, "Target User not found");
}

targetModel = targetUser.role === "player" ? 'Player' : 'User';

const newNotification = new Notification({
initiatorId,
targetId,
initiatorModel,
targetModel,
type,
message,
reference,
referenceId,
status: "pending",
action: action
});

const savedNotification = await newNotification.save();

// let updateResult;
// if (targetModel === "Player") {
// updateResult = await Player.findByIdAndUpdate(
// targetId,
// { $push: { notifications: savedNotification._id } },
// { new: true, useFindAndModify: false }
// );
// } else if (targetModel === "User") {
// updateResult = await User.findByIdAndUpdate(
// targetId,
// { $push: { notifications: savedNotification._id } },
// { new: true, useFindAndModify: false }
// );
// }

// if (!updateResult) {
// throw new Error(`Failed to update ${targetModel} with id ${targetId}`);
// }

console.log("Notification created and target updated successfully.");
} catch (error) {
console.error("Error creating notification:", error);
throw new Error("Failed to create notification.");
}
}

async getUserNotification(req: Request, res: Response, next: NextFunction) {
const _req = req as AuthRequest;
const { userId } = _req.user;
try {
const notifications = await Notification.find({ targetId: userId });
if (!notifications) {
throw createHttpError(404, "No notifications found for user")
}
const userNotifications = notifications.filter(notification => notification.initiatorModel === "User");
const playerNotifications = notifications.filter(notification => notification.initiatorModel === "Player");

const populatedUserNotifications = await Notification.populate(userNotifications, { path: 'initiatorId', select: 'username', model: User });
const populatedPlayerNotifications = await Notification.populate(playerNotifications, { path: 'initiatorId', select: 'username', model: Player });

const allPopulatedNotifications = [...populatedUserNotifications, ...populatedPlayerNotifications];
return res.status(200).json(allPopulatedNotifications);
} catch (error) {
next(error);
}
};
async resolveNotification(req: Request, res: Response, next: NextFunction) {
try {
const { notificationId } = req.params;
const { status } = req.body;
const notificaion = await Notification.findById(notificationId);
if (!notificaion) {
throw createHttpError(404, "Notification not found!");
}
notificaion.status = status;
await notificaion.save();
res.status(200).json({
message: "Notification Resolved"
})
} catch (error) {
next(error)
}

}

}



export default new NotificationController();

1 change: 0 additions & 1 deletion src/workers/processingQueueWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,6 @@ async function processCompletedBet(betDetailId, gameData) {

function checkIfPlayerWonBet(betDetail, gameData) {

throw new Error("Not implemented");

// check if the game is completed
if (!gameData.completed) {
Expand Down

0 comments on commit 672c1e3

Please sign in to comment.