package store import ( "database/sql" "encoding/json" "errors" "fmt" "path" "strings" "time" "unicode/utf8" "github.com/google/uuid" ) var ErrCityChanged = errors.New("city_changed") 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 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=?`, domain).Scan(&version) if err != nil && !errors.Is(err, sql.ErrNoRows) { return err } if expected < 1 || expected != version { return ErrCityChanged } return nil } func recordCityOrganize(tx *sql.Tx, domain, actor, operation, kind, id string, before, after any) error { if err := 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=?,after_json=? WHERE domain_uuid=? AND topology_version=(SELECT version FROM domain_topology_versions WHERE domain_uuid=?)`, 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) error { 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, err := s.DB.Begin() if err != nil { return err } defer tx.Rollback() if err = checkCityVersion(tx, domain, baseVersion); err != nil { return err } table, condition := "zones", " AND kind=?" 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=? AND domain_uuid=? AND state!='archived'`+condition, args...).Scan(&old); err != nil { return err } if old == title { return nil } if _, err = tx.Exec(`UPDATE `+table+` SET title=?,version=version+1,updated_at_ms=? WHERE uuid=? AND domain_uuid=?`, title, time.Now().UnixMilli(), id, domain); err != nil { return err } if err = 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 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=? AND s.domain_uuid=? 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, error) { 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, err := s.DB.Begin() if err != nil { return out, err } defer tx.Rollback() if err = 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 = 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=? AND s.domain_uuid=?`, id, domain).Scan(&oldPath, &oldStreet); err != nil { return out, err } sourceBoundaries[id] = map[string]string{"path_prefix": oldPath, "street_uuid": oldStreet} items, e := 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=? AND domain_uuid=? AND kind='street' AND state!='archived'`, req.StreetUUID, domain).Scan(&streetPath); err != nil { return out, err } boundaries, e := 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=?,version=version+1,updated_at_ms=? WHERE uuid=? AND domain_uuid=?`, b.path, now, b.id, domain); err != nil { return out, err } if _, err = tx.Exec(`UPDATE street_spots SET street_uuid=? WHERE spot_uuid=?`, 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 := 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=? AND name=?`, 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(?,?,?,?,?,'draft',?,?)`, 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(?,?,?)`, n.StreetUUID, id, now); err != nil { return out, err } out.TargetSpotUUID = id } else if err = 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(?,?,?,?,?,?,'organizer',?) 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=MAX(spot_pages.featured,excluded.featured)`, dest, item.PageUUID, edge, item.Label, item.SortKey, item.Featured, now); err != nil { return out, err } if _, err = tx.Exec(`INSERT INTO city_page_overrides(domain_uuid,page_uuid,spot_uuid) VALUES(?,?,?) 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=? AND page_uuid=?`, 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. placeholders := strings.TrimSuffix(strings.Repeat("?,", len(req.Spots)), ",") 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=? AND b.domain_uuid=? AND (r.source_spot_uuid IN (`+placeholders+`) OR r.target_spot_uuid IN (`+placeholders+`)) 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=? AND target_spot_uuid=? AND relation_type=?`, 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(?,?,?,?,?) ON CONFLICT(source_spot_uuid,target_spot_uuid,relation_type) DO UPDATE SET weight=MAX(spot_relations.weight,excluded.weight)`, 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=? WHERE uuid=? AND domain_uuid=?`, now, id, domain); err != nil { return out, err } if _, err = tx.Exec(`DELETE FROM street_spots WHERE spot_uuid=?`, id); err != nil { return out, err } if _, err = tx.Exec(`DELETE FROM spot_pages WHERE spot_uuid=?`, 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=? WHERE domain_uuid=? AND spot_uuid=?`, out.TargetSpotUUID, domain, id); err != nil { return out, err } } } if err = 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() }