hour-tracker/back-end/main.go
2025-01-24 20:10:06 +02:00

80 lines
2 KiB
Go

package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/labstack/echo/v5"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/models"
)
type Entry struct {
Start string
End string
}
func main() {
app := pocketbase.New()
app.OnBeforeServe().Add(func(e *core.ServeEvent) error {
e.Router.GET("/hours/:organisation/:year/:month", func(c echo.Context) error {
year := c.PathParam("year")
month := c.PathParam("month")
organisation := c.PathParam("organisation")
entries := []Entry{}
record, _ := c.Get(apis.ContextAuthRecordKey).(*models.Record)
if record == nil {
return c.JSON(http.StatusOK, map[string]any{"hours": 0, "error": "not logged in"})
}
err := app.Dao().DB().
NewQuery("SELECT * FROM entries WHERE user = {:user} AND start >= {:start} AND end <= {:end} AND end != '' AND project IN (SELECT id FROM projects WHERE organisation = {:organisation})").
Bind(dbx.Params{
"start": fmt.Sprintf("%s-%s-01 00:00:00.000Z", year, month),
"end": fmt.Sprintf("%s-%s-31 23:59:59.999Z", year, month),
"organisation": organisation,
"user": record.Id,
}).
All(&entries)
if err != nil {
return c.JSON(http.StatusOK, map[string]any{"hours": 0, "error": err})
}
hours := 0.0
for _, e := range entries {
start, err := time.Parse("2006-01-02 15:04:05.000Z", e.Start)
if err != nil {
return c.JSON(http.StatusOK, map[string]any{"hours": 0, "error": fmt.Sprintf("time.Parse(%s)", e.Start)})
}
end, err := time.Parse("2006-01-02 15:04:05.000Z", e.End)
if err != nil {
return c.JSON(http.StatusOK, map[string]any{"hours": 0, "error": fmt.Sprintf("time.Parse(%s)", e.End)})
}
hours = hours + end.Sub(start).Hours()
}
return c.JSON(http.StatusOK, map[string]any{"hours": hours, "error": nil})
})
return nil
})
if err := app.Start(); err != nil {
log.Fatal(err)
}
}