Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature Manage WishList #112

Merged
merged 2 commits into from
Jun 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 36 additions & 6 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"format": "prettier --write .",
"test": "cross-env NODE_ENV=test jest --runInBand --no-cache --detectOpenHandles",
"test:ci": "cross-env NODE_ENV=test jest --runInBand --coverage --detectOpenHandles"
},
},
"repository": {
"type": "git",
"url": "git+https://github.com/atlp-rwanda/dynamites-ecomm-be.git"
Expand Down
143 changes: 143 additions & 0 deletions src/__test__/buyerWishlist.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import request from 'supertest';
import app from '../app';
import { afterAllHook, beforeAllHook } from './testSetup';
import { getBuyerToken, getVendorToken } from './testSetup';

beforeAll(beforeAllHook);
afterAll(afterAllHook);
export let buyerToken: string;
let vendorToken: string;
let productId: number;
let categoryId: number;

beforeAll(async () => {
buyerToken = await getBuyerToken();
vendorToken = await getVendorToken();

const categoryData = {
name: 'Category4',
description: 'category description',
};

const categoryResponse = await request(app)
.post('/api/v1/category')
.set('Authorization', `Bearer ${vendorToken}`)
.send(categoryData);

categoryId = categoryResponse.body.data.id;

const productData = {
name: 'New Product Two',
image: 'new_product.jpg',
gallery: [],
shortDesc: 'This is a new product',
longDesc: 'Detailed description of the new product',
categoryId: categoryId,
quantity: 10,
regularPrice: 5,
salesPrice: 4,
tags: ['tag1', 'tag2'],
type: 'Simple',
isAvailable: true,
};

const response = await request(app)
.post('/api/v1/product')
.set('Authorization', `Bearer ${vendorToken}`)
.send(productData);

productId = response.body.data.id;

const getResponse = await request(app)
.get(`/api/v1/buyer/get_product/${productId}`)
.set('Authorization', `Bearer ${buyerToken}`);

expect(getResponse.statusCode).toEqual(200);
expect(getResponse.body.msg).toEqual('Product retrieved successfully');
});

describe('POST /api/v1/buyer/addItemToWishList', () => {
it('should add an item to the wishlist', async () => {
const res = await request(app)
.post('/api/v1/buyer/addItemToWishList')
.set('Authorization', `Bearer ${buyerToken}`)
.send({
productId: productId,
time: '2024-05-21T12:00:00Z',
});

expect(res.statusCode).toEqual(201);
expect(res.body.message).toContain('Wishlist successfully created');
});

it('should not allow adding an item already in the wishlist', async () => {
await request(app)
.post('/api/v1/buyer/addItemToWishList')
.set('Authorization', `Bearer ${buyerToken}`)
.send({
productId: productId,
time: '2024-05-21T12:00:00Z',
});

const res = await request(app)
.post('/api/v1/buyer/addItemToWishList')
.set('Authorization', `Bearer ${buyerToken}`)
.send({
productId: productId,
time: '2024-05-21T12:00:00Z',
});

expect(res.statusCode).toEqual(409);
expect(res.body.message).toContain('Product is already in the wishlist');
});
});

describe('DELETE /api/v1/buyer/removeToWishList', () => {
it('should remove a product from the wishlist', async () => {
const res = await request(app)
.delete('/api/v1/buyer/removeToWishList')
.set('Authorization', `Bearer ${buyerToken}`)
.send({
productId: productId,
});

expect(res.statusCode).toEqual(200);
expect(res.body.message).toContain(
'Product successfully removed from wishlist'
);
});
});

describe('GET /api/v1/buyer/getWishList', () => {
it('should get all wishlists', async () => {
const res = await request(app)
.get('/api/v1/buyer/getWishList')
.set('Authorization', `Bearer ${buyerToken}`);

expect(res.statusCode).toEqual(200);
expect(res.body.message).toContain('Data retrieved successfully');
});
});
describe('GET /api/v1/buyer/getOneWishList', () => {
it('should get all wishlists', async () => {
const res = await request(app)
.get('/api/v1/buyer/getOneWishList')
.set('Authorization', `Bearer ${buyerToken}`);

expect(res.statusCode).toEqual(200);
expect(res.body.message).toContain('Data retrieved successfully');
});
});

describe('RemoveProductFromWishList', () => {
it('should return an error when the wishlist or product is not found', async () => {
const res = await request(app)
.delete('/api/v1/buyer/removeToWishList')
.set('Authorization', `Bearer ${buyerToken}`)
.send({
productId: 9999,
});
expect(res.statusCode).toEqual(404);
expect(res.body.message).toContain('Product not found in wishlist');
});
});
5 changes: 4 additions & 1 deletion src/__test__/payment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
id: 'charge_id',
amount: 10000,
currency: 'usd',
status: 'succeeded',
status: 'succeeded', // Ensure the status is 'succeeded'
} as Stripe.Charge);

MockedStripe.prototype.charges = {
Expand All @@ -48,6 +48,9 @@
.set('Authorization', `Bearer ${token}`)
.send({ token: 'fake-token', orderId: order.id });

console.log('Response status:', response.status); // Debugging line

Check warning on line 51 in src/__test__/payment.test.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

Unexpected console statement
console.log('Response body:', response.body); // Debugging line

Check warning on line 52 in src/__test__/payment.test.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

Unexpected console statement

expect(response.status).toBe(200);
expect(response.body.success).toBe(true);
expect(response.body.paid).toBe(true);
Expand Down
67 changes: 31 additions & 36 deletions src/controller/buyerController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,59 +5,51 @@ import errorHandler from '../middlewares/errorHandler';
import Stripe from 'stripe';
import { Order } from '../database/models/orderEntity';


const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || '', { apiVersion: '2024-04-10' });
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || '', {
apiVersion: '2024-04-10',
});
const productRepository = dbConnection.getRepository(Product);
const orderRepository = dbConnection.getRepository(Order);



export const getOneProduct = errorHandler(
async (req: Request, res: Response) => {
const productId = parseInt(req.params.id);



const product = await productRepository.findOne({
where: { id: productId },
relations: ['category'],
});



if (!product) {
return res.status(404).json({ msg: 'Product not found' });
}



return res
.status(200)
.json({ msg: 'Product retrieved successfully', product });
}
);




export const handlePayment = errorHandler(
);

export const handlePayment = errorHandler(
async (req: Request, res: Response) => {
const { token, orderId } = req.body;



const order = await orderRepository.findOne({ where: { id: orderId } });



if (!order) {
return res.status(404).json({ success: false, message: 'Order not found' });
return res
.status(404)
.json({ success: false, message: 'Order not found' });
}



if (order.paid) {
return res.status(400).json({ success: false, message: 'Order has already been paid' });
return res
.status(400)
.json({ success: false, message: 'Order has already been paid' });
}



const amountInCents = order.totalAmount * 100;



const charge = await stripe.charges.create({
amount: amountInCents,
currency: 'usd',
Expand All @@ -67,14 +59,17 @@ export const getOneProduct = errorHandler(

if (charge.status === 'succeeded') {
order.paid = true;
await orderRepository.save(order)
await orderRepository.save(order);

return res.status(200).json({ success: true, paid: true, charge});
}else{
return res.status(200).json({ success: true, paid: true, charge });
} else {
return res
.status(400)
.json({ success: false, paid: false, message: `Charge status: ${charge.status}` });
}
.status(400)
.json({
success: false,
paid: false,
message: `Charge status: ${charge.status}`,
});
}
}
);

);
Loading
Loading