camper/pkg/app/public.go

91 lines
2.4 KiB
Go

/*
* SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
* SPDX-License-Identifier: AGPL-3.0-only
*/
package app
import (
"context"
"net/http"
"dev.tandem.ws/tandem/camper/pkg/auth"
"dev.tandem.ws/tandem/camper/pkg/campsite"
"dev.tandem.ws/tandem/camper/pkg/database"
httplib "dev.tandem.ws/tandem/camper/pkg/http"
"dev.tandem.ws/tandem/camper/pkg/locale"
"dev.tandem.ws/tandem/camper/pkg/template"
)
type publicHandler struct {
campsite *campsite.PublicHandler
}
func newPublicHandler() *publicHandler {
return &publicHandler{
campsite: campsite.NewPublicHandler(),
}
}
func (h *publicHandler) Handler(user *auth.User, company *auth.Company, conn *database.Conn) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var head string
head, r.URL.Path = httplib.ShiftPath(r.URL.Path)
switch head {
case "":
home := newHomePage()
home.MustRender(w, r, user, company, conn)
case "campsites":
h.campsite.Handler(user, company, conn).ServeHTTP(w, r)
default:
http.NotFound(w, r)
}
})
}
type homePage struct {
*template.PublicPage
CampsiteTypes []*campsiteType
}
func newHomePage() *homePage {
return &homePage{template.NewPublicPage(), nil}
}
func (p *homePage) MustRender(w http.ResponseWriter, r *http.Request, user *auth.User, company *auth.Company, conn *database.Conn) {
p.Setup(r, user, company, conn)
p.CampsiteTypes = mustCollectCampsiteTypes(r.Context(), company, conn, user.Locale)
template.MustRenderPublic(w, r, user, company, "home.gohtml", p)
}
type campsiteType struct {
Label string
HRef string
Media string
}
func mustCollectCampsiteTypes(ctx context.Context, company *auth.Company, conn *database.Conn, loc *locale.Locale) []*campsiteType {
rows, err := conn.Query(ctx, "select name, '/campsites/types/' || slug, '/media/' || encode(hash, 'hex') || '/' || original_filename from campsite_type join media using (media_id) where campsite_type.company_id = $1 and campsite_type.active", company.ID)
if err != nil {
panic(err)
}
defer rows.Close()
localePath := "/" + loc.Language.String()
var items []*campsiteType
for rows.Next() {
item := &campsiteType{}
err = rows.Scan(&item.Label, &item.HRef, &item.Media)
if err != nil {
panic(err)
}
item.HRef = localePath + item.HRef
items = append(items, item)
}
if rows.Err() != nil {
panic(rows.Err())
}
return items
}