Skip to content

Commit

Permalink
Merge pull request #98 from atlp-rwanda/ft-chat
Browse files Browse the repository at this point in the history
Ft chat
  • Loading branch information
sevelinCa authored Jul 20, 2024
2 parents f85074f + 516da73 commit 0cff03d
Show file tree
Hide file tree
Showing 17 changed files with 280 additions and 121 deletions.
29 changes: 23 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"sequelize-typescript": "^2.1.6",
"sinon": "^18.0.0",
"socket.io": "^4.7.5",
"stripe": "^16.2.0",
"supertest": "^7.0.0",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.0",
Expand Down
99 changes: 99 additions & 0 deletions src/controllers/Payment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import express, { Request, Response } from "express";
import Stripe from "stripe";
import dotenv from "dotenv";
import { findOrderById, findProductById } from "../services/paymentService";

dotenv.config();

const stripe = new Stripe(`${process.env.STRIPE_SECRET_KEY}`);
export const checkout = async (req: Request, res: Response) => {
try {
const orderId = req.params.id;
const order = await findOrderById(orderId);
if (!order) {
return res.status(404).json({ message: "Order not found" });
}
const line_items: any[] = await Promise.all(
order.products.map(async (item: any) => {
const productDetails:any = await findProductById(item.productId);
const unit_amount = Math.round(productDetails!.price * 100);
return {
price_data: {
currency: "usd",
product_data: {
name: productDetails?.name,
images: [productDetails?.image[0]],
},
unit_amount: unit_amount,
},
quantity: item.quantity,
};
})
);
console.log(line_items)


const session = await stripe.checkout.sessions.create({
line_items,
mode: "payment",
success_url: process.env.SUCCESS_PAYMENT_URL,
cancel_url: process.env.CANCEL_PAYMENT_URL,
metadata: {
orderId: orderId,
},
});


res.status(200).json({ url: session.url });
} catch (error: any) {
res.status(500).json({ message: error.message });
}
};

export const webhook = async (req: Request, res: Response) => {
const sig: any = req.headers["stripe-signature"];
const webhookSecret: any = process.env.WEBHOOK_SECRET_KEY;
let event: any;
try {
event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
} catch (err: any) {
console.log(`⚠️ Webhook signature verification failed.`, err.message);
return res.status(400).send(`Webhook Error: ${err.message}`);
}

switch (event.type) {
case "checkout.session.completed":
const session = event.data.object;

try {
const lineItems = await stripe.checkout.sessions.listLineItems(
session.id
);

const orderId = session.metadata.orderId;
const order = await findOrderById(orderId);
if (order) {
order.status = "paid";
await order.save();
} else {
console.error("Order not found:", orderId);
}
} catch (err) {
console.error("Error processing session completed event:", err);
}
break;

case "payment_intent.succeeded":
const paymentIntent = event.data.object;
console.log("Payment Intent succeeded: ", paymentIntent);
break;
case "payment_method.attached":
const paymentMethod = event.data.object;
console.log("Payment Method attached: ", paymentMethod);
break;

default:
console.log(`Unhandled event type ${event.type}`);
}
res.json({ received: true });
};
5 changes: 4 additions & 1 deletion src/controllers/cart.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,10 @@ export const getCart = async (req: Request, res: Response) => {
if (!cart) {
return res.status(404).json({ message: "Cart not found" });
}
const cartitem = await CartItem.findAll({ where: { cartId: cart.cartId } });
const cartitem = await CartItem.findAll({ where: { cartId: cart.cartId }, include: {
model: Product,
as: "Product"
} });

return res.status(200).json({ cartitem });
} catch (error: any) {
Expand Down
5 changes: 3 additions & 2 deletions src/controllers/checkout.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { v4 as uuidv4 } from 'uuid';


export const createOrder = async (req: Request, res: Response) => {
const { userId, deliveryAddress, paymentMethod } = req.body;
const { userId, deliveryAddress, paymentMethod,client } = req.body;
if(!userId || !deliveryAddress || !paymentMethod) {
return res.status(400).json({ message: 'All fields are required' })
}
Expand Down Expand Up @@ -37,7 +37,8 @@ export const createOrder = async (req: Request, res: Response) => {
paymentMethod,
status: 'pending',
products: orderItems,
totalAmount: totalAmount
totalAmount: totalAmount,
client
});
await CartItem.destroy({ where: { cartId: cart.cartId } });
res.status(201).json({ message: 'Order placed successfully', order });
Expand Down
6 changes: 4 additions & 2 deletions src/controllers/product.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export const createProduct = async (req: Request, res: Response) => {
category,
expiringDate,
} = req.body;
console.log(image)
if (!name || !image || !description || !price || !quantity || !category) {
return res.status(200).json("All Field are required");
}
Expand All @@ -55,11 +56,11 @@ export const createProduct = async (req: Request, res: Response) => {
return res.status(400).json({ message: "Exactly 4 images are required" });
}

const imageArray: string[] = image;


const data = {
name,
images: imageArray,
image: image,
description,
discount: discount ? discount : 0,
price,
Expand Down Expand Up @@ -205,6 +206,7 @@ export const deleteProduct = async (req: Request, res: Response) => {
const tokenData = (req as any).token;
const productId = req.params.id;
const { vendorId } = req.body;
console.log(productId)

const permissionCheck: any = await checkVendorModifyPermission(
tokenData,
Expand Down
1 change: 0 additions & 1 deletion src/controllers/review.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,6 @@ export const sales_products = async (req: Request, res: Response) => {
}
}
}

return res.status(200).json({ product: product_purchase });
} catch (error:any) {
return res.status(500).json({ message: error.message });
Expand Down
63 changes: 63 additions & 0 deletions src/controllers/vendor.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { Request, Response } from "express";
import Vendor from "../database/models/vendor";
import { deleteVendorById, saveVendor, updateVendor } from "../services/vendorServices";
import User from "../database/models/user";
import Order from "../database/models/order";
import { Op, Sequelize } from "sequelize";

export const registerVendor = async (req: Request, res: Response) => {
const { userId, storeName, address, TIN, bankAccount, paymentDetails } = req.body
Expand Down Expand Up @@ -67,6 +69,67 @@ export const editVendor = async (req: Request, res: Response) => {
}
};

export const selectVendorInfo = async(req:Request,res:Response)=>{
try {
const vendor = await Vendor.findOne({where:{userId:req.params.id}});
if(!vendor){
return res.status(404).json({message:'Vendor not found'})
}
res.status(200).json({vendor})

} catch (error) {
res.status(500).json({message: error})

}
}

const getOrdersByVendorId = async (vendorId) => {
try {
const orders = await Order.findAll({
where: {
products: {
[Op.contains]: [{
vendorId: vendorId
}]
}
}
});
return orders;
} catch (error) {
console.error("Error fetching orders:", error);
throw error;
}
};

export const vendorOrder = async (req: Request, res: Response) => {
const { vendorId } = req.params;

try {
// Fetch orders that contain products from the specified vendor
const orders = await Order.findAll({
where: {
products: {
[Op.contains]: [{
vendorId: vendorId
}]
}
}
});

const filteredOrders = orders.map(order => {
const filteredProducts = order.products.filter(product => product.vendorId === vendorId);
return {
...order.toJSON(),
products: filteredProducts
};
});

res.status(200).json(filteredOrders);
} catch (error) {
console.error("Error fetching vendor orders:", error);
res.status(500).json({ error: "Internal Server Error" });
}
};

export const allRequests = async (req: Request, res: Response) => {
try {
Expand Down
Loading

0 comments on commit 0cff03d

Please sign in to comment.