Merge branch 'Fix/Frontend/Folder-Move-Persistence'
This commit is contained in:
@@ -45,6 +45,7 @@ var (
|
||||
ErrAdminNotConfigured = errors.New("bootstrap admin step has not been completed")
|
||||
ErrProjectNotFound = errors.New("project not found")
|
||||
ErrProjectFolderNotFound = errors.New("project folder not found")
|
||||
ErrInvalidProjectFolderMove = errors.New("invalid project folder move")
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
@@ -203,6 +204,12 @@ type RenameProjectFolderInput struct {
|
||||
Name string
|
||||
}
|
||||
|
||||
type MoveProjectFolderInput struct {
|
||||
ProjectID string
|
||||
FolderID string
|
||||
ParentFolderID string
|
||||
}
|
||||
|
||||
type CreateProjectFolderResult struct {
|
||||
ProjectID string `json:"projectId"`
|
||||
CreatedFolder ProjectHierarchyFolderRecord `json:"createdFolder"`
|
||||
@@ -222,6 +229,13 @@ type RenameProjectFolderResult struct {
|
||||
Folders []ProjectHierarchyFolderRecord `json:"folders"`
|
||||
}
|
||||
|
||||
type MoveProjectFolderResult struct {
|
||||
ProjectID string `json:"projectId"`
|
||||
PreviousFolderID string `json:"previousFolderId"`
|
||||
MovedFolder ProjectHierarchyFolderRecord `json:"movedFolder"`
|
||||
Folders []ProjectHierarchyFolderRecord `json:"folders"`
|
||||
}
|
||||
|
||||
type projectHierarchyFolderRow struct {
|
||||
Path string
|
||||
ParentPath string
|
||||
@@ -944,6 +958,14 @@ func (service *Service) RenameProjectTreeFolder(ctx context.Context, input Renam
|
||||
return service.renameProjectHierarchyFolder(ctx, input, projectTreeRootPath, service.renameProjectTreeFolderOnDisk)
|
||||
}
|
||||
|
||||
func (service *Service) MoveProjectFolder(ctx context.Context, input MoveProjectFolderInput) (MoveProjectFolderResult, error) {
|
||||
return service.moveProjectHierarchyFolder(ctx, input, projectHierarchyRootPath, service.moveProjectHierarchyFolderOnDisk)
|
||||
}
|
||||
|
||||
func (service *Service) MoveProjectTreeFolder(ctx context.Context, input MoveProjectFolderInput) (MoveProjectFolderResult, error) {
|
||||
return service.moveProjectHierarchyFolder(ctx, input, projectTreeRootPath, service.moveProjectTreeFolderOnDisk)
|
||||
}
|
||||
|
||||
func (service *Service) createProjectHierarchyFolder(
|
||||
ctx context.Context,
|
||||
input CreateProjectFolderInput,
|
||||
@@ -1059,6 +1081,50 @@ func (service *Service) renameProjectHierarchyFolder(
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (service *Service) moveProjectHierarchyFolder(
|
||||
ctx context.Context,
|
||||
input MoveProjectFolderInput,
|
||||
rootPath func(projectSlug string) string,
|
||||
moveOnDisk func(projectSlug, folderID, parentFolderID string) (string, string, error),
|
||||
) (MoveProjectFolderResult, error) {
|
||||
project, err := service.loadProjectByID(ctx, strings.TrimSpace(input.ProjectID))
|
||||
if err != nil {
|
||||
return MoveProjectFolderResult{}, err
|
||||
}
|
||||
|
||||
previousFolderID, movedFolderID, err := moveOnDisk(project.Slug, input.FolderID, input.ParentFolderID)
|
||||
if err != nil {
|
||||
return MoveProjectFolderResult{}, err
|
||||
}
|
||||
|
||||
if err := posixproj.NewProjector(service.db, service.posixRoot).Rebuild(ctx); err != nil {
|
||||
return MoveProjectFolderResult{}, fmt.Errorf("rebuild POSIX projection: %w", err)
|
||||
}
|
||||
|
||||
folders, err := service.getProjectHierarchyFoldersByRootPath(ctx, project.ID, rootPath)
|
||||
if err != nil {
|
||||
return MoveProjectFolderResult{}, err
|
||||
}
|
||||
|
||||
movedFolder, found := findProjectHierarchyFolder(folders, movedFolderID)
|
||||
if !found {
|
||||
return MoveProjectFolderResult{}, fmt.Errorf("moved project folder missing from projection")
|
||||
}
|
||||
|
||||
if previousFolderID != movedFolderID {
|
||||
if _, found := findProjectHierarchyFolder(folders, previousFolderID); found {
|
||||
return MoveProjectFolderResult{}, fmt.Errorf("previous project folder path still present in projection")
|
||||
}
|
||||
}
|
||||
|
||||
return MoveProjectFolderResult{
|
||||
ProjectID: project.ID,
|
||||
PreviousFolderID: previousFolderID,
|
||||
MovedFolder: movedFolder,
|
||||
Folders: folders,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (service *Service) listWorkspaces(ctx context.Context) ([]WorkspaceRecord, error) {
|
||||
rows, err := service.db.Pool.Query(ctx, `
|
||||
SELECT id::text, organization_id::text, name, slug, kind::text, department_id::text, team_id::text, project_id::text
|
||||
@@ -1358,6 +1424,14 @@ func (service *Service) renameProjectTreeFolderOnDisk(projectSlug, folderID, nam
|
||||
return service.renameProjectFolderOnDisk(projectSlug, folderID, name, projectTreeRootPath)
|
||||
}
|
||||
|
||||
func (service *Service) moveProjectHierarchyFolderOnDisk(projectSlug, folderID, parentFolderID string) (string, string, error) {
|
||||
return service.moveProjectFolderOnDisk(projectSlug, folderID, parentFolderID, projectHierarchyRootPath)
|
||||
}
|
||||
|
||||
func (service *Service) moveProjectTreeFolderOnDisk(projectSlug, folderID, parentFolderID string) (string, string, error) {
|
||||
return service.moveProjectFolderOnDisk(projectSlug, folderID, parentFolderID, projectTreeRootPath)
|
||||
}
|
||||
|
||||
func (service *Service) createProjectFolderOnDisk(
|
||||
projectSlug, parentFolderID, name string,
|
||||
rootPathBuilder func(projectSlug string) string,
|
||||
@@ -1550,6 +1624,136 @@ func (service *Service) renameProjectFolderOnDisk(
|
||||
return folderProjectionPath, renamedProjectionPath, nil
|
||||
}
|
||||
|
||||
func (service *Service) moveProjectFolderOnDisk(
|
||||
projectSlug, folderID, parentFolderID string,
|
||||
rootPathBuilder func(projectSlug string) string,
|
||||
) (string, string, error) {
|
||||
posixRoot := strings.TrimSpace(service.posixRoot)
|
||||
if posixRoot == "" {
|
||||
return "", "", fmt.Errorf("POSIX root is not configured")
|
||||
}
|
||||
|
||||
rootProjectionPath := rootPathBuilder(projectSlug)
|
||||
folderProjectionPath := strings.TrimPrefix(filepath.ToSlash(filepath.Clean("/"+strings.TrimSpace(folderID))), "/")
|
||||
if folderProjectionPath == "." || folderProjectionPath == rootProjectionPath || !strings.HasPrefix(folderProjectionPath, rootProjectionPath+"/") {
|
||||
return "", "", ErrProjectFolderNotFound
|
||||
}
|
||||
|
||||
folderDir := filepath.Join(posixRoot, filepath.FromSlash(folderProjectionPath))
|
||||
info, err := os.Stat(folderDir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return "", "", ErrProjectFolderNotFound
|
||||
}
|
||||
return "", "", fmt.Errorf("stat project folder: %w", err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return "", "", ErrProjectFolderNotFound
|
||||
}
|
||||
|
||||
trimmedParentFolderID := strings.TrimSpace(parentFolderID)
|
||||
parentChildrenProjectionPath := rootProjectionPath
|
||||
parentDir := filepath.Join(posixRoot, filepath.FromSlash(rootProjectionPath))
|
||||
|
||||
if trimmedParentFolderID != "" {
|
||||
parentProjectionPath := strings.TrimPrefix(filepath.ToSlash(filepath.Clean("/"+trimmedParentFolderID)), "/")
|
||||
if parentProjectionPath == "." || parentProjectionPath == rootProjectionPath || !strings.HasPrefix(parentProjectionPath, rootProjectionPath+"/") {
|
||||
return "", "", ErrProjectFolderNotFound
|
||||
}
|
||||
if parentProjectionPath == folderProjectionPath || strings.HasPrefix(parentProjectionPath, folderProjectionPath+"/children/") {
|
||||
return "", "", ErrInvalidProjectFolderMove
|
||||
}
|
||||
|
||||
parentChildrenProjectionPath = filepath.ToSlash(filepath.Join(parentProjectionPath, "children"))
|
||||
parentDir = filepath.Join(posixRoot, filepath.FromSlash(parentChildrenProjectionPath))
|
||||
}
|
||||
|
||||
parentInfo, err := os.Stat(parentDir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return "", "", ErrProjectFolderNotFound
|
||||
}
|
||||
return "", "", fmt.Errorf("stat project folder parent: %w", err)
|
||||
}
|
||||
if !parentInfo.IsDir() {
|
||||
return "", "", ErrProjectFolderNotFound
|
||||
}
|
||||
|
||||
currentParentDir := filepath.Dir(folderDir)
|
||||
if samePath(currentParentDir, parentDir) {
|
||||
return folderProjectionPath, folderProjectionPath, nil
|
||||
}
|
||||
|
||||
folderPayload := readJSONFileMap(filepath.Join(folderDir, "folder.json"))
|
||||
folderName, _ := folderPayload["name"].(string)
|
||||
if strings.TrimSpace(folderName) == "" {
|
||||
folderName = fallbackFolderLabel(folderProjectionPath)
|
||||
}
|
||||
|
||||
currentBase := filepath.Base(folderDir)
|
||||
baseSlug := strings.TrimPrefix(currentBase, "folder-")
|
||||
if strings.TrimSpace(baseSlug) == "" {
|
||||
baseSlug = normalizePOSIXSlug(folderName)
|
||||
}
|
||||
|
||||
folderSlug := baseSlug
|
||||
folderDirName := slugDir("folder", folderSlug)
|
||||
destinationDir := filepath.Join(parentDir, folderDirName)
|
||||
for attempt := 2; ; attempt += 1 {
|
||||
if _, err := os.Stat(destinationDir); os.IsNotExist(err) {
|
||||
break
|
||||
} else if err != nil {
|
||||
return "", "", fmt.Errorf("stat candidate moved project folder: %w", err)
|
||||
}
|
||||
|
||||
folderSlug = fmt.Sprintf("%s-%d", baseSlug, attempt)
|
||||
folderDirName = slugDir("folder", folderSlug)
|
||||
destinationDir = filepath.Join(parentDir, folderDirName)
|
||||
}
|
||||
|
||||
if err := os.Rename(folderDir, destinationDir); err != nil {
|
||||
return "", "", fmt.Errorf("move project folder: %w", err)
|
||||
}
|
||||
|
||||
folderPayload["name"] = folderName
|
||||
folderPayload["slug"] = folderSlug
|
||||
folderPayload["type"] = "folder"
|
||||
if err := writeJSONFile(filepath.Join(destinationDir, "folder.json"), folderPayload); err != nil {
|
||||
return "", "", fmt.Errorf("write moved project folder.json: %w", err)
|
||||
}
|
||||
|
||||
movedProjectionPath := filepath.ToSlash(filepath.Join(parentChildrenProjectionPath, folderDirName))
|
||||
return folderProjectionPath, movedProjectionPath, nil
|
||||
}
|
||||
|
||||
func samePath(left, right string) bool {
|
||||
cleanLeft := filepath.Clean(left)
|
||||
cleanRight := filepath.Clean(right)
|
||||
if cleanLeft == cleanRight {
|
||||
return true
|
||||
}
|
||||
leftInfo, leftErr := os.Stat(cleanLeft)
|
||||
rightInfo, rightErr := os.Stat(cleanRight)
|
||||
if leftErr == nil && rightErr == nil {
|
||||
return os.SameFile(leftInfo, rightInfo)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func readJSONFileMap(path string) map[string]any {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return map[string]any{}
|
||||
}
|
||||
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(data, &payload); err != nil || payload == nil {
|
||||
return map[string]any{}
|
||||
}
|
||||
|
||||
return payload
|
||||
}
|
||||
|
||||
func buildProjectHierarchyFolderTree(rows []projectHierarchyFolderRow, rootParentPath string) []ProjectHierarchyFolderRecord {
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
|
||||
@@ -2,6 +2,7 @@ package bootstrap
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
@@ -310,6 +311,147 @@ func TestRenameProjectTreeFolderOnDiskRenamesFolderShape(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveProjectHierarchyFolderOnDiskMovesFolderToNewParent(t *testing.T) {
|
||||
rootPath := filepath.Join(t.TempDir(), "POSIX")
|
||||
service := NewService(nil, rootPath)
|
||||
|
||||
err := service.ensureBootstrapPOSIXSkeleton(
|
||||
InstallationRecord{ID: "installation-1", Name: "MangoPig", Mode: "personal", Access: "local", Protocol: "http", Host: "localhost", IsBootstrapped: true},
|
||||
AdminSummary{ID: "admin-1", Email: "ronald@example.com", DisplayName: "Ronald"},
|
||||
namedRecord{ID: "org-1", Name: "Primary Organization", Slug: "primary-organization"},
|
||||
namedRecord{ID: "dept-1", Name: "Primary Department", Slug: "primary-department"},
|
||||
namedRecord{ID: "team-1", Name: "Primary Team", Slug: "primary-team"},
|
||||
namedRecord{ID: "project-1", Name: "Primary Project", Slug: "primary-project"},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("ensure bootstrap POSIX skeleton: %v", err)
|
||||
}
|
||||
|
||||
designPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", "", "Design")
|
||||
if err != nil {
|
||||
t.Fatalf("create design folder: %v", err)
|
||||
}
|
||||
operationsPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", "", "Operations")
|
||||
if err != nil {
|
||||
t.Fatalf("create operations folder: %v", err)
|
||||
}
|
||||
researchPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", designPath, "Research")
|
||||
if err != nil {
|
||||
t.Fatalf("create research folder: %v", err)
|
||||
}
|
||||
nestedPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", researchPath, "Interview Notes")
|
||||
if err != nil {
|
||||
t.Fatalf("create nested folder: %v", err)
|
||||
}
|
||||
|
||||
previousPath, movedPath, err := service.moveProjectHierarchyFolderOnDisk("primary-project", researchPath, operationsPath)
|
||||
if err != nil {
|
||||
t.Fatalf("moveProjectHierarchyFolderOnDisk: %v", err)
|
||||
}
|
||||
if previousPath != researchPath {
|
||||
t.Fatalf("expected previous path %s, got %s", researchPath, previousPath)
|
||||
}
|
||||
if movedPath != "projects/project-primary-project/children/folder-operations/children/folder-research" {
|
||||
t.Fatalf("unexpected moved path: %s", movedPath)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filepath.Join(rootPath, filepath.FromSlash(researchPath))); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected previous folder path to be gone, got err=%v", err)
|
||||
}
|
||||
|
||||
movedFolderPath := filepath.Join(rootPath, filepath.FromSlash(movedPath))
|
||||
if _, err := os.Stat(filepath.Join(movedFolderPath, "children", filepath.Base(nestedPath))); err != nil {
|
||||
t.Fatalf("expected nested child folder to move with moved parent: %v", err)
|
||||
}
|
||||
|
||||
folderPayload := readJSONFileForTest[map[string]any](t, filepath.Join(movedFolderPath, "folder.json"))
|
||||
if folderPayload["name"] != "Research" {
|
||||
t.Fatalf("expected moved folder name Research, got %#v", folderPayload["name"])
|
||||
}
|
||||
if folderPayload["slug"] != "research" {
|
||||
t.Fatalf("expected moved folder slug research, got %#v", folderPayload["slug"])
|
||||
}
|
||||
if folderPayload["type"] != "folder" {
|
||||
t.Fatalf("expected moved folder type folder, got %#v", folderPayload["type"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveProjectTreeFolderOnDiskMovesFolderToNewParent(t *testing.T) {
|
||||
rootPath := filepath.Join(t.TempDir(), "POSIX")
|
||||
service := NewService(nil, rootPath)
|
||||
|
||||
err := service.ensureBootstrapPOSIXSkeleton(
|
||||
InstallationRecord{ID: "installation-1", Name: "MangoPig", Mode: "personal", Access: "local", Protocol: "http", Host: "localhost", IsBootstrapped: true},
|
||||
AdminSummary{ID: "admin-1", Email: "ronald@example.com", DisplayName: "Ronald"},
|
||||
namedRecord{ID: "org-1", Name: "Primary Organization", Slug: "primary-organization"},
|
||||
namedRecord{ID: "dept-1", Name: "Primary Department", Slug: "primary-department"},
|
||||
namedRecord{ID: "team-1", Name: "Primary Team", Slug: "primary-team"},
|
||||
namedRecord{ID: "project-1", Name: "Primary Project", Slug: "primary-project"},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("ensure bootstrap POSIX skeleton: %v", err)
|
||||
}
|
||||
|
||||
docsPath, _, err := service.createProjectTreeFolderOnDisk("primary-project", "", "Docs")
|
||||
if err != nil {
|
||||
t.Fatalf("create docs folder: %v", err)
|
||||
}
|
||||
archivePath, _, err := service.createProjectTreeFolderOnDisk("primary-project", "", "Archive")
|
||||
if err != nil {
|
||||
t.Fatalf("create archive folder: %v", err)
|
||||
}
|
||||
|
||||
previousPath, movedPath, err := service.moveProjectTreeFolderOnDisk("primary-project", docsPath, archivePath)
|
||||
if err != nil {
|
||||
t.Fatalf("moveProjectTreeFolderOnDisk: %v", err)
|
||||
}
|
||||
if previousPath != docsPath {
|
||||
t.Fatalf("expected previous path %s, got %s", docsPath, previousPath)
|
||||
}
|
||||
if movedPath != "projects/project-primary-project/tree/folder-archive/children/folder-docs" {
|
||||
t.Fatalf("unexpected moved path: %s", movedPath)
|
||||
}
|
||||
|
||||
folderPayload := readJSONFileForTest[map[string]any](t, filepath.Join(rootPath, filepath.FromSlash(movedPath), "folder.json"))
|
||||
if folderPayload["name"] != "Docs" {
|
||||
t.Fatalf("expected moved folder name Docs, got %#v", folderPayload["name"])
|
||||
}
|
||||
if folderPayload["slug"] != "docs" {
|
||||
t.Fatalf("expected moved folder slug docs, got %#v", folderPayload["slug"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveProjectHierarchyFolderOnDiskRejectsDescendantTarget(t *testing.T) {
|
||||
rootPath := filepath.Join(t.TempDir(), "POSIX")
|
||||
service := NewService(nil, rootPath)
|
||||
|
||||
err := service.ensureBootstrapPOSIXSkeleton(
|
||||
InstallationRecord{ID: "installation-1", Name: "MangoPig", Mode: "personal", Access: "local", Protocol: "http", Host: "localhost", IsBootstrapped: true},
|
||||
AdminSummary{ID: "admin-1", Email: "ronald@example.com", DisplayName: "Ronald"},
|
||||
namedRecord{ID: "org-1", Name: "Primary Organization", Slug: "primary-organization"},
|
||||
namedRecord{ID: "dept-1", Name: "Primary Department", Slug: "primary-department"},
|
||||
namedRecord{ID: "team-1", Name: "Primary Team", Slug: "primary-team"},
|
||||
namedRecord{ID: "project-1", Name: "Primary Project", Slug: "primary-project"},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("ensure bootstrap POSIX skeleton: %v", err)
|
||||
}
|
||||
|
||||
parentPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", "", "Parent")
|
||||
if err != nil {
|
||||
t.Fatalf("create parent folder: %v", err)
|
||||
}
|
||||
childPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", parentPath, "Child")
|
||||
if err != nil {
|
||||
t.Fatalf("create child folder: %v", err)
|
||||
}
|
||||
|
||||
_, _, err = service.moveProjectHierarchyFolderOnDisk("primary-project", parentPath, childPath)
|
||||
if !errors.Is(err, ErrInvalidProjectFolderMove) {
|
||||
t.Fatalf("expected ErrInvalidProjectFolderMove, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildProjectHierarchyFolderTreeBuildsNestedStructure(t *testing.T) {
|
||||
rows := []projectHierarchyFolderRow{
|
||||
{Path: "projects/project-primary-project/children/folder-design", ParentPath: projectHierarchyRootPath("primary-project"), Label: "Design"},
|
||||
|
||||
@@ -26,6 +26,11 @@ type deleteProjectFolderRequest struct {
|
||||
FolderID string `json:"folderId"`
|
||||
}
|
||||
|
||||
type moveProjectFolderRequest struct {
|
||||
FolderID string `json:"folderId"`
|
||||
ParentFolderID string `json:"parentFolderId"`
|
||||
}
|
||||
|
||||
func (routes apiRoutes) handleProjectFolders(w http.ResponseWriter, r *http.Request) {
|
||||
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||
if projectID == "" {
|
||||
@@ -161,6 +166,44 @@ func (routes apiRoutes) handleRenameProjectFolder(w http.ResponseWriter, r *http
|
||||
})
|
||||
}
|
||||
|
||||
func (routes apiRoutes) handleMoveProjectFolder(w http.ResponseWriter, r *http.Request) {
|
||||
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||
if projectID == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Project ID is required.")
|
||||
return
|
||||
}
|
||||
|
||||
payload, ok := decodeMoveProjectFolderRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
payload.FolderID = strings.TrimSpace(payload.FolderID)
|
||||
payload.ParentFolderID = strings.TrimSpace(payload.ParentFolderID)
|
||||
if payload.FolderID == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder ID is required.")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := routes.bootstrapService().MoveProjectFolder(r.Context(), bootstrapservice.MoveProjectFolderInput{
|
||||
ProjectID: projectID,
|
||||
FolderID: payload.FolderID,
|
||||
ParentFolderID: payload.ParentFolderID,
|
||||
})
|
||||
if err != nil {
|
||||
routes.writeProjectFolderError(w, r, err, "move")
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"data": result,
|
||||
"meta": map[string]any{
|
||||
"resource": "project-folder-move",
|
||||
"persisted": true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (routes apiRoutes) handleProjectTreeFolders(w http.ResponseWriter, r *http.Request) {
|
||||
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||
if projectID == "" {
|
||||
@@ -296,10 +339,50 @@ func (routes apiRoutes) handleRenameProjectTreeFolder(w http.ResponseWriter, r *
|
||||
})
|
||||
}
|
||||
|
||||
func (routes apiRoutes) handleMoveProjectTreeFolder(w http.ResponseWriter, r *http.Request) {
|
||||
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||
if projectID == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Project ID is required.")
|
||||
return
|
||||
}
|
||||
|
||||
payload, ok := decodeMoveProjectFolderRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
payload.FolderID = strings.TrimSpace(payload.FolderID)
|
||||
payload.ParentFolderID = strings.TrimSpace(payload.ParentFolderID)
|
||||
if payload.FolderID == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder ID is required.")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := routes.bootstrapService().MoveProjectTreeFolder(r.Context(), bootstrapservice.MoveProjectFolderInput{
|
||||
ProjectID: projectID,
|
||||
FolderID: payload.FolderID,
|
||||
ParentFolderID: payload.ParentFolderID,
|
||||
})
|
||||
if err != nil {
|
||||
routes.writeProjectFolderError(w, r, err, "move")
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"data": result,
|
||||
"meta": map[string]any{
|
||||
"resource": "project-tree-folder-move",
|
||||
"persisted": true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (routes apiRoutes) writeProjectFolderError(w http.ResponseWriter, r *http.Request, err error, operation string) {
|
||||
switch {
|
||||
case errors.Is(err, bootstrapservice.ErrProjectNotFound), errors.Is(err, bootstrapservice.ErrProjectFolderNotFound):
|
||||
WriteError(w, http.StatusNotFound, RequestIDFromContext(r.Context()), "not_found", err.Error())
|
||||
case errors.Is(err, bootstrapservice.ErrInvalidProjectFolderMove):
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", err.Error())
|
||||
default:
|
||||
routes.cfg.Logger.Error(operation+" project folder", "error", err, "path", r.URL.Path)
|
||||
message := "Failed to " + operation + " project folder."
|
||||
@@ -310,6 +393,30 @@ func (routes apiRoutes) writeProjectFolderError(w http.ResponseWriter, r *http.R
|
||||
}
|
||||
}
|
||||
|
||||
func decodeMoveProjectFolderRequest(w http.ResponseWriter, r *http.Request) (moveProjectFolderRequest, bool) {
|
||||
var payload moveProjectFolderRequest
|
||||
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(&payload); err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_json", "The request body is required and must be valid JSON.")
|
||||
return payload, false
|
||||
}
|
||||
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_json", "The request body must be valid JSON.")
|
||||
return payload, false
|
||||
}
|
||||
|
||||
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_json", "The request body must contain a single JSON object.")
|
||||
return payload, false
|
||||
}
|
||||
|
||||
return payload, true
|
||||
}
|
||||
|
||||
func decodeDeleteProjectFolderRequest(r *http.Request) deleteProjectFolderRequest {
|
||||
return deleteProjectFolderRequest{
|
||||
FolderID: strings.TrimSpace(r.URL.Query().Get("folderId")),
|
||||
|
||||
@@ -37,10 +37,12 @@ func (routes apiRoutes) Register(router chi.Router) {
|
||||
projectRouter.Get("/folders", routes.handleProjectFolders)
|
||||
projectRouter.Post("/folders", routes.handleCreateProjectFolder)
|
||||
projectRouter.Patch("/folders", routes.handleRenameProjectFolder)
|
||||
projectRouter.Patch("/folders/move", routes.handleMoveProjectFolder)
|
||||
projectRouter.Delete("/folders", routes.handleDeleteProjectFolder)
|
||||
projectRouter.Get("/tree/folders", routes.handleProjectTreeFolders)
|
||||
projectRouter.Post("/tree/folders", routes.handleCreateProjectTreeFolder)
|
||||
projectRouter.Patch("/tree/folders", routes.handleRenameProjectTreeFolder)
|
||||
projectRouter.Patch("/tree/folders/move", routes.handleMoveProjectTreeFolder)
|
||||
projectRouter.Delete("/tree/folders", routes.handleDeleteProjectTreeFolder)
|
||||
})
|
||||
|
||||
|
||||
@@ -58,6 +58,7 @@ type ProjectFoldersResponse = {
|
||||
data?: {
|
||||
folders?: PersistedProjectFolderRecord[];
|
||||
renamedFolder?: PersistedProjectFolderRecord;
|
||||
movedFolder?: PersistedProjectFolderRecord;
|
||||
previousFolderId?: string;
|
||||
};
|
||||
error?: string;
|
||||
@@ -574,9 +575,27 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
||||
}
|
||||
|
||||
suppressTreeClickTemporarily();
|
||||
setProjectTreeNodes((current) =>
|
||||
moveTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget as ProjectDragTarget, projectTreeAdapter),
|
||||
);
|
||||
|
||||
const currentNodes = projectTreeNodes();
|
||||
const draggedLocation = findTreeNodeLocation(currentNodes, nextDragState.draggedNodeId, projectTreeAdapter);
|
||||
const persistedParentId = nextDragState.dropTarget.parentId;
|
||||
const canPersistMove = isUuidString(selectedProject().id);
|
||||
const persistedParentLocation = persistedParentId
|
||||
? findTreeNodeLocation(currentNodes, persistedParentId, projectTreeAdapter)
|
||||
: null;
|
||||
|
||||
if (
|
||||
canPersistMove &&
|
||||
draggedLocation?.node.kind === "folder" &&
|
||||
(persistedParentId === null || persistedParentLocation?.node.kind === "folder")
|
||||
) {
|
||||
void movePersistedFolder(draggedLocation.node.id, persistedParentId);
|
||||
} else {
|
||||
setProjectTreeNodes((current) =>
|
||||
moveTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget as ProjectDragTarget, projectTreeAdapter),
|
||||
);
|
||||
}
|
||||
|
||||
setDragState(null);
|
||||
};
|
||||
|
||||
@@ -732,6 +751,45 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
||||
}
|
||||
};
|
||||
|
||||
const movePersistedFolder = async (folderId: string, parentFolderId: string | null): Promise<void> => {
|
||||
const projectId = selectedProject().id;
|
||||
if (!folderId || !isUuidString(projectId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/folders/move`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
folderId,
|
||||
parentFolderId,
|
||||
}),
|
||||
});
|
||||
|
||||
const body = (await response.json()) as ProjectFoldersResponse;
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(body.message || "Failed to move project folder.");
|
||||
}
|
||||
|
||||
setPersistedFolders(readPersistedFolders(body));
|
||||
|
||||
const previousFolderId = body.data?.previousFolderId;
|
||||
const movedFolderId = body.data?.movedFolder?.id;
|
||||
if (previousFolderId && movedFolderId && previousFolderId !== movedFolderId) {
|
||||
setCollapsedFolderIds((current) =>
|
||||
current.map((id) => (id === previousFolderId ? movedFolderId : id)),
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const submitPendingFolderRename = async (): Promise<void> => {
|
||||
const draft = pendingFolderRename();
|
||||
const name = pendingFolderRenameName().trim();
|
||||
|
||||
@@ -8,6 +8,7 @@ import { ProjectSelector } from "../ProjectSelector/ProjectSelector";
|
||||
import {
|
||||
collectBranchNodeIds,
|
||||
findTreeNodeDepth,
|
||||
findTreeNodeLocation,
|
||||
getPointerRelativeY,
|
||||
isUuidString,
|
||||
moveTreeNode,
|
||||
@@ -59,6 +60,7 @@ type WorkspaceFoldersResponse = {
|
||||
data?: {
|
||||
folders?: PersistedWorkspaceFolderRecord[];
|
||||
renamedFolder?: PersistedWorkspaceFolderRecord;
|
||||
movedFolder?: PersistedWorkspaceFolderRecord;
|
||||
previousFolderId?: string;
|
||||
};
|
||||
error?: string;
|
||||
@@ -527,9 +529,27 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
}
|
||||
|
||||
suppressTreeClickTemporarily();
|
||||
setWorkspaceTreeNodes((current) =>
|
||||
moveTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget as WorkspaceDragTarget, workspaceTreeAdapter),
|
||||
);
|
||||
|
||||
const currentNodes = workspaceTreeNodes();
|
||||
const draggedLocation = findTreeNodeLocation(currentNodes, nextDragState.draggedNodeId, workspaceTreeAdapter);
|
||||
const persistedParentId = nextDragState.dropTarget.parentId;
|
||||
const canPersistMove = isUuidString(activeProject()?.id ?? "");
|
||||
const persistedParentLocation = persistedParentId
|
||||
? findTreeNodeLocation(currentNodes, persistedParentId, workspaceTreeAdapter)
|
||||
: null;
|
||||
|
||||
if (
|
||||
canPersistMove &&
|
||||
draggedLocation?.node.kind === "folder" &&
|
||||
(persistedParentId === null || persistedParentLocation?.node.kind === "folder")
|
||||
) {
|
||||
void movePersistedFolder(draggedLocation.node.id, persistedParentId);
|
||||
} else {
|
||||
setWorkspaceTreeNodes((current) =>
|
||||
moveTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget as WorkspaceDragTarget, workspaceTreeAdapter),
|
||||
);
|
||||
}
|
||||
|
||||
setDragState(null);
|
||||
};
|
||||
|
||||
@@ -655,6 +675,45 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
}
|
||||
};
|
||||
|
||||
const movePersistedFolder = async (folderId: string, parentFolderId: string | null): Promise<void> => {
|
||||
const projectId = activeProject()?.id ?? "";
|
||||
if (!folderId || !projectId || !isUuidString(projectId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/tree/folders/move`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
folderId,
|
||||
parentFolderId,
|
||||
}),
|
||||
});
|
||||
|
||||
const body = (await response.json()) as WorkspaceFoldersResponse;
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(body.message || "Failed to move project tree folder.");
|
||||
}
|
||||
|
||||
setPersistedFolders(readPersistedWorkspaceFolders(body));
|
||||
|
||||
const previousFolderId = body.data?.previousFolderId;
|
||||
const movedFolderId = body.data?.movedFolder?.id;
|
||||
if (previousFolderId && movedFolderId && previousFolderId !== movedFolderId) {
|
||||
setCollapsedFolderIds((current) =>
|
||||
current.map((id) => (id === previousFolderId ? movedFolderId : id)),
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const submitPendingFolderRename = async (): Promise<void> => {
|
||||
const draft = pendingFolderRename();
|
||||
const name = pendingFolderRenameName().trim();
|
||||
|
||||
Reference in New Issue
Block a user