Compare commits

...

35 commits

Author SHA1 Message Date
Peter KW
46eb3c76a8 Small fix to statistics 2024-04-02 19:18:05 +02:00
Peter KW
632676e3d2 Added admin to all projects in sample_data 2024-04-02 19:16:02 +02:00
Peter KW
51a4d2a0b7 Fix to comments 2024-04-02 13:45:03 +02:00
Peter KW
524bd6c691 Can now delete project 2024-04-02 13:44:31 +02:00
Peter KW
b50d88f670 DeleteProject component 2024-04-02 13:44:06 +02:00
Peter KW
3ed4393c77 Fixed fetch path in removeProject 2024-04-02 13:43:32 +02:00
Peter KW
75876e43da Minor design fix 2024-04-02 13:22:46 +02:00
Peter KW
ea5bbf5f0a Merge branch 'frontend' into gruppPP 2024-04-02 13:18:25 +02:00
Peter KW
948dcce1ca Some fixes to design and comments 2024-04-02 13:14:08 +02:00
Peter KW
cb68a6323b Now shows project statistics 2024-04-02 13:11:33 +02:00
Peter KW
ca88daf493 GetProjectTimes component 2024-04-02 13:10:04 +02:00
Peter KW
644d0ee12c getProjectTimes API 2024-04-02 13:09:28 +02:00
Peter KW
6efc961774 Added getProjectTimes 2024-04-02 13:08:55 +02:00
Davenludd
7df1654bdc Merge branch 'frontend' into gruppDM 2024-04-02 11:49:46 +02:00
Davenludd
6dfa917cf0 Fix in DisplayUserProjects component 2024-04-02 11:37:53 +02:00
Peter KW
17a571fd7c Uses component to get projects now 2024-04-01 02:25:12 +02:00
Peter KW
f3466854c7 Removed unused pages and paths to them in main 2024-04-01 02:24:26 +02:00
Peter KW
1212b3c5ef Removed some stuff 2024-04-01 02:20:48 +02:00
Peter KW
dc98fb510e Clears username+password fields on successful register 2024-04-01 02:17:57 +02:00
Peter KW
58deef400a Removed unused code 2024-04-01 02:17:02 +02:00
Peter KW
cc039d27ae New modal for member info 2024-04-01 02:16:23 +02:00
Peter KW
3981190c7a Can now change username in this modal + moved some stuff to a separate modal 2024-04-01 02:16:06 +02:00
Peter KW
9b0a231701 Some fixes to ChangeUsername 2024-04-01 02:14:44 +02:00
Peter KW
e06aced6dd ChangeRole component to change role and a view for it 2024-04-01 02:13:24 +02:00
Peter KW
68fbbb4b19 Added some alerts + removed unused code 2024-04-01 02:09:28 +02:00
Peter KW
378dd99592 Changed so that you can only change other users role 2024-04-01 02:08:19 +02:00
Peter KW
6fa8135e32 ChangeUserRole API added + bugfix 2024-04-01 02:02:22 +02:00
Peter KW
60fb333090 Fix to paths 2024-03-31 21:04:58 +02:00
Peter KW
e7911574be Removed unused files 2024-03-31 20:56:40 +02:00
Peter KW
0c8a394f74 Small fix so that it uses component for getting users in a proj 2024-03-31 20:56:08 +02:00
Peter KW
5f42fa7818 Fixed types and imports of types 2024-03-31 20:54:00 +02:00
Peter KW
8b6462abee Changed so that username is required to get projects, so that you can get another user's projects (for admin stuff) 2024-03-29 20:19:22 +01:00
Davenludd
c1f49915ba Refactor signReport method signature 2024-03-29 18:29:38 +01:00
Davenludd
2aaa327a01 Merge branch 'dev' into gruppDM 2024-03-29 17:55:32 +01:00
Davenludd
05545f6f88 Minor fixes 2024-03-29 17:53:37 +01:00
35 changed files with 702 additions and 523 deletions

View file

@ -21,6 +21,12 @@ VALUES ("projecttest3","test project3", 1);
INSERT OR IGNORE INTO user_roles(user_id,project_id,p_role) INSERT OR IGNORE INTO user_roles(user_id,project_id,p_role)
VALUES (1,1,"project_manager"); VALUES (1,1,"project_manager");
INSERT OR IGNORE INTO user_roles(user_id,project_id,p_role)
VALUES (1,2,"project_manager");
INSERT OR IGNORE INTO user_roles(user_id,project_id,p_role)
VALUES (1,3,"project_manager");
INSERT OR IGNORE INTO user_roles(user_id,project_id,p_role) INSERT OR IGNORE INTO user_roles(user_id,project_id,p_role)
VALUES (2,1,"member"); VALUES (2,1,"member");

View file

