Files
pages/internal/server/city_autoplan.go
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

185 lines
6.2 KiB
Go

package server
import (
"crypto/sha256"
"database/sql"
"encoding/hex"
"errors"
"fmt"
"net/url"
"path"
"strings"
)
type cityAutoPlanItem struct {
Path string `json:"path"`
PageUUID string `json:"page_uuid"`
Quartier, Street, Spot string
QuartierPath, StreetPath, SpotPath string `json:",omitempty"`
Undefined bool `json:"undefined_spot"`
Action string `json:"action"`
}
func cityAutoName(raw, prefix string) string {
decoded, err := url.PathUnescape(raw)
if err == nil {
raw = decoded
}
name := citySuggestionName(raw)
if len(name) >= 2 {
return name
}
sum := sha256.Sum256([]byte(raw))
return prefix + "-" + hex.EncodeToString(sum[:4])
}
// Names are identifiers, not ownership. In particular Spot names are unique
// across the entire Domain, even when their Streets differ.
func (s *Server) availableCityAutoName(domain, kind, parent, base, boundary string) (string, error) {
for attempt := 0; attempt < 32; attempt++ {
name := base
if attempt > 0 {
sum := sha256.Sum256([]byte(fmt.Sprintf("%s:%s:%d", kind, boundary, attempt)))
stem := base
if len(stem) > 47 {
stem = stem[:47]
}
name = stem + "-" + hex.EncodeToString(sum[:8])
}
var exists bool
var err error
if kind == "spot" {
err = s.store.DB.QueryRow(`SELECT EXISTS(SELECT 1 FROM spots WHERE domain_uuid=? AND name=? AND state!='archived')`, domain, name).Scan(&exists)
} else if kind == "quartier" {
err = s.store.DB.QueryRow(`SELECT EXISTS(SELECT 1 FROM zones WHERE domain_uuid=? AND kind='quartier' AND name=? AND state!='archived')`, domain, name).Scan(&exists)
} else {
err = s.store.DB.QueryRow(`SELECT EXISTS(SELECT 1 FROM zones WHERE domain_uuid=? AND parent_uuid=? AND name=? AND state!='archived')`, domain, parent, name).Scan(&exists)
}
if err != nil {
return "", err
}
if !exists {
return name, nil
}
}
return "", errors.New("unable to allocate unique generated City name")
}
func (s *Server) buildCityAutoPlan(domainUUID string) ([]cityAutoPlanItem, error) {
rows, err := s.store.DB.Query(`SELECT p.path,p.object_uuid FROM paths p WHERE p.domain_uuid=? AND p.path LIKE '/%' AND p.path!='/u' AND p.path NOT LIKE '/u/%'
AND NOT EXISTS(SELECT 1 FROM city_page_overrides ov JOIN spots dest ON dest.uuid=ov.spot_uuid AND dest.domain_uuid=ov.domain_uuid AND dest.state!='archived' WHERE ov.domain_uuid=p.domain_uuid AND ov.page_uuid=p.object_uuid)
ORDER BY p.path`, domainUUID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []cityAutoPlanItem
for rows.Next() {
var semanticPath, pageUUID string
if err := rows.Scan(&semanticPath, &pageUUID); err != nil {
return nil, err
}
parts := strings.Split(strings.Trim(semanticPath, "/"), "/")
if len(parts) < 3 || parts[0] == "system" {
continue
}
item := cityAutoPlanItem{Path: semanticPath, PageUUID: pageUUID, Quartier: cityAutoName(parts[0], "quartier"), Street: cityAutoName(parts[1], "street"), QuartierPath: "/" + parts[0], StreetPath: "/" + parts[0] + "/" + parts[1]}
if len(parts) >= 4 {
item.Spot = cityAutoName(parts[2], "spot")
item.SpotPath = item.StreetPath + "/" + parts[2]
} else {
item.Undefined = true
item.Spot = item.Street + "-undefined"
item.SpotPath = item.StreetPath + "/_undefined"
}
item.Action = "create"
if q, e := s.store.CityNodeOverlappingPath(domainUUID, "quartier", "", item.QuartierPath); e == nil {
item.Quartier = q.Name
item.Action = "merge"
if st, e := s.store.CityNodeOverlappingPath(domainUUID, "street", q.UUID, item.StreetPath); e == nil {
item.Street = st.Name
if spot, e := s.store.CityNodeOverlappingPath(domainUUID, "spot", st.UUID, item.SpotPath); e == nil {
item.Spot = spot.Name
}
}
}
out = append(out, item)
}
return out, rows.Err()
}
func (s *Server) applyCityAutoPlan(domainUUID, actor string) (int, error) {
plan, err := s.buildCityAutoPlan(domainUUID)
if err != nil {
return 0, err
}
quartiers, streets, spots := map[string]string{}, map[string]string{}, map[string]string{}
applied := 0
for _, item := range plan {
qID := quartiers[item.QuartierPath]
if qID == "" {
if q, e := s.store.CityNodeOverlappingPath(domainUUID, "quartier", "", item.QuartierPath); e == nil {
qID = q.UUID
} else {
if !errors.Is(e, sql.ErrNoRows) {
return applied, e
}
name, err := s.availableCityAutoName(domainUUID, "quartier", "", item.Quartier, item.QuartierPath)
if err != nil {
return applied, err
}
qID, e = s.store.CreateZoneAtPath(domainUUID, actor, "quartier", "", name, item.Quartier, "Generated from URL Paths", item.QuartierPath)
if e != nil {
return applied, e
}
}
quartiers[item.QuartierPath] = qID
}
streetKey := qID + item.StreetPath
streetID := streets[streetKey]
if streetID == "" {
if st, e := s.store.CityNodeOverlappingPath(domainUUID, "street", qID, item.StreetPath); e == nil {
streetID = st.UUID
} else {
if !errors.Is(e, sql.ErrNoRows) {
return applied, e
}
name, err := s.availableCityAutoName(domainUUID, "street", qID, item.Street, item.StreetPath)
if err != nil {
return applied, err
}
streetID, e = s.store.CreateZoneAtPath(domainUUID, actor, "street", qID, name, item.Street, "", item.StreetPath)
if e != nil {
return applied, e
}
}
streets[streetKey] = streetID
}
spotKey := streetID + item.SpotPath
spotID := spots[spotKey]
if spotID == "" {
if spot, e := s.store.CityNodeOverlappingPath(domainUUID, "spot", streetID, item.SpotPath); e == nil {
spotID = spot.UUID
} else {
if !errors.Is(e, sql.ErrNoRows) {
return applied, e
}
name, err := s.availableCityAutoName(domainUUID, "spot", streetID, item.Spot, item.SpotPath)
if err != nil {
return applied, err
}
spotID, e = s.store.CreateSpotAtPath(domainUUID, actor, streetID, name, item.Spot, "Generated from URL Paths", item.SpotPath)
if e != nil {
return applied, e
}
}
spots[spotKey] = spotID
}
if err := s.store.AddSpotPage(domainUUID, actor, spotID, item.PageUUID, item.Path, "primary", path.Base(item.Path)); err != nil && !errors.Is(err, sql.ErrNoRows) {
return applied, err
}
applied++
}
return applied, nil
}