Skip to content

Commit

Permalink
resolving conflict
Browse files Browse the repository at this point in the history
  • Loading branch information
Ndevu12 committed Jun 3, 2024
2 parents 5553358 + 85e590e commit cede14b
Show file tree
Hide file tree
Showing 10 changed files with 222 additions and 10 deletions.
10 changes: 9 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,15 @@ env:
GOOGLE_CLIENT_SECRET: ${{secrets.GOOGLE_CLIENT_SECRET}}

STRIPE_SECRET_KEY: ${{secrets.STRIPE_SECRET_KEYT}}


TEST_USER_EMAIL: ${{secrets.TEST_USER_EMAIL}}
TEST_USER_PASS: ${{secrets.TEST_USER_PASS}}
TEST_VENDOR_EMAIL: ${{secrets.TEST_VENDOR_EMAIL}}
TEST_VENDOR1_EMAIL: ${{secrets.TEST_VENDOR1_EMAIL}}
TEST_BUYER_EMAIL: ${{secrets.TEST_BUYER_EMAIL}}
TEST_SAMPLE_BUYER_EMAIL: ${{secrets.TEST_SAMPLE_BUYER_EMAIL}}
TEST_VENDOR2_EMAIL: ${{secrets.TEST_VENDOR2_EMAIL}}

jobs:
build-lint-test-coverage:
runs-on: ubuntu-latest
Expand Down
202 changes: 202 additions & 0 deletions src/__test__/adminDeleteFeedBack.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
import request from 'supertest';
import { app, server } from '../index';
import { dbConnection } from '../startups/dbConnection';
import { getRepository } from 'typeorm';
import { Feedback } from '../entities/Feedback';
import { v4 as uuid } from 'uuid';
import { User, UserInterface } from '../entities/User';
import { Product } from '../entities/Product';
import { Order } from '../entities/Order';
import { Category } from '../entities/Category';
import jwt from 'jsonwebtoken';
import { cleanDatabase } from './test-assets/DatabaseCleanup';

const vendorId = uuid();
const productId = uuid();
const buyerId = uuid();
const orderId = uuid();
const adminId = uuid();
const feedbackId1 = uuid();
const feedbackId2 = uuid();
const invalidFeedbackId = '11278df2-d026-457a-9471-4749f038df68';

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

const getAccessToken = (id: string, email: string) => {

Check warning on line 25 in src/__test__/adminDeleteFeedBack.test.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Missing return type on function

Check warning on line 25 in src/__test__/adminDeleteFeedBack.test.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Missing return type on function

Check warning on line 25 in src/__test__/adminDeleteFeedBack.test.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Missing return type on function

Check warning on line 25 in src/__test__/adminDeleteFeedBack.test.ts

View workflow job for this annotation

GitHub Actions / build-lint-test-coverage

Missing return type on function
return jwt.sign(
{
id: id,
email: email,
},
jwtSecretKey
);
};

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

const sampleAdmin: UserInterface = {
id: adminId,
firstName: 'admin',
lastName: 'user',
email:process.env.TEST_USER_EMAIL,
password: process.env.TEST_USER_PASS,
userType: 'Admin',
gender: 'Male',
phoneNumber: '126380997',
photoUrl: 'https://example.com/photo.jpg',
verified: true,
role: 'ADMIN',
};

const sampleVendor: UserInterface = {
id: vendorId,
firstName: 'vendor',
lastName: 'user',
email:process.env.TEST_VENDOR_EMAIL,
password: process.env.TEST_USER_PASS,
userType: 'Vendor',
gender: 'Male',
phoneNumber: '126380996347',
photoUrl: 'https://example.com/photo.jpg',
verified: true,
role: 'VENDOR',
};

const sampleBuyer: UserInterface = {
id: buyerId,
firstName: 'buyer',
lastName: 'user',
email: process.env.TEST_BUYER_EMAIL,
password: process.env.TEST_USER_PASS,
userType: 'Buyer',
gender: 'Male',
phoneNumber: '6380996347',
photoUrl: 'https://example.com/photo.jpg',
verified: true,
role: 'BUYER',
};

const sampleCat = {
id: uuid(),
name: 'accessories',
};

const sampleProduct = {
id: productId,
name: 'test product',
description: 'amazing product',
images: ['photo1.jpg', 'photo2.jpg', 'photo3.jpg'],
newPrice: 200,
quantity: 10,
vendor: sampleVendor,
categories: [sampleCat],
};

const sampleOrder = {
id: orderId,
totalPrice: 400,
quantity: 2,
orderDate: new Date(),
buyer: sampleBuyer,
orderStatus: 'received',
address: 'Rwanda, Kigali, KK20st',
};
const sampleFeedback1 = {
id: feedbackId1,
user: sampleBuyer as User,
product: sampleProduct as Product,
rating: 4,
order: sampleOrder as Order,
comment: 'Great product!',
};

