Merge branch 'master' into BumBranch
This commit is contained in:
commit
11341ce37e
89 changed files with 3457 additions and 2028 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
@ -14,9 +14,11 @@ diagram.puml
|
||||||
backend/*.png
|
backend/*.png
|
||||||
backend/*.jpg
|
backend/*.jpg
|
||||||
backend/*.svg
|
backend/*.svg
|
||||||
|
__pycache__
|
||||||
|
|
||||||
/go.work.sum
|
/go.work.sum
|
||||||
/package-lock.json
|
/package-lock.json
|
||||||
|
/backend/docs/swagger.json
|
||||||
|
|
||||||
# Test binary, built with `go test -c`
|
# Test binary, built with `go test -c`
|
||||||
*.test
|
*.test
|
||||||
|
|
|
@ -34,6 +34,7 @@ clean:
|
||||||
rm -f plantuml.jar
|
rm -f plantuml.jar
|
||||||
rm -f erd.png
|
rm -f erd.png
|
||||||
rm -f config.toml
|
rm -f config.toml
|
||||||
|
rm -f database.txt
|
||||||
|
|
||||||
# Test target
|
# Test target
|
||||||
test: db.sqlite3
|
test: db.sqlite3
|
||||||
|
@ -46,7 +47,7 @@ itest:
|
||||||
make build
|
make build
|
||||||
./bin/$(PROC_NAME) >/dev/null 2>&1 &
|
./bin/$(PROC_NAME) >/dev/null 2>&1 &
|
||||||
sleep 1 # Adjust if needed
|
sleep 1 # Adjust if needed
|
||||||
python ../testing.py
|
python ../testing/testing.py || pkill $(PROC_NAME)
|
||||||
pkill $(PROC_NAME)
|
pkill $(PROC_NAME)
|
||||||
|
|
||||||
# Get dependencies target
|
# Get dependencies target
|
||||||
|
@ -104,6 +105,17 @@ default: build
|
||||||
docs:
|
docs:
|
||||||
swag init -outputTypes go
|
swag init -outputTypes go
|
||||||
|
|
||||||
|
api: ./docs/swagger.json
|
||||||
|
rm ../frontend/src/API/GenApi.ts
|
||||||
|
npx swagger-typescript-api \
|
||||||
|
--api-class-name GenApi \
|
||||||
|
--path ./docs/swagger.json \
|
||||||
|
--output ../frontend/src/API \
|
||||||
|
--name GenApi.ts \
|
||||||
|
|
||||||
|
./docs/swagger.json:
|
||||||
|
swag init -outputTypes json
|
||||||
|
|
||||||
.PHONY: docfmt
|
.PHONY: docfmt
|
||||||
docfmt:
|
docfmt:
|
||||||
swag fmt
|
swag fmt
|
||||||
|
|
|
@ -21,21 +21,21 @@ const docTemplate = `{
|
||||||
"paths": {
|
"paths": {
|
||||||
"/login": {
|
"/login": {
|
||||||
"post": {
|
"post": {
|
||||||
"description": "logs the user in and returns a jwt token",
|
"description": "Logs in a user and returns a JWT token",
|
||||||
"consumes": [
|
"consumes": [
|
||||||
"application/json"
|
"application/json"
|
||||||
],
|
],
|
||||||
"produces": [
|
"produces": [
|
||||||
"text/plain"
|
"application/json"
|
||||||
],
|
],
|
||||||
"tags": [
|
"tags": [
|
||||||
"User"
|
"Auth"
|
||||||
],
|
],
|
||||||
"summary": "login",
|
"summary": "Login",
|
||||||
"parameters": [
|
"parameters": [
|
||||||
{
|
{
|
||||||
"description": "login info",
|
"description": "User credentials",
|
||||||
"name": "NewUser",
|
"name": "body",
|
||||||
"in": "body",
|
"in": "body",
|
||||||
"required": true,
|
"required": true,
|
||||||
"schema": {
|
"schema": {
|
||||||
|
@ -45,9 +45,9 @@ const docTemplate = `{
|
||||||
],
|
],
|
||||||
"responses": {
|
"responses": {
|
||||||
"200": {
|
"200": {
|
||||||
"description": "Successfully signed token for user",
|
"description": "JWT token",
|
||||||
"schema": {
|
"schema": {
|
||||||
"type": "Token"
|
"$ref": "#/definitions/types.Token"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"400": {
|
"400": {
|
||||||
|
@ -71,29 +71,26 @@ const docTemplate = `{
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"/loginerenew": {
|
"/loginrenew": {
|
||||||
"post": {
|
"post": {
|
||||||
"security": [
|
"security": [
|
||||||
{
|
{
|
||||||
"bererToken": []
|
"JWT": []
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"description": "renews the users token",
|
"description": "Renews the users token.",
|
||||||
"consumes": [
|
"produces": [
|
||||||
"application/json"
|
"application/json"
|
||||||
],
|
],
|
||||||
"produces": [
|
|
||||||
"text/plain"
|
|
||||||
],
|
|
||||||
"tags": [
|
"tags": [
|
||||||
"User"
|
"Auth"
|
||||||
],
|
],
|
||||||
"summary": "LoginRenews",
|
"summary": "LoginRenews",
|
||||||
"responses": {
|
"responses": {
|
||||||
"200": {
|
"200": {
|
||||||
"description": "Successfully signed token for user",
|
"description": "Successfully signed token for user",
|
||||||
"schema": {
|
"schema": {
|
||||||
"type": "Token"
|
"$ref": "#/definitions/types.Token"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"401": {
|
"401": {
|
||||||
|
@ -111,9 +108,64 @@ const docTemplate = `{
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"/promote/{projectName}": {
|
||||||
|
"put": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"JWT": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Promote a user to project manager",
|
||||||
|
"consumes": [
|
||||||
|
"text/plain"
|
||||||
|
],
|
||||||
|
"produces": [
|
||||||
|
"text/plain"
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
"Auth"
|
||||||
|
],
|
||||||
|
"summary": "Promote to project manager",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"type": "string",
|
||||||
|
"description": "Project name",
|
||||||
|
"name": "projectName",
|
||||||
|
"in": "path",
|
||||||
|
"required": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "string",
|
||||||
|
"description": "User name",
|
||||||
|
"name": "userName",
|
||||||
|
"in": "query",
|
||||||
|
"required": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"responses": {
|
||||||
|
"403": {
|
||||||
|
"description": "Forbidden",
|
||||||
|
"schema": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"description": "Internal server error",
|
||||||
|
"schema": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"/promoteToAdmin": {
|
"/promoteToAdmin": {
|
||||||
"post": {
|
"post": {
|
||||||
"description": "promote chosen user to admin",
|
"security": [
|
||||||
|
{
|
||||||
|
"JWT": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Promote chosen user to site admin",
|
||||||
"consumes": [
|
"consumes": [
|
||||||
"application/json"
|
"application/json"
|
||||||
],
|
],
|
||||||
|
@ -137,13 +189,13 @@ const docTemplate = `{
|
||||||
],
|
],
|
||||||
"responses": {
|
"responses": {
|
||||||
"200": {
|
"200": {
|
||||||
"description": "Successfully prometed user",
|
"description": "Successfully promoted user",
|
||||||
"schema": {
|
"schema": {
|
||||||
"type": "json"
|
"$ref": "#/definitions/types.Token"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"400": {
|
"400": {
|
||||||
"description": "bad request",
|
"description": "Bad request",
|
||||||
"schema": {
|
"schema": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
}
|
}
|
||||||
|
@ -173,7 +225,7 @@ const docTemplate = `{
|
||||||
"text/plain"
|
"text/plain"
|
||||||
],
|
],
|
||||||
"tags": [
|
"tags": [
|
||||||
"User"
|
"Auth"
|
||||||
],
|
],
|
||||||
"summary": "Register",
|
"summary": "Register",
|
||||||
"parameters": [
|
"parameters": [
|
||||||
|
@ -211,6 +263,11 @@ const docTemplate = `{
|
||||||
},
|
},
|
||||||
"/userdelete/{username}": {
|
"/userdelete/{username}": {
|
||||||
"delete": {
|
"delete": {
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"JWT": []
|
||||||
|
}
|
||||||
|
],
|
||||||
"description": "UserDelete deletes a user from the database",
|
"description": "UserDelete deletes a user from the database",
|
||||||
"consumes": [
|
"consumes": [
|
||||||
"application/json"
|
"application/json"
|
||||||
|
@ -252,12 +309,14 @@ const docTemplate = `{
|
||||||
},
|
},
|
||||||
"/users/all": {
|
"/users/all": {
|
||||||
"get": {
|
"get": {
|
||||||
"description": "lists all users",
|
"security": [
|
||||||
"consumes": [
|
{
|
||||||
"application/json"
|
"JWT": []
|
||||||
|
}
|
||||||
],
|
],
|
||||||
|
"description": "lists all users",
|
||||||
"produces": [
|
"produces": [
|
||||||
"text/plain"
|
"application/json"
|
||||||
],
|
],
|
||||||
"tags": [
|
"tags": [
|
||||||
"User"
|
"User"
|
||||||
|
@ -265,9 +324,12 @@ const docTemplate = `{
|
||||||
"summary": "ListsAllUsers",
|
"summary": "ListsAllUsers",
|
||||||
"responses": {
|
"responses": {
|
||||||
"200": {
|
"200": {
|
||||||
"description": "Successfully signed token for user",
|
"description": "Successfully returned all users",
|
||||||
"schema": {
|
"schema": {
|
||||||
"type": "json"
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"401": {
|
"401": {
|
||||||
|
@ -291,16 +353,27 @@ const docTemplate = `{
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"password": {
|
"password": {
|
||||||
"type": "string"
|
"type": "string",
|
||||||
|
"example": "password123"
|
||||||
},
|
},
|
||||||
"username": {
|
"username": {
|
||||||
|
"type": "string",
|
||||||
|
"example": "username123"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"types.Token": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"token": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"securityDefinitions": {
|
"securityDefinitions": {
|
||||||
"bererToken": {
|
"JWT": {
|
||||||
|
"description": "Use the JWT token provided by the login endpoint to authenticate requests. **Prefix the token with \"Bearer \".**",
|
||||||
"type": "apiKey",
|
"type": "apiKey",
|
||||||
"name": "Authorization",
|
"name": "Authorization",
|
||||||
"in": "header"
|
"in": "header"
|
||||||
|
|
|
@ -17,6 +17,7 @@ type Database interface {
|
||||||
AddUser(username string, password string) error
|
AddUser(username string, password string) error
|
||||||
CheckUser(username string, password string) bool
|
CheckUser(username string, password string) bool
|
||||||
RemoveUser(username string) error
|
RemoveUser(username string) error
|
||||||
|
RemoveUserFromProject(username string, projectname string) error
|
||||||
PromoteToAdmin(username string) error
|
PromoteToAdmin(username string) error
|
||||||
GetUserId(username string) (int, error)
|
GetUserId(username string) (int, error)
|
||||||
AddProject(name string, description string, username string) error
|
AddProject(name string, description string, username string) error
|
||||||
|
@ -35,7 +36,7 @@ type Database interface {
|
||||||
GetProject(projectId int) (types.Project, error)
|
GetProject(projectId int) (types.Project, error)
|
||||||
GetUserRole(username string, projectname string) (string, error)
|
GetUserRole(username string, projectname string) (string, error)
|
||||||
GetWeeklyReport(username string, projectName string, week int) (types.WeeklyReport, error)
|
GetWeeklyReport(username string, projectName string, week int) (types.WeeklyReport, error)
|
||||||
GetWeeklyReportsUser(username string, projectname string) ([]types.WeeklyReportList, error)
|
GetAllWeeklyReports(username string, projectname string) ([]types.WeeklyReportList, error)
|
||||||
GetUnsignedWeeklyReports(projectName string) ([]types.WeeklyReport, error)
|
GetUnsignedWeeklyReports(projectName string) ([]types.WeeklyReport, error)
|
||||||
SignWeeklyReport(reportId int, projectManagerId int) error
|
SignWeeklyReport(reportId int, projectManagerId int) error
|
||||||
IsSiteAdmin(username string) (bool, error)
|
IsSiteAdmin(username string) (bool, error)
|
||||||
|
@ -43,6 +44,7 @@ type Database interface {
|
||||||
GetProjectTimes(projectName string) (map[string]int, error)
|
GetProjectTimes(projectName string) (map[string]int, error)
|
||||||
UpdateWeeklyReport(projectName string, userName string, week int, developmentTime int, meetingTime int, adminTime int, ownWorkTime int, studyTime int, testingTime int) error
|
UpdateWeeklyReport(projectName string, userName string, week int, developmentTime int, meetingTime int, adminTime int, ownWorkTime int, studyTime int, testingTime int) error
|
||||||
RemoveProject(projectname string) error
|
RemoveProject(projectname string) error
|
||||||
|
GetUserName(id int) (string, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// This struct is a wrapper type that holds the database connection
|
// This struct is a wrapper type that holds the database connection
|
||||||
|
@ -86,6 +88,10 @@ const isProjectManagerQuery = `SELECT COUNT(*) > 0 FROM user_roles
|
||||||
JOIN projects ON user_roles.project_id = projects.id
|
JOIN projects ON user_roles.project_id = projects.id
|
||||||
WHERE users.username = ? AND projects.name = ? AND user_roles.p_role = 'project_manager'`
|
WHERE users.username = ? AND projects.name = ? AND user_roles.p_role = 'project_manager'`
|
||||||
|
|
||||||
|
const removeUserFromProjectQuery = `DELETE FROM user_roles
|
||||||
|
WHERE user_id = (SELECT id FROM users WHERE username = ?)
|
||||||
|
AND project_id = (SELECT id FROM projects WHERE name = ?)`
|
||||||
|
|
||||||
// DbConnect connects to the database
|
// DbConnect connects to the database
|
||||||
func DbConnect(dbpath string) Database {
|
func DbConnect(dbpath string) Database {
|
||||||
// Open the database
|
// Open the database
|
||||||
|
@ -147,6 +153,11 @@ func (d *Db) AddUserToProject(username string, projectname string, role string)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (d *Db) RemoveUserFromProject(username string, projectname string) error {
|
||||||
|
_, err := d.Exec(removeUserFromProjectQuery, username, projectname)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
// ChangeUserRole changes the role of a user within a project.
|
// ChangeUserRole changes the role of a user within a project.
|
||||||
func (d *Db) ChangeUserRole(username string, projectname string, role string) error {
|
func (d *Db) ChangeUserRole(username string, projectname string, role string) error {
|
||||||
// Execute the SQL query to change the user's role
|
// Execute the SQL query to change the user's role
|
||||||
|
@ -339,9 +350,14 @@ func (d *Db) SignWeeklyReport(reportId int, projectManagerId int) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
managerQuery := `SELECT project_id FROM user_roles
|
||||||
|
WHERE user_id = ?
|
||||||
|
AND project_id = (SELECT project_id FROM weekly_reports WHERE report_id = ?)
|
||||||
|
AND p_role = 'project_manager'`
|
||||||
|
|
||||||
// Retrieve the project ID associated with the project manager
|
// Retrieve the project ID associated with the project manager
|
||||||
var managerProjectID int
|
var managerProjectID int
|
||||||
err = d.Get(&managerProjectID, "SELECT project_id FROM user_roles WHERE user_id = ? AND p_role = 'project_manager'", projectManagerId)
|
err = d.Get(&managerProjectID, managerQuery, projectManagerId, reportId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
@ -463,8 +479,8 @@ func (d *Db) Migrate() error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetWeeklyReportsUser retrieves weekly reports for a specific user and project.
|
// GetAllWeeklyReports retrieves weekly reports for a specific user and project.
|
||||||
func (d *Db) GetWeeklyReportsUser(username string, projectName string) ([]types.WeeklyReportList, error) {
|
func (d *Db) GetAllWeeklyReports(username string, projectName string) ([]types.WeeklyReportList, error) {
|
||||||
query := `
|
query := `
|
||||||
SELECT
|
SELECT
|
||||||
wr.week,
|
wr.week,
|
||||||
|
@ -601,3 +617,9 @@ func (d *Db) RemoveProject(projectname string) error {
|
||||||
_, err := d.Exec("DELETE FROM projects WHERE name = ?", projectname)
|
_, err := d.Exec("DELETE FROM projects WHERE name = ?", projectname)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (d *Db) GetUserName(id int) (string, error) {
|
||||||
|
var username string
|
||||||
|
err := d.Get(&username, "SELECT username FROM users WHERE id = ?", id)
|
||||||
|
return username, err
|
||||||
|
}
|
||||||
|
|
|
@ -705,7 +705,7 @@ func TestGetWeeklyReportsUser(t *testing.T) {
|
||||||
t.Error("AddWeeklyReport failed:", err)
|
t.Error("AddWeeklyReport failed:", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
reports, err := db.GetWeeklyReportsUser("testuser", "testproject")
|
reports, err := db.GetAllWeeklyReports("testuser", "testproject")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Error("GetWeeklyReportsUser failed:", err)
|
t.Error("GetWeeklyReportsUser failed:", err)
|
||||||
}
|
}
|
||||||
|
@ -964,4 +964,3 @@ func TestRemoveProject(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
17
backend/internal/database/middleware.go
Normal file
17
backend/internal/database/middleware.go
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
package database
|
||||||
|
|
||||||
|
import "github.com/gofiber/fiber/v2"
|
||||||
|
|
||||||
|
// Simple middleware that provides a shared database pool as a local key "db"
|
||||||
|
func DbMiddleware(db *Database) func(c *fiber.Ctx) error {
|
||||||
|
return func(c *fiber.Ctx) error {
|
||||||
|
c.Locals("db", db)
|
||||||
|
return c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function to get the database from the context, without fiddling with casts
|
||||||
|
func GetDb(c *fiber.Ctx) Database {
|
||||||
|
// Dereference a pointer to a local, casted to a pointer to a Database
|
||||||
|
return *c.Locals("db").(*Database)
|
||||||
|
}
|
|
@ -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");
|
||||||
|
|
||||||
|
|
|
@ -1,44 +0,0 @@
|
||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"ttime/internal/database"
|
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v2"
|
|
||||||
)
|
|
||||||
|
|
||||||
// The actual interface that we will use
|
|
||||||
type GlobalState interface {
|
|
||||||
Register(c *fiber.Ctx) error // To register a new user
|
|
||||||
UserDelete(c *fiber.Ctx) error // To delete a user
|
|
||||||
Login(c *fiber.Ctx) error // To get the token
|
|
||||||
LoginRenew(c *fiber.Ctx) error // To renew the token
|
|
||||||
CreateProject(c *fiber.Ctx) error // To create a new project
|
|
||||||
GetUserProjects(c *fiber.Ctx) error // To get all projects
|
|
||||||
SubmitWeeklyReport(c *fiber.Ctx) error
|
|
||||||
GetWeeklyReport(c *fiber.Ctx) error
|
|
||||||
SignReport(c *fiber.Ctx) error
|
|
||||||
GetProject(c *fiber.Ctx) error
|
|
||||||
AddUserToProjectHandler(c *fiber.Ctx) error
|
|
||||||
PromoteToAdmin(c *fiber.Ctx) error
|
|
||||||
GetWeeklyReportsUserHandler(c *fiber.Ctx) error
|
|
||||||
IsProjectManagerHandler(c *fiber.Ctx) error
|
|
||||||
DeleteProject(c *fiber.Ctx) error // To delete a project // WIP
|
|
||||||
ListAllUsers(c *fiber.Ctx) error // To get a list of all users in the application database
|
|
||||||
ListAllUsersProject(c *fiber.Ctx) error // To get a list of all users for a specific project
|
|
||||||
ProjectRoleChange(c *fiber.Ctx) error // To change a users role in a project
|
|
||||||
ChangeUserName(c *fiber.Ctx) error // WIP
|
|
||||||
GetAllUsersProject(c *fiber.Ctx) error // WIP
|
|
||||||
GetUnsignedReports(c *fiber.Ctx) error //
|
|
||||||
UpdateWeeklyReport(c *fiber.Ctx) error
|
|
||||||
RemoveProject(c *fiber.Ctx) error
|
|
||||||
}
|
|
||||||
|
|
||||||
// "Constructor"
|
|
||||||
func NewGlobalState(db database.Database) GlobalState {
|
|
||||||
return &GState{Db: db}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The global state, which implements all the handlers
|
|
||||||
type GState struct {
|
|
||||||
Db database.Database
|
|
||||||
}
|
|
|
@ -1,15 +0,0 @@
|
||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
"ttime/internal/database"
|
|
||||||
)
|
|
||||||
|
|
||||||
// The actual interface that we will use
|
|
||||||
func TestGlobalState(t *testing.T) {
|
|
||||||
db := database.DbConnect(":memory:")
|
|
||||||
gs := NewGlobalState(db)
|
|
||||||
if gs == nil {
|
|
||||||
t.Error("NewGlobalState returned nil")
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,315 +0,0 @@
|
||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strconv"
|
|
||||||
"ttime/internal/types"
|
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v2"
|
|
||||||
"github.com/gofiber/fiber/v2/log"
|
|
||||||
"github.com/golang-jwt/jwt/v5"
|
|
||||||
)
|
|
||||||
|
|
||||||
// CreateProject is a simple handler that creates a new project
|
|
||||||
func (gs *GState) CreateProject(c *fiber.Ctx) error {
|
|
||||||
user := c.Locals("user").(*jwt.Token)
|
|
||||||
|
|
||||||
p := new(types.NewProject)
|
|
||||||
if err := c.BodyParser(p); err != nil {
|
|
||||||
return c.Status(400).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the username from the token and set it as the owner of the project
|
|
||||||
// This is ugly but
|
|
||||||
claims := user.Claims.(jwt.MapClaims)
|
|
||||||
owner := claims["name"].(string)
|
|
||||||
|
|
||||||
if err := gs.Db.AddProject(p.Name, p.Description, owner); err != nil {
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.Status(200).SendString("Project added")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gs *GState) DeleteProject(c *fiber.Ctx) error {
|
|
||||||
|
|
||||||
projectID := c.Params("projectID")
|
|
||||||
username := c.Params("username")
|
|
||||||
|
|
||||||
if err := gs.Db.DeleteProject(projectID, username); err != nil {
|
|
||||||
return c.Status(500).SendString((err.Error()))
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.Status(200).SendString("Project deleted")
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetUserProjects returns all projects that the user is a member of
|
|
||||||
func (gs *GState) GetUserProjects(c *fiber.Ctx) error {
|
|
||||||
// First we get the username from the token
|
|
||||||
user := c.Locals("user").(*jwt.Token)
|
|
||||||
claims := user.Claims.(jwt.MapClaims)
|
|
||||||
username := claims["name"].(string)
|
|
||||||
|
|
||||||
// Then dip into the database to get the projects
|
|
||||||
projects, err := gs.Db.GetProjectsForUser(username)
|
|
||||||
if err != nil {
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return a json serialized list of projects
|
|
||||||
return c.JSON(projects)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ProjectRoleChange is a handler that changes a user's role within a project
|
|
||||||
func (gs *GState) ProjectRoleChange(c *fiber.Ctx) error {
|
|
||||||
|
|
||||||
//check token and get username of current user
|
|
||||||
user := c.Locals("user").(*jwt.Token)
|
|
||||||
claims := user.Claims.(jwt.MapClaims)
|
|
||||||
username := claims["name"].(string)
|
|
||||||
|
|
||||||
// Extract the necessary parameters from the request
|
|
||||||
data := new(types.RoleChange)
|
|
||||||
if err := c.BodyParser(data); err != nil {
|
|
||||||
log.Info("error parsing username, project or role")
|
|
||||||
return c.Status(400).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Info("Changing role for user: ", username, " in project: ", data.Projectname, " to: ", data.Role)
|
|
||||||
|
|
||||||
// Dubble diping and checcking if current user is
|
|
||||||
if ismanager, err := gs.Db.IsProjectManager(username, data.Projectname); err != nil {
|
|
||||||
log.Warn("Error checking if projectmanager:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
} else if !ismanager {
|
|
||||||
log.Warn("User is not projectmanager")
|
|
||||||
return c.Status(401).SendString("User is not projectmanager")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Change the user's role within the project in the database
|
|
||||||
if err := gs.Db.ChangeUserRole(username, data.Projectname, data.Role); err != nil {
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return a success message
|
|
||||||
return c.SendStatus(fiber.StatusOK)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetProject retrieves a specific project by its ID
|
|
||||||
func (gs *GState) GetProject(c *fiber.Ctx) error {
|
|
||||||
// Extract the project ID from the request parameters or body
|
|
||||||
projectID := c.Params("projectID")
|
|
||||||
if projectID == "" {
|
|
||||||
log.Info("No project ID provided")
|
|
||||||
return c.Status(400).SendString("No project ID provided")
|
|
||||||
}
|
|
||||||
log.Info("Getting project with ID: ", projectID)
|
|
||||||
|
|
||||||
// Parse the project ID into an integer
|
|
||||||
projectIDInt, err := strconv.Atoi(projectID)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Invalid project ID")
|
|
||||||
return c.Status(400).SendString("Invalid project ID")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the project from the database by its ID
|
|
||||||
project, err := gs.Db.GetProject(projectIDInt)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Error getting project:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return the project as JSON
|
|
||||||
log.Info("Returning project: ", project.Name)
|
|
||||||
return c.JSON(project)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gs *GState) ListAllUsersProject(c *fiber.Ctx) error {
|
|
||||||
// Extract the project name from the request parameters or body
|
|
||||||
projectName := c.Params("projectName")
|
|
||||||
if projectName == "" {
|
|
||||||
log.Info("No project name provided")
|
|
||||||
return c.Status(400).SendString("No project name provided")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the user token
|
|
||||||
userToken := c.Locals("user").(*jwt.Token)
|
|
||||||
claims := userToken.Claims.(jwt.MapClaims)
|
|
||||||
username := claims["name"].(string)
|
|
||||||
|
|
||||||
// Check if the user is a project manager for the specified project
|
|
||||||
isManager, err := gs.Db.IsProjectManager(username, projectName)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Error checking project manager status:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
// If the user is not a project manager, check if the user is a site admin
|
|
||||||
if !isManager {
|
|
||||||
isAdmin, err := gs.Db.IsSiteAdmin(username)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Error checking admin status:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
if !isAdmin {
|
|
||||||
log.Info("User is neither a project manager nor a site admin:", username)
|
|
||||||
return c.Status(403).SendString("User is neither a project manager nor a site admin")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get all users associated with the project from the database
|
|
||||||
users, err := gs.Db.GetAllUsersProject(projectName)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Error getting users for project:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Info("Returning users for project: ", projectName)
|
|
||||||
|
|
||||||
// Return the list of users as JSON
|
|
||||||
return c.JSON(users)
|
|
||||||
}
|
|
||||||
|
|
||||||
// AddUserToProjectHandler is a handler that adds a user to a project with a specified role
|
|
||||||
func (gs *GState) AddUserToProjectHandler(c *fiber.Ctx) error {
|
|
||||||
// Extract necessary parameters from the request
|
|
||||||
var requestData struct {
|
|
||||||
Username string `json:"username"`
|
|
||||||
ProjectName string `json:"projectName"`
|
|
||||||
Role string `json:"role"`
|
|
||||||
}
|
|
||||||
if err := c.BodyParser(&requestData); err != nil {
|
|
||||||
log.Info("Error parsing request body:", err)
|
|
||||||
return c.Status(400).SendString("Bad request")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if the user adding another user to the project is a site admin
|
|
||||||
user := c.Locals("user").(*jwt.Token)
|
|
||||||
claims := user.Claims.(jwt.MapClaims)
|
|
||||||
adminUsername := claims["name"].(string)
|
|
||||||
log.Info("Admin username from claims:", adminUsername)
|
|
||||||
|
|
||||||
isAdmin, err := gs.Db.IsSiteAdmin(adminUsername)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Error checking admin status:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
if !isAdmin {
|
|
||||||
log.Info("User is not a site admin:", adminUsername)
|
|
||||||
return c.Status(403).SendString("User is not a site admin")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add the user to the project with the specified role
|
|
||||||
err = gs.Db.AddUserToProject(requestData.Username, requestData.ProjectName, requestData.Role)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Error adding user to project:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return success message
|
|
||||||
log.Info("User added to project successfully:", requestData.Username)
|
|
||||||
return c.SendStatus(fiber.StatusOK)
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsProjectManagerHandler is a handler that checks if a user is a project manager for a given project
|
|
||||||
func (gs *GState) IsProjectManagerHandler(c *fiber.Ctx) error {
|
|
||||||
// Get the username from the token
|
|
||||||
user := c.Locals("user").(*jwt.Token)
|
|
||||||
claims := user.Claims.(jwt.MapClaims)
|
|
||||||
username := claims["name"].(string)
|
|
||||||
|
|
||||||
// Extract necessary parameters from the request query string
|
|
||||||
projectName := c.Params("projectName")
|
|
||||||
|
|
||||||
log.Info("Checking if user ", username, " is a project manager for project ", projectName)
|
|
||||||
|
|
||||||
// Check if the user is a project manager for the specified project
|
|
||||||
isManager, err := gs.Db.IsProjectManager(username, projectName)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Error checking project manager status:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return the result as JSON
|
|
||||||
return c.JSON(fiber.Map{"isProjectManager": isManager})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gs *GState) GetProjectTimesHandler(c *fiber.Ctx) error {
|
|
||||||
// Get the username from the token
|
|
||||||
user := c.Locals("user").(*jwt.Token)
|
|
||||||
claims := user.Claims.(jwt.MapClaims)
|
|
||||||
username := claims["name"].(string)
|
|
||||||
|
|
||||||
// Get project
|
|
||||||
projectName := c.Params("projectName")
|
|
||||||
if projectName == "" {
|
|
||||||
log.Info("No project name provided")
|
|
||||||
return c.Status(400).SendString("No project name provided")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get all users in the project and roles
|
|
||||||
userProjects, err := gs.Db.GetAllUsersProject(projectName)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Error getting users in project:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
// If the user is member
|
|
||||||
isMember := false
|
|
||||||
for _, userProject := range userProjects {
|
|
||||||
if userProject.Username == username {
|
|
||||||
isMember = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// If the user is admin
|
|
||||||
if !isMember {
|
|
||||||
isAdmin, err := gs.Db.IsSiteAdmin(username)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Error checking admin status:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
if !isAdmin {
|
|
||||||
log.Info("User is neither a project member nor a site admin:", username)
|
|
||||||
return c.Status(403).SendString("User is neither a project member nor a site admin")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get project times
|
|
||||||
projectTimes, err := gs.Db.GetProjectTimes(projectName)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Error getting project times:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return project times as JSON
|
|
||||||
log.Info("Returning project times for project:", projectName)
|
|
||||||
return c.JSON(projectTimes)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gs *GState) RemoveProject(c *fiber.Ctx) error {
|
|
||||||
user := c.Locals("user").(*jwt.Token)
|
|
||||||
claims := user.Claims.(jwt.MapClaims)
|
|
||||||
username := claims["name"].(string)
|
|
||||||
|
|
||||||
// Check if the user is a site admin
|
|
||||||
isAdmin, err := gs.Db.IsSiteAdmin(username)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Error checking admin status:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
if !isAdmin {
|
|
||||||
log.Info("User is not a site admin:", username)
|
|
||||||
return c.Status(403).SendString("User is not a site admin")
|
|
||||||
}
|
|
||||||
|
|
||||||
projectName := c.Params("projectName")
|
|
||||||
|
|
||||||
if err := gs.Db.RemoveProject(projectName); err != nil {
|
|
||||||
return c.Status(500).SendString((err.Error()))
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.Status(200).SendString("Project deleted")
|
|
||||||
}
|
|
|
@ -1,218 +0,0 @@
|
||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strconv"
|
|
||||||
"ttime/internal/types"
|
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v2"
|
|
||||||
"github.com/gofiber/fiber/v2/log"
|
|
||||||
"github.com/golang-jwt/jwt/v5"
|
|
||||||
)
|
|
||||||
|
|
||||||
func (gs *GState) SubmitWeeklyReport(c *fiber.Ctx) error {
|
|
||||||
// Extract the necessary parameters from the token
|
|
||||||
user := c.Locals("user").(*jwt.Token)
|
|
||||||
claims := user.Claims.(jwt.MapClaims)
|
|
||||||
username := claims["name"].(string)
|
|
||||||
|
|
||||||
report := new(types.NewWeeklyReport)
|
|
||||||
if err := c.BodyParser(report); err != nil {
|
|
||||||
log.Info("Error parsing weekly report")
|
|
||||||
return c.Status(400).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Make sure all the fields of the report are valid
|
|
||||||
if report.Week < 1 || report.Week > 52 {
|
|
||||||
log.Info("Invalid week number")
|
|
||||||
return c.Status(400).SendString("Invalid week number")
|
|
||||||
}
|
|
||||||
if report.DevelopmentTime < 0 || report.MeetingTime < 0 || report.AdminTime < 0 || report.OwnWorkTime < 0 || report.StudyTime < 0 || report.TestingTime < 0 {
|
|
||||||
log.Info("Invalid time report")
|
|
||||||
return c.Status(400).SendString("Invalid time report")
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := gs.Db.AddWeeklyReport(report.ProjectName, username, report.Week, report.DevelopmentTime, report.MeetingTime, report.AdminTime, report.OwnWorkTime, report.StudyTime, report.TestingTime); err != nil {
|
|
||||||
log.Info("Error adding weekly report to db:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Info("Weekly report added")
|
|
||||||
return c.Status(200).SendString("Time report added")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handler for retrieving weekly report
|
|
||||||
func (gs *GState) GetWeeklyReport(c *fiber.Ctx) error {
|
|
||||||
// Extract the necessary parameters from the request
|
|
||||||
user := c.Locals("user").(*jwt.Token)
|
|
||||||
claims := user.Claims.(jwt.MapClaims)
|
|
||||||
username := claims["name"].(string)
|
|
||||||
|
|
||||||
log.Info("Getting weekly report for: ", username)
|
|
||||||
|
|
||||||
// Extract project name and week from query parameters
|
|
||||||
projectName := c.Query("projectName")
|
|
||||||
week := c.Query("week")
|
|
||||||
|
|
||||||
if projectName == "" || week == "" {
|
|
||||||
log.Info("Missing project name or week number")
|
|
||||||
return c.Status(400).SendString("Missing project name or week number")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert week to integer
|
|
||||||
weekInt, err := strconv.Atoi(week)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Invalid week number")
|
|
||||||
return c.Status(400).SendString("Invalid week number")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Call the database function to get the weekly report
|
|
||||||
report, err := gs.Db.GetWeeklyReport(username, projectName, weekInt)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Error getting weekly report from db:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Info("Returning weekly report")
|
|
||||||
// Return the retrieved weekly report
|
|
||||||
return c.JSON(report)
|
|
||||||
}
|
|
||||||
|
|
||||||
type ReportId struct {
|
|
||||||
ReportId int
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gs *GState) SignReport(c *fiber.Ctx) error {
|
|
||||||
// Extract the necessary parameters from the token
|
|
||||||
user := c.Locals("user").(*jwt.Token)
|
|
||||||
claims := user.Claims.(jwt.MapClaims)
|
|
||||||
projectManagerUsername := claims["name"].(string)
|
|
||||||
|
|
||||||
log.Info("Signing report for: ", projectManagerUsername)
|
|
||||||
|
|
||||||
// Extract report ID from the request query parameters
|
|
||||||
// reportID := c.Query("reportId")
|
|
||||||
rid := new(ReportId)
|
|
||||||
if err := c.BodyParser(rid); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
log.Info("Signing report for: ", rid.ReportId)
|
|
||||||
|
|
||||||
// Get the project manager's ID
|
|
||||||
projectManagerID, err := gs.Db.GetUserId(projectManagerUsername)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Failed to get project manager ID")
|
|
||||||
return c.Status(500).SendString("Failed to get project manager ID")
|
|
||||||
}
|
|
||||||
log.Info("Project manager ID: ", projectManagerID)
|
|
||||||
|
|
||||||
// Call the database function to sign the weekly report
|
|
||||||
err = gs.Db.SignWeeklyReport(rid.ReportId, projectManagerID)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Error signing weekly report:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.Status(200).SendString("Weekly report signed successfully")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gs *GState) GetUnsignedReports(c *fiber.Ctx) error {
|
|
||||||
// Extract the necessary parameters from the token
|
|
||||||
user := c.Locals("user").(*jwt.Token)
|
|
||||||
claims := user.Claims.(jwt.MapClaims)
|
|
||||||
projectManagerUsername := claims["name"].(string)
|
|
||||||
|
|
||||||
// Extract project name and week from query parameters
|
|
||||||
projectName := c.Params("projectName")
|
|
||||||
|
|
||||||
log.Info("Getting unsigned reports for")
|
|
||||||
|
|
||||||
if projectName == "" {
|
|
||||||
log.Info("Missing project name")
|
|
||||||
return c.Status(400).SendString("Missing project name")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the project manager's ID
|
|
||||||
isProjectManager, err := gs.Db.IsProjectManager(projectManagerUsername, projectName)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Failed to get project manager ID")
|
|
||||||
return c.Status(500).SendString("Failed to get project manager ID")
|
|
||||||
}
|
|
||||||
if !isProjectManager {
|
|
||||||
log.Info("User is not a project manager")
|
|
||||||
return c.Status(401).SendString("User is not a project manager")
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Info("User is Project Manager: ", isProjectManager)
|
|
||||||
|
|
||||||
// Call the database function to get the unsigned weekly reports
|
|
||||||
reports, err := gs.Db.GetUnsignedWeeklyReports(projectName)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Error getting unsigned weekly reports:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Info("Returning unsigned reports")
|
|
||||||
// Return the list of unsigned reports
|
|
||||||
return c.JSON(reports)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetWeeklyReportsUserHandler retrieves all weekly reports for a user in a specific project
|
|
||||||
func (gs *GState) GetWeeklyReportsUserHandler(c *fiber.Ctx) error {
|
|
||||||
// Extract the necessary parameters from the token
|
|
||||||
user := c.Locals("user").(*jwt.Token)
|
|
||||||
claims := user.Claims.(jwt.MapClaims)
|
|
||||||
username := claims["name"].(string)
|
|
||||||
|
|
||||||
// Extract necessary (path) parameters from the request
|
|
||||||
projectName := c.Params("projectName")
|
|
||||||
|
|
||||||
// TODO: Here we need to check whether the user is a member of the project
|
|
||||||
// If not, we should return an error. On the other hand, if the user not a member,
|
|
||||||
// the returned list of reports will (should) allways be empty.
|
|
||||||
|
|
||||||
// Retrieve weekly reports for the user in the project from the database
|
|
||||||
reports, err := gs.Db.GetWeeklyReportsUser(username, projectName)
|
|
||||||
if err != nil {
|
|
||||||
log.Error("Error getting weekly reports for user:", username, "in project:", projectName, ":", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Info("Returning weekly reports for user:", username, "in project:", projectName)
|
|
||||||
|
|
||||||
// Return the list of reports as JSON
|
|
||||||
return c.JSON(reports)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gs *GState) UpdateWeeklyReport(c *fiber.Ctx) error {
|
|
||||||
// Extract the necessary parameters from the token
|
|
||||||
user := c.Locals("user").(*jwt.Token)
|
|
||||||
claims := user.Claims.(jwt.MapClaims)
|
|
||||||
username := claims["name"].(string)
|
|
||||||
|
|
||||||
// Parse the request body into an UpdateWeeklyReport struct
|
|
||||||
var updateReport types.UpdateWeeklyReport
|
|
||||||
if err := c.BodyParser(&updateReport); err != nil {
|
|
||||||
log.Info("Error parsing weekly report")
|
|
||||||
return c.Status(400).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Make sure all the fields of the report are valid
|
|
||||||
if updateReport.Week < 1 || updateReport.Week > 52 {
|
|
||||||
log.Info("Invalid week number")
|
|
||||||
return c.Status(400).SendString("Invalid week number")
|
|
||||||
}
|
|
||||||
|
|
||||||
if updateReport.DevelopmentTime < 0 || updateReport.MeetingTime < 0 || updateReport.AdminTime < 0 || updateReport.OwnWorkTime < 0 || updateReport.StudyTime < 0 || updateReport.TestingTime < 0 {
|
|
||||||
log.Info("Invalid time report")
|
|
||||||
return c.Status(400).SendString("Invalid time report")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update the weekly report in the database
|
|
||||||
if err := gs.Db.UpdateWeeklyReport(updateReport.ProjectName, username, updateReport.Week, updateReport.DevelopmentTime, updateReport.MeetingTime, updateReport.AdminTime, updateReport.OwnWorkTime, updateReport.StudyTime, updateReport.TestingTime); err != nil {
|
|
||||||
log.Info("Error updating weekly report in db:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Info("Weekly report updated")
|
|
||||||
return c.Status(200).SendString("Weekly report updated")
|
|
||||||
}
|
|
|
@ -1,269 +0,0 @@
|
||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
"ttime/internal/types"
|
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v2/log"
|
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v2"
|
|
||||||
"github.com/golang-jwt/jwt/v5"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Register is a simple handler that registers a new user
|
|
||||||
//
|
|
||||||
// @Summary Register
|
|
||||||
// @Description Register a new user
|
|
||||||
// @Tags User
|
|
||||||
// @Accept json
|
|
||||||
// @Produce plain
|
|
||||||
// @Param NewUser body types.NewUser true "User to register"
|
|
||||||
// @Success 200 {string} string "User added"
|
|
||||||
// @Failure 400 {string} string "Bad request"
|
|
||||||
// @Failure 500 {string} string "Internal server error"
|
|
||||||
// @Router /register [post]
|
|
||||||
func (gs *GState) Register(c *fiber.Ctx) error {
|
|
||||||
u := new(types.NewUser)
|
|
||||||
if err := c.BodyParser(u); err != nil {
|
|
||||||
log.Warn("Error parsing body")
|
|
||||||
return c.Status(400).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Info("Adding user:", u.Username)
|
|
||||||
if err := gs.Db.AddUser(u.Username, u.Password); err != nil {
|
|
||||||
log.Warn("Error adding user:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Info("User added:", u.Username)
|
|
||||||
return c.Status(200).SendString("User added")
|
|
||||||
}
|
|
||||||
|
|
||||||
// This path should obviously be protected in the future
|
|
||||||
// UserDelete deletes a user from the database
|
|
||||||
//
|
|
||||||
// @Summary UserDelete
|
|
||||||
// @Description UserDelete deletes a user from the database
|
|
||||||
// @Tags User
|
|
||||||
// @Accept json
|
|
||||||
// @Produce plain
|
|
||||||
// @Success 200 {string} string "User deleted"
|
|
||||||
// @Failure 403 {string} string "You can only delete yourself"
|
|
||||||
// @Failure 500 {string} string "Internal server error"
|
|
||||||
// @Failure 401 {string} string "Unauthorized"
|
|
||||||
// @Router /userdelete/{username} [delete]
|
|
||||||
func (gs *GState) UserDelete(c *fiber.Ctx) error {
|
|
||||||
// Read from path parameters
|
|
||||||
username := c.Params("username")
|
|
||||||
|
|
||||||
// Read username from Locals
|
|
||||||
auth_username := c.Locals("user").(*jwt.Token).Claims.(jwt.MapClaims)["name"].(string)
|
|
||||||
|
|
||||||
if username == auth_username {
|
|
||||||
log.Info("User tried to delete itself")
|
|
||||||
return c.Status(403).SendString("You can't delete yourself")
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := gs.Db.RemoveUser(username); err != nil {
|
|
||||||
log.Warn("Error deleting user:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Info("User deleted:", username)
|
|
||||||
return c.Status(200).SendString("User deleted")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Login is a simple login handler that returns a JWT token
|
|
||||||
//
|
|
||||||
// @Summary login
|
|
||||||
// @Description logs the user in and returns a jwt token
|
|
||||||
// @Tags User
|
|
||||||
// @Accept json
|
|
||||||
// @Param NewUser body types.NewUser true "login info"
|
|
||||||
// @Produce plain
|
|
||||||
// @Success 200 Token types.Token "Successfully signed token for user"
|
|
||||||
// @Failure 400 {string} string "Bad request"
|
|
||||||
// @Failure 401 {string} string "Unauthorized"
|
|
||||||
// @Failure 500 {string} string "Internal server error"
|
|
||||||
// @Router /login [post]
|
|
||||||
func (gs *GState) Login(c *fiber.Ctx) error {
|
|
||||||
// The body type is identical to a NewUser
|
|
||||||
|
|
||||||
u := new(types.NewUser)
|
|
||||||
if err := c.BodyParser(u); err != nil {
|
|
||||||
log.Warn("Error parsing body")
|
|
||||||
return c.Status(400).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Info("Username logging in:", u.Username)
|
|
||||||
if !gs.Db.CheckUser(u.Username, u.Password) {
|
|
||||||
log.Info("User not found")
|
|
||||||
return c.SendStatus(fiber.StatusUnauthorized)
|
|
||||||
}
|
|
||||||
|
|
||||||
isAdmin, err := gs.Db.IsSiteAdmin(u.Username)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Error checking admin status:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
// Create the Claims
|
|
||||||
claims := jwt.MapClaims{
|
|
||||||
"name": u.Username,
|
|
||||||
"admin": isAdmin,
|
|
||||||
"exp": time.Now().Add(time.Hour * 72).Unix(),
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create token
|
|
||||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
||||||
log.Info("Token created for user:", u.Username)
|
|
||||||
|
|
||||||
// Generate encoded token and send it as response.
|
|
||||||
t, err := token.SignedString([]byte("secret"))
|
|
||||||
if err != nil {
|
|
||||||
log.Warn("Error signing token")
|
|
||||||
return c.SendStatus(fiber.StatusInternalServerError)
|
|
||||||
}
|
|
||||||
|
|
||||||
println("Successfully signed token for user:", u.Username)
|
|
||||||
return c.JSON(types.Token{Token: t})
|
|
||||||
}
|
|
||||||
|
|
||||||
// LoginRenew is a simple handler that renews the token
|
|
||||||
//
|
|
||||||
// @Summary LoginRenews
|
|
||||||
// @Description renews the users token
|
|
||||||
// @Security bererToken
|
|
||||||
// @Tags User
|
|
||||||
// @Accept json
|
|
||||||
// @Produce plain
|
|
||||||
// @Success 200 Token types.Token "Successfully signed token for user"
|
|
||||||
// @Failure 401 {string} string "Unauthorized"
|
|
||||||
// @Failure 500 {string} string "Internal server error"
|
|
||||||
// @Router /loginerenew [post]
|
|
||||||
func (gs *GState) LoginRenew(c *fiber.Ctx) error {
|
|
||||||
user := c.Locals("user").(*jwt.Token)
|
|
||||||
|
|
||||||
log.Info("Renewing token for user:", user.Claims.(jwt.MapClaims)["name"])
|
|
||||||
|
|
||||||
claims := user.Claims.(jwt.MapClaims)
|
|
||||||
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
|
|
||||||
renewed := jwt.MapClaims{
|
|
||||||
"name": claims["name"],
|
|
||||||
"admin": claims["admin"],
|
|
||||||
"exp": claims["exp"],
|
|
||||||
}
|
|
||||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, renewed)
|
|
||||||
t, err := token.SignedString([]byte("secret"))
|
|
||||||
if err != nil {
|
|
||||||
log.Warn("Error signing token")
|
|
||||||
return c.SendStatus(fiber.StatusInternalServerError)
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Info("Successfully renewed token for user:", user.Claims.(jwt.MapClaims)["name"])
|
|
||||||
return c.JSON(types.Token{Token: t})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListAllUsers is a handler that returns a list of all users in the application database
|
|
||||||
//
|
|
||||||
// @Summary ListsAllUsers
|
|
||||||
// @Description lists all users
|
|
||||||
// @Tags User
|
|
||||||
// @Accept json
|
|
||||||
// @Produce plain
|
|
||||||
// @Success 200 {json} json "Successfully signed token for user"
|
|
||||||
// @Failure 401 {string} string "Unauthorized"
|
|
||||||
// @Failure 500 {string} string "Internal server error"
|
|
||||||
// @Router /users/all [get]
|
|
||||||
func (gs *GState) ListAllUsers(c *fiber.Ctx) error {
|
|
||||||
// Get all users from the database
|
|
||||||
users, err := gs.Db.GetAllUsersApplication()
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Error getting users from db:", err) // Debug print
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Info("Returning all users")
|
|
||||||
// Return the list of users as JSON
|
|
||||||
return c.JSON(users)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (gs *GState) GetAllUsersProject(c *fiber.Ctx) error {
|
|
||||||
// Get all users from a project
|
|
||||||
projectName := c.Params("projectName")
|
|
||||||
users, err := gs.Db.GetAllUsersProject(projectName)
|
|
||||||
if err != nil {
|
|
||||||
log.Info("Error getting users from project:", err) // Debug print
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Info("Returning all users")
|
|
||||||
// Return the list of users as JSON
|
|
||||||
return c.JSON(users)
|
|
||||||
}
|
|
||||||
|
|
||||||
// @Summary PromoteToAdmin
|
|
||||||
// @Description promote chosen user to admin
|
|
||||||
// @Tags User
|
|
||||||
// @Accept json
|
|
||||||
// @Produce plain
|
|
||||||
// @Param NewUser body types.NewUser true "user info"
|
|
||||||
// @Success 200 {json} json "Successfully promoted user"
|
|
||||||
// @Failure 400 {string} string "Bad request"
|
|
||||||
// @Failure 401 {string} string "Unauthorized"
|
|
||||||
// @Failure 500 {string} string "Internal server error"
|
|
||||||
// @Router /promoteToAdmin [post]
|
|
||||||
func (gs *GState) PromoteToAdmin(c *fiber.Ctx) error {
|
|
||||||
// Extract the username from the request body
|
|
||||||
var newUser types.NewUser
|
|
||||||
if err := c.BodyParser(&newUser); err != nil {
|
|
||||||
return c.Status(400).SendString("Bad request")
|
|
||||||
}
|
|
||||||
username := newUser.Username
|
|
||||||
|
|
||||||
log.Info("Promoting user to admin:", username) // Debug print
|
|
||||||
|
|
||||||
// Promote the user to a site admin in the database
|
|
||||||
if err := gs.Db.PromoteToAdmin(username); err != nil {
|
|
||||||
log.Info("Error promoting user to admin:", err) // Debug print
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Info("User promoted to admin successfully:", username) // Debug print
|
|
||||||
|
|
||||||
// Return a success message
|
|
||||||
return c.SendStatus(fiber.StatusOK)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ChangeUserName changes a user's username in the database
|
|
||||||
func (gs *GState) ChangeUserName(c *fiber.Ctx) error {
|
|
||||||
// Check token and get username of current user
|
|
||||||
user := c.Locals("user").(*jwt.Token)
|
|
||||||
claims := user.Claims.(jwt.MapClaims)
|
|
||||||
adminUsername := claims["name"].(string)
|
|
||||||
log.Info(adminUsername)
|
|
||||||
|
|
||||||
// Extract the necessary parameters from the request
|
|
||||||
data := new(types.StrNameChange)
|
|
||||||
if err := c.BodyParser(data); err != nil {
|
|
||||||
log.Info("Error parsing username")
|
|
||||||
return c.Status(400).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if the current user is an admin
|
|
||||||
isAdmin, err := gs.Db.IsSiteAdmin(adminUsername)
|
|
||||||
if err != nil {
|
|
||||||
log.Warn("Error checking if admin:", err)
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
} else if !isAdmin {
|
|
||||||
log.Warn("Tried changing name when not admin")
|
|
||||||
return c.Status(401).SendString("You cannot change name unless you are an admin")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Change the user's name in the database
|
|
||||||
if err := gs.Db.ChangeUserName(data.PrevName, data.NewName); err != nil {
|
|
||||||
return c.Status(500).SendString(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return a success message
|
|
||||||
return c.SendStatus(fiber.StatusOK)
|
|
||||||
}
|
|
42
backend/internal/handlers/projects/AddUserToProject.go
Normal file
42
backend/internal/handlers/projects/AddUserToProject.go
Normal file
|
@ -0,0 +1,42 @@
|
||||||
|
package projects
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AddUserToProjectHandler is a handler that adds a user to a project with a specified role
|
||||||
|
func AddUserToProjectHandler(c *fiber.Ctx) error {
|
||||||
|
user := c.Locals("user").(*jwt.Token)
|
||||||
|
claims := user.Claims.(jwt.MapClaims)
|
||||||
|
pm_name := claims["name"].(string)
|
||||||
|
|
||||||
|
project := c.Params("projectName")
|
||||||
|
username := c.Query("userName")
|
||||||
|
|
||||||
|
// Check if the user is a project manager
|
||||||
|
isPM, err := db.GetDb(c).IsProjectManager(pm_name, project)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error checking if user is project manager:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if !isPM {
|
||||||
|
log.Info("User: ", pm_name, " is not a project manager in project: ", project)
|
||||||
|
return c.Status(403).SendString("User is not a project manager")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add the user to the project with the specified role
|
||||||
|
err = db.GetDb(c).AddUserToProject(username, project, "member")
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error adding user to project:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return success message
|
||||||
|
log.Info("User : ", username, " added to project: ", project)
|
||||||
|
return c.SendStatus(fiber.StatusOK)
|
||||||
|
}
|
30
backend/internal/handlers/projects/CreateProject.go
Normal file
30
backend/internal/handlers/projects/CreateProject.go
Normal file
|
@ -0,0 +1,30 @@
|
||||||
|
package projects
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
"ttime/internal/types"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CreateProject is a simple handler that creates a new project
|
||||||
|
func CreateProject(c *fiber.Ctx) error {
|
||||||
|
user := c.Locals("user").(*jwt.Token)
|
||||||
|
|
||||||
|
p := new(types.NewProject)
|
||||||
|
if err := c.BodyParser(p); err != nil {
|
||||||
|
return c.Status(400).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the username from the token and set it as the owner of the project
|
||||||
|
// This is ugly but
|
||||||
|
claims := user.Claims.(jwt.MapClaims)
|
||||||
|
owner := claims["name"].(string)
|
||||||
|
|
||||||
|
if err := db.GetDb(c).AddProject(p.Name, p.Description, owner); err != nil {
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.Status(200).SendString("Project added")
|
||||||
|
}
|
19
backend/internal/handlers/projects/DeleteProject.go
Normal file
19
backend/internal/handlers/projects/DeleteProject.go
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
package projects
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
func DeleteProject(c *fiber.Ctx) error {
|
||||||
|
|
||||||
|
projectID := c.Params("projectID")
|
||||||
|
username := c.Params("username")
|
||||||
|
|
||||||
|
if err := db.GetDb(c).DeleteProject(projectID, username); err != nil {
|
||||||
|
return c.Status(500).SendString((err.Error()))
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.Status(200).SendString("Project deleted")
|
||||||
|
}
|
38
backend/internal/handlers/projects/GetProject.go
Normal file
38
backend/internal/handlers/projects/GetProject.go
Normal file
|
@ -0,0 +1,38 @@
|
||||||
|
package projects
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
db "ttime/internal/database"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GetProject retrieves a specific project by its ID
|
||||||
|
func GetProject(c *fiber.Ctx) error {
|
||||||
|
// Extract the project ID from the request parameters or body
|
||||||
|
projectID := c.Params("projectID")
|
||||||
|
if projectID == "" {
|
||||||
|
log.Info("No project ID provided")
|
||||||
|
return c.Status(400).SendString("No project ID provided")
|
||||||
|
}
|
||||||
|
log.Info("Getting project with ID: ", projectID)
|
||||||
|
|
||||||
|
// Parse the project ID into an integer
|
||||||
|
projectIDInt, err := strconv.Atoi(projectID)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Invalid project ID")
|
||||||
|
return c.Status(400).SendString("Invalid project ID")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the project from the database by its ID
|
||||||
|
project, err := db.GetDb(c).GetProject(projectIDInt)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error getting project:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return the project as JSON
|
||||||
|
log.Info("Returning project: ", project.Name)
|
||||||
|
return c.JSON(project)
|
||||||
|
}
|
63
backend/internal/handlers/projects/GetProjectTimes.go
Normal file
63
backend/internal/handlers/projects/GetProjectTimes.go
Normal file
|
@ -0,0 +1,63 @@
|
||||||
|
package projects
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GetProjectTimesHandler(c *fiber.Ctx) error {
|
||||||
|
// Get the username from the token
|
||||||
|
user := c.Locals("user").(*jwt.Token)
|
||||||
|
claims := user.Claims.(jwt.MapClaims)
|
||||||
|
username := claims["name"].(string)
|
||||||
|
|
||||||
|
// Get project
|
||||||
|
projectName := c.Params("projectName")
|
||||||
|
if projectName == "" {
|
||||||
|
log.Info("No project name provided")
|
||||||
|
return c.Status(400).SendString("No project name provided")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get all users in the project and roles
|
||||||
|
userProjects, err := db.GetDb(c).GetAllUsersProject(projectName)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error getting users in project:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the user is member
|
||||||
|
isMember := false
|
||||||
|
for _, userProject := range userProjects {
|
||||||
|
if userProject.Username == username {
|
||||||
|
isMember = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the user is admin
|
||||||
|
if !isMember {
|
||||||
|
isAdmin, err := db.GetDb(c).IsSiteAdmin(username)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error checking admin status:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
if !isAdmin {
|
||||||
|
log.Info("User is neither a project member nor a site admin:", username)
|
||||||
|
return c.Status(403).SendString("User is neither a project member nor a site admin")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get project times
|
||||||
|
projectTimes, err := db.GetDb(c).GetProjectTimes(projectName)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error getting project times:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return project times as JSON
|
||||||
|
log.Info("Returning project times for project:", projectName)
|
||||||
|
return c.JSON(projectTimes)
|
||||||
|
}
|
26
backend/internal/handlers/projects/GetUserProject.go
Normal file
26
backend/internal/handlers/projects/GetUserProject.go
Normal file
|
@ -0,0 +1,26 @@
|
||||||
|
package projects
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GetUserProjects returns all projects that the user is a member of
|
||||||
|
func GetUserProjects(c *fiber.Ctx) error {
|
||||||
|
username := c.Params("username")
|
||||||
|
if username == "" {
|
||||||
|
log.Info("No username provided")
|
||||||
|
return c.Status(400).SendString("No username provided")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then dip into the database to get the projects
|
||||||
|
projects, err := db.GetDb(c).GetProjectsForUser(username)
|
||||||
|
if err != nil {
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return a json serialized list of projects
|
||||||
|
return c.JSON(projects)
|
||||||
|
}
|
32
backend/internal/handlers/projects/IsProjectManager.go
Normal file
32
backend/internal/handlers/projects/IsProjectManager.go
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
package projects
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// IsProjectManagerHandler is a handler that checks if a user is a project manager for a given project
|
||||||
|
func IsProjectManagerHandler(c *fiber.Ctx) error {
|
||||||
|
// Get the username from the token
|
||||||
|
user := c.Locals("user").(*jwt.Token)
|
||||||
|
claims := user.Claims.(jwt.MapClaims)
|
||||||
|
username := claims["name"].(string)
|
||||||
|
|
||||||
|
// Extract necessary parameters from the request query string
|
||||||
|
projectName := c.Params("projectName")
|
||||||
|
|
||||||
|
log.Info("Checking if user ", username, " is a project manager for project ", projectName)
|
||||||
|
|
||||||
|
// Check if the user is a project manager for the specified project
|
||||||
|
isManager, err := db.GetDb(c).IsProjectManager(username, projectName)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error checking project manager status:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return the result as JSON
|
||||||
|
return c.JSON(fiber.Map{"isProjectManager": isManager})
|
||||||
|
}
|
55
backend/internal/handlers/projects/ListAllUserProjects.go
Normal file
55
backend/internal/handlers/projects/ListAllUserProjects.go
Normal file
|
@ -0,0 +1,55 @@
|
||||||
|
package projects
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ListAllUsersProject(c *fiber.Ctx) error {
|
||||||
|
// Extract the project name from the request parameters or body
|
||||||
|
projectName := c.Params("projectName")
|
||||||
|
if projectName == "" {
|
||||||
|
log.Info("No project name provided")
|
||||||
|
return c.Status(400).SendString("No project name provided")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the user token
|
||||||
|
userToken := c.Locals("user").(*jwt.Token)
|
||||||
|
claims := userToken.Claims.(jwt.MapClaims)
|
||||||
|
username := claims["name"].(string)
|
||||||
|
|
||||||
|
// Check if the user is a project manager for the specified project
|
||||||
|
isManager, err := db.GetDb(c).IsProjectManager(username, projectName)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error checking project manager status:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the user is not a project manager, check if the user is a site admin
|
||||||
|
if !isManager {
|
||||||
|
isAdmin, err := db.GetDb(c).IsSiteAdmin(username)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error checking admin status:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
if !isAdmin {
|
||||||
|
log.Info("User is neither a project manager nor a site admin:", username)
|
||||||
|
return c.Status(403).SendString("User is neither a project manager nor a site admin")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get all users associated with the project from the database
|
||||||
|
users, err := db.GetDb(c).GetAllUsersProject(projectName)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error getting users for project:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info("Returning users for project: ", projectName)
|
||||||
|
|
||||||
|
// Return the list of users as JSON
|
||||||
|
return c.JSON(users)
|
||||||
|
}
|
51
backend/internal/handlers/projects/ProjectRoleChange.go
Normal file
51
backend/internal/handlers/projects/ProjectRoleChange.go
Normal file
|
@ -0,0 +1,51 @@
|
||||||
|
package projects
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
"ttime/internal/types"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ProjectRoleChange is a handler that changes a user's role within a project
|
||||||
|
func ProjectRoleChange(c *fiber.Ctx) error {
|
||||||
|
|
||||||
|
//check token and get username of current user
|
||||||
|
user := c.Locals("user").(*jwt.Token)
|
||||||
|
claims := user.Claims.(jwt.MapClaims)
|
||||||
|
username := claims["name"].(string)
|
||||||
|
|
||||||
|
// Extract the necessary parameters from the request
|
||||||
|
data := new(types.RoleChange)
|
||||||
|
if err := c.BodyParser(data); err != nil {
|
||||||
|
log.Info("error parsing username, project or role")
|
||||||
|
return c.Status(400).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
if ismanager, err := db.GetDb(c).IsProjectManager(username, data.Projectname); err != nil {
|
||||||
|
log.Warn("Error checking if projectmanager:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
} else if !ismanager {
|
||||||
|
log.Warn("User is not projectmanager")
|
||||||
|
return c.Status(401).SendString("User is not projectmanager")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Change the user's role within the project in the database
|
||||||
|
if err := db.GetDb(c).ChangeUserRole(data.UserName, data.Projectname, data.Role); err != nil {
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return a success message
|
||||||
|
return c.SendStatus(fiber.StatusOK)
|
||||||
|
}
|
55
backend/internal/handlers/projects/PromoteToPm.go
Normal file
55
backend/internal/handlers/projects/PromoteToPm.go
Normal file
|
@ -0,0 +1,55 @@
|
||||||
|
package projects
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// @Summary Promote to project manager
|
||||||
|
// @Description Promote a user to project manager
|
||||||
|
// @Tags Auth
|
||||||
|
// @Security JWT
|
||||||
|
// @Accept plain
|
||||||
|
// @Produce plain
|
||||||
|
// @Param projectName path string true "Project name"
|
||||||
|
// @Param userName query string true "User name"
|
||||||
|
// @Failure 500 {string} string "Internal server error"
|
||||||
|
// @Failure 403 {string} string "Forbidden"
|
||||||
|
// @Router /promote/{projectName} [put]
|
||||||
|
//
|
||||||
|
// Login logs in a user and returns a JWT token
|
||||||
|
// Promote to project manager
|
||||||
|
func PromoteToPm(c *fiber.Ctx) error {
|
||||||
|
user := c.Locals("user").(*jwt.Token)
|
||||||
|
claims := user.Claims.(jwt.MapClaims)
|
||||||
|
pm_name := claims["name"].(string)
|
||||||
|
|
||||||
|
project := c.Params("projectName")
|
||||||
|
new_pm_name := c.Query("userName")
|
||||||
|
|
||||||
|
// Check if the user is a project manager
|
||||||
|
isPM, err := db.GetDb(c).IsProjectManager(pm_name, project)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error checking if user is project manager:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if !isPM {
|
||||||
|
log.Info("User: ", pm_name, " is not a project manager in project: ", project)
|
||||||
|
return c.Status(403).SendString("User is not a project manager")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add the user to the project with the specified role
|
||||||
|
err = db.GetDb(c).ChangeUserRole(new_pm_name, project, "project_manager")
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error promoting user to project manager:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return success message
|
||||||
|
log.Info("User : ", new_pm_name, " promoted to project manager in project: ", project)
|
||||||
|
return c.SendStatus(fiber.StatusOK)
|
||||||
|
}
|
35
backend/internal/handlers/projects/RemoveProject.go
Normal file
35
backend/internal/handlers/projects/RemoveProject.go
Normal file
|
@ -0,0 +1,35 @@
|
||||||
|
package projects
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func RemoveProject(c *fiber.Ctx) error {
|
||||||
|
user := c.Locals("user").(*jwt.Token)
|
||||||
|
claims := user.Claims.(jwt.MapClaims)
|
||||||
|
username := claims["name"].(string)
|
||||||
|
|
||||||
|
// Check if the user is a site admin
|
||||||
|
isAdmin, err := db.GetDb(c).IsSiteAdmin(username)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error checking admin status:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if !isAdmin {
|
||||||
|
log.Info("User is not a site admin:", username)
|
||||||
|
return c.Status(403).SendString("User is not a site admin")
|
||||||
|
}
|
||||||
|
|
||||||
|
projectName := c.Params("projectName")
|
||||||
|
|
||||||
|
if err := db.GetDb(c).RemoveProject(projectName); err != nil {
|
||||||
|
return c.Status(500).SendString((err.Error()))
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.Status(200).SendString("Project deleted")
|
||||||
|
}
|
40
backend/internal/handlers/projects/RemoveUserFromProject.go
Normal file
40
backend/internal/handlers/projects/RemoveUserFromProject.go
Normal file
|
@ -0,0 +1,40 @@
|
||||||
|
package projects
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func RemoveUserFromProject(c *fiber.Ctx) error {
|
||||||
|
user := c.Locals("user").(*jwt.Token)
|
||||||
|
claims := user.Claims.(jwt.MapClaims)
|
||||||
|
pm_name := claims["name"].(string)
|
||||||
|
|
||||||
|
project := c.Params("projectName")
|
||||||
|
username := c.Query("userName")
|
||||||
|
|
||||||
|
// Check if the user is a project manager
|
||||||
|
isPM, err := db.GetDb(c).IsProjectManager(pm_name, project)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error checking if user is project manager:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if !isPM {
|
||||||
|
log.Info("User: ", pm_name, " is not a project manager in project: ", project)
|
||||||
|
return c.Status(403).SendString("User is not a project manager")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove the user from the project
|
||||||
|
if err = db.GetDb(c).RemoveUserFromProject(username, project); err != nil {
|
||||||
|
log.Info("Error removing user from project:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return success message
|
||||||
|
log.Info("User : ", username, " removed from project: ", project)
|
||||||
|
return c.SendStatus(fiber.StatusOK)
|
||||||
|
}
|
56
backend/internal/handlers/reports/GetAllWeeklyReports.go
Normal file
56
backend/internal/handlers/reports/GetAllWeeklyReports.go
Normal file
|
@ -0,0 +1,56 @@
|
||||||
|
package reports
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GetAllWeeklyReports retrieves all weekly reports for a user in a specific project
|
||||||
|
func GetAllWeeklyReports(c *fiber.Ctx) error {
|
||||||
|
// Extract the necessary parameters from the token
|
||||||
|
user := c.Locals("user").(*jwt.Token)
|
||||||
|
claims := user.Claims.(jwt.MapClaims)
|
||||||
|
username := claims["name"].(string)
|
||||||
|
|
||||||
|
// Extract project name and week from query parameters
|
||||||
|
projectName := c.Params("projectName")
|
||||||
|
target_user := c.Query("targetUser") // The user whose reports are being requested
|
||||||
|
|
||||||
|
// If the target user is not empty, use it as the username
|
||||||
|
if target_user == "" {
|
||||||
|
target_user = username
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info(username, " trying to get all weekly reports for: ", target_user)
|
||||||
|
|
||||||
|
if projectName == "" {
|
||||||
|
log.Info("Missing project name")
|
||||||
|
return c.Status(400).SendString("Missing project name")
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the user is not a project manager, they can only view their own reports
|
||||||
|
pm, err := db.GetDb(c).IsProjectManager(username, projectName)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error checking if user is project manager:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if !(pm || target_user == username) {
|
||||||
|
log.Info("Unauthorized access")
|
||||||
|
return c.Status(403).SendString("Unauthorized access")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retrieve weekly reports for the user in the project from the database
|
||||||
|
reports, err := db.GetDb(c).GetAllWeeklyReports(target_user, projectName)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error getting weekly reports for user:", target_user, "in project:", projectName, ":", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info("Returning weekly report")
|
||||||
|
// Return the retrieved weekly report
|
||||||
|
return c.JSON(reports)
|
||||||
|
}
|
45
backend/internal/handlers/reports/GetUnsignedReports.go
Normal file
45
backend/internal/handlers/reports/GetUnsignedReports.go
Normal file
|
@ -0,0 +1,45 @@
|
||||||
|
package reports
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GetUnsignedReports(c *fiber.Ctx) error {
|
||||||
|
// Extract the necessary parameters from the token
|
||||||
|
user := c.Locals("user").(*jwt.Token)
|
||||||
|
claims := user.Claims.(jwt.MapClaims)
|
||||||
|
projectManagerUsername := claims["name"].(string)
|
||||||
|
|
||||||
|
// Extract project name and week from query parameters
|
||||||
|
projectName := c.Params("projectName")
|
||||||
|
|
||||||
|
log.Info("Getting unsigned reports for")
|
||||||
|
|
||||||
|
if projectName == "" {
|
||||||
|
log.Info("Missing project name")
|
||||||
|
return c.Status(400).SendString("Missing project name")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the project manager's ID
|
||||||
|
isProjectManager, err := db.GetDb(c).IsProjectManager(projectManagerUsername, projectName)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Failed to get project manager ID")
|
||||||
|
return c.Status(500).SendString("Failed to get project manager ID")
|
||||||
|
}
|
||||||
|
log.Info("User is Project Manager: ", isProjectManager)
|
||||||
|
|
||||||
|
// Call the database function to get the unsigned weekly reports
|
||||||
|
reports, err := db.GetDb(c).GetUnsignedWeeklyReports(projectName)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error getting unsigned weekly reports:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info("Returning unsigned reports")
|
||||||
|
// Return the list of unsigned reports
|
||||||
|
return c.JSON(reports)
|
||||||
|
}
|
65
backend/internal/handlers/reports/GetWeeklyReport.go
Normal file
65
backend/internal/handlers/reports/GetWeeklyReport.go
Normal file
|
@ -0,0 +1,65 @@
|
||||||
|
package reports
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
db "ttime/internal/database"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Handler for retrieving weekly report
|
||||||
|
func GetWeeklyReport(c *fiber.Ctx) error {
|
||||||
|
// Extract the necessary parameters from the request
|
||||||
|
user := c.Locals("user").(*jwt.Token)
|
||||||
|
claims := user.Claims.(jwt.MapClaims)
|
||||||
|
username := claims["name"].(string)
|
||||||
|
|
||||||
|
// Extract project name and week from query parameters
|
||||||
|
projectName := c.Query("projectName")
|
||||||
|
week := c.Query("week")
|
||||||
|
target_user := c.Query("targetUser") // The user whose report is being requested
|
||||||
|
|
||||||
|
// If the target user is not empty, use it as the username
|
||||||
|
if target_user == "" {
|
||||||
|
target_user = username
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info(username, " trying to get weekly report for: ", target_user)
|
||||||
|
|
||||||
|
if projectName == "" || week == "" {
|
||||||
|
log.Info("Missing project name or week number")
|
||||||
|
return c.Status(400).SendString("Missing project name or week number")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert week to integer
|
||||||
|
weekInt, err := strconv.Atoi(week)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Invalid week number")
|
||||||
|
return c.Status(400).SendString("Invalid week number")
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the token user is not an admin, check if the target user is the same as the token user
|
||||||
|
pm, err := db.GetDb(c).IsProjectManager(username, projectName)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error checking if user is project manager:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
if !(pm || target_user == username) {
|
||||||
|
log.Info("Unauthorized access")
|
||||||
|
return c.Status(403).SendString("Unauthorized access")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call the database function to get the weekly report
|
||||||
|
report, err := db.GetDb(c).GetWeeklyReport(target_user, projectName, weekInt)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error getting weekly report from db:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info("Returning weekly report")
|
||||||
|
// Return the retrieved weekly report
|
||||||
|
return c.JSON(report)
|
||||||
|
}
|
41
backend/internal/handlers/reports/SignReport.go
Normal file
41
backend/internal/handlers/reports/SignReport.go
Normal file
|
@ -0,0 +1,41 @@
|
||||||
|
package reports
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
db "ttime/internal/database"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func SignReport(c *fiber.Ctx) error {
|
||||||
|
// Extract the necessary parameters from the token
|
||||||
|
user := c.Locals("user").(*jwt.Token)
|
||||||
|
claims := user.Claims.(jwt.MapClaims)
|
||||||
|
projectManagerUsername := claims["name"].(string)
|
||||||
|
|
||||||
|
// Extract report ID from the path
|
||||||
|
reportId, err := strconv.Atoi(c.Params("reportId"))
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Invalid report ID")
|
||||||
|
return c.Status(400).SendString("Invalid report ID")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the project manager's ID
|
||||||
|
projectManagerID, err := db.GetDb(c).GetUserId(projectManagerUsername)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Failed to get project manager ID for user: ", projectManagerUsername)
|
||||||
|
return c.Status(500).SendString("Failed to get project manager ID")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call the database function to sign the weekly report
|
||||||
|
err = db.GetDb(c).SignWeeklyReport(reportId, projectManagerID)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error signing weekly report:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info("Project manager ID: ", projectManagerID, " signed report ID: ", reportId)
|
||||||
|
return c.Status(200).SendString("Weekly report signed successfully")
|
||||||
|
}
|
41
backend/internal/handlers/reports/SubmitWeeklyReport.go
Normal file
41
backend/internal/handlers/reports/SubmitWeeklyReport.go
Normal file
|
@ -0,0 +1,41 @@
|
||||||
|
package reports
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
"ttime/internal/types"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func SubmitWeeklyReport(c *fiber.Ctx) error {
|
||||||
|
// Extract the necessary parameters from the token
|
||||||
|
user := c.Locals("user").(*jwt.Token)
|
||||||
|
claims := user.Claims.(jwt.MapClaims)
|
||||||
|
username := claims["name"].(string)
|
||||||
|
|
||||||
|
report := new(types.NewWeeklyReport)
|
||||||
|
if err := c.BodyParser(report); err != nil {
|
||||||
|
log.Info("Error parsing weekly report")
|
||||||
|
return c.Status(400).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make sure all the fields of the report are valid
|
||||||
|
if report.Week < 1 || report.Week > 52 {
|
||||||
|
log.Info("Invalid week number")
|
||||||
|
return c.Status(400).SendString("Invalid week number")
|
||||||
|
}
|
||||||
|
if report.DevelopmentTime < 0 || report.MeetingTime < 0 || report.AdminTime < 0 || report.OwnWorkTime < 0 || report.StudyTime < 0 || report.TestingTime < 0 {
|
||||||
|
log.Info("Invalid time report")
|
||||||
|
return c.Status(400).SendString("Invalid time report")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.GetDb(c).AddWeeklyReport(report.ProjectName, username, report.Week, report.DevelopmentTime, report.MeetingTime, report.AdminTime, report.OwnWorkTime, report.StudyTime, report.TestingTime); err != nil {
|
||||||
|
log.Info("Error adding weekly report to db:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info("Weekly report added")
|
||||||
|
return c.Status(200).SendString("Time report added")
|
||||||
|
}
|
44
backend/internal/handlers/reports/UpdateWeeklyReport.go
Normal file
44
backend/internal/handlers/reports/UpdateWeeklyReport.go
Normal file
|
@ -0,0 +1,44 @@
|
||||||
|
package reports
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
"ttime/internal/types"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func UpdateWeeklyReport(c *fiber.Ctx) error {
|
||||||
|
// Extract the necessary parameters from the token
|
||||||
|
user := c.Locals("user").(*jwt.Token)
|
||||||
|
claims := user.Claims.(jwt.MapClaims)
|
||||||
|
username := claims["name"].(string)
|
||||||
|
|
||||||
|
// Parse the request body into an UpdateWeeklyReport struct
|
||||||
|
var updateReport types.UpdateWeeklyReport
|
||||||
|
if err := c.BodyParser(&updateReport); err != nil {
|
||||||
|
log.Info("Error parsing weekly report")
|
||||||
|
return c.Status(400).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make sure all the fields of the report are valid
|
||||||
|
if updateReport.Week < 1 || updateReport.Week > 52 {
|
||||||
|
log.Info("Invalid week number")
|
||||||
|
return c.Status(400).SendString("Invalid week number")
|
||||||
|
}
|
||||||
|
|
||||||
|
if updateReport.DevelopmentTime < 0 || updateReport.MeetingTime < 0 || updateReport.AdminTime < 0 || updateReport.OwnWorkTime < 0 || updateReport.StudyTime < 0 || updateReport.TestingTime < 0 {
|
||||||
|
log.Info("Invalid time report")
|
||||||
|
return c.Status(400).SendString("Invalid time report")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the weekly report in the database
|
||||||
|
if err := db.GetDb(c).UpdateWeeklyReport(updateReport.ProjectName, username, updateReport.Week, updateReport.DevelopmentTime, updateReport.MeetingTime, updateReport.AdminTime, updateReport.OwnWorkTime, updateReport.StudyTime, updateReport.TestingTime); err != nil {
|
||||||
|
log.Info("Error updating weekly report in db:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info("Weekly report updated")
|
||||||
|
return c.Status(200).SendString("Weekly report updated")
|
||||||
|
}
|
44
backend/internal/handlers/users/ChangeUserName.go
Normal file
44
backend/internal/handlers/users/ChangeUserName.go
Normal file
|
@ -0,0 +1,44 @@
|
||||||
|
package users
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
"ttime/internal/types"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ChangeUserName changes a user's username in the database
|
||||||
|
func ChangeUserName(c *fiber.Ctx) error {
|
||||||
|
// Check token and get username of current user
|
||||||
|
user := c.Locals("user").(*jwt.Token)
|
||||||
|
claims := user.Claims.(jwt.MapClaims)
|
||||||
|
adminUsername := claims["name"].(string)
|
||||||
|
log.Info(adminUsername)
|
||||||
|
|
||||||
|
// Extract the necessary parameters from the request
|
||||||
|
data := new(types.StrNameChange)
|
||||||
|
if err := c.BodyParser(data); err != nil {
|
||||||
|
log.Info("Error parsing username")
|
||||||
|
return c.Status(400).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if the current user is an admin
|
||||||
|
isAdmin, err := db.GetDb(c).IsSiteAdmin(adminUsername)
|
||||||
|
if err != nil {
|
||||||
|
log.Warn("Error checking if admin:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
} else if !isAdmin {
|
||||||
|
log.Warn("Tried changing name when not admin")
|
||||||
|
return c.Status(401).SendString("You cannot change name unless you are an admin")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Change the user's name in the database
|
||||||
|
if err := db.GetDb(c).ChangeUserName(data.PrevName, data.NewName); err != nil {
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return a success message
|
||||||
|
return c.SendStatus(fiber.StatusOK)
|
||||||
|
}
|
32
backend/internal/handlers/users/GetUserName.go
Normal file
32
backend/internal/handlers/users/GetUserName.go
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
package users
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
db "ttime/internal/database"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Return the username of a user given their user id
|
||||||
|
func GetUserName(c *fiber.Ctx) error {
|
||||||
|
// Check the query params for userId
|
||||||
|
user_id_string := c.Query("userId")
|
||||||
|
if user_id_string == "" {
|
||||||
|
return c.Status(400).SendString("Missing user id")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert to int
|
||||||
|
user_id, err := strconv.Atoi(user_id_string)
|
||||||
|
if err != nil {
|
||||||
|
return c.Status(400).SendString("Invalid user id")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the username from the database
|
||||||
|
username, err := db.GetDb(c).GetUserName(user_id)
|
||||||
|
if err != nil {
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send the nuclear launch codes to north korea
|
||||||
|
return c.JSON(fiber.Map{"username": username})
|
||||||
|
}
|
22
backend/internal/handlers/users/GetUsersProjects.go
Normal file
22
backend/internal/handlers/users/GetUsersProjects.go
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
package users
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GetAllUsersProject(c *fiber.Ctx) error {
|
||||||
|
// Get all users from a project
|
||||||
|
projectName := c.Params("projectName")
|
||||||
|
users, err := db.GetDb(c).GetAllUsersProject(projectName)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error getting users from project:", err) // Debug print
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info("Returning all users")
|
||||||
|
// Return the list of users as JSON
|
||||||
|
return c.JSON(users)
|
||||||
|
}
|
32
backend/internal/handlers/users/ListAllUsers.go
Normal file
32
backend/internal/handlers/users/ListAllUsers.go
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
package users
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
// @Summary ListsAllUsers
|
||||||
|
// @Description lists all users
|
||||||
|
// @Tags User
|
||||||
|
// @Produce json
|
||||||
|
// @Security JWT
|
||||||
|
// @Success 200 {array} string "Successfully returned all users"
|
||||||
|
// @Failure 401 {string} string "Unauthorized"
|
||||||
|
// @Failure 500 {string} string "Internal server error"
|
||||||
|
// @Router /users/all [get]
|
||||||
|
//
|
||||||
|
// ListAllUsers returns a list of all users in the application database
|
||||||
|
func ListAllUsers(c *fiber.Ctx) error {
|
||||||
|
// Get all users from the database
|
||||||
|
users, err := db.GetDb(c).GetAllUsersApplication()
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error getting users from db:", err) // Debug print
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info("Returning all users")
|
||||||
|
// Return the list of users as JSON
|
||||||
|
return c.JSON(users)
|
||||||
|
}
|
66
backend/internal/handlers/users/Login.go
Normal file
66
backend/internal/handlers/users/Login.go
Normal file
|
@ -0,0 +1,66 @@
|
||||||
|
package users
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
db "ttime/internal/database"
|
||||||
|
"ttime/internal/types"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// @Summary Login
|
||||||
|
// @Description Logs in a user and returns a JWT token
|
||||||
|
// @Tags Auth
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param body body types.NewUser true "User credentials"
|
||||||
|
// @Success 200 {object} types.Token "JWT token"
|
||||||
|
// @Failure 400 {string} string "Bad request"
|
||||||
|
// @Failure 401 {string} string "Unauthorized"
|
||||||
|
// @Failure 500 {string} string "Internal server error"
|
||||||
|
// @Router /login [post]
|
||||||
|
//
|
||||||
|
// Login logs in a user and returns a JWT token
|
||||||
|
func Login(c *fiber.Ctx) error {
|
||||||
|
// The body type is identical to a NewUser
|
||||||
|
|
||||||
|
u := new(types.NewUser)
|
||||||
|
if err := c.BodyParser(u); err != nil {
|
||||||
|
log.Warn("Error parsing body")
|
||||||
|
return c.Status(400).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info("Username logging in:", u.Username)
|
||||||
|
if !db.GetDb(c).CheckUser(u.Username, u.Password) {
|
||||||
|
log.Info("User not found")
|
||||||
|
return c.SendStatus(fiber.StatusUnauthorized)
|
||||||
|
}
|
||||||
|
|
||||||
|
isAdmin, err := db.GetDb(c).IsSiteAdmin(u.Username)
|
||||||
|
if err != nil {
|
||||||
|
log.Info("Error checking admin status:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
// Create the Claims
|
||||||
|
claims := jwt.MapClaims{
|
||||||
|
"name": u.Username,
|
||||||
|
"admin": isAdmin,
|
||||||
|
"exp": time.Now().Add(time.Hour * 72).Unix(),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create token
|
||||||
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||||
|
log.Info("Token created for user:", u.Username)
|
||||||
|
|
||||||
|
// Generate encoded token and send it as response.
|
||||||
|
t, err := token.SignedString([]byte("secret"))
|
||||||
|
if err != nil {
|
||||||
|
log.Warn("Error signing token")
|
||||||
|
return c.SendStatus(fiber.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
|
||||||
|
println("Successfully signed token for user:", u.Username)
|
||||||
|
return c.JSON(types.Token{Token: t})
|
||||||
|
}
|
50
backend/internal/handlers/users/LoginRenew.go
Normal file
50
backend/internal/handlers/users/LoginRenew.go
Normal file
|
@ -0,0 +1,50 @@
|
||||||
|
package users
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
"ttime/internal/types"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// @Summary LoginRenews
|
||||||
|
// @Description Renews the users token.
|
||||||
|
// @Tags Auth
|
||||||
|
// @Produce json
|
||||||
|
// @Security JWT
|
||||||
|
// @Success 200 {object} types.Token "Successfully signed token for user"
|
||||||
|
// @Failure 401 {string} string "Unauthorized"
|
||||||
|
// @Failure 500 {string} string "Internal server error"
|
||||||
|
// @Router /loginrenew [post]
|
||||||
|
//
|
||||||
|
// LoginRenew renews the users token
|
||||||
|
func LoginRenew(c *fiber.Ctx) error {
|
||||||
|
user := c.Locals("user").(*jwt.Token)
|
||||||
|
|
||||||
|
log.Info("Renewing token for user:", user.Claims.(jwt.MapClaims)["name"])
|
||||||
|
|
||||||
|
// Renewing the token means we trust whatever is already in the token
|
||||||
|
claims := user.Claims.(jwt.MapClaims)
|
||||||
|
|
||||||
|
// 72 hour expiration time
|
||||||
|
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
|
||||||
|
|
||||||
|
// Create token with old claims, but new expiration time
|
||||||
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||||
|
"name": claims["name"],
|
||||||
|
"admin": claims["admin"],
|
||||||
|
"exp": claims["exp"],
|
||||||
|
})
|
||||||
|
|
||||||
|
// Sign it with top secret key
|
||||||
|
t, err := token.SignedString([]byte("secret"))
|
||||||
|
if err != nil {
|
||||||
|
log.Warn("Error signing token")
|
||||||
|
return c.SendStatus(fiber.StatusInternalServerError) // 500
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info("Successfully renewed token for user:", user.Claims.(jwt.MapClaims)["name"])
|
||||||
|
return c.JSON(types.Token{Token: t})
|
||||||
|
}
|
45
backend/internal/handlers/users/PromoteToAdmin.go
Normal file
45
backend/internal/handlers/users/PromoteToAdmin.go
Normal file
|
@ -0,0 +1,45 @@
|
||||||
|
package users
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
"ttime/internal/types"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
// @Summary PromoteToAdmin
|
||||||
|
// @Description Promote chosen user to site admin
|
||||||
|
// @Tags User
|
||||||
|
// @Accept json
|
||||||
|
// @Produce plain
|
||||||
|
// @Security JWT
|
||||||
|
// @Param NewUser body types.NewUser true "user info"
|
||||||
|
// @Success 200 {object} types.Token "Successfully promoted user"
|
||||||
|
// @Failure 400 {string} string "Bad request"
|
||||||
|
// @Failure 401 {string} string "Unauthorized"
|
||||||
|
// @Failure 500 {string} string "Internal server error"
|
||||||
|
// @Router /promoteToAdmin [post]
|
||||||
|
//
|
||||||
|
// PromoteToAdmin promotes a user to a site admin
|
||||||
|
func PromoteToAdmin(c *fiber.Ctx) error {
|
||||||
|
// Extract the username from the request body
|
||||||
|
var newUser types.NewUser
|
||||||
|
if err := c.BodyParser(&newUser); err != nil {
|
||||||
|
return c.Status(400).SendString("Bad request")
|
||||||
|
}
|
||||||
|
username := newUser.Username
|
||||||
|
|
||||||
|
log.Info("Promoting user to admin:", username) // Debug print
|
||||||
|
|
||||||
|
// Promote the user to a site admin in the database
|
||||||
|
if err := db.GetDb(c).PromoteToAdmin(username); err != nil {
|
||||||
|
log.Info("Error promoting user to admin:", err) // Debug print
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info("User promoted to admin successfully:", username) // Debug print
|
||||||
|
|
||||||
|
// Return a success message
|
||||||
|
return c.SendStatus(fiber.StatusOK)
|
||||||
|
}
|
38
backend/internal/handlers/users/Register.go
Normal file
38
backend/internal/handlers/users/Register.go
Normal file
|
@ -0,0 +1,38 @@
|
||||||
|
package users
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
"ttime/internal/types"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
// @Summary Register
|
||||||
|
// @Description Register a new user
|
||||||
|
// @Tags Auth
|
||||||
|
// @Accept json
|
||||||
|
// @Produce plain
|
||||||
|
// @Param NewUser body types.NewUser true "User to register"
|
||||||
|
// @Success 200 {string} string "User added"
|
||||||
|
// @Failure 400 {string} string "Bad request"
|
||||||
|
// @Failure 500 {string} string "Internal server error"
|
||||||
|
// @Router /register [post]
|
||||||
|
//
|
||||||
|
// Register is a simple handler that registers a new user
|
||||||
|
func Register(c *fiber.Ctx) error {
|
||||||
|
u := new(types.NewUser)
|
||||||
|
if err := c.BodyParser(u); err != nil {
|
||||||
|
log.Warn("Error parsing body")
|
||||||
|
return c.Status(400).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info("Adding user:", u.Username)
|
||||||
|
if err := db.GetDb(c).AddUser(u.Username, u.Password); err != nil {
|
||||||
|
log.Warn("Error adding user:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info("User added:", u.Username)
|
||||||
|
return c.Status(200).SendString("User added")
|
||||||
|
}
|
43
backend/internal/handlers/users/UserDelete.go
Normal file
43
backend/internal/handlers/users/UserDelete.go
Normal file
|
@ -0,0 +1,43 @@
|
||||||
|
package users
|
||||||
|
|
||||||
|
import (
|
||||||
|
db "ttime/internal/database"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/log"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// @Summary UserDelete
|
||||||
|
// @Description UserDelete deletes a user from the database
|
||||||
|
// @Tags User
|
||||||
|
// @Accept json
|
||||||
|
// @Produce plain
|
||||||
|
// @Security JWT
|
||||||
|
// @Success 200 {string} string "User deleted"
|
||||||
|
// @Failure 403 {string} string "You can only delete yourself"
|
||||||
|
// @Failure 500 {string} string "Internal server error"
|
||||||
|
// @Failure 401 {string} string "Unauthorized"
|
||||||
|
// @Router /userdelete/{username} [delete]
|
||||||
|
//
|
||||||
|
// UserDelete deletes a user from the database
|
||||||
|
func UserDelete(c *fiber.Ctx) error {
|
||||||
|
// Read from path parameters
|
||||||
|
username := c.Params("username")
|
||||||
|
|
||||||
|
// Read username from Locals
|
||||||
|
auth_username := c.Locals("user").(*jwt.Token).Claims.(jwt.MapClaims)["name"].(string)
|
||||||
|
|
||||||
|
if username == auth_username {
|
||||||
|
log.Info("User tried to delete itself")
|
||||||
|
return c.Status(403).SendString("You can't delete yourself")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.GetDb(c).RemoveUser(username); err != nil {
|
||||||
|
log.Warn("Error deleting user:", err)
|
||||||
|
return c.Status(500).SendString(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info("User deleted:", username)
|
||||||
|
return c.Status(200).SendString("User deleted")
|
||||||
|
}
|
|
@ -18,8 +18,8 @@ func (u *User) ToPublicUser() (*PublicUser, error) {
|
||||||
|
|
||||||
// Should be used when registering, for example
|
// Should be used when registering, for example
|
||||||
type NewUser struct {
|
type NewUser struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username" example:"username123"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password" example:"password123"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// PublicUser represents a user that is safe to send over the API (no password)
|
// PublicUser represents a user that is safe to send over the API (no password)
|
||||||
|
|
|
@ -6,7 +6,9 @@ import (
|
||||||
_ "ttime/docs"
|
_ "ttime/docs"
|
||||||
"ttime/internal/config"
|
"ttime/internal/config"
|
||||||
"ttime/internal/database"
|
"ttime/internal/database"
|
||||||
"ttime/internal/handlers"
|
"ttime/internal/handlers/projects"
|
||||||
|
"ttime/internal/handlers/reports"
|
||||||
|
"ttime/internal/handlers/users"
|
||||||
|
|
||||||
"github.com/BurntSushi/toml"
|
"github.com/BurntSushi/toml"
|
||||||
"github.com/gofiber/fiber/v2"
|
"github.com/gofiber/fiber/v2"
|
||||||
|
@ -23,15 +25,16 @@ import (
|
||||||
// @license.name AGPL
|
// @license.name AGPL
|
||||||
// @license.url https://www.gnu.org/licenses/agpl-3.0.html
|
// @license.url https://www.gnu.org/licenses/agpl-3.0.html
|
||||||
|
|
||||||
//@securityDefinitions.apikey bererToken
|
// @securityDefinitions.apikey JWT
|
||||||
//@in header
|
// @in header
|
||||||
//@name Authorization
|
// @name Authorization
|
||||||
|
// @description Use the JWT token provided by the login endpoint to authenticate requests. **Prefix the token with "Bearer ".**
|
||||||
|
|
||||||
// @host localhost:8080
|
// @host localhost:8080
|
||||||
// @BasePath /api
|
// @BasePath /api
|
||||||
|
|
||||||
// @externalDocs.description OpenAPI
|
// @externalDocs.description OpenAPI
|
||||||
// @externalDocs.url https://swagger.io/resources/open-api/
|
// @externalDocs.url https://swagger.io/resources/open-api/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Main function for starting the server and initializing configurations.
|
Main function for starting the server and initializing configurations.
|
||||||
|
@ -54,24 +57,28 @@ func main() {
|
||||||
|
|
||||||
// Connect to the database
|
// Connect to the database
|
||||||
db := database.DbConnect(conf.DbPath)
|
db := database.DbConnect(conf.DbPath)
|
||||||
|
|
||||||
// Migrate the database
|
// Migrate the database
|
||||||
if err = db.Migrate(); err != nil {
|
if err = db.Migrate(); err != nil {
|
||||||
fmt.Println("Error migrating database: ", err)
|
fmt.Println("Error migrating database: ", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Migrate sample data, should not be used in production
|
||||||
if err = db.MigrateSampleData(); err != nil {
|
if err = db.MigrateSampleData(); err != nil {
|
||||||
fmt.Println("Error migrating sample data: ", err)
|
fmt.Println("Error migrating sample data: ", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get our global state
|
|
||||||
gs := handlers.NewGlobalState(db)
|
|
||||||
// Create the server
|
// Create the server
|
||||||
server := fiber.New()
|
server := fiber.New()
|
||||||
|
|
||||||
|
// We want some logs
|
||||||
server.Use(logger.New())
|
server.Use(logger.New())
|
||||||
|
|
||||||
|
// Sets up db middleware, accessed as Local "db" key
|
||||||
|
server.Use(database.DbMiddleware(&db))
|
||||||
|
|
||||||
// Mounts the swagger documentation, this is available at /swagger/index.html
|
// Mounts the swagger documentation, this is available at /swagger/index.html
|
||||||
server.Get("/swagger/*", swagger.HandlerDefault)
|
server.Get("/swagger/*", swagger.HandlerDefault)
|
||||||
|
|
||||||
|
@ -79,37 +86,54 @@ func main() {
|
||||||
// This will likely be replaced by an embedded filesystem in the future
|
// This will likely be replaced by an embedded filesystem in the future
|
||||||
server.Static("/", "./static")
|
server.Static("/", "./static")
|
||||||
|
|
||||||
// Register our unprotected routes
|
// Create a group for our API
|
||||||
server.Post("/api/register", gs.Register)
|
api := server.Group("/api")
|
||||||
server.Post("/api/login", gs.Login)
|
|
||||||
|
|
||||||
// Every route from here on will require a valid JWT
|
// Register our unprotected routes
|
||||||
|
api.Post("/register", users.Register)
|
||||||
|
api.Post("/login", users.Login)
|
||||||
|
|
||||||
|
// Every route from here on will require a valid
|
||||||
|
// JWT bearer token authentication in the header
|
||||||
server.Use(jwtware.New(jwtware.Config{
|
server.Use(jwtware.New(jwtware.Config{
|
||||||
SigningKey: jwtware.SigningKey{Key: []byte("secret")},
|
SigningKey: jwtware.SigningKey{Key: []byte("secret")},
|
||||||
}))
|
}))
|
||||||
|
|
||||||
// Protected routes (require a valid JWT bearer token authentication header)
|
// All user related routes
|
||||||
server.Post("/api/submitWeeklyReport", gs.SubmitWeeklyReport)
|
// userGroup := api.Group("/user") // Not currently in use
|
||||||
server.Get("/api/getUserProjects", gs.GetUserProjects)
|
api.Get("/users/all", users.ListAllUsers)
|
||||||
server.Post("/api/loginrenew", gs.LoginRenew)
|
api.Get("/project/getAllUsers", users.GetAllUsersProject)
|
||||||
server.Delete("/api/userdelete/:username", gs.UserDelete) // Perhaps just use POST to avoid headaches
|
api.Get("/username", users.GetUserName)
|
||||||
server.Delete("api/project/:projectID", gs.DeleteProject) // WIP
|
api.Post("/login", users.Login)
|
||||||
server.Post("/api/project", gs.CreateProject) // WIP
|
api.Post("/register", users.Register)
|
||||||
server.Get("/api/project/:projectId", gs.GetProject)
|
api.Post("/loginrenew", users.LoginRenew)
|
||||||
server.Get("/api/project/getAllUsers", gs.GetAllUsersProject)
|
api.Post("/promoteToAdmin", users.PromoteToAdmin)
|
||||||
server.Get("/api/getWeeklyReport", gs.GetWeeklyReport)
|
api.Put("/changeUserName", users.ChangeUserName)
|
||||||
server.Get("/api/getUnsignedReports/:projectName", gs.GetUnsignedReports)
|
api.Delete("/userdelete/:username", users.UserDelete) // Perhaps just use POST to avoid headaches
|
||||||
server.Post("/api/signReport", gs.SignReport)
|
|
||||||
server.Put("/api/addUserToProject", gs.AddUserToProjectHandler)
|
// All project related routes
|
||||||
server.Put("/api/changeUserName", gs.ChangeUserName)
|
// projectGroup := api.Group("/project") // Not currently in use
|
||||||
server.Post("/api/promoteToAdmin", gs.PromoteToAdmin)
|
api.Get("/getProjectTimes/:projectName", projects.GetProjectTimesHandler)
|
||||||
server.Get("/api/users/all", gs.ListAllUsers)
|
api.Get("/getUserProjects/:username", projects.GetUserProjects)
|
||||||
server.Get("/api/getWeeklyReportsUser/:projectName", gs.GetWeeklyReportsUserHandler)
|
api.Get("/project/:projectId", projects.GetProject)
|
||||||
server.Get("/api/checkIfProjectManager/:projectName", gs.IsProjectManagerHandler)
|
api.Get("/checkIfProjectManager/:projectName", projects.IsProjectManagerHandler)
|
||||||
server.Post("/api/ProjectRoleChange", gs.ProjectRoleChange)
|
api.Get("/getUsersProject/:projectName", projects.ListAllUsersProject)
|
||||||
server.Get("/api/getUsersProject/:projectName", gs.ListAllUsersProject)
|
api.Post("/project", projects.CreateProject)
|
||||||
server.Put("/api/updateWeeklyReport", gs.UpdateWeeklyReport)
|
api.Post("/ProjectRoleChange", projects.ProjectRoleChange)
|
||||||
server.Delete("/api/removeProject/:projectName", gs.RemoveProject)
|
api.Put("/promoteToPm/:projectName", projects.PromoteToPm)
|
||||||
|
api.Put("/addUserToProject/:projectName", projects.AddUserToProjectHandler)
|
||||||
|
api.Delete("/removeUserFromProject/:projectName", projects.RemoveUserFromProject)
|
||||||
|
api.Delete("/removeProject/:projectName", projects.RemoveProject)
|
||||||
|
api.Delete("/project/:projectID", projects.DeleteProject)
|
||||||
|
|
||||||
|
// All report related routes
|
||||||
|
// reportGroup := api.Group("/report") // Not currently in use
|
||||||
|
api.Get("/getWeeklyReport", reports.GetWeeklyReport)
|
||||||
|
api.Get("/getUnsignedReports/:projectName", reports.GetUnsignedReports)
|
||||||
|
api.Get("/getAllWeeklyReports/:projectName", reports.GetAllWeeklyReports)
|
||||||
|
api.Post("/submitWeeklyReport", reports.SubmitWeeklyReport)
|
||||||
|
api.Put("/signReport/:reportId", reports.SignReport)
|
||||||
|
api.Put("/updateWeeklyReport", reports.UpdateWeeklyReport)
|
||||||
|
|
||||||
// Announce the port we are listening on and start the server
|
// Announce the port we are listening on and start the server
|
||||||
err = server.Listen(fmt.Sprintf(":%d", conf.Port))
|
err = server.Listen(fmt.Sprintf(":%d", conf.Port))
|
||||||
|
|
2
frontend/.prettierignore
Normal file
2
frontend/.prettierignore
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
goTypes.ts
|
||||||
|
GenApi.ts
|
|
@ -1,13 +1,16 @@
|
||||||
|
import { AddMemberInfo } from "../Components/AddMember";
|
||||||
|
import { ProjectRoleChange } from "../Components/ChangeRole";
|
||||||
|
import { projectTimes } from "../Components/GetProjectTimes";
|
||||||
|
import { ProjectMember } from "../Components/GetUsersInProject";
|
||||||
import {
|
import {
|
||||||
|
UpdateWeeklyReport,
|
||||||
NewWeeklyReport,
|
NewWeeklyReport,
|
||||||
NewUser,
|
NewUser,
|
||||||
User,
|
User,
|
||||||
Project,
|
Project,
|
||||||
NewProject,
|
NewProject,
|
||||||
UserProjectMember,
|
|
||||||
WeeklyReport,
|
WeeklyReport,
|
||||||
StrNameChange,
|
StrNameChange,
|
||||||
NewProjMember,
|
|
||||||
} from "../Types/goTypes";
|
} from "../Types/goTypes";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -73,10 +76,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.
|
||||||
|
@ -88,16 +88,31 @@ interface API {
|
||||||
token: string,
|
token: string,
|
||||||
): Promise<APIResponse<string>>;
|
): Promise<APIResponse<string>>;
|
||||||
|
|
||||||
/** Gets a weekly report for a specific user, project and week
|
/**
|
||||||
|
* Updates a weekly report.
|
||||||
|
* @param {UpdateWeeklyReport} weeklyReport The updated weekly report object.
|
||||||
|
* @param {string} token The authentication token.
|
||||||
|
* @returns {Promise<APIResponse<string>>} A promise containing the API response with the updated report.
|
||||||
|
*/
|
||||||
|
updateWeeklyReport(
|
||||||
|
weeklyReport: UpdateWeeklyReport,
|
||||||
|
token: string,
|
||||||
|
): Promise<APIResponse<string>>;
|
||||||
|
|
||||||
|
/** Gets a weekly report for a specific user, project and week.
|
||||||
|
* Keep in mind that the user within the token needs to be PM
|
||||||
|
* of the project to get the report, unless the user is the target user.
|
||||||
* @param {string} projectName The name of the project.
|
* @param {string} projectName The name of the project.
|
||||||
* @param {string} week The week number.
|
* @param {string} week The week number.
|
||||||
* @param {string} token The authentication token.
|
* @param {string} token The authentication token.
|
||||||
|
* @param {string} targetUser The username of the target user. Defaults to token user.
|
||||||
* @returns {Promise<APIResponse<WeeklyReport>>} A promise resolving to an API response with the retrieved report.
|
* @returns {Promise<APIResponse<WeeklyReport>>} A promise resolving to an API response with the retrieved report.
|
||||||
*/
|
*/
|
||||||
getWeeklyReport(
|
getWeeklyReport(
|
||||||
projectName: string,
|
projectName: string,
|
||||||
week: string,
|
week: string,
|
||||||
token: string,
|
token: string,
|
||||||
|
targetUser?: string,
|
||||||
): Promise<APIResponse<WeeklyReport>>;
|
): Promise<APIResponse<WeeklyReport>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -107,16 +122,21 @@ interface API {
|
||||||
* @param {string} token The token of the user
|
* @param {string} token The token of the user
|
||||||
* @returns {APIResponse<WeeklyReport[]>} A list of weekly reports
|
* @returns {APIResponse<WeeklyReport[]>} A list of weekly reports
|
||||||
*/
|
*/
|
||||||
getWeeklyReportsForUser(
|
getAllWeeklyReportsForUser(
|
||||||
projectName: string,
|
projectName: string,
|
||||||
token: string,
|
token: string,
|
||||||
|
targetUser?: string,
|
||||||
): Promise<APIResponse<WeeklyReport[]>>;
|
): Promise<APIResponse<WeeklyReport[]>>;
|
||||||
|
|
||||||
/** Gets all the projects of a user
|
/** Gets all the projects of a user
|
||||||
|
* @param {string} username - The authentication token.
|
||||||
* @param {string} token - The authentication token.
|
* @param {string} token - The authentication token.
|
||||||
* @returns {Promise<APIResponse<Project[]>>} A promise containing the API response with the user's projects.
|
* @returns {Promise<APIResponse<Project[]>>} A promise containing the API response with the user's projects.
|
||||||
*/
|
*/
|
||||||
getUserProjects(token: string): Promise<APIResponse<Project[]>>;
|
getUserProjects(
|
||||||
|
username: string,
|
||||||
|
token: string,
|
||||||
|
): Promise<APIResponse<Project[]>>;
|
||||||
|
|
||||||
/** Gets a project by its id.
|
/** Gets a project by its id.
|
||||||
* @param {number} id The id of the project to retrieve.
|
* @param {number} id The id of the project to retrieve.
|
||||||
|
@ -124,6 +144,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.
|
||||||
|
@ -133,7 +163,18 @@ interface API {
|
||||||
getAllUsersProject(
|
getAllUsersProject(
|
||||||
projectName: string,
|
projectName: string,
|
||||||
token: string,
|
token: string,
|
||||||
): Promise<APIResponse<UserProjectMember[]>>;
|
): Promise<APIResponse<ProjectMember[]>>;
|
||||||
|
|
||||||
|
/** Gets all unsigned reports in a project.
|
||||||
|
* @param {string} projectName The name of the project.
|
||||||
|
* @param {string} token The authentication token.
|
||||||
|
* @returns {Promise<APIResponse<WeeklyReport[]>>} A promise resolving to an API response containing the list of unsigned reports.
|
||||||
|
*/
|
||||||
|
getUnsignedReportsInProject(
|
||||||
|
projectName: string,
|
||||||
|
token: string,
|
||||||
|
): Promise<APIResponse<WeeklyReport[]>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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.
|
||||||
|
@ -144,15 +185,60 @@ interface API {
|
||||||
data: StrNameChange,
|
data: StrNameChange,
|
||||||
token: string,
|
token: string,
|
||||||
): Promise<APIResponse<void>>;
|
): Promise<APIResponse<void>>;
|
||||||
addUserToProject(
|
/**
|
||||||
user: NewProjMember,
|
* 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,
|
token: string,
|
||||||
): Promise<APIResponse<NewProjMember>>;
|
): Promise<APIResponse<void>>;
|
||||||
|
|
||||||
|
addUserToProject(
|
||||||
|
addMemberInfo: AddMemberInfo,
|
||||||
|
token: string,
|
||||||
|
): Promise<APIResponse<void>>;
|
||||||
|
|
||||||
|
removeUserFromProject(
|
||||||
|
user: string,
|
||||||
|
project: string,
|
||||||
|
token: string,
|
||||||
|
): Promise<APIResponse<void>>;
|
||||||
|
|
||||||
removeProject(
|
removeProject(
|
||||||
projectName: string,
|
projectName: string,
|
||||||
token: string,
|
token: string,
|
||||||
): Promise<APIResponse<string>>;
|
): Promise<APIResponse<string>>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Signs a report. Keep in mind that the user which the token belongs to must be
|
||||||
|
* the project manager of the project the report belongs to.
|
||||||
|
*
|
||||||
|
* @param {number} reportId The id of the report to sign
|
||||||
|
* @param {string} token The authentication token
|
||||||
|
*/
|
||||||
|
signReport(reportId: number, token: string): Promise<APIResponse<string>>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Promotes a user to project manager within a project.
|
||||||
|
*
|
||||||
|
* @param {string} userName The username of the user to promote
|
||||||
|
* @param {string} projectName The name of the project to promote the user in
|
||||||
|
* @returns {Promise<APIResponse<string>} A promise resolving to an API response.
|
||||||
|
*/
|
||||||
|
promoteToPm(
|
||||||
|
userName: string,
|
||||||
|
projectName: string,
|
||||||
|
token: string,
|
||||||
|
): Promise<APIResponse<string>>;
|
||||||
|
/**
|
||||||
|
* Get the username from the id
|
||||||
|
* @param {number} id The id of the user
|
||||||
|
* @param {string} token Your token
|
||||||
|
*/
|
||||||
|
getUsername(id: number, token: string): Promise<APIResponse<string>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** An instance of the API */
|
/** An instance of the API */
|
||||||
|
@ -240,7 +326,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",
|
||||||
|
@ -254,27 +340,28 @@ 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,
|
addMemberInfo: AddMemberInfo,
|
||||||
token: string,
|
token: string,
|
||||||
): Promise<APIResponse<NewProjMember>> {
|
): Promise<APIResponse<void>> {
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/addUserToProject", {
|
const response = await fetch(
|
||||||
method: "PUT",
|
`/api/addUserToProject/${addMemberInfo.projectName}/?userName=${addMemberInfo.userName}`,
|
||||||
headers: {
|
{
|
||||||
"Content-Type": "application/json",
|
method: "PUT",
|
||||||
Authorization: "Bearer " + token,
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: "Bearer " + token,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
body: JSON.stringify(user),
|
);
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
return { success: false, message: "Failed to add member" };
|
return { success: false, message: "Failed to add member" };
|
||||||
|
@ -286,6 +373,31 @@ export const api: API = {
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
async removeUserFromProject(
|
||||||
|
user: string,
|
||||||
|
project: string,
|
||||||
|
token: string,
|
||||||
|
): Promise<APIResponse<void>> {
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`/api/removeUserFromProject/${project}?userName=${user}`,
|
||||||
|
{
|
||||||
|
method: "DELETE",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: "Bearer " + token,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
return { success: false, message: "Failed to remove member" };
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
return { success: false, message: "Failed to remove member" };
|
||||||
|
}
|
||||||
|
return { success: true, message: "Removed member" };
|
||||||
|
},
|
||||||
|
|
||||||
async renewToken(token: string): Promise<APIResponse<string>> {
|
async renewToken(token: string): Promise<APIResponse<string>> {
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/loginrenew", {
|
const response = await fetch("/api/loginrenew", {
|
||||||
|
@ -307,9 +419,39 @@ export const api: API = {
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
async getUserProjects(token: string): Promise<APIResponse<Project[]>> {
|
async changeUserRole(
|
||||||
|
roleInfo: ProjectRoleChange,
|
||||||
|
token: string,
|
||||||
|
): Promise<APIResponse<void>> {
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/getUserProjects", {
|
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(
|
||||||
|
username: string,
|
||||||
|
token: string,
|
||||||
|
): Promise<APIResponse<Project[]>> {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/getUserProjects/${username}`, {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
|
@ -334,6 +476,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,
|
||||||
|
@ -365,14 +538,46 @@ export const api: API = {
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
async updateWeeklyReport(
|
||||||
|
weeklyReport: UpdateWeeklyReport,
|
||||||
|
token: string,
|
||||||
|
): Promise<APIResponse<string>> {
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/updateWeeklyReport", {
|
||||||
|
method: "PUT",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: "Bearer " + token,
|
||||||
|
},
|
||||||
|
body: JSON.stringify(weeklyReport),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: "Failed to update weekly report",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.text();
|
||||||
|
return { success: true, message: data };
|
||||||
|
} catch (e) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: "Failed to update weekly report",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
async getWeeklyReport(
|
async getWeeklyReport(
|
||||||
projectName: string,
|
projectName: string,
|
||||||
week: string,
|
week: string,
|
||||||
token: string,
|
token: string,
|
||||||
|
targetUser?: string,
|
||||||
): Promise<APIResponse<WeeklyReport>> {
|
): Promise<APIResponse<WeeklyReport>> {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
`/api/getWeeklyReport?projectName=${projectName}&week=${week}`,
|
`/api/getWeeklyReport?projectName=${projectName}&week=${week}&targetUser=${targetUser ?? ""}`,
|
||||||
{
|
{
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: {
|
headers: {
|
||||||
|
@ -393,18 +598,22 @@ export const api: API = {
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
async getWeeklyReportsForUser(
|
async getAllWeeklyReportsForUser(
|
||||||
projectName: string,
|
projectName: string,
|
||||||
token: string,
|
token: string,
|
||||||
|
targetUser?: string,
|
||||||
): Promise<APIResponse<WeeklyReport[]>> {
|
): Promise<APIResponse<WeeklyReport[]>> {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`/api/getWeeklyReportsUser/${projectName}`, {
|
const response = await fetch(
|
||||||
method: "GET",
|
`/api/getAllWeeklyReports/${projectName}?targetUser=${targetUser ?? ""}`,
|
||||||
headers: {
|
{
|
||||||
"Content-Type": "application/json",
|
method: "GET",
|
||||||
Authorization: "Bearer " + token,
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: "Bearer " + token,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
});
|
);
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
return {
|
return {
|
||||||
|
@ -501,7 +710,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",
|
||||||
|
@ -517,7 +726,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) {
|
||||||
|
@ -528,6 +737,38 @@ export const api: API = {
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
async getUnsignedReportsInProject(
|
||||||
|
projectName: string,
|
||||||
|
token: string,
|
||||||
|
): Promise<APIResponse<WeeklyReport[]>> {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/getUnsignedReports/${projectName}`, {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: "Bearer " + token,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message:
|
||||||
|
"Failed to get unsigned reports for project: Response code " +
|
||||||
|
response.status,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
const data = (await response.json()) as WeeklyReport[];
|
||||||
|
return { success: true, data };
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: "Failed to get unsigned reports for project, unknown error",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
async changeUserName(
|
async changeUserName(
|
||||||
data: StrNameChange,
|
data: StrNameChange,
|
||||||
token: string,
|
token: string,
|
||||||
|
@ -557,7 +798,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",
|
||||||
|
@ -581,4 +822,79 @@ export const api: API = {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
async signReport(
|
||||||
|
reportId: number,
|
||||||
|
token: string,
|
||||||
|
): Promise<APIResponse<string>> {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/signReport/${reportId}`, {
|
||||||
|
method: "PUT",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: "Bearer " + token,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
return { success: false, message: "Failed to sign report" };
|
||||||
|
} else {
|
||||||
|
return { success: true, message: "Report signed" };
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
return { success: false, message: "Failed to sign report" };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async promoteToPm(
|
||||||
|
userName: string,
|
||||||
|
projectName: string,
|
||||||
|
token: string,
|
||||||
|
): Promise<APIResponse<string>> {
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`/api/promoteToPm/${projectName}?userName=${userName}`,
|
||||||
|
{
|
||||||
|
method: "PUT",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: "Bearer " + token,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: "Failed to promote user to project manager",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: "Failed to promote user to project manager",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { success: true, message: "User promoted to project manager" };
|
||||||
|
},
|
||||||
|
|
||||||
|
async getUsername(id: number, token: string): Promise<APIResponse<string>> {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/username?userId=${id}`, {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: "Bearer " + token,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
return { success: false, message: "Failed to get username" };
|
||||||
|
} else {
|
||||||
|
const data = (await response.json()) as string;
|
||||||
|
return { success: true, data };
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
return { success: false, message: "Failed to get username" };
|
||||||
|
}
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
358
frontend/src/API/GenApi.ts
Normal file
358
frontend/src/API/GenApi.ts
Normal file
|
@ -0,0 +1,358 @@
|
||||||
|
/* eslint-disable */
|
||||||
|
/* tslint:disable */
|
||||||
|
/*
|
||||||
|
* ---------------------------------------------------------------
|
||||||
|
* ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
|
||||||
|
* ## ##
|
||||||
|
* ## AUTHOR: acacode ##
|
||||||
|
* ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
|
||||||
|
* ---------------------------------------------------------------
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface TypesNewUser {
|
||||||
|
/** @example "password123" */
|
||||||
|
password?: string;
|
||||||
|
/** @example "username123" */
|
||||||
|
username?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TypesToken {
|
||||||
|
token?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type QueryParamsType = Record<string | number, any>;
|
||||||
|
export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">;
|
||||||
|
|
||||||
|
export interface FullRequestParams extends Omit<RequestInit, "body"> {
|
||||||
|
/** set parameter to `true` for call `securityWorker` for this request */
|
||||||
|
secure?: boolean;
|
||||||
|
/** request path */
|
||||||
|
path: string;
|
||||||
|
/** content type of request body */
|
||||||
|
type?: ContentType;
|
||||||
|
/** query params */
|
||||||
|
query?: QueryParamsType;
|
||||||
|
/** format of response (i.e. response.json() -> format: "json") */
|
||||||
|
format?: ResponseFormat;
|
||||||
|
/** request body */
|
||||||
|
body?: unknown;
|
||||||
|
/** base url */
|
||||||
|
baseUrl?: string;
|
||||||
|
/** request cancellation token */
|
||||||
|
cancelToken?: CancelToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">;
|
||||||
|
|
||||||
|
export interface ApiConfig<SecurityDataType = unknown> {
|
||||||
|
baseUrl?: string;
|
||||||
|
baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">;
|
||||||
|
securityWorker?: (securityData: SecurityDataType | null) => Promise<RequestParams | void> | RequestParams | void;
|
||||||
|
customFetch?: typeof fetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HttpResponse<D extends unknown, E extends unknown = unknown> extends Response {
|
||||||
|
data: D;
|
||||||
|
error: E;
|
||||||
|
}
|
||||||
|
|
||||||
|
type CancelToken = Symbol | string | number;
|
||||||
|
|
||||||
|
export enum ContentType {
|
||||||
|
Json = "application/json",
|
||||||
|
FormData = "multipart/form-data",
|
||||||
|
UrlEncoded = "application/x-www-form-urlencoded",
|
||||||
|
Text = "text/plain",
|
||||||
|
}
|
||||||
|
|
||||||
|
export class HttpClient<SecurityDataType = unknown> {
|
||||||
|
public baseUrl: string = "//localhost:8080/api";
|
||||||
|
private securityData: SecurityDataType | null = null;
|
||||||
|
private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
|
||||||
|
private abortControllers = new Map<CancelToken, AbortController>();
|
||||||
|
private customFetch = (...fetchParams: Parameters<typeof fetch>) => fetch(...fetchParams);
|
||||||
|
|
||||||
|
private baseApiParams: RequestParams = {
|
||||||
|
credentials: "same-origin",
|
||||||
|
headers: {},
|
||||||
|
redirect: "follow",
|
||||||
|
referrerPolicy: "no-referrer",
|
||||||
|
};
|
||||||
|
|
||||||
|
constructor(apiConfig: ApiConfig<SecurityDataType> = {}) {
|
||||||
|
Object.assign(this, apiConfig);
|
||||||
|
}
|
||||||
|
|
||||||
|
public setSecurityData = (data: SecurityDataType | null) => {
|
||||||
|
this.securityData = data;
|
||||||
|
};
|
||||||
|
|
||||||
|
protected encodeQueryParam(key: string, value: any) {
|
||||||
|
const encodedKey = encodeURIComponent(key);
|
||||||
|
return `${encodedKey}=${encodeURIComponent(typeof value === "number" ? value : `${value}`)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected addQueryParam(query: QueryParamsType, key: string) {
|
||||||
|
return this.encodeQueryParam(key, query[key]);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected addArrayQueryParam(query: QueryParamsType, key: string) {
|
||||||
|
const value = query[key];
|
||||||
|
return value.map((v: any) => this.encodeQueryParam(key, v)).join("&");
|
||||||
|
}
|
||||||
|
|
||||||
|
protected toQueryString(rawQuery?: QueryParamsType): string {
|
||||||
|
const query = rawQuery || {};
|
||||||
|
const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]);
|
||||||
|
return keys
|
||||||
|
.map((key) => (Array.isArray(query[key]) ? this.addArrayQueryParam(query, key) : this.addQueryParam(query, key)))
|
||||||
|
.join("&");
|
||||||
|
}
|
||||||
|
|
||||||
|
protected addQueryParams(rawQuery?: QueryParamsType): string {
|
||||||
|
const queryString = this.toQueryString(rawQuery);
|
||||||
|
return queryString ? `?${queryString}` : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
private contentFormatters: Record<ContentType, (input: any) => any> = {
|
||||||
|
[ContentType.Json]: (input: any) =>
|
||||||
|
input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input,
|
||||||
|
[ContentType.Text]: (input: any) => (input !== null && typeof input !== "string" ? JSON.stringify(input) : input),
|
||||||
|
[ContentType.FormData]: (input: any) =>
|
||||||
|
Object.keys(input || {}).reduce((formData, key) => {
|
||||||
|
const property = input[key];
|
||||||
|
formData.append(
|
||||||
|
key,
|
||||||
|
property instanceof Blob
|
||||||
|
? property
|
||||||
|
: typeof property === "object" && property !== null
|
||||||
|
? JSON.stringify(property)
|
||||||
|
: `${property}`,
|
||||||
|
);
|
||||||
|
return formData;
|
||||||
|
}, new FormData()),
|
||||||
|
[ContentType.UrlEncoded]: (input: any) => this.toQueryString(input),
|
||||||
|
};
|
||||||
|
|
||||||
|
protected mergeRequestParams(params1: RequestParams, params2?: RequestParams): RequestParams {
|
||||||
|
return {
|
||||||
|
...this.baseApiParams,
|
||||||
|
...params1,
|
||||||
|
...(params2 || {}),
|
||||||
|
headers: {
|
||||||
|
...(this.baseApiParams.headers || {}),
|
||||||
|
...(params1.headers || {}),
|
||||||
|
...((params2 && params2.headers) || {}),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
protected createAbortSignal = (cancelToken: CancelToken): AbortSignal | undefined => {
|
||||||
|
if (this.abortControllers.has(cancelToken)) {
|
||||||
|
const abortController = this.abortControllers.get(cancelToken);
|
||||||
|
if (abortController) {
|
||||||
|
return abortController.signal;
|
||||||
|
}
|
||||||
|
return void 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const abortController = new AbortController();
|
||||||
|
this.abortControllers.set(cancelToken, abortController);
|
||||||
|
return abortController.signal;
|
||||||
|
};
|
||||||
|
|
||||||
|
public abortRequest = (cancelToken: CancelToken) => {
|
||||||
|
const abortController = this.abortControllers.get(cancelToken);
|
||||||
|
|
||||||
|
if (abortController) {
|
||||||
|
abortController.abort();
|
||||||
|
this.abortControllers.delete(cancelToken);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
public request = async <T = any, E = any>({
|
||||||
|
body,
|
||||||
|
secure,
|
||||||
|
path,
|
||||||
|
type,
|
||||||
|
query,
|
||||||
|
format,
|
||||||
|
baseUrl,
|
||||||
|
cancelToken,
|
||||||
|
...params
|
||||||
|
}: FullRequestParams): Promise<HttpResponse<T, E>> => {
|
||||||
|
const secureParams =
|
||||||
|
((typeof secure === "boolean" ? secure : this.baseApiParams.secure) &&
|
||||||
|
this.securityWorker &&
|
||||||
|
(await this.securityWorker(this.securityData))) ||
|
||||||
|
{};
|
||||||
|
const requestParams = this.mergeRequestParams(params, secureParams);
|
||||||
|
const queryString = query && this.toQueryString(query);
|
||||||
|
const payloadFormatter = this.contentFormatters[type || ContentType.Json];
|
||||||
|
const responseFormat = format || requestParams.format;
|
||||||
|
|
||||||
|
return this.customFetch(`${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, {
|
||||||
|
...requestParams,
|
||||||
|
headers: {
|
||||||
|
...(requestParams.headers || {}),
|
||||||
|
...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}),
|
||||||
|
},
|
||||||
|
signal: (cancelToken ? this.createAbortSignal(cancelToken) : requestParams.signal) || null,
|
||||||
|
body: typeof body === "undefined" || body === null ? null : payloadFormatter(body),
|
||||||
|
}).then(async (response) => {
|
||||||
|
const r = response as HttpResponse<T, E>;
|
||||||
|
r.data = null as unknown as T;
|
||||||
|
r.error = null as unknown as E;
|
||||||
|
|
||||||
|
const data = !responseFormat
|
||||||
|
? r
|
||||||
|
: await response[responseFormat]()
|
||||||
|
.then((data) => {
|
||||||
|
if (r.ok) {
|
||||||
|
r.data = data;
|
||||||
|
} else {
|
||||||
|
r.error = data;
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
r.error = e;
|
||||||
|
return r;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (cancelToken) {
|
||||||
|
this.abortControllers.delete(cancelToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) throw data;
|
||||||
|
return data;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @title TTime API
|
||||||
|
* @version 0.0.1
|
||||||
|
* @license AGPL (https://www.gnu.org/licenses/agpl-3.0.html)
|
||||||
|
* @baseUrl //localhost:8080/api
|
||||||
|
* @externalDocs https://swagger.io/resources/open-api/
|
||||||
|
* @contact
|
||||||
|
*
|
||||||
|
* This is the API for TTime, a time tracking application.
|
||||||
|
*/
|
||||||
|
export class GenApi<SecurityDataType extends unknown> extends HttpClient<SecurityDataType> {
|
||||||
|
login = {
|
||||||
|
/**
|
||||||
|
* @description Logs in a user and returns a JWT token
|
||||||
|
*
|
||||||
|
* @tags Auth
|
||||||
|
* @name LoginCreate
|
||||||
|
* @summary Login
|
||||||
|
* @request POST:/login
|
||||||
|
*/
|
||||||
|
loginCreate: (body: TypesNewUser, params: RequestParams = {}) =>
|
||||||
|
this.request<TypesToken, string>({
|
||||||
|
path: `/login`,
|
||||||
|
method: "POST",
|
||||||
|
body: body,
|
||||||
|
type: ContentType.Json,
|
||||||
|
format: "json",
|
||||||
|
...params,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
loginrenew = {
|
||||||
|
/**
|
||||||
|
* @description Renews the users token.
|
||||||
|
*
|
||||||
|
* @tags Auth
|
||||||
|
* @name LoginrenewCreate
|
||||||
|
* @summary LoginRenews
|
||||||
|
* @request POST:/loginrenew
|
||||||
|
* @secure
|
||||||
|
*/
|
||||||
|
loginrenewCreate: (params: RequestParams = {}) =>
|
||||||
|
this.request<TypesToken, string>({
|
||||||
|
path: `/loginrenew`,
|
||||||
|
method: "POST",
|
||||||
|
secure: true,
|
||||||
|
format: "json",
|
||||||
|
...params,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
promoteToAdmin = {
|
||||||
|
/**
|
||||||
|
* @description Promote chosen user to site admin
|
||||||
|
*
|
||||||
|
* @tags User
|
||||||
|
* @name PromoteToAdminCreate
|
||||||
|
* @summary PromoteToAdmin
|
||||||
|
* @request POST:/promoteToAdmin
|
||||||
|
* @secure
|
||||||
|
*/
|
||||||
|
promoteToAdminCreate: (NewUser: TypesNewUser, params: RequestParams = {}) =>
|
||||||
|
this.request<TypesToken, string>({
|
||||||
|
path: `/promoteToAdmin`,
|
||||||
|
method: "POST",
|
||||||
|
body: NewUser,
|
||||||
|
secure: true,
|
||||||
|
type: ContentType.Json,
|
||||||
|
...params,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
register = {
|
||||||
|
/**
|
||||||
|
* @description Register a new user
|
||||||
|
*
|
||||||
|
* @tags Auth
|
||||||
|
* @name RegisterCreate
|
||||||
|
* @summary Register
|
||||||
|
* @request POST:/register
|
||||||
|
*/
|
||||||
|
registerCreate: (NewUser: TypesNewUser, params: RequestParams = {}) =>
|
||||||
|
this.request<string, string>({
|
||||||
|
path: `/register`,
|
||||||
|
method: "POST",
|
||||||
|
body: NewUser,
|
||||||
|
type: ContentType.Json,
|
||||||
|
...params,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
userdelete = {
|
||||||
|
/**
|
||||||
|
* @description UserDelete deletes a user from the database
|
||||||
|
*
|
||||||
|
* @tags User
|
||||||
|
* @name UserdeleteDelete
|
||||||
|
* @summary UserDelete
|
||||||
|
* @request DELETE:/userdelete/{username}
|
||||||
|
* @secure
|
||||||
|
*/
|
||||||
|
userdeleteDelete: (username: string, params: RequestParams = {}) =>
|
||||||
|
this.request<string, string>({
|
||||||
|
path: `/userdelete/${username}`,
|
||||||
|
method: "DELETE",
|
||||||
|
secure: true,
|
||||||
|
type: ContentType.Json,
|
||||||
|
...params,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
users = {
|
||||||
|
/**
|
||||||
|
* @description lists all users
|
||||||
|
*
|
||||||
|
* @tags User
|
||||||
|
* @name GetUsers
|
||||||
|
* @summary ListsAllUsers
|
||||||
|
* @request GET:/users/all
|
||||||
|
* @secure
|
||||||
|
*/
|
||||||
|
getUsers: (params: RequestParams = {}) =>
|
||||||
|
this.request<string[], string>({
|
||||||
|
path: `/users/all`,
|
||||||
|
method: "GET",
|
||||||
|
secure: true,
|
||||||
|
format: "json",
|
||||||
|
...params,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
|
@ -1,39 +1,35 @@
|
||||||
import { APIResponse, api } from "../API/API";
|
import { api } from "../API/API";
|
||||||
import { NewProjMember } from "../Types/goTypes";
|
|
||||||
|
export interface AddMemberInfo {
|
||||||
|
userName: string;
|
||||||
|
projectName: string;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tries to add a member to a project
|
* Tries to add a member to a project
|
||||||
* @param {Object} props - A NewProjMember
|
* @param {AddMemberInfo} props.membertoAdd - Contains user's name and project's name
|
||||||
* @returns {boolean} True if added, false if not
|
* @returns {Promise<void>}
|
||||||
*/
|
*/
|
||||||
function AddMember(props: { memberToAdd: NewProjMember }): boolean {
|
async function AddMember(props: { memberToAdd: AddMemberInfo }): Promise<void> {
|
||||||
let added = false;
|
if (props.memberToAdd.userName === "") {
|
||||||
if (
|
alert("You must choose at least one user to add");
|
||||||
props.memberToAdd.username === "" ||
|
return;
|
||||||
props.memberToAdd.role === "" ||
|
|
||||||
props.memberToAdd.projectname === ""
|
|
||||||
) {
|
|
||||||
alert("All fields must be filled before adding");
|
|
||||||
return added;
|
|
||||||
}
|
}
|
||||||
api
|
try {
|
||||||
.addUserToProject(
|
const response = await api.addUserToProject(
|
||||||
props.memberToAdd,
|
props.memberToAdd,
|
||||||
localStorage.getItem("accessToken") ?? "",
|
localStorage.getItem("accessToken") ?? "",
|
||||||
)
|
);
|
||||||
.then((response: APIResponse<NewProjMember>) => {
|
if (response.success) {
|
||||||
if (response.success) {
|
alert(`[${props.memberToAdd.userName}] added`);
|
||||||
alert("Member added");
|
} else {
|
||||||
added = true;
|
alert(`[${props.memberToAdd.userName}] not added`);
|
||||||
} else {
|
console.error(response.message);
|
||||||
alert("Member not added");
|
}
|
||||||
console.error(response.message);
|
} catch (error) {
|
||||||
}
|
alert(`[${props.memberToAdd.userName}] not added`);
|
||||||
})
|
console.error("An error occurred during member add:", error);
|
||||||
.catch((error) => {
|
}
|
||||||
console.error("An error occurred during member add:", error);
|
|
||||||
});
|
|
||||||
return added;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default AddMember;
|
export default AddMember;
|
||||||
|
|
|
@ -1,38 +1,10 @@
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { APIResponse, api } from "../API/API";
|
import { 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";
|
||||||
|
|
||||||
/**
|
|
||||||
* Tries to add a project to the system
|
|
||||||
* @param {Object} props - Project name and description
|
|
||||||
* @returns {boolean} True if created, false if not
|
|
||||||
*/
|
|
||||||
function CreateProject(props: { name: string; description: string }): boolean {
|
|
||||||
const project: NewProject = {
|
|
||||||
name: props.name,
|
|
||||||
description: props.description,
|
|
||||||
};
|
|
||||||
|
|
||||||
let created = false;
|
|
||||||
|
|
||||||
api
|
|
||||||
.createProject(project, localStorage.getItem("accessToken") ?? "")
|
|
||||||
.then((response: APIResponse<Project>) => {
|
|
||||||
if (response.success) {
|
|
||||||
created = true;
|
|
||||||
} else {
|
|
||||||
console.error(response.message);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
|
||||||
console.error("An error occurred during creation:", error);
|
|
||||||
});
|
|
||||||
return created;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Provides UI for adding a project to the system.
|
* Provides UI for adding a project to the system.
|
||||||
* @returns {JSX.Element} - Returns the component UI for adding a project
|
* @returns {JSX.Element} - Returns the component UI for adding a project
|
||||||
|
@ -41,6 +13,33 @@ function AddProject(): JSX.Element {
|
||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
const [description, setDescription] = useState("");
|
const [description, setDescription] = useState("");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tries to add a project to the system
|
||||||
|
*/
|
||||||
|
const handleCreateProject = async (): Promise<void> => {
|
||||||
|
const project: NewProject = {
|
||||||
|
name: name.replace(/ /g, ""),
|
||||||
|
description: description.trim(),
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const response = await api.createProject(
|
||||||
|
project,
|
||||||
|
localStorage.getItem("accessToken") ?? "",
|
||||||
|
);
|
||||||
|
if (response.success) {
|
||||||
|
alert(`${project.name} added!`);
|
||||||
|
setDescription("");
|
||||||
|
setName("");
|
||||||
|
} else {
|
||||||
|
alert("Project not added, name could be taken");
|
||||||
|
console.error(response.message);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
alert("Project not added");
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col h-fit w-screen items-center justify-center">
|
<div className="flex flex-col h-fit w-screen items-center justify-center">
|
||||||
<div className="border-4 border-black bg-white flex flex-col items-center justify-center h-fit w-fit rounded-3xl content-center pl-20 pr-20">
|
<div className="border-4 border-black bg-white flex flex-col items-center justify-center h-fit w-fit rounded-3xl content-center pl-20 pr-20">
|
||||||
|
@ -48,7 +47,7 @@ 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 });
|
void handleCreateProject();
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<img
|
<img
|
||||||
|
@ -59,22 +58,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"
|
||||||
|
|
|
@ -1,72 +1,86 @@
|
||||||
import { useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { NewProjMember } from "../Types/goTypes";
|
|
||||||
import Button from "./Button";
|
import Button from "./Button";
|
||||||
import GetAllUsers from "./GetAllUsers";
|
import AddMember, { AddMemberInfo } from "./AddMember";
|
||||||
import AddMember from "./AddMember";
|
|
||||||
import BackButton from "./BackButton";
|
import BackButton from "./BackButton";
|
||||||
|
import GetUsersInProject, { ProjectMember } from "./GetUsersInProject";
|
||||||
|
import GetAllUsers from "./GetAllUsers";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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 [names, setNames] = useState<string[]>([]);
|
||||||
const [users, setUsers] = useState<string[]>([]);
|
const [users, setUsers] = useState<string[]>([]);
|
||||||
const [role, setRole] = useState("");
|
const [usersProj, setUsersProj] = useState<ProjectMember[]>([]);
|
||||||
GetAllUsers({ setUsersProp: setUsers });
|
|
||||||
|
|
||||||
const handleClick = (): boolean => {
|
// Gets all users and project members for filtering
|
||||||
const newMember: NewProjMember = {
|
GetAllUsers({ setUsersProp: setUsers });
|
||||||
username: name,
|
GetUsersInProject({
|
||||||
projectname: localStorage.getItem("projectName") ?? "",
|
setUsersProp: setUsersProj,
|
||||||
role: role,
|
projectName: props.projectName,
|
||||||
};
|
});
|
||||||
return AddMember({ memberToAdd: newMember });
|
/*
|
||||||
|
* Filters the members from users so that users who are already
|
||||||
|
* members are not shown
|
||||||
|
*/
|
||||||
|
useEffect(() => {
|
||||||
|
setUsers((prevUsers) => {
|
||||||
|
const filteredUsers = prevUsers.filter(
|
||||||
|
(user) =>
|
||||||
|
!usersProj.some((projectUser) => projectUser.Username === user),
|
||||||
|
);
|
||||||
|
return filteredUsers;
|
||||||
|
});
|
||||||
|
}, [usersProj]);
|
||||||
|
|
||||||
|
// Attempts to add all of the selected users to the project
|
||||||
|
const handleAddClick = async (): Promise<void> => {
|
||||||
|
if (names.length === 0)
|
||||||
|
alert("You have to choose at least one user to add");
|
||||||
|
for (const name of names) {
|
||||||
|
const newMember: AddMemberInfo = {
|
||||||
|
userName: name,
|
||||||
|
projectName: props.projectName,
|
||||||
|
};
|
||||||
|
await AddMember({ memberToAdd: newMember });
|
||||||
|
}
|
||||||
|
setNames([]);
|
||||||
|
location.reload();
|
||||||
|
};
|
||||||
|
|
||||||
|
// Updates the names that have been selected
|
||||||
|
const handleUserClick = (user: string): void => {
|
||||||
|
setNames((prevNames): string[] => {
|
||||||
|
if (!prevNames.includes(user)) {
|
||||||
|
return [...prevNames, user];
|
||||||
|
}
|
||||||
|
return prevNames.filter((name) => name !== user);
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="border-4 border-black bg-white flex flex-col items-center justify-center rounded-3xl content-center pl-20 pr-20 h-[75vh] w-[50vh]">
|
<div className="border-4 border-black bg-white flex flex-col items-center pt-10 rounded-3xl content-center pl-20 pr-20 h-[63vh] w-[50] overflow-auto">
|
||||||
<p className="pb-4 mb-2 text-center font-bold text-[18px]">
|
<h1 className="text-center font-bold text-[36px] pb-10">
|
||||||
User chosen: [{name}]
|
{props.projectName}
|
||||||
|
</h1>
|
||||||
|
<p className="p-1 text-center font-bold text-[26px]">
|
||||||
|
Choose users to add:
|
||||||
</p>
|
</p>
|
||||||
<p className="pb-4 mb-2 text-center font-bold text-[18px]">
|
<div className="border-2 border-black pl-2 pr-2 pb-2 rounded-xl text-center overflow-auto h-[26vh] w-[26vh]">
|
||||||
Role chosen: [{role}]
|
|
||||||
</p>
|
|
||||||
<p className="pb-4 mb-2 text-center font-bold text-[18px]">
|
|
||||||
Project chosen: [{localStorage.getItem("projectName") ?? ""}]
|
|
||||||
</p>
|
|
||||||
<p className="p-1">Choose role:</p>
|
|
||||||
<div className="border-2 border-black p-2 rounded-xl text-center h-[10h] w-[16vh]">
|
|
||||||
<ul className="text-center items-center font-medium space-y-2">
|
|
||||||
<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"
|
|
||||||
onClick={() => {
|
|
||||||
setRole("member");
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{"Member"}
|
|
||||||
</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"
|
|
||||||
onClick={() => {
|
|
||||||
setRole("project_manager");
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{"Project manager"}
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
<p className="p-1">Choose user:</p>
|
|
||||||
<div className="border-2 border-black p-2 rounded-xl text-center overflow-scroll h-[26vh] w-[26vh]">
|
|
||||||
<ul className="text-center font-medium space-y-2">
|
<ul className="text-center font-medium space-y-2">
|
||||||
<div></div>
|
<div></div>
|
||||||
{users.map((user) => (
|
{users.map((user) => (
|
||||||
<li
|
<li
|
||||||
className="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={
|
||||||
|
names.includes(user)
|
||||||
|
? "items-start p-1 border-2 border-transparent rounded-full bg-orange-500 hover:bg-orange-600 text-white hover:cursor-pointer ring-2 ring-black"
|
||||||
|
: "items-start p-1 border-2 border-black rounded-full bg-orange-200 hover:bg-orange-400 hover:text-slate-100 hover:cursor-pointer"
|
||||||
|
}
|
||||||
key={user}
|
key={user}
|
||||||
value={user}
|
value={user}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setName(user);
|
handleUserClick(user);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<span>{user}</span>
|
<span>{user}</span>
|
||||||
|
@ -74,13 +88,16 @@ function AddUserToProject(): JSX.Element {
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex space-x-5 items-center justify-between">
|
<p className="pt-10 pb-5 underline text-center font-bold text-[18px]">
|
||||||
|
Number of users to be added: {names.length}
|
||||||
|
</p>
|
||||||
|
<div className="space-x-10 items-center">
|
||||||
<Button
|
<Button
|
||||||
text="Add"
|
text="Add"
|
||||||
onClick={(): void => {
|
onClick={(): void => {
|
||||||
handleClick();
|
void handleAddClick();
|
||||||
}}
|
}}
|
||||||
type="submit"
|
type="button"
|
||||||
/>
|
/>
|
||||||
<BackButton />
|
<BackButton />
|
||||||
</div>
|
</div>
|
||||||
|
|
|
@ -17,7 +17,7 @@ function AllTimeReportsInProject(): JSX.Element {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const getWeeklyReports = async (): Promise<void> => {
|
const getWeeklyReports = async (): Promise<void> => {
|
||||||
const token = localStorage.getItem("accessToken") ?? "";
|
const token = localStorage.getItem("accessToken") ?? "";
|
||||||
const response = await api.getWeeklyReportsForUser(
|
const response = await api.getAllWeeklyReportsForUser(
|
||||||
projectName ?? "",
|
projectName ?? "",
|
||||||
token,
|
token,
|
||||||
);
|
);
|
||||||
|
|
|
@ -1,8 +1,9 @@
|
||||||
//Info: This component is used to display all the time reports for a project. It will display the week number,
|
//Info: This component is used to display all the time reports for a project. It will display the week number,
|
||||||
//total time spent, and if the report has been signed or not. The user can click on a report to edit it.
|
//total time spent, and if the report has been signed or not. The user can click on a report to edit it.
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { NewWeeklyReport } from "../Types/goTypes";
|
import { WeeklyReport } from "../Types/goTypes";
|
||||||
import { Link, useParams } from "react-router-dom";
|
import { Link, useParams } from "react-router-dom";
|
||||||
|
import { api } from "../API/API";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders a component that displays all the time reports for a specific project.
|
* Renders a component that displays all the time reports for a specific project.
|
||||||
|
@ -11,15 +12,15 @@ import { Link, useParams } from "react-router-dom";
|
||||||
function AllTimeReportsInProject(): JSX.Element {
|
function AllTimeReportsInProject(): JSX.Element {
|
||||||
const { username } = useParams();
|
const { username } = useParams();
|
||||||
const { projectName } = useParams();
|
const { projectName } = useParams();
|
||||||
const [weeklyReports, setWeeklyReports] = useState<NewWeeklyReport[]>([]);
|
const [weeklyReports, setWeeklyReports] = useState<WeeklyReport[]>([]);
|
||||||
|
|
||||||
/* // Call getProjects when the component mounts
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const getWeeklyReports = async (): Promise<void> => {
|
const getWeeklyReports = async (): Promise<void> => {
|
||||||
const token = localStorage.getItem("accessToken") ?? "";
|
const token = localStorage.getItem("accessToken") ?? "";
|
||||||
const response = await api.getWeeklyReportsForUser(
|
const response = await api.getAllWeeklyReportsForUser(
|
||||||
projectName ?? "",
|
projectName ?? "",
|
||||||
token,
|
token,
|
||||||
|
username ?? "",
|
||||||
);
|
);
|
||||||
console.log(response);
|
console.log(response);
|
||||||
if (response.success) {
|
if (response.success) {
|
||||||
|
@ -27,41 +28,10 @@ function AllTimeReportsInProject(): JSX.Element {
|
||||||
} else {
|
} else {
|
||||||
console.error(response.message);
|
console.error(response.message);
|
||||||
}
|
}
|
||||||
}; */
|
};
|
||||||
// Mock data
|
|
||||||
const getWeeklyReports = async (): Promise<void> => {
|
|
||||||
// Simulate a delay
|
|
||||||
await Promise.resolve();
|
|
||||||
const mockWeeklyReports: NewWeeklyReport[] = [
|
|
||||||
{
|
|
||||||
projectName: "Project 1",
|
|
||||||
week: 1,
|
|
||||||
developmentTime: 10,
|
|
||||||
meetingTime: 2,
|
|
||||||
adminTime: 1,
|
|
||||||
ownWorkTime: 3,
|
|
||||||
studyTime: 4,
|
|
||||||
testingTime: 5,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
projectName: "Project 1",
|
|
||||||
week: 2,
|
|
||||||
developmentTime: 8,
|
|
||||||
meetingTime: 2,
|
|
||||||
adminTime: 1,
|
|
||||||
ownWorkTime: 3,
|
|
||||||
studyTime: 4,
|
|
||||||
testingTime: 5,
|
|
||||||
},
|
|
||||||
// Add more reports as needed
|
|
||||||
];
|
|
||||||
|
|
||||||
// Use the mock data instead of the real data
|
|
||||||
setWeeklyReports(mockWeeklyReports);
|
|
||||||
};
|
|
||||||
useEffect(() => {
|
|
||||||
void getWeeklyReports();
|
void getWeeklyReports();
|
||||||
}, []);
|
}, [projectName, username]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
@ -90,7 +60,7 @@ function AllTimeReportsInProject(): JSX.Element {
|
||||||
</h1>
|
</h1>
|
||||||
<h1>
|
<h1>
|
||||||
<span className="font-bold">{"Signed: "}</span>
|
<span className="font-bold">{"Signed: "}</span>
|
||||||
NO
|
{newWeeklyReport.signedBy ? "YES" : "NO"}
|
||||||
</h1>
|
</h1>
|
||||||
</div>
|
</div>
|
||||||
</Link>
|
</Link>
|
||||||
|
|
37
frontend/src/Components/ChangeRole.tsx
Normal file
37
frontend/src/Components/ChangeRole.tsx
Normal 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);
|
||||||
|
});
|
||||||
|
}
|
73
frontend/src/Components/ChangeRoleView.tsx
Normal file
73
frontend/src/Components/ChangeRoleView.tsx
Normal file
|
@ -0,0 +1,73 @@
|
||||||
|
import { useState } from "react";
|
||||||
|
import Button from "./Button";
|
||||||
|
import ChangeRole, { ProjectRoleChange } from "./ChangeRole";
|
||||||
|
|
||||||
|
export default function ChangeRoleView(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>
|
||||||
|
);
|
||||||
|
}
|
|
@ -1,61 +1,29 @@
|
||||||
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 === "" ||
|
||||||
|
props.nameChange.newName === props.nameChange.prevName
|
||||||
|
) {
|
||||||
|
alert("You have to give a new name\n\nName not changed");
|
||||||
|
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, name could be taken");
|
||||||
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;
|
||||||
|
|
33
frontend/src/Components/DeleteProject.tsx
Normal file
33
frontend/src/Components/DeleteProject.tsx
Normal 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;
|
|
@ -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;
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,93 +1,38 @@
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { Link, useParams } from "react-router-dom";
|
import { Link, useParams } from "react-router-dom";
|
||||||
|
import { api } from "../API/API";
|
||||||
|
import { WeeklyReport } from "../Types/goTypes";
|
||||||
|
|
||||||
interface UnsignedReports {
|
|
||||||
projectName: string;
|
|
||||||
username: string;
|
|
||||||
week: number;
|
|
||||||
signed: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Renders a component that displays the projects a user is a part of and links to the projects start-page.
|
|
||||||
* @returns The JSX element representing the component.
|
|
||||||
*/
|
|
||||||
function DisplayUserProject(): JSX.Element {
|
function DisplayUserProject(): JSX.Element {
|
||||||
const { projectName } = useParams();
|
const { projectName } = useParams();
|
||||||
const [unsignedReports, setUnsignedReports] = useState<UnsignedReports[]>([]);
|
const [unsignedReports, setUnsignedReports] = useState<WeeklyReport[]>([]);
|
||||||
//const navigate = useNavigate();
|
const [usernames, setUsernames] = useState<string[]>([]);
|
||||||
|
const token = localStorage.getItem("accessToken") ?? "";
|
||||||
|
|
||||||
// const getUnsignedReports = async (): Promise<void> => {
|
|
||||||
// const token = localStorage.getItem("accessToken") ?? "";
|
|
||||||
// const response = await api.getUserProjects(token);
|
|
||||||
// console.log(response);
|
|
||||||
// if (response.success) {
|
|
||||||
// setUnsignedReports(response.data ?? []);
|
|
||||||
// } else {
|
|
||||||
// console.error(response.message);
|
|
||||||
// }
|
|
||||||
// };
|
|
||||||
|
|
||||||
// const handleReportClick = async (projectName: string): Promise<void> => {
|
|
||||||
// const username = localStorage.getItem("username") ?? "";
|
|
||||||
// const token = localStorage.getItem("accessToken") ?? "";
|
|
||||||
// const response = await api.checkIfProjectManager(
|
|
||||||
// username,
|
|
||||||
// projectName,
|
|
||||||
// token,
|
|
||||||
// );
|
|
||||||
// if (response.success) {
|
|
||||||
// if (response.data) {
|
|
||||||
// navigate(`/PMProjectPage/${projectName}`);
|
|
||||||
// } else {
|
|
||||||
// navigate(`/project/${projectName}`);
|
|
||||||
// }
|
|
||||||
// } else {
|
|
||||||
// // handle error
|
|
||||||
// console.error(response.message);
|
|
||||||
// }
|
|
||||||
// };
|
|
||||||
|
|
||||||
const getUnsignedReports = async (): Promise<void> => {
|
|
||||||
// Simulate a delay
|
|
||||||
await Promise.resolve();
|
|
||||||
|
|
||||||
// Use mock data
|
|
||||||
const reports: UnsignedReports[] = [
|
|
||||||
{
|
|
||||||
projectName: "projecttest",
|
|
||||||
username: "user1",
|
|
||||||
week: 2,
|
|
||||||
signed: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
projectName: "projecttest",
|
|
||||||
username: "user2",
|
|
||||||
week: 2,
|
|
||||||
signed: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
projectName: "projecttest",
|
|
||||||
username: "user3",
|
|
||||||
week: 2,
|
|
||||||
signed: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
projectName: "projecttest",
|
|
||||||
username: "user4",
|
|
||||||
week: 2,
|
|
||||||
signed: false,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
// Set the state with the mock data
|
|
||||||
setUnsignedReports(reports);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Call getProjects when the component mounts
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
const getUnsignedReports = async (): Promise<void> => {
|
||||||
|
const response = await api.getUnsignedReportsInProject(
|
||||||
|
projectName ?? "",
|
||||||
|
token,
|
||||||
|
);
|
||||||
|
console.log(response);
|
||||||
|
if (response.success) {
|
||||||
|
setUnsignedReports(response.data ?? []);
|
||||||
|
const usernamesPromises = (response.data ?? []).map((report) =>
|
||||||
|
api.getUsername(report.userId, token),
|
||||||
|
);
|
||||||
|
const usernamesResponses = await Promise.all(usernamesPromises);
|
||||||
|
const usernames = usernamesResponses.map(
|
||||||
|
(res) => (res.data as { username?: string }).username ?? "",
|
||||||
|
);
|
||||||
|
setUsernames(usernames);
|
||||||
|
} else {
|
||||||
|
console.error(response.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
void getUnsignedReports();
|
void getUnsignedReports();
|
||||||
}, []);
|
}, [projectName, token]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
@ -95,32 +40,40 @@ function DisplayUserProject(): JSX.Element {
|
||||||
All Unsigned Reports In: {projectName}{" "}
|
All Unsigned Reports In: {projectName}{" "}
|
||||||
</h1>
|
</h1>
|
||||||
<div className="border-4 border-black bg-white flex flex-col items-center justify-center min-h-[65vh] h-fit w-[70vw] rounded-3xl content-center overflow-scroll space-y-[10vh] p-[30px] text-[20px]">
|
<div className="border-4 border-black bg-white flex flex-col items-center justify-center min-h-[65vh] h-fit w-[70vw] rounded-3xl content-center overflow-scroll space-y-[10vh] p-[30px] text-[20px]">
|
||||||
{unsignedReports.map(
|
{unsignedReports.map((unsignedReport: WeeklyReport, index: number) => (
|
||||||
(unsignedReport: UnsignedReports, index: number) => (
|
<h1 key={index} className="border-b-2 border-black w-full">
|
||||||
<h1 key={index} className="border-b-2 border-black w-full">
|
<div className="flex justify-between">
|
||||||
<div className="flex justify-between">
|
<div className="flex">
|
||||||
<div className="flex">
|
<span className="ml-6 mr-2 font-bold">Username:</span>
|
||||||
<h1>{unsignedReport.username}</h1>
|
<h1>{usernames[index]}</h1>{" "}
|
||||||
<span className="ml-6 mr-2 font-bold">Week:</span>
|
<span className="ml-6 mr-2 font-bold">Week:</span>
|
||||||
<h1>{unsignedReport.week}</h1>
|
<h1>{unsignedReport.week}</h1>
|
||||||
<span className="ml-6 mr-2 font-bold">Signed:</span>
|
<span className="ml-6 mr-2 font-bold">Total Time:</span>
|
||||||
<h1>NO</h1>
|
<h1>
|
||||||
</div>
|
{unsignedReport.developmentTime +
|
||||||
<div className="flex">
|
unsignedReport.meetingTime +
|
||||||
<div className="ml-auto flex space-x-4">
|
unsignedReport.adminTime +
|
||||||
<Link
|
unsignedReport.ownWorkTime +
|
||||||
to={`/PMViewUnsignedReport/${projectName}/${unsignedReport.username}/${unsignedReport.week}`}
|
unsignedReport.studyTime +
|
||||||
>
|
unsignedReport.testingTime}
|
||||||
<h1 className="underline cursor-pointer font-bold">
|
</h1>
|
||||||
View Report
|
<span className="ml-6 mr-2 font-bold">Signed:</span>
|
||||||
</h1>
|
<h1>NO</h1>
|
||||||
</Link>
|
</div>
|
||||||
</div>
|
<div className="flex">
|
||||||
|
<div className="ml-auto flex space-x-4">
|
||||||
|
<Link
|
||||||
|
to={`/PMViewUnsignedReport/${projectName}/${usernames[index]}/${unsignedReport.week}`}
|
||||||
|
>
|
||||||
|
<h1 className="underline cursor-pointer font-bold">
|
||||||
|
View Report
|
||||||
|
</h1>
|
||||||
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</h1>
|
</div>
|
||||||
),
|
</h1>
|
||||||
)}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
import { useState, useEffect } from "react";
|
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 { api } from "../API/API";
|
import { api } from "../API/API";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -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>
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { WeeklyReport, NewWeeklyReport } from "../Types/goTypes";
|
import { WeeklyReport, UpdateWeeklyReport } from "../Types/goTypes";
|
||||||
import { api } from "../API/API";
|
import { api } from "../API/API";
|
||||||
import { useNavigate, useParams } from "react-router-dom";
|
import { useNavigate, useParams } from "react-router-dom";
|
||||||
import Button from "./Button";
|
import Button from "./Button";
|
||||||
|
@ -22,6 +22,7 @@ export default function GetWeeklyReport(): JSX.Element {
|
||||||
projectName: string;
|
projectName: string;
|
||||||
fetchedWeek: string;
|
fetchedWeek: string;
|
||||||
}>();
|
}>();
|
||||||
|
const username = localStorage.getItem("userName") ?? "";
|
||||||
console.log(projectName, fetchedWeek);
|
console.log(projectName, fetchedWeek);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
@ -60,8 +61,9 @@ export default function GetWeeklyReport(): JSX.Element {
|
||||||
void fetchWeeklyReport();
|
void fetchWeeklyReport();
|
||||||
}, [projectName, fetchedWeek, token]);
|
}, [projectName, fetchedWeek, token]);
|
||||||
|
|
||||||
const handleNewWeeklyReport = async (): Promise<void> => {
|
const handleUpdateWeeklyReport = async (): Promise<void> => {
|
||||||
const newWeeklyReport: NewWeeklyReport = {
|
const updateWeeklyReport: UpdateWeeklyReport = {
|
||||||
|
userName: username,
|
||||||
projectName: projectName ?? "",
|
projectName: projectName ?? "",
|
||||||
week,
|
week,
|
||||||
developmentTime,
|
developmentTime,
|
||||||
|
@ -72,7 +74,7 @@ export default function GetWeeklyReport(): JSX.Element {
|
||||||
testingTime,
|
testingTime,
|
||||||
};
|
};
|
||||||
|
|
||||||
await api.submitWeeklyReport(newWeeklyReport, token);
|
await api.updateWeeklyReport(updateWeeklyReport, token);
|
||||||
};
|
};
|
||||||
|
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
@ -89,7 +91,8 @@ export default function GetWeeklyReport(): JSX.Element {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
void handleNewWeeklyReport();
|
void handleUpdateWeeklyReport();
|
||||||
|
alert("Changes submitted");
|
||||||
navigate(-1);
|
navigate(-1);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
@ -128,7 +131,12 @@ export default function GetWeeklyReport(): JSX.Element {
|
||||||
}}
|
}}
|
||||||
onKeyDown={(event) => {
|
onKeyDown={(event) => {
|
||||||
const keyValue = event.key;
|
const keyValue = event.key;
|
||||||
if (!/\d/.test(keyValue) && keyValue !== "Backspace")
|
if (
|
||||||
|
!/\d/.test(keyValue) &&
|
||||||
|
keyValue !== "Backspace" &&
|
||||||
|
keyValue !== "ArrowLeft" &&
|
||||||
|
keyValue !== "ArrowRight"
|
||||||
|
)
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
@ -152,7 +160,12 @@ export default function GetWeeklyReport(): JSX.Element {
|
||||||
}}
|
}}
|
||||||
onKeyDown={(event) => {
|
onKeyDown={(event) => {
|
||||||
const keyValue = event.key;
|
const keyValue = event.key;
|
||||||
if (!/\d/.test(keyValue) && keyValue !== "Backspace")
|
if (
|
||||||
|
!/\d/.test(keyValue) &&
|
||||||
|
keyValue !== "Backspace" &&
|
||||||
|
keyValue !== "ArrowLeft" &&
|
||||||
|
keyValue !== "ArrowRight"
|
||||||
|
)
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
@ -176,7 +189,12 @@ export default function GetWeeklyReport(): JSX.Element {
|
||||||
}}
|
}}
|
||||||
onKeyDown={(event) => {
|
onKeyDown={(event) => {
|
||||||
const keyValue = event.key;
|
const keyValue = event.key;
|
||||||
if (!/\d/.test(keyValue) && keyValue !== "Backspace")
|
if (
|
||||||
|
!/\d/.test(keyValue) &&
|
||||||
|
keyValue !== "Backspace" &&
|
||||||
|
keyValue !== "ArrowLeft" &&
|
||||||
|
keyValue !== "ArrowRight"
|
||||||
|
)
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
@ -200,7 +218,12 @@ export default function GetWeeklyReport(): JSX.Element {
|
||||||
}}
|
}}
|
||||||
onKeyDown={(event) => {
|
onKeyDown={(event) => {
|
||||||
const keyValue = event.key;
|
const keyValue = event.key;
|
||||||
if (!/\d/.test(keyValue) && keyValue !== "Backspace")
|
if (
|
||||||
|
!/\d/.test(keyValue) &&
|
||||||
|
keyValue !== "Backspace" &&
|
||||||
|
keyValue !== "ArrowLeft" &&
|
||||||
|
keyValue !== "ArrowRight"
|
||||||
|
)
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
@ -224,7 +247,12 @@ export default function GetWeeklyReport(): JSX.Element {
|
||||||
}}
|
}}
|
||||||
onKeyDown={(event) => {
|
onKeyDown={(event) => {
|
||||||
const keyValue = event.key;
|
const keyValue = event.key;
|
||||||
if (!/\d/.test(keyValue) && keyValue !== "Backspace")
|
if (
|
||||||
|
!/\d/.test(keyValue) &&
|
||||||
|
keyValue !== "Backspace" &&
|
||||||
|
keyValue !== "ArrowLeft" &&
|
||||||
|
keyValue !== "ArrowRight"
|
||||||
|
)
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
@ -248,7 +276,12 @@ export default function GetWeeklyReport(): JSX.Element {
|
||||||
}}
|
}}
|
||||||
onKeyDown={(event) => {
|
onKeyDown={(event) => {
|
||||||
const keyValue = event.key;
|
const keyValue = event.key;
|
||||||
if (!/\d/.test(keyValue) && keyValue !== "Backspace")
|
if (
|
||||||
|
!/\d/.test(keyValue) &&
|
||||||
|
keyValue !== "Backspace" &&
|
||||||
|
keyValue !== "ArrowLeft" &&
|
||||||
|
keyValue !== "ArrowRight"
|
||||||
|
)
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
59
frontend/src/Components/GetProjectTimes.tsx
Normal file
59
frontend/src/Components/GetProjectTimes.tsx
Normal 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;
|
|
@ -4,14 +4,17 @@ 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[]>>;
|
||||||
|
username: string;
|
||||||
}): void {
|
}): void {
|
||||||
const setProjects: Dispatch<React.SetStateAction<Project[]>> =
|
const setProjects: Dispatch<React.SetStateAction<Project[]>> =
|
||||||
props.setProjectsProp;
|
props.setProjectsProp;
|
||||||
|
@ -19,7 +22,7 @@ function GetProjects(props: {
|
||||||
const fetchUsers = async (): Promise<void> => {
|
const fetchUsers = async (): Promise<void> => {
|
||||||
try {
|
try {
|
||||||
const token = localStorage.getItem("accessToken") ?? "";
|
const token = localStorage.getItem("accessToken") ?? "";
|
||||||
const response = await api.getUserProjects(token);
|
const response = await api.getUserProjects(props.username, token);
|
||||||
if (response.success) {
|
if (response.success) {
|
||||||
setProjects(response.data ?? []);
|
setProjects(response.data ?? []);
|
||||||
} else {
|
} else {
|
||||||
|
@ -31,7 +34,7 @@ function GetProjects(props: {
|
||||||
};
|
};
|
||||||
|
|
||||||
void fetchUsers();
|
void fetchUsers();
|
||||||
}, [setProjects]);
|
}, [props.username, setProjects]);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default GetProjects;
|
export default GetProjects;
|
||||||
|
|
|
@ -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();
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
//info: Header component to display the header of the page including the logo and user information where thr user can logout
|
//info: Header component to display the header of the page including the logo and user information where thr user can logout
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { Link } from "react-router-dom";
|
import { Link, useNavigate } from "react-router-dom";
|
||||||
import backgroundImage from "../assets/1.jpg";
|
import backgroundImage from "../assets/1.jpg";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -9,23 +9,33 @@ import backgroundImage from "../assets/1.jpg";
|
||||||
*/
|
*/
|
||||||
function Header(): JSX.Element {
|
function Header(): JSX.Element {
|
||||||
const [isOpen, setIsOpen] = useState(false);
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
|
const username = localStorage.getItem("username");
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const handleLogout = (): void => {
|
const handleLogout = (): void => {
|
||||||
localStorage.clear();
|
localStorage.clear();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleNavigation = (): void => {
|
||||||
|
if (username === "admin") {
|
||||||
|
navigate("/admin");
|
||||||
|
} else {
|
||||||
|
navigate("/yourProjects");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<header
|
<header
|
||||||
className="fixed top-0 left-0 right-0 border-[1.75px] border-black text-black p-3 pl-5 flex items-center justify-between bg-cover"
|
className="fixed top-0 left-0 right-0 border-[1.75px] border-black text-black p-3 pl-5 flex items-center justify-between bg-cover"
|
||||||
style={{ backgroundImage: `url(${backgroundImage})` }}
|
style={{ backgroundImage: `url(${backgroundImage})` }}
|
||||||
>
|
>
|
||||||
<Link to="/your-projects">
|
<div onClick={handleNavigation}>
|
||||||
<img
|
<img
|
||||||
src="/src/assets/Logo.svg"
|
src="/src/assets/Logo.svg"
|
||||||
alt="TTIME Logo"
|
alt="TTIME Logo"
|
||||||
className="w-11 h-14 cursor-pointer"
|
className="w-11 h-14 cursor-pointer"
|
||||||
/>
|
/>
|
||||||
</Link>
|
</div>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
className="relative"
|
className="relative"
|
||||||
|
|
|
@ -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}
|
||||||
|
|
|
@ -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 => {
|
||||||
|
|
75
frontend/src/Components/MemberInfoModal.tsx
Normal file
75
frontend/src/Components/MemberInfoModal.tsx
Normal file
|
@ -0,0 +1,75 @@
|
||||||
|
import Button from "./Button";
|
||||||
|
import UserProjectListAdmin from "./UserProjectListAdmin";
|
||||||
|
import { useState } from "react";
|
||||||
|
import ChangeRoleView from "./ChangeRoleView";
|
||||||
|
import RemoveUserFromProj from "./RemoveUserFromProj";
|
||||||
|
|
||||||
|
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-10 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={"Remove"}
|
||||||
|
onClick={function (): void {
|
||||||
|
if (
|
||||||
|
window.confirm(
|
||||||
|
"Are you sure you want to remove this user from the project?",
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
RemoveUserFromProj({
|
||||||
|
userToRemove: props.username,
|
||||||
|
projectName: props.projectName,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
type="button"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
text={"Close"}
|
||||||
|
onClick={function (): void {
|
||||||
|
setShowRoles(false);
|
||||||
|
props.onClose();
|
||||||
|
}}
|
||||||
|
type="button"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default MemberInfoModal;
|
|
@ -62,7 +62,7 @@ export default function NewWeeklyReport(): JSX.Element {
|
||||||
const success = await handleNewWeeklyReport();
|
const success = await handleNewWeeklyReport();
|
||||||
if (!success) {
|
if (!success) {
|
||||||
alert(
|
alert(
|
||||||
"A Time Report for this week already exists, please go to the edit page to edit it or change week number.",
|
"Error occurred! Your connection to the server might be lost or a time report for this week already exists, please check your connection or go to the edit page to edit your report or change week number.",
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -139,7 +139,12 @@ export default function NewWeeklyReport(): JSX.Element {
|
||||||
}}
|
}}
|
||||||
onKeyDown={(event) => {
|
onKeyDown={(event) => {
|
||||||
const keyValue = event.key;
|
const keyValue = event.key;
|
||||||
if (!/\d/.test(keyValue) && keyValue !== "Backspace")
|
if (
|
||||||
|
!/\d/.test(keyValue) &&
|
||||||
|
keyValue !== "Backspace" &&
|
||||||
|
keyValue !== "ArrowLeft" &&
|
||||||
|
keyValue !== "ArrowRight"
|
||||||
|
)
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
@ -163,7 +168,12 @@ export default function NewWeeklyReport(): JSX.Element {
|
||||||
}}
|
}}
|
||||||
onKeyDown={(event) => {
|
onKeyDown={(event) => {
|
||||||
const keyValue = event.key;
|
const keyValue = event.key;
|
||||||
if (!/\d/.test(keyValue) && keyValue !== "Backspace")
|
if (
|
||||||
|
!/\d/.test(keyValue) &&
|
||||||
|
keyValue !== "Backspace" &&
|
||||||
|
keyValue !== "ArrowLeft" &&
|
||||||
|
keyValue !== "ArrowRight"
|
||||||
|
)
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
@ -187,7 +197,12 @@ export default function NewWeeklyReport(): JSX.Element {
|
||||||
}}
|
}}
|
||||||
onKeyDown={(event) => {
|
onKeyDown={(event) => {
|
||||||
const keyValue = event.key;
|
const keyValue = event.key;
|
||||||
if (!/\d/.test(keyValue) && keyValue !== "Backspace")
|
if (
|
||||||
|
!/\d/.test(keyValue) &&
|
||||||
|
keyValue !== "Backspace" &&
|
||||||
|
keyValue !== "ArrowLeft" &&
|
||||||
|
keyValue !== "ArrowRight"
|
||||||
|
)
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
@ -211,7 +226,12 @@ export default function NewWeeklyReport(): JSX.Element {
|
||||||
}}
|
}}
|
||||||
onKeyDown={(event) => {
|
onKeyDown={(event) => {
|
||||||
const keyValue = event.key;
|
const keyValue = event.key;
|
||||||
if (!/\d/.test(keyValue) && keyValue !== "Backspace")
|
if (
|
||||||
|
!/\d/.test(keyValue) &&
|
||||||
|
keyValue !== "Backspace" &&
|
||||||
|
keyValue !== "ArrowLeft" &&
|
||||||
|
keyValue !== "ArrowRight"
|
||||||
|
)
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
@ -235,7 +255,12 @@ export default function NewWeeklyReport(): JSX.Element {
|
||||||
}}
|
}}
|
||||||
onKeyDown={(event) => {
|
onKeyDown={(event) => {
|
||||||
const keyValue = event.key;
|
const keyValue = event.key;
|
||||||
if (!/\d/.test(keyValue) && keyValue !== "Backspace")
|
if (
|
||||||
|
!/\d/.test(keyValue) &&
|
||||||
|
keyValue !== "Backspace" &&
|
||||||
|
keyValue !== "ArrowLeft" &&
|
||||||
|
keyValue !== "ArrowRight"
|
||||||
|
)
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
@ -259,7 +284,12 @@ export default function NewWeeklyReport(): JSX.Element {
|
||||||
}}
|
}}
|
||||||
onKeyDown={(event) => {
|
onKeyDown={(event) => {
|
||||||
const keyValue = event.key;
|
const keyValue = event.key;
|
||||||
if (!/\d/.test(keyValue) && keyValue !== "Backspace")
|
if (
|
||||||
|
!/\d/.test(keyValue) &&
|
||||||
|
keyValue !== "Backspace" &&
|
||||||
|
keyValue !== "ArrowLeft" &&
|
||||||
|
keyValue !== "ArrowRight"
|
||||||
|
)
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
|
@ -29,6 +29,7 @@ export default function OtherUsersTR(): JSX.Element {
|
||||||
projectName ?? "",
|
projectName ?? "",
|
||||||
fetchedWeek?.toString() ?? "0",
|
fetchedWeek?.toString() ?? "0",
|
||||||
token,
|
token,
|
||||||
|
username ?? "",
|
||||||
);
|
);
|
||||||
|
|
||||||
if (response.success) {
|
if (response.success) {
|
||||||
|
@ -86,6 +87,7 @@ export default function OtherUsersTR(): JSX.Element {
|
||||||
min="0"
|
min="0"
|
||||||
className="border-2 border-black rounded-md text-center w-1/2"
|
className="border-2 border-black rounded-md text-center w-1/2"
|
||||||
value={developmentTime === 0 ? "" : developmentTime}
|
value={developmentTime === 0 ? "" : developmentTime}
|
||||||
|
readOnly
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
@ -97,6 +99,7 @@ export default function OtherUsersTR(): JSX.Element {
|
||||||
min="0"
|
min="0"
|
||||||
className="border-2 border-black rounded-md text-center w-1/2"
|
className="border-2 border-black rounded-md text-center w-1/2"
|
||||||
value={meetingTime === 0 ? "" : meetingTime}
|
value={meetingTime === 0 ? "" : meetingTime}
|
||||||
|
readOnly
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
@ -108,6 +111,7 @@ export default function OtherUsersTR(): JSX.Element {
|
||||||
min="0"
|
min="0"
|
||||||
className="border-2 border-black rounded-md text-center w-1/2"
|
className="border-2 border-black rounded-md text-center w-1/2"
|
||||||
value={adminTime === 0 ? "" : adminTime}
|
value={adminTime === 0 ? "" : adminTime}
|
||||||
|
readOnly
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
@ -119,6 +123,7 @@ export default function OtherUsersTR(): JSX.Element {
|
||||||
min="0"
|
min="0"
|
||||||
className="border-2 border-black rounded-md text-center w-1/2"
|
className="border-2 border-black rounded-md text-center w-1/2"
|
||||||
value={ownWorkTime === 0 ? "" : ownWorkTime}
|
value={ownWorkTime === 0 ? "" : ownWorkTime}
|
||||||
|
readOnly
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
@ -130,6 +135,7 @@ export default function OtherUsersTR(): JSX.Element {
|
||||||
min="0"
|
min="0"
|
||||||
className="border-2 border-black rounded-md text-center w-1/2"
|
className="border-2 border-black rounded-md text-center w-1/2"
|
||||||
value={studyTime === 0 ? "" : studyTime}
|
value={studyTime === 0 ? "" : studyTime}
|
||||||
|
readOnly
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
@ -141,6 +147,7 @@ export default function OtherUsersTR(): JSX.Element {
|
||||||
min="0"
|
min="0"
|
||||||
className="border-2 border-black rounded-md text-center w-1/2"
|
className="border-2 border-black rounded-md text-center w-1/2"
|
||||||
value={testingTime === 0 ? "" : testingTime}
|
value={testingTime === 0 ? "" : testingTime}
|
||||||
|
readOnly
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|
|
@ -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>
|
||||||
|
|
|
@ -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) => (
|
||||||
|
|
|
@ -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 (
|
||||||
<>
|
<>
|
||||||
|
|
|
@ -15,15 +15,21 @@ export default function Register(): JSX.Element {
|
||||||
const [errMessage, setErrMessage] = useState<string>();
|
const [errMessage, setErrMessage] = useState<string>();
|
||||||
|
|
||||||
const handleRegister = async (): Promise<void> => {
|
const handleRegister = async (): Promise<void> => {
|
||||||
|
if (username === "" || password === "") {
|
||||||
|
alert("Must provide username and password");
|
||||||
|
return;
|
||||||
|
}
|
||||||
const newUser: NewUser = {
|
const newUser: NewUser = {
|
||||||
username: username ?? "",
|
username: username?.replace(/ /g, "") ?? "",
|
||||||
password: password ?? "",
|
password: password ?? "",
|
||||||
};
|
};
|
||||||
const response = await api.registerUser(newUser);
|
const response = await api.registerUser(newUser);
|
||||||
if (response.success) {
|
if (response.success) {
|
||||||
alert("User added!");
|
alert(`${newUser.username} added!`);
|
||||||
|
setPassword("");
|
||||||
|
setUsername("");
|
||||||
} else {
|
} else {
|
||||||
alert("User not added");
|
alert("User not added, name could be taken");
|
||||||
setErrMessage(response.message ?? "Unknown error");
|
setErrMessage(response.message ?? "Unknown error");
|
||||||
console.error(errMessage);
|
console.error(errMessage);
|
||||||
}
|
}
|
||||||
|
@ -47,22 +53,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"
|
||||||
|
|
41
frontend/src/Components/RemoveUserFromProj.tsx
Normal file
41
frontend/src/Components/RemoveUserFromProj.tsx
Normal file
|
@ -0,0 +1,41 @@
|
||||||
|
import { api, APIResponse } from "../API/API";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes a user from a project
|
||||||
|
* @param {string} props.usernameToDelete - The username of user to remove
|
||||||
|
* @param {string} props.projectName - Project to remove user from
|
||||||
|
* @returns {void}
|
||||||
|
* @example
|
||||||
|
* const exampleUsername = "user";
|
||||||
|
* const exampleProjectName "project";
|
||||||
|
* RemoveUserFromProj({ userToRemove: exampleUsername, projectName: exampleProjectName });
|
||||||
|
*/
|
||||||
|
|
||||||
|
export default function RemoveUserFromProj(props: {
|
||||||
|
userToRemove: string;
|
||||||
|
projectName: string;
|
||||||
|
}): void {
|
||||||
|
if (props.userToRemove === localStorage.getItem("username")) {
|
||||||
|
alert("Cannot remove yourself");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
api
|
||||||
|
.removeUserFromProject(
|
||||||
|
props.userToRemove,
|
||||||
|
props.projectName,
|
||||||
|
localStorage.getItem("accessToken") ?? "",
|
||||||
|
)
|
||||||
|
.then((response: APIResponse<void>) => {
|
||||||
|
if (response.success) {
|
||||||
|
alert(`${props.userToRemove} has been removed!`);
|
||||||
|
location.reload();
|
||||||
|
} else {
|
||||||
|
alert(`${props.userToRemove} has not been removed due to an error`);
|
||||||
|
console.error(response.message);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
alert(`${props.userToRemove} has not been removed due to an error`);
|
||||||
|
console.error("An error occurred during deletion:", error);
|
||||||
|
});
|
||||||
|
}
|
|
@ -1,70 +1,45 @@
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { useParams } from "react-router-dom";
|
import { useParams } from "react-router-dom";
|
||||||
|
import { api } from "../API/API";
|
||||||
|
import { projectTimes } from "./GetProjectTimes";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders the component for showing total time per role in a project.
|
* Renders the component for showing total time per role in a project.
|
||||||
* @returns JSX.Element
|
* @returns JSX.Element
|
||||||
*/
|
*/
|
||||||
export default function TimePerRole(): JSX.Element {
|
export default function TimePerRole(): JSX.Element {
|
||||||
const [developmentTime, setDevelopmentTime] = useState<number>();
|
const [development, setDevelopment] = useState<number>(0);
|
||||||
const [meetingTime, setMeetingTime] = useState<number>();
|
const [meeting, setMeeting] = useState<number>(0);
|
||||||
const [adminTime, setAdminTime] = useState<number>();
|
const [admin, setAdmin] = useState<number>(0);
|
||||||
const [ownWorkTime, setOwnWorkTime] = useState<number>();
|
const [own_work, setOwnWork] = useState<number>(0);
|
||||||
const [studyTime, setStudyTime] = useState<number>();
|
const [study, setStudy] = useState<number>(0);
|
||||||
const [testingTime, setTestingTime] = useState<number>();
|
const [testing, setTesting] = useState<number>(0);
|
||||||
|
|
||||||
// const token = localStorage.getItem("accessToken") ?? "";
|
const token = localStorage.getItem("accessToken") ?? "";
|
||||||
// const username = localStorage.getItem("username") ?? "";
|
|
||||||
const { projectName } = useParams();
|
const { projectName } = useParams();
|
||||||
|
|
||||||
// const fetchTimePerRole = async (): Promise<void> => {
|
|
||||||
// const response = await api.getTimePerRole(
|
|
||||||
// username,
|
|
||||||
// projectName ?? "",
|
|
||||||
// token,
|
|
||||||
// );
|
|
||||||
// {
|
|
||||||
// if (response.success) {
|
|
||||||
// const report: TimePerRole = response.data ?? {
|
|
||||||
// PManagerTime: 0,
|
|
||||||
// SManagerTime: 0,
|
|
||||||
// DeveloperTime: 0,
|
|
||||||
// TesterTime: 0,
|
|
||||||
// };
|
|
||||||
// } else {
|
|
||||||
// console.error("Failed to fetch weekly report:", response.message);
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
interface TimePerActivity {
|
|
||||||
developmentTime: number;
|
|
||||||
meetingTime: number;
|
|
||||||
adminTime: number;
|
|
||||||
ownWorkTime: number;
|
|
||||||
studyTime: number;
|
|
||||||
testingTime: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const fetchTimePerActivity = async (): Promise<void> => {
|
const fetchTimePerActivity = async (): Promise<void> => {
|
||||||
// Use mock data
|
const response = await api.getProjectTimes(projectName ?? "", token);
|
||||||
const report: TimePerActivity = {
|
{
|
||||||
developmentTime: 100,
|
if (response.success) {
|
||||||
meetingTime: 200,
|
const report: projectTimes = response.data ?? {
|
||||||
adminTime: 300,
|
development: 0,
|
||||||
ownWorkTime: 50,
|
meeting: 0,
|
||||||
studyTime: 75,
|
admin: 0,
|
||||||
testingTime: 110,
|
own_work: 0,
|
||||||
};
|
study: 0,
|
||||||
|
testing: 0,
|
||||||
// Set the state with the mock data
|
};
|
||||||
setDevelopmentTime(report.developmentTime);
|
setDevelopment(report.development);
|
||||||
setMeetingTime(report.meetingTime);
|
setMeeting(report.meeting);
|
||||||
setAdminTime(report.adminTime);
|
setAdmin(report.admin);
|
||||||
setOwnWorkTime(report.ownWorkTime);
|
setOwnWork(report.own_work);
|
||||||
setStudyTime(report.studyTime);
|
setStudy(report.study);
|
||||||
setTestingTime(report.testingTime);
|
setTesting(report.testing);
|
||||||
|
} else {
|
||||||
await Promise.resolve();
|
console.error("Failed to fetch weekly report:", response.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
@ -94,10 +69,8 @@ export default function TimePerRole(): JSX.Element {
|
||||||
<input
|
<input
|
||||||
type="string"
|
type="string"
|
||||||
className="border-2 border-black rounded-md text-center w-1/2"
|
className="border-2 border-black rounded-md text-center w-1/2"
|
||||||
value={developmentTime}
|
value={development}
|
||||||
onKeyDown={(event) => {
|
readOnly
|
||||||
event.preventDefault();
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
@ -107,10 +80,8 @@ export default function TimePerRole(): JSX.Element {
|
||||||
<input
|
<input
|
||||||
type="string"
|
type="string"
|
||||||
className="border-2 border-black rounded-md text-center w-1/2"
|
className="border-2 border-black rounded-md text-center w-1/2"
|
||||||
value={meetingTime}
|
value={meeting}
|
||||||
onKeyDown={(event) => {
|
readOnly
|
||||||
event.preventDefault();
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
@ -120,10 +91,8 @@ export default function TimePerRole(): JSX.Element {
|
||||||
<input
|
<input
|
||||||
type="string"
|
type="string"
|
||||||
className="border-2 border-black rounded-md text-center w-1/2"
|
className="border-2 border-black rounded-md text-center w-1/2"
|
||||||
value={adminTime}
|
value={admin}
|
||||||
onKeyDown={(event) => {
|
readOnly
|
||||||
event.preventDefault();
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
@ -133,10 +102,8 @@ export default function TimePerRole(): JSX.Element {
|
||||||
<input
|
<input
|
||||||
type="string"
|
type="string"
|
||||||
className="border-2 border-black rounded-md text-center w-1/2"
|
className="border-2 border-black rounded-md text-center w-1/2"
|
||||||
value={ownWorkTime}
|
value={own_work}
|
||||||
onKeyDown={(event) => {
|
readOnly
|
||||||
event.preventDefault();
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
@ -146,10 +113,8 @@ export default function TimePerRole(): JSX.Element {
|
||||||
<input
|
<input
|
||||||
type="string"
|
type="string"
|
||||||
className="border-2 border-black rounded-md text-center w-1/2"
|
className="border-2 border-black rounded-md text-center w-1/2"
|
||||||
value={studyTime}
|
value={study}
|
||||||
onKeyDown={(event) => {
|
readOnly
|
||||||
event.preventDefault();
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
@ -159,10 +124,8 @@ export default function TimePerRole(): JSX.Element {
|
||||||
<input
|
<input
|
||||||
type="string"
|
type="string"
|
||||||
className="border-2 border-black rounded-md text-center w-1/2"
|
className="border-2 border-black rounded-md text-center w-1/2"
|
||||||
value={testingTime}
|
value={testing}
|
||||||
onKeyDown={(event) => {
|
readOnly
|
||||||
event.preventDefault();
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|
|
@ -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.replace(/ /g, ""),
|
||||||
|
};
|
||||||
|
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 />
|
</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>
|
||||||
);
|
);
|
||||||
|
|
|
@ -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}
|
||||||
/>
|
/>
|
||||||
|
|
|
@ -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(): 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(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();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
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>
|
||||||
))}
|
))}
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { WeeklyReport, NewWeeklyReport } from "../Types/goTypes";
|
import { WeeklyReport } from "../Types/goTypes";
|
||||||
import { api } from "../API/API";
|
import { api } from "../API/API";
|
||||||
import { useNavigate, useParams } from "react-router-dom";
|
import { useNavigate, useParams } from "react-router-dom";
|
||||||
import Button from "./Button";
|
import Button from "./Button";
|
||||||
|
@ -18,6 +18,7 @@ export default function GetOtherUsersReport(): JSX.Element {
|
||||||
const [ownWorkTime, setOwnWorkTime] = useState(0);
|
const [ownWorkTime, setOwnWorkTime] = useState(0);
|
||||||
const [studyTime, setStudyTime] = useState(0);
|
const [studyTime, setStudyTime] = useState(0);
|
||||||
const [testingTime, setTestingTime] = useState(0);
|
const [testingTime, setTestingTime] = useState(0);
|
||||||
|
const [reportId, setReportId] = useState(0);
|
||||||
|
|
||||||
const token = localStorage.getItem("accessToken") ?? "";
|
const token = localStorage.getItem("accessToken") ?? "";
|
||||||
const { projectName } = useParams();
|
const { projectName } = useParams();
|
||||||
|
@ -30,8 +31,9 @@ export default function GetOtherUsersReport(): JSX.Element {
|
||||||
projectName ?? "",
|
projectName ?? "",
|
||||||
fetchedWeek?.toString() ?? "0",
|
fetchedWeek?.toString() ?? "0",
|
||||||
token,
|
token,
|
||||||
|
username ?? "",
|
||||||
);
|
);
|
||||||
|
console.log(response);
|
||||||
if (response.success) {
|
if (response.success) {
|
||||||
const report: WeeklyReport = response.data ?? {
|
const report: WeeklyReport = response.data ?? {
|
||||||
reportId: 0,
|
reportId: 0,
|
||||||
|
@ -45,6 +47,7 @@ export default function GetOtherUsersReport(): JSX.Element {
|
||||||
studyTime: 0,
|
studyTime: 0,
|
||||||
testingTime: 0,
|
testingTime: 0,
|
||||||
};
|
};
|
||||||
|
setReportId(report.reportId);
|
||||||
setWeek(report.week);
|
setWeek(report.week);
|
||||||
setDevelopmentTime(report.developmentTime);
|
setDevelopmentTime(report.developmentTime);
|
||||||
setMeetingTime(report.meetingTime);
|
setMeetingTime(report.meetingTime);
|
||||||
|
@ -60,32 +63,33 @@ export default function GetOtherUsersReport(): JSX.Element {
|
||||||
void fetchUsersWeeklyReport();
|
void fetchUsersWeeklyReport();
|
||||||
});
|
});
|
||||||
|
|
||||||
const handleSignWeeklyReport = async (): Promise<void> => {
|
const handleSignWeeklyReport = async (): Promise<boolean> => {
|
||||||
const newWeeklyReport: NewWeeklyReport = {
|
const response = await api.signReport(reportId, token);
|
||||||
projectName: projectName ?? "",
|
if (response.success) {
|
||||||
week,
|
return true;
|
||||||
developmentTime,
|
} else {
|
||||||
meetingTime,
|
return false;
|
||||||
adminTime,
|
}
|
||||||
ownWorkTime,
|
|
||||||
studyTime,
|
|
||||||
testingTime,
|
|
||||||
};
|
|
||||||
|
|
||||||
await api.submitWeeklyReport(newWeeklyReport, token);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<h1 className="text-[30px] font-bold">{username}'s Report</h1>
|
<h1 className="text-[30px] font-bold"> {username}'s Report</h1>
|
||||||
<div className="border-4 border-black bg-white flex flex-col justify-start min-h-[65vh] h-fit w-[50vw] rounded-3xl overflow-scroll space-y-[2vh] p-[30px] items-center">
|
<div className="border-4 border-black bg-white flex flex-col justify-start min-h-[65vh] h-fit w-[50vw] rounded-3xl overflow-scroll space-y-[2vh] p-[30px] items-center">
|
||||||
<form
|
<form
|
||||||
onSubmit={(e) => {
|
onSubmit={(e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
void handleSignWeeklyReport();
|
void (async (): Promise<void> => {
|
||||||
navigate(-1);
|
const success = await handleSignWeeklyReport();
|
||||||
|
if (!success) {
|
||||||
|
alert("Failed to sign report!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
alert("Report successfully signed!");
|
||||||
|
navigate(-1);
|
||||||
|
})();
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div className="flex flex-col items-center">
|
<div className="flex flex-col items-center">
|
||||||
|
@ -112,7 +116,10 @@ export default function GetOtherUsersReport(): JSX.Element {
|
||||||
type="text"
|
type="text"
|
||||||
min="0"
|
min="0"
|
||||||
className="border-2 border-black rounded-md text-center w-1/2"
|
className="border-2 border-black rounded-md text-center w-1/2"
|
||||||
value={developmentTime === 0 ? "" : developmentTime}
|
defaultValue={
|
||||||
|
developmentTime === 0 ? "" : developmentTime
|
||||||
|
}
|
||||||
|
readOnly
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
@ -123,7 +130,8 @@ export default function GetOtherUsersReport(): JSX.Element {
|
||||||
type="text"
|
type="text"
|
||||||
min="0"
|
min="0"
|
||||||
className="border-2 border-black rounded-md text-center w-1/2"
|
className="border-2 border-black rounded-md text-center w-1/2"
|
||||||
value={meetingTime === 0 ? "" : meetingTime}
|
defaultValue={meetingTime === 0 ? "" : meetingTime}
|
||||||
|
readOnly
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
@ -134,7 +142,8 @@ export default function GetOtherUsersReport(): JSX.Element {
|
||||||
type="text"
|
type="text"
|
||||||
min="0"
|
min="0"
|
||||||
className="border-2 border-black rounded-md text-center w-1/2"
|
className="border-2 border-black rounded-md text-center w-1/2"
|
||||||
value={adminTime === 0 ? "" : adminTime}
|
defaultValue={adminTime === 0 ? "" : adminTime}
|
||||||
|
readOnly
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
@ -145,7 +154,8 @@ export default function GetOtherUsersReport(): JSX.Element {
|
||||||
type="text"
|
type="text"
|
||||||
min="0"
|
min="0"
|
||||||
className="border-2 border-black rounded-md text-center w-1/2"
|
className="border-2 border-black rounded-md text-center w-1/2"
|
||||||
value={ownWorkTime === 0 ? "" : ownWorkTime}
|
defaultValue={ownWorkTime === 0 ? "" : ownWorkTime}
|
||||||
|
readOnly
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
@ -156,7 +166,8 @@ export default function GetOtherUsersReport(): JSX.Element {
|
||||||
type="text"
|
type="text"
|
||||||
min="0"
|
min="0"
|
||||||
className="border-2 border-black rounded-md text-center w-1/2"
|
className="border-2 border-black rounded-md text-center w-1/2"
|
||||||
value={studyTime === 0 ? "" : studyTime}
|
defaultValue={studyTime === 0 ? "" : studyTime}
|
||||||
|
readOnly
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
@ -167,7 +178,8 @@ export default function GetOtherUsersReport(): JSX.Element {
|
||||||
type="text"
|
type="text"
|
||||||
min="0"
|
min="0"
|
||||||
className="border-2 border-black rounded-md text-center w-1/2"
|
className="border-2 border-black rounded-md text-center w-1/2"
|
||||||
value={testingTime === 0 ? "" : testingTime}
|
defaultValue={testingTime === 0 ? "" : testingTime}
|
||||||
|
readOnly
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|
23
frontend/src/Containers/GenApiDemo.tsx
Normal file
23
frontend/src/Containers/GenApiDemo.tsx
Normal file
|
@ -0,0 +1,23 @@
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { GenApi } from "../API/GenApi";
|
||||||
|
|
||||||
|
// Instantiation of the API
|
||||||
|
const api = new GenApi();
|
||||||
|
|
||||||
|
export function GenApiDemo(): JSX.Element {
|
||||||
|
// Sync wrapper around the loginCreate method
|
||||||
|
const register = async (): Promise<void> => {
|
||||||
|
const response = await api.login.loginCreate({
|
||||||
|
username: "admin",
|
||||||
|
password: "admin",
|
||||||
|
});
|
||||||
|
console.log(response.data); // This should be the inner type of the response
|
||||||
|
};
|
||||||
|
|
||||||
|
// Call the wrapper
|
||||||
|
useEffect(() => {
|
||||||
|
void register();
|
||||||
|
});
|
||||||
|
|
||||||
|
return <></>;
|
||||||
|
}
|
|
@ -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;
|
|
|
@ -9,7 +9,10 @@ import { useState } from "react";
|
||||||
|
|
||||||
function AdminManageProjects(): JSX.Element {
|
function AdminManageProjects(): JSX.Element {
|
||||||
const [projects, setProjects] = useState<Project[]>([]);
|
const [projects, setProjects] = useState<Project[]>([]);
|
||||||
GetProjects({ setProjectsProp: setProjects });
|
GetProjects({
|
||||||
|
setProjectsProp: setProjects,
|
||||||
|
username: localStorage.getItem("username") ?? "",
|
||||||
|
});
|
||||||
const content = (
|
const content = (
|
||||||
<>
|
<>
|
||||||
<h1 className="font-bold text-[30px] mb-[20px]">Manage Projects</h1>
|
<h1 className="font-bold text-[30px] mb-[20px]">Manage Projects</h1>
|
||||||
|
|
|
@ -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;
|
||||||
|
|
|
@ -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;
|
|
|
@ -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;
|
|
|
@ -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;
|
|
|
@ -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;
|
|
|
@ -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;
|
|
|
@ -124,6 +124,44 @@ export interface WeeklyReport {
|
||||||
*/
|
*/
|
||||||
signedBy?: number /* int */;
|
signedBy?: number /* int */;
|
||||||
}
|
}
|
||||||
|
export interface UpdateWeeklyReport {
|
||||||
|
/**
|
||||||
|
* The name of the project, as it appears in the database
|
||||||
|
*/
|
||||||
|
projectName: string;
|
||||||
|
/**
|
||||||
|
* The name of the user
|
||||||
|
*/
|
||||||
|
userName: string;
|
||||||
|
/**
|
||||||
|
* The week number
|
||||||
|
*/
|
||||||
|
week: number /* int */;
|
||||||
|
/**
|
||||||
|
* Total time spent on development
|
||||||
|
*/
|
||||||
|
developmentTime: number /* int */;
|
||||||
|
/**
|
||||||
|
* Total time spent in meetings
|
||||||
|
*/
|
||||||
|
meetingTime: number /* int */;
|
||||||
|
/**
|
||||||
|
* Total time spent on administrative tasks
|
||||||
|
*/
|
||||||
|
adminTime: number /* int */;
|
||||||
|
/**
|
||||||
|
* Total time spent on personal projects
|
||||||
|
*/
|
||||||
|
ownWorkTime: number /* int */;
|
||||||
|
/**
|
||||||
|
* Total time spent on studying
|
||||||
|
*/
|
||||||
|
studyTime: number /* int */;
|
||||||
|
/**
|
||||||
|
* Total time spent on testing
|
||||||
|
*/
|
||||||
|
testingTime: number /* int */;
|
||||||
|
}
|
||||||
|
|
||||||
//////////
|
//////////
|
||||||
// source: project.go
|
// source: project.go
|
||||||
|
@ -151,16 +189,9 @@ export interface NewProject {
|
||||||
*/
|
*/
|
||||||
export interface RoleChange {
|
export interface RoleChange {
|
||||||
username: string;
|
username: string;
|
||||||
role: "project_manager" | "user";
|
role: 'project_manager' | 'user';
|
||||||
projectname: string;
|
projectname: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface NewProjMember {
|
|
||||||
username: string;
|
|
||||||
projectname: string;
|
|
||||||
role: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface NameChange {
|
export interface NameChange {
|
||||||
id: number /* int */;
|
id: number /* int */;
|
||||||
name: string;
|
name: string;
|
||||||
|
@ -191,11 +222,6 @@ export interface PublicUser {
|
||||||
userId: string;
|
userId: string;
|
||||||
username: string;
|
username: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UserProjectMember {
|
|
||||||
Username: string;
|
|
||||||
UserRole: string;
|
|
||||||
}
|
|
||||||
/**
|
/**
|
||||||
* wrapper type for token
|
* wrapper type for token
|
||||||
*/
|
*/
|
||||||
|
|
|
@ -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 />,
|
||||||
|
|
151
testing/helpers.py
Normal file
151
testing/helpers.py
Normal file
|
@ -0,0 +1,151 @@
|
||||||
|
import requests
|
||||||
|
import string
|
||||||
|
import random
|
||||||
|
import json
|
||||||
|
|
||||||
|
# Helper function for the TTime API testing suite
|
||||||
|
|
||||||
|
# For style guide, see:
|
||||||
|
# https://peps.python.org/pep-0008/#function-and-variable-names
|
||||||
|
# https://google.github.io/styleguide/pyguide.html#316-naming
|
||||||
|
|
||||||
|
##################
|
||||||
|
## Static Paths ##
|
||||||
|
##################
|
||||||
|
|
||||||
|
base_url = "http://localhost:8080"
|
||||||
|
|
||||||
|
registerPath = base_url + "/api/register"
|
||||||
|
loginPath = base_url + "/api/login"
|
||||||
|
addProjectPath = base_url + "/api/project"
|
||||||
|
submitReportPath = base_url + "/api/submitWeeklyReport"
|
||||||
|
getWeeklyReportPath = base_url + "/api/getWeeklyReport"
|
||||||
|
getProjectPath = base_url + "/api/project"
|
||||||
|
signReportPath = base_url + "/api/signReport"
|
||||||
|
addUserToProjectPath = base_url + "/api/addUserToProject"
|
||||||
|
promoteToAdminPath = base_url + "/api/promoteToAdmin"
|
||||||
|
getUserProjectsPath = base_url + "/api/getUserProjects"
|
||||||
|
getAllWeeklyReportsPath = base_url + "/api/getAllWeeklyReports"
|
||||||
|
checkIfProjectManagerPath = base_url + "/api/checkIfProjectManager"
|
||||||
|
ProjectRoleChangePath = base_url + "/api/ProjectRoleChange"
|
||||||
|
getUsersProjectPath = base_url + "/api/getUsersProject"
|
||||||
|
getUnsignedReportsPath = base_url + "/api/getUnsignedReports"
|
||||||
|
getChangeUserNamePath = base_url + "/api/changeUserName"
|
||||||
|
getUpdateWeeklyReportPath = base_url + "/api/updateWeeklyReport"
|
||||||
|
removeProjectPath = base_url + "/api/removeProject"
|
||||||
|
promoteToPmPath = base_url + "/api/promoteToPm"
|
||||||
|
|
||||||
|
debug_output = False
|
||||||
|
|
||||||
|
|
||||||
|
def gprint(*args, **kwargs):
|
||||||
|
print("\033[92m", *args, "\033[00m", **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def dprint(*args, **kwargs):
|
||||||
|
if debug_output:
|
||||||
|
print(*args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def randomString(len=10):
|
||||||
|
"""Generate a random string of fixed length"""
|
||||||
|
letters = string.ascii_lowercase
|
||||||
|
return "".join(random.choice(letters) for i in range(len))
|
||||||
|
|
||||||
|
|
||||||
|
############ ############ ############ ############ ############
|
||||||
|
|
||||||
|
|
||||||
|
# Posts the username and password to the register endpoint
|
||||||
|
def register(username: string, password: string):
|
||||||
|
dprint("Registering with username: ", username, " and password: ", password)
|
||||||
|
response = requests.post(
|
||||||
|
registerPath, json={"username": username, "password": password}
|
||||||
|
)
|
||||||
|
dprint(response.text)
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
# Posts the username and password to the login endpoint
|
||||||
|
def login(username: string, password: string):
|
||||||
|
dprint("Logging in with username: ", username, " and password: ", password)
|
||||||
|
response = requests.post(
|
||||||
|
loginPath, json={"username": username, "password": password}
|
||||||
|
)
|
||||||
|
dprint(response.text)
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
# Register a user and return the token
|
||||||
|
def register_and_login(username: string, password: string) -> string:
|
||||||
|
register(username, password)
|
||||||
|
response = login(username, password)
|
||||||
|
return response.json()["token"]
|
||||||
|
|
||||||
|
|
||||||
|
def create_project(
|
||||||
|
token: string, project_name: string, description: string = "Test description"
|
||||||
|
):
|
||||||
|
dprint("Creating project with name: ", project_name)
|
||||||
|
response = requests.post(
|
||||||
|
addProjectPath,
|
||||||
|
headers={"Authorization": "Bearer " + token},
|
||||||
|
json={"name": project_name, "description": description},
|
||||||
|
)
|
||||||
|
dprint(response.text)
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
# Add a user to a project, requires the user withing the token to be a project manager of said project
|
||||||
|
def addToProject(token: string, username: string, project_name: string):
|
||||||
|
dprint("Adding user with username: ", username, " to project: ", project_name)
|
||||||
|
response = requests.put(
|
||||||
|
addUserToProjectPath + "/" + project_name,
|
||||||
|
headers={"Authorization": "Bearer " + token},
|
||||||
|
params={"userName": username},
|
||||||
|
)
|
||||||
|
dprint(response.text)
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
def promoteToManager(token: string, username: string, project_name: string):
|
||||||
|
dprint(
|
||||||
|
"Promoting user with username: ",
|
||||||
|
username,
|
||||||
|
" to project manager of project: ",
|
||||||
|
project_name,
|
||||||
|
)
|
||||||
|
response = requests.put(
|
||||||
|
promoteToPmPath + "/" + project_name,
|
||||||
|
headers={"Authorization": "Bearer " + token},
|
||||||
|
params={"userName": username},
|
||||||
|
)
|
||||||
|
dprint(response.text)
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
def submitReport(token: string, report):
|
||||||
|
dprint("Submitting report: ", report)
|
||||||
|
response = requests.post(
|
||||||
|
submitReportPath,
|
||||||
|
json=report,
|
||||||
|
headers={"Authorization": "Bearer " + token},
|
||||||
|
)
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
def getReport(token: string, username: string, projectName: string):
|
||||||
|
# Retrieve the report ID
|
||||||
|
response = requests.get(
|
||||||
|
getWeeklyReportPath,
|
||||||
|
headers={"Authorization": "Bearer " + token},
|
||||||
|
params={"username": username, "projectName": projectName, "week": 1},
|
||||||
|
)
|
||||||
|
return response.json()
|
||||||
|
|
||||||
|
|
||||||
|
def signReport(project_manager_token: string, report_id: int):
|
||||||
|
return requests.put(
|
||||||
|
signReportPath + "/" + str(report_id),
|
||||||
|
headers={"Authorization": "Bearer " + project_manager_token},
|
||||||
|
)
|
|
@ -1,61 +1,23 @@
|
||||||
import requests
|
import requests
|
||||||
import string
|
|
||||||
import random
|
|
||||||
|
|
||||||
debug_output = True
|
# This modules contains helper functions for the tests
|
||||||
|
from helpers import *
|
||||||
def gprint(*args, **kwargs):
|
|
||||||
print("\033[92m", *args, "\033[00m", **kwargs)
|
|
||||||
|
|
||||||
print("Running Tests...")
|
print("Running Tests...")
|
||||||
|
|
||||||
def dprint(*args, **kwargs):
|
|
||||||
if debug_output:
|
|
||||||
print(*args, **kwargs)
|
|
||||||
|
|
||||||
def randomString(len=10):
|
|
||||||
"""Generate a random string of fixed length"""
|
|
||||||
letters = string.ascii_lowercase
|
|
||||||
return "".join(random.choice(letters) for i in range(len))
|
|
||||||
|
|
||||||
|
|
||||||
# Defined once per test run
|
# Defined once per test run
|
||||||
username = "user_" + randomString()
|
username = "user_" + randomString()
|
||||||
projectName = "project_" + randomString()
|
projectName = "project_" + randomString()
|
||||||
|
|
||||||
# The base URL of the API
|
|
||||||
base_url = "http://localhost:8080"
|
|
||||||
|
|
||||||
# Endpoint to test
|
# ta bort auth i handlern för att få testet att gå igenom
|
||||||
registerPath = base_url + "/api/register"
|
|
||||||
loginPath = base_url + "/api/login"
|
|
||||||
addProjectPath = base_url + "/api/project"
|
|
||||||
submitReportPath = base_url + "/api/submitWeeklyReport"
|
|
||||||
getWeeklyReportPath = base_url + "/api/getWeeklyReport"
|
|
||||||
getProjectPath = base_url + "/api/project"
|
|
||||||
signReportPath = base_url + "/api/signReport"
|
|
||||||
addUserToProjectPath = base_url + "/api/addUserToProject"
|
|
||||||
promoteToAdminPath = base_url + "/api/promoteToAdmin"
|
|
||||||
getUserProjectsPath = base_url + "/api/getUserProjects"
|
|
||||||
getWeeklyReportsUserPath = base_url + "/api/getWeeklyReportsUser"
|
|
||||||
checkIfProjectManagerPath = base_url + "/api/checkIfProjectManager"
|
|
||||||
ProjectRoleChangePath = base_url + "/api/ProjectRoleChange"
|
|
||||||
getUsersProjectPath = base_url + "/api/getUsersProject"
|
|
||||||
getUnsignedReportsPath = base_url + "/api/getUnsignedReports"
|
|
||||||
getChangeUserNamePath = base_url + "/api/changeUserName"
|
|
||||||
getUpdateWeeklyReportPath = base_url + "/api/updateWeeklyReport"
|
|
||||||
removeProjectPath = base_url + "/api/removeProject"
|
|
||||||
|
|
||||||
#ta bort auth i handlern för att få testet att gå igenom
|
|
||||||
def test_ProjectRoleChange():
|
def test_ProjectRoleChange():
|
||||||
dprint("Testing ProjectRoleChange")
|
dprint("Testing ProjectRoleChange")
|
||||||
localUsername = randomString()
|
localUsername = randomString()
|
||||||
localProjectName = randomString()
|
localProjectName = randomString()
|
||||||
register(localUsername, "username_password")
|
register(localUsername, "username_password")
|
||||||
|
|
||||||
token = login(localUsername, "username_password").json()[
|
token = login(localUsername, "username_password").json()["token"]
|
||||||
"token"
|
|
||||||
]
|
|
||||||
|
|
||||||
# Just checking since this test is built somewhat differently than the others
|
# Just checking since this test is built somewhat differently than the others
|
||||||
assert token != None, "Login failed"
|
assert token != None, "Login failed"
|
||||||
|
@ -83,13 +45,14 @@ def test_ProjectRoleChange():
|
||||||
|
|
||||||
|
|
||||||
def test_get_user_projects():
|
def test_get_user_projects():
|
||||||
|
username = "user2"
|
||||||
|
password = "123"
|
||||||
|
|
||||||
dprint("Testing get user projects")
|
dprint("Testing get user projects")
|
||||||
loginResponse = login("user2", "123")
|
loginResponse = login(username, password)
|
||||||
# Check if the user is added to the project
|
# Check if the user is added to the project
|
||||||
response = requests.get(
|
response = requests.get(
|
||||||
getUserProjectsPath,
|
getUserProjectsPath + "/" + username,
|
||||||
json={"username": "user2"},
|
|
||||||
headers={"Authorization": "Bearer " + loginResponse.json()["token"]},
|
headers={"Authorization": "Bearer " + loginResponse.json()["token"]},
|
||||||
)
|
)
|
||||||
dprint(response.text)
|
dprint(response.text)
|
||||||
|
@ -98,26 +61,6 @@ def test_get_user_projects():
|
||||||
gprint("test_get_user_projects successful")
|
gprint("test_get_user_projects successful")
|
||||||
|
|
||||||
|
|
||||||
# Posts the username and password to the register endpoint
|
|
||||||
def register(username: string, password: string):
|
|
||||||
dprint("Registering with username: ", username, " and password: ", password)
|
|
||||||
response = requests.post(
|
|
||||||
registerPath, json={"username": username, "password": password}
|
|
||||||
)
|
|
||||||
dprint(response.text)
|
|
||||||
return response
|
|
||||||
|
|
||||||
|
|
||||||
# Posts the username and password to the login endpoint
|
|
||||||
def login(username: string, password: string):
|
|
||||||
dprint("Logging in with username: ", username, " and password: ", password)
|
|
||||||
response = requests.post(
|
|
||||||
loginPath, json={"username": username, "password": password}
|
|
||||||
)
|
|
||||||
dprint(response.text)
|
|
||||||
return response
|
|
||||||
|
|
||||||
|
|
||||||
# Test function to login
|
# Test function to login
|
||||||
def test_login():
|
def test_login():
|
||||||
response = login(username, "always_same")
|
response = login(username, "always_same")
|
||||||
|
@ -133,6 +76,7 @@ def test_create_user():
|
||||||
assert response.status_code == 200, "Registration failed"
|
assert response.status_code == 200, "Registration failed"
|
||||||
gprint("test_create_user successful")
|
gprint("test_create_user successful")
|
||||||
|
|
||||||
|
|
||||||
# Test function to add a project
|
# Test function to add a project
|
||||||
def test_add_project():
|
def test_add_project():
|
||||||
loginResponse = login(username, "always_same")
|
loginResponse = login(username, "always_same")
|
||||||
|
@ -146,6 +90,7 @@ def test_add_project():
|
||||||
assert response.status_code == 200, "Add project failed"
|
assert response.status_code == 200, "Add project failed"
|
||||||
gprint("test_add_project successful")
|
gprint("test_add_project successful")
|
||||||
|
|
||||||
|
|
||||||
# Test function to submit a report
|
# Test function to submit a report
|
||||||
def test_submit_report():
|
def test_submit_report():
|
||||||
token = login(username, "always_same").json()["token"]
|
token = login(username, "always_same").json()["token"]
|
||||||
|
@ -167,6 +112,7 @@ def test_submit_report():
|
||||||
assert response.status_code == 200, "Submit report failed"
|
assert response.status_code == 200, "Submit report failed"
|
||||||
gprint("test_submit_report successful")
|
gprint("test_submit_report successful")
|
||||||
|
|
||||||
|
|
||||||
# Test function to get a weekly report
|
# Test function to get a weekly report
|
||||||
def test_get_weekly_report():
|
def test_get_weekly_report():
|
||||||
token = login(username, "always_same").json()["token"]
|
token = login(username, "always_same").json()["token"]
|
||||||
|
@ -194,91 +140,58 @@ def test_get_project():
|
||||||
|
|
||||||
# Test function to add a user to a project
|
# Test function to add a user to a project
|
||||||
def test_add_user_to_project():
|
def test_add_user_to_project():
|
||||||
# Log in as a site admin
|
# User to create
|
||||||
admin_username = randomString()
|
pm_user = "user" + randomString()
|
||||||
admin_password = "admin_password"
|
pm_passwd = "password"
|
||||||
dprint(
|
|
||||||
"Registering with username: ", admin_username, " and password: ", admin_password
|
|
||||||
)
|
|
||||||
response = requests.post(
|
|
||||||
registerPath, json={"username": admin_username, "password": admin_password}
|
|
||||||
)
|
|
||||||
dprint(response.text)
|
|
||||||
|
|
||||||
admin_token = login(admin_username, admin_password).json()["token"]
|
# User to add
|
||||||
response = requests.post(
|
member_user = "member" + randomString()
|
||||||
promoteToAdminPath,
|
member_passwd = "password"
|
||||||
json={"username": admin_username},
|
|
||||||
headers={"Authorization": "Bearer " + admin_token},
|
|
||||||
)
|
|
||||||
dprint(response.text)
|
|
||||||
assert response.status_code == 200, "Promote to site admin failed"
|
|
||||||
dprint("Admin promoted to site admin successfully")
|
|
||||||
|
|
||||||
# Create a new user to add to the project
|
# Name of the project to be created
|
||||||
new_user = randomString()
|
project_name = "project" + randomString()
|
||||||
register(new_user, "new_user_password")
|
|
||||||
|
|
||||||
# Add the new user to the project as a member
|
pm_token = register_and_login(pm_user, pm_passwd)
|
||||||
response = requests.put(
|
register(member_user, member_passwd)
|
||||||
addUserToProjectPath,
|
|
||||||
json={"projectName": projectName, "username": new_user, "role": "member"},
|
|
||||||
headers={"Authorization": "Bearer " + admin_token},
|
|
||||||
)
|
|
||||||
|
|
||||||
dprint(response.text)
|
response = create_project(pm_token, project_name)
|
||||||
|
assert response.status_code == 200, "Create project failed"
|
||||||
|
|
||||||
|
# Promote the user to project manager
|
||||||
|
response = addToProject(pm_token, member_user, project_name)
|
||||||
assert response.status_code == 200, "Add user to project failed"
|
assert response.status_code == 200, "Add user to project failed"
|
||||||
gprint("test_add_user_to_project successful")
|
|
||||||
|
|
||||||
# Test function to sign a report
|
# Test function to sign a report
|
||||||
def test_sign_report():
|
def test_sign_report():
|
||||||
# Create a project manager user
|
# Pm user
|
||||||
project_manager = randomString()
|
pm_username = "pm" + randomString()
|
||||||
register(project_manager, "project_manager_password")
|
pm_password = "admin_password2"
|
||||||
|
|
||||||
# Register an admin
|
# User to add
|
||||||
admin_username = randomString()
|
member_user = "member" + randomString()
|
||||||
admin_password = "admin_password2"
|
member_passwd = "password"
|
||||||
dprint(
|
|
||||||
"Registering with username: ", admin_username, " and password: ", admin_password
|
|
||||||
)
|
|
||||||
response = requests.post(
|
|
||||||
registerPath, json={"username": admin_username, "password": admin_password}
|
|
||||||
)
|
|
||||||
dprint(response.text)
|
|
||||||
|
|
||||||
# Log in as the admin
|
# Name of the project to be created
|
||||||
admin_token = login(admin_username, admin_password).json()["token"]
|
project_name = "project" + randomString()
|
||||||
response = requests.post(
|
|
||||||
promoteToAdminPath,
|
|
||||||
json={"username": admin_username},
|
|
||||||
headers={"Authorization": "Bearer " + admin_token},
|
|
||||||
)
|
|
||||||
|
|
||||||
response = requests.put(
|
# Register and get the tokens for both users
|
||||||
addUserToProjectPath,
|
pm_token = register_and_login(pm_username, pm_password)
|
||||||
json={
|
member_token = register_and_login(member_user, member_passwd)
|
||||||
"projectName": projectName,
|
|
||||||
"username": project_manager,
|
|
||||||
"role": "project_manager",
|
|
||||||
},
|
|
||||||
headers={"Authorization": "Bearer " + admin_token},
|
|
||||||
)
|
|
||||||
assert response.status_code == 200, "Add project manager to project failed"
|
|
||||||
dprint("Project manager added to project successfully")
|
|
||||||
|
|
||||||
# Log in as the project manager
|
# Create the project
|
||||||
project_manager_token = login(project_manager, "project_manager_password").json()[
|
response = create_project(pm_token, project_name)
|
||||||
"token"
|
assert response.status_code == 200, "Create project failed"
|
||||||
]
|
|
||||||
|
# Add the user to the project
|
||||||
|
response = addToProject(pm_token, member_user, project_name)
|
||||||
|
|
||||||
# Submit a report for the project
|
# Submit a report for the project
|
||||||
token = login(username, "always_same").json()["token"]
|
response = submitReport(
|
||||||
response = requests.post(
|
member_token,
|
||||||
submitReportPath,
|
{
|
||||||
json={
|
"projectName": project_name,
|
||||||
"projectName": projectName,
|
"week": 1,
|
||||||
"week": 2,
|
|
||||||
"developmentTime": 10,
|
"developmentTime": 10,
|
||||||
"meetingTime": 5,
|
"meetingTime": 5,
|
||||||
"adminTime": 5,
|
"adminTime": 5,
|
||||||
|
@ -286,47 +199,33 @@ def test_sign_report():
|
||||||
"studyTime": 10,
|
"studyTime": 10,
|
||||||
"testingTime": 10,
|
"testingTime": 10,
|
||||||
},
|
},
|
||||||
headers={"Authorization": "Bearer " + token},
|
|
||||||
)
|
)
|
||||||
assert response.status_code == 200, "Submit report failed"
|
assert response.status_code == 200, "Submit report failed"
|
||||||
dprint("Submit report successful")
|
|
||||||
|
|
||||||
# Retrieve the report ID
|
# Retrieve the report ID
|
||||||
response = requests.get(
|
report_id = getReport(member_token, member_user, project_name)["reportId"]
|
||||||
getWeeklyReportPath,
|
|
||||||
headers={"Authorization": "Bearer " + token},
|
|
||||||
params={"username": username, "projectName": projectName, "week": 1},
|
|
||||||
)
|
|
||||||
dprint(response.text)
|
|
||||||
report_id = response.json()["reportId"]
|
|
||||||
|
|
||||||
# Sign the report as the project manager
|
# Sign the report as the project manager
|
||||||
response = requests.post(
|
response = signReport(pm_token, report_id)
|
||||||
signReportPath,
|
|
||||||
json={"reportId": report_id},
|
|
||||||
headers={"Authorization": "Bearer " + project_manager_token},
|
|
||||||
)
|
|
||||||
assert response.status_code == 200, "Sign report failed"
|
assert response.status_code == 200, "Sign report failed"
|
||||||
dprint("Sign report successful")
|
dprint("Sign report successful")
|
||||||
|
|
||||||
# Retrieve the report ID again for confirmation
|
# Retrieve the report ID again for confirmation
|
||||||
response = requests.get(
|
report_id = getReport(member_token, member_user, project_name)["reportId"]
|
||||||
getWeeklyReportPath,
|
assert report_id != None, "Get report failed"
|
||||||
headers={"Authorization": "Bearer " + token},
|
|
||||||
params={"username": username, "projectName": projectName, "week": 1},
|
|
||||||
)
|
|
||||||
dprint(response.text)
|
|
||||||
gprint("test_sign_report successful")
|
gprint("test_sign_report successful")
|
||||||
|
|
||||||
|
|
||||||
# Test function to get weekly reports for a user in a project
|
# Test function to get weekly reports for a user in a project
|
||||||
def test_get_weekly_reports_user():
|
def test_get_all_weekly_reports():
|
||||||
# Log in as the user
|
# Log in as the user
|
||||||
token = login(username, "always_same").json()["token"]
|
token = login(username, "always_same").json()["token"]
|
||||||
|
|
||||||
# Get weekly reports for the user in the project
|
# Get weekly reports for the user in the project
|
||||||
response = requests.get(
|
response = requests.get(
|
||||||
getWeeklyReportsUserPath + "/" + projectName,
|
getAllWeeklyReportsPath + "/" + projectName,
|
||||||
headers={"Authorization": "Bearer " + token},
|
headers={"Authorization": "Bearer " + token},
|
||||||
|
params={"targetUser": username},
|
||||||
)
|
)
|
||||||
|
|
||||||
dprint(response.text)
|
dprint(response.text)
|
||||||
|
@ -334,7 +233,6 @@ def test_get_weekly_reports_user():
|
||||||
gprint("test_get_weekly_reports_user successful")
|
gprint("test_get_weekly_reports_user successful")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# Test function to check if a user is a project manager
|
# Test function to check if a user is a project manager
|
||||||
def test_check_if_project_manager():
|
def test_check_if_project_manager():
|
||||||
# Log in as the user
|
# Log in as the user
|
||||||
|
@ -350,6 +248,7 @@ def test_check_if_project_manager():
|
||||||
assert response.status_code == 200, "Check if project manager failed"
|
assert response.status_code == 200, "Check if project manager failed"
|
||||||
gprint("test_check_if_project_manager successful")
|
gprint("test_check_if_project_manager successful")
|
||||||
|
|
||||||
|
|
||||||
def test_ensure_manager_of_created_project():
|
def test_ensure_manager_of_created_project():
|
||||||
# Create a new user to add to the project
|
# Create a new user to add to the project
|
||||||
newUser = "karen_" + randomString()
|
newUser = "karen_" + randomString()
|
||||||
|
@ -373,6 +272,7 @@ def test_ensure_manager_of_created_project():
|
||||||
assert response.json()["isProjectManager"] == True, "User is not project manager"
|
assert response.json()["isProjectManager"] == True, "User is not project manager"
|
||||||
gprint("test_ensure_admin_of_created_project successful")
|
gprint("test_ensure_admin_of_created_project successful")
|
||||||
|
|
||||||
|
|
||||||
def test_change_user_name():
|
def test_change_user_name():
|
||||||
# Register a new user
|
# Register a new user
|
||||||
new_user = randomString()
|
new_user = randomString()
|
||||||
|
@ -410,6 +310,7 @@ def test_change_user_name():
|
||||||
assert response.status_code == 200, "Change user name failed"
|
assert response.status_code == 200, "Change user name failed"
|
||||||
gprint("test_change_user_name successful")
|
gprint("test_change_user_name successful")
|
||||||
|
|
||||||
|
|
||||||
def test_list_all_users_project():
|
def test_list_all_users_project():
|
||||||
# Log in as a user who is a member of the project
|
# Log in as a user who is a member of the project
|
||||||
admin_username = randomString()
|
admin_username = randomString()
|
||||||
|
@ -438,6 +339,7 @@ def test_list_all_users_project():
|
||||||
assert response.status_code == 200, "List all users project failed"
|
assert response.status_code == 200, "List all users project failed"
|
||||||
gprint("test_list_all_users_project sucessful")
|
gprint("test_list_all_users_project sucessful")
|
||||||
|
|
||||||
|
|
||||||
def test_update_weekly_report():
|
def test_update_weekly_report():
|
||||||
# Log in as the user
|
# Log in as the user
|
||||||
token = login(username, "always_same").json()["token"]
|
token = login(username, "always_same").json()["token"]
|
||||||
|
@ -503,22 +405,99 @@ def test_remove_project():
|
||||||
assert response.status_code == 200, "Remove project failed"
|
assert response.status_code == 200, "Remove project failed"
|
||||||
gprint("test_remove_project successful")
|
gprint("test_remove_project successful")
|
||||||
|
|
||||||
|
|
||||||
def test_get_unsigned_reports():
|
def test_get_unsigned_reports():
|
||||||
# Log in as the user
|
# Log in as the user
|
||||||
token = login("admin", "123").json()["token"]
|
token = login("user2", "123").json()["token"]
|
||||||
|
|
||||||
# Make a request to get all unsigned reports
|
# Make a request to get all unsigned reports
|
||||||
response = requests.get(
|
response = requests.get(
|
||||||
getUnsignedReportsPath + "/" "projecttest",
|
getUnsignedReportsPath + "/" + projectName,
|
||||||
headers={"Authorization": "Bearer " + token},
|
headers={"Authorization": "Bearer " + token},
|
||||||
)
|
)
|
||||||
dprint(response.text)
|
assert response.status_code == 200, "Get unsigned reports failed"
|
||||||
assert response.status_code == 200, "Get unsigned reports failed"
|
gprint("test_get_unsigned_reports successful")
|
||||||
gprint("test_get_unsigned_reports successful")
|
|
||||||
|
|
||||||
|
def test_get_other_users_report_as_pm():
|
||||||
|
# Create user
|
||||||
|
user = randomString()
|
||||||
|
register(user, "password")
|
||||||
|
|
||||||
|
# Create project
|
||||||
|
project = randomString()
|
||||||
|
pm_token = login(user, "password").json()["token"]
|
||||||
|
response = requests.post(
|
||||||
|
addProjectPath,
|
||||||
|
json={"name": project, "description": "This is a project"},
|
||||||
|
headers={"Authorization": "Bearer " + pm_token},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200, "Add project failed"
|
||||||
|
|
||||||
|
# Create other user
|
||||||
|
other_user = randomString()
|
||||||
|
register(other_user, "password")
|
||||||
|
user_token = login(other_user, "password").json()["token"]
|
||||||
|
|
||||||
|
# Add other user to project
|
||||||
|
response = requests.put(
|
||||||
|
addUserToProjectPath + "/" + project,
|
||||||
|
headers={"Authorization": "Bearer " + pm_token}, # note pm_token
|
||||||
|
params={"userName": other_user},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200, "Add user to project failed"
|
||||||
|
|
||||||
|
# Submit report as other user
|
||||||
|
response = requests.post(
|
||||||
|
submitReportPath,
|
||||||
|
json={
|
||||||
|
"projectName": project,
|
||||||
|
"week": 1,
|
||||||
|
"developmentTime": 10,
|
||||||
|
"meetingTime": 5,
|
||||||
|
"adminTime": 5,
|
||||||
|
"ownWorkTime": 10,
|
||||||
|
"studyTime": 10,
|
||||||
|
"testingTime": 10,
|
||||||
|
},
|
||||||
|
headers={"Authorization": "Bearer " + user_token},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200, "Submit report failed"
|
||||||
|
|
||||||
|
# Get report as project manager
|
||||||
|
response = requests.get(
|
||||||
|
getWeeklyReportPath,
|
||||||
|
headers={"Authorization": "Bearer " + pm_token},
|
||||||
|
params={"targetUser": other_user, "projectName": project, "week": 1},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200, "Get weekly report failed"
|
||||||
|
|
||||||
|
|
||||||
|
def test_promote_to_manager():
|
||||||
|
# User to create
|
||||||
|
pm_user = "user" + randomString()
|
||||||
|
pm_passwd = "password"
|
||||||
|
|
||||||
|
# User to promote
|
||||||
|
member_user = "member" + randomString()
|
||||||
|
member_passwd = "password"
|
||||||
|
|
||||||
|
# Name of the project to be created
|
||||||
|
project_name = "project" + randomString()
|
||||||
|
|
||||||
|
pm_token = register_and_login(pm_user, pm_passwd)
|
||||||
|
member_token = register_and_login(member_user, member_passwd)
|
||||||
|
|
||||||
|
response = create_project(pm_token, project_name)
|
||||||
|
assert response.status_code == 200, "Create project failed"
|
||||||
|
|
||||||
|
# Promote the user to project manager
|
||||||
|
response = promoteToManager(pm_token, member_user, project_name)
|
||||||
|
assert response.status_code == 200, "Promote to manager failed"
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
test_get_unsigned_reports()
|
test_promote_to_manager()
|
||||||
test_remove_project()
|
test_remove_project()
|
||||||
test_get_user_projects()
|
test_get_user_projects()
|
||||||
test_create_user()
|
test_create_user()
|
||||||
|
@ -529,7 +508,7 @@ if __name__ == "__main__":
|
||||||
test_get_project()
|
test_get_project()
|
||||||
test_sign_report()
|
test_sign_report()
|
||||||
test_add_user_to_project()
|
test_add_user_to_project()
|
||||||
test_get_weekly_reports_user()
|
test_get_all_weekly_reports()
|
||||||
test_check_if_project_manager()
|
test_check_if_project_manager()
|
||||||
test_ProjectRoleChange()
|
test_ProjectRoleChange()
|
||||||
test_ensure_manager_of_created_project()
|
test_ensure_manager_of_created_project()
|
||||||
|
@ -537,4 +516,4 @@ if __name__ == "__main__":
|
||||||
test_list_all_users_project()
|
test_list_all_users_project()
|
||||||
test_change_user_name()
|
test_change_user_name()
|
||||||
test_update_weekly_report()
|
test_update_weekly_report()
|
||||||
|
test_get_other_users_report_as_pm()
|
Loading…
Reference in a new issue