Skip to content

Commit

Permalink
Merge pull request #98 from atlp-rwanda/ft-order-notification
Browse files Browse the repository at this point in the history
Fix : extended notification emiter
  • Loading branch information
teerenzo authored Jul 29, 2024
2 parents 13f184d + 56ce458 commit 7f189f8
Show file tree
Hide file tree
Showing 6 changed files with 219 additions and 152 deletions.
84 changes: 48 additions & 36 deletions src/controllers/getOrderController.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,60 @@
import { Request, Response } from "express"
import { getOrderBuyer, updateOrderStatusService } from "../services/OrderService"
import { Request, Response } from "express";
import { getOrderBuyer, updateOrderStatusService } from "../services/OrderService";
import * as mailService from "../services/mail.service";
import { SUBJECTS, UserId } from "../types";
import { orderStatusTemplate } from "../email-templates/orderStatus";
import Order from "../sequelize/models/orders";
import User from "../sequelize/models/users";

import Notification from "../sequelize/models/Notification";
import { notificationEmitter } from "../utils/server";

export const getOrderController = async (req: Request, res: Response) => {
try {
const response = await getOrderBuyer(req, res)
return res.status(200).json({
status: 200,
length: response?.length,
orders: response?.length === 0? "You have not order yet" : response
})
} catch (error) {
console.log(error);
res.status(500).json({
status: 500,
message: `error accured during fetching order ${error}`
})
}
}
try {
const response = await getOrderBuyer(req, res);
return res.status(200).json({
status: 200,
length: response?.length,
orders: response?.length === 0 ? "You have not order yet" : response,
});
} catch (error) {
console.log(error);
res.status(500).json({
status: 500,
message: `error accured during fetching order ${error}`,
});
}
};

export const updateOrderStatus = async (req: Request, res: Response) => {

try {
const { id: userId} = req.user as UserId;
const { id: orderId } = req.params;
const { status } = req.body;
const buyerId = await Order.findByPk(orderId)
const dataValues = await User.findByPk(buyerId?.buyerId)
try {
const { id: userId } = req.user as UserId;
const { id: orderId } = req.params;
const { status } = req.body;
const buyerOrder = await Order.findByPk(orderId);
const dataValues = await User.findByPk(buyerOrder?.buyerId);

const updatedItems = await updateOrderStatusService(userId, orderId, status);
if (updatedItems) {
// @ts-ignore
await mailService.sendNotification(
dataValues?.dataValues.email,
SUBJECTS.ORDER_STATUS_UPDATED,
//@ts-ignore
orderStatusTemplate(dataValues?.dataValues.username, buyerOrder?.id, buyerOrder?.createdAt, status),
);

const notification = await Notification.create({
title: "Order Status updated",
message: `Dear ${dataValues?.dataValues.username} your Order ${buyerOrder?.id} status updated to ${status}`,
//@ts-ignore
userId: buyerOrder?.buyerId,
});

const updatedItems = await updateOrderStatusService(userId, orderId, status);
if (updatedItems) {
// @ts-ignore
await mailService.sendNotification(dataValues?.dataValues.email, SUBJECTS.ORDER_STATUS_UPDATED, orderStatusTemplate(dataValues?.dataValues.username, buyerId?.id, buyerId?.createdAt, status))
notificationEmitter.emit("order updated", notification.dataValues);

return res.json({ message: 'Order items status updated', updatedItems });
}

} catch (error: any) {
res.status(500).json({ message: error.message });
return res.json({ message: "Order items status updated", updatedItems });
}
};

} catch (error: any) {
res.status(500).json({ message: error.message });
}
};
90 changes: 45 additions & 45 deletions src/controllers/paymentController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,58 +7,58 @@ import { SUBJECTS } from "../types";
import { confirmPayment } from "../email-templates/confirmPayment";
import stripe from "../config/stripe";
import dotenv from "dotenv";
dotenv.config()
dotenv.config();

const BASE_URL = process.env.IS_REMOTE === "true" ? process.env.FE_URL : process.env.LOCAL_URL;

export const createCheckoutSession = async (req: Request, res: Response) => {
const user: any = req.user;
try {
//@ts-ignore
const cart = req.cart;
const line_items = makeLineItems(cart.userCart);
const customer = await getOrCreateCustomer(user);
const session = await stripe.checkout.sessions.create({
line_items,
mode: "payment",
customer: customer.id,
success_url: `${BASE_URL}/payment/success?sessionId={CHECKOUT_SESSION_ID}&userId=${user.id}`,
cancel_url: `${BASE_URL}/payment/canceled`,
});
return res.status(200).json({
message: "payment session created!",
sessionUrl: session.url
});
} catch (err: any) {
return res.status(500).json({
message: err.message
})
}

const user: any = req.user;
try {
//@ts-ignore
const cart = req.cart;
const line_items = makeLineItems(cart.userCart);
const customer = await getOrCreateCustomer(user);
const session = await stripe.checkout.sessions.create({
line_items,
mode: "payment",
customer: customer.id,
success_url: `${BASE_URL}/payment/success?sessionId={CHECKOUT_SESSION_ID}&userId=${user.id}`,
cancel_url: `${BASE_URL}/payment/canceled`,
});
return res.status(200).json({
message: "payment session created!",
sessionUrl: session.url,
});
} catch (err: any) {
return res.status(500).json({
message: err.message,
});
}
};

