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
IsSiteAdmin(username 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
@ -491,36 +493,36 @@ func (d *Db) MigrateSampleData() error {
return nil
}
func (d *Db) GetTotalTimePerActivity(projectName string) (map[string]int, error) {
query := `
// GetProjectTimes retrieves a map with times per "Activity" for a given project
func (d *Db) GetProjectTimes(projectName string) (map[string]int, error) {
query := `
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
WHERE projects.name = ?
`
rows, err := d.DB.Query(query, projectName)
if err != nil {
return nil, err
}
defer rows.Close()
rows, err := d.DB.Query(query, projectName)
if err != nil {
return nil, err
}
defer rows.Close()
totalTime := make(map[string]int)
for rows.Next() {
var developmentTime, meetingTime, adminTime, ownWorkTime, studyTime, testingTime int
if err := rows.Scan(&developmentTime, &meetingTime, &adminTime, &ownWorkTime, &studyTime, &testingTime); err != nil {
return nil, err
}
for rows.Next() {
var developmentTime, meetingTime, adminTime, ownWorkTime, studyTime, testingTime int
if err := rows.Scan(&developmentTime, &meetingTime, &adminTime, &ownWorkTime, &studyTime, &testingTime); err != nil {
return nil, err
}
totalTime["development"] += developmentTime
totalTime["meeting"] += meetingTime
totalTime["admin"] += adminTime
totalTime["own_work"] += ownWorkTime
totalTime["study"] += studyTime
totalTime["testing"] += testingTime
}
totalTime["development"] += developmentTime
totalTime["meeting"] += meetingTime
totalTime["admin"] += adminTime
totalTime["own_work"] += ownWorkTime
totalTime["study"] += studyTime
totalTime["testing"] += testingTime
}
if err := rows.Err(); err != nil {
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
totalTime, err := db.GetTotalTimePerActivity("projecttest")
if err != nil {
t.Error("GetTotalTimePerActivity failed:", err)
}
func TestGetProjectTimes(t *testing.T) {
// Initialize
db, err := setupState()
if err != nil {
t.Error("setupState failed:", err)
return
}
// Check if the totalTime map is not nil
if totalTime == nil {
t.Error("Expected non-nil totalTime map, got nil")
}
// Create a user
user := "TeaUser"
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) {
db, err := setupState()
if err != nil {

View file

@ -234,33 +234,33 @@ func (gs *GState) PromoteToAdmin(c *fiber.Ctx) error {
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 {
//check token and get username of current user
// Check token and get username of current user
user := c.Locals("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
projectManagerUsername := claims["name"].(string)
log.Info(projectManagerUsername)
adminUsername := claims["name"].(string)
log.Info(adminUsername)
// Extract the necessary parameters from the request
data := new(types.NameChange)
data := new(types.StrNameChange)
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())
}
// dubble diping and checcking if current user is
if ismanager, err := gs.Db.IsProjectManager(projectManagerUsername, c.Params(data.Name)); err != nil {
log.Warn("Error checking if projectmanager:", err)
// 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 !ismanager {
log.Warn("tried changing name when not projectmanager:", err)
return c.Status(401).SendString("you can not change name when not projectmanager")
} 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 within the project in the database
if err := gs.Db.ChangeUserName(projectManagerUsername, data.Name); err != nil {
// 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())
}

View file

@ -41,6 +41,7 @@ getWeeklyReportsUserPath = base_url + "/api/getWeeklyReportsUser"
checkIfProjectManagerPath = base_url + "/api/checkIfProjectManager"
ProjectRoleChangePath = base_url + "/api/ProjectRoleChange"
getUsersProjectPath = base_url + "/api/getUsersProject"
getChangeUserNamePath = base_url + "/api/changeUserName"
#ta bort auth i handlern för att få testet att gå igenom
def test_ProjectRoleChange():
@ -367,6 +368,70 @@ def test_ensure_manager_of_created_project():
assert response.json()["isProjectManager"] == True, "User is not project manager"
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__":
test_get_user_projects()
@ -381,5 +446,6 @@ if __name__ == "__main__":
test_get_weekly_reports_user()
test_check_if_project_manager()
test_ProjectRoleChange()
#test_list_all_users_project()
test_ensure_manager_of_created_project()
test_list_all_users_project()
test_change_user_name()