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

Merge pull request #124 from atlp-rwanda/fix-user-profile-management #129

Merged
merged 1 commit into from
Jul 25, 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
8,571 changes: 4,902 additions & 3,669 deletions model.nlp

Large diffs are not rendered by default.

49 changes: 17 additions & 32 deletions src/__test__/cart.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

import request from 'supertest';
import jwt from 'jsonwebtoken';
import { app, server } from '../index';
Expand Down Expand Up @@ -38,7 +37,8 @@ let returnedCartItem2Id: string;

const jwtSecretKey = process.env.JWT_SECRET || '';

if (!process.env.TEST_USER_EMAIL || !process.env.TEST_USER_PASS) throw new Error('TEST_USER_PASS or TEST_USER_EMAIL not set in .env');
if (!process.env.TEST_USER_EMAIL || !process.env.TEST_USER_PASS)
throw new Error('TEST_USER_PASS or TEST_USER_EMAIL not set in .env');

const sampleAdmin: UserInterface = {
id: sampleAdminId,
Expand All @@ -53,7 +53,6 @@ const sampleAdmin: UserInterface = {
role: 'ADMIN',
};


const getAccessToken = (id: string, email: string) => {
return jwt.sign(
{
Expand Down Expand Up @@ -232,7 +231,6 @@ afterAll(async () => {
});

describe('Cart| Order management for guest/buyer', () => {

describe('Adding product to cart on guest/buyer', () => {
it('should add product to cart as authenticated buyer', async () => {
const response = await request(app)
Expand Down Expand Up @@ -315,13 +313,10 @@ describe('Cart| Order management for guest/buyer', () => {
});

it('should return 400 for incorrect Id syntax (IDs not in uuid form), when add product to cart', async () => {
const response = await request(app)
.post(`/cart`)
.set('Cookie', [`cartId=dfgdsf`])
.send({
productId: product1Id,
quantity: 3,
});
const response = await request(app).post(`/cart`).set('Cookie', [`cartId=dfgdsf`]).send({
productId: product1Id,
quantity: 3,
});

expect(response.status).toBe(400);
});
Expand Down Expand Up @@ -412,11 +407,8 @@ describe('Cart| Order management for guest/buyer', () => {
expect(response.body.data.cart).toBeDefined;
});


it('should return 400 for incorrect Id syntax (IDs not in uuid form), when getting cart', async () => {
const response = await request(app)
.get(`/cart`)
.set('Cookie', [`cartId=dfgdsf`]);
const response = await request(app).get(`/cart`).set('Cookie', [`cartId=dfgdsf`]);

expect(response.status).toBe(400);
});
Expand Down Expand Up @@ -497,7 +489,6 @@ describe('Cart| Order management for guest/buyer', () => {
productId = response.body.data.orders[0]?.orderItems[0]?.product?.id;
});


it('should get single order', async () => {
const response = await request(app)
.get(`/product/client/orders/${orderId}`)
Expand All @@ -507,7 +498,7 @@ describe('Cart| Order management for guest/buyer', () => {
expect(response.body.data.order).toBeDefined();
});

it('should not return data for single order, if order doesn\'t exist', async () => {
it("should not return data for single order, if order doesn't exist", async () => {
const response = await request(app)
.get(`/product/client/orders/${uuid()}`)
.set('Authorization', `Bearer ${getAccessToken(buyer1Id, sampleBuyer1.email)}`);
Expand Down Expand Up @@ -541,9 +532,7 @@ describe('Cart| Order management for guest/buyer', () => {
});

it('should return 400 when user is not AUTHORIZED', async () => {
const response = await request(app)
.get('/product/orders/history')
.set('Authorization', `Bearer ''`);
const response = await request(app).get('/product/orders/history').set('Authorization', `Bearer ''`);
expect(response.status).toBe(403);
});
});
Expand All @@ -557,7 +546,7 @@ describe('Cart| Order management for guest/buyer', () => {
expect(response.status).toBe(200);
});

it('should return 404, if order doesn\'t exist', async () => {
it("should return 404, if order doesn't exist", async () => {
const response = await request(app)
.put(`/product/client/orders/${uuid()}`)
.send({ orderStatus: 'completed' })
Expand All @@ -583,18 +572,17 @@ describe('Cart| Order management for guest/buyer', () => {
feedbackId = response.body.data.id;
});


it('should create second feedback to the ordered product', async () => {
const response = await request(app)
.post(`/feedback/${productId}/new`)
.send({ orderId, comment: 'Murigalike this product looks so fantastic' })
.set('Authorization', `Bearer ${getAccessToken(buyer1Id, sampleBuyer1.email)}`);
expect(response.status).toBe(201);
feedback2Id = response.body.data.id
feedback2Id = response.body.data.id;
});
it('should updated existing feedback successfully', async () => {
const response = await request(app)
.put(`/feedback/update/${feedbackId}`,)
.put(`/feedback/update/${feedbackId}`)
.send({ orderId, comment: 'Well this product looks so lovely' })
.set('Authorization', `Bearer ${getAccessToken(buyer1Id, sampleBuyer1.email)}`);
expect(response.status).toBe(200);
Expand All @@ -609,7 +597,6 @@ describe('Cart| Order management for guest/buyer', () => {
});

describe('Feedback API', () => {

describe('Add feedback to the product with order', () => {
it('should create new feedback for the ordered product', async () => {
const response = await request(app)
Expand Down Expand Up @@ -725,15 +712,15 @@ describe('Cart| Order management for guest/buyer', () => {
expect(response.body.data.message).toBe('Feedback successfully removed');
});

it('should return 404, if feedback doesn\'t exist', async () => {
it("should return 404, if feedback doesn't exist", async () => {
const response = await request(app)
.delete(`/feedback/admin/delete/${uuid()}`)
.set('Authorization', `Bearer ${getAccessToken(sampleAdminId, sampleAdmin.email)}`);

expect(response.status).toBe(404);
});

it('should return 500, for incorrect feedback id syntax (invalid uuid) doesn\'t exist', async () => {
it("should return 500, for incorrect feedback id syntax (invalid uuid) doesn't exist", async () => {
const response = await request(app)
.delete(`/feedback/admin/delete/invalid-uuid`)
.set('Authorization', `Bearer ${getAccessToken(sampleAdminId, sampleAdmin.email)}`);
Expand All @@ -742,7 +729,6 @@ describe('Cart| Order management for guest/buyer', () => {
});
});
});

});

describe('Deleting product from cart', () => {
Expand Down Expand Up @@ -850,7 +836,7 @@ describe('Cart| Order management for guest/buyer', () => {
expect(response.body.data.cart).toBeDefined;
});

it('should return empty cart for guest user, if he/she doesn\'t have cart', async () => {
it("should return empty cart for guest user, if he/she doesn't have cart", async () => {
const response = await request(app)
.delete('/cart')
.set('Cookie', [`cartId=${sampleCartId}`]);
Expand All @@ -861,10 +847,9 @@ describe('Cart| Order management for guest/buyer', () => {
});

it('should return 400, for incorrect cart id syntax (invalid uuid) for guest user', async () => {
const response = await request(app).delete(`/cart`)
.set('Cookie', [`cartId=invalid-uuid`]);
const response = await request(app).delete(`/cart`).set('Cookie', [`cartId=invalid-uuid`]);

expect(response.status).toBe(400);
});
});
});
});
99 changes: 99 additions & 0 deletions src/__test__/transactions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import request from 'supertest';
import { app, server } from '../index'; // Adjust the path to your Express app
import Stripe from 'stripe';
import jwt from 'jsonwebtoken';
import { User, UserInterface } from '../entities/User';
import { dbConnection } from '../startups/dbConnection';
import { v4 as uuid } from 'uuid';
import { cleanDatabase } from './test-assets/DatabaseCleanup';

jest.mock('stripe', () => {
const stripeInstance = {
paymentIntents: {
list: jest.fn(),
},
};

return jest.fn(() => stripeInstance);
});
const jwtSecretKey = process.env.JWT_SECRET || '';

const getAccessToken = (id: string, email: string) => {
return jwt.sign(
{
id: id,
email: email,
},
jwtSecretKey
);
};

afterAll(async () => {
await cleanDatabase();
server.close();
});

const Admin = uuid();
const sampleAdmin1: UserInterface = {
id: Admin,
firstName: 'vendor1o',
lastName: 'user',
email: '[email protected]',
password: 'password',
userType: 'Vendor',
gender: 'Male',
phoneNumber: '126380996348',
photoUrl: 'https://example.com/photo.jpg',
role: 'ADMIN',
};

const mockStripeInstance = new Stripe('fake-key', { apiVersion: '2024-04-10' }) as jest.Mocked<Stripe>;

describe('Transaction function', () => {
beforeEach(async () => {
const connection = await dbConnection();
(mockStripeInstance.paymentIntents.list as jest.Mock).mockClear();
const userRepository = connection?.getRepository(User);
await userRepository?.save({ ...sampleAdmin1 });
});

it('should return the correct payment statistics', async () => {
(mockStripeInstance.paymentIntents.list as jest.Mock).mockResolvedValue({
data: [
{ amount: 1000, amount_received: 1000, status: 'succeeded' },
{ amount: 2000, amount_received: 0, status: 'pending' },
],
} as any);

const response = await request(app)
.get('/product/transaction')
.set('Authorization', `Bearer ${getAccessToken(Admin, sampleAdmin1.email)}`);

expect(response.body).toEqual({
payments: [
{ amount: 1000, amount_received: 1000, status: 'succeeded' },
{ amount: 2000, amount_received: 0, status: 'pending' },
],
statistics: {
totalPayments: 2,
totalAmount: 3000,
totalCapturedAmount: 1000,
successfulPayments: 1,
pendingPayments: 1,
averagePaymentAmount: 1500,
},
});
});

it('should handle errors gracefully', async () => {
const error = new Error('Something went wrong');
(mockStripeInstance.paymentIntents.list as jest.Mock).mockRejectedValueOnce(error);

const response = await request(app)
.get('/product/transaction')
.set('Authorization', `Bearer ${getAccessToken(Admin, sampleAdmin1.email)}`);

expect(response.status).toBe(500);
expect(response.body).toEqual({ error: 'Something went wrong' });
});
});
13 changes: 8 additions & 5 deletions src/controllers/productController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ import {
productStatusServices,
viewSingleProduct,
searchProductService,
listAllProductsService,
listAllProductsService,
confirmPayment,
getAllCategories
getAllCategories,
transaction,
} from '../services';

export const readProduct = async (req: Request, res: Response) => {
Expand Down Expand Up @@ -53,12 +54,14 @@ export const singleProduct = async (req: Request, res: Response) => {
await viewSingleProduct(req, res);
};
export const searchProduct = async (req: Request, res: Response) => {
await searchProductService (req, res);

await searchProductService(req, res);
};
export const Payment = async (req: Request, res: Response) => {
await confirmPayment(req, res);
};
export const getAllCategory = async (req: Request, res: Response) => {
await getAllCategories(req, res);
};
};
export const getAllTransaction = async (req: Request, res: Response) => {
await transaction(req, res);
};
14 changes: 10 additions & 4 deletions src/routes/ProductRoutes.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { RequestHandler, Router } from 'express';

import { productStatus, searchProduct, } from '../controllers/index';
import { productStatus, searchProduct } from '../controllers/index';
import { hasRole } from '../middlewares/roleCheck';
import upload from '../middlewares/multer';
import { authMiddleware } from '../middlewares/verifyToken';
Expand All @@ -16,19 +16,23 @@ import {
listAllProducts,
singleProduct,
createOrder,
getOrders, getOrder,
getOrders,
getOrder,
updateOrder,
getOrdersHistory, Payment,
getOrdersHistory,
Payment,
getSingleVendorOrder,
getVendorOrders,
updateVendorOrder,
getBuyerVendorOrders,
getSingleBuyerVendorOrder,
updateBuyerVendorOrder,
getAllCategory
getAllCategory,
getAllTransaction,
} from '../controllers';
const router = Router();

router.get('/transaction', authMiddleware as RequestHandler, hasRole('ADMIN'), getAllTransaction);
router.get('/search', searchProduct);
router.get('/all', listAllProducts);
router.get('/recommended', authMiddleware as RequestHandler, hasRole('BUYER'), getRecommendedProducts);
Expand All @@ -55,10 +59,12 @@ router.get('/vendor/orders/:id', authMiddleware as RequestHandler, hasRole('VEND
router.put('/vendor/orders/:id', authMiddleware as RequestHandler, hasRole('VENDOR'), updateVendorOrder);

// Admin order management

router.get('/admin/orders', authMiddleware as RequestHandler, hasRole('ADMIN'), getBuyerVendorOrders);
router.get('/admin/orders/:id', authMiddleware as RequestHandler, hasRole('ADMIN'), getSingleBuyerVendorOrder);
router.put('/admin/orders/:id', authMiddleware as RequestHandler, hasRole('ADMIN'), updateBuyerVendorOrder);
router.post('/payment/:id', authMiddleware as RequestHandler, hasRole('BUYER'), Payment);

//all transaction

export default router;
6 changes: 3 additions & 3 deletions src/services/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ export * from './userServices/userResendOTP';
export * from './userServices/logoutServices';
export * from './userServices/userProfileUpdateServices';


// Vendor product services
export * from './productServices/createProduct';
export * from './productServices/updateProduct';
Expand All @@ -23,6 +22,7 @@ export * from './productServices/productStatus';
export * from './productServices/viewSingleProduct';
export * from './productServices/searchProduct';
export * from './productServices/payment';
export * from './productServices/Transctions';
export * from './productServices/getCategories';

// Buyer wishlist services
Expand Down Expand Up @@ -50,5 +50,5 @@ export * from './notificationServices/getNotifications';
export * from './notificationServices/deleteNotification';
export * from './notificationServices/updateNotification';

// chatbot
export * from './chatbotServices/chatBot';
// chatbot
export * from './chatbotServices/chatBot';
Loading
Loading
You are viewing a condensed version of this merge commit. You can view the full changes here.