2024-06-22 07:34:26 -07:00
|
|
|
package handlers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/go-playground/validator/v10"
|
|
|
|
"github.com/labstack/echo/v4"
|
2024-07-27 11:52:05 -07:00
|
|
|
"github.com/mikestefanello/backlite"
|
2024-07-09 17:57:05 -07:00
|
|
|
|
|
|
|
"git.grosinger.net/tgrosinger/saasitone/pkg/form"
|
|
|
|
"git.grosinger.net/tgrosinger/saasitone/pkg/msg"
|
|
|
|
"git.grosinger.net/tgrosinger/saasitone/pkg/page"
|
|
|
|
"git.grosinger.net/tgrosinger/saasitone/pkg/services"
|
|
|
|
"git.grosinger.net/tgrosinger/saasitone/pkg/tasks"
|
2024-07-17 19:58:58 -07:00
|
|
|
"git.grosinger.net/tgrosinger/saasitone/templ/layouts"
|
|
|
|
"git.grosinger.net/tgrosinger/saasitone/templ/pages"
|
2024-06-22 07:34:26 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
routeNameTask = "task"
|
|
|
|
routeNameTaskSubmit = "task.submit"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
Task struct {
|
2024-07-27 11:52:05 -07:00
|
|
|
tasks *backlite.Client
|
2024-06-22 07:34:26 -07:00
|
|
|
*services.TemplateRenderer
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
Register(new(Task))
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Task) Init(c *services.Container) error {
|
|
|
|
h.TemplateRenderer = c.TemplateRenderer
|
|
|
|
h.tasks = c.Tasks
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Task) Routes(g *echo.Group) {
|
|
|
|
g.GET("/task", h.Page).Name = routeNameTask
|
|
|
|
g.POST("/task", h.Submit).Name = routeNameTaskSubmit
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Task) Page(ctx echo.Context) error {
|
|
|
|
p := page.New(ctx)
|
|
|
|
p.Title = "Create a task"
|
2024-07-27 12:28:45 -07:00
|
|
|
p.LayoutComponent = layouts.Main
|
2024-06-22 07:34:26 -07:00
|
|
|
|
2024-07-17 19:58:58 -07:00
|
|
|
f := form.Get[pages.TaskForm](ctx)
|
|
|
|
component := pages.Task(p, f)
|
|
|
|
return h.RenderPageTempl(ctx, p, component)
|
2024-06-22 07:34:26 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Task) Submit(ctx echo.Context) error {
|
2024-07-17 19:58:58 -07:00
|
|
|
var input pages.TaskForm
|
2024-06-22 07:34:26 -07:00
|
|
|
|
|
|
|
err := form.Submit(ctx, &input)
|
|
|
|
|
|
|
|
switch err.(type) {
|
|
|
|
case nil:
|
|
|
|
case validator.ValidationErrors:
|
|
|
|
return h.Page(ctx)
|
|
|
|
default:
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Insert the task
|
2024-07-27 11:52:05 -07:00
|
|
|
err = h.tasks.
|
|
|
|
Add(tasks.ExampleTask{
|
|
|
|
Message: input.Message,
|
|
|
|
}).
|
2024-06-22 07:34:26 -07:00
|
|
|
Wait(time.Duration(input.Delay) * time.Second).
|
|
|
|
Save()
|
|
|
|
if err != nil {
|
|
|
|
return fail(err, "unable to create a task")
|
|
|
|
}
|
|
|
|
|
|
|
|
msg.Success(ctx, fmt.Sprintf("The task has been created. Check the logs in %d seconds.", input.Delay))
|
|
|
|
form.Clear(ctx)
|
|
|
|
|
|
|
|
return h.Page(ctx)
|
|
|
|
}
|