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

DeleteTimeoff/NicoQ #18

Open
wants to merge 3 commits into
base: main
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
33 changes: 26 additions & 7 deletions src/backend/API/timeoff.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,24 @@ const express = require("express");
const router = express.Router();
const db = require("../database");

router.get('/', async (req, res) => {
router.get("/", async (req, res) => {
try {
const allTimeOffs = await db.select('*').from('timeoff');
res.json(allTimeOffs);
const allTimeOffs = await db.select("*").from("timeoff");
res.json(allTimeOffs);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'An unexpected error occurred while processing your request.' });
res
.status(500)
.json({
error: "An unexpected error occurred while processing your request.",
});
}
});

router.post("/:id", async (request, response) => {
const { start_date, end_date, description, member_id } = request.body;
const { start_date, end_date, description, member_id } = request.body;
if (!start_date || !end_date || !description || !member_id) {
return response.status(400).json({ error: 'Missing required fields' });
return response.status(400).json({ error: "Missing required fields" });
}

const addTimeOff = {
Expand All @@ -30,9 +34,24 @@ router.post("/:id", async (request, response) => {
await db("timeoff").insert(addTimeOff);
response.status(201).json("New timeoff has been added");
} catch (error) {
console.error(error);
console.error(error);
response.status(500).json({ error: "Failed to add a new timeoff" });
}
});

router.delete("/", async (request, response) => {
const eventId = request.body.id;
if (!eventId) {
return response.status(400).json({ error: "Event ID is required" });
}

try {
await db("timeoff").where({ id: eventId }).del();
response.status(204).send();
} catch (error) {
console.error(error);
response.status(500).json({ error: "Failed to delete the event" });
}
});

module.exports = router;
41 changes: 39 additions & 2 deletions src/component/Calendar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import dayjs from "dayjs";
import "react-big-calendar/lib/css/react-big-calendar.css";
import { TeamDataContext } from "../component/Context";
import { apiPath } from "../api";
import '../styles/calender.css'
import "../styles/calender.css";
import "../styles/deleteTimeoff.css";

function MyCalendar() {
const localizer = dayjsLocalizer(dayjs);
const { teams, members } = useContext(TeamDataContext);
const { teams, members, refreshTeamData } = useContext(TeamDataContext);
const [events, setEvents] = useState([]);
const [selectedEvent, setSelectedEvent] = useState(null);
const [showDeleteConfirmation, setShowDeleteConfirmation] = useState(false);

useEffect(() => {
const teamCode = window.location.pathname.split("/").pop();
Expand All @@ -34,6 +36,7 @@ function MyCalendar() {
(member) => member.id === event.member_id
);
return {
id: event.id,
start: new Date(event.start_date),
end: new Date(event.end_date),
title: member ? `${member.first_name} ${member.last_name}` : "",
Expand All @@ -43,6 +46,7 @@ function MyCalendar() {
});

setEvents(formattedEvents);
refreshTeamData();
} catch (error) {
console.error("Error fetching events:", error);
}
Expand All @@ -55,6 +59,31 @@ function MyCalendar() {
setSelectedEvent(event);
};

const handleDeleteEvent = async () => {
setShowDeleteConfirmation(true);
};

const confirmDelete = async () => {
try {
await fetch(apiPath(`/timeoff`), {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ id: selectedEvent.id }),
});
setEvents(events.filter((event) => event.id !== selectedEvent.id));
setSelectedEvent(null);
setShowDeleteConfirmation(false);
} catch (error) {
console.error("Error deleting event:", error);
}
};

const cancelDelete = () => {
setShowDeleteConfirmation(false);
};

return (
<div className="calender-container">
<Calendar
Expand Down Expand Up @@ -83,6 +112,14 @@ function MyCalendar() {
<div>
<h3>{selectedEvent.title}</h3>
<p>{selectedEvent.description}</p>
<button onClick={handleDeleteEvent}>Delete Event</button>
{showDeleteConfirmation && (
<div className="delete-confirmation">
<p>Are you sure you want to delete this event?</p>
<button onClick={confirmDelete}>Yes</button>
<button onClick={cancelDelete}>No</button>
</div>
)}
</div>
)}
</div>
Expand Down
20 changes: 16 additions & 4 deletions src/component/Context.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,13 @@ const TeamDataProvider = ({ children }) => {
const [teams, setTeams] = useState([]);
const [members, setMembers] = useState([]);
const [timeOff, setTimeOff] = useState([]);
const [dataIsOld, setDataIsOld] = useState(false);

useEffect(() => {
const fetchData = async () => {
const refreshTeamData = () => {
setDataIsOld(true)
}

const fetchData = async () => {
try {
const [teamsResponse, membersResponse, timeOffResponse] = await Promise.all([
fetch(apiPath('/teams')),
Expand All @@ -28,12 +32,20 @@ const TeamDataProvider = ({ children }) => {
console.error('Error fetching data:', error);
}
};


useEffect(() => {
fetchData();
}, []);

useEffect(() => {
if(dataIsOld) {
fetchData();
setDataIsOld(false)
}
}, [dataIsOld]);

return (
<TeamDataContext.Provider value={{ teams, members, timeOff }}>
<TeamDataContext.Provider value={{ teams, members, timeOff, setMembers, refreshTeamData }}>
{children}
</TeamDataContext.Provider>
);
Expand Down
30 changes: 18 additions & 12 deletions src/component/CreateMember.jsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,24 @@
import { useState, useEffect, useContext } from "react";
import { useParams } from "react-router-dom";
import { apiPath } from '../api';
import { TeamDataContext } from '../component/Context';
import '../styles/createMember.css'
import { apiPath } from "../api";
import { TeamDataContext } from "../component/Context";
import "../styles/createMember.css";

function CreateMember() {
const { code } = useParams();
const contextData = useContext(TeamDataContext);
const teams = contextData.teams;
const { code } = useParams();
const { teams, refreshTeamData } = useContext(TeamDataContext);

const [teamId, setTeamId] = useState(null);
const [memberData, setMemberData] = useState({
first_name: "",
last_name: "",
email: "",
color: "#000000",
allowed_dayoff: 0,
allowed_dayoff: 0,
});

useEffect(() => {
const team = teams.find(team => team.team_code === code);
const team = teams.find((team) => team.team_code === code);
if (team) {
setTeamId(team.id);
} else {
Expand All @@ -31,21 +30,28 @@ function CreateMember() {
e.preventDefault();

try {
const response = await fetch(apiPath('/members'), {
const response = await fetch(apiPath("/members"), {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
...memberData,
team_id: teamId,
assigned_dayoff: 0,
assigned_dayoff: 0,
}),
});

if (response.ok) {
alert("Member created successfully!");
setMemberData({ first_name: "", last_name: "", email: "", color: "#000000", allowed_dayoff: 0 });
refreshTeamData();
setMemberData({
first_name: "",
last_name: "",
email: "",
color: "#000000",
allowed_dayoff: 0,
});
} else {
const data = await response.json();
alert(data.error || "Failed to create member. Please try again.");
Expand All @@ -58,7 +64,7 @@ function CreateMember() {

const handleChange = (e) => {
const { name, value } = e.target;
setMemberData(prevState => ({
setMemberData((prevState) => ({
...prevState,
[name]: value,
}));
Expand Down
5 changes: 3 additions & 2 deletions src/component/DeleteMember.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useParams } from 'react-router-dom';
import '../styles/deleteMember.css';

const DeleteMember = () => {
const { members, teams } = useContext(TeamDataContext);
const { members, teams, setMembers } = useContext(TeamDataContext);
const [selectedMember, setSelectedMember] = useState('');
const [filteredMembers, setFilteredMembers] = useState([]);
const { code } = useParams();
Expand Down Expand Up @@ -48,9 +48,10 @@ const DeleteMember = () => {
});

if (response.ok) {
const updatedMembers = filteredMembers.filter(member => member.id !== selectedMember);
const updatedMembers = filteredMembers.filter(member => member.id !== Number(selectedMember));
setFilteredMembers(updatedMembers);
alert('Member deleted successfully');
setMembers(updatedMembers)
} else {
alert('Failed to delete member. Please try again.');
}
Expand Down
4 changes: 1 addition & 3 deletions src/pages/Team.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ return(
<DeleteTeam/>
<CreateTimeoff/>
</section>
<section className="DayOff">
<h3>Day Off Rank</h3>
</section>

</section>
</div>

Expand Down
11 changes: 11 additions & 0 deletions src/styles/deleteTimeoff.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
button {
width: 8em;
background-color: #e10808;
color: white;
border: none;
border-radius: 10px;
cursor: pointer;
font-family: 'Poppins';
padding: 6px;
margin: 1em;
}
1 change: 1 addition & 0 deletions src/styles/team.css
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

.container-section {
display: flex;
height: 69em;
}

.left-section {
Expand Down