export const handleSuccess = async (req: Request, res: Response) => {
try {
const { userId, sessionId } = req.query as { userId: string, sessionId: string }
const session = await stripe.checkout.sessions.retrieve(sessionId);
const user: any = await findUserById(userId);
const cart: any = await viewCart(user);
if (session.payment_status === "paid") {
const order = await placeOrder(cart);
await clearCart(user);
await mailService.sendEmailService(user, SUBJECTS.PAYMENT_CONFIRMATION, confirmPayment(user, order));
return res.status(200).json({
message: "you have successfully paid your products",
order
});
}
} catch (err: any) {
return res.status(500).json({
message: err.message
})
try {
const { userId, sessionId } = req.query as { userId: string; sessionId: string };
const session = await stripe.checkout.sessions.retrieve(sessionId);
const user: any = await findUserById(userId);
const cart: any = await viewCart(user);
if (session.payment_status === "paid") {
const order = await placeOrder(cart);
await clearCart(user);
await mailService.sendEmailService(user, SUBJECTS.PAYMENT_CONFIRMATION, confirmPayment(user, order));

return res.status(200).json({
message: "you have successfully paid your products",
order,
});
}
}
} catch (err: any) {
return res.status(500).json({
message: err.message,
});
}
};

export const handleFailure = async (req: Request, res: Response) => {
return res.status(500).json({ message: "Your payment has failed!" })
}
return res.status(500).json({ message: "Your payment has failed!" });
};
37 changes: 34 additions & 3 deletions src/controllers/wishesController.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import * as wishlistService from "../services/wishlist.service";
import { Request, Response } from "express";
import { wishSchema } from "../schemas/wishShema";
import { notificationEmitter } from "../utils/server";
import Notification from "../sequelize/models/Notification";
import { IUser } from "../types";
import Product from "../sequelize/models/products";

export const addToWishes = async (req: Request, res: Response) => {
//@ts-ignore
const id = req.user.id;
const currentUser: IUser = (req as any).user;
try {
const { error, value } = wishSchema.validate(req.body);
if (error) {
Expand All @@ -14,10 +19,10 @@ export const addToWishes = async (req: Request, res: Response) => {
});
}
const product = await wishlistService.getProduct(value.productId);
if(!product){
if (!product) {
return res.status(404).json({
message: 'product not found'
})
message: "product not found",
});
}
const isProdExisting = await wishlistService.getSingleWish(id, value.productId);
if (isProdExisting) {
Expand All @@ -27,6 +32,14 @@ export const addToWishes = async (req: Request, res: Response) => {
}
const wish = await wishlistService.addToWishlist(id, value.productId);
if (wish) {
const notification = await Notification.create({
title: "Product Added to Wishlist",
message: `${currentUser.name} has added your product ${product.name} to his wishlist`,
userId: wish.sellerId,
});

notificationEmitter.emit("wishlist", notification.dataValues);

return res.status(201).json({
message: "product was added to your wishlist",
});
Expand Down Expand Up @@ -92,14 +105,32 @@ export const deleteWish = async (req: Request, res: Response) => {
//@ts-ignore
const id = req.user.id;
const productId = Number(req.params.id);

const currentUser: IUser = (req as any).user;
try {
const isOwner = await wishlistService.getSingleWish(id, productId);
const product = await Product.findByPk(productId);

if (!product) {
return res.status(404).json({
message: "product not found",
});
}
if (!isOwner) {
return res.status(404).json({
message: "product does not exist in your wishes",
});
} else {
await wishlistService.removeProduct(id, productId);

const notification = await Notification.create({
title: "Product Removed from Wishlist",
message: `${currentUser.name} has removed your product ${product?.name} from his wishlist`,
userId: product.userId,
});

notificationEmitter.emit("wishlist", notification.dataValues);

return res.status(200).json({
message: "product was removed from your wishes",
});
Expand Down
11 changes: 11 additions & 0 deletions src/events/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import NotificationEmitter from "./emmiter";
import { INotification } from "../sequelize/models/Notification";
import { IUser } from "../types";
import { passwordEventEmitter } from "../jobs/isPasswordExpired";
import { wishAttributes } from "../sequelize/models/wishes";

class EventHandler {
public io: SocketIOServer;
Expand Down Expand Up @@ -45,6 +46,16 @@ class EventHandler {
this.io.to(`${data[0].userId}`).emit("notifications", data);
});

this.notificationEmitter.on("wishlist", (data: INotification) => {
this.io.to(`${data.userId}`).emit("notification", data);
});
this.notificationEmitter.on("new order", (data: INotification) => {
this.io.to(`${data.userId}`).emit("notification", data);
});
this.notificationEmitter.on("order updated", (data: INotification) => {
this.io.to(`${data.userId}`).emit("notification", data);
});

passwordEventEmitter.on("password expired", (data: IUser) => {
this.io.to(`${data.id}`).emit("password expired", data);
});
Expand Down
4 changes: 2 additions & 2 deletions src/services/OrderService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,9 @@ export const updateOrderStatusService = async (userId: string, orderId: string,

for (const item of orderItems) {
item.status = status;

await item.save();
}

return orderItems;
};

Loading

0 comments on commit 7f189f8

Please sign in to comment.