Skip to content

Commit

Permalink
implement get client api adress and locatio
Browse files Browse the repository at this point in the history
  • Loading branch information
wayneleon1 committed Jul 11, 2024
1 parent 88c23e7 commit 40adc7e
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 63 deletions.
1 change: 1 addition & 0 deletions .github/workflows/workflow_for_ecomm.yml
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,4 @@ jobs:
API_KEY_URL: ${{ secrets.API_KEY_URL }}
SUBSCRIPTION_KEY: ${{ secrets.SUBSCRIPTION_KEY }}
DEFAULT_PROFILE_URL: ${{ secrets.DEFAULT_PROFILE_URL }}
IP_KEYS: ${{ secrets.IP_KEYS }}
10 changes: 5 additions & 5 deletions package-lock.json

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

41 changes: 26 additions & 15 deletions src/controller/cartController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,8 @@ import applyCoupon from '../utilis/couponCalculator';
import { Order } from '../database/models/orderEntity';
import { OrderDetails } from '../database/models/orderDetailsEntity';
import { check, validationResult } from 'express-validator';


import {eventEmitter} from '../Notification.vendor/event.services'
import { eventEmitter } from '../Notification.vendor/event.services';
import axios from 'axios';

const cartRepository = dbConnection.getRepository(Cart);
const productRepository = dbConnection.getRepository(Product);
Expand Down Expand Up @@ -65,9 +64,9 @@ export const addToCart = errorHandler(async (req: Request, res: Response) => {
newItem.quantity = quantity;

const savedItem = await cartRepository.save(newItem);
eventEmitter.emit('addToCart',productId, userId)

eventEmitter.emit('addToCart', productId, userId);

return res
.status(201)
.json({ msg: 'Item added to cart successfully', cartItem: savedItem });
Expand Down Expand Up @@ -150,7 +149,7 @@ export const removeItem = errorHandler(async (req: Request, res: Response) => {

const cartItem = await cartRepository.findOne({
where: { id: itemId },
select:{user:{id:true}, product:{id:true}},
select: { user: { id: true }, product: { id: true } },
relations: ['user', 'product'],
});

Expand All @@ -159,7 +158,7 @@ export const removeItem = errorHandler(async (req: Request, res: Response) => {
}
const deletedItem = await cartRepository.delete(itemId);

eventEmitter.emit('removeItem', cartItem)
eventEmitter.emit('removeItem', cartItem);

return res.status(200).json({
msg: 'Cart Item deleted successfully',
Expand Down Expand Up @@ -198,6 +197,20 @@ export const checkout = [
// Fetch the user who is checking out
const user = await userRepository.findOne({ where: { id: userId } });

// Get user country location
let country: string;
axios
.get(
`https://ipgeolocation.abstractapi.com/v1/?api_key=${process.env.IP_KEYS}&ip_address=`
)
.then((response) => {
// console.log(response.data.country);
country = response.data.country;
})
.catch((error) => {
res.send(error);
});

// Fetch the cart items for this user
const cartItems = await cartRepository.find({
where: { user: { id: userId } },
Expand Down Expand Up @@ -233,7 +246,6 @@ export const checkout = [
orderDetail.price = price;

orderDetails.push(orderDetail);

}

// Ensure totalAmount is an integer
Expand All @@ -246,12 +258,13 @@ export const checkout = [
order.totalAmount = totalAmount;
order.status = 'Pending';
order.deliveryInfo = deliveryInfo;
order.country = country!;
order.trackingNumber = trackingNumber;
order.orderDetails = orderDetails;

const savedOrder = await orderRepository.save(order);
eventEmitter.emit('pressorder', order)

eventEmitter.emit('pressorder', order);

await cartRepository.delete({ user: { id: userId } });

Expand Down Expand Up @@ -292,11 +305,9 @@ export const cancelOrder = errorHandler(async (req: Request, res: Response) => {
if (!order) {
return res.status(404).json({ msg: 'Order not found' });
}
eventEmitter.emit('order_canceled', orderId)

await orderRepository.remove(order);
eventEmitter.emit('order_canceled', orderId);


await orderRepository.remove(order);

return res.status(200).json({ msg: 'Order canceled successfully' });
});
90 changes: 47 additions & 43 deletions src/controller/categoryController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import errorHandler from '../middlewares/errorHandler';
import { Order } from '../database/models/orderEntity';

const categoryRepository = dbConnection.getRepository(Category);
const orderRepository = dbConnection.getRepository(Order)
const orderRepository = dbConnection.getRepository(Order);

interface categoryRequestBody {
name: string;
Expand Down Expand Up @@ -136,64 +136,68 @@ export const deleteCategory = errorHandler(
export const getCategoryMetrics = errorHandler(
async (req: Request, res: Response) => {
const orders = await orderRepository.find({
where:{
paid: true
where: {
paid: true,
},
select:{
id:true,
totalAmount:true,
paid:true,
orderDetails:{
id:true,
price:true,
quantity:true,
product:{
id:true,
name:true,
category:{
id:true,
name:true
}
select: {
id: true,
totalAmount: true,
paid: true,
orderDetails: {
id: true,
price: true,
quantity: true,
product: {
id: true,
name: true,
category: {
id: true,
name: true,
},
},
}
},
},
relations:['orderDetails','orderDetails.product','orderDetails.product.category']
})
relations: [
'orderDetails',
'orderDetails.product',
'orderDetails.product.category',
],
});

const categories = await categoryRepository.find({
select:{
products:{
id:true
}
select: {
products: {
id: true,
},
},
relations: ['products']
})

const counter:{[key:string]:number} = {};
for(const order of orders){
for(const orderDetail of order.orderDetails){
if(orderDetail.product.category.name in order){
counter[orderDetail.product.category.name] += orderDetail.price
}else{
counter[orderDetail.product.category.name] = orderDetail.price
relations: ['products'],
});

const counter: { [key: string]: number } = {};
for (const order of orders) {
for (const orderDetail of order.orderDetails) {
if (orderDetail.product.category.name in counter) {
counter[orderDetail.product.category.name] += orderDetail.price;
} else {
counter[orderDetail.product.category.name] = orderDetail.price;
}
}
}

const data = []
const data = [];

for(const category of categories){
if(category.name in counter){
for (const category of categories) {
if (category.name in counter) {
data.push({
categoryName: category.name,
totalProducts: category.products.length,
totalSales: counter[category.name]
})
totalSales: counter[category.name],
});
}
}

data.sort((a, b) => b.totalSales - a.totalSales)
data.sort((a, b) => b.totalSales - a.totalSales);

return res.status(200).json({data:data.slice(0,4)})
return res.status(200).json({ data: data.slice(0, 4) });
}
);
);
3 changes: 3 additions & 0 deletions src/database/models/orderEntity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ export class Order {
@Column({ nullable: true })
deliveryInfo: string;

@Column({ nullable: true })
country: string;

@Column({ nullable: true })
paymentInfo: string;

Expand Down

0 comments on commit 40adc7e

Please sign in to comment.