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.
784 lines
34 KiB
Go
784 lines
34 KiB
Go
package store
|
|
|
|
import (
|
|
"database/sql"
|
|
"errors"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
var cityNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{1,63}$`)
|
|
|
|
type CitySpot struct {
|
|
DetailHref string `json:"detail_href,omitempty"`
|
|
UUID string `json:"uuid"`
|
|
Name string `json:"name"`
|
|
Title string `json:"title"`
|
|
Summary string `json:"summary"`
|
|
State string `json:"state"`
|
|
SortKey int `json:"sort_key"`
|
|
PageCount int `json:"page_count"`
|
|
Pages []CityPagePlacement `json:"pages"`
|
|
PathPrefix string `json:"path_prefix"`
|
|
PortalPath string `json:"portal_path"`
|
|
PortalPageUUID string `json:"portal_page_uuid"`
|
|
}
|
|
type CityStreet struct {
|
|
DetailHref string `json:"detail_href,omitempty"`
|
|
UUID string `json:"uuid"`
|
|
Name string `json:"name"`
|
|
Title string `json:"title"`
|
|
Description string `json:"description"`
|
|
State string `json:"state"`
|
|
SortKey int `json:"sort_key"`
|
|
Spots []CitySpot `json:"spots"`
|
|
PathPrefix string `json:"path_prefix"`
|
|
}
|
|
type CityQuartier struct {
|
|
DetailHref string `json:"detail_href,omitempty"`
|
|
UUID string `json:"uuid"`
|
|
Name string `json:"name"`
|
|
Title string `json:"title"`
|
|
Description string `json:"description"`
|
|
State string `json:"state"`
|
|
SortKey int `json:"sort_key"`
|
|
Streets []CityStreet `json:"streets"`
|
|
PathPrefix string `json:"path_prefix"`
|
|
}
|
|
type CityMap struct {
|
|
DomainUUID string `json:"domain_uuid"`
|
|
Version int64 `json:"version"`
|
|
Quartiers []CityQuartier `json:"quartiers"`
|
|
Relations []CitySpotRelation `json:"relations"`
|
|
}
|
|
|
|
type CitySpotRelation struct {
|
|
SourceSpotUUID string `json:"source_spot_uuid"`
|
|
TargetSpotUUID string `json:"target_spot_uuid"`
|
|
RelationType string `json:"relation_type"`
|
|
Weight float64 `json:"weight"`
|
|
}
|
|
|
|
type CityPagePlacement struct {
|
|
PageUUID string `json:"page_uuid"`
|
|
Path string `json:"path"`
|
|
EdgeType string `json:"edge_type"`
|
|
Label string `json:"label"`
|
|
SortKey int `json:"sort_key"`
|
|
Featured bool `json:"featured"`
|
|
Source string `json:"source"`
|
|
}
|
|
|
|
type CitySpotAppearance struct {
|
|
SpotUUID, SpotName, SpotTitle, EdgeType, Label, Source, PathPrefix string
|
|
}
|
|
|
|
type CityNodeDetail struct {
|
|
UUID, DomainUUID, Kind, ParentUUID, Name, Title, Description, State string
|
|
PathPrefix string
|
|
SortKey, Version int
|
|
Quartier *CityNodeAncestor `json:"quartier,omitempty"`
|
|
Street *CityNodeAncestor `json:"street,omitempty"`
|
|
}
|
|
|
|
func (s *Store) EnsureCitySchema() error {
|
|
statements := []string{
|
|
`CREATE TABLE IF NOT EXISTS domain_topology_versions (domain_uuid TEXT PRIMARY KEY,version INTEGER NOT NULL DEFAULT 1,updated_at_ms INTEGER NOT NULL)`,
|
|
`CREATE TABLE IF NOT EXISTS zones (uuid TEXT PRIMARY KEY,domain_uuid TEXT NOT NULL,kind TEXT NOT NULL,parent_uuid TEXT,name TEXT NOT NULL,title TEXT NOT NULL DEFAULT '',description TEXT NOT NULL DEFAULT '',path_prefix TEXT NOT NULL DEFAULT '',charter_json TEXT NOT NULL DEFAULT '{}',policy_json TEXT NOT NULL DEFAULT '{}',state TEXT NOT NULL DEFAULT 'draft',sort_key INTEGER NOT NULL DEFAULT 0,version INTEGER NOT NULL DEFAULT 1,created_at_ms INTEGER NOT NULL,updated_at_ms INTEGER NOT NULL,UNIQUE(domain_uuid,parent_uuid,name))`,
|
|
`CREATE UNIQUE INDEX IF NOT EXISTS idx_zones_quartier_name ON zones(domain_uuid,name) WHERE kind='quartier'`,
|
|
`CREATE INDEX IF NOT EXISTS idx_zones_parent ON zones(domain_uuid,parent_uuid,sort_key,name)`,
|
|
`CREATE TABLE IF NOT EXISTS spots (uuid TEXT PRIMARY KEY,domain_uuid TEXT NOT NULL,name TEXT NOT NULL,title TEXT NOT NULL DEFAULT '',summary TEXT NOT NULL DEFAULT '',path_prefix TEXT NOT NULL DEFAULT '',charter_json TEXT NOT NULL DEFAULT '{}',schema_json TEXT NOT NULL DEFAULT '{}',landing_json TEXT NOT NULL DEFAULT '{}',state TEXT NOT NULL DEFAULT 'draft',version INTEGER NOT NULL DEFAULT 1,created_at_ms INTEGER NOT NULL,updated_at_ms INTEGER NOT NULL,UNIQUE(domain_uuid,name))`,
|
|
`CREATE TABLE IF NOT EXISTS street_spots (street_uuid TEXT NOT NULL,spot_uuid TEXT NOT NULL UNIQUE,sort_key INTEGER NOT NULL DEFAULT 0,section TEXT NOT NULL DEFAULT '',created_at_ms INTEGER NOT NULL,PRIMARY KEY(street_uuid,spot_uuid))`,
|
|
`CREATE TABLE IF NOT EXISTS spot_pages (spot_uuid TEXT NOT NULL,page_uuid TEXT NOT NULL,edge_type TEXT NOT NULL DEFAULT 'primary',label TEXT NOT NULL DEFAULT '',sort_key INTEGER NOT NULL DEFAULT 0,featured INTEGER NOT NULL DEFAULT 0,source TEXT NOT NULL DEFAULT 'local',created_at_ms INTEGER NOT NULL,PRIMARY KEY(spot_uuid,page_uuid,edge_type))`,
|
|
`CREATE TABLE IF NOT EXISTS spot_relations (source_spot_uuid TEXT NOT NULL,target_spot_uuid TEXT NOT NULL,relation_type TEXT NOT NULL,weight REAL NOT NULL DEFAULT 1.0,created_at_ms INTEGER NOT NULL,PRIMARY KEY(source_spot_uuid,target_spot_uuid,relation_type))`,
|
|
`CREATE INDEX IF NOT EXISTS idx_spot_relations_target ON spot_relations(target_spot_uuid,source_spot_uuid,relation_type)`,
|
|
`CREATE TABLE IF NOT EXISTS street_inbox_pages (street_uuid TEXT NOT NULL,page_uuid TEXT NOT NULL,created_at_ms INTEGER NOT NULL,PRIMARY KEY(street_uuid,page_uuid))`,
|
|
`CREATE TABLE IF NOT EXISTS city_page_overrides (domain_uuid TEXT NOT NULL,page_uuid TEXT NOT NULL,spot_uuid TEXT NOT NULL,PRIMARY KEY(domain_uuid,page_uuid))`,
|
|
`CREATE INDEX IF NOT EXISTS idx_city_page_overrides_spot ON city_page_overrides(domain_uuid,spot_uuid,page_uuid)`,
|
|
`CREATE TABLE IF NOT EXISTS topology_events (id INTEGER PRIMARY KEY AUTOINCREMENT,domain_uuid TEXT NOT NULL,topology_version INTEGER NOT NULL,actor_principal_uuid TEXT NOT NULL DEFAULT '',operation TEXT NOT NULL,target_type TEXT NOT NULL,target_uuid TEXT NOT NULL,before_json TEXT NOT NULL DEFAULT '{}',after_json TEXT NOT NULL DEFAULT '{}',request_id TEXT NOT NULL DEFAULT '',created_at_ms INTEGER NOT NULL)`,
|
|
}
|
|
for _, statement := range statements {
|
|
if _, err := s.DB.Exec(statement); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if err := ensureCityColumn(s.DB, "zones", "path_prefix", "TEXT NOT NULL DEFAULT ''"); err != nil {
|
|
return err
|
|
}
|
|
if err := ensureCityColumn(s.DB, "spots", "path_prefix", "TEXT NOT NULL DEFAULT ''"); err != nil {
|
|
return err
|
|
}
|
|
return s.ensureCityGovernanceSchema()
|
|
}
|
|
|
|
func ensureCityColumn(db *sql.DB, table, column, declaration string) error {
|
|
rows, err := db.Query(`PRAGMA table_info(` + table + `)`)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
found := false
|
|
for rows.Next() {
|
|
var cid int
|
|
var name, kind string
|
|
var notnull, pk int
|
|
var defaultValue any
|
|
if err := rows.Scan(&cid, &name, &kind, ¬null, &defaultValue, &pk); err != nil {
|
|
rows.Close()
|
|
return err
|
|
}
|
|
found = found || name == column
|
|
}
|
|
if err := rows.Close(); err != nil {
|
|
return err
|
|
}
|
|
if found {
|
|
return nil
|
|
}
|
|
_, err = db.Exec(`ALTER TABLE ` + table + ` ADD COLUMN ` + column + ` ` + declaration)
|
|
return err
|
|
}
|
|
|
|
func cityPathContains(parent, child string) bool {
|
|
parent, child = normalizePath(parent), normalizePath(child)
|
|
if parent == "/" {
|
|
return child != "/"
|
|
}
|
|
return child != parent && strings.HasPrefix(child, parent+"/")
|
|
}
|
|
|
|
func validateCityPathPrefix(tx *sql.Tx, domainUUID, kind, pathPrefix string) (string, error) {
|
|
pathPrefix = normalizePath(pathPrefix)
|
|
if pathPrefix == "/" && kind != "quartier" {
|
|
return "", errors.New("only a Quartier may bind the Domain root")
|
|
}
|
|
var conflicts int
|
|
table := "zones"
|
|
if kind == "spot" {
|
|
table = "spots"
|
|
}
|
|
query := `SELECT COUNT(*) FROM ` + table + ` CROSS JOIN (SELECT ? AS candidate) input WHERE domain_uuid=? AND state!='archived' AND ` + cityPathOverlapSQL("path_prefix", "input.candidate")
|
|
if kind != "spot" {
|
|
query += ` AND kind=?`
|
|
}
|
|
args := []any{pathPrefix, domainUUID}
|
|
if kind != "spot" {
|
|
args = append(args, kind)
|
|
}
|
|
if err := tx.QueryRow(query, args...).Scan(&conflicts); err != nil {
|
|
return "", err
|
|
}
|
|
if conflicts > 0 {
|
|
return "", errors.New("City Path boundaries of the same level must not overlap")
|
|
}
|
|
return pathPrefix, nil
|
|
}
|
|
|
|
type cityPathBoundary struct{ id, kind, parent, path string }
|
|
|
|
func validateCityBoundaryChanges(items []cityPathBoundary, changed map[string]bool) error {
|
|
byID := make(map[string]cityPathBoundary, len(items))
|
|
for _, item := range items {
|
|
byID[item.id] = item
|
|
}
|
|
for i, item := range items {
|
|
for j := i + 1; j < len(items); j++ {
|
|
other := items[j]
|
|
if (changed[item.id] || changed[other.id]) && item.kind == other.kind && (item.path == other.path || cityPathContains(item.path, other.path) || cityPathContains(other.path, item.path)) {
|
|
return errors.New("City Path boundaries of the same level must not overlap")
|
|
}
|
|
}
|
|
if item.kind == "street" && (changed[item.id] || changed[item.parent]) {
|
|
parent, ok := byID[item.parent]
|
|
if !ok || parent.kind != "quartier" || !cityPathContains(parent.path, item.path) {
|
|
return errors.New("Street Path must be a strict descendant of its Quartier Path")
|
|
}
|
|
}
|
|
if item.kind == "spot" && (changed[item.id] || changed[item.parent]) {
|
|
parent, ok := byID[item.parent]
|
|
if !ok || parent.kind != "street" || !cityPathContains(parent.path, item.path) {
|
|
return errors.New("Spot Path must be a strict descendant of its Street Path")
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func loadCityBoundaries(tx *sql.Tx, domainUUID string) ([]cityPathBoundary, error) {
|
|
rows, err := tx.Query(`SELECT uuid,kind,COALESCE(parent_uuid,''),path_prefix FROM zones WHERE domain_uuid=? AND state!='archived' UNION ALL SELECT s.uuid,'spot',COALESCE(ss.street_uuid,''),s.path_prefix FROM spots s LEFT JOIN street_spots ss ON ss.spot_uuid=s.uuid WHERE s.domain_uuid=? AND s.state!='archived'`, domainUUID, domainUUID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var items []cityPathBoundary
|
|
for rows.Next() {
|
|
var item cityPathBoundary
|
|
if err := rows.Scan(&item.id, &item.kind, &item.parent, &item.path); err != nil {
|
|
return nil, err
|
|
}
|
|
item.path = normalizePath(item.path)
|
|
items = append(items, item)
|
|
}
|
|
return items, rows.Err()
|
|
}
|
|
|
|
func renameCityPathPrefixesTx(tx *sql.Tx, domainUUID, oldPath, newPath string) (int, error) {
|
|
items, err := loadCityBoundaries(tx, domainUUID)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
changed := make(map[string]string)
|
|
changedIDs := make(map[string]bool)
|
|
for i := range items {
|
|
if items[i].path == oldPath || strings.HasPrefix(items[i].path, oldPath+"/") {
|
|
items[i].path = newPath + strings.TrimPrefix(items[i].path, oldPath)
|
|
changed[items[i].id] = items[i].path
|
|
changedIDs[items[i].id] = true
|
|
}
|
|
}
|
|
if len(changed) == 0 {
|
|
return 0, nil
|
|
}
|
|
if err := validateCityBoundaryChanges(items, changedIDs); err != nil {
|
|
return 0, err
|
|
}
|
|
now := time.Now().UnixMilli()
|
|
for _, item := range items {
|
|
path, ok := changed[item.id]
|
|
if !ok {
|
|
continue
|
|
}
|
|
table := "zones"
|
|
if item.kind == "spot" {
|
|
table = "spots"
|
|
}
|
|
if _, err := tx.Exec(`UPDATE `+table+` SET path_prefix=?,version=version+1,updated_at_ms=? WHERE uuid=? AND domain_uuid=?`, path, now, item.id, domainUUID); err != nil {
|
|
return 0, err
|
|
}
|
|
}
|
|
return len(changed), nil
|
|
}
|
|
|
|
func (s *Store) UpdateCityNodePath(domainUUID, actor, kind, id, pathPrefix string) error {
|
|
pathPrefix = normalizePath(pathPrefix)
|
|
tx, err := s.DB.Begin()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
items, err := loadCityBoundaries(tx, domainUUID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
found := false
|
|
changed := map[string]bool{id: true}
|
|
for i := range items {
|
|
if items[i].id == id && items[i].kind == kind {
|
|
items[i].path, found = pathPrefix, true
|
|
}
|
|
}
|
|
if !found {
|
|
return sql.ErrNoRows
|
|
}
|
|
if err := validateCityBoundaryChanges(items, changed); err != nil {
|
|
return err
|
|
}
|
|
table := "zones"
|
|
if kind == "spot" {
|
|
table = "spots"
|
|
}
|
|
result, err := tx.Exec(`UPDATE `+table+` SET path_prefix=?,version=version+1,updated_at_ms=? WHERE uuid=? AND domain_uuid=? AND state!='archived'`, pathPrefix, time.Now().UnixMilli(), id, domainUUID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if changed, _ := result.RowsAffected(); changed != 1 {
|
|
return sql.ErrNoRows
|
|
}
|
|
if err := bumpTopologyVersion(tx, domainUUID, actor, "city.node.path_updated", kind, id); err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}
|
|
|
|
func normalizeCityName(name string) (string, error) {
|
|
name = strings.ToLower(strings.TrimSpace(name))
|
|
if !cityNamePattern.MatchString(name) {
|
|
return "", errors.New("city name must be 2-64 lowercase letters, digits, underscores, or hyphens")
|
|
}
|
|
return name, nil
|
|
}
|
|
|
|
func bumpTopologyVersion(tx *sql.Tx, domainUUID, actor, operation, targetType, targetUUID string) error {
|
|
now := time.Now().UnixMilli()
|
|
_, err := tx.Exec(`INSERT INTO domain_topology_versions(domain_uuid,version,updated_at_ms) VALUES(?,2,?) ON CONFLICT(domain_uuid) DO UPDATE SET version=version+1,updated_at_ms=excluded.updated_at_ms`, domainUUID, now)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var version int64
|
|
if err := tx.QueryRow(`SELECT version FROM domain_topology_versions WHERE domain_uuid=?`, domainUUID).Scan(&version); err != nil {
|
|
return err
|
|
}
|
|
_, err = tx.Exec(`INSERT INTO topology_events(domain_uuid,topology_version,actor_principal_uuid,operation,target_type,target_uuid,created_at_ms) VALUES(?,?,?,?,?,?,?)`, domainUUID, version, actor, operation, targetType, targetUUID, now)
|
|
return err
|
|
}
|
|
|
|
func (s *Store) CreateZone(domainUUID, actor, kind, parentUUID, name, title, description string) (string, error) {
|
|
pathPrefix := "/" + strings.ToLower(strings.TrimSpace(name))
|
|
if strings.EqualFold(kind, "street") {
|
|
var parentPath string
|
|
if s.DB.QueryRow(`SELECT path_prefix FROM zones WHERE uuid=? AND domain_uuid=?`, parentUUID, domainUUID).Scan(&parentPath) == nil {
|
|
pathPrefix = normalizePath(parentPath) + "/" + strings.ToLower(strings.TrimSpace(name))
|
|
}
|
|
}
|
|
return s.CreateZoneAtPath(domainUUID, actor, kind, parentUUID, name, title, description, pathPrefix)
|
|
}
|
|
|
|
func (s *Store) CreateZoneAtPath(domainUUID, actor, kind, parentUUID, name, title, description, pathPrefix string) (string, error) {
|
|
name, err := normalizeCityName(name)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
kind = strings.ToLower(strings.TrimSpace(kind))
|
|
if kind != "quartier" && kind != "street" {
|
|
return "", errors.New("zone kind must be quartier or street")
|
|
}
|
|
if strings.TrimSpace(title) == "" {
|
|
title = name
|
|
}
|
|
tx, err := s.DB.Begin()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer tx.Rollback()
|
|
if strings.TrimSpace(pathPrefix) == "" {
|
|
pathPrefix = "/" + name
|
|
}
|
|
pathPrefix, err = validateCityPathPrefix(tx, domainUUID, kind, pathPrefix)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if kind == "quartier" {
|
|
parentUUID = ""
|
|
} else {
|
|
var parentKind, parentPath string
|
|
if err := tx.QueryRow(`SELECT kind,path_prefix FROM zones WHERE uuid=? AND domain_uuid=? AND state!='archived'`, parentUUID, domainUUID).Scan(&parentKind, &parentPath); err != nil || parentKind != "quartier" {
|
|
return "", errors.New("street parent must be an active Quartier")
|
|
}
|
|
if !cityPathContains(parentPath, pathPrefix) {
|
|
return "", errors.New("Street Path must be a strict descendant of its Quartier Path")
|
|
}
|
|
}
|
|
id, now := uuid.NewString(), time.Now().UnixMilli()
|
|
var parent any
|
|
if parentUUID == "" {
|
|
parent = nil
|
|
} else {
|
|
parent = parentUUID
|
|
}
|
|
// Archived nodes retain their UUID and audit history, but must not reserve
|
|
// a human-facing name forever. Move an old conflicting name aside before
|
|
// inserting the replacement node.
|
|
if kind == "quartier" {
|
|
if _, err := tx.Exec(`UPDATE zones SET name=name||'~archived-'||substr(uuid,1,8),updated_at_ms=? WHERE domain_uuid=? AND kind=? AND parent_uuid IS NULL AND name=? AND state='archived'`, time.Now().UnixMilli(), domainUUID, kind, name); err != nil {
|
|
return "", err
|
|
}
|
|
} else {
|
|
if _, err := tx.Exec(`UPDATE zones SET name=name||'~archived-'||substr(uuid,1,8),updated_at_ms=? WHERE domain_uuid=? AND kind=? AND parent_uuid=? AND name=? AND state='archived'`, time.Now().UnixMilli(), domainUUID, kind, parentUUID, name); err != nil {
|
|
return "", err
|
|
}
|
|
}
|
|
if _, err := tx.Exec(`INSERT INTO zones(uuid,domain_uuid,kind,parent_uuid,name,title,description,path_prefix,state,created_at_ms,updated_at_ms) VALUES(?,?,?,?,?,?,?,?,'draft',?,?)`, id, domainUUID, kind, parent, name, strings.TrimSpace(title), strings.TrimSpace(description), pathPrefix, now, now); err != nil {
|
|
return "", err
|
|
}
|
|
if err := bumpTopologyVersion(tx, domainUUID, actor, "city.zone.created", kind, id); err != nil {
|
|
return "", err
|
|
}
|
|
return id, tx.Commit()
|
|
}
|
|
|
|
func (s *Store) CreateSpot(domainUUID, actor, streetUUID, name, title, summary string) (string, error) {
|
|
pathPrefix := "/" + strings.ToLower(strings.TrimSpace(name))
|
|
var streetPath string
|
|
if s.DB.QueryRow(`SELECT path_prefix FROM zones WHERE uuid=? AND domain_uuid=?`, streetUUID, domainUUID).Scan(&streetPath) == nil {
|
|
pathPrefix = normalizePath(streetPath) + "/" + strings.ToLower(strings.TrimSpace(name))
|
|
}
|
|
return s.CreateSpotAtPath(domainUUID, actor, streetUUID, name, title, summary, pathPrefix)
|
|
}
|
|
|
|
func (s *Store) CreateSpotAtPath(domainUUID, actor, streetUUID, name, title, summary, pathPrefix string) (string, error) {
|
|
name, err := normalizeCityName(name)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if strings.TrimSpace(title) == "" {
|
|
title = name
|
|
}
|
|
tx, err := s.DB.Begin()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer tx.Rollback()
|
|
if strings.TrimSpace(pathPrefix) == "" {
|
|
pathPrefix = "/" + name
|
|
}
|
|
pathPrefix, err = validateCityPathPrefix(tx, domainUUID, "spot", pathPrefix)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
var kind, streetPath string
|
|
if err := tx.QueryRow(`SELECT kind,path_prefix FROM zones WHERE uuid=? AND domain_uuid=? AND state!='archived'`, streetUUID, domainUUID).Scan(&kind, &streetPath); err != nil || kind != "street" {
|
|
return "", errors.New("spot placement must be an active Street")
|
|
}
|
|
if !cityPathContains(streetPath, pathPrefix) {
|
|
return "", errors.New("Spot Path must be a strict descendant of its Street Path")
|
|
}
|
|
id, now := uuid.NewString(), time.Now().UnixMilli()
|
|
if _, err := tx.Exec(`UPDATE spots SET name=name||'~archived-'||substr(uuid,1,8),updated_at_ms=? WHERE domain_uuid=? AND name=? AND state='archived'`, now, domainUUID, name); err != nil {
|
|
return "", err
|
|
}
|
|
if _, err := tx.Exec(`INSERT INTO spots(uuid,domain_uuid,name,title,summary,path_prefix,state,created_at_ms,updated_at_ms) VALUES(?,?,?,?,?,?,'draft',?,?)`, id, domainUUID, name, strings.TrimSpace(title), strings.TrimSpace(summary), pathPrefix, now, now); err != nil {
|
|
return "", err
|
|
}
|
|
if _, err := tx.Exec(`INSERT INTO street_spots(street_uuid,spot_uuid,created_at_ms) VALUES(?,?,?)`, streetUUID, id, now); err != nil {
|
|
return "", err
|
|
}
|
|
if err := bumpTopologyVersion(tx, domainUUID, actor, "city.spot.created", "spot", id); err != nil {
|
|
return "", err
|
|
}
|
|
return id, tx.Commit()
|
|
}
|
|
|
|
func (s *Store) AddSpotPage(domainUUID, actor, spotUUID, pageUUID, path, edgeType, label string) error {
|
|
edgeType = strings.ToLower(strings.TrimSpace(edgeType))
|
|
valid := map[string]bool{"primary": true, "guide": true, "reference": true, "example": true, "attachment": true, "related": true}
|
|
if !valid[edgeType] {
|
|
return errors.New("invalid SpotPage edge type")
|
|
}
|
|
if pageUUID == "" {
|
|
var err error
|
|
pageUUID, err = s.ResolvePathInDomain(domainUUID, path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
tx, err := s.DB.Begin()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
var validTarget int
|
|
if err := tx.QueryRow(`SELECT EXISTS(SELECT 1 FROM spots WHERE uuid=? AND domain_uuid=? AND state!='archived') AND EXISTS(SELECT 1 FROM paths WHERE domain_uuid=? AND object_uuid=?)`, spotUUID, domainUUID, domainUUID, pageUUID).Scan(&validTarget); err != nil || validTarget == 0 {
|
|
return errors.New("Spot and Page must belong to the current Domain")
|
|
}
|
|
_, err = tx.Exec(`INSERT INTO spot_pages(spot_uuid,page_uuid,edge_type,label,created_at_ms) VALUES(?,?,?,?,?) ON CONFLICT(spot_uuid,page_uuid,edge_type) DO UPDATE SET label=excluded.label`, spotUUID, pageUUID, edgeType, strings.TrimSpace(label), time.Now().UnixMilli())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := bumpTopologyVersion(tx, domainUUID, actor, "city.spot_page.added", "spot", spotUUID); err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}
|
|
|
|
func (s *Store) RemoveSpotPage(domainUUID, actor, spotUUID, pageUUID, edgeType string) error {
|
|
tx, err := s.DB.Begin()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
result, err := tx.Exec(`DELETE FROM spot_pages WHERE spot_uuid=? AND page_uuid=? AND edge_type=? AND EXISTS(SELECT 1 FROM spots WHERE uuid=? AND domain_uuid=?)`, spotUUID, pageUUID, edgeType, spotUUID, domainUUID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
changed, _ := result.RowsAffected()
|
|
if changed == 0 {
|
|
return sql.ErrNoRows
|
|
}
|
|
if err := bumpTopologyVersion(tx, domainUUID, actor, "city.spot_page.removed", "spot", spotUUID); err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}
|
|
|
|
func (s *Store) ListSpotPages(domainUUID, spotUUID string) ([]CityPagePlacement, error) {
|
|
return listSpotPages(s.DB, domainUUID, spotUUID, -1)
|
|
}
|
|
|
|
type cityQuerier interface {
|
|
Query(string, ...any) (*sql.Rows, error)
|
|
}
|
|
|
|
func listSpotPages(db cityQuerier, domainUUID, spotUUID string, limit int) ([]CityPagePlacement, error) {
|
|
rows, err := db.Query(`SELECT page_uuid,path,edge_type,label,sort_key,featured,source FROM (
|
|
SELECT sp.page_uuid AS page_uuid,COALESCE((SELECT path FROM paths WHERE domain_uuid=? AND object_uuid=sp.page_uuid ORDER BY is_primary DESC,path LIMIT 1),'') AS path,sp.edge_type AS edge_type,sp.label AS label,sp.sort_key AS sort_key,sp.featured AS featured,sp.source AS source
|
|
FROM spot_pages sp JOIN spots s ON s.uuid=sp.spot_uuid AND s.domain_uuid=? WHERE sp.spot_uuid=?
|
|
AND EXISTS(SELECT 1 FROM paths local WHERE local.domain_uuid=s.domain_uuid AND local.object_uuid=sp.page_uuid)
|
|
UNION ALL
|
|
SELECT p.object_uuid,MIN(p.path),'path','',0,0,'path' FROM paths p JOIN spots s ON s.uuid=? AND s.domain_uuid=p.domain_uuid AND s.state!='archived'
|
|
WHERE p.domain_uuid=? AND `+cityPathScopeSQL("s.path_prefix", "p.path")+`
|
|
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 AND ov.spot_uuid!=s.uuid)
|
|
AND NOT EXISTS(SELECT 1 FROM spot_pages explicit WHERE explicit.spot_uuid=s.uuid AND explicit.page_uuid=p.object_uuid)
|
|
GROUP BY p.object_uuid
|
|
) ORDER BY featured DESC,sort_key,edge_type,path LIMIT ?`, domainUUID, domainUUID, spotUUID, spotUUID, domainUUID, limit)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var out []CityPagePlacement
|
|
for rows.Next() {
|
|
var item CityPagePlacement
|
|
if err := rows.Scan(&item.PageUUID, &item.Path, &item.EdgeType, &item.Label, &item.SortKey, &item.Featured, &item.Source); err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, item)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
func (s *Store) ListPageSpotAppearances(domainUUID, pageUUID string) ([]CitySpotAppearance, error) {
|
|
rows, err := s.DB.Query(`SELECT uuid,name,title,edge_type,label,source,path_prefix FROM (
|
|
SELECT s.uuid,s.name,s.title,sp.edge_type,sp.label,sp.source,s.path_prefix FROM spot_pages sp JOIN spots s ON s.uuid=sp.spot_uuid AND s.domain_uuid=? AND s.state!='archived' WHERE sp.page_uuid=?
|
|
UNION ALL
|
|
SELECT s.uuid,s.name,s.title,'path','','path',s.path_prefix FROM spots s JOIN paths p ON p.domain_uuid=s.domain_uuid AND p.object_uuid=? AND `+cityPathScopeSQL("s.path_prefix", "p.path")+`
|
|
WHERE s.domain_uuid=? AND s.state!='archived' AND NOT EXISTS(SELECT 1 FROM spot_pages explicit WHERE explicit.spot_uuid=s.uuid AND explicit.page_uuid=?)
|
|
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 AND ov.spot_uuid!=s.uuid)
|
|
) ORDER BY lower(title),edge_type`, domainUUID, pageUUID, pageUUID, domainUUID, pageUUID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var out []CitySpotAppearance
|
|
for rows.Next() {
|
|
var item CitySpotAppearance
|
|
if err := rows.Scan(&item.SpotUUID, &item.SpotName, &item.SpotTitle, &item.EdgeType, &item.Label, &item.Source, &item.PathPrefix); err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, item)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
func (s *Store) AddSpotRelation(domainUUID, actor, sourceUUID, targetUUID, relationType string) error {
|
|
relationType = strings.ToLower(strings.TrimSpace(relationType))
|
|
valid := map[string]bool{"related": true, "depends_on": true, "supersedes": true, "implements": true, "learn_before": true, "operated_by": true}
|
|
if !valid[relationType] || sourceUUID == targetUUID {
|
|
return errors.New("invalid Spot relation")
|
|
}
|
|
tx, err := s.DB.Begin()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
var count int
|
|
if err := tx.QueryRow(`SELECT COUNT(*) FROM spots WHERE domain_uuid=? AND uuid IN (?,?) AND state!='archived'`, domainUUID, sourceUUID, targetUUID).Scan(&count); err != nil || count != 2 {
|
|
return errors.New("both Spots must belong to the current Domain")
|
|
}
|
|
if _, err := tx.Exec(`INSERT INTO spot_relations(source_spot_uuid,target_spot_uuid,relation_type,created_at_ms) VALUES(?,?,?,?) ON CONFLICT DO NOTHING`, sourceUUID, targetUUID, relationType, time.Now().UnixMilli()); err != nil {
|
|
return err
|
|
}
|
|
if err := bumpTopologyVersion(tx, domainUUID, actor, "city.spot_relation.added", "spot", sourceUUID); err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}
|
|
|
|
func (s *Store) RemoveSpotRelation(domainUUID, actor, sourceUUID, targetUUID, relationType string) error {
|
|
tx, err := s.DB.Begin()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
result, err := tx.Exec(`DELETE FROM spot_relations WHERE source_spot_uuid=? AND target_spot_uuid=? AND relation_type=? AND EXISTS(SELECT 1 FROM spots WHERE uuid=? AND domain_uuid=?)`, sourceUUID, targetUUID, relationType, sourceUUID, domainUUID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
changed, _ := result.RowsAffected()
|
|
if changed == 0 {
|
|
return sql.ErrNoRows
|
|
}
|
|
if err := bumpTopologyVersion(tx, domainUUID, actor, "city.spot_relation.removed", "spot", sourceUUID); err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}
|
|
|
|
func (s *Store) MoveStreet(domainUUID, actor, streetUUID, quartierUUID string, sortKey int) error {
|
|
tx, err := s.DB.Begin()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
var parentKind, parentPath, streetPath string
|
|
if err := tx.QueryRow(`SELECT kind,path_prefix FROM zones WHERE uuid=? AND domain_uuid=? AND state!='archived'`, quartierUUID, domainUUID).Scan(&parentKind, &parentPath); err != nil || parentKind != "quartier" {
|
|
return errors.New("destination must be an active Quartier")
|
|
}
|
|
if err := tx.QueryRow(`SELECT path_prefix FROM zones WHERE uuid=? AND domain_uuid=? AND kind='street' AND state!='archived'`, streetUUID, domainUUID).Scan(&streetPath); err != nil {
|
|
return err
|
|
}
|
|
if !cityPathContains(parentPath, streetPath) {
|
|
return errors.New("Street Path is outside the destination Quartier Path; change its boundary first")
|
|
}
|
|
result, err := tx.Exec(`UPDATE zones SET parent_uuid=?,sort_key=?,version=version+1,updated_at_ms=? WHERE uuid=? AND domain_uuid=? AND kind='street' AND state!='archived'`, quartierUUID, sortKey, time.Now().UnixMilli(), streetUUID, domainUUID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
changed, _ := result.RowsAffected()
|
|
if changed != 1 {
|
|
return sql.ErrNoRows
|
|
}
|
|
if err := bumpTopologyVersion(tx, domainUUID, actor, "city.street.moved", "street", streetUUID); err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}
|
|
|
|
func (s *Store) MoveSpot(domainUUID, actor, spotUUID, streetUUID string, sortKey int) error {
|
|
tx, err := s.DB.Begin()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
var kind, streetPath string
|
|
if err := tx.QueryRow(`SELECT kind,path_prefix FROM zones WHERE uuid=? AND domain_uuid=? AND state!='archived'`, streetUUID, domainUUID).Scan(&kind, &streetPath); err != nil || kind != "street" {
|
|
return errors.New("destination must be an active Street")
|
|
}
|
|
var spotDomain, spotPath string
|
|
if err := tx.QueryRow(`SELECT domain_uuid,path_prefix FROM spots WHERE uuid=? AND state!='archived'`, spotUUID).Scan(&spotDomain, &spotPath); err != nil || spotDomain != domainUUID {
|
|
return errors.New("Spot must belong to the current Domain")
|
|
}
|
|
if !cityPathContains(streetPath, spotPath) {
|
|
return errors.New("Spot Path is outside the destination Street Path; change its boundary first")
|
|
}
|
|
result, err := tx.Exec(`UPDATE street_spots SET street_uuid=?,sort_key=? WHERE spot_uuid=?`, streetUUID, sortKey, spotUUID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
changed, _ := result.RowsAffected()
|
|
if changed != 1 {
|
|
return sql.ErrNoRows
|
|
}
|
|
if _, err := tx.Exec(`UPDATE spots SET version=version+1,updated_at_ms=? WHERE uuid=?`, time.Now().UnixMilli(), spotUUID); err != nil {
|
|
return err
|
|
}
|
|
if err := bumpTopologyVersion(tx, domainUUID, actor, "city.spot.moved", "spot", spotUUID); err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}
|
|
|
|
// DeleteCityNode archives a City element and removes topology edges which can
|
|
// no longer be reached. Deleting a zone recursively archives its descendants;
|
|
// documents themselves are never deleted.
|
|
func (s *Store) DeleteCityNode(domainUUID, actor, kind, id string) error {
|
|
tx, err := s.DB.Begin()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
now := time.Now().UnixMilli()
|
|
var changed int64
|
|
switch kind {
|
|
case "spot":
|
|
result, err := tx.Exec(`UPDATE spots SET state='archived',version=version+1,updated_at_ms=? WHERE uuid=? AND domain_uuid=? AND state!='archived'`, now, id, domainUUID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
changed, _ = result.RowsAffected()
|
|
if changed > 0 {
|
|
_, _ = tx.Exec(`DELETE FROM street_spots WHERE spot_uuid=?`, id)
|
|
_, _ = tx.Exec(`DELETE FROM spot_pages WHERE spot_uuid=?`, id)
|
|
_, _ = tx.Exec(`DELETE FROM spot_relations WHERE source_spot_uuid=? OR target_spot_uuid=?`, id, id)
|
|
}
|
|
case "street", "quartier":
|
|
var actual string
|
|
if err := tx.QueryRow(`SELECT kind FROM zones WHERE uuid=? AND domain_uuid=? AND state!='archived'`, id, domainUUID).Scan(&actual); err != nil || actual != kind {
|
|
return sql.ErrNoRows
|
|
}
|
|
streetIDs := []string{}
|
|
if kind == "street" {
|
|
streetIDs = append(streetIDs, id)
|
|
} else {
|
|
rows, err := tx.Query(`SELECT uuid FROM zones WHERE domain_uuid=? AND kind='street' AND parent_uuid=? AND state!='archived'`, domainUUID, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for rows.Next() {
|
|
var streetID string
|
|
if err := rows.Scan(&streetID); err != nil {
|
|
rows.Close()
|
|
return err
|
|
}
|
|
streetIDs = append(streetIDs, streetID)
|
|
}
|
|
if err := rows.Close(); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
for _, streetID := range streetIDs {
|
|
_, err = tx.Exec(`DELETE FROM spot_pages WHERE spot_uuid IN (SELECT spot_uuid FROM street_spots WHERE street_uuid=?)`, streetID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = tx.Exec(`DELETE FROM spot_relations WHERE source_spot_uuid IN (SELECT spot_uuid FROM street_spots WHERE street_uuid=?) OR target_spot_uuid IN (SELECT spot_uuid FROM street_spots WHERE street_uuid=?)`, streetID, streetID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = tx.Exec(`UPDATE spots SET state='archived',version=version+1,updated_at_ms=? WHERE uuid IN (SELECT spot_uuid FROM street_spots WHERE street_uuid=?) AND domain_uuid=?`, now, streetID, domainUUID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = tx.Exec(`DELETE FROM street_spots WHERE street_uuid=?`, streetID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if kind == "quartier" {
|
|
_, err = tx.Exec(`UPDATE zones SET state='archived',version=version+1,updated_at_ms=? WHERE domain_uuid=? AND kind='street' AND parent_uuid=? AND state!='archived'`, now, domainUUID, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
result, err := tx.Exec(`UPDATE zones SET state='archived',version=version+1,updated_at_ms=? WHERE uuid=? AND domain_uuid=? AND kind=? AND state!='archived'`, now, id, domainUUID, kind)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
changed, _ = result.RowsAffected()
|
|
default:
|
|
return errors.New("invalid City element kind")
|
|
}
|
|
if changed == 0 {
|
|
return sql.ErrNoRows
|
|
}
|
|
if err := bumpTopologyVersion(tx, domainUUID, actor, "city.node.deleted", kind, id); err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}
|
|
|
|
// CityNodeOverlappingPath resolves the active locality which already owns an
|
|
// exact, ancestor, or descendant boundary. parentUUID scopes Streets and Spots
|
|
// so an import cannot silently move a locality across its planned parent.
|
|
func (s *Store) CityNodeOverlappingPath(domainUUID, kind, parentUUID, pathPrefix string) (CityNodeDetail, error) {
|
|
pathPrefix = normalizePath(pathPrefix)
|
|
var detail CityNodeDetail
|
|
if kind == "spot" {
|
|
query := `SELECT s.uuid,s.domain_uuid,'spot',ss.street_uuid,s.name,s.title,s.summary,s.state,s.path_prefix,ss.sort_key,s.version FROM spots s JOIN street_spots ss ON ss.spot_uuid=s.uuid
|
|
JOIN zones st ON st.uuid=ss.street_uuid AND st.domain_uuid=s.domain_uuid AND st.kind='street' AND st.state!='archived'
|
|
CROSS JOIN (SELECT ? AS candidate) input WHERE s.domain_uuid=? AND ss.street_uuid=? AND s.state!='archived' AND ` + cityPathOverlapSQL("s.path_prefix", "input.candidate") +
|
|
` ORDER BY CASE WHEN s.path_prefix=input.candidate THEN 0 WHEN ` + cityPathScopeSQL("s.path_prefix", "input.candidate") + ` THEN 1 ELSE 2 END,LENGTH(s.path_prefix),s.uuid LIMIT 1`
|
|
err := s.DB.QueryRow(query, pathPrefix, domainUUID, parentUUID).Scan(&detail.UUID, &detail.DomainUUID, &detail.Kind, &detail.ParentUUID, &detail.Name, &detail.Title, &detail.Description, &detail.State, &detail.PathPrefix, &detail.SortKey, &detail.Version)
|
|
return detail, err
|
|
}
|
|
query := `SELECT uuid,domain_uuid,kind,COALESCE(parent_uuid,''),name,title,description,state,path_prefix,sort_key,version FROM zones CROSS JOIN (SELECT ? AS candidate) input WHERE domain_uuid=? AND kind=? AND state!='archived' AND ` + cityPathOverlapSQL("path_prefix", "input.candidate")
|
|
args := []any{pathPrefix, domainUUID, kind}
|
|
if kind == "street" {
|
|
query += ` AND parent_uuid=?`
|
|
args = append(args, parentUUID)
|
|
}
|
|
query += ` ORDER BY CASE WHEN path_prefix=input.candidate THEN 0 WHEN ` + cityPathScopeSQL("path_prefix", "input.candidate") + ` THEN 1 ELSE 2 END,LENGTH(path_prefix),uuid LIMIT 1`
|
|
err := s.DB.QueryRow(query, args...).Scan(&detail.UUID, &detail.DomainUUID, &detail.Kind, &detail.ParentUUID, &detail.Name, &detail.Title, &detail.Description, &detail.State, &detail.PathPrefix, &detail.SortKey, &detail.Version)
|
|
return detail, err
|
|
}
|