Compare commits
No commits in common. "master" and "ddogge" have entirely different histories.
178 changed files with 829 additions and 17288 deletions
33
.github/workflows/go.yml
vendored
33
.github/workflows/go.yml
vendored
|
@ -1,33 +0,0 @@
|
|||
# This workflow will build a golang project
|
||||
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-go
|
||||
|
||||
name: Go
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: ./backend
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: '1.21'
|
||||
|
||||
- name: Build
|
||||
run: go build -v ./...
|
||||
|
||||
- name: Test
|
||||
run: go test -v ./...
|
54
.github/workflows/golangci-lint.yml
vendored
54
.github/workflows/golangci-lint.yml
vendored
|
@ -1,54 +0,0 @@
|
|||
name: golangci-lint
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
# Optional: allow read access to pull request. Use with `only-new-issues` option.
|
||||
# pull-requests: read
|
||||
|
||||
jobs:
|
||||
golangci:
|
||||
name: lint
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.21"
|
||||
cache: false
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v4
|
||||
with:
|
||||
# Require: The version of golangci-lint to use.
|
||||
# When `install-mode` is `binary` (default) the value can be v1.2 or v1.2.3 or `latest` to use the latest version.
|
||||
# When `install-mode` is `goinstall` the value can be v1.2.3, `latest`, or the hash of a commit.
|
||||
version: v1.54
|
||||
|
||||
# Optional: working directory, useful for monorepos
|
||||
working-directory: ./backend
|
||||
|
||||
# Optional: golangci-lint command line arguments.
|
||||
#
|
||||
# Note: By default, the `.golangci.yml` file should be at the root of the repository.
|
||||
# The location of the configuration file can be changed by using `--config=`
|
||||
# args: --timeout=30m --config=/my/path/.golangci.yml --issues-exit-code=0
|
||||
|
||||
# Optional: show only new issues if it's a pull request. The default value is `false`.
|
||||
# only-new-issues: true
|
||||
|
||||
# Optional: if set to true, then all caching functionality will be completely disabled,
|
||||
# takes precedence over all other caching options.
|
||||
# skip-cache: true
|
||||
|
||||
# Optional: if set to true, then the action won't cache or restore ~/go/pkg.
|
||||
# skip-pkg-cache: true
|
||||
|
||||
# Optional: if set to true, then the action won't cache or restore ~/.cache/go-build.
|
||||
# skip-build-cache: true
|
||||
|
||||
# Optional: The mode to install golangci-lint. It can be 'binary' or 'goinstall'.
|
||||
# install-mode: "goinstall"
|
37
.github/workflows/node.js.yml
vendored
37
.github/workflows/node.js.yml
vendored
|
@ -1,37 +0,0 @@
|
|||
# This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node
|
||||
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs
|
||||
|
||||
name: Node.js CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: ./frontend
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [20.x]
|
||||
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: 'npm'
|
||||
cache-dependency-path: '**/package-lock.json'
|
||||
- run: npm ci
|
||||
- run: npm run lint
|
||||
- run: npm run build --if-present
|
||||
- run: npm test
|
25
.github/workflows/sqlite3-migrations.yml
vendored
25
.github/workflows/sqlite3-migrations.yml
vendored
|
@ -1,25 +0,0 @@
|
|||
name: SQLite3 Migrations
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: ./backend
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Install SQLite3
|
||||
run: sudo apt-get install sqlite3
|
||||
- name: Install Make
|
||||
run: sudo apt-get install make
|
||||
- name: Run Migrations
|
||||
run: make migrate
|
16
.gitignore
vendored
16
.gitignore
vendored
|
@ -6,19 +6,7 @@
|
|||
*.dylib
|
||||
|
||||
bin
|
||||
database.txt
|
||||
plantuml.jar
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
diagram.puml
|
||||
backend/*.png
|
||||
backend/*.jpg
|
||||
backend/*.svg
|
||||
__pycache__
|
||||
|
||||
/go.work.sum
|
||||
/package-lock.json
|
||||
/backend/docs/swagger.json
|
||||
|
||||
# Test binary, built with `go test -c`
|
||||
*.test
|
||||
|
@ -42,7 +30,6 @@ dist/
|
|||
.vscode/
|
||||
.idea/
|
||||
.DS_Store
|
||||
.go.work.sum
|
||||
|
||||
# Ignore configuration files
|
||||
.env
|
||||
|
@ -61,6 +48,5 @@ dist/
|
|||
*.7z
|
||||
*.bak
|
||||
|
||||
backend/backups
|
||||
|
||||
config.toml
|
||||
|
||||
|
|
21
Justfile
21
Justfile
|
@ -11,29 +11,19 @@ start-release: build-container-release remove-podman-containers
|
|||
# Removes and stops any containers related to the project
|
||||
[private]
|
||||
remove-podman-containers:
|
||||
podman container rm -fi ttime
|
||||
podman container rm -f ttime
|
||||
|
||||
# Saves the release container to a tarball, pigz is just gzip but multithreaded
|
||||
save-release: build-container-release
|
||||
podman save --format=oci-archive ttime-server | pigz -9 > ttime-server_`date -I`_`git rev-parse --short HEAD`.tar.gz
|
||||
podman save --format=oci-archive ttime-server | pigz -9 > ttime-server.tar.gz
|
||||
|
||||
# Loads the release container from a tarball
|
||||
load-release file:
|
||||
podman load --input {{file}}
|
||||
|
||||
# Tests every part of the project
|
||||
testall:
|
||||
cd frontend && npm install
|
||||
cd frontend && npm test
|
||||
cd frontend && npm run lint
|
||||
cd frontend && npm run build
|
||||
cd backend && make test
|
||||
cd backend && make lint
|
||||
cd backend && make itest
|
||||
|
||||
# Cleans up everything related to the project
|
||||
clean: remove-podman-containers
|
||||
podman image rm -fi ttime-server
|
||||
podman image rm -f ttime-server
|
||||
rm -rf frontend/dist
|
||||
rm -rf frontend/node_modules
|
||||
rm -f ttime-server.tar.gz
|
||||
|
@ -43,7 +33,4 @@ clean: remove-podman-containers
|
|||
# Cleans up everything related to podman, not just the project. Make sure you understand what this means.
|
||||
[confirm]
|
||||
podman-clean:
|
||||
podman system reset --force
|
||||
|
||||
install-linter:
|
||||
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.56.2
|
||||
podman system reset --force
|
48
Makefile
48
Makefile
|
@ -1,48 +0,0 @@
|
|||
# Builds a release container
|
||||
build-container-release:
|
||||
podman build -t ttime-server -f container/Containerfile .
|
||||
|
||||
# Builds a release container and runs it
|
||||
start-release: build-container-release remove-podman-containers
|
||||
podman run -d -e DATABASE_URL=sqlite:release.db -p 8080:8080 --name ttime ttime-server
|
||||
@echo "Started production ttime-server on http://localhost:8080"
|
||||
|
||||
# Removes and stops any containers related to the project
|
||||
remove-podman-containers:
|
||||
podman container rm -fi ttime
|
||||
|
||||
# Tests every part of the project
|
||||
testall:
|
||||
cd frontend && npm install
|
||||
cd frontend && npm test
|
||||
cd frontend && npm run lint
|
||||
cd frontend && npm run build
|
||||
cd backend && make test
|
||||
cd backend && make lint
|
||||
cd backend && make itest
|
||||
|
||||
# Cleans up everything related to the project
|
||||
clean: remove-podman-containers
|
||||
podman image rm -fi ttime-server
|
||||
rm -rf frontend/dist
|
||||
rm -rf frontend/node_modules
|
||||
rm -f ttime-server.tar.gz
|
||||
cd backend && make clean
|
||||
@echo "Cleaned up!"
|
||||
|
||||
.PHONY: itest
|
||||
itest:
|
||||
python testing.py
|
||||
|
||||
# Cleans up everything related to podman, not just the project. Make sure you understand what this means.
|
||||
podman-clean:
|
||||
podman system reset --force
|
||||
|
||||
# Installs the linter, which is not included in the ubuntu repo
|
||||
install-linter:
|
||||
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.56.2
|
||||
|
||||
# This installs just, a make alternative, which is slightly more ergonomic to use
|
||||
install-just:
|
||||
@echo "Installing just"
|
||||
@curl --proto '=https' --tlsv1.2 -sSf https://just.systems/install.sh | bash -s -- --to /usr/local/bin
|
51
README.md
51
README.md
|
@ -23,16 +23,12 @@ Dependencies:
|
|||
- [Podman](https://podman.io/) / [Docker](https://www.docker.com/)
|
||||
- [Just](https://github.com/casey/just) (Optional)
|
||||
|
||||
### Fedora/Red Hat
|
||||
|
||||
If you're on [Fedora](https://fedoraproject.org/)/Red Hat derivatives, this is as simple as:
|
||||
|
||||
```bash
|
||||
sudo dnf install -y make golang nodejs podman just
|
||||
```
|
||||
|
||||
### Debian/Ubuntu
|
||||
|
||||
Any [Debian](https://www.debian.org/)/[Ubuntu](https://ubuntu.com/desktop)-based distro:
|
||||
|
||||
```bash
|
||||
|
@ -40,43 +36,19 @@ sudo apt install -y make golang nodejs podman
|
|||
sudo apt install -y just # For Ubuntu
|
||||
```
|
||||
|
||||
### Arch Linux
|
||||
|
||||
[Arch Linux](https://archlinux.org/) & derivatives:
|
||||
|
||||
```bash
|
||||
sudo pacman -S make go nodejs npm podman just
|
||||
```
|
||||
|
||||
### MacOS
|
||||
|
||||
[MacOS](https://www.apple.com/macos/): (Requires [Homebrew](https://brew.sh/)) (Untested)
|
||||
|
||||
```bash
|
||||
brew install make go nodejs npm podman just
|
||||
```
|
||||
|
||||
### Windows
|
||||
|
||||
#### Vanilla Windows
|
||||
|
||||
The project should now build properly on Windows, given the dependencies:
|
||||
|
||||
- [Go](https://go.dev/)
|
||||
- [Node & npm](https://nodejs.org/en/)
|
||||
|
||||
With chocolatey, you can install these dependencies with the following commands:
|
||||
|
||||
```powershell
|
||||
choco install -y golang nodejs
|
||||
```
|
||||
|
||||
Note that none of the convenience tools (Make, Podman, Just*) are available on Windows.
|
||||
|
||||
*Just is available, but the targets are written for a Unix-like environment.
|
||||
|
||||
#### Windows Subsystem for Linux (WSL)
|
||||
|
||||
[Windows](https://www.microsoft.com/en-us/windows):
|
||||
Unfortunately, [Windows Subsystem for Linux (WSL)](https://docs.microsoft.com/en-us/windows/wsl/install) is required for the build process. Running any form of containerized workload on windows is currently unsupported. More info [here](https://podman.io/docs/installation#windows). From my understanding, WSL also requires virtualization extensions to be enabled in the BIOS, which is not always the case for all users.
|
||||
|
||||
It is possible to run the code on Windows, but this will be without the use of containers or any other build tools that are not available on Windows.
|
||||
|
@ -87,22 +59,15 @@ My recommendation would be to make WSL your primary development environment if y
|
|||
You should consult the [WSL documentation](https://docs.microsoft.com/en-us/windows/wsl/install), but for any recent version of windows, installation essentially boils down to running the following command in **PowerShell as an administrator**:
|
||||
|
||||
```powershell
|
||||
wsl --install -d Ubuntu-22.04 # To get a somewhat recent version of Go
|
||||
wsl --install
|
||||
```
|
||||
|
||||
After this, you can open a (wsl) terminal and run the commands:
|
||||
If you get any errors related to virtualization, you will need to enable virtualization in the BIOS. This is a common issue, and you can find a guide for your specific motherboard online. This is a one-time operation and will not affect your windows installation. This setting is usually called "VT-x" or "AMD-V" and is usually found in the CPU settings. If you can't find it, shoot me a message and I'll find it for you.
|
||||
|
||||
```bash
|
||||
sudo apt update && sudo apt upgrade
|
||||
sudo apt install -y make podman
|
||||
If you're **still dead set** on using a vanilla Windows environment, you will need the following:
|
||||
|
||||
sudo add-apt-repository ppa:longsleep/golang-backports
|
||||
sudo apt update
|
||||
sudo apt install golang-go
|
||||
- [Go](https://go.dev/)
|
||||
- [Node & npm](https://nodejs.org/en/)
|
||||
- [MariaDB](https://mariadb.org/) / [MySQL](https://www.mysql.com/) / [PostgreSQL](https://www.postgresql.org/) (This is undecided so far)
|
||||
|
||||
# For a recent version of node:
|
||||
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
|
||||
nvm install node
|
||||
```
|
||||
|
||||
If you get any errors related to virtualization, you will need to enable virtualization in the BIOS. This is a common issue, and you can find a guide for your specific motherboard online. This is a one-time operation and will not affect your windows installation. This setting is usually called "VT-x" or "AMD-V" and is usually found in the CPU settings.
|
||||
With some grit and determination, you can get it to work. It's not recommended, but I (Imbus) will try to help you.
|
||||
|
|
126
backend/Makefile
126
backend/Makefile
|
@ -8,47 +8,29 @@ GOGET = $(GOCMD) get
|
|||
# SQLite database filename
|
||||
DB_FILE = db.sqlite3
|
||||
|
||||
PROC_NAME = ttime_server
|
||||
|
||||
# Directory containing migration SQL scripts
|
||||
MIGRATIONS_DIR = internal/database/migrations
|
||||
SAMPLE_DATA_DIR = internal/database/sample_data
|
||||
MIGRATIONS_DIR = migrations
|
||||
|
||||
# Build target
|
||||
build:
|
||||
$(GOBUILD) -o bin/$(PROC_NAME) main.go
|
||||
$(GOBUILD) -o bin/server cmd/*.go
|
||||
|
||||
# Run target
|
||||
run: build
|
||||
./bin/$(PROC_NAME)
|
||||
./bin/server
|
||||
|
||||
watch: build
|
||||
watchexec -c -w . -r make run
|
||||
watchexec -w . -r make run
|
||||
|
||||
# Clean target
|
||||
clean:
|
||||
$(GOCLEAN)
|
||||
rm -rf bin
|
||||
rm -f db.sqlite3
|
||||
rm -f diagram*
|
||||
rm -f plantuml.jar
|
||||
rm -f erd.png
|
||||
rm -f config.toml
|
||||
rm -f database.txt
|
||||
|
||||
# Test target
|
||||
test: db.sqlite3
|
||||
$(GOTEST) ./... -count=1
|
||||
|
||||
# Integration test target
|
||||
.PHONY: itest
|
||||
itest:
|
||||
pgrep $(PROC_NAME) && echo "Server already running" && exit 1 || true
|
||||
make build
|
||||
./bin/$(PROC_NAME) >/dev/null 2>&1 &
|
||||
sleep 1 # Adjust if needed
|
||||
python ../testing/testing.py || pkill $(PROC_NAME)
|
||||
pkill $(PROC_NAME)
|
||||
test:
|
||||
$(GOTEST) ./...
|
||||
|
||||
# Get dependencies target
|
||||
deps:
|
||||
|
@ -61,105 +43,11 @@ update:
|
|||
|
||||
# Migration target
|
||||
migrate:
|
||||
@echo "If this ever fails, run make clean and try again"
|
||||
@echo "Migrating database $(DB_FILE) using SQL scripts in $(MIGRATIONS_DIR)"
|
||||
@for file in $(wildcard $(MIGRATIONS_DIR)/*.sql); do \
|
||||
echo "Applying migration: $$file"; \
|
||||
sqlite3 $(DB_FILE) < $$file; \
|
||||
done
|
||||
|
||||
sampledata:
|
||||
@echo "If this ever fails, run make clean and try again"
|
||||
@echo "Migrating database $(DB_FILE) using SQL scripts in $(SAMPLE_DATA_DIR)"
|
||||
@for file in $(wildcard $(SAMPLE_DATA_DIR)/*.sql); do \
|
||||
echo "Applying migration: $$file"; \
|
||||
sqlite3 $(DB_FILE) < $$file; \
|
||||
done
|
||||
|
||||
# Target added primarily for CI/CD to ensure that the database is created before running tests
|
||||
db.sqlite3:
|
||||
make migrate
|
||||
|
||||
dbdump:
|
||||
sqlite3 $(DB_FILE) .dump > database.txt
|
||||
|
||||
backup:
|
||||
mkdir -p backups
|
||||
sqlite3 $(DB_FILE) .dump | gzip -9 > ./backups/BACKUP_$(DB_FILE)_$(shell date +"%Y-%m-%d_%H:%M:%S").sql.gz
|
||||
# Restore with:
|
||||
# gzip -cd BACKUP_FILE.sql.gz | sqlite3 $(DB_FILE)
|
||||
|
||||
# Format
|
||||
fmt:
|
||||
$(GOCMD) fmt ./...
|
||||
|
||||
# Lint
|
||||
lint:
|
||||
golangci-lint run ./...
|
||||
|
||||
# Default target
|
||||
default: build
|
||||
|
||||
# Generate swagger docs
|
||||
.PHONY: docs
|
||||
docs:
|
||||
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
|
||||
docfmt:
|
||||
swag fmt
|
||||
|
||||
# Generate ERD
|
||||
# Requires eralchemy2
|
||||
.PHONY: erd
|
||||
erd:
|
||||
eralchemy2 -i sqlite:///db.sqlite3 -o erd.png
|
||||
|
||||
install-swag:
|
||||
@echo "Installing swag"
|
||||
@go get -u github.com/swaggo/swag/cmd/swag
|
||||
|
||||
# Convenience target to install golangci-lint
|
||||
install-lint:
|
||||
@echo "Installing golangci-lint"
|
||||
@curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(shell go env GOPATH)/bin v1.42.1
|
||||
|
||||
# Fetches the latest plantuml.jar and checks its SHA256 hash
|
||||
plantuml.jar:
|
||||
curl -sSfL https://github.com/plantuml/plantuml/releases/download/v1.2024.3/plantuml.jar -o plantuml.jar \
|
||||
&& echo "519a4a7284c6a0357c369e4bb0caf72c4bfbbde851b8c6d6bbdb7af3c01fc82f plantuml.jar" | sha256sum -c
|
||||
|
||||
# Generate UML diagrams diagral.png & diagram.svg
|
||||
.PHONY: uml
|
||||
uml: plantuml.jar
|
||||
goplantuml -recursive . > diagram.puml
|
||||
java -jar plantuml.jar -tpng diagram.puml
|
||||
java -jar plantuml.jar -tsvg diagram.puml
|
||||
|
||||
# Convenience target to install just (requires sudo privileges)
|
||||
install-just:
|
||||
@echo "Installing just"
|
||||
@curl --proto '=https' --tlsv1.2 -sSf https://just.systems/install.sh | bash -s -- --to /usr/local/bin
|
||||
|
||||
.PHONY: types
|
||||
types:
|
||||
tygo generate
|
||||
|
||||
.PHONY: install-golds
|
||||
install-golds:
|
||||
go install go101.org/golds@latest
|
||||
|
||||
.PHONY: golds
|
||||
golds:
|
||||
golds -port 6060 -nouses -plainsrc -wdpkgs-listing=promoted ./...
|
||||
default: build
|
61
backend/cmd/main.go
Normal file
61
backend/cmd/main.go
Normal file
|
@ -0,0 +1,61 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"ttime/internal/database"
|
||||
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
// The button state as represented in memory
|
||||
type ButtonState struct {
|
||||
PressCount int `json:"pressCount"`
|
||||
}
|
||||
|
||||
// This is what a handler with a receiver looks like
|
||||
// Keep in mind that concurrent state access is not (usually) safe
|
||||
// And will in practice be guarded by a mutex
|
||||
func (b *ButtonState) pressHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == "POST" {
|
||||
b.PressCount++
|
||||
}
|
||||
|
||||
response, err := json.Marshal(b)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("Request received")
|
||||
io.WriteString(w, string(response))
|
||||
}
|
||||
|
||||
// This is what a handler looks like
|
||||
func handler(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Println("Request received")
|
||||
io.WriteString(w, "This is my website!\n")
|
||||
}
|
||||
|
||||
func main() {
|
||||
database.DbConnect()
|
||||
b := &ButtonState{PressCount: 0}
|
||||
|
||||
// Mounting the handlers
|
||||
fs := http.FileServer(http.Dir("static"))
|
||||
http.Handle("/", fs)
|
||||
http.HandleFunc("/hello", handler)
|
||||
http.HandleFunc("/api/button", b.pressHandler)
|
||||
|
||||
// Start the server on port 8080
|
||||
println("Currently listening on http://localhost:8080")
|
||||
println("Visit http://localhost:8080/hello to see the hello handler in action")
|
||||
println("Visit http://localhost:8080/button to see the button handler in action")
|
||||
println("Press Ctrl+C to stop the server")
|
||||
err := http.ListenAndServe(":8080", nil)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
|
@ -1,404 +0,0 @@
|
|||
// Package docs Code generated by swaggo/swag. DO NOT EDIT
|
||||
package docs
|
||||
|
||||
import "github.com/swaggo/swag"
|
||||
|
||||
const docTemplate = `{
|
||||
"schemes": {{ marshal .Schemes }},
|
||||
"swagger": "2.0",
|
||||
"info": {
|
||||
"description": "{{escape .Description}}",
|
||||
"title": "{{.Title}}",
|
||||
"contact": {},
|
||||
"license": {
|
||||
"name": "AGPL",
|
||||
"url": "https://www.gnu.org/licenses/agpl-3.0.html"
|
||||
},
|
||||
"version": "{{.Version}}"
|
||||
},
|
||||
"host": "{{.Host}}",
|
||||
"basePath": "{{.BasePath}}",
|
||||
"paths": {
|
||||
"/login": {
|
||||
"post": {
|
||||
"description": "Logs in a user and returns a JWT token",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Auth"
|
||||
],
|
||||
"summary": "Login",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "User credentials",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/types.NewUser"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "JWT token",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/types.Token"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad request",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal server error",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/loginrenew": {
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"JWT": []
|
||||
}
|
||||
],
|
||||
"description": "Renews the users token.",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"Auth"
|
||||
],
|
||||
"summary": "LoginRenews",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successfully signed token for user",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/types.Token"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal server error",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/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": {
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"JWT": []
|
||||
}
|
||||
],
|
||||
"description": "Promote chosen user to site admin",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"text/plain"
|
||||
],
|
||||
"tags": [
|
||||
"User"
|
||||
],
|
||||
"summary": "PromoteToAdmin",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "user info",
|
||||
"name": "NewUser",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/types.NewUser"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successfully promoted user",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/types.Token"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad request",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal server error",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/register": {
|
||||
"post": {
|
||||
"description": "Register a new user",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"text/plain"
|
||||
],
|
||||
"tags": [
|
||||
"Auth"
|
||||
],
|
||||
"summary": "Register",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "User to register",
|
||||
"name": "NewUser",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/types.NewUser"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "User added",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad request",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal server error",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/userdelete/{username}": {
|
||||
"delete": {
|
||||
"security": [
|
||||
{
|
||||
"JWT": []
|
||||
}
|
||||
],
|
||||
"description": "UserDelete deletes a user from the database",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"text/plain"
|
||||
],
|
||||
"tags": [
|
||||
"User"
|
||||
],
|
||||
"summary": "UserDelete",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "User deleted",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"403": {
|
||||
"description": "You can only delete yourself",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal server error",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/users/all": {
|
||||
"get": {
|
||||
"security": [
|
||||
{
|
||||
"JWT": []
|
||||
}
|
||||
],
|
||||
"description": "lists all users",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"User"
|
||||
],
|
||||
"summary": "ListsAllUsers",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successfully returned all users",
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal server error",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"types.NewUser": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"password": {
|
||||
"type": "string",
|
||||
"example": "password123"
|
||||
},
|
||||
"username": {
|
||||
"type": "string",
|
||||
"example": "username123"
|
||||
}
|
||||
}
|
||||
},
|
||||
"types.Token": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"token": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"securityDefinitions": {
|
||||
"JWT": {
|
||||
"description": "Use the JWT token provided by the login endpoint to authenticate requests. **Prefix the token with \"Bearer \".**",
|
||||
"type": "apiKey",
|
||||
"name": "Authorization",
|
||||
"in": "header"
|
||||
}
|
||||
},
|
||||
"externalDocs": {
|
||||
"description": "OpenAPI",
|
||||
"url": "https://swagger.io/resources/open-api/"
|
||||
}
|
||||
}`
|
||||
|
||||
// SwaggerInfo holds exported Swagger Info so clients can modify it
|
||||
var SwaggerInfo = &swag.Spec{
|
||||
Version: "0.0.1",
|
||||
Host: "localhost:8080",
|
||||
BasePath: "/api",
|
||||
Schemes: []string{},
|
||||
Title: "TTime API",
|
||||
Description: "This is the API for TTime, a time tracking application.",
|
||||
InfoInstanceName: "swagger",
|
||||
SwaggerTemplate: docTemplate,
|
||||
LeftDelim: "{{",
|
||||
RightDelim: "}}",
|
||||
}
|
||||
|
||||
func init() {
|
||||
swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)
|
||||
}
|
|
@ -3,54 +3,8 @@ module ttime
|
|||
go 1.21.1
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.3.2
|
||||
github.com/gofiber/swagger v1.0.0
|
||||
github.com/jmoiron/sqlx v1.3.5
|
||||
github.com/swaggo/swag v1.16.3
|
||||
modernc.org/sqlite v1.29.5
|
||||
github.com/mattn/go-sqlite3 v1.14.22
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/KyleBanks/depth v1.2.1 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.21.0 // indirect
|
||||
github.com/go-openapi/jsonreference v0.21.0 // indirect
|
||||
github.com/go-openapi/spec v0.21.0 // indirect
|
||||
github.com/go-openapi/swag v0.23.0 // indirect
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/mailru/easyjson v0.7.7 // indirect
|
||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/swaggo/files/v2 v2.0.0 // indirect
|
||||
golang.org/x/tools v0.19.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
modernc.org/gc/v3 v3.0.0-20240304020402-f0dba7c97c2b // indirect
|
||||
modernc.org/libc v1.49.1 // indirect
|
||||
modernc.org/mathutil v1.6.0 // indirect
|
||||
modernc.org/memory v1.8.0 // indirect
|
||||
modernc.org/strutil v1.2.0 // indirect
|
||||
modernc.org/token v1.1.0 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/MicahParks/keyfunc/v2 v2.1.0 // indirect
|
||||
github.com/gofiber/contrib/jwt v1.0.8
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1
|
||||
)
|
||||
|
||||
// These are all for fiber
|
||||
require (
|
||||
github.com/andybalholm/brotli v1.1.0 // indirect
|
||||
github.com/gofiber/fiber/v2 v2.52.4
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/klauspost/compress v1.17.7 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.15 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasthttp v1.52.0 // indirect
|
||||
github.com/valyala/tcplisten v1.0.0 // indirect
|
||||
golang.org/x/sys v0.19.0 // indirect
|
||||
)
|
||||
require github.com/BurntSushi/toml v1.3.2 // indirect
|
||||
|
|
111
backend/go.sum
111
backend/go.sum
|
@ -1,122 +1,11 @@
|
|||
github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8=
|
||||
github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
|
||||
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
|
||||
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
|
||||
github.com/MicahParks/keyfunc/v2 v2.1.0 h1:6ZXKb9Rp6qp1bDbJefnG7cTH8yMN1IC/4nf+GVjO99k=
|
||||
github.com/MicahParks/keyfunc/v2 v2.1.0/go.mod h1:rW42fi+xgLJ2FRRXAfNx9ZA8WpD4OeE/yHVMteCkw9k=
|
||||
github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=
|
||||
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
|
||||
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
|
||||
github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ=
|
||||
github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4=
|
||||
github.com/go-openapi/spec v0.21.0 h1:LTVzPc3p/RzRnkQqLRndbAzjY0d0BCL72A6j3CdL9ZY=
|
||||
github.com/go-openapi/spec v0.21.0/go.mod h1:78u6VdPw81XU44qEWGhtr982gJ5BWg2c0I5XwVMotYk=
|
||||
github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
|
||||
github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ=
|
||||
github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
|
||||
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
|
||||
github.com/gofiber/contrib/jwt v1.0.8 h1:/GeOsm/Mr1OGr0GTy+RIVSz5VgNNyP3ZgK4wdqxF/WY=
|
||||
github.com/gofiber/contrib/jwt v1.0.8/go.mod h1:gWWBtBiLmKXRN7xy6a96QO0KGvPEyxdh8x496Ujtg84=
|
||||
github.com/gofiber/fiber/v2 v2.52.4 h1:P+T+4iK7VaqUsq2PALYEfBBo6bJZ4q3FP8cZ84EggTM=
|
||||
github.com/gofiber/fiber/v2 v2.52.4/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ=
|
||||
github.com/gofiber/swagger v1.0.0 h1:BzUzDS9ZT6fDUa692kxmfOjc1DZiloLiPK/W5z1H1tc=
|
||||
github.com/gofiber/swagger v1.0.0/go.mod h1:QrYNF1Yrc7ggGK6ATsJ6yfH/8Zi5bu9lA7wB8TmCecg=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
|
||||
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g=
|
||||
github.com/jmoiron/sqlx v1.3.5/go.mod h1:nRVWtLre0KfCLJvgxzCsLVMogSvQ1zNJtpYr2Ccp0mQ=
|
||||
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
|
||||
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
|
||||
github.com/klauspost/compress v1.17.7 h1:ehO88t2UGzQK66LMdE8tibEd1ErmzZjNEqWkjLAKQQg=
|
||||
github.com/klauspost/compress v1.17.7/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/lib/pq v1.2.0 h1:LXpIM/LZ5xGFhOpXAQUIMM1HdyqzVYM13zNdjCEEcA0=
|
||||
github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
|
||||
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
|
||||
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
|
||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
|
||||
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
|
||||
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
|
||||
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/swaggo/files/v2 v2.0.0 h1:hmAt8Dkynw7Ssz46F6pn8ok6YmGZqHSVLZ+HQM7i0kw=
|
||||
github.com/swaggo/files/v2 v2.0.0/go.mod h1:24kk2Y9NYEJ5lHuCra6iVwkMjIekMCaFq/0JQj66kyM=
|
||||
github.com/swaggo/swag v1.16.3 h1:PnCYjPCah8FK4I26l2F/KQ4yz3sILcVUN3cTlBFA9Pg=
|
||||
github.com/swaggo/swag v1.16.3/go.mod h1:DImHIuOFXKpMFAQjcC7FG4m3Dg4+QuUgUzJmKjI/gRk=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasthttp v1.52.0 h1:wqBQpxH71XW0e2g+Og4dzQM8pk34aFYlA1Ga8db7gU0=
|
||||
github.com/valyala/fasthttp v1.52.0/go.mod h1:hf5C4QnVMkNXMspnsUlfM3WitlgYflyhHYoKol/szxQ=
|
||||
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
|
||||
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
|
||||
golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
|
||||
golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
|
||||
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
|
||||
golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
modernc.org/cc/v4 v4.20.0 h1:45Or8mQfbUqJOG9WaxvlFYOAQO0lQ5RvqBcFCXngjxk=
|
||||
modernc.org/cc/v4 v4.20.0/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ=
|
||||
modernc.org/ccgo/v4 v4.15.0 h1:uwfCZOkKhaNNotgYW7kxkJwrkQC1HfGitt/7ousudJE=
|
||||
modernc.org/ccgo/v4 v4.15.0/go.mod h1:XVITcYGiI+O97UNDLMsnZ9ZjJOhC+ACX+TfxpsWWyRc=
|
||||
modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
|
||||
modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=
|
||||
modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw=
|
||||
modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU=
|
||||
modernc.org/gc/v3 v3.0.0-20240304020402-f0dba7c97c2b h1:BnN1t+pb1cy61zbvSUV7SeI0PwosMhlAEi/vBY4qxp8=
|
||||
modernc.org/gc/v3 v3.0.0-20240304020402-f0dba7c97c2b/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4=
|
||||
modernc.org/libc v1.49.1 h1:r4UaWllkYXRPA7Mq/KzmassZBvNJiH9egF4O/KV/gdE=
|
||||
modernc.org/libc v1.49.1/go.mod h1:Hx2rWfza47GSzCluTU7Vf0Qx3z9rWCVORL6RNgq+Xog=
|
||||
modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
|
||||
modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
|
||||
modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E=
|
||||
modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU=
|
||||
modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
|
||||
modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
|
||||
modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc=
|
||||
modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss=
|
||||
modernc.org/sqlite v1.29.5 h1:8l/SQKAjDtZFo9lkJLdk8g9JEOeYRG4/ghStDCCTiTE=
|
||||
modernc.org/sqlite v1.29.5/go.mod h1:S02dvcmm7TnTRvGhv8IGYyLnIt7AS2KPaB1F/71p75U=
|
||||
modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=
|
||||
modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
|
|
|
@ -22,7 +22,7 @@ type Config struct {
|
|||
}
|
||||
|
||||
// WriteConfigToFile writes a Config to a file
|
||||
func (c *Config) WriteConfigToFile(filename string) error {
|
||||
func WriteConfigToFile(c *Config, filename string) error {
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
|
@ -5,12 +5,8 @@ import (
|
|||
"testing"
|
||||
)
|
||||
|
||||
// TestNewConfig tests the creation of a new configuration object
|
||||
func TestNewConfig(t *testing.T) {
|
||||
// Arrange
|
||||
c := NewConfig()
|
||||
|
||||
// Act & Assert
|
||||
if c.Port != 8080 {
|
||||
t.Errorf("Expected port to be 8080, got %d", c.Port)
|
||||
}
|
||||
|
@ -28,15 +24,9 @@ func TestNewConfig(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestWriteConfig tests the function to write the configuration to a file
|
||||
func TestWriteConfig(t *testing.T) {
|
||||
// Arrange
|
||||
c := NewConfig()
|
||||
|
||||
//Act
|
||||
err := c.WriteConfigToFile("test.toml")
|
||||
|
||||
// Assert
|
||||
err := WriteConfigToFile(c, "test.toml")
|
||||
if err != nil {
|
||||
t.Errorf("Expected no error, got %s", err)
|
||||
}
|
||||
|
@ -45,23 +35,14 @@ func TestWriteConfig(t *testing.T) {
|
|||
_ = os.Remove("test.toml")
|
||||
}
|
||||
|
||||
// TestReadConfig tests the function to read the configuration from a file
|
||||
func TestReadConfig(t *testing.T) {
|
||||
// Arrange
|
||||
c := NewConfig()
|
||||
|
||||
// Act
|
||||
err := c.WriteConfigToFile("test.toml")
|
||||
|
||||
// Assert
|
||||
err := WriteConfigToFile(c, "test.toml")
|
||||
if err != nil {
|
||||
t.Errorf("Expected no error, got %s", err)
|
||||
}
|
||||
|
||||
// Act
|
||||
c2, err := ReadConfigFromFile("test.toml")
|
||||
|
||||
// Assert
|
||||
if err != nil {
|
||||
t.Errorf("Expected no error, got %s", err)
|
||||
}
|
||||
|
|
|
@ -1,685 +1,32 @@
|
|||
package database
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"ttime/internal/types"
|
||||
"os"
|
||||
|
||||
"github.com/gofiber/fiber/v2/log"
|
||||
"github.com/jmoiron/sqlx"
|
||||
_ "modernc.org/sqlite"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
// Interface for the database
|
||||
type Database interface {
|
||||
// Insert a new user into the database, password should be hashed before calling
|
||||
AddUser(username string, password string) error
|
||||
CheckUser(username string, password string) bool
|
||||
RemoveUser(username string) error
|
||||
RemoveUserFromProject(username string, projectname string) error
|
||||
PromoteToAdmin(username string) error
|
||||
GetUserId(username string) (int, error)
|
||||
AddProject(name string, description string, username string) error
|
||||
DeleteProject(name string, username string) error
|
||||
GetProjectId(projectname string) (int, 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
|
||||
ChangeUserRole(username string, projectname string, role string) error
|
||||
ChangeUserName(username string, newname string) error
|
||||
GetAllUsersProject(projectname string) ([]UserProjectMember, error)
|
||||
GetAllUsersApplication() ([]string, error)
|
||||
GetProjectsForUser(username string) ([]types.Project, error)
|
||||
GetAllProjects() ([]types.Project, error)
|
||||
GetProject(projectId int) (types.Project, error)
|
||||
GetUserRole(username string, projectname string) (string, error)
|
||||
GetWeeklyReport(username string, projectName string, week int) (types.WeeklyReport, error)
|
||||
GetAllWeeklyReports(username string, projectname string) ([]types.WeeklyReportList, error)
|
||||
GetUnsignedWeeklyReports(projectName string) ([]types.WeeklyReport, error)
|
||||
SignWeeklyReport(reportId int, projectManagerId int) error
|
||||
IsSiteAdmin(username string) (bool, error)
|
||||
IsProjectManager(username string, projectname string) (bool, error)
|
||||
ReportStatistics(username string, projectName string) (*types.Statistics, 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
|
||||
RemoveProject(projectname string) error
|
||||
GetUserName(id int) (string, error)
|
||||
UnsignWeeklyReport(reportId int, projectManagerId int) error
|
||||
DeleteReport(reportID int) error
|
||||
ChangeProjectName(projectName string, newProjectName string) error
|
||||
ChangeUserPassword(username string, password string) error
|
||||
}
|
||||
func DbConnect() *sqlx.DB {
|
||||
// Check for the environment variable
|
||||
dbpath := os.Getenv("SQLITE_DB_PATH")
|
||||
|
||||
// This struct is a wrapper type that holds the database connection
|
||||
// Internally DB holds a connection pool, so it's safe for concurrent use
|
||||
type Db struct {
|
||||
*sqlx.Tx
|
||||
}
|
||||
// Default to something reasonable
|
||||
if dbpath == "" {
|
||||
dbpath = "./db.sqlite3"
|
||||
}
|
||||
|
||||
type UserProjectMember struct {
|
||||
Username string `db:"username"`
|
||||
UserRole string `db:"p_role"`
|
||||
}
|
||||
|
||||
//go:embed migrations
|
||||
var scripts embed.FS
|
||||
|
||||
//go:embed sample_data
|
||||
var sampleData embed.FS
|
||||
|
||||
// TODO: Possibly break these out into separate files bundled with the embed package?
|
||||
const userInsert = "INSERT INTO users (username, password) VALUES (?, ?)"
|
||||
const projectInsert = "INSERT INTO projects (name, description, owner_user_id) VALUES (?, ?, (SELECT id FROM users WHERE username = ?))"
|
||||
const promoteToAdmin = "INSERT INTO site_admin (admin_id) 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 = ?)
|
||||
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),?, ?, ?, ?, ?, ?, ?);`
|
||||
const addUserToProject = `INSERT OR IGNORE INTO user_roles (user_id, project_id, p_role)
|
||||
VALUES ((SELECT id FROM users WHERE username = ?),
|
||||
(SELECT id FROM projects WHERE name = ?), ?)`
|
||||
const changeUserRole = "UPDATE user_roles SET p_role = ? WHERE user_id = (SELECT id FROM users WHERE username = ?) AND project_id = (SELECT id FROM projects WHERE name = ?)"
|
||||
const getProjectsForUser = `SELECT p.id, p.name, p.description FROM projects p
|
||||
JOIN user_roles ur ON p.id = ur.project_id
|
||||
JOIN users u ON ur.user_id = u.id
|
||||
WHERE u.username = ?`
|
||||
const deleteProject = `DELETE FROM projects
|
||||
WHERE id = ? AND owner_username = ?`
|
||||
|
||||
const isProjectManagerQuery = `SELECT COUNT(*) > 0 FROM user_roles
|
||||
JOIN users ON user_roles.user_id = users.id
|
||||
JOIN projects ON user_roles.project_id = projects.id
|
||||
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 = ?)`
|
||||
|
||||
const reportStatistics = `SELECT SUM(development_time) AS total_development_time,
|
||||
SUM(meeting_time) AS total_meeting_time,
|
||||
SUM(admin_time) AS total_admin_time,
|
||||
SUM(own_work_time) AS total_own_work_time,
|
||||
SUM(study_time) AS total_study_time,
|
||||
SUM(testing_time) AS total_testing_time
|
||||
FROM weekly_reports
|
||||
WHERE user_id = (SELECT id FROM users WHERE username = ?)
|
||||
AND project_id = (SELECT id FROM projects WHERE name = ?)
|
||||
GROUP BY user_id, project_id`
|
||||
|
||||
// DbConnect connects to the database
|
||||
func DbConnect(dbpath string) sqlx.DB {
|
||||
// Open the database
|
||||
db, err := sqlx.Connect("sqlite", dbpath)
|
||||
// db, err := sqlx.Connect("sqlite3", ":memory:")
|
||||
db, err := sqlx.Connect("sqlite3", dbpath)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Ping forces the connection to be established
|
||||
err = db.Ping()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return *db
|
||||
}
|
||||
|
||||
func (d *Db) ReportStatistics(username string, projectName string) (*types.Statistics, error) {
|
||||
var result types.Statistics
|
||||
|
||||
err := d.Get(&result, reportStatistics, username, projectName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
serialized, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.Info(string(serialized))
|
||||
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
func (d *Db) CheckUser(username string, password string) bool {
|
||||
var dbPassword string
|
||||
err := d.Get(&dbPassword, "SELECT password FROM users WHERE username = ?", username)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return dbPassword == password
|
||||
}
|
||||
|
||||
// GetProjectsForUser retrieves all projects associated with a specific user.
|
||||
func (d *Db) GetProjectsForUser(username string) ([]types.Project, error) {
|
||||
var projects []types.Project
|
||||
err := d.Select(&projects, getProjectsForUser, username)
|
||||
return projects, err
|
||||
}
|
||||
|
||||
// GetAllProjects retrieves all projects from the database.
|
||||
func (d *Db) GetAllProjects() ([]types.Project, error) {
|
||||
var projects []types.Project
|
||||
err := d.Select(&projects, "SELECT * FROM projects")
|
||||
return projects, err
|
||||
}
|
||||
|
||||
// GetProject retrieves a specific project by its ID.
|
||||
func (d *Db) GetProject(projectId int) (types.Project, error) {
|
||||
var project types.Project
|
||||
err := d.Get(&project, "SELECT * FROM projects WHERE id = ?", projectId)
|
||||
if err != nil {
|
||||
println("Error getting project: ", err)
|
||||
}
|
||||
return project, err
|
||||
}
|
||||
|
||||
func (d *Db) AddWeeklyReport(projectName string, userName string, week int, developmentTime int, meetingTime int, adminTime int, ownWorkTime int, studyTime int, testingTime int) error {
|
||||
_, err := d.Exec(addWeeklyReport, userName, projectName, week, developmentTime, meetingTime, adminTime, ownWorkTime, studyTime, testingTime)
|
||||
return err
|
||||
}
|
||||
|
||||
// AddUserToProject adds a user to a project with a specified role.
|
||||
func (d *Db) AddUserToProject(username string, projectname string, role string) error {
|
||||
_, err := d.Exec(addUserToProject, username, projectname, role)
|
||||
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.
|
||||
func (d *Db) ChangeUserRole(username string, projectname string, role string) error {
|
||||
// Execute the SQL query to change the user's role
|
||||
_, err := d.Exec(changeUserRole, role, username, projectname)
|
||||
return err
|
||||
}
|
||||
|
||||
// ChangeUserName changes the username of a user.
|
||||
func (d *Db) ChangeUserName(username string, newname string) error {
|
||||
// Execute the SQL query to update the username
|
||||
_, err := d.Exec("UPDATE users SET username = ? WHERE username = ?", newname, username)
|
||||
return err
|
||||
}
|
||||
|
||||
// GetUserRole retrieves the role of a user within a project.
|
||||
func (d *Db) GetUserRole(username string, projectname string) (string, error) {
|
||||
var role string
|
||||
err := d.Get(&role, "SELECT p_role FROM user_roles WHERE user_id = (SELECT id FROM users WHERE username = ?) AND project_id = (SELECT id FROM projects WHERE name = ?)", username, projectname)
|
||||
return role, err
|
||||
}
|
||||
|
||||
// AddUser adds a user to the database
|
||||
func (d *Db) AddUser(username string, password string) error {
|
||||
_, err := d.Exec(userInsert, username, password)
|
||||
return err
|
||||
}
|
||||
|
||||
// Removes a user from the database
|
||||
func (d *Db) RemoveUser(username string) error {
|
||||
_, err := d.Exec("DELETE FROM users WHERE username = ?", username)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *Db) PromoteToAdmin(username string) error {
|
||||
_, err := d.Exec(promoteToAdmin, username)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *Db) GetUserId(username string) (int, error) {
|
||||
var id int
|
||||
err := d.Get(&id, "SELECT id FROM users WHERE username = ?", username) // Borde det inte vara "user" i singular
|
||||
return id, err
|
||||
}
|
||||
|
||||
func (d *Db) GetProjectId(projectname string) (int, error) {
|
||||
var id int
|
||||
err := d.Get(&id, "SELECT id FROM projects WHERE name = ?", projectname)
|
||||
return id, err
|
||||
}
|
||||
|
||||
// Creates a new project in the database, associated with a user
|
||||
func (d *Db) AddProject(name string, description string, username string) error {
|
||||
// Insert the project into the database
|
||||
_, err := d.Exec(projectInsert, name, description, username)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Add creator to project as project manager
|
||||
_, err = d.Exec(addUserToProject, username, name, "project_manager")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *Db) DeleteProject(projectID string, username string) error {
|
||||
_, err := d.Exec(deleteProject, projectID, username)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *Db) GetAllUsersProject(projectname string) ([]UserProjectMember, error) {
|
||||
// Define the SQL query to fetch users and their roles for a given project
|
||||
query := `
|
||||
SELECT u.username, ur.p_role
|
||||
FROM users u
|
||||
INNER JOIN user_roles ur ON u.id = ur.user_id
|
||||
INNER JOIN projects p ON ur.project_id = p.id
|
||||
WHERE p.name = ?
|
||||
`
|
||||
|
||||
// Execute the query
|
||||
rows, err := d.Queryx(query, projectname)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
// Iterate over the rows and populate the result slice
|
||||
var users []UserProjectMember
|
||||
for rows.Next() {
|
||||
var user UserProjectMember
|
||||
if err := rows.StructScan(&user); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
users = append(users, user)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// GetAllUsersApplication retrieves all usernames from the database
|
||||
func (d *Db) GetAllUsersApplication() ([]string, error) {
|
||||
// Define the SQL query to fetch all usernames
|
||||
query := `
|
||||
SELECT username FROM users
|
||||
`
|
||||
|
||||
// Execute the query
|
||||
rows, err := d.Queryx(query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
// Iterate over the rows and populate the result slice
|
||||
var usernames []string
|
||||
for rows.Next() {
|
||||
var username string
|
||||
if err := rows.Scan(&username); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
usernames = append(usernames, username)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return usernames, nil
|
||||
}
|
||||
|
||||
func (d *Db) GetWeeklyReport(username string, projectName string, week int) (types.WeeklyReport, error) {
|
||||
var report types.WeeklyReport
|
||||
query := `
|
||||
SELECT
|
||||
report_id,
|
||||
user_id,
|
||||
project_id,
|
||||
week,
|
||||
development_time,
|
||||
meeting_time,
|
||||
admin_time,
|
||||
own_work_time,
|
||||
study_time,
|
||||
testing_time,
|
||||
signed_by
|
||||
FROM
|
||||
weekly_reports
|
||||
WHERE
|
||||
user_id = (SELECT id FROM users WHERE username = ?)
|
||||
AND project_id = (SELECT id FROM projects WHERE name = ?)
|
||||
AND week = ?
|
||||
`
|
||||
err := d.Get(&report, query, username, projectName, week)
|
||||
return report, err
|
||||
}
|
||||
|
||||
// SignWeeklyReport signs a weekly report by updating the signed_by field
|
||||
// with the provided project manager's ID, but only if the project manager
|
||||
// is in the same project as the report
|
||||
func (d *Db) SignWeeklyReport(reportId int, projectManagerId int) error {
|
||||
// Retrieve the project ID associated with the report
|
||||
var reportProjectID int
|
||||
err := d.Get(&reportProjectID, "SELECT project_id FROM weekly_reports WHERE report_id = ?", reportId)
|
||||
if err != nil {
|
||||
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
|
||||
var managerProjectID int
|
||||
err = d.Get(&managerProjectID, managerQuery, projectManagerId, reportId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Check if the project manager is in the same project as the report
|
||||
if reportProjectID != managerProjectID {
|
||||
return errors.New("project manager doesn't have permission to sign the report")
|
||||
}
|
||||
|
||||
// Update the signed_by field of the specified report
|
||||
_, err = d.Exec("UPDATE weekly_reports SET signed_by = ? WHERE report_id = ?", projectManagerId, reportId)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *Db) UnsignWeeklyReport(reportId int, projectManagerId int) error {
|
||||
// Retrieve the project ID associated with the report
|
||||
var reportProjectID int
|
||||
err := d.Get(&reportProjectID, "SELECT project_id FROM weekly_reports WHERE report_id = ?", reportId)
|
||||
if err != nil {
|
||||
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
|
||||
var managerProjectID int
|
||||
err = d.Get(&managerProjectID, managerQuery, projectManagerId, reportId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Check if the project manager is in the same project as the report
|
||||
if reportProjectID != managerProjectID {
|
||||
return errors.New("project manager doesn't have permission to unsign the report")
|
||||
}
|
||||
|
||||
// Update the signed_by field of the specified report
|
||||
_, err = d.Exec("UPDATE weekly_reports SET signed_by = NULL WHERE report_id = ?;", reportId)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *Db) GetUnsignedWeeklyReports(projectName string) ([]types.WeeklyReport, error) {
|
||||
// Define the SQL query to fetch unsigned reports for a given user
|
||||
query := `
|
||||
SELECT
|
||||
report_id,
|
||||
user_id,
|
||||
project_id,
|
||||
week,
|
||||
development_time,
|
||||
meeting_time,
|
||||
admin_time,
|
||||
own_work_time,
|
||||
study_time,
|
||||
testing_time,
|
||||
signed_by
|
||||
FROM
|
||||
weekly_reports
|
||||
WHERE
|
||||
signed_by IS NULL
|
||||
AND project_id = (SELECT id FROM projects WHERE name = ?)
|
||||
`
|
||||
|
||||
// Execute the query
|
||||
rows, err := d.Queryx(query, projectName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
// Iterate over the rows and populate the result slice
|
||||
var reports []types.WeeklyReport
|
||||
for rows.Next() {
|
||||
var report types.WeeklyReport
|
||||
if err := rows.StructScan(&report); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reports = append(reports, report)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return reports, nil
|
||||
}
|
||||
|
||||
// IsSiteAdmin checks if a given username is a site admin
|
||||
func (d *Db) IsSiteAdmin(username string) (bool, error) {
|
||||
// Define the SQL query to check if the user is a site admin
|
||||
query := `
|
||||
SELECT COUNT(*) FROM site_admin
|
||||
JOIN users ON site_admin.admin_id = users.id
|
||||
WHERE users.username = ?
|
||||
`
|
||||
|
||||
// Execute the query
|
||||
var count int
|
||||
err := d.Get(&count, query, username)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// If count is greater than 0, the user is a site admin
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
// Reads a directory of migration files and applies them to the database.
|
||||
// This will eventually be used on an embedded directory
|
||||
func Migrate(db sqlx.DB) error {
|
||||
// Read the embedded scripts directory
|
||||
files, err := scripts.ReadDir("migrations")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(files) == 0 {
|
||||
println("No migration files found")
|
||||
return nil
|
||||
}
|
||||
|
||||
tr := db.MustBegin()
|
||||
|
||||
// Iterate over each SQL file and execute it
|
||||
for _, file := range files {
|
||||
if file.IsDir() || filepath.Ext(file.Name()) != ".sql" {
|
||||
continue
|
||||
}
|
||||
|
||||
// This is perhaps not the most elegant way to do this
|
||||
sqlBytes, err := scripts.ReadFile("migrations/" + file.Name())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
sqlQuery := string(sqlBytes)
|
||||
_, err = tr.Exec(sqlQuery)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if tr.Commit() != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAllWeeklyReports retrieves weekly reports for a specific user and project.
|
||||
func (d *Db) GetAllWeeklyReports(username string, projectName string) ([]types.WeeklyReportList, error) {
|
||||
query := `
|
||||
SELECT
|
||||
wr.week,
|
||||
wr.development_time,
|
||||
wr.meeting_time,
|
||||
wr.admin_time,
|
||||
wr.own_work_time,
|
||||
wr.study_time,
|
||||
wr.testing_time,
|
||||
wr.signed_by
|
||||
FROM
|
||||
weekly_reports wr
|
||||
INNER JOIN
|
||||
users u ON wr.user_id = u.id
|
||||
INNER JOIN
|
||||
projects p ON wr.project_id = p.id
|
||||
WHERE
|
||||
u.username = ? AND p.name = ?
|
||||
`
|
||||
|
||||
var reports []types.WeeklyReportList
|
||||
if err := d.Select(&reports, query, username, projectName); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return reports, nil
|
||||
}
|
||||
|
||||
// IsProjectManager checks if a given username is a project manager for the specified project
|
||||
func (d *Db) IsProjectManager(username string, projectname string) (bool, error) {
|
||||
var manager bool
|
||||
err := d.Get(&manager, isProjectManagerQuery, username, projectname)
|
||||
return manager, err
|
||||
}
|
||||
|
||||
func (d *Db) UpdateWeeklyReport(projectName string, userName string, week int, developmentTime int, meetingTime int, adminTime int, ownWorkTime int, studyTime int, testingTime int) error {
|
||||
query := `
|
||||
UPDATE weekly_reports
|
||||
SET
|
||||
development_time = ?,
|
||||
meeting_time = ?,
|
||||
admin_time = ?,
|
||||
own_work_time = ?,
|
||||
study_time = ?,
|
||||
testing_time = ?
|
||||
WHERE
|
||||
user_id = (SELECT id FROM users WHERE username = ?)
|
||||
AND project_id = (SELECT id FROM projects WHERE name = ?)
|
||||
AND week = ?
|
||||
`
|
||||
|
||||
_, err := d.Exec(query, developmentTime, meetingTime, adminTime, ownWorkTime, studyTime, testingTime, userName, projectName, week)
|
||||
return err
|
||||
}
|
||||
|
||||
// MigrateSampleData applies sample data to the database.
|
||||
func MigrateSampleData(db sqlx.DB) error {
|
||||
// Insert sample data
|
||||
files, err := sampleData.ReadDir("sample_data")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(files) == 0 {
|
||||
println("No sample data files found")
|
||||
}
|
||||
tr := db.MustBegin()
|
||||
|
||||
// Iterate over each SQL file and execute it
|
||||
for _, file := range files {
|
||||
if file.IsDir() || filepath.Ext(file.Name()) != ".sql" {
|
||||
continue
|
||||
}
|
||||
|
||||
// This is perhaps not the most elegant way to do this
|
||||
sqlBytes, err := sampleData.ReadFile("sample_data/" + file.Name())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
sqlQuery := string(sqlBytes)
|
||||
_, err = tr.Exec(sqlQuery)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if tr.Commit() != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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
|
||||
JOIN projects ON weekly_reports.project_id = projects.id
|
||||
WHERE projects.name = ?
|
||||
`
|
||||
|
||||
rows, err := d.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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
return totalTime, nil
|
||||
}
|
||||
|
||||
func (d *Db) RemoveProject(projectname string) error {
|
||||
_, err := d.Exec("DELETE FROM projects WHERE name = ?", projectname)
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func (d *Db) ChangeUserPassword(username string, password string) error {
|
||||
_, err := d.Exec("UPDATE users SET password = ? WHERE username = ?", password, username)
|
||||
return err
|
||||
return db
|
||||
}
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -1,34 +0,0 @@
|
|||
package database
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/log"
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
// Simple middleware that provides a transaction as a local key "db"
|
||||
func DbMiddleware(db *sqlx.DB) func(c *fiber.Ctx) error {
|
||||
return func(c *fiber.Ctx) error {
|
||||
tx := db.MustBegin()
|
||||
|
||||
defer func() {
|
||||
if err := tx.Commit(); err != nil {
|
||||
if err = tx.Rollback(); err != nil {
|
||||
log.Error("Failed to rollback transaction: ", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
var db_iface Database = &Db{tx}
|
||||
|
||||
c.Locals("db", &db_iface)
|
||||
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)
|
||||
}
|
|
@ -1,12 +0,0 @@
|
|||
-- Id is a surrogate key for in ternal use
|
||||
-- userId is what is used for external id
|
||||
-- username is what is used for login
|
||||
-- password is the hashed password
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username VARCHAR(255) NOT NULL UNIQUE,
|
||||
password VARCHAR(255) NOT NULL
|
||||
);
|
||||
|
||||
-- Users are commonly searched by username and userId
|
||||
CREATE INDEX IF NOT EXISTS users_username_index ON users (username);
|
|
@ -1,9 +0,0 @@
|
|||
CREATE TABLE IF NOT EXISTS projects (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name VARCHAR(255) NOT NULL UNIQUE,
|
||||
description TEXT NOT NULL,
|
||||
owner_user_id INTEGER NOT NULL,
|
||||
FOREIGN KEY (owner_user_id) REFERENCES users (id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS projects_user_id_index ON projects (owner_user_id);
|
|
@ -1,17 +0,0 @@
|
|||
CREATE TABLE IF NOT EXISTS weekly_reports (
|
||||
report_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
project_id INTEGER NOT NULL,
|
||||
week INTEGER NOT NULL,
|
||||
development_time INTEGER,
|
||||
meeting_time INTEGER,
|
||||
admin_time INTEGER,
|
||||
own_work_time INTEGER,
|
||||
study_time INTEGER,
|
||||
testing_time INTEGER,
|
||||
signed_by INTEGER,
|
||||
UNIQUE(user_id, project_id, week),
|
||||
FOREIGN KEY (user_id) REFERENCES users(id),
|
||||
FOREIGN KEY (project_id) REFERENCES projects(id),
|
||||
FOREIGN KEY (signed_by) REFERENCES users(id)
|
||||
);
|
|
@ -1,9 +0,0 @@
|
|||
-- This table represents the possible role a user can have in a project.
|
||||
-- It has nothing to do with the site admin table.
|
||||
CREATE TABLE IF NOT EXISTS project_role (
|
||||
p_role TEXT PRIMARY KEY
|
||||
);
|
||||
|
||||
-- Insert the possible roles a user can have in a project.
|
||||
INSERT OR IGNORE INTO project_role (p_role) VALUES ('project_manager');
|
||||
INSERT OR IGNORE INTO project_role (p_role) VALUES ('member');
|
|
@ -1,9 +0,0 @@
|
|||
CREATE TABLE IF NOT EXISTS user_roles (
|
||||
user_id INTEGER NOT NULL,
|
||||
project_id INTEGER NOT NULL,
|
||||
p_role TEXT NOT NULL, -- 'project_manager' or 'member'
|
||||
FOREIGN KEY (user_id) REFERENCES users (id)
|
||||
FOREIGN KEY (project_id) REFERENCES projects (id)
|
||||
FOREIGN KEY (p_role) REFERENCES project_role (p_role)
|
||||
PRIMARY KEY (user_id, project_id)
|
||||
);
|
|
@ -1,4 +0,0 @@
|
|||
CREATE TABLE IF NOT EXISTS site_admin (
|
||||
admin_id INTEGER PRIMARY KEY,
|
||||
FOREIGN KEY (admin_id) REFERENCES users (id) ON DELETE CASCADE
|
||||
)
|
|
@ -1,15 +0,0 @@
|
|||
# Database migrations
|
||||
|
||||
This directory contains all the database migrations for the backend.
|
||||
|
||||
[!WARNING]
|
||||
Keep in mind that these migrations are **not yet stable**.
|
||||
In practice, this means that the database schema may change at any time, and that the migrations may not be backwards compatible.
|
||||
|
||||
## Running migrations
|
||||
|
||||
In the root of the backend directory, run:
|
||||
|
||||
```bash
|
||||
make migrate
|
||||
```
|
|
@ -1,220 +0,0 @@
|
|||
INSERT OR IGNORE INTO users(username, password)
|
||||
VALUES ("admin", "123"),
|
||||
("user", "123"),
|
||||
("user2", "123"),
|
||||
("John", "123"),
|
||||
("Emma", "123"),
|
||||
("Michael", "123"),
|
||||
("Liam", "123"),
|
||||
("Oliver", "123"),
|
||||
("Amelia", "123"),
|
||||
("Benjamin", "123"),
|
||||
("Mia", "123"),
|
||||
("Elijah", "123"),
|
||||
("Charlotte", "123"),
|
||||
("Henry", "123"),
|
||||
("Harper", "123"),
|
||||
("Lucas", "123"),
|
||||
("Emily", "123"),
|
||||
("Alexander", "123"),
|
||||
("Daniel", "123"),
|
||||
("Ella", "123"),
|
||||
("Matthew", "123"),
|
||||
("Madison", "123"),
|
||||
("Samuel", "123"),
|
||||
("Avery", "123"),
|
||||
("Sofia", "123"),
|
||||
("David", "123"),
|
||||
("Victoria", "123"),
|
||||
("Jackson", "123"),
|
||||
("Abigail", "123"),
|
||||
("Gabriel", "123"),
|
||||
("Luna", "123"),
|
||||
("Wyatt", "123"),
|
||||
("Chloe", "123"),
|
||||
("Nora", "123"),
|
||||
("Joshua", "123"),
|
||||
("Hazel", "123"),
|
||||
("Riley", "123"),
|
||||
("Scarlett", "123"),
|
||||
("Aria", "123"),
|
||||
("Carter", "123"),
|
||||
("Grace", "123"),
|
||||
("Jayden", "123"),
|
||||
("Hannah", "123"),
|
||||
("Zoe", "123"),
|
||||
("Luke", "123"),
|
||||
("Sophia", "123"),
|
||||
("Jack", "123"),
|
||||
("Isabella", "123"),
|
||||
("William", "123"),
|
||||
("Mason", "123"),
|
||||
("Evelyn", "123"),
|
||||
("James", "123"),
|
||||
("Cynthia", "123"),
|
||||
("Abraham", "123"),
|
||||
("Ava", "123"),
|
||||
("Aiden", "123"),
|
||||
("Natalie", "123"),
|
||||
("Lily", "123"),
|
||||
("Olivia", "123"),
|
||||
("Alexander", "123"),
|
||||
("Ethan", "123"),
|
||||
("Mila", "123"),
|
||||
("Evelyn", "123"),
|
||||
("Logan", "123"),
|
||||
("Riley", "123"),
|
||||
("Grace", "123"),
|
||||
("Arnold", "123"),
|
||||
("Connor", "123"),
|
||||
("Samantha", "123"),
|
||||
("Emma", "123"),
|
||||
("Sarah", "123"),
|
||||
("Nathan", "123"),
|
||||
("Layla", "123"),
|
||||
("Ryan", "123"),
|
||||
("Zoey", "123"),
|
||||
("Megan", "123"),
|
||||
("Christian", "123"),
|
||||
("Eva", "123"),
|
||||
("Isaac", "123"),
|
||||
("Michaela", "123"),
|
||||
("Caroline", "123"),
|
||||
("Elijah", "123"),
|
||||
("Elena", "123"),
|
||||
("Julian", "123"),
|
||||
("Sophie", "123"),
|
||||
("Gabriella", "123"),
|
||||
("Cole", "123"),
|
||||
("Hannah", "123"),
|
||||
("Lucy", "123"),
|
||||
("Katherine", "123"),
|
||||
("Benjamin", "123"),
|
||||
("Ella", "123"),
|
||||
("Evan", "123");
|
||||
|
||||
INSERT OR IGNORE INTO projects(name, description, owner_user_id)
|
||||
VALUES ("projecttest1", "Description for projecttest1", 1),
|
||||
("projecttest2", "Description for projecttest2", 1),
|
||||
("projecttest3", "Description for projecttest3", 1),
|
||||
("projecttest4", "Description for projecttest4", 1),
|
||||
("projecttest5", "Description for projecttest5", 1),
|
||||
("projecttest6", "Description for projecttest6", 1),
|
||||
("projecttest7", "Description for projecttest7", 1),
|
||||
("projecttest8", "Description for projecttest8", 1),
|
||||
("projecttest9", "Description for projecttest9", 1),
|
||||
("projecttest10", "Description for projecttest10", 1),
|
||||
("projecttest11", "Description for projecttest11", 1),
|
||||
("projecttest12", "Description for projecttest12", 1),
|
||||
("projecttest13", "Description for projecttest13", 1),
|
||||
("projecttest14", "Description for projecttest14", 1),
|
||||
("projecttest15", "Description for projecttest15", 1);
|
||||
|
||||
INSERT OR IGNORE INTO user_roles(user_id,project_id,p_role)
|
||||
VALUES (1,1,"project_manager"),
|
||||
(1,2,"project_manager"),
|
||||
(1,3,"project_manager"),
|
||||
(1,4,"project_manager"),
|
||||
(1,5,"project_manager"),
|
||||
(1,6,"project_manager"),
|
||||
(1,7,"project_manager"),
|
||||
(1,8,"project_manager"),
|
||||
(1,9,"project_manager"),
|
||||
(1,10,"project_manager"),
|
||||
(1,11,"project_manager"),
|
||||
(1,12,"project_manager"),
|
||||
(1,13,"project_manager"),
|
||||
(1,14,"project_manager"),
|
||||
(1,15,"project_manager"),
|
||||
(2,1,"project_manager"),
|
||||
(2,2,"member"),
|
||||
(2,3,"member"),
|
||||
(2,4,"member"),
|
||||
(2,5,"member"),
|
||||
(2,6,"member"),
|
||||
(2,7,"member"),
|
||||
(2,8,"member"),
|
||||
(2,9,"member"),
|
||||
(2,10,"member"),
|
||||
(2,11,"member"),
|
||||
(2,12,"member"),
|
||||
(2,13,"member"),
|
||||
(2,14,"member"),
|
||||
(2,15,"member"),
|
||||
(3,1,"member"),
|
||||
(3,2,"member"),
|
||||
(3,3,"member"),
|
||||
(3,4,"member"),
|
||||
(3,5,"member"),
|
||||
(3,6,"member"),
|
||||
(3,7,"member"),
|
||||
(3,8,"member"),
|
||||
(3,9,"member"),
|
||||
(3,10,"member"),
|
||||
(3,11,"member"),
|
||||
(3,12,"member"),
|
||||
(3,13,"member"),
|
||||
(3,14,"member"),
|
||||
(3,15,"member"),
|
||||
(4,1,"member"),
|
||||
(4,2,"member"),
|
||||
(4,3,"member"),
|
||||
(4,4,"member"),
|
||||
(4,5,"member"),
|
||||
(4,6,"member"),
|
||||
(4,7,"member"),
|
||||
(4,8,"member"),
|
||||
(4,9,"member"),
|
||||
(4,10,"member"),
|
||||
(4,11,"member"),
|
||||
(4,12,"member"),
|
||||
(4,13,"member"),
|
||||
(4,14,"member"),
|
||||
(4,15,"member"),
|
||||
(5,1,"member"),
|
||||
(5,2,"member"),
|
||||
(5,3,"member"),
|
||||
(5,4,"member"),
|
||||
(5,5,"member"),
|
||||
(5,6,"member"),
|
||||
(5,7,"member"),
|
||||
(5,8,"member"),
|
||||
(5,9,"member"),
|
||||
(5,10,"member"),
|
||||
(5,11,"member"),
|
||||
(5,12,"member"),
|
||||
(5,13,"member"),
|
||||
(5,14,"member"),
|
||||
(5,15,"member");
|
||||
|
||||
INSERT OR IGNORE INTO weekly_reports (user_id, project_id, week, development_time, meeting_time, admin_time, own_work_time, study_time, testing_time, signed_by)
|
||||
VALUES (2, 1, 12, 100, 50, 30, 150, 80, 20, NULL),
|
||||
(3, 1, 12, 200, 80, 20, 200, 100, 30, NULL),
|
||||
(3, 1, 14, 150, 70, 40, 180, 90, 25, NULL),
|
||||
(3, 2, 12, 120, 60, 35, 160, 85, 15, NULL),
|
||||
(3, 3, 12, 180, 90, 25, 190, 110, 40, NULL),
|
||||
(2, 1, 13, 130, 70, 40, 170, 95, 35, NULL),
|
||||
(3, 1, 15, 140, 60, 50, 200, 120, 30, NULL),
|
||||
(2, 2, 11, 110, 50, 45, 140, 70, 25, NULL),
|
||||
(3, 3, 14, 170, 80, 30, 180, 100, 35, NULL),
|
||||
(3, 3, 15, 200, 100, 20, 220, 130, 45, NULL),
|
||||
(2, 4, 12, 120, 60, 40, 160, 80, 30, NULL),
|
||||
(3, 5, 14, 150, 70, 30, 180, 90, 25, NULL),
|
||||
(3, 5, 15, 180, 90, 20, 190, 110, 35, NULL),
|
||||
(2, 6, 11, 100, 50, 35, 130, 60, 20, NULL),
|
||||
(3, 7, 14, 170, 80, 25, 180, 100, 30, NULL),
|
||||
(2, 8, 12, 130, 70, 30, 170, 90, 25, NULL),
|
||||
(2, 8, 13, 150, 80, 20, 180, 110, 35, NULL),
|
||||
(3, 9, 12, 140, 60, 40, 180, 100, 30, NULL),
|
||||
(3, 10, 11, 120, 50, 45, 150, 70, 25, NULL),
|
||||
(2, 11, 13, 110, 60, 35, 140, 80, 30, NULL),
|
||||
(3, 12, 12, 160, 70, 30, 180, 100, 35, NULL),
|
||||
(3, 12, 13, 180, 90, 25, 190, 110, 40, NULL),
|
||||
(3, 12, 14, 200, 100, 20, 220, 130, 45, NULL),
|
||||
(2, 13, 11, 100, 50, 45, 130, 60, 20, NULL),
|
||||
(2, 13, 12, 120, 60, 40, 160, 80, 30, NULL),
|
||||
(3, 14, 13, 140, 70, 30, 160, 90, 35, NULL),
|
||||
(3, 15, 12, 150, 80, 25, 180, 100, 30, NULL),
|
||||
(3, 15, 13, 170, 90, 20, 190, 110, 35, NULL);
|
||||
|
||||
INSERT OR IGNORE INTO site_admin VALUES (1);
|
|
@ -1,42 +0,0 @@
|
|||
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)
|
||||
}
|
|
@ -1,43 +0,0 @@
|
|||
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 site admin
|
||||
issiteadmin, err := db.GetDb(c).IsSiteAdmin(username)
|
||||
if err != nil {
|
||||
log.Warn("Error checking if siteadmin:", err)
|
||||
return c.Status(500).SendString(err.Error())
|
||||
} else if !issiteadmin {
|
||||
log.Warn("User is not siteadmin")
|
||||
return c.Status(401).SendString("User is not siteadmin")
|
||||
}
|
||||
|
||||
|
||||
// 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")
|
||||
}
|
|
@ -1,30 +0,0 @@
|
|||
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")
|
||||
}
|
|
@ -1,19 +0,0 @@
|
|||
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")
|
||||
}
|
|
@ -1,38 +0,0 @@
|
|||
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)
|
||||
}
|
|
@ -1,63 +0,0 @@
|
|||
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)
|
||||
}
|
|
@ -1,26 +0,0 @@
|
|||
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)
|
||||
}
|
|
@ -1,32 +0,0 @@
|
|||
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})
|
||||
}
|
|
@ -1,55 +0,0 @@
|
|||
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)
|
||||
}
|
|
@ -1,51 +0,0 @@
|
|||
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)
|
||||
}
|
|
@ -1,55 +0,0 @@
|
|||
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)
|
||||
}
|
|
@ -1,35 +0,0 @@
|
|||
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")
|
||||
}
|
|
@ -1,40 +0,0 @@
|
|||
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)
|
||||
}
|
|
@ -1,22 +0,0 @@
|
|||
package reports
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
db "ttime/internal/database"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func DeleteReport(c *fiber.Ctx) error {
|
||||
reportID := c.Params("reportID")
|
||||
reportIDInt, err := strconv.Atoi(reportID)
|
||||
if err != nil {
|
||||
return c.Status(400).SendString("Invalid report ID")
|
||||
}
|
||||
|
||||
if err := db.GetDb(c).DeleteReport(reportIDInt); err != nil {
|
||||
return c.Status(500).SendString((err.Error()))
|
||||
}
|
||||
|
||||
return c.Status(200).SendString("Weekly report deleted")
|
||||
}
|
|
@ -1,56 +0,0 @@
|
|||
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)
|
||||
}
|
|
@ -1,45 +0,0 @@
|
|||
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)
|
||||
}
|
|
@ -1,65 +0,0 @@
|
|||
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)
|
||||
}
|
|
@ -1,41 +0,0 @@
|
|||
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")
|
||||
}
|
|
@ -1,56 +0,0 @@
|
|||
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 GetStatistics(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 from query parameters
|
||||
projectName := c.Query("projectName")
|
||||
userNameParam := c.Query("userName")
|
||||
|
||||
log.Info(username, " trying to get statistics for project: ", projectName)
|
||||
|
||||
if projectName == "" {
|
||||
log.Info("Missing project name")
|
||||
return c.Status(400).SendString("Missing project name")
|
||||
}
|
||||
|
||||
// Check if the user is a project manager
|
||||
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())
|
||||
}
|
||||
|
||||
// Bail if the user is not a PM or checking its own statistics
|
||||
if !pm && userNameParam != "" && userNameParam != username {
|
||||
log.Info("Unauthorized access for user: ", username, "trying to access project: ", projectName, "statistics for user: ", userNameParam)
|
||||
return c.Status(403).SendString("Unauthorized access")
|
||||
}
|
||||
|
||||
if pm && userNameParam != "" {
|
||||
username = userNameParam
|
||||
}
|
||||
|
||||
// Retrieve statistics for the project from the database
|
||||
statistics, err := db.GetDb(c).ReportStatistics(username, projectName)
|
||||
if err != nil {
|
||||
log.Error("Error getting statistics for project:", projectName, ":", err)
|
||||
return c.Status(500).SendString(err.Error())
|
||||
}
|
||||
|
||||
log.Info("Returning statistics")
|
||||
// Return the retrieved statistics
|
||||
return c.JSON(statistics)
|
||||
|
||||
}
|
|
@ -1,41 +0,0 @@
|
|||
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")
|
||||
}
|
|
@ -1,41 +0,0 @@
|
|||
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 UnsignReport(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).UnsignWeeklyReport(reportId, projectManagerID)
|
||||
if err != nil {
|
||||
log.Info("Error Unsigning weekly report:", err)
|
||||
return c.Status(500).SendString(err.Error())
|
||||
}
|
||||
|
||||
log.Info("Project manager ID: ", projectManagerID, " unsigned report ID: ", reportId)
|
||||
return c.Status(200).SendString("Weekly report unsigned successfully")
|
||||
}
|
|
@ -1,44 +0,0 @@
|
|||
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")
|
||||
}
|
|
@ -1,44 +0,0 @@
|
|||
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)
|
||||
}
|
|
@ -1,42 +0,0 @@
|
|||
package users
|
||||
|
||||
import (
|
||||
db "ttime/internal/database"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/log"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// ChangeUserPassword is a handler that changes the password of a user
|
||||
func ChangeUserPassword(c *fiber.Ctx) error {
|
||||
|
||||
//Check token and get username of current user
|
||||
user := c.Locals("user").(*jwt.Token)
|
||||
claims := user.Claims.(jwt.MapClaims)
|
||||
admin := claims["name"].(string)
|
||||
|
||||
// Extract the necessary parameters from the request
|
||||
username := c.Params("username")
|
||||
newPassword := c.Query("newPassword")
|
||||
|
||||
// Check if user is site admin
|
||||
issiteadmin, err := db.GetDb(c).IsSiteAdmin(admin)
|
||||
if err != nil {
|
||||
log.Warn("Error checking if siteadmin:", err)
|
||||
return c.Status(500).SendString(err.Error())
|
||||
} else if !issiteadmin {
|
||||
log.Warn("User is not siteadmin")
|
||||
return c.Status(401).SendString("User is not siteadmin")
|
||||
}
|
||||
|
||||
// Perform the password change
|
||||
err = db.GetDb(c).ChangeUserPassword(username, newPassword)
|
||||
if err != nil {
|
||||
log.Warn("Error changing password:", err)
|
||||
return c.Status(500).SendString(err.Error())
|
||||
}
|
||||
|
||||
// Return a success message
|
||||
return c.Status(200).SendString("Password changed successfully")
|
||||
}
|
|
@ -1,32 +0,0 @@
|
|||
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})
|
||||
}
|
|
@ -1,22 +0,0 @@
|
|||
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)
|
||||
}
|
|
@ -1,32 +0,0 @@
|
|||
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)
|
||||
}
|
|
@ -1,66 +0,0 @@
|
|||
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})
|
||||
}
|
|
@ -1,50 +0,0 @@
|
|||
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})
|
||||
}
|
|
@ -1,45 +0,0 @@
|
|||
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)
|
||||
}
|
|
@ -1,38 +0,0 @@
|
|||
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")
|
||||
}
|
|
@ -1,43 +0,0 @@
|
|||
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")
|
||||
}
|
|
@ -1,97 +0,0 @@
|
|||
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 `json:"projectName"`
|
||||
// The week number
|
||||
Week int `json:"week"`
|
||||
// Total time spent on development
|
||||
DevelopmentTime int `json:"developmentTime"`
|
||||
// Total time spent in meetings
|
||||
MeetingTime int `json:"meetingTime"`
|
||||
// Total time spent on administrative tasks
|
||||
AdminTime int `json:"adminTime"`
|
||||
// Total time spent on personal projects
|
||||
OwnWorkTime int `json:"ownWorkTime"`
|
||||
// Total time spent on studying
|
||||
StudyTime int `json:"studyTime"`
|
||||
// Total time spent on testing
|
||||
TestingTime int `json:"testingTime"`
|
||||
}
|
||||
|
||||
type WeeklyReportList struct {
|
||||
// The name of the project, as it appears in the database
|
||||
ProjectName string `json:"projectName" db:"project_name"`
|
||||
// The week number
|
||||
Week int `json:"week" db:"week"`
|
||||
// Total time spent on development
|
||||
DevelopmentTime int `json:"developmentTime" db:"development_time"`
|
||||
// Total time spent in meetings
|
||||
MeetingTime int `json:"meetingTime" db:"meeting_time"`
|
||||
// Total time spent on administrative tasks
|
||||
AdminTime int `json:"adminTime" db:"admin_time"`
|
||||
// Total time spent on personal projects
|
||||
OwnWorkTime int `json:"ownWorkTime" db:"own_work_time"`
|
||||
// Total time spent on studying
|
||||
StudyTime int `json:"studyTime" db:"study_time"`
|
||||
// Total time spent on testing
|
||||
TestingTime int `json:"testingTime" db:"testing_time"`
|
||||
// The project manager who signed it
|
||||
SignedBy *int `json:"signedBy" db:"signed_by"`
|
||||
}
|
||||
|
||||
type WeeklyReport struct {
|
||||
// The ID of the report
|
||||
ReportId int `json:"reportId" db:"report_id"`
|
||||
// The user id of the user who submitted the report
|
||||
UserId int `json:"userId" db:"user_id"`
|
||||
// The name of the project, as it appears in the database
|
||||
ProjectId int `json:"projectId" db:"project_id"`
|
||||
// The week number
|
||||
Week int `json:"week" db:"week"`
|
||||
// Total time spent on development
|
||||
DevelopmentTime int `json:"developmentTime" db:"development_time"`
|
||||
// Total time spent in meetings
|
||||
MeetingTime int `json:"meetingTime" db:"meeting_time"`
|
||||
// Total time spent on administrative tasks
|
||||
AdminTime int `json:"adminTime" db:"admin_time"`
|
||||
// Total time spent on personal projects
|
||||
OwnWorkTime int `json:"ownWorkTime" db:"own_work_time"`
|
||||
// Total time spent on studying
|
||||
StudyTime int `json:"studyTime" db:"study_time"`
|
||||
// Total time spent on testing
|
||||
TestingTime int `json:"testingTime" db:"testing_time"`
|
||||
// The project manager who signed it
|
||||
SignedBy *int `json:"signedBy" db:"signed_by"`
|
||||
}
|
||||
|
||||
type Statistics struct {
|
||||
TotalDevelopmentTime int `json:"totalDevelopmentTime" db:"total_development_time"`
|
||||
TotalMeetingTime int `json:"totalMeetingTime" db:"total_meeting_time"`
|
||||
TotalAdminTime int `json:"totalAdminTime" db:"total_admin_time"`
|
||||
TotalOwnWorkTime int `json:"totalOwnWorkTime" db:"total_own_work_time"`
|
||||
TotalStudyTime int `json:"totalStudyTime" db:"total_study_time"`
|
||||
TotalTestingTime int `json:"totalTestingTime" db:"total_testing_time"`
|
||||
}
|
||||
|
||||
type UpdateWeeklyReport struct {
|
||||
// The name of the project, as it appears in the database
|
||||
ProjectName string `json:"projectName"`
|
||||
// The name of the user
|
||||
UserName string `json:"userName"`
|
||||
// The week number
|
||||
Week int `json:"week"`
|
||||
// Total time spent on development
|
||||
DevelopmentTime int `json:"developmentTime"`
|
||||
// Total time spent in meetings
|
||||
MeetingTime int `json:"meetingTime"`
|
||||
// Total time spent on administrative tasks
|
||||
AdminTime int `json:"adminTime"`
|
||||
// Total time spent on personal projects
|
||||
OwnWorkTime int `json:"ownWorkTime"`
|
||||
// Total time spent on studying
|
||||
StudyTime int `json:"studyTime"`
|
||||
// Total time spent on testing
|
||||
TestingTime int `json:"testingTime"`
|
||||
}
|
|
@ -1,29 +0,0 @@
|
|||
package types
|
||||
|
||||
// Project is a struct that holds the information about a project
|
||||
type Project struct {
|
||||
ID int `json:"id" db:"id"`
|
||||
Name string `json:"name" db:"name"`
|
||||
Description string `json:"description" db:"description"`
|
||||
Owner string `json:"owner" db:"owner_user_id"`
|
||||
}
|
||||
|
||||
// As it arrives from the client, Owner is derived from the JWT token
|
||||
type NewProject struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// Used to change the role of a user in a project.
|
||||
// If name is identical to the name contained in the token, the role can be changed.
|
||||
// If the name is different, only a project manager can change the role.
|
||||
type RoleChange struct {
|
||||
UserName string `json:"username"`
|
||||
Role string `json:"role" tstype:"'project_manager' | 'user'"`
|
||||
Projectname string `json:"projectname"`
|
||||
}
|
||||
|
||||
type NameChange struct {
|
||||
ID int `json:"id" db:"id"`
|
||||
Name string `json:"name" db:"name"`
|
||||
}
|
|
@ -1,39 +0,0 @@
|
|||
package types
|
||||
|
||||
// User struct represents a user in the system
|
||||
type User struct {
|
||||
UserId string `json:"userId"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
// If the user needs to be served over the api, we dont want to send the password
|
||||
// ToPublicUser converts a User to a PublicUser
|
||||
func (u *User) ToPublicUser() (*PublicUser, error) {
|
||||
return &PublicUser{
|
||||
UserId: u.UserId,
|
||||
Username: u.Username,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Should be used when registering, for example
|
||||
type NewUser struct {
|
||||
Username string `json:"username" example:"username123"`
|
||||
Password string `json:"password" example:"password123"`
|
||||
}
|
||||
|
||||
// PublicUser represents a user that is safe to send over the API (no password)
|
||||
type PublicUser struct {
|
||||
UserId string `json:"userId"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
// wrapper type for token
|
||||
type Token struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
type StrNameChange struct {
|
||||
PrevName string `json:"prevName" db:"prevName"`
|
||||
NewName string `json:"newName" db:"newName"`
|
||||
}
|
|
@ -1,35 +0,0 @@
|
|||
package types
|
||||
|
||||
import "testing"
|
||||
|
||||
// NewUser returns a new User
|
||||
func TestNewUser(t *testing.T) {
|
||||
u := User{
|
||||
UserId: "123",
|
||||
Username: "test",
|
||||
Password: "password",
|
||||
}
|
||||
|
||||
if u.UserId != "123" {
|
||||
t.Errorf("Expected user id to be 123, got %s", u.UserId)
|
||||
}
|
||||
if u.Username != "test" {
|
||||
t.Errorf("Expected username to be test, got %s", u.Username)
|
||||
}
|
||||
if u.Password != "password" {
|
||||
t.Errorf("Expected password to be password, got %s", u.Password)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToPublicUser(t *testing.T) {
|
||||
u := User{
|
||||
UserId: "123",
|
||||
Username: "test",
|
||||
Password: "password",
|
||||
}
|
||||
|
||||
_, err := u.ToPublicUser()
|
||||
if err != nil {
|
||||
t.Errorf("Expected no error, got %s", err)
|
||||
}
|
||||
}
|
148
backend/main.go
148
backend/main.go
|
@ -1,148 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
_ "ttime/docs"
|
||||
"ttime/internal/config"
|
||||
"ttime/internal/database"
|
||||
"ttime/internal/handlers/projects"
|
||||
"ttime/internal/handlers/reports"
|
||||
"ttime/internal/handlers/users"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/logger"
|
||||
"github.com/gofiber/swagger"
|
||||
|
||||
jwtware "github.com/gofiber/contrib/jwt"
|
||||
)
|
||||
|
||||
// @title TTime API
|
||||
// @version 0.0.1
|
||||
// @description This is the API for TTime, a time tracking application.
|
||||
|
||||
// @license.name AGPL
|
||||
// @license.url https://www.gnu.org/licenses/agpl-3.0.html
|
||||
|
||||
// @securityDefinitions.apikey JWT
|
||||
// @in header
|
||||
// @name Authorization
|
||||
// @description Use the JWT token provided by the login endpoint to authenticate requests. **Prefix the token with "Bearer ".**
|
||||
|
||||
// @host localhost:8080
|
||||
// @BasePath /api
|
||||
|
||||
// @externalDocs.description OpenAPI
|
||||
// @externalDocs.url https://swagger.io/resources/open-api/
|
||||
|
||||
/**
|
||||
Main function for starting the server and initializing configurations.
|
||||
Reads configuration from file, pretty prints it, connects to the database,
|
||||
migrates it, and sets up routes for the server.
|
||||
*/
|
||||
|
||||
func main() {
|
||||
conf, err := config.ReadConfigFromFile("config.toml")
|
||||
if err != nil {
|
||||
conf = config.NewConfig()
|
||||
_ = conf.WriteConfigToFile("config.toml")
|
||||
}
|
||||
|
||||
// Pretty print the current config with toml
|
||||
_ = toml.NewEncoder(os.Stdout).Encode(conf)
|
||||
|
||||
fmt.Printf("Starting server on http://localhost:%d\n", conf.Port)
|
||||
fmt.Printf("For documentation, go to http://localhost:%d/swagger/index.html\n", conf.Port)
|
||||
|
||||
// Connect to the database
|
||||
db := database.DbConnect(conf.DbPath)
|
||||
|
||||
// Migrate the database
|
||||
if err = database.Migrate(db); err != nil {
|
||||
fmt.Println("Error migrating database: ", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Migrate sample data, should not be used in production
|
||||
if err = database.MigrateSampleData(db); err != nil {
|
||||
fmt.Println("Error migrating sample data: ", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Create the server
|
||||
server := fiber.New()
|
||||
|
||||
// We want some logs
|
||||
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
|
||||
server.Get("/swagger/*", swagger.HandlerDefault)
|
||||
|
||||
// Mount our static files (Beware of the security implications of this!)
|
||||
// This will likely be replaced by an embedded filesystem in the future
|
||||
server.Static("/", "./static")
|
||||
|
||||
// Create a group for our API
|
||||
api := server.Group("/api")
|
||||
|
||||
// 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{
|
||||
SigningKey: jwtware.SigningKey{Key: []byte("secret")},
|
||||
}))
|
||||
|
||||
// All user related routes
|
||||
// userGroup := api.Group("/user") // Not currently in use
|
||||
api.Get("/users/all", users.ListAllUsers)
|
||||
api.Get("/project/getAllUsers", users.GetAllUsersProject)
|
||||
api.Get("/username", users.GetUserName)
|
||||
api.Post("/login", users.Login)
|
||||
api.Post("/register", users.Register)
|
||||
api.Post("/loginrenew", users.LoginRenew)
|
||||
api.Post("/promoteToAdmin", users.PromoteToAdmin)
|
||||
api.Put("/changeUserName", users.ChangeUserName)
|
||||
api.Delete("/userdelete/:username", users.UserDelete) // Perhaps just use POST to avoid headaches
|
||||
api.Put("/changeUserPassword/:username", users.ChangeUserPassword)
|
||||
|
||||
// All project related routes
|
||||
// projectGroup := api.Group("/project") // Not currently in use
|
||||
api.Get("/getProjectTimes/:projectName", projects.GetProjectTimesHandler)
|
||||
api.Get("/getUserProjects/:username", projects.GetUserProjects)
|
||||
api.Get("/project/:projectId", projects.GetProject)
|
||||
api.Get("/checkIfProjectManager/:projectName", projects.IsProjectManagerHandler)
|
||||
api.Get("/getUsersProject/:projectName", projects.ListAllUsersProject)
|
||||
api.Post("/project", projects.CreateProject)
|
||||
api.Post("/ProjectRoleChange", projects.ProjectRoleChange)
|
||||
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)
|
||||
api.Put("/changeProjectName/:projectName", projects.ChangeProjectName)
|
||||
|
||||
// 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.Get("/getStatistics", reports.GetStatistics)
|
||||
api.Post("/submitWeeklyReport", reports.SubmitWeeklyReport)
|
||||
api.Put("/signReport/:reportId", reports.SignReport)
|
||||
api.Put("/updateWeeklyReport", reports.UpdateWeeklyReport)
|
||||
api.Put("/unsignReport/:reportId", reports.UnsignReport)
|
||||
api.Delete("/deleteReport/:reportId", reports.DeleteReport)
|
||||
|
||||
// Announce the port we are listening on and start the server
|
||||
err = server.Listen(fmt.Sprintf(":%d", conf.Port))
|
||||
if err != nil {
|
||||
fmt.Println("Error starting server: ", err)
|
||||
}
|
||||
}
|
50
backend/migrations/0010.sql
Normal file
50
backend/migrations/0010.sql
Normal file
|
@ -0,0 +1,50 @@
|
|||
PRAGMA foreign_keys = ON;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY,
|
||||
username VARCHAR(255) NOT NULL,
|
||||
password VARCHAR(255) NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS projects (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
description TEXT NOT NULL,
|
||||
user_id INTEGER NOT NULL,
|
||||
FOREIGN KEY (user_id) REFERENCES users (id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS time_reports (
|
||||
id INTEGER PRIMARY KEY,
|
||||
project_id INTEGER NOT NULL,
|
||||
start DATETIME NOT NULL,
|
||||
end DATETIME NOT NULL,
|
||||
FOREIGN KEY (project_id) REFERENCES projects (id)
|
||||
);
|
||||
|
||||
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;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS report_collection (
|
||||
id INTEGER PRIMARY KEY,
|
||||
project_id INTEGER NOT NULL,
|
||||
date DATE NOT NULL,
|
||||
signed_by INTEGER, -- NULL if not signed
|
||||
FOREIGN KEY (signed_by) REFERENCES users (id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_roles (
|
||||
user_id INTEGER NOT NULL,
|
||||
project_id INTEGER NOT NULL,
|
||||
role STRING NOT NULL,
|
||||
FOREIGN KEY (user_id) REFERENCES users (id)
|
||||
FOREIGN KEY (project_id) REFERENCES projects (id)
|
||||
);
|
|
@ -1,9 +0,0 @@
|
|||
packages:
|
||||
- path: "ttime/internal/types"
|
||||
output_path: "../frontend/src/Types/goTypes.ts"
|
||||
type_mappings:
|
||||
time.Time: "string /* RFC3339 */"
|
||||
null.String: "null | string"
|
||||
null.Bool: "null | boolean"
|
||||
uuid.UUID: "string /* uuid */"
|
||||
uuid.NullUUID: "null | string /* uuid */"
|
|
@ -13,6 +13,7 @@ FROM docker.io/golang:alpine as go
|
|||
RUN apk add gcompat
|
||||
RUN apk add gcc
|
||||
RUN apk add musl-dev
|
||||
RUN apk add make
|
||||
RUN apk add sqlite
|
||||
WORKDIR /build
|
||||
ADD backend/go.mod backend/go.sum ./
|
||||
|
@ -23,8 +24,10 @@ RUN go mod download
|
|||
# Add the source code
|
||||
ADD backend .
|
||||
|
||||
RUN go build -o server
|
||||
RUN CGO_ENABLED=1 GOOS=linux go build -a -installsuffix cgo -o ./server ./main.go
|
||||
RUN make migrate
|
||||
|
||||
# RUN go build -o server
|
||||
RUN CGO_ENABLED=1 GOOS=linux go build -a -installsuffix cgo -o ./server ./cmd/
|
||||
|
||||
# Strip the binary for a smaller image
|
||||
RUN strip ./server
|
||||
|
@ -34,7 +37,6 @@ FROM docker.io/alpine:latest as runner
|
|||
RUN adduser -D nonroot
|
||||
RUN addgroup nonroot nonroot
|
||||
WORKDIR /app
|
||||
RUN chown nonroot:nonroot /app
|
||||
|
||||
# Copy the frontend SPA build into public
|
||||
COPY --from=client /build/dist static
|
||||
|
@ -42,6 +44,9 @@ COPY --from=client /build/dist static
|
|||
# Copy the server binary
|
||||
COPY --from=go /build/server server
|
||||
|
||||
# Copy the database
|
||||
COPY --from=go /build/db.sqlite3 db.sqlite3
|
||||
|
||||
# Expose port 8080
|
||||
EXPOSE 8080
|
||||
|
||||
|
@ -49,4 +54,4 @@ EXPOSE 8080
|
|||
USER nonroot:nonroot
|
||||
|
||||
# Run the server
|
||||
CMD ["./server"]
|
||||
CMD ["./server"]
|
|
@ -9,7 +9,7 @@ module.exports = {
|
|||
'plugin:react-hooks/recommended',
|
||||
'plugin:prettier/recommended',
|
||||
],
|
||||
ignorePatterns: ['dist', '.eslintrc.cjs', 'tailwind.config.js', 'postcss.config.js', 'jest.config.cjs', 'goTypes.ts'],
|
||||
ignorePatterns: ['dist', '.eslintrc.cjs'],
|
||||
parser: '@typescript-eslint/parser',
|
||||
plugins: ['react-refresh', 'prettier'],
|
||||
rules: {
|
||||
|
|
|
@ -1,2 +0,0 @@
|
|||
goTypes.ts
|
||||
GenApi.ts
|
|
@ -2,9 +2,9 @@
|
|||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/x-icon" href="src/assets/favicon.ico" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>TTIME</title>
|
||||
<title>Vite + React + TS</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
|
|
@ -1,5 +0,0 @@
|
|||
module.exports = {
|
||||
transform: {
|
||||
'^.+\\.(t|j)sx?$': '@swc/jest',
|
||||
},
|
||||
}
|
5130
frontend/package-lock.json
generated
5130
frontend/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
@ -8,38 +8,25 @@
|
|||
"build": "tsc && vite build",
|
||||
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
|
||||
"preview": "vite preview",
|
||||
"format": "prettier --config .prettierrc '**/*.ts' '**/*.tsx' '**/*.js' '**/*.json' --write",
|
||||
"test": "jest"
|
||||
"format": "prettier --config .prettierrc '**/*.ts' '**/*.tsx' '**/*.js' '**/*.json' --write"
|
||||
},
|
||||
"dependencies": {
|
||||
"localforage": "^1.10.0",
|
||||
"match-sorter": "^6.3.4",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-router-dom": "^6.22.2",
|
||||
"sort-by": "^0.0.2"
|
||||
"react-dom": "^18.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@swc/core": "^1.4.2",
|
||||
"@swc/jest": "^0.2.36",
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/react": "^18.2.55",
|
||||
"@types/react-dom": "^18.2.19",
|
||||
"@typescript-eslint/eslint-plugin": "^6.21.0",
|
||||
"@typescript-eslint/parser": "^6.21.0",
|
||||
"@vitejs/plugin-react-swc": "^3.5.0",
|
||||
"autoprefixer": "^10.4.17",
|
||||
"eslint": "^8.56.0",
|
||||
"eslint-config-prettier": "^9.1.0",
|
||||
"eslint-plugin-prettier": "^5.1.3",
|
||||
"eslint-plugin-react": "^7.33.2",
|
||||
"eslint-plugin-react-hooks": "^4.6.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.5",
|
||||
"jest": "^29.7.0",
|
||||
"postcss": "^8.4.35",
|
||||
"prettier": "3.2.5",
|
||||
"react-test-renderer": "^18.2.0",
|
||||
"tailwindcss": "^3.4.1",
|
||||
"typescript": "^5.2.2",
|
||||
"vite": "^5.1.0"
|
||||
}
|
||||
|
|
|
@ -1,6 +0,0 @@
|
|||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
};
|
File diff suppressed because it is too large
Load diff
|
@ -1,358 +0,0 @@
|
|||
/* 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,3 +0,0 @@
|
|||
# API
|
||||
|
||||
This file contains the high-level API interface and implementation.
|
42
frontend/src/App.css
Normal file
42
frontend/src/App.css
Normal file
|
@ -0,0 +1,42 @@
|
|||
#root {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: filter 300ms;
|
||||
}
|
||||
.logo:hover {
|
||||
filter: drop-shadow(0 0 2em #646cffaa);
|
||||
}
|
||||
.logo.react:hover {
|
||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||
}
|
||||
|
||||
@keyframes logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
a:nth-of-type(2) .logo {
|
||||
animation: logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
31
frontend/src/App.tsx
Normal file
31
frontend/src/App.tsx
Normal file
|
@ -0,0 +1,31 @@
|
|||
import reactLogo from "./assets/react.svg";
|
||||
import viteLogo from "/vite.svg";
|
||||
import "./App.css";
|
||||
import { CountButton } from "./Components/CountButton";
|
||||
|
||||
function App(): JSX.Element {
|
||||
return (
|
||||
<>
|
||||
<div>
|
||||
<a href="https://vitejs.dev" target="_blank" rel="noreferrer">
|
||||
<img src={viteLogo} className="logo" alt="Vite logo" />
|
||||
</a>
|
||||
<a href="https://react.dev" target="_blank" rel="noreferrer">
|
||||
<img src={reactLogo} className="logo react" alt="React logo" />
|
||||
</a>
|
||||
</div>
|
||||
<h1>Vite + React</h1>
|
||||
<div className="card">
|
||||
<CountButton />
|
||||
<p>
|
||||
Edit <code>src/App.tsx</code> and save to test HMR
|
||||
</p>
|
||||
</div>
|
||||
<p className="read-the-docs">
|
||||
Click on the Vite and React logos to learn more
|
||||
</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
|
@ -1,35 +0,0 @@
|
|||
import { api } from "../API/API";
|
||||
|
||||
export interface AddMemberInfo {
|
||||
userName: string;
|
||||
projectName: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to add a member to a project
|
||||
* @param {AddMemberInfo} props.membertoAdd - Contains user's name and project's name
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function AddMember(props: { memberToAdd: AddMemberInfo }): Promise<void> {
|
||||
if (props.memberToAdd.userName === "") {
|
||||
alert("You must choose at least one user to add");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await api.addUserToProject(
|
||||
props.memberToAdd,
|
||||
localStorage.getItem("accessToken") ?? "",
|
||||
);
|
||||
if (response.success) {
|
||||
alert(`[${props.memberToAdd.userName}] added`);
|
||||
} else {
|
||||
alert(`[${props.memberToAdd.userName}] not added`);
|
||||
console.error(response.message);
|
||||
}
|
||||
} catch (error) {
|
||||
alert(`[${props.memberToAdd.userName}] not added`);
|
||||
console.error("An error occurred during member add:", error);
|
||||
}
|
||||
}
|
||||
|
||||
export default AddMember;
|
|
@ -1,113 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import { api } from "../API/API";
|
||||
import { NewProject } from "../Types/goTypes";
|
||||
import Logo from "../assets/Logo.svg";
|
||||
import Button from "./Button";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import ProjectNameInput from "./Inputs/ProjectNameInput";
|
||||
import DescriptionInput from "./Inputs/DescriptionInput";
|
||||
import { alphanumeric } from "../Data/regex";
|
||||
import { projNameHighLimit, projNameLowLimit } from "../Data/constants";
|
||||
|
||||
/**
|
||||
* Provides UI for adding a project to the system.
|
||||
* @returns {JSX.Element} - Returns the component UI for adding a project
|
||||
*/
|
||||
function AddProject(): JSX.Element {
|
||||
const [name, setName] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const navigate = useNavigate();
|
||||
|
||||
/**
|
||||
* Tries to add a project to the system
|
||||
*/
|
||||
const handleCreateProject = async (): Promise<void> => {
|
||||
if (
|
||||
!alphanumeric.test(name) ||
|
||||
name.length > projNameHighLimit ||
|
||||
name.length < projNameLowLimit
|
||||
) {
|
||||
alert(
|
||||
"Please provide valid project name: \n-Between 10-99 characters \n-No special characters (.-!?/*)",
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (description.length > projNameHighLimit) {
|
||||
alert("Please provide valid description: \n-Max 100 characters");
|
||||
return;
|
||||
}
|
||||
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("");
|
||||
navigate("/admin");
|
||||
} else {
|
||||
alert("Project not added, name could be taken");
|
||||
console.error(response.message);
|
||||
}
|
||||
} catch (error) {
|
||||
alert("Project not added");
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<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">
|
||||
<form
|
||||
className="bg-white rounded px-8 pt-6 pb-8 mb-4 justify-center flex flex-col w-fit h-fit"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void handleCreateProject();
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={Logo}
|
||||
className="logo w-[7vw] self-center mb-10 mt-10"
|
||||
alt="TTIME Logo"
|
||||
/>
|
||||
<h3 className="pb-4 mb-2 text-center font-bold text-[18px]">
|
||||
Create a new project
|
||||
</h3>
|
||||
<ProjectNameInput
|
||||
name={name}
|
||||
onChange={(e) => {
|
||||
e.preventDefault();
|
||||
setName(e.target.value);
|
||||
}}
|
||||
/>
|
||||
<div className="p-2"></div>
|
||||
<DescriptionInput
|
||||
desc={description}
|
||||
onChange={(e) => {
|
||||
e.preventDefault();
|
||||
setDescription(e.target.value);
|
||||
}}
|
||||
placeholder={"Description (Optional)"}
|
||||
/>
|
||||
<div className="flex self-center mt-4 justify-between">
|
||||
<Button
|
||||
text="Create"
|
||||
onClick={(): void => {
|
||||
return;
|
||||
}}
|
||||
type="submit"
|
||||
/>
|
||||
</div>
|
||||
</form>
|
||||
<p className="text-center text-gray-500 text-xs"></p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default AddProject;
|
|
@ -1,125 +0,0 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import Button from "./Button";
|
||||
import AddMember, { AddMemberInfo } from "./AddMember";
|
||||
import GetUsersInProject, { ProjectMember } from "./GetUsersInProject";
|
||||
import GetAllUsers from "./GetAllUsers";
|
||||
import InputField from "./InputField";
|
||||
|
||||
/**
|
||||
* Provides UI for adding a member to a project.
|
||||
* @returns {JSX.Element} - Returns the component UI for adding a member
|
||||
*/
|
||||
function AddUserToProject(props: { projectName: string }): JSX.Element {
|
||||
const [names, setNames] = useState<string[]>([]);
|
||||
const [users, setUsers] = useState<string[]>([]);
|
||||
const [usersProj, setUsersProj] = useState<ProjectMember[]>([]);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
// Gets all users and project members for filtering
|
||||
GetAllUsers({ setUsersProp: setUsers });
|
||||
GetUsersInProject({
|
||||
setUsersProp: setUsersProj,
|
||||
projectName: props.projectName,
|
||||
});
|
||||
/*
|
||||
* 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");
|
||||
return;
|
||||
}
|
||||
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 (
|
||||
<div className="border-4 border-black bg-white flex flex-col items-center py-10 px-20 rounded-3xl content-center overflow-auto">
|
||||
<h1 className="text-center font-bold text-[36px] pb-10">
|
||||
{props.projectName}
|
||||
</h1>
|
||||
<p className="p-1 text-center font-bold text-[26px]">
|
||||
Choose users to add:
|
||||
</p>
|
||||
|
||||
<div>
|
||||
<InputField
|
||||
placeholder={"Search users"}
|
||||
type={"Text"}
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.target.value);
|
||||
}}
|
||||
/>
|
||||
<ul className="font-medium space-y-2 border-2 border-black mt-2 px-2 pb-2 rounded-2xl text-center overflow-auto h-[26vh] w-[34vh]">
|
||||
<div></div>
|
||||
{users
|
||||
.filter((user) => {
|
||||
return search.toLowerCase() === ""
|
||||
? user
|
||||
: user.toLowerCase().includes(search.toLowerCase());
|
||||
})
|
||||
.map((user) => (
|
||||
<li
|
||||
className={
|
||||
names.includes(user)
|
||||
? "items-start p-1 border-2 border-transparent rounded-full bg-orange-500 transition-all 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 transition-all hover:text-white hover:cursor-pointer"
|
||||
}
|
||||
key={user}
|
||||
value={user}
|
||||
onClick={() => {
|
||||
handleUserClick(user);
|
||||
}}
|
||||
>
|
||||
<span>{user}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
<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
|
||||
text="Add"
|
||||
onClick={(): void => {
|
||||
void handleAddClick();
|
||||
}}
|
||||
type="button"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default AddUserToProject;
|
|
@ -1,71 +0,0 @@
|
|||
//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.
|
||||
import { useEffect, useState } from "react";
|
||||
import { WeeklyReport } from "../Types/goTypes";
|
||||
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.
|
||||
* @returns {JSX.Element} representing the component.
|
||||
*/
|
||||
function AllTimeReportsInProject(): JSX.Element {
|
||||
const { projectName } = useParams();
|
||||
const [weeklyReports, setWeeklyReports] = useState<WeeklyReport[]>([]);
|
||||
|
||||
// Call getProjects when the component mounts
|
||||
useEffect(() => {
|
||||
const getWeeklyReports = async (): Promise<void> => {
|
||||
const token = localStorage.getItem("accessToken") ?? "";
|
||||
const response = await api.getAllWeeklyReportsForUser(
|
||||
projectName ?? "",
|
||||
token,
|
||||
);
|
||||
console.log(response);
|
||||
if (response.success) {
|
||||
setWeeklyReports(response.data ?? []);
|
||||
} else {
|
||||
console.error(response.message);
|
||||
}
|
||||
};
|
||||
|
||||
void getWeeklyReports();
|
||||
}, [projectName]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="border-4 border-black bg-white flex flex-col items-center justify-center min-h-[65vh] h-fit w-[50vw] rounded-3xl content-center overflow-scroll space-y-[10vh] p-[30px] text-[30px]">
|
||||
{weeklyReports.map((newWeeklyReport, index) => (
|
||||
<Link
|
||||
to={`/editTimeReport/${projectName}/${newWeeklyReport.week}/${newWeeklyReport.signedBy ? "signed" : "unsigned"}`}
|
||||
key={index}
|
||||
className="border-b-2 border-black w-full cursor-pointer hover:font-extrabold"
|
||||
>
|
||||
<div className="flex justify-between">
|
||||
<h1>
|
||||
<span className="font-bold">{"Week: "}</span>
|
||||
{newWeeklyReport.week}
|
||||
</h1>
|
||||
<h1>
|
||||
<span className="font-bold">{"Total Time: "}</span>
|
||||
{newWeeklyReport.developmentTime +
|
||||
newWeeklyReport.meetingTime +
|
||||
newWeeklyReport.adminTime +
|
||||
newWeeklyReport.ownWorkTime +
|
||||
newWeeklyReport.studyTime +
|
||||
newWeeklyReport.testingTime}{" "}
|
||||
min
|
||||
</h1>
|
||||
<h1>
|
||||
<span className="font-bold">{"Signed: "}</span>
|
||||
{newWeeklyReport.signedBy ? "YES" : "NO"}
|
||||
</h1>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default AllTimeReportsInProject;
|
|
@ -1,73 +0,0 @@
|
|||
//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.
|
||||
import { useEffect, useState } from "react";
|
||||
import { WeeklyReport } from "../Types/goTypes";
|
||||
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.
|
||||
* @returns {JSX.Element} representing the component.
|
||||
*/
|
||||
function AllTimeReportsInProject(): JSX.Element {
|
||||
const { username } = useParams();
|
||||
const { projectName } = useParams();
|
||||
const [weeklyReports, setWeeklyReports] = useState<WeeklyReport[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const getWeeklyReports = async (): Promise<void> => {
|
||||
const token = localStorage.getItem("accessToken") ?? "";
|
||||
const response = await api.getAllWeeklyReportsForUser(
|
||||
projectName ?? "",
|
||||
token,
|
||||
username ?? "",
|
||||
);
|
||||
console.log(response);
|
||||
if (response.success) {
|
||||
setWeeklyReports(response.data ?? []);
|
||||
} else {
|
||||
console.error(response.message);
|
||||
}
|
||||
};
|
||||
|
||||
void getWeeklyReports();
|
||||
}, [projectName, username]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className="text-[30px] font-bold">{username}'s Time Reports</h1>
|
||||
<div className="border-4 border-black bg-white flex flex-col items-center justify-center min-h-[65vh] h-fit w-[50vw] rounded-3xl content-center overflow-scroll space-y-[10vh] p-[30px] text-[30px]">
|
||||
{weeklyReports.map((newWeeklyReport, index) => (
|
||||
<Link
|
||||
to={`/editOthersTR/${projectName}/${username}/${newWeeklyReport.week}/${newWeeklyReport.signedBy ? "signed" : "unsigned"}`}
|
||||
key={index}
|
||||
className="border-b-2 border-black w-full hover:font-extrabold"
|
||||
>
|
||||
<div className="flex justify-between">
|
||||
<h1>
|
||||
<span className="font-bold">{"Week: "}</span>
|
||||
{newWeeklyReport.week}
|
||||
</h1>
|
||||
<h1>
|
||||
<span className="font-bold">{"Total Time: "}</span>
|
||||
{newWeeklyReport.developmentTime +
|
||||
newWeeklyReport.meetingTime +
|
||||
newWeeklyReport.adminTime +
|
||||
newWeeklyReport.ownWorkTime +
|
||||
newWeeklyReport.studyTime +
|
||||
newWeeklyReport.testingTime}{" "}
|
||||
min
|
||||
</h1>
|
||||
<h1>
|
||||
<span className="font-bold">{"Signed: "}</span>
|
||||
{newWeeklyReport.signedBy ? "YES" : "NO"}
|
||||
</h1>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default AllTimeReportsInProject;
|
|
@ -1,18 +0,0 @@
|
|||
import { Navigate } from "react-router-dom";
|
||||
import React from "react";
|
||||
|
||||
interface AuthorizedRouteProps {
|
||||
children: React.ReactNode;
|
||||
isAuthorized: boolean;
|
||||
}
|
||||
|
||||
export function AuthorizedRoute({
|
||||
children,
|
||||
isAuthorized,
|
||||
}: AuthorizedRouteProps): JSX.Element {
|
||||
if (!isAuthorized) {
|
||||
return <Navigate to="/unauthorized" />;
|
||||
}
|
||||
|
||||
return children as React.ReactElement;
|
||||
}
|
|
@ -1,24 +0,0 @@
|
|||
//info: Back button component to navigate back to the previous page
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
/**
|
||||
* Renders a back button component.
|
||||
*
|
||||
* @returns The JSX element representing the back button.
|
||||
*/
|
||||
function BackButton(): JSX.Element {
|
||||
const navigate = useNavigate();
|
||||
const goBack = (): void => {
|
||||
navigate(-1);
|
||||
};
|
||||
return (
|
||||
<button
|
||||
onClick={goBack}
|
||||
className="inline-block py-1 px-8 font-bold bg-orange-500 text-white border-2 border-black rounded-full cursor-pointer mt-5 mb-5 transition-colors duration-10 hover:bg-orange-600 hover:text-gray-300 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; font-size: 4vh;"
|
||||
>
|
||||
Back
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export default BackButton;
|
|
@ -1,29 +0,0 @@
|
|||
//info: Background animation component to animate the background of loginpage
|
||||
import { useEffect } from "react";
|
||||
|
||||
/**
|
||||
* Renders a background animation component.
|
||||
* This component pre-loads images and starts a background transition animation.
|
||||
*/
|
||||
const BackgroundAnimation = (): JSX.Element => {
|
||||
useEffect(() => {
|
||||
const images = [
|
||||
"src/assets/1.jpg",
|
||||
"src/assets/2.jpg",
|
||||
"src/assets/3.jpg",
|
||||
"src/assets/4.jpg",
|
||||
];
|
||||
|
||||
// Pre-load images
|
||||
for (const i of images) {
|
||||
console.log(i);
|
||||
}
|
||||
|
||||
// Start animation
|
||||
document.body.style.animation = "backgroundTransition 30s infinite";
|
||||
}, []);
|
||||
|
||||
return <></>;
|
||||
};
|
||||
|
||||
export default BackgroundAnimation;
|
|
@ -1,30 +0,0 @@
|
|||
//info: Basic window component to display content and buttons of a page, inclduing header and footer
|
||||
//content to insert is placed in the content prop, and buttons in the buttons prop
|
||||
import Header from "./Header";
|
||||
import Footer from "./Footer";
|
||||
|
||||
/**
|
||||
* Renders a basic window component with a header, content, and footer.
|
||||
*
|
||||
* @param {Object} props - The component props.
|
||||
* @param {React.ReactNode} props.content - The content to be rendered in the window.
|
||||
* @param {React.ReactNode} props.buttons - The buttons to be rendered in the footer.
|
||||
* @returns {JSX.Element} The rendered basic window component.
|
||||
*/
|
||||
function BasicWindow({
|
||||
content,
|
||||
buttons,
|
||||
}: {
|
||||
content: React.ReactNode;
|
||||
buttons: React.ReactNode;
|
||||
}): JSX.Element {
|
||||
return (
|
||||
<div className="font-sans flex flex-col h-screen bg-white border-2 border-black overflow-auto pt-[110px]">
|
||||
<Header />
|
||||
<div className="flex flex-col items-center flex-grow">{content}</div>
|
||||
<Footer>{buttons}</Footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default BasicWindow;
|
|
@ -1,30 +0,0 @@
|
|||
/**
|
||||
* Button component to display a button with text and onClick function.
|
||||
*
|
||||
* @param {Object} props - The component props.
|
||||
* @param {string} props.text - The text to display on the button.
|
||||
* @param {Function} props.onClick - The function to run when the button is clicked.
|
||||
* @param {"submit" | "button" | "reset"} props.type - The type of button.
|
||||
* @returns {JSX.Element} The rendered Button component.
|
||||
*/
|
||||
function Button({
|
||||
text,
|
||||
onClick,
|
||||
type,
|
||||
}: {
|
||||
text: string;
|
||||
onClick: () => void;
|
||||
type: "submit" | "button" | "reset";
|
||||
}): JSX.Element {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className="inline-block py-1 px-8 font-bold bg-orange-500 text-white border-2 border-black rounded-full cursor-pointer mt-5 mb-5 transition-colors duration-10 hover:bg-orange-600 hover:text-gray-300 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; font-size: 4vh;"
|
||||
type={type}
|
||||
>
|
||||
{text}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export default Button;
|
|
@ -1,36 +0,0 @@
|
|||
import { APIResponse, api } from "../API/API";
|
||||
|
||||
/**
|
||||
* Changes the name of a project
|
||||
* @param {string} props.projectName - Current project name
|
||||
* @param {string} props.newProjectName - New project name
|
||||
* @returns {void} - Nothing
|
||||
*/
|
||||
export default function ChangeProjectName(props: {
|
||||
projectName: string;
|
||||
newProjectName: string;
|
||||
}): void {
|
||||
if (props.projectName === "" || props.projectName === props.newProjectName) {
|
||||
alert("You have to give a new name\n\nName not changed");
|
||||
return;
|
||||
}
|
||||
api
|
||||
.changeProjectName(
|
||||
props.projectName,
|
||||
props.newProjectName,
|
||||
localStorage.getItem("accessToken") ?? "",
|
||||
)
|
||||
.then((response: APIResponse<string>) => {
|
||||
if (response.success) {
|
||||
alert("Name changed successfully");
|
||||
location.reload();
|
||||
} else {
|
||||
alert("Name not changed, name could be taken");
|
||||
console.error(response.message);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
alert("Name not changed");
|
||||
console.error("An error occurred during change:", error);
|
||||
});
|
||||
}
|
|
@ -1,37 +0,0 @@
|
|||
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);
|
||||
});
|
||||
}
|
|
@ -1,76 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import Button from "./Button";
|
||||
import ChangeRole, { ProjectRoleChange } from "./ChangeRole";
|
||||
|
||||
export default function ChangeRoleView(props: {
|
||||
projectName: string;
|
||||
username: string;
|
||||
currentRole: 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 => {
|
||||
console.log("Cur: " + props.currentRole + " " + "new: " + selectedRole);
|
||||
event.preventDefault();
|
||||
if (selectedRole === props.currentRole) {
|
||||
alert(`Already ${props.currentRole}, nothing changed`);
|
||||
return;
|
||||
}
|
||||
const roleChangeInfo: ProjectRoleChange = {
|
||||
username: props.username,
|
||||
projectname: props.projectName,
|
||||
role: selectedRole,
|
||||
};
|
||||
ChangeRole(roleChangeInfo);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="overflow-auto">
|
||||
<h1 className="font-bold text-[20px]">Select role:</h1>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="py-1 px-1 w-full self-start text-left font-medium overflow-auto border-2 border-black rounded-2xl">
|
||||
<label className="hover:cursor-pointer hover:font-bold">
|
||||
<input
|
||||
type="radio"
|
||||
value="project_manager"
|
||||
checked={selectedRole === "project_manager"}
|
||||
onChange={handleRoleChange}
|
||||
className="m-2"
|
||||
/>
|
||||
Project manager
|
||||
</label>
|
||||
<br />
|
||||
<label className="hover:cursor-pointer hover:font-bold">
|
||||
<input
|
||||
type="radio"
|
||||
value="member"
|
||||
checked={selectedRole === "member"}
|
||||
onChange={handleRoleChange}
|
||||
className="m-2 hover:cursor-pointer"
|
||||
/>
|
||||
Member
|
||||
</label>
|
||||
</div>
|
||||
<Button
|
||||
text="Change"
|
||||
onClick={(): void => {
|
||||
return;
|
||||
}}
|
||||
type="submit"
|
||||
/>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
|
@ -1,83 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import Button from "./Button";
|
||||
|
||||
export default function ChangeRoles(): JSX.Element {
|
||||
const [selectedRole, setSelectedRole] = useState("");
|
||||
const { username } = useParams();
|
||||
|
||||
const handleRoleChange = (
|
||||
event: React.ChangeEvent<HTMLInputElement>,
|
||||
): void => {
|
||||
setSelectedRole(event.target.value);
|
||||
};
|
||||
|
||||
// const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
// event.preventDefault();
|
||||
|
||||
// const response = await api.changeRole(username, selectedRole, token);
|
||||
// if (response.success) {
|
||||
// console.log("Role changed successfully");
|
||||
// } else {
|
||||
// console.error("Failed to change role:", response.message);
|
||||
// }
|
||||
// };
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className="font-bold text-[30px] mb-[20px]">
|
||||
Change roll for: {username}
|
||||
</h1>
|
||||
<form
|
||||
className="text-[20px] font-bold border-4 border-black bg-white flex flex-col items-center justify-center min-h-[50vh] h-fit w-[30vw] rounded-3xl content-center overflow-scroll space-y-[10vh] p-[30px]"
|
||||
onSubmit={undefined}
|
||||
>
|
||||
<div className="self-start">
|
||||
<div>
|
||||
<label>
|
||||
<input
|
||||
type="radio"
|
||||
value="System Manager"
|
||||
checked={selectedRole === "System Manager"}
|
||||
onChange={handleRoleChange}
|
||||
className="ml-2 mr-2 mb-6"
|
||||
/>
|
||||
System Manager
|
||||
</label>
|
||||
</div>
|
||||
<div>
|
||||
<label>
|
||||
<input
|
||||
type="radio"
|
||||
value="Developer"
|
||||
checked={selectedRole === "Developer"}
|
||||
onChange={handleRoleChange}
|
||||
className="ml-2 mr-2 mb-6"
|
||||
/>
|
||||
Developer
|
||||
</label>
|
||||
</div>
|
||||
<div>
|
||||
<label>
|
||||
<input
|
||||
type="radio"
|
||||
value="Tester"
|
||||
checked={selectedRole === "Tester"}
|
||||
onChange={handleRoleChange}
|
||||
className="ml-2 mr-2 mb-6"
|
||||
/>
|
||||
Tester
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
text="Save"
|
||||
onClick={(): void => {
|
||||
return;
|
||||
}}
|
||||
type="submit"
|
||||
/>
|
||||
</form>
|
||||
</>
|
||||
);
|
||||
}
|
|
@ -1,36 +0,0 @@
|
|||
import { APIResponse, api } from "../API/API";
|
||||
|
||||
/**
|
||||
* Changes the password of a user
|
||||
* @param {string} props.username - The username of the user
|
||||
* @param {string} props.newPassword - The new password
|
||||
* @returns {void} - Nothing
|
||||
*/
|
||||
export default function ChangeUserPassword(props: {
|
||||
username: string;
|
||||
newPassword: string;
|
||||
}): void {
|
||||
if (props.username === localStorage.getItem("username")) {
|
||||
alert("You cannot change admin password");
|
||||
return;
|
||||
}
|
||||
api
|
||||
.changeUserPassword(
|
||||
props.username,
|
||||
props.newPassword,
|
||||
localStorage.getItem("accessToken") ?? "",
|
||||
)
|
||||
.then((response: APIResponse<string>) => {
|
||||
if (response.success) {
|
||||
alert("Password changed successfully");
|
||||
location.reload();
|
||||
} else {
|
||||
alert("Password not changed");
|
||||
console.error(response.message);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
alert("Password not changed");
|
||||
console.error("An error occurred during change:", error);
|
||||
});
|
||||
}
|
|
@ -1,33 +0,0 @@
|
|||
import { APIResponse, api } from "../API/API";
|
||||
import { StrNameChange } from "../Types/goTypes";
|
||||
|
||||
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;
|
||||
}
|
||||
if (props.nameChange.prevName === localStorage.getItem("username")) {
|
||||
alert("You cannot change admin name");
|
||||
return;
|
||||
}
|
||||
api
|
||||
.changeUserName(props.nameChange, localStorage.getItem("accessToken") ?? "")
|
||||
.then((response: APIResponse<void>) => {
|
||||
if (response.success) {
|
||||
alert("Name changed successfully");
|
||||
location.reload();
|
||||
} else {
|
||||
alert("Name not changed, name could be taken");
|
||||
console.error(response.message);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
alert("Name not changed");
|
||||
console.error("An error occurred during change:", error);
|
||||
});
|
||||
}
|
||||
|
||||
export default ChangeUsername;
|
38
frontend/src/Components/CountButton.tsx
Normal file
38
frontend/src/Components/CountButton.tsx
Normal file
|
@ -0,0 +1,38 @@
|
|||
import { useState, useEffect } from "react";
|
||||
|
||||
// Interface for the response from the server
|
||||
// This should eventually reside in a dedicated file
|
||||
interface CountResponse {
|
||||
pressCount: number;
|
||||
}
|
||||
|
||||
// Some constants for the button
|
||||
const BUTTON_ENDPOINT = "/api/button";
|
||||
|
||||
// A simple button that counts how many times it's been pressed
|
||||
export function CountButton(): JSX.Element {
|
||||
const [count, setCount] = useState<number>(NaN);
|
||||
|
||||
// useEffect with a [] dependency array runs only once
|
||||
useEffect(() => {
|
||||
async function getCount(): Promise<void> {
|
||||
const response = await fetch(BUTTON_ENDPOINT);
|
||||
const data = (await response.json()) as CountResponse;
|
||||
setCount(data.pressCount);
|
||||
}
|
||||
void getCount();
|
||||
}, []);
|
||||
|
||||
// This is what runs on every button click
|
||||
function press(): void {
|
||||
async function pressPost(): Promise<void> {
|
||||
const response = await fetch(BUTTON_ENDPOINT, { method: "POST" });
|
||||
const data = (await response.json()) as CountResponse;
|
||||
setCount(data.pressCount);
|
||||
}
|
||||
void pressPost();
|
||||
}
|
||||
|
||||
// Return some JSX with the button and associated handler
|
||||
return <button onClick={press}>count is {count}</button>;
|
||||
}
|
|
@ -1,33 +0,0 @@
|
|||
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;
|
|
@ -1,37 +0,0 @@
|
|||
import { User } from "../Types/goTypes";
|
||||
import { api, APIResponse } from "../API/API";
|
||||
|
||||
/**
|
||||
* Use to remove a user from the system
|
||||
* @param {string} props.usernameToDelete - The username of user to remove
|
||||
* @returns {boolean} True if removed, false if not
|
||||
* @example
|
||||
* const exampleUsername = "user";
|
||||
* DeleteUser({ usernameToDelete: exampleUsername });
|
||||
*/
|
||||
|
||||
function DeleteUser(props: { usernameToDelete: string }): boolean {
|
||||
let removed = false;
|
||||
api
|
||||
.removeUser(
|
||||
props.usernameToDelete,
|
||||
localStorage.getItem("accessToken") ?? "",
|
||||
)
|
||||
.then((response: APIResponse<User>) => {
|
||||
if (response.success) {
|
||||
alert("User has been deleted!");
|
||||
location.reload();
|
||||
removed = true;
|
||||
} else {
|
||||
alert("User has not been deleted");
|
||||
console.error(response.message);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
alert("User has not been deleted");
|
||||
console.error("An error occurred during deletion:", error);
|
||||
});
|
||||
return removed;
|
||||
}
|
||||
|
||||
export default DeleteUser;
|
|
@ -1,82 +0,0 @@
|
|||
import { useState, useEffect } from "react";
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { api } from "../API/API";
|
||||
import { WeeklyReport } from "../Types/goTypes";
|
||||
|
||||
function DisplayUserProject(): JSX.Element {
|
||||
const { projectName } = useParams();
|
||||
const [unsignedReports, setUnsignedReports] = useState<WeeklyReport[]>([]);
|
||||
const [usernames, setUsernames] = useState<string[]>([]);
|
||||
const token = localStorage.getItem("accessToken") ?? "";
|
||||
|
||||
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();
|
||||
}, [projectName, token]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className="font-bold text-[30px] mb-[20px]">
|
||||
All Unsigned Reports In: {projectName}{" "}
|
||||
</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]">
|
||||
{unsignedReports.map((unsignedReport: WeeklyReport, index: number) => (
|
||||
<h1 key={index} className="border-b-2 border-black w-full">
|
||||
<div className="flex justify-between">
|
||||
<div className="flex">
|
||||
<span className="ml-6 mr-2 font-bold">Username:</span>
|
||||
<h1>{usernames[index]}</h1>{" "}
|
||||
<span className="ml-6 mr-2 font-bold">Week:</span>
|
||||
<h1>{unsignedReport.week}</h1>
|
||||
<span className="ml-6 mr-2 font-bold">Total Time:</span>
|
||||
<h1>
|
||||
{unsignedReport.developmentTime +
|
||||
unsignedReport.meetingTime +
|
||||
unsignedReport.adminTime +
|
||||
unsignedReport.ownWorkTime +
|
||||
unsignedReport.studyTime +
|
||||
unsignedReport.testingTime}
|
||||
</h1>
|
||||
<span className="ml-6 mr-2 font-bold">Signed:</span>
|
||||
<h1>NO</h1>
|
||||
</div>
|
||||
<div className="flex">
|
||||
<div className="ml-auto flex space-x-4">
|
||||
<Link
|
||||
to={`/PMViewUnsignedReport/${projectName}/${usernames[index]}/${unsignedReport.week}`}
|
||||
>
|
||||
<h1 className="cursor-pointer font-bold hover:font-extrabold hover:underline">
|
||||
View Report
|
||||
</h1>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</h1>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default DisplayUserProject;
|
|
@ -1,58 +0,0 @@
|
|||
import { useState } from "react";
|
||||
import { Project } from "../Types/goTypes";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import GetProjects from "./GetProjects";
|
||||
import { api } from "../API/API";
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
const navigate = useNavigate();
|
||||
|
||||
GetProjects({
|
||||
setProjectsProp: setProjects,
|
||||
username: localStorage.getItem("username") ?? "",
|
||||
});
|
||||
|
||||
const handleProjectClick = async (projectName: string): Promise<void> => {
|
||||
const token = localStorage.getItem("accessToken") ?? "";
|
||||
const response = await api.checkIfProjectManager(projectName, token);
|
||||
console.log(response.data);
|
||||
if (response.success) {
|
||||
if (
|
||||
(response.data as unknown as { isProjectManager: boolean })
|
||||
.isProjectManager
|
||||
) {
|
||||
navigate(`/PMProjectPage/${projectName}`);
|
||||
} else {
|
||||
navigate(`/project/${projectName}`);
|
||||
}
|
||||
} else {
|
||||
// handle error
|
||||
console.error(response.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className="font-bold text-[30px] mb-[20px]">Your Projects</h1>
|
||||
<div className="border-4 border-black bg-white flex flex-col items-center justify-center min-h-[65vh] h-fit w-[50vw] rounded-3xl content-center overflow-scroll space-y-[10vh] p-[30px]">
|
||||
{projects.map((project) => (
|
||||
<div
|
||||
onClick={() => void handleProjectClick(project.name)}
|
||||
key={project.id}
|
||||
>
|
||||
<h1 className="font-bold hover:underline text-[30px] cursor-pointer hover:font-extrabold">
|
||||
{project.name}
|
||||
</h1>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default DisplayUserProject;
|
|
@ -1,343 +0,0 @@
|
|||
import { useState, useEffect } from "react";
|
||||
import { WeeklyReport, UpdateWeeklyReport } from "../Types/goTypes";
|
||||
import { api } from "../API/API";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import Button from "./Button";
|
||||
|
||||
/**
|
||||
* Renders the component for editing a weekly report.
|
||||
* @returns JSX.Element
|
||||
*/
|
||||
export default function GetWeeklyReport(): JSX.Element {
|
||||
const [week, setWeek] = useState(0);
|
||||
const [developmentTime, setDevelopmentTime] = useState(0);
|
||||
const [meetingTime, setMeetingTime] = useState(0);
|
||||
const [adminTime, setAdminTime] = useState(0);
|
||||
const [ownWorkTime, setOwnWorkTime] = useState(0);
|
||||
const [studyTime, setStudyTime] = useState(0);
|
||||
const [testingTime, setTestingTime] = useState(0);
|
||||
|
||||
const token = localStorage.getItem("accessToken") ?? "";
|
||||
const { projectName, fetchedWeek, signedOrUnsigned } = useParams<{
|
||||
projectName: string;
|
||||
fetchedWeek: string;
|
||||
signedOrUnsigned: string;
|
||||
}>();
|
||||
const username = localStorage.getItem("userName") ?? "";
|
||||
console.log(projectName, fetchedWeek, signedOrUnsigned);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchWeeklyReport = async (): Promise<void> => {
|
||||
const response = await api.getWeeklyReport(
|
||||
projectName ?? "",
|
||||
fetchedWeek ?? "",
|
||||
token,
|
||||
);
|
||||
|
||||
if (response.success) {
|
||||
const report: WeeklyReport = response.data ?? {
|
||||
reportId: 0,
|
||||
userId: 0,
|
||||
projectId: 0,
|
||||
week: 0,
|
||||
developmentTime: 0,
|
||||
meetingTime: 0,
|
||||
adminTime: 0,
|
||||
ownWorkTime: 0,
|
||||
studyTime: 0,
|
||||
testingTime: 0,
|
||||
};
|
||||
setWeek(report.week);
|
||||
setDevelopmentTime(report.developmentTime);
|
||||
setMeetingTime(report.meetingTime);
|
||||
setAdminTime(report.adminTime);
|
||||
setOwnWorkTime(report.ownWorkTime);
|
||||
setStudyTime(report.studyTime);
|
||||
setTestingTime(report.testingTime);
|
||||
} else {
|
||||
console.error("Failed to fetch weekly report:", response.message);
|
||||
}
|
||||
};
|
||||
|
||||
void fetchWeeklyReport();
|
||||
}, [projectName, fetchedWeek, signedOrUnsigned, token]);
|
||||
|
||||
const handleUpdateWeeklyReport = async (): Promise<void> => {
|
||||
const updateWeeklyReport: UpdateWeeklyReport = {
|
||||
userName: username,
|
||||
projectName: projectName ?? "",
|
||||
week,
|
||||
developmentTime,
|
||||
meetingTime,
|
||||
adminTime,
|
||||
ownWorkTime,
|
||||
studyTime,
|
||||
testingTime,
|
||||
};
|
||||
|
||||
await api.updateWeeklyReport(updateWeeklyReport, token);
|
||||
};
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1 className="font-bold text-[30px] mb-[20px]">Edit Time 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">
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
if (week === 0) {
|
||||
alert("Please enter a week number");
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
e.preventDefault();
|
||||
void handleUpdateWeeklyReport();
|
||||
alert("Changes submitted");
|
||||
navigate(-1);
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="flex flex-col w-1/2 border-b-2 border-black items-center justify-center">
|
||||
<h1 className="font-bold text-[30px]"> Week: {week}</h1>
|
||||
</div>
|
||||
|
||||
<table className="w-full text-center divide-y divide-x divide-white text-[30px]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="w-1/2 py-2 border-b-2 border-black">
|
||||
Activity
|
||||
</th>
|
||||
<th className="w-1/2 py-2 border-b-2 border-black">
|
||||
Total Time (min)
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-black">
|
||||
<tr className="h-[10vh]">
|
||||
<td>Development</td>
|
||||
<td>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
className="border-2 border-black rounded-md text-center w-1/2"
|
||||
value={developmentTime === 0 ? "" : developmentTime}
|
||||
onChange={(e) => {
|
||||
if (e.target.value === "") {
|
||||
setDevelopmentTime(0);
|
||||
return;
|
||||
} else {
|
||||
setDevelopmentTime(parseInt(e.target.value));
|
||||
}
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
const keyValue = event.key;
|
||||
if (
|
||||
!/\d/.test(keyValue) &&
|
||||
keyValue !== "Backspace" &&
|
||||
keyValue !== "ArrowLeft" &&
|
||||
keyValue !== "ArrowRight"
|
||||
)
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
if (signedOrUnsigned === "signed") {
|
||||
alert("You cannot edit a signed report.");
|
||||
}
|
||||
}}
|
||||
readOnly={signedOrUnsigned === "signed"}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
<tr className="h-[10vh]">
|
||||
<td>Meeting</td>
|
||||
<td>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
className="border-2 border-black rounded-md text-center w-1/2"
|
||||
value={meetingTime === 0 ? "" : meetingTime}
|
||||
onChange={(e) => {
|
||||
if (e.target.value === "") {
|
||||
setMeetingTime(0);
|
||||
return;
|
||||
} else {
|
||||
setMeetingTime(parseInt(e.target.value));
|
||||
}
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
const keyValue = event.key;
|
||||
if (
|
||||
!/\d/.test(keyValue) &&
|
||||
keyValue !== "Backspace" &&
|
||||
keyValue !== "ArrowLeft" &&
|
||||
keyValue !== "ArrowRight"
|
||||
)
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
if (signedOrUnsigned === "signed") {
|
||||
alert("You cannot edit a signed report.");
|
||||
}
|
||||
}}
|
||||
readOnly={signedOrUnsigned === "signed"}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
<tr className="h-[10vh]">
|
||||
<td>Administration</td>
|
||||
<td>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
className="border-2 border-black rounded-md text-center w-1/2"
|
||||
value={adminTime === 0 ? "" : adminTime}
|
||||
onChange={(e) => {
|
||||
if (e.target.value === "") {
|
||||
setAdminTime(0);
|
||||
return;
|
||||
} else {
|
||||
setAdminTime(parseInt(e.target.value));
|
||||
}
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
const keyValue = event.key;
|
||||
if (
|
||||
!/\d/.test(keyValue) &&
|
||||
keyValue !== "Backspace" &&
|
||||
keyValue !== "ArrowLeft" &&
|
||||
keyValue !== "ArrowRight"
|
||||
)
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
if (signedOrUnsigned === "signed") {
|
||||
alert("You cannot edit a signed report.");
|
||||
}
|
||||
}}
|
||||
readOnly={signedOrUnsigned === "signed"}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
<tr className="h-[10vh]">
|
||||
<td>Own Work</td>
|
||||
<td>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
className="border-2 border-black rounded-md text-center w-1/2"
|
||||
value={ownWorkTime === 0 ? "" : ownWorkTime}
|
||||
onChange={(e) => {
|
||||
if (e.target.value === "") {
|
||||
setOwnWorkTime(0);
|
||||
return;
|
||||
} else {
|
||||
setOwnWorkTime(parseInt(e.target.value));
|
||||
}
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
const keyValue = event.key;
|
||||
if (
|
||||
!/\d/.test(keyValue) &&
|
||||
keyValue !== "Backspace" &&
|
||||
keyValue !== "ArrowLeft" &&
|
||||
keyValue !== "ArrowRight"
|
||||
)
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
if (signedOrUnsigned === "signed") {
|
||||
alert("You cannot edit a signed report.");
|
||||
}
|
||||
}}
|
||||
readOnly={signedOrUnsigned === "signed"}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
<tr className="h-[10vh]">
|
||||
<td>Studies</td>
|
||||
<td>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
className="border-2 border-black rounded-md text-center w-1/2"
|
||||
value={studyTime === 0 ? "" : studyTime}
|
||||
onChange={(e) => {
|
||||
if (e.target.value === "") {
|
||||
setStudyTime(0);
|
||||
return;
|
||||
} else {
|
||||
setStudyTime(parseInt(e.target.value));
|
||||
}
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
const keyValue = event.key;
|
||||
if (
|
||||
!/\d/.test(keyValue) &&
|
||||
keyValue !== "Backspace" &&
|
||||
keyValue !== "ArrowLeft" &&
|
||||
keyValue !== "ArrowRight"
|
||||
)
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
if (signedOrUnsigned === "signed") {
|
||||
alert("You cannot edit a signed report.");
|
||||
}
|
||||
}}
|
||||
readOnly={signedOrUnsigned === "signed"}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
<tr className="h-[10vh]">
|
||||
<td>Testing</td>
|
||||
<td>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
className="border-2 border-black rounded-md text-center w-1/2"
|
||||
value={testingTime === 0 ? "" : testingTime}
|
||||
onChange={(e) => {
|
||||
if (e.target.value === "") {
|
||||
setTestingTime(0);
|
||||
return;
|
||||
} else {
|
||||
setTestingTime(parseInt(e.target.value));
|
||||
}
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
const keyValue = event.key;
|
||||
if (
|
||||
!/\d/.test(keyValue) &&
|
||||
keyValue !== "Backspace" &&
|
||||
keyValue !== "ArrowLeft" &&
|
||||
keyValue !== "ArrowRight"
|
||||
)
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
if (signedOrUnsigned === "signed") {
|
||||
alert("You cannot edit a signed report.");
|
||||
}
|
||||
}}
|
||||
readOnly={signedOrUnsigned === "signed"}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
{signedOrUnsigned !== "signed" && (
|
||||
<Button
|
||||
text="Submit changes"
|
||||
onClick={(): void => {
|
||||
return;
|
||||
}}
|
||||
type="submit"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue