Skip to content

Commit 563ceb5

Browse files
committed
2 parents 31c3f7c + e9f4627 commit 563ceb5

File tree

7 files changed

+167
-32
lines changed

7 files changed

+167
-32
lines changed

Backend/HistoryService/controllers/histories.js

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,30 @@ const HistoryModel = require('../models/Histories');
1616
// }
1717
// });
1818

19-
// Assuming Express.js
19+
// error at populate
2020
historyRouter.get('/user/:userId', async (req, res) => {
2121
const { userId } = req.params;
2222
try {
23-
const attempts = await HistoryModel.find({ user: userId }); // Fetch by user object ID
24-
res.json(attempts);
23+
console.log('Attempting to fetch history for user:', userId);
24+
const attempts = await HistoryModel.find({ user: userId })
25+
.populate({
26+
path: 'matchedUser',
27+
select: '_id username'
28+
})
29+
.populate({
30+
path: 'question',
31+
select: '_id title'
32+
});
33+
34+
console.log('Successfully fetched', attempts.length, 'attempts');
35+
res.json(attempts);
2536
} catch (error) {
26-
res.status(500).json({ error: 'Failed to fetch attempt history' });
37+
console.error('Error fetching attempt history:', error);
38+
res.status(500).json({ error: 'Failed to fetch attempt history', details: error.message });
2739
}
28-
});
40+
});
41+
42+
2943

3044

3145
// // Post a new history entry when a user exits a session
@@ -48,14 +62,16 @@ historyRouter.get('/user/:userId', async (req, res) => {
4862
// }
4963
// });
5064

65+
// POST route to create a new history entry
5166
historyRouter.post('/', async (req, res) => {
5267
try {
53-
const newSession = new HistoryModel(req.body);
54-
await newSession.save();
55-
res.status(201).json({ message: 'Session saved successfully' });
68+
const newHistory = new HistoryModel(req.body);
69+
const savedHistory = await newHistory.save();
70+
res.status(201).json(savedHistory);
5671
} catch (error) {
57-
res.status(500).json({ error: 'Failed to save session data' });
72+
console.error('Error creating history entry:', error);
73+
res.status(500).json({ error: 'Failed to create history entry' });
5874
}
59-
});
75+
});
6076

6177
module.exports = historyRouter;

Backend/HistoryService/models/Histories.js

Lines changed: 75 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,72 @@
1-
const mongoose = require('mongoose');
1+
// const mongoose = require('mongoose');
2+
// const User = require('../../user-service/model/user-model');
3+
// const Question = require('../../user-service/model/Questions');
24

