Files
pages/internal/store/city_organize.go
T
2026-11-15 05:47:14 +09:00

397 lines
16 KiB
Go

package store
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"path"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
)
var ErrCityChanged = errors.New("city_changed")
func (s *Store) cityMutationError(operation string, err error) error {
if err == nil || s.sqlBackend != storePostgreSQL {
return err
}
switch err.Error() {
case "city_invalid_title", "city_invalid_selection", "city_invalid_target", "city_too_many_pages", "city_too_many_relations", "city_name_conflict",
"city name must be 2-64 lowercase letters, digits, underscores, or hyphens",
"City Path boundaries of the same level must not overlap", "Street Path must be a strict descendant of its Quartier Path", "Spot Path must be a strict descendant of its Street Path":
return namespaceValidationError(err.Error())
}
return s.sqlError(operation, err)
}
type CityPageSelection struct {
SpotUUID string `json:"spot_uuid"`
PageUUID string `json:"page_uuid"`
}
type CityNewSpot struct {
StreetUUID string `json:"street_uuid"`
Name string `json:"name"`
Title string `json:"title"`
PathPrefix string `json:"path_prefix"`
}
type CityOrganizeRequest struct {
BaseVersion int64 `json:"base_version"`
Action string `json:"action"` // merge or move; neither moves document URLs
Spots []string `json:"spots"`
Pages []CityPageSelection `json:"pages"`
TargetSpotUUID string `json:"target_spot_uuid"`
NewSpot *CityNewSpot `json:"new_spot,omitempty"`
StreetUUID string `json:"street_uuid,omitempty"`
PathPrefix string `json:"path_prefix,omitempty"` // optional single-Spot move boundary
}
type CityOrganizeResult struct {
TargetSpotUUID string `json:"target_spot_uuid"`
Pages int `json:"pages"`
}
func (s *Store) checkCityVersion(tx *sql.Tx, domain string, expected int64) error {
var version int64 = 1
err := tx.QueryRow(`SELECT version FROM domain_topology_versions WHERE domain_uuid=`+s.sqlParam(1), domain).Scan(&version)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return err
}
if expected < 1 || expected != version {
return ErrCityChanged
}
return nil
}
func (s *Store) recordCityOrganize(tx *sql.Tx, domain, actor, operation, kind, id string, before, after any) error {
if err := s.bumpTopologyVersion(tx, domain, actor, operation, kind, id); err != nil {
return err
}
b, err := json.Marshal(before)
if err != nil {
return err
}
a, err := json.Marshal(after)
if err != nil {
return err
}
_, err = tx.Exec(`UPDATE topology_events SET before_json=`+s.sqlParam(1)+`,after_json=`+s.sqlParam(2)+` WHERE domain_uuid=`+s.sqlParam(3)+` AND topology_version=(SELECT version FROM domain_topology_versions WHERE domain_uuid=`+s.sqlParam(4)+`)`, string(b), string(a), domain, domain)
return err
}
// RenameCityTitle changes only the display title. UUIDs, name routes and Paths
// deliberately remain stable; renaming document URLs is a separate operation.
func (s *Store) RenameCityTitle(domain, actor, kind, id, title string, baseVersion int64) (resultErr error) {
defer func() { resultErr = s.cityMutationError("rename city title", resultErr) }()
title = strings.TrimSpace(title)
if title == "" || utf8.RuneCountInString(title) > 160 {
return errors.New("city_invalid_title")
}
if kind != "quartier" && kind != "street" && kind != "spot" {
return errors.New("city_invalid_selection")
}
tx, cancel, err := s.beginPathMutation(domain)
defer cancel()
if err != nil {
return err
}
defer tx.Rollback()
if err = s.checkCityVersion(tx, domain, baseVersion); err != nil {
return err
}
table, condition := "zones", " AND kind="+s.sqlParam(3)
args := []any{id, domain, kind}
if kind == "spot" {
table, condition, args = "spots", "", []any{id, domain}
}
var old string
if err = tx.QueryRow(`SELECT title FROM `+table+` WHERE uuid=`+s.sqlParam(1)+` AND domain_uuid=`+s.sqlParam(2)+` AND state!='archived'`+condition, args...).Scan(&old); err != nil {
return err
}
if old == title {
return nil
}
if _, err = tx.Exec(`UPDATE `+table+` SET title=`+s.sqlParam(1)+`,version=version+1,updated_at_ms=`+s.sqlParam(2)+` WHERE uuid=`+s.sqlParam(3)+` AND domain_uuid=`+s.sqlParam(4), title, time.Now().UnixMilli(), id, domain); err != nil {
return err
}
if err = s.recordCityOrganize(tx, domain, actor, "city.title.changed", kind, id, map[string]string{"title": old}, map[string]string{"title": title}); err != nil {
return err
}
return tx.Commit()
}
func (s *Store) activeCitySpot(tx *sql.Tx, domain, id string) error {
var found int
return tx.QueryRow(`SELECT 1 FROM spots s JOIN street_spots ss ON ss.spot_uuid=s.uuid JOIN zones z ON z.uuid=ss.street_uuid AND z.domain_uuid=s.domain_uuid AND z.kind='street' AND z.state!='archived' WHERE s.uuid=`+s.sqlParam(1)+` AND s.domain_uuid=`+s.sqlParam(2)+` AND s.state!='archived'`, id, domain).Scan(&found)
}
// OrganizeCity changes City membership only, atomically. Document Paths,
// revisions and payloads are never renamed or removed by this operation.
func (s *Store) OrganizeCity(domain, actor string, req CityOrganizeRequest) (_ CityOrganizeResult, resultErr error) {
defer func() { resultErr = s.cityMutationError("organize city", resultErr) }()
out := CityOrganizeResult{}
if len(req.Spots)+len(req.Pages) == 0 || len(req.Spots)+len(req.Pages) > 200 || (req.Action != "merge" && req.Action != "move") {
return out, errors.New("city_invalid_selection")
}
if req.Action == "merge" && ((req.TargetSpotUUID == "") == (req.NewSpot == nil)) {
return out, errors.New("city_invalid_target")
}
if req.Action == "move" && (len(req.Pages) > 0 || req.StreetUUID == "" || req.NewSpot != nil || req.TargetSpotUUID != "" || (req.PathPrefix != "" && len(req.Spots) != 1)) {
return out, errors.New("city_invalid_target")
}
tx, cancel, err := s.beginPathMutation(domain)
defer cancel()
if err != nil {
return out, err
}
defer tx.Rollback()
if err = s.checkCityVersion(tx, domain, req.BaseVersion); err != nil {
return out, err
}
whole := map[string]bool{}
selected := map[string]map[string]bool{}
for _, id := range req.Spots {
if id == "" || whole[id] {
return out, errors.New("city_invalid_selection")
}
whole[id] = true
selected[id] = nil
}
for _, p := range req.Pages {
if p.PageUUID == "" || p.SpotUUID == "" || whole[p.SpotUUID] {
return out, errors.New("city_invalid_selection")
}
if selected[p.SpotUUID] == nil {
selected[p.SpotUUID] = map[string]bool{}
}
selected[p.SpotUUID][p.PageUUID] = true
}
if whole[req.TargetSpotUUID] || selected[req.TargetSpotUUID] != nil {
return out, errors.New("city_invalid_target")
}
// Bound expansion as well as selection count. No truncated merge is applied.
placements := map[string][]CityPagePlacement{}
sourceBoundaries := map[string]map[string]string{}
uniquePages := map[string]bool{}
total := 0
for id, pages := range selected {
if err = s.activeCitySpot(tx, domain, id); err != nil {
return out, err
}
var oldPath, oldStreet string
if err = tx.QueryRow(`SELECT s.path_prefix,ss.street_uuid FROM spots s JOIN street_spots ss ON ss.spot_uuid=s.uuid WHERE s.uuid=`+s.sqlParam(1)+` AND s.domain_uuid=`+s.sqlParam(2), id, domain).Scan(&oldPath, &oldStreet); err != nil {
return out, err
}
sourceBoundaries[id] = map[string]string{"path_prefix": oldPath, "street_uuid": oldStreet}
items, e := s.listSpotPages(tx, domain, id, 2001)
if e != nil {
return out, e
}
if len(items) > 2000 {
return out, errors.New("city_too_many_pages")
}
found := map[string]bool{}
for _, item := range items {
if !whole[id] && !pages[item.PageUUID] {
continue
}
if item.Path == "" {
return out, errors.New("city_invalid_selection")
}
placements[id] = append(placements[id], item)
found[item.PageUUID] = true
uniquePages[item.PageUUID] = true
total++
}
if total > 2000 {
return out, errors.New("city_too_many_pages")
}
for page := range pages {
if !found[page] {
return out, errors.New("city_invalid_selection")
}
}
}
out.Pages = len(uniquePages)
now := time.Now().UnixMilli()
if req.Action == "move" {
var streetPath string
if err = tx.QueryRow(`SELECT path_prefix FROM zones WHERE uuid=`+s.sqlParam(1)+` AND domain_uuid=`+s.sqlParam(2)+` AND kind='street' AND state!='archived'`, req.StreetUUID, domain).Scan(&streetPath); err != nil {
return out, err
}
boundaries, e := s.loadCityBoundaries(tx, domain)
if e != nil {
return out, e
}
for i := range boundaries {
if whole[boundaries[i].id] {
boundaries[i].parent = req.StreetUUID
boundaries[i].path = normalizePath(streetPath + "/" + path.Base(boundaries[i].path))
if req.PathPrefix != "" {
boundaries[i].path = normalizePath(req.PathPrefix)
}
}
}
if err = validateCityBoundaryChanges(boundaries, whole); err != nil {
return out, err
}
for _, b := range boundaries {
if whole[b.id] {
if _, err = tx.Exec(`UPDATE spots SET path_prefix=`+s.sqlParam(1)+`,version=version+1,updated_at_ms=`+s.sqlParam(2)+` WHERE uuid=`+s.sqlParam(3)+` AND domain_uuid=`+s.sqlParam(4), b.path, now, b.id, domain); err != nil {
return out, err
}
if _, err = tx.Exec(`UPDATE street_spots SET street_uuid=`+s.sqlParam(1)+` WHERE spot_uuid=`+s.sqlParam(2), req.StreetUUID, b.id); err != nil {
return out, err
}
}
}
} else {
out.TargetSpotUUID = req.TargetSpotUUID
if req.NewSpot != nil {
n := req.NewSpot
name, e := normalizeCityName(n.Name)
if e != nil {
return out, e
}
if strings.TrimSpace(n.Title) == "" || utf8.RuneCountInString(n.Title) > 160 || strings.TrimSpace(n.PathPrefix) == "" {
return out, errors.New("city_invalid_title")
}
boundaries, e := s.loadCityBoundaries(tx, domain)
if e != nil {
return out, e
}
// Sources will be archived in this same transaction, so their old
// boundaries need not conflict with a replacement's boundary.
kept := boundaries[:0]
for _, b := range boundaries {
if !whole[b.id] {
kept = append(kept, b)
}
}
id := uuid.NewString()
kept = append(kept, cityPathBoundary{id: id, kind: "spot", parent: n.StreetUUID, path: normalizePath(n.PathPrefix)})
if err = validateCityBoundaryChanges(kept, map[string]bool{id: true}); err != nil {
return out, err
}
var collision int
if err = tx.QueryRow(`SELECT COUNT(*) FROM spots WHERE domain_uuid=`+s.sqlParam(1)+` AND name=`+s.sqlParam(2), domain, name).Scan(&collision); err != nil {
return out, err
}
if collision != 0 {
return out, errors.New("city_name_conflict")
}
if _, err = tx.Exec(`INSERT INTO spots(uuid,domain_uuid,name,title,path_prefix,state,created_at_ms,updated_at_ms) VALUES(`+s.sqlParam(1)+`,`+s.sqlParam(2)+`,`+s.sqlParam(3)+`,`+s.sqlParam(4)+`,`+s.sqlParam(5)+`,'draft',`+s.sqlParam(6)+`,`+s.sqlParam(7)+`)`, id, domain, name, strings.TrimSpace(n.Title), normalizePath(n.PathPrefix), now, now); err != nil {
return out, err
}
if _, err = tx.Exec(`INSERT INTO street_spots(street_uuid,spot_uuid,created_at_ms) VALUES(`+s.sqlValues(3)+`)`, n.StreetUUID, id, now); err != nil {
return out, err
}
out.TargetSpotUUID = id
} else if err = s.activeCitySpot(tx, domain, out.TargetSpotUUID); err != nil {
return out, err
}
}
for source, items := range placements {
dest := out.TargetSpotUUID
if req.Action == "move" {
dest = source
}
for _, item := range items {
edge := item.EdgeType
if edge == "path" {
edge = "primary"
}
if _, err = tx.Exec(`INSERT INTO spot_pages(spot_uuid,page_uuid,edge_type,label,sort_key,featured,source,created_at_ms) VALUES(`+s.sqlParam(1)+`,`+s.sqlParam(2)+`,`+s.sqlParam(3)+`,`+s.sqlParam(4)+`,`+s.sqlParam(5)+`,`+s.sqlParam(6)+`,'organizer',`+s.sqlParam(7)+`) ON CONFLICT(spot_uuid,page_uuid,edge_type) DO UPDATE SET label=CASE WHEN spot_pages.label='' THEN excluded.label ELSE spot_pages.label END,featured=CASE WHEN spot_pages.featured>excluded.featured THEN spot_pages.featured ELSE excluded.featured END`, dest, item.PageUUID, edge, item.Label, item.SortKey, boolToInt(item.Featured), now); err != nil {
return out, err
}
if _, err = tx.Exec(`INSERT INTO city_page_overrides(domain_uuid,page_uuid,spot_uuid) VALUES(`+s.sqlValues(3)+`) ON CONFLICT(domain_uuid,page_uuid) DO UPDATE SET spot_uuid=excluded.spot_uuid`, domain, item.PageUUID, dest); err != nil {
return out, err
}
if req.Action == "merge" && !whole[source] {
if _, err = tx.Exec(`DELETE FROM spot_pages WHERE spot_uuid=`+s.sqlParam(1)+` AND page_uuid=`+s.sqlParam(2), source, item.PageUUID); err != nil {
return out, err
}
}
}
}
if req.Action == "merge" && len(whole) > 0 {
// Redirect graph relations in one pass; internal/self edges disappear,
// duplicate relations retain the greater weight. No unrelated edges change.
left, right := make([]string, len(req.Spots)), make([]string, len(req.Spots))
for i := range req.Spots {
left[i] = s.sqlParam(3 + i)
right[i] = s.sqlParam(3 + len(req.Spots) + i)
}
args := []any{domain, domain}
for _, id := range req.Spots {
args = append(args, id)
}
for _, id := range req.Spots {
args = append(args, id)
}
rows, e := tx.Query(`SELECT r.source_spot_uuid,r.target_spot_uuid,r.relation_type,r.weight FROM spot_relations r JOIN spots a ON a.uuid=r.source_spot_uuid JOIN spots b ON b.uuid=r.target_spot_uuid WHERE a.domain_uuid=`+s.sqlParam(1)+` AND b.domain_uuid=`+s.sqlParam(2)+` AND (r.source_spot_uuid IN (`+strings.Join(left, ",")+`) OR r.target_spot_uuid IN (`+strings.Join(right, ",")+`)) LIMIT 2001`, args...)
if e != nil {
return out, e
}
relations := []CitySpotRelation{}
for rows.Next() {
var r CitySpotRelation
if e = rows.Scan(&r.SourceSpotUUID, &r.TargetSpotUUID, &r.RelationType, &r.Weight); e != nil {
rows.Close()
return out, e
}
if whole[r.SourceSpotUUID] || whole[r.TargetSpotUUID] {
relations = append(relations, r)
}
}
e = rows.Err()
rows.Close()
if e != nil {
return out, e
}
if len(relations) > 2000 {
return out, errors.New("city_too_many_relations")
}
for _, r := range relations {
if _, err = tx.Exec(`DELETE FROM spot_relations WHERE source_spot_uuid=`+s.sqlParam(1)+` AND target_spot_uuid=`+s.sqlParam(2)+` AND relation_type=`+s.sqlParam(3), r.SourceSpotUUID, r.TargetSpotUUID, r.RelationType); err != nil {
return out, err
}
}
for _, r := range relations {
if whole[r.SourceSpotUUID] {
r.SourceSpotUUID = out.TargetSpotUUID
}
if whole[r.TargetSpotUUID] {
r.TargetSpotUUID = out.TargetSpotUUID
}
if r.SourceSpotUUID == r.TargetSpotUUID {
continue
}
if _, err = tx.Exec(`INSERT INTO spot_relations(source_spot_uuid,target_spot_uuid,relation_type,weight,created_at_ms) VALUES(`+s.sqlValues(5)+`) ON CONFLICT(source_spot_uuid,target_spot_uuid,relation_type) DO UPDATE SET weight=CASE WHEN spot_relations.weight>excluded.weight THEN spot_relations.weight ELSE excluded.weight END`, r.SourceSpotUUID, r.TargetSpotUUID, r.RelationType, r.Weight, now); err != nil {
return out, err
}
}
for id := range whole {
if _, err = tx.Exec(`UPDATE spots SET state='archived',version=version+1,updated_at_ms=`+s.sqlParam(1)+` WHERE uuid=`+s.sqlParam(2)+` AND domain_uuid=`+s.sqlParam(3), now, id, domain); err != nil {
return out, err
}
if _, err = tx.Exec(`DELETE FROM street_spots WHERE spot_uuid=`+s.sqlParam(1), id); err != nil {
return out, err
}
if _, err = tx.Exec(`DELETE FROM spot_pages WHERE spot_uuid=`+s.sqlParam(1), id); err != nil {
return out, err
}
// Includes earlier manual placements whose Page has since disappeared.
if _, err = tx.Exec(`UPDATE city_page_overrides SET spot_uuid=`+s.sqlParam(1)+` WHERE domain_uuid=`+s.sqlParam(2)+` AND spot_uuid=`+s.sqlParam(3), out.TargetSpotUUID, domain, id); err != nil {
return out, err
}
}
}
if err = s.recordCityOrganize(tx, domain, actor, "city.organize."+req.Action, "spot", out.TargetSpotUUID, map[string]any{"request": req, "placements": placements, "boundaries": sourceBoundaries}, out); err != nil {
return out, fmt.Errorf("record City operation: %w", err)
}
return out, tx.Commit()
}