Skip to content

Commit

Permalink
creating a task
Browse files Browse the repository at this point in the history
  • Loading branch information
Kabadzh0b committed May 28, 2024
1 parent 1255169 commit 1bccc93
Show file tree
Hide file tree
Showing 4 changed files with 137 additions and 25 deletions.
3 changes: 3 additions & 0 deletions frontend/src/components/ProtectedRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
ROLE_LOCALSTORAGE_KEY,
SERVER_URL,
TOKEN_LOCALSTORAGE_KEY,
USER_ID_LOCALSTORAGE_KEY,
} from "../constants";

const ProtectedRoute = ({
Expand Down Expand Up @@ -36,7 +37,9 @@ const ProtectedRoute = ({
});

const role = response.data.role;
const userId = response.data.id;
localStorage.setItem(ROLE_LOCALSTORAGE_KEY, role);
localStorage.setItem(USER_ID_LOCALSTORAGE_KEY, userId);

if (roles.includes(role)) {
setIsAuthenticated(true);
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ export const SERVER_URL = "http://localhost:3001";
export const TOKEN_LOCALSTORAGE_KEY = "accessToken";

export const ROLE_LOCALSTORAGE_KEY = "role";

export const USER_ID_LOCALSTORAGE_KEY = "userId";
20 changes: 19 additions & 1 deletion frontend/src/pages/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useNavigate } from "react-router";
import axios from "axios";
import { SERVER_URL, TOKEN_LOCALSTORAGE_KEY } from "../constants";
import { Form, Input, Button } from "antd";
import { Role } from "./signUp";

type LoginValues = {
email: string;
Expand All @@ -20,7 +21,24 @@ export const Login: React.FC = () => {
.then((response) => {
const accessToken = response.data.access_token;
localStorage.setItem(TOKEN_LOCALSTORAGE_KEY, accessToken);
navigate("/");
axios
.get(`${SERVER_URL}/auth/me`, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
})
.then((response) => {
const role = response.data.role;
localStorage.setItem("role", role);
if (role === Role.BOSS) {
console.log("boss");
navigate("/boss");
} else if (role === Role.EMPLOYEE) {
navigate("/tasks");
} else {
console.error("role not found");
}
});
});
};
return (
Expand Down
137 changes: 113 additions & 24 deletions frontend/src/pages/tasks.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
import { Button, Card, DatePicker, Form, Input, Modal, Select } from "antd";
import {
Button,
Card,
DatePicker,
Form,
FormInstance,
Input,
Modal,
Select,
} from "antd";
import Title from "antd/es/typography/Title";
import { useNavigate } from "react-router";
import dayjs from "dayjs";
import { useEffect, useState } from "react";
import { LegacyRef, useEffect, useRef, useState } from "react";
import axios from "axios";
import {
ROLE_LOCALSTORAGE_KEY,
SERVER_URL,
TOKEN_LOCALSTORAGE_KEY,
USER_ID_LOCALSTORAGE_KEY,
} from "../constants";

export enum TaskStatus {
Expand All @@ -24,13 +34,16 @@ export type Task = {
status: TaskStatus;
startDate: Date;
endDate: Date;
userId: number;
userId: string;
};

export const Tasks: React.FC = () => {
const navigate = useNavigate();
const formRef = useRef<FormInstance<Task>>();
const [tasks, setTasks] = useState<Task[]>([]);
const [isAddingTask, setIsAddingTask] = useState<boolean>(false);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);

const openModal = () => {
setIsAddingTask(true);
Expand All @@ -40,22 +53,82 @@ export const Tasks: React.FC = () => {
setIsAddingTask(false);
};

const handleCreateTask = async (values: Task) => {
const userID = localStorage.getItem(USER_ID_LOCALSTORAGE_KEY);
const token = localStorage.getItem(TOKEN_LOCALSTORAGE_KEY);

if (!userID || !token) {
navigate("/login");
return;
}

const startDate = dayjs(values.startDate).toISOString();
const endDate = dayjs(values.endDate).toISOString();

console.log("Start Date:", startDate, "Type:", typeof startDate);
console.log("End Date:", endDate, "Type:", typeof endDate);

const newTaskValues = {
...values,
startDate: startDate,
endDate: endDate,
userId: userID,
};

try {
const response = await axios.post(`${SERVER_URL}/task`, newTaskValues, {
headers: {
Authorization: `Bearer ${token}`,
},
});
setTasks([...tasks, response.data]);
closeModal();
} catch (error) {
console.error("Error during task creation:", error);
}
};

const handleLogout = () => {
localStorage.removeItem(TOKEN_LOCALSTORAGE_KEY);
localStorage.removeItem(ROLE_LOCALSTORAGE_KEY);
localStorage.removeItem(USER_ID_LOCALSTORAGE_KEY);
navigate("/login");
};

useEffect(() => {
axios
.get(`${SERVER_URL}/task`)
.then((response) => {
const token = localStorage.getItem(TOKEN_LOCALSTORAGE_KEY);

if (!token) {
navigate("/login");
return;
}

const fetchTasks = async () => {
try {
const response = await axios.get(`${SERVER_URL}/task`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
setTasks(response.data);
})
.catch((error) => {
} catch (error) {
console.error("Error during fetching tasks:", error);
});
}, []);
setError("Failed to fetch tasks. Please try again later.");
} finally {
setLoading(false);
}
};

fetchTasks();
}, [navigate]);

if (loading) {
return <div>Loading tasks...</div>;
}

if (error) {
return <div>{error}</div>;
}

return (
<div style={{ margin: 20 }}>
Expand All @@ -67,7 +140,13 @@ export const Tasks: React.FC = () => {
}}
>
<h1>Tasks</h1>
<div>
<div
style={{
display: "flex",
flexDirection: "row",
gap: 10,
}}
>
<Button onClick={openModal}>Add Task</Button>
<Button onClick={handleLogout}>Logout</Button>
</div>
Expand All @@ -90,29 +169,37 @@ export const Tasks: React.FC = () => {
<Title level={3}>{task.title}</Title>
<p>{task.description}</p>
<p>{task.status}</p>
<p>
start date:{" "}
{dayjs(task.startDate).format("YYYY-MM-DD").toString()}
</p>
<p>
end date: {dayjs(task.endDate).format("YYYY-MM-DD").toString()}
</p>
<p>Start date: {dayjs(task.startDate).format("YYYY-MM-DD")}</p>
<p>End date: {dayjs(task.endDate).format("YYYY-MM-DD")}</p>
</Card>
))}
</div>
<Modal open={isAddingTask} onCancel={closeModal}>
<Form>
<Form.Item label="Title" name="title" rules={[{ required: true }]}>
<Form<Task>
ref={formRef as LegacyRef<FormInstance<Task>>}
onFinish={handleCreateTask}
>
<Form.Item
label="Title"
name="title"
rules={[{ required: true, message: "Please input the title!" }]}
>
<Input />
</Form.Item>
<Form.Item
label="Description"
name="description"
rules={[{ required: true }]}
rules={[
{ required: true, message: "Please input the description!" },
]}
>
<Input.TextArea />
</Form.Item>
<Form.Item label="Status" name="status" rules={[{ required: true }]}>
<Form.Item
label="Status"
name="status"
rules={[{ required: true, message: "Please select a status!" }]}
>
<Select>
<Select.Option value={TaskStatus.IN_PROGRESS}>
In Progress
Expand All @@ -125,14 +212,16 @@ export const Tasks: React.FC = () => {
<Form.Item
label="Start Date"
name="startDate"
rules={[{ required: true }]}
rules={[
{ required: true, message: "Please select the start date!" },
]}
>
<DatePicker />
</Form.Item>
<Form.Item
label="End Date"
name="endDate"
rules={[{ required: true }]}
rules={[{ required: true, message: "Please select the end date!" }]}
>
<DatePicker />
</Form.Item>
Expand Down

0 comments on commit 1bccc93

Please sign in to comment.