Skip to content

Commit

Permalink
Merge pull request #50 from BUMETCS673/hw105_dailydata_backend
Browse files Browse the repository at this point in the history
Hw105 dailydata backend
  • Loading branch information
abbiekuma authored Oct 4, 2024
2 parents 9af3ee1 + 2343d5b commit c2c9eb8
Show file tree
Hide file tree
Showing 5 changed files with 141 additions and 51 deletions.
2 changes: 1 addition & 1 deletion code/client/src/components/CreateGoal.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import {
InputLabel,
Select,
MenuItem,
Button
} from "@mui/material";
import { Button } from "@mui/material";
import {
box,
title,
Expand Down
123 changes: 75 additions & 48 deletions code/client/src/components/DailyData.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useState, useRef, useEffect } from "react";
import apiClient from "../services/apiClient.js";
import {
Box,
Typography,
Expand All @@ -8,6 +9,7 @@ import {
InputAdornment,
Collapse,
Paper,
Button
} from "@mui/material";
import { DayPicker } from "react-day-picker";
import "react-day-picker/dist/style.css";
Expand All @@ -26,40 +28,56 @@ import {
} from "./style/styles.js";

function DailyData() {
const [weight, setWeight] = useState("");
const [steps, setSteps] = useState("");
const [sleep, setSleep] = useState("");
const [mood, setMood] = useState(3);
const [exercise, setExercise] = useState("No");
const [exerciseType, setExerciseType] = useState("");
const [exerciseTime, setExerciseTime] = useState({
type: "",
exerciseTimeValue: 0,

const [formData, setFormData] = useState({
// entryDate: "",
weight: "",
steps: "",
sleep: "",
water: "",
exercise: ""
});
const [water, setWater] = useState("");
const [breakfast, setBreakfast] = useState("");
const [lunch, setLunch] = useState("");
const [dinner, setDinner] = useState("");

// Handle input changes and update formData state
const handleChange = (e) => {
const { name, value } = e.target;
setFormData((prevData) => ({
...prevData,
[name]: value,
}));
};

// const [mood, setMood] = useState(3);
// const [breakfast, setBreakfast] = useState("");
// const [lunch, setLunch] = useState("");
// const [dinner, setDinner] = useState("");

// date
const [date, setDate] = useState(null); //

const [anchorEl, setAnchorEl] = useState(null); // control Popper content
const [open, setOpen] = useState(false); // control Popper open/close

const handleDateChange = (selectedDate) => {
setDate(selectedDate);
setOpen(false); // close after chosing date
};

const handleTextFieldClick = (event) => {
setAnchorEl(event.currentTarget);
setOpen((prevOpen) => !prevOpen); // open/close calendar
};

const formatDate = (date) => {
return date ? date.toLocaleDateString("en-CA") : "";
};

const handleMoodChange = (event, newValue) => {
setMood(newValue);
};
// const handleMoodChange = (event, newValue) => {
// setMood(newValue);
// };

const calendarRef = useRef(null);

useEffect(() => {
function handleClickOutside(event) {
if (calendarRef.current && !calendarRef.current.contains(event.target)) {
Expand All @@ -78,15 +96,30 @@ function DailyData() {
};
}, [open]);

const handleSubmit = async (event) => {
event.preventDefault(); // Prevent default form submission behavior (e.g., page reload)

// Clear any existing messages before processing the form
// setSuccessMessage('');
// setErrorMessage('');

try {
await apiClient.post("/enter-daily-data", formData);
console.log("Daily entry processed")
// setSuccessMessage('Profile updated!');
} catch (err) {
console.log("Error submitting daily entry", err);
// setErrorMessage('Error: Failed to update profile. Please try again');
}
};

return (
<Box sx={box}>
<Typography variant="h6" gutterBottom sx={title}>
Enter your data here:
</Typography>

{/* <Typography variant="body1" gutterBottom sx={{ marginBottom: "2%" }}>
{date}
</Typography> */}
<form onSubmit={handleSubmit}>
<TextField
label="Select a date"
value={formatDate(date)}
Expand Down Expand Up @@ -121,8 +154,9 @@ function DailyData() {
label="Weight"
variant="filled"
fullWidth
value={weight}
onChange={(e) => setWeight(e.target.value)}
name="weight"
value={formData.weight}
onChange={handleChange}
InputProps={{
endAdornment: (
<InputAdornment position="end">
Expand All @@ -141,8 +175,9 @@ function DailyData() {
label="Count"
variant="filled"
fullWidth
value={steps}
onChange={(e) => setSteps(e.target.value)}
name="steps"
value={formData.steps}
onChange={handleChange}
InputProps={{
endAdornment: (
<InputAdornment position="end">
Expand All @@ -161,8 +196,9 @@ function DailyData() {
label="Sleep"
variant="filled"
fullWidth
value={sleep}
onChange={(e) => setSleep(e.target.value)}
name="sleep"
value={formData.sleep}
onChange={handleChange}
InputProps={{
endAdornment: (
<InputAdornment position="end">
Expand All @@ -182,8 +218,9 @@ function DailyData() {
label="Water"
variant="filled"
fullWidth
value={water}
onChange={(e) => setWater(e.target.value)}
name="water"
value={formData.water}
onChange={handleChange}
InputProps={{
endAdornment: (
<InputAdornment position="end">
Expand All @@ -203,15 +240,10 @@ function DailyData() {
<TextField
data-testid="exerciseTime"
type="number"
name="exerciseTime"
name="exercise"
label="How long did you exercise - min"
value={exerciseTime.exerciseTimeValue}
onChange={(e) =>
setExerciseTime({
...exerciseTime,
exerciseTimeValue: e.target.value,
})
}
value={formData.exercise}
onChange={handleChange}
required
InputLabelProps={{
sx: inputLable,
Expand All @@ -224,19 +256,6 @@ function DailyData() {
/>
</FormControl>
</Grid2>
{/* <InputLabel sx={inputLable}>How long did you exercise</InputLabel> */}
{/* <Select
value={exerciseTime}
onChange={(e) => setExerciseTime(e.target.value)}
label="How long did you exercise"
sx={inputBackground}
MenuProps={menuPropsStyles}
>
<MenuItem value="30 mins">30 mins</MenuItem>
<MenuItem value="1 hour">1 hour</MenuItem>
<MenuItem value="2 hours">2 hours</MenuItem>
</Select> */}

{/* Mood */}
{/* <Grid item xs={12}>
<Typography variant="body1">Mood</Typography>
Expand Down Expand Up @@ -461,7 +480,15 @@ function DailyData() {
</Select>
</FormControl>
</Grid> */}

{/* Submit Button */}
<Grid2 item xs={12}>
<Button type="submit" variant="contained" sx={submitButton}>
Submit
</Button>
</Grid2>
</Grid2>
</form>
</Box>
);
}
Expand Down
16 changes: 15 additions & 1 deletion code/server/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,28 @@ let userSchema = new Schema({
collection: 'users'
})

let dailyEntrySchema = new Schema({
dailyEntryId: { type: Number, required: true },
userId: { type: Number, required: true },
entryDate: { type: Date },
weight: { type: Number },
steps: { type: Number },
sleep: { type: Number },
water: { type: Number },
exercise: { type: Number }
}, {
collection: 'daily_entries'
})

module.exports = {
getModel: () => {
if (connection == null) {
connection = mongoose.createConnection(process.env.MONGO_URI)
console.log("Connected to MongoDB!")
userModel = connection.model("User", userSchema);
goalModel = connection.model("Goal", goalSchema);
models = {userModel: userModel, goalModel: goalModel}
dailyEntryModel = connection.model("DailyEntry", dailyEntrySchema);
models = {userModel: userModel, goalModel: goalModel, dailyEntryModel: dailyEntryModel}
}
return models
},
Expand Down
19 changes: 18 additions & 1 deletion code/server/initdb.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@ const db = require("./db.js")

const User = db.getModel().userModel
const Goal = db.getModel().goalModel
const DailyEntry = db.getModel().dailyEntryModel

async function init() {
try {
// Option to delete existing data for full reset
// await User.deleteMany({})
// await Goal.deleteMany({})
// await DailyEntry.deleteMany({})

let goal1 = new Goal({
goalId: 50001,
Expand Down Expand Up @@ -46,12 +48,24 @@ async function init() {
// createdAt: "2024-09-01", // testing the default param in schema works
goals: []
})

let dailyEntry1 = new DailyEntry({
dailyEntryId: 1,
userId: 10001,
entryDate: "2024-10-04",
weight: 150,
steps: 9999,
sleep: 7.5,
water: 4,
exercise: 45
})

await Promise.all([
user1.save(),
user2.save(),
goal1.save(),
goal2.save()
goal2.save(),
dailyEntry1.save()
])

let users = await User.find({})
Expand All @@ -60,6 +74,9 @@ async function init() {
let goals = await Goal.find({})
console.log(goals)

let dailyEntries = await DailyEntry.find({})
console.log(dailyEntries)

} catch(error) {
console.log(error)
} finally {
Expand Down
32 changes: 32 additions & 0 deletions code/server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const app = express();
const port = process.env.PORT || 5000
const User = db.getModel().userModel
const Goal = db.getModel().goalModel
const DailyEntry = db.getModel().dailyEntryModel

const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
Expand Down Expand Up @@ -166,6 +167,37 @@ app.post('/create-goal', async (req, res) => {
}
})


app.post('/enter-daily-data', async (req, res) => {

try {
const { weight, steps, sleep, water, exercise } = req.body;

// generate new ID based on max goal ID
let lastEntry = await DailyEntry.find().sort({"dailyEntryId": -1}).limit(1)
let newEntryId = lastEntry[0].dailyEntryId + 1

const newDailyEntry = new DailyEntry({
dailyEntryId: newEntryId,
userId: 10001, // UPDATE TO USERID BASED ON WHO IS LOGGED IN
entryDate: "2024-10-04", // TO DO: FIGURE OUT HOW TO GRAB THIS FROM FORM
weight: weight,
steps: steps,
sleep: sleep,
water: water,
exercise: exercise
})

await newDailyEntry.save();
res.status(201).json({ message: 'Daily entry created successfully!' });

} catch (error) {
res.status(500).json({ message: 'Error creating daily entry' });
}

})


//Listen for incoming connections
app.listen(port, () => {
console.log(`Server running on port ${port}`);
Expand Down

0 comments on commit c2c9eb8

Please sign in to comment.