2024-04-29 08:36:13 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
// External
|
|
|
|
re "git.gibonuddevalla.se/go/wrappederror"
|
|
|
|
|
|
|
|
// Standard
|
|
|
|
"encoding/json"
|
|
|
|
"sort"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Area struct {
|
2024-05-01 21:02:45 +02:00
|
|
|
ID int
|
2024-04-29 08:36:13 +02:00
|
|
|
Name string
|
|
|
|
|
|
|
|
Sections []Section
|
|
|
|
}
|
|
|
|
|
2024-05-01 21:02:45 +02:00
|
|
|
func AreaRetrieve() (areas []Area, err error) { // {{{
|
2024-04-29 08:36:13 +02:00
|
|
|
areas = []Area{}
|
|
|
|
row := service.Db.Conn.QueryRow(`
|
|
|
|
SELECT
|
|
|
|
jsonb_agg(jsonsections)
|
|
|
|
FROM (
|
|
|
|
SELECT
|
|
|
|
a.id,
|
|
|
|
a.name,
|
|
|
|
jsonb_agg(
|
|
|
|
jsonb_build_object(
|
|
|
|
'id', s.id,
|
|
|
|
'name', s.name
|
|
|
|
)
|
|
|
|
) AS sections
|
|
|
|
FROM area a
|
2024-05-01 21:02:45 +02:00
|
|
|
LEFT JOIN section s ON s.area_id = a.id
|
2024-04-29 08:36:13 +02:00
|
|
|
GROUP BY
|
|
|
|
a.id, a.name
|
|
|
|
) jsonsections`,
|
|
|
|
)
|
|
|
|
|
|
|
|
var jsonData []byte
|
|
|
|
err = row.Scan(&jsonData)
|
|
|
|
if err != nil {
|
|
|
|
err = re.Wrap(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-05-01 21:44:53 +02:00
|
|
|
if jsonData == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-04-29 08:36:13 +02:00
|
|
|
err = json.Unmarshal(jsonData, &areas)
|
|
|
|
if err != nil {
|
|
|
|
err = re.Wrap(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-05-01 21:02:45 +02:00
|
|
|
return
|
|
|
|
} // }}}
|
|
|
|
func AreaCreate(name string) (err error) {// {{{
|
|
|
|
_, err = service.Db.Conn.Exec(`INSERT INTO area(name) VALUES($1)`, name)
|
|
|
|
return
|
|
|
|
}// }}}
|
|
|
|
func AreaRename(id int, name string) (err error) {// {{{
|
|
|
|
_, err = service.Db.Conn.Exec(`UPDATE area SET name=$2 WHERE id=$1`, id, name)
|
2024-04-29 08:36:13 +02:00
|
|
|
return
|
|
|
|
}// }}}
|
|
|
|
|
2024-05-01 21:02:45 +02:00
|
|
|
func (a Area) SortedSections() []Section { // {{{
|
|
|
|
sort.SliceStable(a.Sections, func(i, j int) bool {
|
2024-04-29 08:36:13 +02:00
|
|
|
return a.Sections[i].Name < a.Sections[j].Name
|
|
|
|
})
|
|
|
|
return a.Sections
|
2024-05-01 21:02:45 +02:00
|
|
|
} // }}}
|