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

feat : product recommendations using user last product data #263

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
30 changes: 30 additions & 0 deletions client/app/ProductRecommendations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchRecommendations } from '../../actions/product';
import ProductCard from '../components/ProductCard';

const ProductRecommendations = () => {
const dispatch = useDispatch();
const recommendations = useSelector(state => state.product.recommendations);

useEffect(() => {
dispatch(fetchRecommendations());
}, [dispatch]);

if (recommendations.length === 0) {
return null;
}

return (
<div className="product-recommendations">
<h2>Recommended Products</h2>
<div className="products-grid">
{recommendations.map(product => (
<ProductCard key={product._id} product={product} />
))}
</div>
</div>
);
};

export default ProductRecommendations;
13 changes: 13 additions & 0 deletions client/app/components/Common/product.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import axios from 'axios';
import { FETCH_RECOMMENDATIONS } from '../../constants';

export const fetchRecommendations = () => {
return async (dispatch, getState) => {
try {
const response = await axios.get('/api/product/recommendations');
dispatch({ type: FETCH_RECOMMENDATIONS, payload: response.data.recommendations });
} catch (error) {
console.log('Error fetching recommendations:', error);
}
};
};
68 changes: 68 additions & 0 deletions server/controller/product_controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
const Product = require('../models/product');
const RecentlyViewed = require('../models/recentlyViewed');


exports.getProduct = async (req, res) => {
try {
const productId = req.params.id;
const userId = req.user._id; // Assuming you have user authentication middleware

const product = await Product.findById(productId);

if (!product) {
return res.status(404).json({
message: 'No product found.'
});
}

// Record this product view
await RecentlyViewed.findOneAndUpdate(
{ user: userId, product: productId },
{ $set: { viewedAt: new Date() } },
{ upsert: true, new: true }
);

res.status(200).json({
product
});
} catch (error) {
res.status(400).json({
error: 'Your request could not be processed. Please try again.'
});
}
};

exports.getRecommendations = async (req, res) => {
try {
const userId = req.user._id; // Assuming you have user authentication middleware

// Get the user's recently viewed products
const recentlyViewed = await RecentlyViewed.find({ user: userId })
.sort('-viewedAt')
.limit(5)
.populate('product');

// Extract categories and brands from recently viewed products
const categories = recentlyViewed.map(rv => rv.product.category);
const brands = recentlyViewed.map(rv => rv.product.brand);

// Find similar products
const recommendations = await Product.find({
$or: [
{ category: { $in: categories } },
{ brand: { $in: brands } }
],
_id: { $nin: recentlyViewed.map(rv => rv.product._id) } // Exclude already viewed products
})
.limit(10)
.populate('brand');

res.status(200).json({
recommendations
});
} catch (error) {
res.status(400).json({
error: 'Your request could not be processed. Please try again.'
});
}
};
24 changes: 24 additions & 0 deletions server/models/recentlyViewed.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const RecentlyViewedSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
product: {
type: Schema.Types.ObjectId,
ref: 'Product',
required: true
},
viewedAt: {
type: Date,
default: Date.now
}
});

// Compound index to ensure a user can only have one entry per product
RecentlyViewedSchema.index({ user: 1, product: 1 }, { unique: true });

module.exports = mongoose.model('RecentlyViewed', RecentlyViewedSchema);
24 changes: 24 additions & 0 deletions server/reducer/product.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import {
FETCH_PRODUCTS,
FETCH_PRODUCT,
FETCH_RECOMMENDATIONS,
// ... other imports ...
} from '../actions/constants';

const initialState = {
products: [],
product: {},
recommendations: [],
};

export default function (state = initialState, action) {
switch (action.type) {
case FETCH_RECOMMENDATIONS:
return {
...state,
recommendations: action.payload
};
default:
return state;
}
}
4 changes: 4 additions & 0 deletions server/routes/api/product.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ const express = require('express');
const router = express.Router();
const multer = require('multer');
const Mongoose = require('mongoose');
const Product = require('../../models/product');
const RecentlyViewed = require('../../models/recentlyViewed');
const productController = require('../../controllers/product_controller');
const auth = require('../../middleware/auth');

// Bring in Models & Utils
const Product = require('../../models/product');
Expand Down