@ -4,15 +4,16 @@ import (
db "ttime/internal/database" db "ttime/internal/database"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt/v5" "github.com/gofiber/fiber/v2/log"
) )
// GetUserProjects returns all projects that the user is a member of // GetUserProjects returns all projects that the user is a member of
func GetUserProjects(c *fiber.Ctx) error { func GetUserProjects(c *fiber.Ctx) error {
// First we get the username from the token username := c.Params("username")
user := c.Locals("user").(*jwt.Token) if username == "" {
claims := user.Claims.(jwt.MapClaims) log.Info("No username provided")
username := claims["name"].(string) return c.Status(400).SendString("No username provided")
}
// Then dip into the database to get the projects // Then dip into the database to get the projects
projects, err := db.GetDb(c).GetProjectsForUser(username) projects, err := db.GetDb(c).GetProjectsForUser(username)

View file

@ -24,7 +24,13 @@ func ProjectRoleChange(c *fiber.Ctx) error {
return c.Status(400).SendString(err.Error()) return c.Status(400).SendString(err.Error())
} }
log.Info("Changing role for user: ", username, " in project: ", data.Projectname, " to: ", data.Role) // Check if user is trying to change its own role
if username == data.UserName {
log.Info("Can't change your own role")
return c.Status(403).SendString("Can't change your own role")
}
log.Info("Changing role for user: ", data.UserName, " in project: ", data.Projectname, " to: ", data.Role)
// Dubble diping and checcking if current user is // Dubble diping and checcking if current user is
if ismanager, err := db.GetDb(c).IsProjectManager(username, data.Projectname); err != nil { if ismanager, err := db.GetDb(c).IsProjectManager(username, data.Projectname); err != nil {
@ -36,7 +42,7 @@ func ProjectRoleChange(c *fiber.Ctx) error {
} }
// Change the user's role within the project in the database // Change the user's role within the project in the database
if err := db.GetDb(c).ChangeUserRole(username, data.Projectname, data.Role); err != nil { if err := db.GetDb(c).ChangeUserRole(data.UserName, data.Projectname, data.Role); err != nil {
return c.Status(500).SendString(err.Error()) return c.Status(500).SendString(err.Error())
} }

View file

@ -112,7 +112,8 @@ func main() {
// All project related routes // All project related routes
// projectGroup := api.Group("/project") // Not currently in use // projectGroup := api.Group("/project") // Not currently in use
api.Get("/getUserProjects", projects.GetUserProjects) api.Get("/getProjectTimes/:projectName", projects.GetProjectTimesHandler)
api.Get("/getUserProjects/:username", projects.GetUserProjects)
api.Get("/project/:projectId", projects.GetProject) api.Get("/project/:projectId", projects.GetProject)
api.Get("/checkIfProjectManager/:projectName", projects.IsProjectManagerHandler) api.Get("/checkIfProjectManager/:projectName", projects.IsProjectManagerHandler)
api.Get("/getUsersProject/:projectName", projects.ListAllUsersProject) api.Get("/getUsersProject/:projectName", projects.ListAllUsersProject)

View file

@ -1,13 +1,15 @@
import { NewProjMember } from "../Components/AddMember";
import { ProjectRoleChange } from "../Components/ChangeRole";
import { projectTimes } from "../Components/GetProjectTimes";
import { ProjectMember } from "../Components/GetUsersInProject";
import { import {
NewWeeklyReport, NewWeeklyReport,
NewUser, NewUser,
User, User,
Project, Project,
NewProject, NewProject,
UserProjectMember,
WeeklyReport, WeeklyReport,
StrNameChange, StrNameChange,
NewProjMember,
} from "../Types/goTypes"; } from "../Types/goTypes";
/** /**
@ -73,10 +75,7 @@ interface API {
* @param {string} token The authentication token. * @param {string} token The authentication token.
* @returns {Promise<APIResponse<Project>>} A promise resolving to an API response with the created project. * @returns {Promise<APIResponse<Project>>} A promise resolving to an API response with the created project.
*/ */
createProject( createProject(project: NewProject, token: string): Promise<APIResponse<void>>;
project: NewProject,
token: string,
): Promise<APIResponse<Project>>;
/** Submits a weekly report /** Submits a weekly report
* @param {NewWeeklyReport} weeklyReport The weekly report object. * @param {NewWeeklyReport} weeklyReport The weekly report object.
@ -128,6 +127,16 @@ interface API {
*/ */
getProject(id: number): Promise<APIResponse<Project>>; getProject(id: number): Promise<APIResponse<Project>>;
/** Gets a projects reported time
* @param {string} projectName The name of the project.
* @param {string} token The usertoken.
* @returns {Promise<APIResponse<Times>>} A promise resolving to an API response containing the project times.
*/
getProjectTimes(
projectName: string,
token: string,
): Promise<APIResponse<projectTimes>>;
/** Gets a list of all users. /** Gets a list of all users.
* @param {string} token The authentication token of the requesting user. * @param {string} token The authentication token of the requesting user.
* @returns {Promise<APIResponse<string[]>>} A promise resolving to an API response containing the list of users. * @returns {Promise<APIResponse<string[]>>} A promise resolving to an API response containing the list of users.
@ -137,7 +146,7 @@ interface API {
getAllUsersProject( getAllUsersProject(
projectName: string, projectName: string,
token: string, token: string,
): Promise<APIResponse<UserProjectMember[]>>; ): Promise<APIResponse<ProjectMember[]>>;
/** /**
* Changes the username of a user in the database. * Changes the username of a user in the database.
* @param {StrNameChange} data The object containing the previous and new username. * @param {StrNameChange} data The object containing the previous and new username.
@ -148,10 +157,21 @@ interface API {
data: StrNameChange, data: StrNameChange,
token: string, token: string,
): Promise<APIResponse<void>>; ): Promise<APIResponse<void>>;
/**
* Changes the role of a user in the database.
* @param {RoleChange} roleInfo The object containing the previous and new username.
* @param {string} token The authentication token.
* @returns {Promise<APIResponse<void>>} A promise resolving to an API response.
*/
changeUserRole(
roleInfo: ProjectRoleChange,
token: string,
): Promise<APIResponse<void>>;
addUserToProject( addUserToProject(
user: NewProjMember, user: NewProjMember,
token: string, token: string,
): Promise<APIResponse<NewProjMember>>; ): Promise<APIResponse<void>>;
removeProject( removeProject(
projectName: string, projectName: string,
@ -165,10 +185,7 @@ interface API {
* @param {number} reportId The id of the report to sign * @param {number} reportId The id of the report to sign
* @param {string} token The authentication token * @param {string} token The authentication token
*/ */
signReport( signReport(reportId: number, token: string): Promise<APIResponse<string>>;
reportId: number,
token: string,
): Promise<APIResponse<string>>;
} }
/** An instance of the API */ /** An instance of the API */
@ -256,7 +273,7 @@ export const api: API = {
async createProject( async createProject(
project: NewProject, project: NewProject,
token: string, token: string,
): Promise<APIResponse<Project>> { ): Promise<APIResponse<void>> {
try { try {
const response = await fetch("/api/project", { const response = await fetch("/api/project", {
method: "POST", method: "POST",
@ -270,18 +287,17 @@ export const api: API = {
if (!response.ok) { if (!response.ok) {
return { success: false, message: "Failed to create project" }; return { success: false, message: "Failed to create project" };
} else { } else {
const data = (await response.json()) as Project; return { success: true };
return { success: true, data };
} }
} catch (e) { } catch (e) {
return { success: false, message: "Failed to create project" }; return { success: false, message: "Failed to create project!" };
} }
}, },
async addUserToProject( async addUserToProject(
user: NewProjMember, user: NewProjMember,
token: string, token: string,
): Promise<APIResponse<NewProjMember>> { ): Promise<APIResponse<void>> {
try { try {
const response = await fetch("/api/addUserToProject", { const response = await fetch("/api/addUserToProject", {
method: "PUT", method: "PUT",
@ -323,6 +339,33 @@ export const api: API = {
} }
}, },
async changeUserRole(
roleInfo: ProjectRoleChange,
token: string,
): Promise<APIResponse<void>> {
try {
const response = await fetch("/api/ProjectRoleChange", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
body: JSON.stringify(roleInfo),
});
if (!response.ok) {
if (response.status === 403) {
return { success: false, message: "Cannot change your own role" };
}
return { success: false, message: "Could not change role" };
} else {
return { success: true };
}
} catch (e) {
return { success: false, message: "Could not change role" };
}
},
async getUserProjects( async getUserProjects(
username: string, username: string,
token: string, token: string,
@ -353,6 +396,37 @@ export const api: API = {
} }
}, },
async getProjectTimes(
projectName: string,
token: string,
): Promise<APIResponse<projectTimes>> {
try {
const response = await fetch(`/api/getProjectTimes/${projectName}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
});
if (!response.ok) {
return Promise.resolve({
success: false,
message:
"Fetch error: " + response.status + ", failed to get project times",
});
} else {
const data = (await response.json()) as projectTimes;
return Promise.resolve({ success: true, data });
}
} catch (e) {
return Promise.resolve({
success: false,
message: "API error! Could not get times.",
});
}
},
async submitWeeklyReport( async submitWeeklyReport(
weeklyReport: NewWeeklyReport, weeklyReport: NewWeeklyReport,
token: string, token: string,
@ -520,7 +594,7 @@ export const api: API = {
async getAllUsersProject( async getAllUsersProject(
projectName: string, projectName: string,
token: string, token: string,
): Promise<APIResponse<UserProjectMember[]>> { ): Promise<APIResponse<ProjectMember[]>> {
try { try {
const response = await fetch(`/api/getUsersProject/${projectName}`, { const response = await fetch(`/api/getUsersProject/${projectName}`, {
method: "GET", method: "GET",
@ -536,7 +610,7 @@ export const api: API = {
message: "Failed to get users", message: "Failed to get users",
}); });
} else { } else {
const data = (await response.json()) as UserProjectMember[]; const data = (await response.json()) as ProjectMember[];
return Promise.resolve({ success: true, data }); return Promise.resolve({ success: true, data });
} }
} catch (e) { } catch (e) {
@ -576,7 +650,7 @@ export const api: API = {
token: string, token: string,
): Promise<APIResponse<string>> { ): Promise<APIResponse<string>> {
try { try {
const response = await fetch(`/api/projectdelete/${projectName}`, { const response = await fetch(`/api/removeProject/${projectName}`, {
method: "DELETE", method: "DELETE",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -622,5 +696,5 @@ export const api: API = {
} catch (e) { } catch (e) {
return { success: false, message: "Failed to sign report" }; return { success: false, message: "Failed to sign report" };
} }
} },
}; };

View file

@ -1,5 +1,10 @@
import { APIResponse, api } from "../API/API"; import { APIResponse, api } from "../API/API";
import { NewProjMember } from "../Types/goTypes";
export interface NewProjMember {
username: string;
role: string;
projectname: string;
}
/** /**
* Tries to add a member to a project * Tries to add a member to a project
@ -21,7 +26,7 @@ function AddMember(props: { memberToAdd: NewProjMember }): boolean {
props.memberToAdd, props.memberToAdd,
localStorage.getItem("accessToken") ?? "", localStorage.getItem("accessToken") ?? "",
) )
.then((response: APIResponse<NewProjMember>) => { .then((response: APIResponse<void>) => {
if (response.success) { if (response.success) {
alert("Member added"); alert("Member added");
added = true; added = true;

View file

@ -1,6 +1,6 @@
import { useState } from "react"; import { useState } from "react";
import { APIResponse, api } from "../API/API"; import { APIResponse, api } from "../API/API";
import { NewProject, Project } from "../Types/goTypes"; import { NewProject } from "../Types/goTypes";
import InputField from "./InputField"; import InputField from "./InputField";
import Logo from "../assets/Logo.svg"; import Logo from "../assets/Logo.svg";
import Button from "./Button"; import Button from "./Button";
@ -10,27 +10,26 @@ import Button from "./Button";
* @param {Object} props - Project name and description * @param {Object} props - Project name and description
* @returns {boolean} True if created, false if not * @returns {boolean} True if created, false if not
*/ */
function CreateProject(props: { name: string; description: string }): boolean { function CreateProject(props: { name: string; description: string }): void {
const project: NewProject = { const project: NewProject = {
name: props.name, name: props.name,
description: props.description, description: props.description,
}; };
let created = false;
api api
.createProject(project, localStorage.getItem("accessToken") ?? "") .createProject(project, localStorage.getItem("accessToken") ?? "")
.then((response: APIResponse<Project>) => { .then((response: APIResponse<void>) => {
if (response.success) { if (response.success) {
created = true; alert("Project added!");
} else { } else {
alert("Project NOT added!");
console.error(response.message); console.error(response.message);
} }
}) })
.catch((error) => { .catch((error) => {
alert("Project NOT added!");
console.error("An error occurred during creation:", error); console.error("An error occurred during creation:", error);
}); });
return created;
} }
/** /**
@ -48,7 +47,10 @@ function AddProject(): JSX.Element {
className="bg-white rounded px-8 pt-6 pb-8 mb-4 items-center justify-center flex flex-col w-fit h-fit" className="bg-white rounded px-8 pt-6 pb-8 mb-4 items-center justify-center flex flex-col w-fit h-fit"
onSubmit={(e) => { onSubmit={(e) => {
e.preventDefault(); e.preventDefault();
CreateProject({ name: name, description: description }); CreateProject({
name: name,
description: description,
});
}} }}
> >
<img <img
@ -59,22 +61,26 @@ function AddProject(): JSX.Element {
<h3 className="pb-4 mb-2 text-center font-bold text-[18px]"> <h3 className="pb-4 mb-2 text-center font-bold text-[18px]">
Create a new project Create a new project
</h3> </h3>
<InputField <div className="space-y-3">
label="Name" <InputField
type="text" label="Name"
value={name} type="text"
onChange={(e) => { value={name}
setName(e.target.value); onChange={(e) => {
}} e.preventDefault();
/> setName(e.target.value);
<InputField }}
label="Description" />
type="text" <InputField
value={description} label="Description"
onChange={(e) => { type="text"
setDescription(e.target.value); value={description}
}} onChange={(e) => {
/> e.preventDefault();
setDescription(e.target.value);
}}
/>
</div>
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<Button <Button
text="Create" text="Create"

View file

@ -1,15 +1,14 @@
import { useState } from "react"; import { useState } from "react";
import { NewProjMember } from "../Types/goTypes";
import Button from "./Button"; import Button from "./Button";
import GetAllUsers from "./GetAllUsers"; import GetAllUsers from "./GetAllUsers";
import AddMember from "./AddMember"; import AddMember, { NewProjMember } from "./AddMember";
import BackButton from "./BackButton"; import BackButton from "./BackButton";
/** /**
* Provides UI for adding a member to a project. * Provides UI for adding a member to a project.
* @returns {JSX.Element} - Returns the component UI for adding a member * @returns {JSX.Element} - Returns the component UI for adding a member
*/ */
function AddUserToProject(): JSX.Element { function AddUserToProject(props: { projectName: string }): JSX.Element {
const [name, setName] = useState(""); const [name, setName] = useState("");
const [users, setUsers] = useState<string[]>([]); const [users, setUsers] = useState<string[]>([]);
const [role, setRole] = useState(""); const [role, setRole] = useState("");
@ -18,7 +17,7 @@ function AddUserToProject(): JSX.Element {
const handleClick = (): boolean => { const handleClick = (): boolean => {
const newMember: NewProjMember = { const newMember: NewProjMember = {
username: name, username: name,
projectname: localStorage.getItem("projectName") ?? "", projectname: props.projectName,
role: role, role: role,
}; };
return AddMember({ memberToAdd: newMember }); return AddMember({ memberToAdd: newMember });
@ -33,13 +32,13 @@ function AddUserToProject(): JSX.Element {
Role chosen: [{role}] Role chosen: [{role}]
</p> </p>
<p className="pb-4 mb-2 text-center font-bold text-[18px]"> <p className="pb-4 mb-2 text-center font-bold text-[18px]">
Project chosen: [{localStorage.getItem("projectName") ?? ""}] Project chosen: [{props.projectName}]
</p> </p>
<p className="p-1">Choose role:</p> <p className="p-1">Choose role:</p>
<div className="border-2 border-black p-2 rounded-xl text-center h-[10h] w-[16vh]"> <div className="border-2 border-black p-2 rounded-xl text-center h-[10h] w-[16] overflow-auto">
<ul className="text-center items-center font-medium space-y-2"> <ul className="text-center items-center font-medium space-y-2">
<li <li
className="h-[10h] w-[14vh] items-start p-1 border-2 border-black rounded-full bg-orange-200 hover:bg-orange-600 hover:text-slate-100 hover:cursor-pointer" className="h-[10] w-[14] items-start px-2 py-1 border-2 border-black rounded-full bg-orange-200 hover:bg-orange-600 hover:text-slate-100 hover:cursor-pointer"
onClick={() => { onClick={() => {
setRole("member"); setRole("member");
}} }}
@ -47,7 +46,7 @@ function AddUserToProject(): JSX.Element {
{"Member"} {"Member"}
</li> </li>
<li <li
className="h-[10h] w-[14vh] items-start p-1 border-2 border-black rounded-full bg-orange-200 hover:bg-orange-600 hover:text-slate-100 hover:cursor-pointer" className="h-[10] w-[14] items-start px-2 py-1 border-2 border-black rounded-full bg-orange-200 hover:bg-orange-600 hover:text-slate-100 hover:cursor-pointer"
onClick={() => { onClick={() => {
setRole("project_manager"); setRole("project_manager");
}} }}

View file

@ -0,0 +1,37 @@
import { APIResponse, api } from "../API/API";
export interface ProjectRoleChange {
username: string;
role: "project_manager" | "member" | "";
projectname: string;
}
export default function ChangeRole(roleChangeInfo: ProjectRoleChange): void {
if (
roleChangeInfo.username === "" ||
roleChangeInfo.role === "" ||
roleChangeInfo.projectname === ""
) {
// FOR DEBUG
// console.log(roleChangeInfo.role + ": Role");
// console.log(roleChangeInfo.projectname + ": P-Name");
// console.log(roleChangeInfo.username + ": U-name");
alert("You have to select a role");
return;
}
api
.changeUserRole(roleChangeInfo, localStorage.getItem("accessToken") ?? "")
.then((response: APIResponse<void>) => {
if (response.success) {
alert("Role changed successfully");
location.reload();
} else {
alert(response.message);
console.error(response.message);
}
})
.catch((error) => {
alert(error);
console.error("An error occurred during change:", error);
});
}

View file

@ -0,0 +1,73 @@
import { useState } from "react";
import Button from "./Button";
import ChangeRole, { ProjectRoleChange } from "./ChangeRole";
export default function ChangeRoles(props: {
projectName: string;
username: string;
}): JSX.Element {
const [selectedRole, setSelectedRole] = useState<
"project_manager" | "member" | ""
>("");
const handleRoleChange = (
event: React.ChangeEvent<HTMLInputElement>,
): void => {
if (event.target.value === "member") {
setSelectedRole(event.target.value);
} else if (event.target.value === "project_manager") {
setSelectedRole(event.target.value);
}
};
const handleSubmit = (event: React.FormEvent<HTMLFormElement>): void => {
event.preventDefault();
const roleChangeInfo: ProjectRoleChange = {
username: props.username,
projectname: props.projectName,
role: selectedRole,
};
ChangeRole(roleChangeInfo);
};
return (
<div className="overflow-auto rounded-lg">
<h1 className="font-bold text-[20px]">Select role:</h1>
<form onSubmit={handleSubmit}>
<div className="h-[7vh] self-start text-left font-medium overflow-auto border-2 border-black rounded-lg p-2">
<div className="hover:font-bold">
<label>
<input
type="radio"
value="project_manager"
checked={selectedRole === "project_manager"}
onChange={handleRoleChange}
className="ml-2 mr-2 mb-3"
/>
Project manager
</label>
</div>
<div className="hover:font-bold">
<label>
<input
type="radio"
value="member"
checked={selectedRole === "member"}
onChange={handleRoleChange}
className="ml-2 mr-2"
/>
Member
</label>
</div>
</div>
<Button
text="Change"
onClick={(): void => {
return;
}}
type="submit"
/>
</form>
</div>
);
}

View file

@ -1,61 +1,26 @@
import React, { useState } from "react"; import { APIResponse, api } from "../API/API";
import InputField from "./InputField"; import { StrNameChange } from "../Types/goTypes";
import { api } from "../API/API";
function ChangeUsername(): JSX.Element {
const [newUsername, setNewUsername] = useState("");
const [errorMessage, setErrorMessage] = useState("");
const handleChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
setNewUsername(e.target.value);
};
const handleSubmit = async (): Promise<void> => {
try {
// Call the API function to change the username
const token = localStorage.getItem("accessToken");
if (!token) {
throw new Error("Access token not found");
}
const response = await api.changeUserName(
{ prevName: "currentName", newName: newUsername },
token,
);
function ChangeUsername(props: { nameChange: StrNameChange }): void {
if (props.nameChange.newName === "") {
alert("You have to select a new name");
return;
}
api
.changeUserName(props.nameChange, localStorage.getItem("accessToken") ?? "")
.then((response: APIResponse<void>) => {
if (response.success) { if (response.success) {
// Optionally, add a success message or redirect the user alert("Name changed successfully");
console.log("Username changed successfully"); location.reload();
} else { } else {
// Handle the error message alert("Name not changed");
console.error("Failed to change username:", response.message); console.error(response.message);
setErrorMessage(response.message ?? "Failed to change username");
} }
} catch (error) { })
console.error("Error changing username:", error); .catch((error) => {
// Optionally, handle the error alert("Name not changed");
setErrorMessage("Failed to change username"); console.error("An error occurred during change:", error);
}
};
const handleButtonClick = (): void => {
handleSubmit().catch((error) => {
console.error("Error in handleSubmit:", error);
}); });
};
return (
<div>
<InputField
label="New Username"
type="text"
value={newUsername}
onChange={handleChange}
/>
{errorMessage && <div>{errorMessage}</div>}
<button onClick={handleButtonClick}>Update Username</button>
</div>
);
} }
export default ChangeUsername; export default ChangeUsername;

View file

@ -0,0 +1,33 @@
import { api, APIResponse } from "../API/API";
/**
* Use to delete a project from the system
* @param {string} props.projectToDelete - The projectname of project to delete
* @returns {void} Nothing
* @example
* const exampleProjectName = "project";
* DeleteProject({ projectToDelete: exampleProjectName });
*/
function DeleteProject(props: { projectToDelete: string }): void {
api
.removeProject(
props.projectToDelete,
localStorage.getItem("accessToken") ?? "",
)
.then((response: APIResponse<string>) => {
if (response.success) {
alert("Project has been deleted!");
location.reload();
} else {
alert("Project has not been deleted");
console.error(response.message);
}
})
.catch((error) => {
alert("project has not been deleted");
console.error("An error occurred during deletion:", error);
});
}
export default DeleteProject;

View file

@ -3,7 +3,7 @@ import { api, APIResponse } from "../API/API";
/** /**
* Use to remove a user from the system * Use to remove a user from the system
* @param props - The username of user to remove * @param {string} props.usernameToDelete - The username of user to remove
* @returns {boolean} True if removed, false if not * @returns {boolean} True if removed, false if not
* @example * @example
* const exampleUsername = "user"; * const exampleUsername = "user";
@ -29,7 +29,7 @@ function DeleteUser(props: { usernameToDelete: string }): boolean {
}) })
.catch((error) => { .catch((error) => {
alert("User has not been deleted"); alert("User has not been deleted");
console.error("An error occurred during creation:", error); console.error("An error occurred during deletion:", error);
}); });
return removed; return removed;
} }

View file

@ -2,6 +2,7 @@ import { useState } from "react";
import { Project } from "../Types/goTypes"; import { Project } from "../Types/goTypes";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import GetProjects from "./GetProjects"; import GetProjects from "./GetProjects";
import { api } from "../API/API";
/** /**
* Renders a component that displays the projects a user is a part of and links to the projects start-page. * Renders a component that displays the projects a user is a part of and links to the projects start-page.
@ -11,22 +12,20 @@ function DisplayUserProject(): JSX.Element {
const [projects, setProjects] = useState<Project[]>([]); const [projects, setProjects] = useState<Project[]>([]);
const navigate = useNavigate(); const navigate = useNavigate();
const getProjects = async (): Promise<void> => { GetProjects({
const token = localStorage.getItem("accessToken") ?? ""; setProjectsProp: setProjects,
const response = await api.getUserProjects(token); username: localStorage.getItem("username") ?? "",
console.log(response); });
if (response.success) {
setProjects(response.data ?? []);
} else {
console.error(response.message);
}
};
const handleProjectClick = async (projectName: string): Promise<void> => { const handleProjectClick = async (projectName: string): Promise<void> => {
const token = localStorage.getItem("accessToken") ?? ""; const token = localStorage.getItem("accessToken") ?? "";
const response = await api.checkIfProjectManager(projectName, token); const response = await api.checkIfProjectManager(projectName, token);
console.log(response.data);
if (response.success) { if (response.success) {
if (response.data) { if (
(response.data as unknown as { isProjectManager: boolean })
.isProjectManager
) {
navigate(`/PMProjectPage/${projectName}`); navigate(`/PMProjectPage/${projectName}`);
} else { } else {
navigate(`/project/${projectName}`); navigate(`/project/${projectName}`);
@ -37,11 +36,6 @@ function DisplayUserProject(): JSX.Element {
} }
}; };
// Call getProjects when the component mounts
useEffect(() => {
void getProjects();
}, []);
return ( return (
<> <>
<h1 className="font-bold text-[30px] mb-[20px]">Your Projects</h1> <h1 className="font-bold text-[30px] mb-[20px]">Your Projects</h1>

View file

@ -0,0 +1,59 @@
import { Dispatch, SetStateAction, useEffect } from "react";
import { api } from "../API/API";
/**
* Interface for reported time per category + total time reported
*/
export interface projectTimes {
admin: number;
development: number;
meeting: number;
own_work: number;
study: number;
testing: number;
totalTime?: number;
}
/**
* Gets all reported times for this project
* @param {Dispatch} props.setTimesProp - A setStateAction for the map you want to put times in
* @param {string} props.projectName - Username
* @returns {void} Nothing
* @example
* const projectName = "Example";
* const [times, setTimes] = useState<Times>();
* GetProjectTimes({ setTimesProp: setTimes, projectName: projectName });
*/
function GetProjectTimes(props: {
setTimesProp: Dispatch<SetStateAction<projectTimes | undefined>>;
projectName: string;
}): void {
const setTimes: Dispatch<SetStateAction<projectTimes | undefined>> =
props.setTimesProp;
useEffect(() => {
const fetchUsers = async (): Promise<void> => {
try {
const token = localStorage.getItem("accessToken") ?? "";
const response = await api.getProjectTimes(props.projectName, token);
if (response.success && response.data) {
// Calculates total time reported
response.data.totalTime = response.data.admin;
response.data.totalTime += response.data.development;
response.data.totalTime += response.data.meeting;
response.data.totalTime += response.data.own_work;
response.data.totalTime += response.data.study;
response.data.totalTime += response.data.testing;
setTimes(response.data);
} else {
console.error("Failed to fetch project times:", response.message);
}
} catch (error) {
console.error("Error fetching times:", error);
}
};
void fetchUsers();
}, [props.projectName, setTimes]);
}
export default GetProjectTimes;

View file

@ -4,11 +4,13 @@ import { api } from "../API/API";
/** /**
* Gets all projects that user is a member of * Gets all projects that user is a member of
* @param props - A setStateAction for the array you want to put projects in * @param {Dispatch} props.setProjectsProp - A setStateAction for the array you want to put projects in
* @param {string} props.username - Username
* @returns {void} Nothing * @returns {void} Nothing
* @example * @example
* const username = "Example";
* const [projects, setProjects] = useState<Project[]>([]); * const [projects, setProjects] = useState<Project[]>([]);
* GetAllUsers({ setProjectsProp: setProjects }); * GetProjects({ setProjectsProp: setProjects, username: username });
*/ */
function GetProjects(props: { function GetProjects(props: {
setProjectsProp: Dispatch<React.SetStateAction<Project[]>>; setProjectsProp: Dispatch<React.SetStateAction<Project[]>>;

View file

@ -1,20 +1,25 @@
import { Dispatch, useEffect } from "react"; import { Dispatch, useEffect } from "react";
import { UserProjectMember } from "../Types/goTypes";
import { api } from "../API/API"; import { api } from "../API/API";
export interface ProjectMember {
Username: string;
UserRole: string;
}
/** /**
* Gets all projects that user is a member of * Gets all members of a project
* @param props - A setStateAction for the array you want to put projects in * @param string - The project's name
* @param Dispatch - A setStateAction for the array you want to put members in
* @returns {void} Nothing * @returns {void} Nothing
* @example * @example
* const [projects, setProjects] = useState<Project[]>([]); * const [users, setUsers] = useState<User[]>([]);
* GetAllUsers({ setProjectsProp: setProjects }); * GetUsersInProject({ projectName: props.projectname, setUsersProp: setUsers });
*/ */
function GetUsersInProject(props: { function GetUsersInProject(props: {
projectName: string; projectName: string;
setUsersProp: Dispatch<React.SetStateAction<UserProjectMember[]>>; setUsersProp: Dispatch<React.SetStateAction<ProjectMember[]>>;
}): void { }): void {
const setUsers: Dispatch<React.SetStateAction<UserProjectMember[]>> = const setUsers: Dispatch<React.SetStateAction<ProjectMember[]>> =
props.setUsersProp; props.setUsersProp;
useEffect(() => { useEffect(() => {
const fetchUsers = async (): Promise<void> => { const fetchUsers = async (): Promise<void> => {
@ -24,10 +29,10 @@ function GetUsersInProject(props: {
if (response.success) { if (response.success) {
setUsers(response.data ?? []); setUsers(response.data ?? []);
} else { } else {
console.error("Failed to fetch projects:", response.message); console.error("Failed to fetch members:", response.message);
} }
} catch (error) { } catch (error) {
console.error("Error fetching projects:", error); console.error("Error fetching members:", error);
} }
}; };
void fetchUsers(); void fetchUsers();

View file

@ -19,7 +19,7 @@ function InputField(props: {
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void; onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
}): JSX.Element { }): JSX.Element {
return ( return (
<div className="mb-4"> <div className="">
<label <label
className="block text-gray-700 text-sm font-sans font-bold mb-2" className="block text-gray-700 text-sm font-sans font-bold mb-2"
htmlFor={props.label} htmlFor={props.label}

View file

@ -25,22 +25,24 @@ function Login(props: {
}): JSX.Element { }): JSX.Element {
return ( return (
<form className="flex flex-col items-center" onSubmit={props.handleSubmit}> <form className="flex flex-col items-center" onSubmit={props.handleSubmit}>
<InputField <div className="space-y-3">
type="text" <InputField
label="Username" type="text"
onChange={(e) => { label="Username"
props.setUsername(e.target.value); onChange={(e) => {
}} props.setUsername(e.target.value);
value={props.username} }}
/> value={props.username}
<InputField />
type="password" <InputField
label="Password" type="password"
onChange={(e) => { label="Password"
props.setPassword(e.target.value); onChange={(e) => {
}} props.setPassword(e.target.value);
value={props.password} }}
/> value={props.password}
/>
</div>
<Button <Button
text="Login" text="Login"
onClick={(): void => { onClick={(): void => {

View file

@ -0,0 +1,72 @@
import Button from "./Button";
import DeleteUser from "./DeleteUser";
import UserProjectListAdmin from "./UserProjectListAdmin";
import { useState } from "react";
import ChangeRoleView from "./ChangeRoleView";
function MemberInfoModal(props: {
projectName: string;
username: string;
onClose: () => void;
}): JSX.Element {
const [showRoles, setShowRoles] = useState(false);
const handleChangeRole = (): void => {
if (showRoles) {
setShowRoles(false);
} else {
setShowRoles(true);
}
};
return (
<div
className="fixed inset-0 bg-black bg-opacity-30 backdrop-blur-sm
flex justify-center items-center"
>
<div className="border-4 border-black bg-white rounded-lg text-center flex flex-col">
<div className="mx-10">
<p className="font-bold text-[30px]">{props.username}</p>
<p
className="hover:font-bold hover:cursor-pointer underline"
onClick={handleChangeRole}
>
(Change Role)
</p>
{showRoles && (
<ChangeRoleView
projectName={props.projectName}
username={props.username}
/>
)}
<h2 className="font-bold text-[20px]">Member of these projects:</h2>
<UserProjectListAdmin username={props.username} />
<div className="items-center space-x-6">
<Button
text={"Delete"}
onClick={function (): void {
if (
window.confirm("Are you sure you want to delete this user?")
) {
DeleteUser({
usernameToDelete: props.username,
});
}
}}
type="button"
/>
<Button
text={"Close"}
onClick={function (): void {
setShowRoles(false);
props.onClose();
}}
type="button"
/>
</div>
</div>
</div>
</div>
);
}
export default MemberInfoModal;

View file

@ -1,31 +1,54 @@
import { useState } from "react"; import { useEffect, useRef, useState } from "react";
import Button from "./Button"; import Button from "./Button";
import { UserProjectMember } from "../Types/goTypes"; import GetUsersInProject, { ProjectMember } from "./GetUsersInProject";
import GetUsersInProject from "./GetUsersInProject";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import GetProjectTimes, { projectTimes } from "./GetProjectTimes";
import DeleteProject from "./DeleteProject";
function ProjectInfoModal(props: { function ProjectInfoModal(props: {
isVisible: boolean;
projectname: string; projectname: string;
onClose: () => void; onClose: () => void;
onClick: (username: string) => void; onClick: (username: string) => void;
}): JSX.Element { }): JSX.Element {
const [users, setUsers] = useState<UserProjectMember[]>([]); const [users, setUsers] = useState<ProjectMember[]>([]);
const [times, setTimes] = useState<projectTimes>();
const totalTime = useRef(0);
GetUsersInProject({ projectName: props.projectname, setUsersProp: setUsers }); GetUsersInProject({ projectName: props.projectname, setUsersProp: setUsers });
if (!props.isVisible) return <></>;
GetProjectTimes({ setTimesProp: setTimes, projectName: props.projectname });
useEffect(() => {
if (times?.totalTime !== undefined) {
totalTime.current = times.totalTime;
}
}, [times]);
return ( return (
<div <div
className="fixed inset-0 bg-black bg-opacity-30 backdrop-blur-sm className="fixed inset-0 bg-black bg-opacity-30 backdrop-blur-sm
flex justify-center items-center" flex justify-center items-center"
> >
<div className="border-4 border-black bg-white p-2 rounded-2xl text-center h-[47vh] w-[40] flex flex-col"> <div className="border-4 border-black bg-white p-2 rounded-2xl text-center h-[61vh] w-[40] overflow-auto">
<div className="pl-20 pr-20"> <div className="pl-10 pr-10">
<h1 className="font-bold text-[32px] mb-[20px]"> <h1 className="font-bold text-[32px] mb-[20px]">
{localStorage.getItem("projectName") ?? ""} {props.projectname}
</h1> </h1>
<h2 className="font-bold text-[24px] mb-[20px]">Project members:</h2> <div className="p-1 text-center">
<div className="border-2 border-black p-2 rounded-lg text-center overflow-scroll h-[26vh]"> <h2 className="text-[20px] font-bold">Statistics:</h2>
</div>
<div className="border-2 border-black rounded-lg h-[8vh] text-left divide-y-2 flex flex-col overflow-auto mx-10">
<p className="p-2">Number of members: {users.length}</p>
<p className="p-2">
Total time reported:{" "}
{Math.floor(totalTime.current / 60 / 24) + " d "}
{Math.floor((totalTime.current / 60) % 24) + " h "}
{(totalTime.current % 60) + " m "}
</p>
</div>
<div className="h-[6vh] p-7 text-center">
<h2 className="text-[20px] font-bold">Project members:</h2>
</div>
<div className="border-2 border-black p-2 rounded-lg text-center overflow-auto h-[24vh] mx-10">
<ul className="text-left font-medium space-y-2"> <ul className="text-left font-medium space-y-2">
<div></div> <div></div>
{users.map((user) => ( {users.map((user) => (
@ -45,31 +68,44 @@ function ProjectInfoModal(props: {
))} ))}
</ul> </ul>
</div> </div>
</div> <div className="space-x-5 my-2">
<div className="space-x-16">
<Button
text={"Delete"}
onClick={function (): void {
//DELETE PROJECT
}}
type="button"
/>
<Link to={"/adminProjectAddMember"}>
<Button <Button
text={"Add Member"} text={"Delete"}
onClick={function (): void { onClick={function (): void {
return; if (
window.confirm(
"Are you sure you want to delete this project?",
)
) {
DeleteProject({
projectToDelete: props.projectname,
});
}
}} }}
type="button" type="button"
/> />
</Link> <Link
<Button to={{
text={"Close"} pathname: "/adminProjectAddMember",
onClick={function (): void { search: props.projectname,
props.onClose(); }}
}} >
type="button" <Button
/> text={"Add Member"}
onClick={function (): void {
return;
}}
type="button"
/>
</Link>
<Button
text={"Close"}
onClick={function (): void {
props.onClose();
}}
type="button"
/>
</div>
</div> </div>
</div> </div>
</div> </div>

View file

@ -1,7 +1,7 @@
import { useState } from "react"; import { useState } from "react";
import { NewProject } from "../Types/goTypes"; import { NewProject } from "../Types/goTypes";
import ProjectInfoModal from "./ProjectInfoModal"; import ProjectInfoModal from "./ProjectInfoModal";
import UserInfoModal from "./UserInfoModal"; import MemberInfoModal from "./MemberInfoModal";
/** /**
* A list of projects for admin manage projects page, that sets an onClick * A list of projects for admin manage projects page, that sets an onClick
@ -18,7 +18,7 @@ export function ProjectListAdmin(props: {
projects: NewProject[]; projects: NewProject[];
}): JSX.Element { }): JSX.Element {
const [projectModalVisible, setProjectModalVisible] = useState(false); const [projectModalVisible, setProjectModalVisible] = useState(false);
const [projectname, setProjectname] = useState(""); const [projectName, setProjectName] = useState("");
const [userModalVisible, setUserModalVisible] = useState(false); const [userModalVisible, setUserModalVisible] = useState(false);
const [username, setUsername] = useState(""); const [username, setUsername] = useState("");
@ -28,39 +28,36 @@ export function ProjectListAdmin(props: {
}; };
const handleClickProject = (projectname: string): void => { const handleClickProject = (projectname: string): void => {
setProjectname(projectname); setProjectName(projectname);
localStorage.setItem("projectName", projectname);
setProjectModalVisible(true); setProjectModalVisible(true);
}; };
const handleCloseProject = (): void => { const handleCloseProject = (): void => {
setProjectname(""); setProjectName("");
setProjectModalVisible(false); setProjectModalVisible(false);
}; };
const handleCloseUser = (): void => { const handleCloseUser = (): void => {
setProjectname(""); setUsername("");
setUserModalVisible(false); setUserModalVisible(false);
}; };
return ( return (
<> <>
<ProjectInfoModal {projectModalVisible && (
onClose={handleCloseProject} <ProjectInfoModal
onClick={handleClickUser} onClose={handleCloseProject}
isVisible={projectModalVisible} onClick={handleClickUser}
projectname={projectname} projectname={projectName}
/> />
<UserInfoModal )}
manageMember={true} {userModalVisible && (
onClose={handleCloseUser} <MemberInfoModal
//TODO: CHANGE TO REMOVE USER FROM PROJECT onClose={handleCloseUser}
onDelete={() => { username={username}
return; projectName={projectName}
}} />
isVisible={userModalVisible} )}
username={username}
/>
<div> <div>
<ul className="font-bold underline text-[30px] cursor-pointer padding"> <ul className="font-bold underline text-[30px] cursor-pointer padding">
{props.projects.map((project) => ( {props.projects.map((project) => (

View file

@ -1,31 +1,15 @@
import { useEffect, useState } from "react"; import { useState } from "react";
import { Link, useParams } from "react-router-dom"; import { Link, useParams } from "react-router-dom";
import { api } from "../API/API"; import GetUsersInProject, { ProjectMember } from "./GetUsersInProject";
import { UserProjectMember } from "../Types/goTypes";
function ProjectMembers(): JSX.Element { function ProjectMembers(): JSX.Element {
const { projectName } = useParams(); const { projectName } = useParams();
const [projectMembers, setProjectMembers] = useState<UserProjectMember[]>([]); const [projectMembers, setProjectMembers] = useState<ProjectMember[]>([]);
useEffect(() => { GetUsersInProject({
const getProjectMembers = async (): Promise<void> => { projectName: projectName ?? "",
const token = localStorage.getItem("accessToken") ?? ""; setUsersProp: setProjectMembers,
const response = await api.getAllUsersProject(projectName ?? "", token); });
console.log(response);
if (response.success) {
setProjectMembers(response.data ?? []);
} else {
console.error(response.message);
}
};
void getProjectMembers();
}, [projectName]);
interface ProjectMember {
Username: string;
UserRole: string;
}
return ( return (
<> <>

View file

@ -22,6 +22,8 @@ export default function Register(): JSX.Element {
const response = await api.registerUser(newUser); const response = await api.registerUser(newUser);
if (response.success) { if (response.success) {
alert("User added!"); alert("User added!");
setPassword("");
setUsername("");
} else { } else {
alert("User not added"); alert("User not added");
setErrMessage(response.message ?? "Unknown error"); setErrMessage(response.message ?? "Unknown error");
@ -47,22 +49,24 @@ export default function Register(): JSX.Element {
<h3 className="pb-4 mb-2 text-center font-bold text-[18px]"> <h3 className="pb-4 mb-2 text-center font-bold text-[18px]">
Register New User Register New User
</h3> </h3>
<InputField <div className="space-y-3">
label="Username" <InputField
type="text" label="Username"
value={username ?? ""} type="text"
onChange={(e) => { value={username ?? ""}
setUsername(e.target.value); onChange={(e) => {
}} setUsername(e.target.value);
/> }}
<InputField />
label="Password" <InputField
type="password" label="Password"
value={password ?? ""} type="password"
onChange={(e) => { value={password ?? ""}
setPassword(e.target.value); onChange={(e) => {
}} setPassword(e.target.value);
/> }}
/>
</div>
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<Button <Button
text="Register" text="Register"

View file

@ -1,72 +1,99 @@
import { Link } from "react-router-dom";
import Button from "./Button"; import Button from "./Button";
import DeleteUser from "./DeleteUser"; import DeleteUser from "./DeleteUser";
import UserProjectListAdmin from "./UserProjectListAdmin"; import UserProjectListAdmin from "./UserProjectListAdmin";
import { useState } from "react";
import InputField from "./InputField";
import ChangeUsername from "./ChangeUsername";
import { StrNameChange } from "../Types/goTypes";
function UserInfoModal(props: { function UserInfoModal(props: {
isVisible: boolean; isVisible: boolean;
manageMember: boolean;
username: string; username: string;
onClose: () => void; onClose: () => void;
onDelete: (username: string) => void;
}): JSX.Element { }): JSX.Element {
if (!props.isVisible) return <></>; const [showInput, setShowInput] = useState(false);
const ManageUserOrMember = (check: boolean): JSX.Element => { const [newUsername, setNewUsername] = useState("");
if (check) { if (!props.isVisible) {
return ( return <></>;
<Link to="/AdminChangeRole"> }
<p className="mb-[20px] hover:font-bold hover:cursor-pointer underline">
(Change Role) const handleChangeNameView = (): void => {
</p> if (showInput) {
</Link> setShowInput(false);
); } else {
setShowInput(true);
} }
return (
<Link to="/AdminChangeUserName">
<p className="mb-[20px] hover:font-bold hover:cursor-pointer underline">
(Change Username)
</p>
</Link>
);
}; };
const handleClickChangeName = (): void => {
const nameChange: StrNameChange = {
prevName: props.username,
newName: newUsername,
};
ChangeUsername({ nameChange: nameChange });
};
return ( return (
<div <div
className="fixed inset-0 bg-black bg-opacity-30 backdrop-blur-sm className="fixed inset-0 bg-black bg-opacity-30 backdrop-blur-sm
flex justify-center items-center" flex justify-center items-center"
> >
<div className="border-4 border-black bg-white p-2 rounded-lg text-center flex flex-col"> <div className="border-4 border-black bg-white rounded-lg text-center flex flex-col">
<p className="font-bold text-[30px]">{props.username}</p> <div className="mx-10">
{ManageUserOrMember(props.manageMember)} <p className="font-bold text-[30px]">{props.username}</p>
<div> <p
<h2 className="font-bold text-[22px] mb-[20px]"> className="mb-[10px] hover:font-bold hover:cursor-pointer underline"
Member of these projects: onClick={handleChangeNameView}
</h2> >
<div className="pr-6 pl-6"> (Change Username)
<UserProjectListAdmin username={props.username} /> </p>
{showInput && (
<div>
<InputField
label={"New username"}
type={"text"}
value={newUsername}
onChange={function (e): void {
e.defaultPrevented;
setNewUsername(e.target.value);
}}
/>
<Button
text={"Change"}
onClick={function (): void {
handleClickChangeName();
}}
type={"submit"}
/>
</div>
)}
<h2 className="font-bold text-[20px]">Member of these projects:</h2>
<UserProjectListAdmin username={props.username} />
<div className="items-center space-x-6">
<Button
text={"Delete"}
onClick={function (): void {
if (
window.confirm("Are you sure you want to delete this user?")
) {
DeleteUser({
usernameToDelete: props.username,
});
}
}}
type="button"
/>
<Button
text={"Close"}
onClick={function (): void {
setNewUsername("");
setShowInput(false);
props.onClose();
}}
type="button"
/>
</div> </div>
</div> </div>
<div className="items-center space-x-6 pr-6 pl-6">
<Button
text={"Delete"}
onClick={function (): void {
if (
window.confirm("Are you sure you want to delete this user?")
) {
DeleteUser({
usernameToDelete: props.username,
});
}
}}
type="button"
/>
<Button
text={"Close"}
onClick={function (): void {
props.onClose();
}}
type="button"
/>
</div>
</div> </div>
</div> </div>
); );

View file

@ -1,6 +1,5 @@
import { useState } from "react"; import { useState } from "react";
import UserInfoModal from "./UserInfoModal"; import UserInfoModal from "./UserInfoModal";
import DeleteUser from "./DeleteUser";
/** /**
* A list of users for admin manage users page, that sets an onClick * A list of users for admin manage users page, that sets an onClick
@ -30,9 +29,7 @@ export function UserListAdmin(props: { users: string[] }): JSX.Element {
return ( return (
<> <>
<UserInfoModal <UserInfoModal
manageMember={false}
onClose={handleClose} onClose={handleClose}
onDelete={() => DeleteUser}
isVisible={modalVisible} isVisible={modalVisible}
username={username} username={username}
/> />

View file

@ -1,35 +1,17 @@
import { useEffect, useState } from "react"; import { useState } from "react";
import { api } from "../API/API";
import { Project } from "../Types/goTypes"; import { Project } from "../Types/goTypes";
import GetProjects from "./GetProjects";
function UserProjectListAdmin(props: { username: string }): JSX.Element { function UserProjectListAdmin(props: { username: string }): JSX.Element {
const [projects, setProjects] = useState<Project[]>([]); const [projects, setProjects] = useState<Project[]>([]);
useEffect(() => { GetProjects({ setProjectsProp: setProjects, username: props.username });
const fetchProjects = async (): Promise<void> => {
try {
const token = localStorage.getItem("accessToken") ?? "";
const username = props.username;
const response = await api.getUserProjects(username, token);
if (response.success) {
setProjects(response.data ?? []);
} else {
console.error("Failed to fetch projects:", response.message);
}
} catch (error) {
console.error("Error fetching projects:", error);
}
};
void fetchProjects();
}, [props.username]);
return ( return (
<div className="border-2 border-black bg-white p-2 rounded-lg text-center"> <div className="border-2 border-black bg-white rounded-lg text-left overflow-auto h-[15vh] font-medium">
<ul> <ul className="divide-y-2">
{projects.map((project) => ( {projects.map((project) => (
<li key={project.id}> <li className="mx-2 my-1" key={project.id}>
<span>{project.name}</span> <span>{project.name}</span>
</li> </li>
))} ))}

View file

@ -1,28 +0,0 @@
import BackButton from "../../Components/BackButton";
import BasicWindow from "../../Components/BasicWindow";
import Button from "../../Components/Button";
import ChangeUsername from "../../Components/ChangeUsername";
function AdminChangeUsername(): JSX.Element {
const content = (
<>
<ChangeUsername />
</>
);
const buttons = (
<>
<Button
text="Finish"
onClick={(): void => {
return;
}}
type="button"
/>
<BackButton />
</>
);
return <BasicWindow content={content} buttons={buttons} />;
}
export default AdminChangeUsername;

View file

@ -1,11 +1,11 @@
import { useLocation } from "react-router-dom";
import AddUserToProject from "../../Components/AddUserToProject"; import AddUserToProject from "../../Components/AddUserToProject";
import BasicWindow from "../../Components/BasicWindow"; import BasicWindow from "../../Components/BasicWindow";
function AdminProjectAddMember(): JSX.Element { function AdminProjectAddMember(): JSX.Element {
const content = <AddUserToProject />; const projectName = useLocation().search.slice(1);
const content = <AddUserToProject projectName={projectName} />;
const buttons = <></>; const buttons = <></>;
return <BasicWindow content={content} buttons={buttons} />; return <BasicWindow content={content} buttons={buttons} />;
} }
export default AdminProjectAddMember; export default AdminProjectAddMember;

View file

@ -1,23 +0,0 @@
import BackButton from "../../Components/BackButton";
import BasicWindow from "../../Components/BasicWindow";
import Button from "../../Components/Button";
function AdminProjectChangeUserRole(): JSX.Element {
const content = <></>;
const buttons = (
<>
<Button
text="Change"
onClick={(): void => {
return;
}}
type="button"
/>
<BackButton />
</>
);
return <BasicWindow content={content} buttons={buttons} />;
}
export default AdminProjectChangeUserRole;

View file

@ -1,23 +0,0 @@
import BackButton from "../../Components/BackButton";
import BasicWindow from "../../Components/BasicWindow";
import Button from "../../Components/Button";
function AdminProjectManageMembers(): JSX.Element {
const content = <></>;
const buttons = (
<>
<Button
text="Add Member"
onClick={(): void => {
return;
}}
type="button"
/>
<BackButton />
</>
);
return <BasicWindow content={content} buttons={buttons} />;
}
export default AdminProjectManageMembers;

View file

@ -1,33 +0,0 @@
import { useParams } from "react-router-dom";
import { api } from "../../API/API";
import BackButton from "../../Components/BackButton";
import BasicWindow from "../../Components/BasicWindow";
import Button from "../../Components/Button";
async function handleDeleteProject(
projectName: string,
token: string,
): Promise<void> {
await api.removeProject(projectName, token);
}
function AdminProjectPage(): JSX.Element {
const content = <></>;
const { projectName } = useParams();
const token = localStorage.getItem("accessToken");
const buttons = (
<>
<Button
text="Delete"
onClick={() => handleDeleteProject(projectName, token)}
type="button"
/>
<BackButton />
</>
);
return <BasicWindow content={content} buttons={buttons} />;
}
export default AdminProjectPage;

View file

@ -1,23 +0,0 @@
import BackButton from "../../Components/BackButton";
import BasicWindow from "../../Components/BasicWindow";
import Button from "../../Components/Button";
function AdminProjectViewMemberInfo(): JSX.Element {
const content = <></>;
const buttons = (
<>
<Button
text="Remove"
onClick={(): void => {
return;
}}
type="button"
/>
<BackButton />
</>
);
return <BasicWindow content={content} buttons={buttons} />;
}
export default AdminProjectViewMemberInfo;

View file

@ -1,28 +0,0 @@
import BasicWindow from "../../Components/BasicWindow";
import Button from "../../Components/Button";
import BackButton from "../../Components/BackButton";
import UserProjectListAdmin from "../../Components/UserProjectListAdmin";
function AdminViewUserInfo(): JSX.Element {
const content = (
<>
<UserProjectListAdmin />
</>
);
const buttons = (
<>
<Button
text="Delete"
onClick={(): void => {
return;
}}
type="button"
/>
<BackButton />
</>
);
return <BasicWindow content={content} buttons={buttons} />;
}
export default AdminViewUserInfo;

View file

@ -18,17 +18,11 @@ import PMTotalTimeRole from "./Pages/ProjectManagerPages/PMTotalTimeRole.tsx";
import PMUnsignedReports from "./Pages/ProjectManagerPages/PMUnsignedReports.tsx"; import PMUnsignedReports from "./Pages/ProjectManagerPages/PMUnsignedReports.tsx";
import PMViewUnsignedReport from "./Pages/ProjectManagerPages/PMViewUnsignedReport.tsx"; import PMViewUnsignedReport from "./Pages/ProjectManagerPages/PMViewUnsignedReport.tsx";
import AdminManageUsers from "./Pages/AdminPages/AdminManageUsers.tsx"; import AdminManageUsers from "./Pages/AdminPages/AdminManageUsers.tsx";
import AdminViewUserInfo from "./Pages/AdminPages/AdminViewUserInfo.tsx";
import AdminManageProjects from "./Pages/AdminPages/AdminManageProjects.tsx"; import AdminManageProjects from "./Pages/AdminPages/AdminManageProjects.tsx";
import AdminAddProject from "./Pages/AdminPages/AdminAddProject.tsx"; import AdminAddProject from "./Pages/AdminPages/AdminAddProject.tsx";
import AdminAddUser from "./Pages/AdminPages/AdminAddUser.tsx"; import AdminAddUser from "./Pages/AdminPages/AdminAddUser.tsx";
import AdminChangeUsername from "./Pages/AdminPages/AdminChangeUsername.tsx";
import AdminProjectAddMember from "./Pages/AdminPages/AdminProjectAddMember.tsx"; import AdminProjectAddMember from "./Pages/AdminPages/AdminProjectAddMember.tsx";
import AdminProjectChangeUserRole from "./Pages/AdminPages/AdminProjectChangeUserRole.tsx";
import AdminProjectManageMembers from "./Pages/AdminPages/AdminProjectManageMembers.tsx";
import AdminProjectStatistics from "./Pages/AdminPages/AdminProjectStatistics.tsx"; import AdminProjectStatistics from "./Pages/AdminPages/AdminProjectStatistics.tsx";
import AdminProjectViewMemberInfo from "./Pages/AdminPages/AdminProjectViewMemberInfo.tsx";
import AdminProjectPage from "./Pages/AdminPages/AdminProjectPage.tsx";
import NotFoundPage from "./Pages/NotFoundPage.tsx"; import NotFoundPage from "./Pages/NotFoundPage.tsx";
import UnauthorizedPage from "./Pages/UnauthorizedPage.tsx"; import UnauthorizedPage from "./Pages/UnauthorizedPage.tsx";
import PMViewOtherUsersTR from "./Pages/ProjectManagerPages/PMViewOtherUsersTR.tsx"; import PMViewOtherUsersTR from "./Pages/ProjectManagerPages/PMViewOtherUsersTR.tsx";
@ -100,34 +94,14 @@ const router = createBrowserRouter([
path: "/PMViewUnsignedReport/:projectName/:username/:fetchedWeek", path: "/PMViewUnsignedReport/:projectName/:username/:fetchedWeek",
element: <PMViewUnsignedReport />, element: <PMViewUnsignedReport />,
}, },
{
path: "/adminChangeUsername",
element: <AdminChangeUsername />,
},
{ {
path: "/adminProjectAddMember", path: "/adminProjectAddMember",
element: <AdminProjectAddMember />, element: <AdminProjectAddMember />,
}, },
{
path: "/adminProjectChangeUserRole",
element: <AdminProjectChangeUserRole />,
},
{
path: "/adminProjectManageMembers",
element: <AdminProjectManageMembers />,
},
{
path: "/adminProjectPage",
element: <AdminProjectPage />,
},
{ {
path: "/adminProjectStatistics", path: "/adminProjectStatistics",
element: <AdminProjectStatistics />, element: <AdminProjectStatistics />,
}, },
{
path: "/adminProjectViewMembers",
element: <AdminProjectViewMemberInfo />,
},
{ {
path: "/addProject", path: "/addProject",
element: <AdminAddProject />, element: <AdminAddProject />,
@ -136,10 +110,6 @@ const router = createBrowserRouter([
path: "/adminAddUser", path: "/adminAddUser",
element: <AdminAddUser />, element: <AdminAddUser />,
}, },
{
path: "/adminUserInfo",
element: <AdminViewUserInfo />,
},
{ {
path: "/adminManageProject", path: "/adminManageProject",
element: <AdminManageProjects />, element: <AdminManageProjects />,