Skip to content

Commit

Permalink
Merge pull request #161 from agiledev-students-spring2024/compat
Browse files Browse the repository at this point in the history
Compat
  • Loading branch information
ShadowCat567 authored Apr 28, 2024
2 parents 1148e31 + a469ddc commit 4deb62d
Show file tree
Hide file tree
Showing 13 changed files with 1,353 additions and 149 deletions.
162 changes: 143 additions & 19 deletions back-end/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,8 @@ const sessionOptions = {
app.use(session(sessionOptions));

app.use(function (req, res, next) {
console.log(req.session.user);
req.session.user = req.session.user || "a";
req.session.matches = req.session.matches || [];
//console.log(req.session)
req.session.otheruser = req.session.otheruser || "";
console.log("otheruser:", req.session.otheruser);
next();
});

Expand Down Expand Up @@ -139,10 +137,6 @@ app.post('/login', async (req, res) => {
}
});





app.get('/register', (req, res) => {
})

Expand Down Expand Up @@ -176,16 +170,12 @@ app.post('/register', async (req, res) => {
}
});




//expecting json object with handle sumbit attruputes -- in Survey.js
//should push to surveyData arr
app.post('/survey', (req, res) => {
const surveyData = req.body;
//console.log('Backend has received new survey data:', surveyData);//We should see a message on the backend console with the data that was sent


profiledict = { name: surveyData.name, year: surveyData.year, bio: "" }
answersdict = {
gender: surveyData.genderAns, year: surveyData.year, pets: surveyData.petsAns,
Expand Down Expand Up @@ -214,28 +204,110 @@ app.post('/survey', (req, res) => {
});
});

app.get('/matches', async (req, res) => {
//console.log('matches:', req.session.user)
req.session.user = req.session.user || "randomname";
app.get('/matches', authenticateToken, async (req, res) => {
try {
User.find()
.then(foundUser => {
//jsonArray.push(foundUser);
res.json(foundUser)
if (!foundUser) return res.status(404).json({ message: "User not found" });

const foundOtherUser = [];
const matches = [];
var thisUser = new User({});

for (const user of foundUser) {
if (user._id && req.user.id) {
if (String(user._id) === req.user.id) {
//console.log(user.username);
thisUser = user;
}
else {
foundOtherUser.push(user);
}
}
}
keys = compat.createMatches(thisUser, foundOtherUser);
//console.log(keys);

for (const key of keys) {
for (const user of foundUser) {
if (user.username === key) {
matches.push(user);
}
}
}

res.json(matches);
})
.catch(err => {
console.log(err);
res.status(500).send('server error');
});
} catch (err) {
console.log(err);
}
});

//res.json(jsonArray)//Now, send the array to the front end
app.post('/matches', authenticateToken, async (req, res) => {
const username = req.body.username;
req.session.otheruser = username;
//console.log('the clicked user is', username)

try {
const user = await User.findById(req.user.id);
if (!user) {
console.error('User not found');
return res.status(404).json({ message: 'User not found.' });
}
res.json({ message: 'Profile updated successfully.' });
} catch (err) {
console.error("Error during profile update:", err);
res.status(500).json({ message: 'Internal server error', error: err.message });
}
});

app.get('/otheruser', authenticateToken, (req, res) => {
try {
User.find()
.then(foundUser => {
if (!foundUser) return res.status(404).json({ message: "User not found" });

for (const user of foundUser) {
if(user.username === req.session.otheruser) {
res.json(user);
}
}
})
.catch(err => {
console.log(err);
res.status(500).send('server error');
});
} catch (err) {
console.log(err);
}
});

app.get('/useranswers', authenticateToken, (req, res) => {
console.log('in user answers', req.session.otheruser)
try {
User.find()
.then(foundUser => {
if (!foundUser) return res.status(404).json({ message: "User not found" });
for (const user of foundUser) {
if(user.username === req.session.otheruser) {
res.json(user);
}
}
})
.catch(err => {
console.log(err);
res.status(500).send('server error');
});
} catch (err) {
console.log(err);
}
});


//returns a bunch of json objects as an array
app.get('/chatlist', authenticateToken, async (req, res) => {
try {
Expand Down Expand Up @@ -401,8 +473,60 @@ app.get('/profile', authenticateToken, (req, res) => {
});
});

app.get('/retake', authenticateToken, async(req, res) => {
User.findById(req.user.id, 'profile.name answers.gender answers.year answers.pets ' +
'answers.guests answers.smoke answers.drink ' +
'answers.rent_max answers.rent_min ' +
'answers.bedtime answers.quietness answers.cleanliness ' +
'preferences.gender preferences.year preferences.pets ' +
'preferences.guests preferences.smoke preferences.drink ' +
'preferences.bedtime preferences.quietness preferences.cleanliness')
.then(user => {
if (!user) return res.status(404).json({ message: "User not found" });
res.json(user);
})
.catch(err => {
console.error(err);
res.status(500).json({ message: "Internal server error" });
});
});

app.get('/mypreferences', (req, res) => {
app.post('/retake', authenticateToken, async(req, res) => {
console.log("Received update request for user:", req.user.id);
console.log("Request data:", req.body);

try {
const user = await User.findById(req.user.id);
if (!user) {
console.error('User not found');
return res.status(404).json({ message: 'User not found.' });
}

const surveyData = req.body;

profiledict = { name: surveyData.name, year: surveyData.year, bio: "" }
answersdict = {
gender: surveyData.genderAns, year: surveyData.year, pets: surveyData.petsAns,
guests: surveyData.guestsAns, smoke: surveyData.smokeAns, drink: surveyData.drinkAns,
rent_max: surveyData.maxRent, rent_min: surveyData.minRent,
bedtime: surveyData.bedAns, quietness: surveyData.quietAns, cleanliness: surveyData.cleanAns
}
preferencesdict = {
gender: surveyData.genderPref, year: surveyData.yearPref, pets: surveyData.petsPref,
guests: surveyData.guestsPref, smoke: surveyData.smokePref, drink: surveyData.drinkPref,
bedtime: surveyData.bedPref, quietness: surveyData.quietPref, cleanliness: surveyData.cleanPref
}
user.profile = profiledict;
user.answers = answersdict;
user.preferences = preferencesdict;

await user.save();
console.log('User updated: ', user);
res.json({message: 'Survey updated successfully'});
} catch (err) {
console.error("Error during survey retake update:", err);
res.status(500).json({ message: 'Internal server error', error: err.message });
}
});

app.post('/editprofile', authenticateToken, async (req, res) => {
Expand Down
2 changes: 1 addition & 1 deletion back-end/Compatibility.js
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ function createMatches(arg1, [...args]) {

for (const arg of args) {
if (match(arg1, arg) !== -1) {
matchList[arg.login.username] = match(arg1, arg);
matchList[arg.username] = match(arg1, arg);
}
}

Expand Down
8 changes: 4 additions & 4 deletions front-end/package-lock.json

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

6 changes: 4 additions & 2 deletions front-end/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ import Matches from './Matches';
import Survey from './Survey';
import Profile from './Profile'
import EditProfile from './EditProfile';
import MyPreferences from './MyPreferences'
import Retake from './Retake'
import OtherProfile from './OtherProfile';
import UserAnswers from './UserAnswers';
import ProtectedRoute from './ProtectedRoute';
import axios from 'axios'

Expand All @@ -27,8 +28,9 @@ function App() {
<Route path="/survey" element={<ProtectedRoute><Survey /></ProtectedRoute>} />
<Route path="/profile" element={<ProtectedRoute><Profile /></ProtectedRoute>} />
<Route path="/editprofile" element={<ProtectedRoute><EditProfile /></ProtectedRoute>} />
<Route path="/mypreferences" element={<ProtectedRoute><MyPreferences /></ProtectedRoute>} />
<Route path="/retake" element={<ProtectedRoute><Retake /></ProtectedRoute>} />
<Route path="/otheruser" element={<ProtectedRoute><OtherProfile /></ProtectedRoute>} />
<Route path="/useranswers" element={<ProtectedRoute><UserAnswers /></ProtectedRoute>} />
{/* Redirect all other paths to "/login" */}
<Route path="*" element={<Navigate replace to="/login" />} />
</Routes>
Expand Down
56 changes: 41 additions & 15 deletions front-end/src/Matches.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,25 @@ const Matches = props => {
const [error, setError] = useState('')
const [feedback, setFeedback] = useState('')
const [matches, setMatches] = useState([]);
const [errorMessage, setErrorMessage] = useState("");

const fetchMatches = () => {
axios
.get('http://localhost:3001/matches')//, { withCredentials: true})
.then(response => {
const matchesData = response.data; //response is an array of JSON objects
setMatches(matchesData);
})
.catch(err => {
const errMsg = JSON.stringify(err, null, 2);
setError(errMsg);
})
.finally(() => {
setLoaded(true);
const fetchMatches = async() => {
try {
const response = await axios.get('http://localhost:3001/matches', {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`
}
});
console.log('Fetching profile data', response.data);
if (response.data) {
setMatches(response.data);
} else {
throw new Error('Matches data is missing');
}
} catch (error) {
console.error('Error fetching matches data:', error);
setError('Error fetching matches data: ' + error.message);
}
};

useEffect(() => {
Expand All @@ -46,15 +50,37 @@ const Matches = props => {
}
}, []) // putting a blank array as second argument will cause this function to run only once when component first loads

const handleClick = async (match) => {
console.log("Sending data of user: ", match.username);

try {
const response = await axios.post('http://localhost:3001/matches', match, {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}` // Include the JWT token in the request
}
});
console.log("Update response:", response.data);
if (response.status === 200) {
console.log("Match info sent successfully");
navigate('/otheruser', { state: { updated: true } }); // Pass state to trigger re-fetch
}
} catch (error) {
console.error("Update error:", error);
const message = error.response?.data?.message || "An error occurred while updating the profile.";
setErrorMessage(message);
}
};

//() => navigate('/otheruser')

return (
<>
<div className="MatchList">
<Header />
{error && <h1>{error}</h1>} {/* To fix allignment I made error only show up if it is defined*/}
{matches.map((match, index) => (
<div key={index}>

<button onClick={() => navigate('/otheruser')} className="rowbutton">
<button onClick={() => handleClick(match)} className="rowbutton">
<img src={profilepic} className="profilepic_match" alt="profilepic" />
<ul className="matchentry">
<li className="username_match">{match.profile.name}</li>
Expand Down
Loading

0 comments on commit 4deb62d

Please sign in to comment.