ChangeProjectName Handler + API

This commit is contained in:
al8763be 2024-04-17 21:31:47 +02:00
parent 6c4fe7bda3
commit 47d4bda99b
7 changed files with 166 additions and 2 deletions

View file

@ -47,6 +47,7 @@ type Database interface {
GetUserName(id int) (string, error)
UnsignWeeklyReport(reportId int, projectManagerId int) error
DeleteReport(reportID int) error
ChangeProjectName(projectName string, newProjectName string) error
}
// This struct is a wrapper type that holds the database connection
@ -670,3 +671,9 @@ func (d *Db) DeleteReport(reportID int) error {
_, err := d.Exec("DELETE FROM weekly_reports WHERE report_id = ?", reportID)
return err
}
// ChangeProjectName is a handler that changes the name of a project
func (d *Db) ChangeProjectName(projectName string, newProjectName string) error {
_, err := d.Exec("UPDATE projects SET name = ? WHERE name = ?", newProjectName, projectName)
return err
}

View file

@ -1092,3 +1092,31 @@ func TestDeleteReport(t *testing.T) {
}
}
func TestChangeProjectName(t *testing.T) {
db, err := setupAdvancedState()
if err != nil {
t.Error("setupState failed:", err)
}
// Promote user to Admin
err = db.PromoteToAdmin("demouser")
if err != nil {
t.Error("PromoteToAdmin failed:", err)
}
// Change project name
err = db.ChangeProjectName("projecttest", "newprojectname")
if err != nil {
t.Error("ChangeProjectName failed:", err)
}
// Check if the project name was changed
projects, err := db.GetAllProjects()
if err != nil {
t.Error("GetAllProjects failed:", err)
}
if projects[0].Name != "newprojectname" {
t.Error("ChangeProjectName failed: expected newprojectname, got", projects[0].Name)
}
}

View 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"
)
// ChangeProjectName is a handler that changes the name of a project
func ChangeProjectName(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
projectName := c.Params("projectName")
newProjectName := c.Query("newProjectName")
// Check if user is project manager
ismanager, err := db.GetDb(c).IsProjectManager(username, projectName)
if 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")
}
// Perform the project name change
err = db.GetDb(c).ChangeProjectName(projectName, newProjectName)
if err != nil {
log.Warn("Error changing project name:", err)
return c.Status(500).SendString(err.Error())
}
// Return a success message
return c.Status(200).SendString("Project name changed successfully")
}

View file

@ -125,6 +125,7 @@ func main() {
api.Delete("/removeUserFromProject/:projectName", projects.RemoveUserFromProject)
api.Delete("/removeProject/:projectName", projects.RemoveProject)
api.Delete("/project/:projectID", projects.DeleteProject)
api.Put("/ChangeProjectName/:projectName", projects.ChangeProjectName)
// All report related routes
// reportGroup := api.Group("/report") // Not currently in use

View file

@ -271,6 +271,18 @@ interface API {
token: string,
userName?: string,
): Promise<APIResponse<Statistics>>;
/**
* Changes the name of a project
* @param {string} projectName The name of the project
* @param {string} newProjectName The new name of the project
* @param {string} token The authentication token
*/
changeProjectName(
projectName: string,
newProjectName: string,
token: string,
): Promise<APIResponse<string>>;
}
/** An instance of the API */
@ -1002,4 +1014,31 @@ export const api: API = {
return { success: false, message: "Failed to get statistics" };
}
},
async changeProjectName(
projectName: string,
newProjectName: string,
token: string,
): Promise<APIResponse<string>> {
try {
const response = await fetch(
`/api/changeProjectName/${projectName}?newProjectName=${newProjectName}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
},
);
if (!response.ok) {
return { success: false, message: "Failed to change project name" };
} else {
return { success: true, message: "Project name changed" };
}
} catch (e) {
return { success: false, message: "Failed to change project name" };
}
},
};

View file

@ -37,8 +37,9 @@ promoteToPmPath = base_url + "/api/promoteToPm"
unsignReportPath = base_url + "/api/unsignReport"
deleteReportPath = base_url + "/api/deleteReport"
getStatisticsPath = base_url + "/api/getStatistics"
changeProjectNamePath = base_url + "/api/changeProjectName"
debug_output = False
debug_output = True
def gprint(*args, **kwargs):
@ -170,4 +171,12 @@ def getStatistics(token: string, projectName: string):
headers = {"Authorization": "Bearer " + token},
params={"projectName": projectName}
)
return response.json()
return response.json()
def changeProjectName(token: string, projectName: string, newProjectName: string):
response = requests.put(
changeProjectNamePath + "/" + projectName,
headers = {"Authorization": "Bearer " + token},
params={"newProjectName": newProjectName}
)
return response

View file

@ -666,8 +666,46 @@ def test_get_statistics():
assert stats["totalDevelopmentTime"] == 20, "Total development time is not correct"
gprint("test_get_statistics successful")
def test_project_name_change():
# Create admin
admin_username = randomString()
admin_password = randomString()
project_name = "project" + randomString()
token = register_and_login(admin_username, admin_password)
response = create_project(token, project_name)
assert response.status_code == 200, "Create project failed"
response = requests.get(
getUserProjectsPath + "/" + admin_username,
headers={"Authorization": "Bearer " + token},
)
dprint(response.json())
new_project_name = "new project name " + randomString()
dprint("Changing project name from ", project_name, " to ", new_project_name)
response = changeProjectName(token, project_name, new_project_name)
response = requests.get(
getUserProjectsPath + "/" + admin_username,
headers={"Authorization": "Bearer " + token},
)
dprint(response.json())
if (response.json()[0]["name"] != new_project_name):
assert False, "Project name change failed"
assert response.status_code == 200, "Project name change failed"
gprint("test_projectNameChange successful")
if __name__ == "__main__":
test_project_name_change();
test_delete_report()
test_unsign_report()
test_promote_to_manager()