phoenix/views/groups.go

71 lines
1.7 KiB
Go
Raw Normal View History

2023-04-09 11:22:48 +05:00
package views
import (
"fmt"
2023-04-09 11:22:48 +05:00
"github.com/gin-gonic/gin"
2023-11-01 23:18:33 +05:00
"github.com/ordinary-dev/phoenix/config"
2023-07-22 15:24:01 +05:00
"github.com/ordinary-dev/phoenix/database"
2023-04-09 11:22:48 +05:00
"gorm.io/gorm"
"net/http"
2023-04-09 11:55:08 +05:00
"strconv"
2023-04-09 11:22:48 +05:00
)
2023-11-01 23:18:33 +05:00
func CreateGroup(cfg *config.Config, db *gorm.DB) gin.HandlerFunc {
2023-11-01 22:40:15 +05:00
return func(ctx *gin.Context) {
// Save new group to the database.
group := database.Group{
Name: ctx.PostForm("groupName"),
}
if result := db.Create(&group); result.Error != nil {
2023-11-01 23:18:33 +05:00
ShowError(ctx, cfg, result.Error)
2023-11-01 22:40:15 +05:00
return
}
2023-04-09 11:22:48 +05:00
2023-11-01 22:40:15 +05:00
// This page is called from the settings, return the user back.
ctx.Redirect(http.StatusFound, fmt.Sprintf("/settings#group-%v", group.ID))
2023-11-01 22:40:15 +05:00
}
2023-04-09 11:22:48 +05:00
}
2023-04-09 11:55:08 +05:00
2023-11-01 23:18:33 +05:00
func UpdateGroup(cfg *config.Config, db *gorm.DB) gin.HandlerFunc {
2023-11-01 22:40:15 +05:00
return func(ctx *gin.Context) {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
2023-11-01 23:18:33 +05:00
ShowError(ctx, cfg, err)
2023-11-01 22:40:15 +05:00
return
}
2023-11-01 22:40:15 +05:00
var group database.Group
if result := db.First(&group, id); result.Error != nil {
2023-11-01 23:18:33 +05:00
ShowError(ctx, cfg, result.Error)
2023-11-01 22:40:15 +05:00
return
}
2023-11-01 22:40:15 +05:00
group.Name = ctx.PostForm("groupName")
if result := db.Save(&group); result.Error != nil {
2023-11-01 23:18:33 +05:00
ShowError(ctx, cfg, result.Error)
2023-11-01 22:40:15 +05:00
return
}
2023-04-09 11:55:08 +05:00
2023-11-01 22:40:15 +05:00
// This page is called from the settings, return the user back.
ctx.Redirect(http.StatusFound, fmt.Sprintf("/settings#group-%v", group.ID))
2023-11-01 22:40:15 +05:00
}
2023-04-09 11:55:08 +05:00
}
2023-11-01 23:18:33 +05:00
func DeleteGroup(cfg *config.Config, db *gorm.DB) gin.HandlerFunc {
2023-11-01 22:40:15 +05:00
return func(ctx *gin.Context) {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
2023-11-01 23:18:33 +05:00
ShowError(ctx, cfg, err)
2023-11-01 22:40:15 +05:00
return
}
2023-04-09 11:55:08 +05:00
2023-11-01 22:40:15 +05:00
if result := db.Delete(&database.Group{}, id); result.Error != nil {
2023-11-01 23:18:33 +05:00
ShowError(ctx, cfg, result.Error)
2023-11-01 22:40:15 +05:00
return
}
2023-04-09 11:55:08 +05:00
2023-11-01 22:40:15 +05:00
// Redirect to settings.
ctx.Redirect(http.StatusFound, "/settings")
}
2023-04-09 11:55:08 +05:00
}