Skip to content

Commit

Permalink
rebase from update profile (#87)
Browse files Browse the repository at this point in the history
Co-authored-by: IRADUKUNDA SANGWA CEDRIC <110623461+Dawaic6@users.noreply.github.com>

user should make chat with chatbot
  • Loading branch information
ambroisegithub committed May 28, 2024
1 parent 4232bbb commit dcdf53a
Show file tree
Hide file tree
Showing 9 changed files with 125 additions and 34 deletions.
26 changes: 26 additions & 0 deletions src/controller/chatbotController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Request, Response } from 'express';
import * as chatbotService from '../service/chatbotService';
import errorHandler from '../middlewares/errorHandler';

export const getChatResponse = errorHandler(
async (
req: Request,
res: Response
): Promise<Response<Record<string, unknown>> | undefined> => {
const { message } = req.body;
const userId = req.user?.id;
const response = await chatbotService.processMessage(userId, message);
return res.status(200).json({ message: response });
}
);

export const getChatHistory = errorHandler(
async (
req: Request,
res: Response
): Promise<Response<Record<string, unknown>> | undefined> => {
const userId = req.user?.id;
const history = await chatbotService.getChatHistory(userId);
return res.status(200).json({ history });
}
);
29 changes: 14 additions & 15 deletions src/controller/productController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,6 @@ import { check, validationResult } from 'express-validator';
import errorHandler from '../middlewares/errorHandler';
import productQuantityWatch from '../middlewares/productAvailabilityWatch';




const userRepository = dbConnection.getRepository(UserModel);
const productRepository = dbConnection.getRepository(Product);

Expand Down Expand Up @@ -70,7 +67,7 @@ export const createProduct = [
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}

const vendorId = req.user!.id;

const {
Expand Down Expand Up @@ -366,17 +363,21 @@ export const AvailableProducts = errorHandler(
message: 'Items retrieved successfully.',
availableProducts,
totalPages: Math.ceil(totalCount / limit),
currentPage: page
});
})
currentPage: page,
});
}
);

// From Bernard #38

export const updateProductAvailability = async (req: Request, res: Response) => {
export const updateProductAvailability = async (
req: Request,
res: Response
) => {
const { productId } = req.params;
const { availability } = req.body;
const user = await userRepository.findOne({
where: { id: (req.user as User).id},
where: { id: (req.user as User).id },
});

if (!user) {
Expand All @@ -385,7 +386,7 @@ export const updateProductAvailability = async (req: Request, res: Response) =>

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

if (!product) {
Expand All @@ -402,18 +403,16 @@ export const updateProductAvailability = async (req: Request, res: Response) =>
res.json({ msg: 'Product availability updated' });
};


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

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


const user = await userRepository.findOne({
where: { id: (req.user as User).id},
where: { id: (req.user as User).id },
});

if (!user) {
Expand All @@ -423,7 +422,7 @@ export const checkProductAvailability = async (req: Request, res: Response) => {
if (!product) {
return res.status(404).json({ msg: 'Product not found' });
}
if (product.vendor.id!== user.id) {
if (product.vendor.id !== user.id) {
return res.status(403).json({ msg: 'Product not owned by vendor' });
}

Expand Down
20 changes: 20 additions & 0 deletions src/database/models/chatbotModel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Entity,PrimaryGeneratedColumn,Column,ManyToOne,CreateDateColumn } from 'typeorm';
import User from './userModel';

@Entity()
export default class chat{
@PrimaryGeneratedColumn()
id:number;

@ManyToOne(()=>User)
user: User;

@Column()
message:string;

@Column()
response:string;

@CreateDateColumn()
createdAt:Date;
}
1 change: 1 addition & 0 deletions src/middlewares/errorHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ function errorHandler(func: MiddlewareFunction): MiddlewareFunction {
try {
return await func(req, res);
} catch (error) {
// console.log({'Error':error})
const message =
(error as { detail?: string }).detail || 'Internal Server Error';
return res.status(500).send(message);
Expand Down
11 changes: 11 additions & 0 deletions src/routes/chatbotRoutes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Router } from 'express';
import { getChatResponse, getChatHistory } from '../controller/chatbotController';
import { IsLoggedIn } from '../middlewares/isLoggedIn';
import { checkRole } from '../middlewares/authorize';

const router = Router();

router.post('/chat', IsLoggedIn,checkRole(['Buyer']), getChatResponse);
router.get('/chat/history', IsLoggedIn,checkRole(['Buyer']), getChatHistory);

export default router;
2 changes: 2 additions & 0 deletions src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import buyerRoutes from './buyerRoutes';
import cartRoutes from '../routes/cartRoutes';
import couponRouter from './couponRoute';
import chekoutRoutes from './checkoutRoutes';
import chatRoutes from './chatbotRoutes';
const router = Router();

router.use('/user', userRouter);
Expand All @@ -17,5 +18,6 @@ router.use('/buyer', buyerRoutes);
router.use('/cart', cartRoutes);
router.use('/coupons', couponRouter);
router.use('/checkout', chekoutRoutes);
router.use('/', chatRoutes);

export default router;
32 changes: 32 additions & 0 deletions src/service/chatbotService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import Chat from '../database/models/chatbotModel';
import User from '../database/models/userModel';
import dbConnection from '../database';
import { analyzeMessege, generateResponse } from '../utilis/nlp';

export const processMessage = async (userId: number, message: string): Promise<string> => {
const userRepo = dbConnection.getRepository(User);
const chatRepo = dbConnection.getRepository(Chat);

const user = await userRepo.findOne({
where:{ id:userId }
});
if (!user) {
throw new Error('User not found');
}

const analyzedMessage = analyzeMessege(message);
const response = await generateResponse(analyzedMessage);

const chat = new Chat();
chat.user = user;
chat.message = message;
chat.response = response;
await chatRepo.save(chat);

return response;
};

export const getChatHistory = async (userId: number): Promise<Chat[]> => {
const chatRepo = dbConnection.getRepository(Chat);
return chatRepo.find({ where: { user: { id: userId } }, order: { createdAt: 'DESC' } });
};
19 changes: 19 additions & 0 deletions src/utilis/nlp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export const analyzeMessege = (message: string): string => {
return message.toLowerCase()
};

export const generateResponse= async(message:string):Promise<string>=>{
if (message.includes('product')) {
return 'We sell various products such as electronics, clothing, and home appliances.';
}
if (message.includes('recommend')) {
return 'Based on your history, we recommend our latest smartphones and laptops.';
}
if (message.includes('delivery')) {
return 'Our delivery process usually takes 3-5 business days.';
}
if (message.includes('help')) {
return 'How can I assist you with navigating our platform or completing an order?';
}
return 'I am sorry, I did not understand that. Could you please rephrase?';
}
19 changes: 0 additions & 19 deletions src/utils/couponCalculator.ts

This file was deleted.

0 comments on commit dcdf53a

Please sign in to comment.