Major changes related to reports

This commit is contained in:
Imbus 2024-03-16 22:47:19 +01:00
parent 3526decbad
commit d99de54c5d
12 changed files with 81 additions and 98 deletions

View file

@ -4,7 +4,6 @@ import (
"embed" "embed"
"os" "os"
"path/filepath" "path/filepath"
"time"
"ttime/internal/types" "ttime/internal/types"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
@ -21,7 +20,7 @@ type Database interface {
AddProject(name string, description string, username string) error AddProject(name string, description string, username string) error
Migrate(dirname string) error Migrate(dirname string) error
GetProjectId(projectname string) (int, error) GetProjectId(projectname string) (int, error)
AddTimeReport(projectName string, userName string, activityType string, start time.Time, end time.Time) error AddWeeklyReport(projectName string, userName string, week int, developmentTime int, meetingTime int, adminTime int, ownWorkTime int, studyTime int, testingTime int) error
AddUserToProject(username string, projectname string, role string) error AddUserToProject(username string, projectname string, role string) error
ChangeUserRole(username string, projectname string, role string) error ChangeUserRole(username string, projectname string, role string) error
GetAllUsersProject(projectname string) ([]UserProjectMember, error) GetAllUsersProject(projectname string) ([]UserProjectMember, error)
@ -50,27 +49,16 @@ var scripts embed.FS
const userInsert = "INSERT INTO users (username, password) VALUES (?, ?)" const userInsert = "INSERT INTO users (username, password) VALUES (?, ?)"
const projectInsert = "INSERT INTO projects (name, description, owner_user_id) SELECT ?, ?, id FROM users WHERE username = ?" const projectInsert = "INSERT INTO projects (name, description, owner_user_id) SELECT ?, ?, id FROM users WHERE username = ?"
const promoteToAdmin = "INSERT INTO site_admin (admin_id) SELECT id FROM users WHERE username = ?" const promoteToAdmin = "INSERT INTO site_admin (admin_id) SELECT id FROM users WHERE username = ?"
const addTimeReport = `WITH UserLookup AS (SELECT id FROM users WHERE username = ?), const addWeeklyReport = `WITH UserLookup AS (SELECT id FROM users WHERE username = ?),
ProjectLookup AS (SELECT id FROM projects WHERE name = ?) ProjectLookup AS (SELECT id FROM projects WHERE name = ?)
INSERT INTO time_reports (project_id, user_id, activity_type, start, end) INSERT INTO weekly_reports (project_id, user_id, week, development_time, meeting_time, admin_time, own_work_time, study_time, testing_time)
VALUES ((SELECT id FROM ProjectLookup), (SELECT id FROM UserLookup),?, ?, ?);` VALUES ((SELECT id FROM ProjectLookup), (SELECT id FROM UserLookup),?, ?, ?, ?, ?, ?, ?);`
const addUserToProject = "INSERT INTO user_roles (user_id, project_id, p_role) VALUES (?, ?, ?)" // WIP const addUserToProject = "INSERT INTO user_roles (user_id, project_id, p_role) VALUES (?, ?, ?)" // WIP
const changeUserRole = "UPDATE user_roles SET p_role = ? WHERE user_id = ? AND project_id = ?" const changeUserRole = "UPDATE user_roles SET p_role = ? WHERE user_id = ? AND project_id = ?"
const getProjectsForUser = ` const getProjectsForUser = `SELECT projects.id, projects.name, projects.description, projects.owner_user_id
SELECT FROM projects JOIN user_roles ON projects.id = user_roles.project_id
projects.id, JOIN users ON user_roles.user_id = users.id WHERE users.username = ?;`
projects.name,
projects.description,
projects.owner_user_id
FROM
projects
JOIN
user_roles ON projects.id = user_roles.project_id
JOIN
users ON user_roles.user_id = users.id
WHERE
users.username = ?;`
// DbConnect connects to the database // DbConnect connects to the database
func DbConnect(dbpath string) Database { func DbConnect(dbpath string) Database {
@ -110,9 +98,8 @@ func (d *Db) GetProject(projectId int) (types.Project, error) {
return project, err return project, err
} }
// AddTimeReport adds a time report for a specific project and user. func (d *Db) AddWeeklyReport(projectName string, userName string, week int, developmentTime int, meetingTime int, adminTime int, ownWorkTime int, studyTime int, testingTime int) error {
func (d *Db) AddTimeReport(projectName string, userName string, activityType string, start time.Time, end time.Time) error { // WIP _, err := d.Exec(addWeeklyReport, userName, projectName, week, developmentTime, meetingTime, adminTime, ownWorkTime, studyTime, testingTime)
_, err := d.Exec(addTimeReport, userName, projectName, activityType, start, end)
return err return err
} }

View file

@ -2,7 +2,6 @@ package database
import ( import (
"testing" "testing"
"time"
) )
// Tests are not guaranteed to be sequential // Tests are not guaranteed to be sequential
@ -93,7 +92,7 @@ func TestPromoteToAdmin(t *testing.T) {
} }
} }
func TestAddTimeReport(t *testing.T) { func TestAddWeeklyReport(t *testing.T) {
db, err := setupState() db, err := setupState()
if err != nil { if err != nil {
t.Error("setupState failed:", err) t.Error("setupState failed:", err)
@ -109,12 +108,9 @@ func TestAddTimeReport(t *testing.T) {
t.Error("AddProject failed:", err) t.Error("AddProject failed:", err)
} }
var now = time.Now() err = db.AddWeeklyReport("testproject", "testuser", 1, 1, 1, 1, 1, 1, 1)
var then = now.Add(time.Hour)
err = db.AddTimeReport("testproject", "testuser", "activity", now, then)
if err != nil { if err != nil {
t.Error("AddTimeReport failed:", err) t.Error("AddWeeklyReport failed:", err)
} }
} }
@ -134,12 +130,9 @@ func TestAddUserToProject(t *testing.T) {
t.Error("AddProject failed:", err) t.Error("AddProject failed:", err)
} }
var now = time.Now() err = db.AddWeeklyReport("testproject", "testuser", 1, 1, 1, 1, 1, 1, 1)
var then = now.Add(time.Hour)
err = db.AddTimeReport("testproject", "testuser", "activity", now, then)
if err != nil { if err != nil {
t.Error("AddTimeReport failed:", err) t.Error("AddWeeklyReport failed:", err)
} }
err = db.AddUserToProject("testuser", "testproject", "user") err = db.AddUserToProject("testuser", "testproject", "user")