3-
const HistorySchema = new mongoose.Schema({
5+
6+
// mongoose.model('User', User.schema);
7+
// mongoose.model('Question', Question.schema);
8+
9+
10+
// const HistorySchema = new mongoose.Schema({
11+
// user: {
12+
// type: mongoose.Schema.Types.ObjectId,
13+
// ref: 'User',
14+
// required: true // The user for whom this history entry is being created
15+
// },
16+
// matchedUser: {
17+
// type: mongoose.Schema.Types.ObjectId,
18+
// ref: 'User',
19+
// required: true // The other user they were matched with
20+
// },
21+
// question: {
22+
// type: mongoose.Schema.Types.ObjectId, // Reference to the Question model
23+
// ref: 'Question',
24+
// required: true
25+
// },
26+
// datetime: {
27+
// type: Date, // Time when the session started
28+
// default: Date.now
29+
// },
30+
// duration: {
31+
// type: Number, // Duration in minutes for the individual user
32+
// required: true
33+
// },
34+
// code: {
35+
// type: Number, // Store the code as binary file
36+
// required: true
37+
// }
38+
// });
39+
40+
// // HistorySchema.virtual('matchedUserName').get(function() {
41+
// // return this.matchedUser.username;
42+
// // });
43+
44+
// // HistorySchema.virtual('questionTitle').get(function() {
45+
// // return this.question.title;
46+
// // });
47+
48+
// // Create the History model
49+
// const HistoryModel = mongoose.model('History', HistorySchema, 'Histories');
50+
// module.exports = HistoryModel;
51+
52+
53+
const mongoose = require("mongoose");
54+
const Schema = mongoose.Schema;
55+
56+
async function getUserModel() {
57+
return await import('../../user-service/model/user-model');
58+
}
59+
60+
async function init() {
61+
// const User = await import('../../user-service/model/user-model');
62+
const UserModel = await getUserModel();
63+
const Question = await import('../../user-service/model/Questions');
64+
65+
mongoose.model('User', User.default.schema);
66+
mongoose.model('Question', Question.default.schema);
67+
68+
69+
const HistorySchema = new mongoose.Schema({
470
user: {
571
type: mongoose.Schema.Types.ObjectId,
672
ref: 'User',
@@ -25,11 +91,14 @@ const HistorySchema = new mongoose.Schema({
2591
required: true
2692
},
2793
code: {
28-
type: Buffer, // Store the code as binary file
94+
type: Number, // Store the code as binary file
2995
required: true
3096
}
3197
});
3298

33-
// Create the History model
34-
const HistoryModel = mongoose.model('History', HistorySchema, 'History');
35-
module.exports = HistoryModel;
99+
const HistoryModel = mongoose.model('History', HistorySchema);
100+
101+
module.exports = HistoryModel;
102+
}
103+
104+
init().catch(console.error);

Frontend/src/components/user/HistoryAttempt.jsx

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,21 @@ import React from 'react';
33

44
const HistoryAttempt = ({ attempt }) => {
55
const { matchedUser, question, startTime, duration, codeFile } = attempt;
6-
6+
console.log(`matchedUser: ${matchedUser}`)
77
return (
8-
<div className="history-attempt">
9-
<h3>Attempt with {matchedUser}</h3>
10-
<p>Question: {question.title}</p>
11-
<p>Start Time: {new Date(startTime).toLocaleString()}</p>
12-
<p>Duration: {duration} minutes</p>
13-
<button onClick={() => downloadCode(codeFile)}>Download Code</button>
14-
</div>
8+
<tr>
9+
<td>{matchedUser.username}</td>
10+
<td>{question.title}</td>
11+
<td>{new Date(startTime).toLocaleString()}</td>
12+
<td>{duration} minutes</td>
13+
{/* <td>
14+
{/* <button onClick={() => downloadCode(codeFile)} className="btn btn-sm btn-primary">
15+
Download Code
16+
</button> }
17+
</td>*/}
18+
<td>{codeFile} dummy file content</td>
19+
20+
</tr>
1521
);
1622
};
1723

Frontend/src/components/user/HistoryPage.jsx

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,13 @@ import HistoryTable from './HistoryTable';
44
import ProfileSidebar from './ProfileSidebar';
55
import { getUserFromToken } from "./utils/authUtils";
66

7+
8+
// change the model: include qn title and matched user's name, and the time the session is started
9+
// session starttime: maybe look at websocket level
10+
// when session is started, extract question title (and description)
11+
// when ending session, save the info. need to avoid duplicate based on user id, matched user and start time
12+
13+
714
function HistoryPage() {
815
const [userID, setUserID] = useState(null);
916

Frontend/src/components/user/HistoryTable.jsx

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,15 +54,16 @@ const HistoryTable = ({userID}) => {
5454
try {
5555
if (userID) {
5656
const result = await historyService.getHistoryByUserId(userID);
57+
console.log('Received history data:', result.data);
5758
setHistory(result.data);
5859
console.log(`I have gotten the user id in table: ${userID}`)
5960
}
6061
} catch (error) {
61-
console.error('Error fetching attempt history:', error);
62+
console.error('Error fetching attempt history:', error.response?.data || error.message);
6263
}
6364
}
6465
fetchData();
65-
}, []);
66+
}, [userID]);
6667

6768
return (
6869
<div className="history-table">

Frontend/src/components/user/ProfileSidebar.jsx

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,39 @@
11
// ProfileSidebar.js
22
import React from 'react';
33
import { Link } from 'react-router-dom';
4+
import historyService from '../../services/history';
45

56
const ProfileSidebar = ({ userID }) => {
7+
8+
const handleAddHistory = async () => {
9+
try {
10+
// const codeInput = new TextEncoder().encode("Sample code input");
11+
12+
// Prepare the new history entry
13+
const newHistory = {
14+
user: userID,
15+
matchedUser: userID, // As per your request, both user and matchedUser are the user's own ID
16+
question: "66f63f8758ef3f359e17c18a", // Given question ID
17+
datetime: new Date(), // Current date and time
18+
duration: 3000, // Duration in seconds
19+
code: 1 // Arbitrary code input as a string converted to Buffer
20+
};
21+
22+
// Call the service to create a new history entry
23+
const response = await historyService.createHistory(newHistory);
24+
25+
// Check if the history entry was created successfully
26+
if (response.status === 201) {
27+
console.log("History entry added successfully:", response.data);
28+
} else {
29+
console.log("Error creating history entry:", response.statusText);
30+
}
31+
} catch (error) {
32+
console.error("Error creating history entry:", error);
33+
}
34+
};
35+
36+
637
return (
738
<div
839
className="profile-sidebar"
@@ -20,6 +51,9 @@ const ProfileSidebar = ({ userID }) => {
2051
<Link to={`/history/${userID}`}>
2152
<button className="btn btn-secondary">Attempt History</button>
2253
</Link>
54+
<button onClick={handleAddHistory} className="btn btn-success">
55+
Add History Entry
56+
</button>
2357
</div>
2458
);
2559
};

Frontend/src/services/history.js

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,12 @@ const getHistoryByUserId = (userId) => {
77
return axios.get(`${baseUrl}/user/${userId}`);
88
};
99

10-
// Sample function to add a new history attempt (optional)
11-
const createHistoryAttempt = async (newAttempt) => {
12-
const response = await axios.post(baseUrl, newAttempt);
13-
return response.data;
14-
};
10+
// Function to create a new history entry
11+
const createHistory = async (historyData) => {
12+
const response = await axios.post(baseUrl, historyData, {
13+
headers: { Authorization: `Bearer ${sessionStorage.getItem('jwt_token')}` },
14+
});
15+
return response;
16+
};
1517

16-
export default { getHistoryByUserId, createHistoryAttempt };
18+
export default { getHistoryByUserId, createHistory };

0 commit comments

Comments
 (0)