Merge branch 'dev'

This commit is contained in:
Imbus 2024-03-21 00:48:44 +01:00
commit d4547e997c
4 changed files with 188 additions and 56 deletions

View file

@ -39,7 +39,9 @@ type Database interface {
SignWeeklyReport(reportId int, projectManagerId int) error SignWeeklyReport(reportId int, projectManagerId int) error
IsSiteAdmin(username string) (bool, error) IsSiteAdmin(username string) (bool, error)
IsProjectManager(username string, projectname string) (bool, error) IsProjectManager(username string, projectname string) (bool, error)
GetTotalTimePerActivity(projectName string) (map[string]int, error) GetProjectTimes(projectName string) (map[string]int, error)
} }
// This struct is a wrapper type that holds the database connection // This struct is a wrapper type that holds the database connection
@ -491,36 +493,36 @@ func (d *Db) MigrateSampleData() error {
return nil return nil
} }
func (d *Db) GetTotalTimePerActivity(projectName string) (map[string]int, error) { // GetProjectTimes retrieves a map with times per "Activity" for a given project
func (d *Db) GetProjectTimes(projectName string) (map[string]int, error) {
query := ` query := `
SELECT development_time, meeting_time, admin_time, own_work_time, study_time, testing_time SELECT development_time, meeting_time, admin_time, own_work_time, study_time, testing_time
FROM weekly_reports FROM weekly_reports
JOIN projects ON weekly_reports.project_id = projects.id JOIN projects ON weekly_reports.project_id = projects.id
WHERE projects.name = ? WHERE projects.name = ?
` `
rows, err := d.DB.Query(query, projectName) rows, err := d.DB.Query(query, projectName)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close()
totalTime := make(map[string]int) totalTime := make(map[string]int)
for rows.Next() { for rows.Next() {
var developmentTime, meetingTime, adminTime, ownWorkTime, studyTime, testingTime int var developmentTime, meetingTime, adminTime, ownWorkTime, studyTime, testingTime int
if err := rows.Scan(&developmentTime, &meetingTime, &adminTime, &ownWorkTime, &studyTime, &testingTime); err != nil { if err := rows.Scan(&developmentTime, &meetingTime, &adminTime, &ownWorkTime, &studyTime, &testingTime); err != nil {
return nil, err return nil, err
} }
totalTime["development"] += developmentTime totalTime["development"] += developmentTime
totalTime["meeting"] += meetingTime totalTime["meeting"] += meetingTime
totalTime["admin"] += adminTime totalTime["admin"] += adminTime
totalTime["own_work"] += ownWorkTime totalTime["own_work"] += ownWorkTime
totalTime["study"] += studyTime totalTime["study"] += studyTime
totalTime["testing"] += testingTime totalTime["testing"] += testingTime
} }
if err := rows.Err(); err != nil { if err := rows.Err(); err != nil {
return nil, err return nil, err

View file

@ -729,27 +729,91 @@ func TestIsProjectManager(t *testing.T) {
} }
} }
func TestGetTotalTimePerActivity(t *testing.T) {
// Initialize your test database connection
db, err := setupState()
if err != nil {
t.Error("setupState failed:", err)
}
// Run the query to get total time per activity func TestGetProjectTimes(t *testing.T) {
totalTime, err := db.GetTotalTimePerActivity("projecttest") // Initialize
if err != nil { db, err := setupState()
t.Error("GetTotalTimePerActivity failed:", err) if err != nil {
} t.Error("setupState failed:", err)
return
}
// Check if the totalTime map is not nil // Create a user
if totalTime == nil { user := "TeaUser"
t.Error("Expected non-nil totalTime map, got nil") password := "Vanilla"
} err = db.AddUser(user, password)
if err != nil {
t.Error("AddUser failed:", err)
return
}
// ska lägga till fler assertions // Create a project
projectName := "ProjectVanilla"
projectDescription := "When tea tastes its best"
err = db.AddProject(projectName, projectDescription, user) // Fix the variable name here
if err != nil {
t.Error("AddProject failed:", err)
return
}
// Tests the func in db.go
totalTime, err := db.GetProjectTimes(projectName)
if err != nil {
t.Error("GetTotalTimePerActivity failed:", err)
return
}
// Check if the totalTime map is not nil
if totalTime == nil {
t.Error("Expected non-nil totalTime map, got nil")
return
}
// Define the expected valeus
expectedTotalTime := map[string]int{
"development": 0,
"meeting": 0,
"admin": 0,
"own_work": 0,
"study": 0,
"testing": 0,
}
// Compare the expectedTotalTime with the totalTime retrieved from the database
for activity, expectedTime := range expectedTotalTime {
if totalTime[activity] != expectedTime {
t.Errorf("Expected %s time to be %d, got %d", activity, expectedTime, totalTime[activity])
}
}
// Insert some data into the database for different activities
err = db.AddWeeklyReport(projectName, user, 1, 1, 3, 2, 1, 4, 5)
if err != nil {
t.Error("Failed to insert data into the database:", err)
return
}
newTotalTime, err := db.GetProjectTimes(projectName)
if err != nil {
t.Error("GetTotalTimePerActivity failed:", err)
return
}
newExpectedTotalTime := map[string]int{
"development": 1,
"meeting": 3,
"admin": 2,
"own_work": 1,
"study": 4,
"testing": 5,
}
for activity, newExpectedTime := range newExpectedTotalTime {
if newTotalTime[activity] != newExpectedTime {
t.Errorf("Expected %s time to be %d, got %d", activity, newExpectedTime, newTotalTime[activity])
}
}
} }
func TestEnsureManagerOfCreatedProject(t *testing.T) { func TestEnsureManagerOfCreatedProject(t *testing.T) {
db, err := setupState() db, err := setupState()
if err != nil { if err != nil {

View file

@ -234,33 +234,33 @@ func (gs *GState) PromoteToAdmin(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusOK) return c.SendStatus(fiber.StatusOK)
} }
// Changes a users name in the database // ChangeUserName changes a user's username in the database
func (gs *GState) ChangeUserName(c *fiber.Ctx) error { func (gs *GState) ChangeUserName(c *fiber.Ctx) error {
// Check token and get username of current user
//check token and get username of current user
user := c.Locals("user").(*jwt.Token) user := c.Locals("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims) claims := user.Claims.(jwt.MapClaims)
projectManagerUsername := claims["name"].(string) adminUsername := claims["name"].(string)
log.Info(projectManagerUsername) log.Info(adminUsername)
// Extract the necessary parameters from the request // Extract the necessary parameters from the request
data := new(types.NameChange) data := new(types.StrNameChange)
if err := c.BodyParser(data); err != nil { if err := c.BodyParser(data); err != nil {
log.Info("error parsing username, project or role") log.Info("Error parsing username")
return c.Status(400).SendString(err.Error()) return c.Status(400).SendString(err.Error())
} }
// dubble diping and checcking if current user is // Check if the current user is an admin
isAdmin, err := gs.Db.IsSiteAdmin(adminUsername)
if ismanager, err := gs.Db.IsProjectManager(projectManagerUsername, c.Params(data.Name)); err != nil { if err != nil {
log.Warn("Error checking if projectmanager:", err) log.Warn("Error checking if admin:", err)
return c.Status(500).SendString(err.Error()) return c.Status(500).SendString(err.Error())
} else if !ismanager { } else if !isAdmin {
log.Warn("tried changing name when not projectmanager:", err) log.Warn("Tried changing name when not admin")
return c.Status(401).SendString("you can not change name when not projectmanager") return c.Status(401).SendString("You cannot change name unless you are an admin")
} }
// Change the user's name within the project in the database // Change the user's name in the database
if err := gs.Db.ChangeUserName(projectManagerUsername, data.Name); err != nil { if err := gs.Db.ChangeUserName(data.PrevName, data.NewName); err != nil {
return c.Status(500).SendString(err.Error()) return c.Status(500).SendString(err.Error())
} }

View file

@ -41,6 +41,7 @@ getWeeklyReportsUserPath = base_url + "/api/getWeeklyReportsUser"
checkIfProjectManagerPath = base_url + "/api/checkIfProjectManager" checkIfProjectManagerPath = base_url + "/api/checkIfProjectManager"
ProjectRoleChangePath = base_url + "/api/ProjectRoleChange" ProjectRoleChangePath = base_url + "/api/ProjectRoleChange"
getUsersProjectPath = base_url + "/api/getUsersProject" getUsersProjectPath = base_url + "/api/getUsersProject"
getChangeUserNamePath = base_url + "/api/changeUserName"
#ta bort auth i handlern för att få testet att gå igenom #ta bort auth i handlern för att få testet att gå igenom
def test_ProjectRoleChange(): def test_ProjectRoleChange():
@ -367,6 +368,70 @@ 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():
# Register a new user
new_user = randomString()
register(new_user, "password")
# Log in as the new user
token = login(new_user, "password").json()["token"]
# Register a new admin
admin_username = randomString()
admin_password = "admin_password"
dprint(
"Registering with username: ", admin_username, " and password: ", admin_password
)
response = requests.post(
registerPath, json={"username": admin_username, "password": admin_password}
)
admin_token = login(admin_username, admin_password).json()["token"]
# Promote to admin
response = requests.post(
promoteToAdminPath,
json={"username": admin_username},
headers={"Authorization": "Bearer " + admin_token},
)
# Change the user's name
response = requests.put(
getChangeUserNamePath,
json={"prevName": new_user, "newName": randomString()},
headers={"Authorization": "Bearer " + admin_token},
)
# Check if the change was successful
assert response.status_code == 200, "Change user name failed"
gprint("test_change_user_name successful")
def test_list_all_users_project():
# Log in as a user who is a member of the project
admin_username = randomString()
admin_password = "admin_password2"
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
admin_token = login(admin_username, admin_password).json()["token"]
response = requests.post(
promoteToAdminPath,
json={"username": admin_username},
headers={"Authorization": "Bearer " + admin_token},
)
# Make a request to list all users associated with the project
response = requests.get(
getUsersProjectPath + "/" + projectName,
headers={"Authorization": "Bearer " + admin_token},
)
assert response.status_code == 200, "List all users project failed"
gprint("test_list_all_users_project sucessful")
if __name__ == "__main__": if __name__ == "__main__":
test_get_user_projects() test_get_user_projects()
@ -381,5 +446,6 @@ if __name__ == "__main__":
test_get_weekly_reports_user() test_get_weekly_reports_user()
test_check_if_project_manager() test_check_if_project_manager()
test_ProjectRoleChange() test_ProjectRoleChange()
#test_list_all_users_project()
test_ensure_manager_of_created_project() test_ensure_manager_of_created_project()
test_list_all_users_project()
test_change_user_name()