notatio/tables.go

115 lines
2.5 KiB
Go
Raw Normal View History

2023-11-21 04:10:40 +00:00
package main
import (
"encoding/json"
"log"
"net/http"
"time"
)
type Task struct {
ID int
Title string
Description string
Status string
}
func kanban(w http.ResponseWriter, r *http.Request) {
userSession, err := validateSession(w, r)
if err != nil {
handleError(w, "Error validating session", err)
return
}
if r.Method == "GET" {
var tasks []Task
rows, err := db.Query("SELECT id, title, description, status FROM tasks")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer rows.Close()
for rows.Next() {
var task Task
err := rows.Scan(&task.ID, &task.Title, &task.Description, &task.Status)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tasks = append(tasks, task)
}
err = rows.Err()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data := struct {
Tasks []Task
}{
Tasks: tasks,
}
renderTemplate(w, "kanban.html", data)
} else if r.Method == "POST" {
title := r.FormValue("title")
description := r.FormValue("description")
status := r.FormValue("status")
_, err := db.Exec("INSERT INTO tasks (title, description, status, owner,date) VALUES ($1, $2, $3, $4, $5)", title, description, status, userSession.username, time.Now())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/kanban", http.StatusSeeOther)
}
}
func createTableDB() {
// Create Task Table
createTaskTable := `
CREATE TABLE IF NOT EXISTS tasks (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
description TEXT NOT NULL,
status TEXT NOT NULL,
owner TEXT NOT NULL,
date TIMESTAMP NOT NULL
);`
_, err := db.Exec(createTaskTable)
if err != nil {
log.Fatal(err)
}
}
func updateTaskStatus(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
var task struct {
ID int `json:"id"`
Status string `json:"status"`
}
err := json.NewDecoder(r.Body).Decode(&task)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Update the task status in the database
_, err = db.Exec("UPDATE tasks SET status = $1 WHERE id = $2", task.Status, task.ID)
if err != nil {
log.Println("Error updating task status:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Return a success response
w.WriteHeader(http.StatusOK)
} else {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
}
}