const sampleFeedback2 = {
id: feedbackId2,
user: sampleBuyer as User,
product: sampleProduct as Product,
order: sampleOrder as Order,
rating: 2,
comment: 'Not satisfied.',
};

beforeAll(async () => {
const connection = await dbConnection();

const categoryRepository = connection?.getRepository(Category);
await categoryRepository?.save(sampleCat);

const userRepository = connection?.getRepository(User);
await userRepository?.save([sampleAdmin, sampleVendor, sampleBuyer]);

const productRepository = connection?.getRepository(Product);
await productRepository?.save(sampleProduct);

const orderRepository = connection?.getRepository(Order);
await orderRepository?.save(sampleOrder);

const feedbackRepository = connection?.getRepository(Feedback);
await feedbackRepository?.save({ ...sampleFeedback1 });
await feedbackRepository?.save({ ...sampleFeedback2 });
});

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

describe('/DELETE admin Delete Feedback Service', () => {
it('should successfully delete a feedback', async () => {
const response = await request(app)
.delete(`/feedback/admin/delete/${feedbackId1}`)
.set('Authorization', `Bearer ${getAccessToken(adminId, sampleAdmin.email)}`)
.send();
expect(response.status).toBe(200);

const feedbackRepository = getRepository(Feedback);
const feedback = await feedbackRepository.findOne({ where: { id: feedbackId1 } });
expect(feedback).toBeNull();
});

it('should return 404 if feedback not found', async () => {
const response = await request(app)
.delete(`/feedback/admin/delete/${invalidFeedbackId}`)
.set('Authorization', `Bearer ${getAccessToken(adminId, sampleAdmin.email)}`)
.send();
expect(response.status).toBe(404);
expect(response.body.message).toBe('Feedback not found');
});

it('should handle server errors', async () => {
const response = await request(app)
.delete(`/feedback/admin/delete/123`)
.set('Authorization', `Bearer ${getAccessToken(adminId, sampleAdmin.email)}`)
.send();
expect(response.status).toBe(500);
});
});

describe('/DELETE Access controll on Admin deleting feedback route.', () => {
it('should return 403 if user is not an admin', async () => {
const response = await request(app)
.delete(`/feedback/admin/delete/${feedbackId2}`)
.set('Authorization', `Bearer ${getAccessToken(vendorId, sampleVendor.email)}`)
.send();
expect(response.status).toBe(403);
expect(response.body.message).toBe('Unauthorized action');
});

it('should return 404 if user is not found', async () => {
const response = await request(app)
.delete(`/feedback/admin/delete/${feedbackId2}`)
.set('Authorization', `Bearer ${getAccessToken(invalidFeedbackId, sampleBuyer.email)}`)
.send();
expect(response.status).toBe(403);
});

it('should return 403 if user is not authenticated', async () => {
const response = await request(app)
.delete(`/feedback/admin/delete/${feedbackId2}`)
.send();
expect(response.status).toBe(401);
});
});
3 changes: 2 additions & 1 deletion src/__test__/test-assets/DatabaseCleanup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,5 @@ export const cleanDatabase = async () => {
// console.log('Database cleaned');
// }).catch(error => {
// console.error('Error cleaning database:', error);
// });

// });
2 changes: 1 addition & 1 deletion src/__test__/vendorProduct.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ describe('Vendor product management tests', () => {

expect(response.status).toBe(201);
expect(response.body.data.product).toBeDefined;
}, 120000);
}, 60000);

it('return an error if the number of product images exceeds 6', async () => {
const response = await request(app)
Expand Down
4 changes: 2 additions & 2 deletions src/routes/ProductRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,6 @@ router.put('/vendor/orders/:id', authMiddleware as RequestHandler, hasRole('VEND
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)
router.post('/payment/:id', authMiddleware as RequestHandler, hasRole('BUYER'), Payment);

export default router;
export default router;
3 changes: 2 additions & 1 deletion src/services/orderServices/updateOrderService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,5 @@ async function processRefund (order: Order, entityManager: EntityManager) {

function isOrderFinalStatus (status: string): boolean {
return ['cancelled', 'delivered', 'returned', 'completed'].includes(status);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,4 @@ export const getRecommendedProductsService = async (req: Request, res: Response)
} catch (error) {
return responseError(res, 400, (error as Error).message);
}
};
};
2 changes: 1 addition & 1 deletion src/services/productServices/listAllProductsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,4 @@ export const listAllProductsService = async (req: Request, res: Response) => {
} catch (error) {
responseError(res, 400, (error as Error).message);
}
};
};
2 changes: 1 addition & 1 deletion src/services/productServices/readProduct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,4 @@ export const readProductService = async (req: Request, res: Response) => {
} catch (error) {
responseError(res, 400, (error as Error).message);
}
};
};
2 changes: 1 addition & 1 deletion src/services/productServices/viewSingleProduct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,4 @@ export const viewSingleProduct = async (req: Request, res: Response) => {
console.error('Error handling request:', error);
res.status(500).send('Error fetching product details');
}
};
};

0 comments on commit cede14b

Please sign in to comment.