Skip to content

Commit

Permalink
Merge branch 'develop' of github.com:atlp-rwanda/e-commerce-ninjas-bn…
Browse files Browse the repository at this point in the history
… into fixes
  • Loading branch information
Aime-Patrick committed Aug 5, 2024
2 parents 1026490 + f2292aa commit 1f287e9
Show file tree
Hide file tree
Showing 10 changed files with 646 additions and 349 deletions.
274 changes: 170 additions & 104 deletions src/middlewares/validation.ts

Large diffs are not rendered by default.

12 changes: 7 additions & 5 deletions src/modules/auth/controller/authControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { usersAttributes } from "../../../databases/models/users";
import authRepositories from "../repository/authRepositories";
import { sendEmail } from "../../../services/sendEmail";
import { eventEmitter } from "../../../helpers/notifications";
import { getEmailVerificationTemplate, getResendVerificationTemplate, passwordResetEmail } from "../../../services/emailTemplate";

const registerUser = async (req: Request, res: Response): Promise<void> => {
try {
Expand All @@ -24,7 +25,7 @@ const registerUser = async (req: Request, res: Response): Promise<void> => {
await sendEmail(
register.email,
"Verification Email",
`${process.env.SERVER_URL_PRO}/api/auth/verify-email/${token}`
getEmailVerificationTemplate(register,token)
);
res.status(httpStatus.CREATED).json({
status: httpStatus.CREATED,
Expand All @@ -45,7 +46,7 @@ const sendVerifyEmail = async (req: any, res: Response) => {
await sendEmail(
req.user.email,
"Verification Email",
`${process.env.SERVER_URL_PRO}/api/auth/verify-email/${req.session.token}`
getResendVerificationTemplate(req.user, req.session.token)
);
res.status(httpStatus.OK).json({
status: httpStatus.OK,
Expand Down Expand Up @@ -123,7 +124,7 @@ const forgetPassword = async (req: any, res: Response): Promise<void> => {
otp: null
};
await authRepositories.createSession(session);
await sendEmail(req.user.email, "Reset password", `${process.env.SERVER_URL_PRO}/api/auth/reset-password/${token}`);
await sendEmail(req.user.email, "Reset password", passwordResetEmail(req.user, token));
res.status(httpStatus.OK).json({ status: httpStatus.OK, message: "Check email for reset password." });
} catch (error) {
res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ status: httpStatus.INTERNAL_SERVER_ERROR, message: error.message });
Expand All @@ -141,16 +142,17 @@ const resetPassword = async (req: any, res: Response): Promise<void> => {
};

const updateUser2FA = async (req: any, res: Response) => {
const { is2FAEnabled } = req.body;
try {
const user = await authRepositories.updateUserByAttributes(
"is2FAEnabled",
true,
!!is2FAEnabled,
"id",
req.user.id
);
res.status(httpStatus.OK).json({
status: httpStatus.OK,
message: "2FA enabled successfully.",
message: `2FA ${is2FAEnabled ? "Enabled" : "Disabled"} successfully.`,
data: { user: user }
});
} catch (error) {
Expand Down
2 changes: 1 addition & 1 deletion src/modules/auth/test/auth.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -942,7 +942,7 @@ describe("updateUser2FA", () => {
expect(response.body).to.have.property("status", httpStatus.OK);
expect(response.body).to.have.property(
"message",
"2FA enabled successfully."
"2FA Enabled successfully."
);
expect(response.body).to.have.property("data");
done(error);
Expand Down
97 changes: 84 additions & 13 deletions src/modules/cart/controller/cartControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ const getProductDetails = (
image: product.images[0],
quantity: cartProduct.quantity,
totalPrice: totalPrice,
shopId: product.shopId,
description: product.description
};
});

Expand Down Expand Up @@ -63,7 +65,7 @@ const buyerGetCart = async (req: ExtendRequest, res: Response) => {

const buyerGetCarts = async (req: ExtendRequest, res: Response) => {
try {
const carts = await cartRepositories.getCartsByUserId(req.user.id);
const carts = await cartRepositories.getCartsByUserId1(req.user.id);

const allCartsDetails = await Promise.all(
carts.map(async (cart) => {
Expand All @@ -74,12 +76,12 @@ const buyerGetCarts = async (req: ExtendRequest, res: Response) => {

return {
cartId: cart.id,
status: cart.status,
products: productsDetails,
total: cartTotal,
};
})
);

return res.status(httpStatus.OK).json({
status: httpStatus.OK,
message: "Buyer's all carts",
Expand Down Expand Up @@ -150,7 +152,7 @@ const buyerCreateUpdateCart = async (req: ExtendRequest, res: Response) => {
try {
const { productId, quantity } = req.body;
const userId = req.user.id;
const carts = await cartRepositories.getCartsByUserId(userId);
const carts = await cartRepositories.getCartsByUserId1(userId);

for (const cart of carts) {
const cartProducts = await cartRepositories.getCartProductsByCartId(
Expand Down Expand Up @@ -275,7 +277,6 @@ const buyerCheckout = async (req: ExtendRequest, res: Response) => {
cart.cartProducts.forEach(product => {
totalAmount += product.totalPrice;
});

return res.status(httpStatus.OK).json({
status: httpStatus.OK,
data: { totalAmount, cart }
Expand All @@ -302,7 +303,20 @@ const buyerGetOrderStatus = async (req: ExtendRequest, res: Response) => {
})
}
}
const buyerGetOrderStatus2 = async (req, res) => {
try {
const order = await req.order
return res.status(httpStatus.OK).json({
status: httpStatus.OK, message: "Order retrieved successfully",
data: {
order
}
})
} catch (error) {

return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ status: httpStatus.INTERNAL_SERVER_ERROR, message: error.message })
}
}
const buyerGetOrders = async (req: ExtendRequest, res: Response) => {
try {
const orders = req.order
Expand All @@ -318,6 +332,21 @@ const buyerGetOrders = async (req: ExtendRequest, res: Response) => {
})
}
}
const buyerGetOrders2 = (req, res) => {
try {
const orders = req.orders
return res.status(httpStatus.OK).json({
message: "Orders found successfully",
data: { orders }
})
}
catch (error) {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({
status: httpStatus.INTERNAL_SERVER_ERROR,
error: error.message
})
}
}

const adminUpdateOrderStatus = async (req: ExtendRequest, res: Response) => {
try {
Expand All @@ -337,28 +366,65 @@ const adminUpdateOrderStatus = async (req: ExtendRequest, res: Response) => {

}

const stripeCreateProduct = async (req, res) => {
try {
let product = await cartRepositories.getStripeProductByAttribute('name', req.body.planInfo.name);
if (!product) product = await cartRepositories.createStripeProduct(req.body.planInfo);
return res.status(httpStatus.OK).json({ message: "Success.", data: { product } });
} catch (error) {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ status: httpStatus.INTERNAL_SERVER_ERROR, error: error.message })
}
};

const stripeCheckoutSession = async (req, res) => {
try {
let customer = await cartRepositories.getStripeCustomerByAttribute('email', req.body.sessionInfo.customer_email);
if (!customer) customer = await cartRepositories.createStripeCustomer({ email: req.body.sessionInfo.customer_email });
delete req.body.sessionInfo.customer_email;
req.body.sessionInfo.customer = customer.id;
let session = await cartRepositories.getStripeSessionByAttribute('customer', customer.id);
if (!session) session = await cartRepositories.createStripeSession(req.body.sessionInfo);
const session = await cartRepositories.createStripeSession(req.body.sessionInfo);
return res.status(httpStatus.OK).json({ message: "Success.", data: { session } });
} catch (error) {
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ status: httpStatus.INTERNAL_SERVER_ERROR, error: error.message })
}
};
const adminGetOrdersHistory = async(req: ExtendRequest, res:Response)=>{
const OrderHistory = (req as any).orders
return res.status(httpStatus.OK).json({
message: "Order History",
data: { OrderHistory }
})

const buyerUpdateCartStatus = async (req, res) => {
try {
const { cartId, status } = req.body
await cartRepositories.updateCartStatus(cartId, status);
const updatedCart = await cartRepositories.getCartByUserIdAndCartId(req.user.id, cartId)
return res.status(httpStatus.OK).json({ status: httpStatus.OK, message: "Cart status updated successfully", data: { updatedCart } })
} catch (error) {
console.log(error.message)
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ status: httpStatus.INTERNAL_SERVER_ERROR, message: error.message })
}
}
const userCreateOrder = (req, res) => {
try {
const userId = req.user.id;
const body = {
userId: userId,
products: req.body.products,
cartId: req.body.cartId,
paymentMethodId: req.body.paymentMethodId,
orderDate: new Date(),
status: req.body.status,
shippingProcess: "Order placed successfully!",
shopId: req.body.shopId,
expectedDeliveryDate: new Date(new Date().setDate(new Date().getDate() + 7))
}

const order = cartRepositories.userSaveOrder(body)
return res.status(httpStatus.CREATED).json({ status: httpStatus.CREATED, message: "Order created succesfully", data: { order } })
} catch (error) {
console.log(error.message)
return res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ status: httpStatus.INTERNAL_SERVER_ERROR, message: error.message })
}
}



export {
buyerGetCart,
buyerGetCarts,
Expand All @@ -374,6 +440,11 @@ export {
buyerGetOrders,
buyerCheckout,
adminUpdateOrderStatus,
stripeCreateProduct,
stripeCheckoutSession,
adminGetOrdersHistory
buyerUpdateCartStatus,
userCreateOrder,
buyerGetOrders2,
buyerGetOrderStatus2

};
78 changes: 74 additions & 4 deletions src/modules/cart/repositories/cartRepositories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,23 @@ import CartProduct from "../../../databases/models/cartProducts";
import Products from "../../../databases/models/products";
import { stripe } from "../../../services/stripe.service";
const getCartsByUserId = async (userId: string) => {
return await db.Carts.findOne({
where: { userId, status: "pending" },
include: [
{
model: db.CartProducts,
as: "cartProducts",
include: [
{
model: db.Products,
as: "products"
},
],
}
]
});
};
const getCartsByUserId1 = async (userId: string) => {
return await db.Carts.findAll({ where: { userId, status: "pending" } });
};

Expand All @@ -32,7 +49,7 @@ const getCartProductsByCartId = async (cartId: string) => {
{
model: db.Products,
as: "products",
attributes: ["id", "name", "price", "discount", "images", "shopId"],
attributes: ["id", "name", "price", "discount", "images", "shopId", "description"],
},
],
});
Expand Down Expand Up @@ -98,9 +115,9 @@ const findCartProductsByCartId = async (value: any) => {
return result;
};

const getCartByUserIdAndCartId = async (userId: string, cartId: string, status: string = "pending") => {
const getCartByUserIdAndCartId = async (userId: string, cartId: string) => {
return await db.Carts.findOne({
where: { id: cartId, userId, status },
where: { id: cartId, userId, status: "pending" },
include: [
{
model: db.CartProducts,
Expand Down Expand Up @@ -155,6 +172,44 @@ const getOrderByOrderIdAndUserId = async (orderId: string, userId: string) => {
})
}

const getOrdersByCartId = async (userId) => {
return await db.Orders.findAll({
include: [
{
model: db.Carts,
as: "carts",
where: { userId: userId }
}
],
order: [
["createdAt", "DESC"]
]
});
};
const getOrderByCartId = async (userId) => {
return await db.Orders.findOne({
include: [
{
model: db.Carts,
as: "carts",
where: { userId: userId }
}
]
});
};
const getOrderByCartId2 = async (userId,orderId) => {
return await db.Orders.findOne({
where: {id: orderId },
include: [
{
model: db.Carts,
as: "carts",
where: { userId: userId }
}
]
});
};

const getOrderById = async (orderId: string) => {
return await db.Orders.findOne({ where: { id: orderId } })
}
Expand Down Expand Up @@ -209,8 +264,17 @@ const getStripeSessionByAttribute = async (primaryKey: string, primaryValue: num
const createStripeSession = async (body: Stripe.Checkout.SessionCreateParams): Promise<Stripe.Checkout.Session> => {
return await stripe.checkout.sessions.create(body);
};
const updateCartStatus = async (cartId: string, status: string) => {

return await db.Carts.update({ status: status },
{ where: { id: cartId } })
}



const userSaveOrder = async (body) => {
return await db.Orders.create(body);
}
export default {
getCartsByUserId,
getCartProductsByCartId,
Expand All @@ -225,6 +289,7 @@ export default {
deleteAllCartProducts,
findCartByAttributes,
getCartsByProductId,
getCartsByUserId1,
findCartProductsByCartId,
getCartByUserIdAndCartId,
findCartProductByCartId,
Expand All @@ -238,5 +303,10 @@ export default {
createStripeProduct, getStripeProductByAttribute,
createStripeCustomer, getStripeCustomerByAttribute,
createStripeSession, getStripeSessionByAttribute,
getOrdersHistory
getOrdersHistory,
updateCartStatus,
userSaveOrder,
getOrdersByCartId,
getOrderByCartId,
getOrderByCartId2
};
Loading

0 comments on commit 1f287e9

Please sign in to comment.