View file

@ -1,22 +0,0 @@
CREATE TABLE IF NOT EXISTS time_reports (
id INTEGER PRIMARY KEY,
project_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
activity_type TEXT NOT NULL,
start DATETIME NOT NULL,
end DATETIME NOT NULL,
FOREIGN KEY (project_id) REFERENCES projects (id) ON DELETE CASCADE
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
FOREIGN KEY (activity_type) REFERENCES activity_types (name) ON DELETE CASCADE
);
CREATE TRIGGER IF NOT EXISTS time_reports_start_before_end
BEFORE INSERT ON time_reports
FOR EACH ROW
BEGIN
SELECT
CASE
WHEN NEW.start >= NEW.end THEN
RAISE (ABORT, 'start must be before end')
END;
END;

View file

@ -0,0 +1,14 @@
CREATE TABLE weekly_reports (
user_id INTEGER,
project_id INTEGER,
week INTEGER,
development_time INTEGER,
meeting_time INTEGER,
admin_time INTEGER,
own_work_time INTEGER,
study_time INTEGER,
testing_time INTEGER,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (project_id) REFERENCES projects(id)
PRIMARY KEY (user_id, project_id, week)
)

View file

@ -1,9 +0,0 @@
CREATE TABLE IF NOT EXISTS report_collection (
id INTEGER PRIMARY KEY,
owner_id INTEGER NOT NULL,
project_id INTEGER NOT NULL,
date DATE NOT NULL,
signed_by INTEGER, -- NULL if not signed
FOREIGN KEY (owner_id) REFERENCES users (id)
FOREIGN KEY (signed_by) REFERENCES users (id)
);

View file

@ -1,16 +0,0 @@
-- It is unclear weather this table will be used
-- Create the table to store hash salts
CREATE TABLE IF NOT EXISTS salts (
id INTEGER PRIMARY KEY,
salt TEXT NOT NULL
);
-- Commented out for now, no time for good practices, which is atrocious
-- Create a trigger to automatically generate a salt when inserting a new user record
-- CREATE TRIGGER generate_salt_trigger
-- AFTER INSERT ON users
-- BEGIN
-- INSERT INTO salts (salt) VALUES (randomblob(16));
-- UPDATE users SET salt_id = (SELECT last_insert_rowid()) WHERE id = new.id;
-- END;

View file

@ -1,10 +0,0 @@
CREATE TABLE IF NOT EXISTS activity_types (
name TEXT PRIMARY KEY
);
INSERT OR IGNORE INTO activity_types (name) VALUES ('Development');
INSERT OR IGNORE INTO activity_types (name) VALUES ('Meeting');
INSERT OR IGNORE INTO activity_types (name) VALUES ('Administration');
INSERT OR IGNORE INTO activity_types (name) VALUES ('Own Work');
INSERT OR IGNORE INTO activity_types (name) VALUES ('Studies');
INSErt OR IGNORE INTO activity_types (name) VALUES ('Testing');

View file

@ -18,6 +18,7 @@ type GlobalState interface {
LoginRenew(c *fiber.Ctx) error // To renew the token LoginRenew(c *fiber.Ctx) error // To renew the token
CreateProject(c *fiber.Ctx) error // To create a new project CreateProject(c *fiber.Ctx) error // To create a new project
GetUserProjects(c *fiber.Ctx) error // To get all projects GetUserProjects(c *fiber.Ctx) error // To get all projects
SubmitWeeklyReport(c *fiber.Ctx) error
// GetProject(c *fiber.Ctx) error // To get a specific project // GetProject(c *fiber.Ctx) error // To get a specific project
// UpdateProject(c *fiber.Ctx) error // To update a project // UpdateProject(c *fiber.Ctx) error // To update a project
// DeleteProject(c *fiber.Ctx) error // To delete a project // DeleteProject(c *fiber.Ctx) error // To delete a project
@ -77,12 +78,17 @@ func (gs *GState) Register(c *fiber.Ctx) error {
// This path should obviously be protected in the future // This path should obviously be protected in the future
// UserDelete deletes a user from the database // UserDelete deletes a user from the database
func (gs *GState) UserDelete(c *fiber.Ctx) error { func (gs *GState) UserDelete(c *fiber.Ctx) error {
u := new(types.User) // Read from path parameters
if err := c.BodyParser(u); err != nil { username := c.Params("username")
return c.Status(400).SendString(err.Error())
// Read username from Locals
auth_username := c.Locals("user").(*jwt.Token).Claims.(jwt.MapClaims)["name"].(string)
if username != auth_username {
return c.Status(403).SendString("You can only delete yourself")
} }
if err := gs.Db.RemoveUser(u.Username); err != nil { if err := gs.Db.RemoveUser(username); err != nil {
return c.Status(500).SendString(err.Error()) return c.Status(500).SendString(err.Error())
} }
@ -247,3 +253,21 @@ func (gs *GState) GetProject(c *fiber.Ctx) error {
// Return the project as JSON // Return the project as JSON
return c.JSON(project) return c.JSON(project)
} }
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 {
return c.Status(400).SendString(err.Error())
}
if err := gs.Db.AddWeeklyReport(report.ProjectName, username, report.Week, report.DevelopmentTime, report.MeetingTime, report.AdminTime, report.OwnWorkTime, report.StudyTime, report.TestingTime); err != nil {
return c.Status(500).SendString(err.Error())
}
return c.Status(200).SendString("Time report added")
}

View file

@ -0,0 +1,21 @@
package types
// This is what should be submitted to the server, the username will be derived from the JWT token
type NewWeeklyReport struct {
// The name of the project, as it appears in the database
ProjectName string
// The week number
Week int
// Total time spent on development
DevelopmentTime int
// Total time spent in meetings
MeetingTime int
// Total time spent on administrative tasks
AdminTime int
// Total time spent on personal projects
OwnWorkTime int
// Total time spent on studying
StudyTime int
// Total time spent on testing
TestingTime int
}

View file

@ -8,9 +8,8 @@ type Project struct {
Owner string `json:"owner" db:"owner_user_id"` Owner string `json:"owner" db:"owner_user_id"`
} }
// As it arrives from the client // As it arrives from the client, Owner is derived from the JWT token
type NewProject struct { type NewProject struct {
Name string `json:"name"` Name string `json:"name"`
Description string `json:"description"` Description string `json:"description"`
Owner string `json:"owner"`
} }

View file

@ -16,6 +16,7 @@ func (u *User) ToPublicUser() (*PublicUser, error) {
}, nil }, nil
} }
// Should be used when registering, for example
type NewUser struct { type NewUser struct {
Username string `json:"username"` Username string `json:"username"`
Password string `json:"password"` Password string `json:"password"`

View file

@ -68,9 +68,10 @@ func main() {
SigningKey: jwtware.SigningKey{Key: []byte("secret")}, SigningKey: jwtware.SigningKey{Key: []byte("secret")},
})) }))
server.Post("/api/submitReport", gs.SubmitWeeklyReport)
server.Get("/api/getUserProjects", gs.GetUserProjects) server.Get("/api/getUserProjects", gs.GetUserProjects)
server.Post("/api/loginrenew", gs.LoginRenew) server.Post("/api/loginrenew", gs.LoginRenew)
server.Delete("/api/userdelete", gs.UserDelete) // Perhaps just use POST to avoid headaches server.Delete("/api/userdelete/:username", gs.UserDelete) // Perhaps just use POST to avoid headaches
server.Post("/api/project", gs.CreateProject) server.Post("/api/project", gs.CreateProject)
// Announce the port we are listening on and start the server // Announce the port we are listening on and start the server