diff --git a/models/fixtures/project.yml b/models/fixtures/project.yml index 1bf8030f6aa57..c07a4002a4d9c 100644 --- a/models/fixtures/project.yml +++ b/models/fixtures/project.yml @@ -45,3 +45,29 @@ type: 2 created_unix: 1688973000 updated_unix: 1688973000 + +# user projects +- + id: 5 + title: project on user2 + owner_id: 2 + repo_id: 0 + is_closed: false + creator_id: 2 + board_type: 1 + type: 1 + created_unix: 1688973000 + updated_unix: 1688973000 + +# org projects +- + id: 6 + title: project on org17 + owner_id: 17 + repo_id: 0 + is_closed: false + creator_id: 17 + board_type: 1 + type: 3 + created_unix: 1688973000 + updated_unix: 1688973000 diff --git a/models/project/board.go b/models/project/board.go index 3e2d8e0472c51..798c19b5701d2 100644 --- a/models/project/board.go +++ b/models/project/board.go @@ -244,6 +244,24 @@ func (p *Project) GetBoards(ctx context.Context) (BoardList, error) { return append([]*Board{defaultB}, boards...), nil } +func (p *Project) GetBoardsAndCount(ctx context.Context) (BoardList, int64, error) { + boards := make([]*Board, 0, 5) + count, err := db.GetEngine(ctx). + Where("project_id=? AND `default`=?", p.ID, false). + OrderBy("Sorting"). + FindAndCount(&boards) + if err != nil { + return nil, 0, err + } + + defaultB, err := p.getDefaultBoard(ctx) + if err != nil { + return nil, 0, err + } + + return append([]*Board{defaultB}, boards...), count, nil +} + // getDefaultBoard return default board and create a dummy if none exist func (p *Project) getDefaultBoard(ctx context.Context) (*Board, error) { var board Board diff --git a/models/project/project.go b/models/project/project.go index d2fca6cdc8a8a..10e0f3187d2ba 100644 --- a/models/project/project.go +++ b/models/project/project.go @@ -95,6 +95,7 @@ type Project struct { RepoID int64 `xorm:"INDEX"` Repo *repo_model.Repository `xorm:"-"` CreatorID int64 `xorm:"NOT NULL"` + Creator *user_model.User `xorm:"-"` IsClosed bool `xorm:"INDEX"` BoardType BoardType CardType CardType @@ -107,6 +108,8 @@ type Project struct { ClosedDateUnix timeutil.TimeStamp } +type ProjectList []*Project + func (p *Project) LoadOwner(ctx context.Context) (err error) { if p.Owner != nil { return nil @@ -115,6 +118,14 @@ func (p *Project) LoadOwner(ctx context.Context) (err error) { return err } +func (p *Project) LoadCreator(ctx context.Context) (err error) { + if p.Creator != nil { + return nil + } + p.Creator, err = user_model.GetUserByID(ctx, p.CreatorID) + return err +} + func (p *Project) LoadRepo(ctx context.Context) (err error) { if p.RepoID == 0 || p.Repo != nil { return nil @@ -343,7 +354,11 @@ func updateRepositoryProjectCount(ctx context.Context, repoID int64) error { } // ChangeProjectStatusByRepoIDAndID toggles a project between opened and closed -func ChangeProjectStatusByRepoIDAndID(ctx context.Context, repoID, projectID int64, isClosed bool) error { +func ChangeProjectStatusByRepoIDAndID( + ctx context.Context, + repoID, projectID int64, + isClosed bool, +) error { ctx, committer, err := db.TxContext(ctx) if err != nil { return err @@ -384,7 +399,11 @@ func ChangeProjectStatus(ctx context.Context, p *Project, isClosed bool) error { func changeProjectStatus(ctx context.Context, p *Project, isClosed bool) error { p.IsClosed = isClosed p.ClosedDateUnix = timeutil.TimeStampNow() - count, err := db.GetEngine(ctx).ID(p.ID).Where("repo_id = ? AND is_closed = ?", p.RepoID, !isClosed).Cols("is_closed", "closed_date_unix").Update(p) + count, err := db.GetEngine(ctx). + ID(p.ID). + Where("repo_id = ? AND is_closed = ?", p.RepoID, !isClosed). + Cols("is_closed", "closed_date_unix"). + Update(p) if err != nil { return err } diff --git a/models/project/project_test.go b/models/project/project_test.go index 7a37c1faf2908..8a6dcfee9b52d 100644 --- a/models/project/project_test.go +++ b/models/project/project_test.go @@ -92,19 +92,19 @@ func TestProjectsSort(t *testing.T) { }{ { sortType: "default", - wants: []int64{1, 3, 2, 4}, + wants: []int64{1, 3, 2, 4, 5, 6}, }, { sortType: "oldest", - wants: []int64{4, 2, 3, 1}, + wants: []int64{4, 5, 6, 2, 3, 1}, }, { sortType: "recentupdate", - wants: []int64{1, 3, 2, 4}, + wants: []int64{1, 3, 2, 4, 5, 6}, }, { sortType: "leastupdate", - wants: []int64{4, 2, 3, 1}, + wants: []int64{4, 5, 6, 2, 3, 1}, }, } @@ -113,8 +113,8 @@ func TestProjectsSort(t *testing.T) { OrderBy: GetSearchOrderByBySortType(tt.sortType), }) assert.NoError(t, err) - assert.EqualValues(t, int64(4), count) - if assert.Len(t, projects, 4) { + assert.EqualValues(t, int64(6), count) + if assert.Len(t, projects, 6) { for i := range projects { assert.EqualValues(t, tt.wants[i], projects[i].ID) } diff --git a/modules/structs/project.go b/modules/structs/project.go new file mode 100644 index 0000000000000..4f1683e96c116 --- /dev/null +++ b/modules/structs/project.go @@ -0,0 +1,42 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package structs + +import "time" + +// swagger:model +type NewProjectPayload struct { + // required:true + Title string `json:"title" binding:"Required"` + // required:true + BoardType uint8 `json:"board_type"` + // required:true + CardType uint8 `json:"card_type"` + Description string `json:"description"` +} + +// swagger:model +type UpdateProjectPayload struct { + // required:true + Title string `json:"title" binding:"Required"` + Description string `json:"description"` +} + +type Project struct { + ID int64 `json:"id"` + Title string `json:"title"` + Description string `json:"description"` + BoardType uint8 `json:"board_type"` + IsClosed bool `json:"is_closed"` + // swagger:strfmt date-time + Created time.Time `json:"created_at"` + // swagger:strfmt date-time + Updated time.Time `json:"updated_at"` + // swagger:strfmt date-time + Closed time.Time `json:"closed_at"` + + Repo *RepositoryMeta `json:"repository"` + Creator *User `json:"creator"` + Owner *User `json:"owner"` +} diff --git a/modules/structs/project_board.go b/modules/structs/project_board.go new file mode 100644 index 0000000000000..13aee79f5c5d8 --- /dev/null +++ b/modules/structs/project_board.go @@ -0,0 +1,35 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package structs + +import "time" + +type ProjectBoard struct { + ID int64 `json:"id"` + Title string `json:"title"` + Default bool `json:"default"` + Color string `json:"color"` + Sorting int8 `json:"sorting"` + Project *Project `json:"project"` + Creator *User `json:"creator"` + // swagger:strfmt date-time + Created time.Time `json:"created_at"` + // swagger:strfmt date-time + Updated time.Time `json:"updated_at"` +} + +// swagger:model +type NewProjectBoardPayload struct { + // required:true + Title string `json:"title"` + Default bool `json:"default"` + Color string `json:"color"` + Sorting int8 `json:"sorting` +} + +// swagger:model +type UpdateProjectBoardPayload struct { + Title string `json:"title"` + Color string `json:"color"` +} diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 8d7669762b722..2edd859b5ab52 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -90,6 +90,7 @@ import ( "code.gitea.io/gitea/routers/api/v1/notify" "code.gitea.io/gitea/routers/api/v1/org" "code.gitea.io/gitea/routers/api/v1/packages" + "code.gitea.io/gitea/routers/api/v1/projects" "code.gitea.io/gitea/routers/api/v1/repo" "code.gitea.io/gitea/routers/api/v1/settings" "code.gitea.io/gitea/routers/api/v1/user" @@ -1029,6 +1030,10 @@ func Routes() *web.Route { m.Post("", bind(api.UpdateUserAvatarOption{}), user.UpdateAvatar) m.Delete("", user.DeleteAvatar) }, reqToken()) + + m.Combo("/projects", tokenRequiresScopes(auth_model.AccessTokenScopeCategoryIssue)). + Get(projects.ListUserProjects). + Post(bind(api.NewProjectPayload{}), projects.CreateUserProject) }, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryUser), reqToken()) // Repositories (requires repo scope, org scope) @@ -1402,6 +1407,10 @@ func Routes() *web.Route { Patch(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), bind(api.EditMilestoneOption{}), repo.EditMilestone). Delete(reqToken(), reqRepoWriter(unit.TypeIssues, unit.TypePullRequests), repo.DeleteMilestone) }) + m.Group("/projects", func() { + m.Combo("").Get(projects.ListRepoProjects). + Post(bind(api.NewProjectPayload{}), projects.CreateRepoProject) + }, mustEnableIssues) }, repoAssignment()) }, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryIssue)) @@ -1476,6 +1485,10 @@ func Routes() *web.Route { m.Delete("", org.DeleteAvatar) }, reqToken(), reqOrgOwnership()) m.Get("/activities/feeds", org.ListOrgActivityFeeds) + m.Group("/projects", func() { + m.Combo("").Get(projects.ListOrgProjects). + Post(bind(api.NewProjectPayload{}), projects.CreateOrgProject) + }, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryIssue), reqToken(), reqOrgMembership()) }, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryOrganization), orgAssignment(true)) m.Group("/teams/{teamid}", func() { m.Combo("").Get(reqToken(), org.GetTeam). @@ -1541,6 +1554,25 @@ func Routes() *web.Route { }) }, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryAdmin), reqToken(), reqSiteAdmin()) + m.Group("/projects", func() { + m.Group("/{projectId}", func() { + m.Combo(""). + Get(projects.GetProject). + Patch(bind(api.UpdateProjectPayload{}), projects.UpdateProject). + Delete(projects.DeleteProject) + m.Combo("/boards"). + Get(projects.ListProjectBoards). + Post(bind(api.NewProjectBoardPayload{}), projects.CreateProjectBoard) + }) + + m.Group("/boards", func() { + m.Combo("/{boardId}"). + Get(projects.GetProjectBoard). + Patch(bind(api.UpdateProjectBoardPayload{}), projects.UpdateProjectBoard). + Delete(projects.DeleteProjectBoard) + }) + + }, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryIssue), reqToken()) m.Group("/topics", func() { m.Get("/search", repo.TopicSearch) }, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryRepository)) diff --git a/routers/api/v1/projects/boards.go b/routers/api/v1/projects/boards.go new file mode 100644 index 0000000000000..c9f47641e6a71 --- /dev/null +++ b/routers/api/v1/projects/boards.go @@ -0,0 +1,242 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package projects + +import ( + "net/http" + + project_model "code.gitea.io/gitea/models/project" + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/setting" + api "code.gitea.io/gitea/modules/structs" + "code.gitea.io/gitea/modules/web" + "code.gitea.io/gitea/services/convert" +) + +func ListProjectBoards(ctx *context.APIContext) { + // swagger:operation GET /projects/{projectId}/boards board boardGetProjectBoards + // --- + // summary: Get project boards + // produces: + // - application/json + // parameters: + // - name: projectId + // in: path + // description: id of the project + // type: string + // required: true + // - name: page + // in: query + // description: page number of results to return (1-based) + // type: integer + // - name: limit + // in: query + // description: page size of results + // type: integer + // + // responses: + // + // "200": + // "$ref": "#/responses/ProjectBoardList" + // "403": + // "$ref": "#/responses/forbidden" + // "404": + // "$ref": "#/responses/notFound" + project_id := ctx.ParamsInt64(":projectId") + project, err := project_model.GetProjectByID(ctx, project_id) + if err != nil { + ctx.Error(http.StatusNotFound, "ListProjectBoards", err) + return + } + + boards, count, err := project.GetBoardsAndCount(ctx) + if err != nil { + ctx.InternalServerError(err) + return + } + + ctx.SetLinkHeader(int(count), setting.UI.IssuePagingNum) + ctx.SetTotalCountHeader(count) + + apiBoards, err := convert.ToApiProjectBoardList(ctx, boards) + if err != nil { + ctx.InternalServerError(err) + return + } + + ctx.JSON(200, apiBoards) + +} + +func CreateProjectBoard(ctx *context.APIContext) { + // swagger:operation POST /projects/{projectId}/boards board boardCreateProjectBoard + // --- + // summary: Create project board + // produces: + // - application/json + // consumes: + // - application/json + // parameters: + // - name: projectId + // in: path + // description: id of the project + // type: string + // required: true + // - name: board + // in: body + // required: true + // schema: { "$ref": "#/definitions/NewProjectBoardPayload" } + // + // responses: + // + // "201": + // "$ref": "#/responses/ProjectBoard" + // "403": + // "$ref": "#/responses/forbidden" + // "404": + // "$ref": "#/responses/notFound" + form := web.GetForm(ctx).(*api.NewProjectBoardPayload) + + board := &project_model.Board{ + Title: form.Title, + Default: form.Default, + Sorting: form.Sorting, + Color: form.Color, + ProjectID: ctx.ParamsInt64(":projectId"), + CreatorID: ctx.Doer.ID, + } + + if err := project_model.NewBoard(ctx, board); err != nil { + ctx.InternalServerError(err) + return + } + + board, err := project_model.GetBoard(ctx, board.ID) + if err != nil { + ctx.InternalServerError(err) + return + } + + ctx.JSON(http.StatusCreated, convert.ToAPIProjectBoard(ctx, board)) +} + +func GetProjectBoard(ctx *context.APIContext) { + // swagger:operation GET /projects/boards/{boardId} board boardGetProjectBoard + // --- + // summary: Get project board + // produces: + // - application/json + // parameters: + // - name: boardId + // in: path + // description: id of the board + // type: string + // required: true + // + // responses: + // + // "200": + // "$ref": "#/responses/ProjectBoard" + // "403": + // "$ref": "#/responses/forbidden" + // "404": + // "$ref": "#/responses/notFound" + board, err := project_model.GetBoard(ctx, ctx.ParamsInt64(":boardId")) + if err != nil { + if project_model.IsErrProjectBoardNotExist(err) { + ctx.Error(http.StatusNotFound, "GetProjectBoard", err) + } else { + ctx.Error(http.StatusInternalServerError, "GetProjectBoard", err) + } + return + } + + ctx.JSON(http.StatusOK, convert.ToAPIProjectBoard(ctx, board)) +} + +func UpdateProjectBoard(ctx *context.APIContext) { + // swagger:operation PATCH /projects/boards/{boardId} board boardUpdateProjectBoard + // --- + // summary: Update project board + // produces: + // - application/json + // consumes: + // - application/json + // parameters: + // - name: boardId + // in: path + // description: id of the project board + // type: string + // required: true + // - name: board + // in: body + // required: true + // schema: { "$ref": "#/definitions/UpdateProjectBoardPayload" } + // + // responses: + // + // "200": + // "$ref": "#/responses/ProjectBoard" + // "403": + // "$ref": "#/responses/forbidden" + // "404": + // "$ref": "#/responses/notFound" + + form := web.GetForm(ctx).(*api.UpdateProjectBoardPayload) + + board, err := project_model.GetBoard(ctx, ctx.ParamsInt64(":boardId")) + if err != nil { + ctx.InternalServerError(err) + return + } + + if board.Title != form.Title { + board.Title = form.Title + } + if board.Color != form.Color { + board.Color = form.Color + } + + if err := project_model.UpdateBoard(ctx, board); err != nil { + ctx.InternalServerError(err) + return + } + + board, err = project_model.GetBoard(ctx, board.ID) + if err != nil { + ctx.InternalServerError(err) + return + } + + ctx.JSON(200, convert.ToAPIProjectBoard(ctx, board)) +} + +func DeleteProjectBoard(ctx *context.APIContext) { + // swagger:operation DELETE /projects/boards/{boardId} board boardDeleteProjectBoard + // --- + // summary: Delete project board + // produces: + // - application/json + // parameters: + // - name: boardId + // in: path + // description: id of the project board + // type: string + // required: true + // + // responses: + // + // "204": + // "description": "Project board deleted" + // "403": + // "$ref": "#/responses/forbidden" + // "404": + // "$ref": "#/responses/notFound" + if err := project_model.DeleteBoardByID(ctx, ctx.ParamsInt64(":boardId")); err != nil { + ctx.InternalServerError(err) + return + } + + ctx.Status(http.StatusNoContent) +} diff --git a/routers/api/v1/projects/project.go b/routers/api/v1/projects/project.go new file mode 100644 index 0000000000000..da07aab42f210 --- /dev/null +++ b/routers/api/v1/projects/project.go @@ -0,0 +1,404 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package projects + +import ( + "net/http" + + "code.gitea.io/gitea/models/db" + project_model "code.gitea.io/gitea/models/project" + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/setting" + api "code.gitea.io/gitea/modules/structs" + "code.gitea.io/gitea/modules/web" + "code.gitea.io/gitea/services/convert" +) + +func innerCreateProject(ctx *context.APIContext, projectType project_model.Type) { + form := web.GetForm(ctx).(*api.NewProjectPayload) + project := &project_model.Project{ + RepoID: 0, + OwnerID: ctx.Doer.ID, + Title: form.Title, + Description: form.Description, + CreatorID: ctx.Doer.ID, + BoardType: project_model.BoardType(form.BoardType), + Type: projectType, + } + + if ctx.ContextUser != nil { + project.OwnerID = ctx.ContextUser.ID + } + + if projectType == project_model.TypeRepository { + project.RepoID = ctx.Repo.Repository.ID + } + + if err := project_model.NewProject(ctx, project); err != nil { + ctx.Error(http.StatusInternalServerError, "NewProject", err) + return + } + + project, err := project_model.GetProjectByID(ctx, project.ID) + if err != nil { + ctx.Error(http.StatusInternalServerError, "NewProject", err) + return + } + + ctx.JSON(http.StatusCreated, convert.ToAPIProject(ctx, project)) +} + +func CreateUserProject(ctx *context.APIContext) { + // swagger:operation POST /user/projects project projectCreateUserProject + // --- + // summary: Create a user project + // produces: + // - application/json + // consumes: + // - application/json + // parameters: + // - name: project + // in: body + // required: true + // schema: { "$ref": "#/definitions/NewProjectPayload" } + // responses: + // "201": + // "$ref": "#/responses/Project" + // "403": + // "$ref": "#/responses/forbidden" + // "404": + // "$ref": "#/responses/notFound" + innerCreateProject(ctx, project_model.TypeIndividual) +} + +func CreateOrgProject(ctx *context.APIContext) { + // swagger:operation POST /orgs/{org}/projects project projectCreateOrgProject + // --- + // summary: Create a organization project + // produces: + // - application/json + // consumes: + // - application/json + // parameters: + // - name: org + // in: path + // description: owner of repo + // type: string + // required: true + // - name: project + // in: body + // required: true + // schema: { "$ref": "#/definitions/NewProjectPayload" } + // responses: + // "201": + // "$ref": "#/responses/Project" + // "403": + // "$ref": "#/responses/forbidden" + // "404": + // "$ref": "#/responses/notFound" + innerCreateProject(ctx, project_model.TypeOrganization) +} + +func CreateRepoProject(ctx *context.APIContext) { + // swagger:operation POST /repos/{owner}/{repo}/projects project projectCreateRepositoryProject + // --- + // summary: Create a repository project + // produces: + // - application/json + // consumes: + // - application/json + // parameters: + // - name: owner + // in: path + // description: owner of repo + // type: string + // required: true + // - name: repo + // in: path + // description: repo + // type: string + // required: true + // - name: project + // in: body + // required: true + // schema: { "$ref": "#/definitions/NewProjectPayload" } + // responses: + // "201": + // "$ref": "#/responses/Project" + // "403": + // "$ref": "#/responses/forbidden" + // "404": + // "$ref": "#/responses/notFound" + innerCreateProject(ctx, project_model.TypeRepository) +} + +func GetProject(ctx *context.APIContext) { + // swagger:operation GET /projects/{projectId} project projectGetProject + // --- + // summary: Get project + // produces: + // - application/json + // parameters: + // - name: projectId + // in: path + // description: id of the project + // type: string + // required: true + // responses: + // "200": + // "$ref": "#/responses/Project" + // "403": + // "$ref": "#/responses/forbidden" + // "404": + // "$ref": "#/responses/notFound" + project, err := project_model.GetProjectByID(ctx, ctx.ParamsInt64(":projectId")) + if err != nil { + if project_model.IsErrProjectNotExist(err) { + ctx.NotFound() + } else { + ctx.Error(http.StatusInternalServerError, "GetProjectByID", err) + } + return + } + + ctx.JSON(http.StatusOK, convert.ToAPIProject(ctx, project)) +} + +func UpdateProject(ctx *context.APIContext) { + // swagger:operation PATCH /projects/{projectId} project projectUpdateProject + // --- + // summary: Update project + // produces: + // - application/json + // consumes: + // - application/json + // parameters: + // - name: projectId + // in: path + // description: id of the project + // type: string + // required: true + // - name: project + // in: body + // required: true + // schema: { "$ref": "#/definitions/UpdateProjectPayload" } + // responses: + // "200": + // "$ref": "#/responses/Project" + // "403": + // "$ref": "#/responses/forbidden" + // "404": + // "$ref": "#/responses/notFound" + form := web.GetForm(ctx).(*api.UpdateProjectPayload) + project, err := project_model.GetProjectByID(ctx, ctx.ParamsInt64(":projectId")) + if err != nil { + if project_model.IsErrProjectNotExist(err) { + ctx.NotFound() + } else { + ctx.Error(http.StatusInternalServerError, "UpdateProject", err) + } + return + } + if project.Title != form.Title { + project.Title = form.Title + } + if project.Description != form.Description { + project.Description = form.Description + } + + err = project_model.UpdateProject(ctx, project) + if err != nil { + ctx.Error(http.StatusInternalServerError, "UpdateProject", err) + return + } + ctx.JSON(http.StatusOK, convert.ToAPIProject(ctx, project)) +} + +func DeleteProject(ctx *context.APIContext) { + // swagger:operation DELETE /projects/{projectId} project projectDeleteProject + // --- + // summary: Delete project + // parameters: + // - name: projectId + // in: path + // description: id of the project + // type: string + // required: true + // responses: + // "204": + // "description": "Deleted the project" + // "403": + // "$ref": "#/responses/forbidden" + // "404": + // "$ref": "#/responses/notFound" + + if err := project_model.DeleteProjectByID(ctx, ctx.ParamsInt64(":projectId")); err != nil { + ctx.Error(http.StatusInternalServerError, "DeleteProjectByID", err) + return + } + + ctx.Status(http.StatusNoContent) +} + +func ListUserProjects(ctx *context.APIContext) { + // swagger:operation GET /user/projects project projectListUserProjects + // --- + // summary: List repository projects + // produces: + // - application/json + // parameters: + // - name: closed + // in: query + // description: include closed issues or not + // type: boolean + // - name: page + // in: query + // description: page number of results to return (1-based) + // type: integer + // - name: limit + // in: query + // description: page size of results + // type: integer + // responses: + // "200": + // "$ref": "#/responses/ProjectList" + // "403": + // "$ref": "#/responses/forbidden" + // "404": + // "$ref": "#/responses/notFound" + projects, count, err := db.FindAndCount[project_model.Project](ctx, project_model.SearchOptions{ + Type: project_model.TypeIndividual, + IsClosed: ctx.FormOptionalBool("closed"), + OwnerID: ctx.Doer.ID, + ListOptions: db.ListOptions{Page: ctx.FormInt("page")}, + }) + if err != nil { + ctx.Error(http.StatusInternalServerError, "Projects", err) + return + } + + ctx.SetLinkHeader(int(count), setting.UI.IssuePagingNum) + ctx.SetTotalCountHeader(count) + + apiProjects, err := convert.ToAPIProjectList(ctx, projects) + if err != nil { + ctx.Error(http.StatusInternalServerError, "Projects", err) + return + } + + ctx.JSON(http.StatusOK, apiProjects) +} + +func ListOrgProjects(ctx *context.APIContext) { + // swagger:operation GET /orgs/{org}/projects project projectListOrgProjects + // --- + // summary: List repository projects + // produces: + // - application/json + // parameters: + // - name: org + // in: path + // description: owner of the repository + // type: string + // required: true + // - name: closed + // in: query + // description: include closed issues or not + // type: boolean + // - name: page + // in: query + // description: page number of results to return (1-based) + // type: integer + // - name: limit + // in: query + // description: page size of results + // type: integer + // responses: + // "200": + // "$ref": "#/responses/ProjectList" + // "403": + // "$ref": "#/responses/forbidden" + // "404": + // "$ref": "#/responses/notFound" + projects, count, err := db.FindAndCount[project_model.Project](ctx, project_model.SearchOptions{ + OwnerID: ctx.Org.Organization.AsUser().ID, + ListOptions: db.ListOptions{Page: ctx.FormInt("page")}, + IsClosed: ctx.FormOptionalBool("closed"), + Type: project_model.TypeOrganization, + }) + if err != nil { + ctx.Error(http.StatusInternalServerError, "Projects", err) + return + } + + ctx.SetLinkHeader(int(count), setting.UI.IssuePagingNum) + ctx.SetTotalCountHeader(count) + + apiProjects, err := convert.ToAPIProjectList(ctx, projects) + if err != nil { + ctx.Error(http.StatusInternalServerError, "Projects", err) + return + } + + ctx.JSON(http.StatusOK, apiProjects) +} + +func ListRepoProjects(ctx *context.APIContext) { + // swagger:operation GET /repos/{owner}/{repo}/projects project projectListRepositoryProjects + // --- + // summary: List repository projects + // produces: + // - application/json + // parameters: + // - name: owner + // in: path + // description: owner of the repository + // type: string + // required: true + // - name: repo + // in: path + // description: repo + // type: string + // required: true + // - name: closed + // in: query + // description: include closed issues or not + // type: boolean + // - name: page + // in: query + // description: page number of results to return (1-based) + // type: integer + // - name: limit + // in: query + // description: page size of results + // type: integer + // responses: + // "200": + // "$ref": "#/responses/ProjectList" + // "403": + // "$ref": "#/responses/forbidden" + // "404": + // "$ref": "#/responses/notFound" + projects, count, err := db.FindAndCount[project_model.Project](ctx, project_model.SearchOptions{ + RepoID: ctx.Repo.Repository.ID, + IsClosed: ctx.FormOptionalBool("closed"), + Type: project_model.TypeRepository, + ListOptions: db.ListOptions{Page: ctx.FormInt("page")}, + }) + if err != nil { + ctx.Error(http.StatusInternalServerError, "Projects", err) + return + } + + ctx.SetLinkHeader(int(count), setting.UI.IssuePagingNum) + ctx.SetTotalCountHeader(count) + + apiProjects, err := convert.ToAPIProjectList(ctx, projects) + if err != nil { + ctx.Error(http.StatusInternalServerError, "Projects", err) + return + } + + ctx.JSON(http.StatusOK, apiProjects) +} diff --git a/routers/api/v1/swagger/options.go b/routers/api/v1/swagger/options.go index 6f7859df62ed4..44ee48da75948 100644 --- a/routers/api/v1/swagger/options.go +++ b/routers/api/v1/swagger/options.go @@ -190,4 +190,16 @@ type swaggerParameterBodies struct { // in:body CreateOrUpdateSecretOption api.CreateOrUpdateSecretOption + + // in:body + NewProjectPayload api.NewProjectPayload + + // in:body + UpdateProjectPayload api.UpdateProjectPayload + + // in:body + NewProjectBoardPayload api.NewProjectBoardPayload + + // in:body + UpdateProjectBoardPayload api.UpdateProjectBoardPayload } diff --git a/routers/api/v1/swagger/project.go b/routers/api/v1/swagger/project.go new file mode 100644 index 0000000000000..cfa00c7faeab3 --- /dev/null +++ b/routers/api/v1/swagger/project.go @@ -0,0 +1,22 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package swagger + +import ( + api "code.gitea.io/gitea/modules/structs" +) + +// Project +// swagger:response Project +type swaggerResponseProject struct { + // in:body + Body api.Project `json:"body"` +} + +// ProjectList +// swagger:response ProjectList +type swaggerResponseProjectList struct { + // in:body + Body []api.Project `json:"body"` +} diff --git a/routers/api/v1/swagger/project_board.go b/routers/api/v1/swagger/project_board.go new file mode 100644 index 0000000000000..d9c1c26f314e7 --- /dev/null +++ b/routers/api/v1/swagger/project_board.go @@ -0,0 +1,22 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package swagger + +import ( + api "code.gitea.io/gitea/modules/structs" +) + +// ProjectBoard +// swagger:response ProjectBoard +type swaggerProjectBoard struct { + // in:body + Body api.ProjectBoard `json:"body"` +} + +// ProjectBoardList +// swagger:response ProjectBoardList +type swaggerProjectBoardList struct { + // in:body + Body []api.ProjectBoard `json:"body"` +} diff --git a/services/convert/project.go b/services/convert/project.go new file mode 100644 index 0000000000000..506202f073e6f --- /dev/null +++ b/services/convert/project.go @@ -0,0 +1,89 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package convert + +import ( + "context" + + project_model "code.gitea.io/gitea/models/project" + api "code.gitea.io/gitea/modules/structs" +) + +func ToAPIProjectBoard(ctx context.Context, board *project_model.Board) *api.ProjectBoard { + apiProjectBoard := api.ProjectBoard{ + ID: board.ID, + Title: board.Title, + Color: board.Color, + Default: board.Default, + Sorting: board.Sorting, + } + + return &apiProjectBoard +} + +func ToApiProjectBoardList( + ctx context.Context, + boards []*project_model.Board, +) ([]*api.ProjectBoard, error) { + result := make([]*api.ProjectBoard, len(boards)) + for i := range boards { + result[i] = ToAPIProjectBoard(ctx, boards[i]) + } + return result, nil +} + +func ToAPIProject(ctx context.Context, project *project_model.Project) *api.Project { + + apiProject := &api.Project{ + Title: project.Title, + Description: project.Description, + BoardType: uint8(project.BoardType), + IsClosed: project.IsClosed, + Created: project.CreatedUnix.AsTime(), + Updated: project.UpdatedUnix.AsTime(), + Closed: project.ClosedDateUnix.AsTime(), + } + + // try to laod the repo + _ = project.LoadRepo(ctx) + if project.Repo != nil { + apiProject.Repo = &api.RepositoryMeta{ + ID: project.RepoID, + Name: project.Repo.Name, + Owner: project.Repo.OwnerName, + FullName: project.Repo.FullName(), + } + } + + _ = project.LoadCreator(ctx) + if project.Creator != nil { + apiProject.Creator = &api.User{ + ID: project.Creator.ID, + UserName: project.Creator.Name, + FullName: project.Creator.FullName, + } + } + + _ = project.LoadOwner(ctx) + if project.Owner != nil { + apiProject.Owner = &api.User{ + ID: project.Owner.ID, + UserName: project.Owner.Name, + FullName: project.Owner.FullName, + } + } + + return apiProject +} + +func ToAPIProjectList( + ctx context.Context, + projects []*project_model.Project, +) ([]*api.Project, error) { + result := make([]*api.Project, len(projects)) + for i := range projects { + result[i] = ToAPIProject(ctx, projects[i]) + } + return result, nil +} diff --git a/templates/swagger/v1_json.tmpl b/templates/swagger/v1_json.tmpl index dc04a97b833c7..0ce35da96a734 100644 --- a/templates/swagger/v1_json.tmpl +++ b/templates/swagger/v1_json.tmpl @@ -2357,6 +2357,75 @@ } } }, + "/orgs/{org}/projects": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "project" + ], + "summary": "List repository projects", + "operationId": "projectListOrgProjects", + "parameters": [ + { + "type": "string", + "description": "owner of the repository", + "name": "org", + "in": "path", + "required": true + }, + { + "type": "boolean", + "description": "include closed issues or not", + "name": "closed", + "in": "query" + }, + { + "type": "integer", + "description": "page number of results to return (1-based)", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "description": "page size of results", + "name": "limit", + "in": "query" + } + ] + }, + "post": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "project" + ], + "summary": "Create a organization project", + "operationId": "projectCreateOrgProject", + "parameters": [ + { + "type": "string", + "description": "owner of repo", + "name": "org", + "in": "path", + "required": true + }, + { + "name": "project", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/NewProjectPayload" + } + } + ] + } + }, "/orgs/{org}/public_members": { "get": { "produces": [ @@ -2958,6 +3027,206 @@ } } }, + "/projects/boards/{boardId}": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "board" + ], + "summary": "Get project board", + "operationId": "boardGetProjectBoard", + "parameters": [ + { + "type": "string", + "description": "id of the board", + "name": "boardId", + "in": "path", + "required": true + } + ] + }, + "delete": { + "produces": [ + "application/json" + ], + "tags": [ + "board" + ], + "summary": "Delete project board", + "operationId": "boardDeleteProjectBoard", + "parameters": [ + { + "type": "string", + "description": "id of the project board", + "name": "boardId", + "in": "path", + "required": true + } + ] + }, + "patch": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "board" + ], + "summary": "Update project board", + "operationId": "boardUpdateProjectBoard", + "parameters": [ + { + "type": "string", + "description": "id of the project board", + "name": "boardId", + "in": "path", + "required": true + }, + { + "name": "board", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/UpdateProjectBoardPayload" + } + } + ] + } + }, + "/projects/{projectId}": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "project" + ], + "summary": "Get project", + "operationId": "projectGetProject", + "parameters": [ + { + "type": "string", + "description": "id of the project", + "name": "projectId", + "in": "path", + "required": true + } + ] + }, + "delete": { + "tags": [ + "project" + ], + "summary": "Delete project", + "operationId": "projectDeleteProject", + "parameters": [ + { + "type": "string", + "description": "id of the project", + "name": "projectId", + "in": "path", + "required": true + } + ] + }, + "patch": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "project" + ], + "summary": "Update project", + "operationId": "projectUpdateProject", + "parameters": [ + { + "type": "string", + "description": "id of the project", + "name": "projectId", + "in": "path", + "required": true + }, + { + "name": "project", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/UpdateProjectPayload" + } + } + ] + } + }, + "/projects/{projectId}/boards": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "board" + ], + "summary": "Get project boards", + "operationId": "boardGetProjectBoards", + "parameters": [ + { + "type": "string", + "description": "id of the project", + "name": "projectId", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "page number of results to return (1-based)", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "description": "page size of results", + "name": "limit", + "in": "query" + } + ] + }, + "post": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "board" + ], + "summary": "Create project board", + "operationId": "boardCreateProjectBoard", + "parameters": [ + { + "type": "string", + "description": "id of the project", + "name": "projectId", + "in": "path", + "required": true + }, + { + "name": "board", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/NewProjectBoardPayload" + } + } + ] + } + }, "/repos/issues/search": { "get": { "produces": [ @@ -10186,6 +10455,89 @@ } } }, + "/repos/{owner}/{repo}/projects": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "project" + ], + "summary": "List repository projects", + "operationId": "projectListRepositoryProjects", + "parameters": [ + { + "type": "string", + "description": "owner of the repository", + "name": "owner", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "repo", + "name": "repo", + "in": "path", + "required": true + }, + { + "type": "boolean", + "description": "include closed issues or not", + "name": "closed", + "in": "query" + }, + { + "type": "integer", + "description": "page number of results to return (1-based)", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "description": "page size of results", + "name": "limit", + "in": "query" + } + ] + }, + "post": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "project" + ], + "summary": "Create a repository project", + "operationId": "projectCreateRepositoryProject", + "parameters": [ + { + "type": "string", + "description": "owner of repo", + "name": "owner", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "repo", + "name": "repo", + "in": "path", + "required": true + }, + { + "name": "project", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/NewProjectPayload" + } + } + ] + } + }, "/repos/{owner}/{repo}/pulls": { "get": { "produces": [ @@ -15571,6 +15923,61 @@ } } }, + "/user/projects": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "project" + ], + "summary": "List repository projects", + "operationId": "projectListUserProjects", + "parameters": [ + { + "type": "boolean", + "description": "include closed issues or not", + "name": "closed", + "in": "query" + }, + { + "type": "integer", + "description": "page number of results to return (1-based)", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "description": "page size of results", + "name": "limit", + "in": "query" + } + ] + }, + "post": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "project" + ], + "summary": "Create a user project", + "operationId": "projectCreateUserProject", + "parameters": [ + { + "name": "project", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/NewProjectPayload" + } + } + ] + } + }, "/user/repos": { "get": { "produces": [ @@ -20854,6 +21261,60 @@ }, "x-go-package": "code.gitea.io/gitea/modules/structs" }, + "NewProjectBoardPayload": { + "type": "object", + "required": [ + "title" + ], + "properties": { + "Sorting": { + "type": "integer", + "format": "int8" + }, + "color": { + "type": "string", + "x-go-name": "Color" + }, + "default": { + "type": "boolean", + "x-go-name": "Default" + }, + "title": { + "type": "string", + "x-go-name": "Title" + } + }, + "x-go-package": "code.gitea.io/gitea/modules/structs" + }, + "NewProjectPayload": { + "type": "object", + "required": [ + "title", + "board_type", + "card_type" + ], + "properties": { + "board_type": { + "type": "integer", + "format": "uint8", + "x-go-name": "BoardType" + }, + "card_type": { + "type": "integer", + "format": "uint8", + "x-go-name": "CardType" + }, + "description": { + "type": "string", + "x-go-name": "Description" + }, + "title": { + "type": "string", + "x-go-name": "Title" + } + }, + "x-go-package": "code.gitea.io/gitea/modules/structs" + }, "NodeInfo": { "description": "NodeInfo contains standardized way of exposing metadata about a server running one of the distributed social networks", "type": "object", @@ -21420,6 +21881,102 @@ }, "x-go-package": "code.gitea.io/gitea/modules/structs" }, + "Project": { + "type": "object", + "properties": { + "board_type": { + "type": "integer", + "format": "uint8", + "x-go-name": "BoardType" + }, + "closed_at": { + "type": "string", + "format": "date-time", + "x-go-name": "Closed" + }, + "created_at": { + "type": "string", + "format": "date-time", + "x-go-name": "Created" + }, + "creator": { + "$ref": "#/definitions/User" + }, + "description": { + "type": "string", + "x-go-name": "Description" + }, + "id": { + "type": "integer", + "format": "int64", + "x-go-name": "ID" + }, + "is_closed": { + "type": "boolean", + "x-go-name": "IsClosed" + }, + "owner": { + "$ref": "#/definitions/User" + }, + "repository": { + "$ref": "#/definitions/RepositoryMeta" + }, + "title": { + "type": "string", + "x-go-name": "Title" + }, + "updated_at": { + "type": "string", + "format": "date-time", + "x-go-name": "Updated" + } + }, + "x-go-package": "code.gitea.io/gitea/modules/structs" + }, + "ProjectBoard": { + "type": "object", + "properties": { + "color": { + "type": "string", + "x-go-name": "Color" + }, + "created_at": { + "type": "string", + "format": "date-time", + "x-go-name": "Created" + }, + "creator": { + "$ref": "#/definitions/User" + }, + "default": { + "type": "boolean", + "x-go-name": "Default" + }, + "id": { + "type": "integer", + "format": "int64", + "x-go-name": "ID" + }, + "project": { + "$ref": "#/definitions/Project" + }, + "sorting": { + "type": "integer", + "format": "int8", + "x-go-name": "Sorting" + }, + "title": { + "type": "string", + "x-go-name": "Title" + }, + "updated_at": { + "type": "string", + "format": "date-time", + "x-go-name": "Updated" + } + }, + "x-go-package": "code.gitea.io/gitea/modules/structs" + }, "PublicKey": { "description": "PublicKey publickey is a user key to push code to repository", "type": "object", @@ -22806,6 +23363,37 @@ }, "x-go-package": "code.gitea.io/gitea/modules/structs" }, + "UpdateProjectBoardPayload": { + "type": "object", + "properties": { + "color": { + "type": "string", + "x-go-name": "Color" + }, + "title": { + "type": "string", + "x-go-name": "Title" + } + }, + "x-go-package": "code.gitea.io/gitea/modules/structs" + }, + "UpdateProjectPayload": { + "type": "object", + "required": [ + "title" + ], + "properties": { + "description": { + "type": "string", + "x-go-name": "Description" + }, + "title": { + "type": "string", + "x-go-name": "Title" + } + }, + "x-go-package": "code.gitea.io/gitea/modules/structs" + }, "UpdateRepoAvatarOption": { "description": "UpdateRepoAvatarUserOption options when updating the repo avatar", "type": "object", @@ -23747,6 +24335,36 @@ } } }, + "Project": { + "description": "Project", + "schema": { + "$ref": "#/definitions/Project" + } + }, + "ProjectBoard": { + "description": "ProjectBoard", + "schema": { + "$ref": "#/definitions/ProjectBoard" + } + }, + "ProjectBoardList": { + "description": "ProjectBoardList", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/ProjectBoard" + } + } + }, + "ProjectList": { + "description": "ProjectList", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Project" + } + } + }, "PublicKey": { "description": "PublicKey", "schema": { @@ -24142,7 +24760,7 @@ "parameterBodies": { "description": "parameterBodies", "schema": { - "$ref": "#/definitions/CreateOrUpdateSecretOption" + "$ref": "#/definitions/UpdateProjectBoardPayload" } }, "redirect": { diff --git a/tests/integration/api_project_board_test.go b/tests/integration/api_project_board_test.go new file mode 100644 index 0000000000000..fb499e28f0897 --- /dev/null +++ b/tests/integration/api_project_board_test.go @@ -0,0 +1,101 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package integration + +import ( + "fmt" + "net/http" + "net/url" + "testing" + + auth_model "code.gitea.io/gitea/models/auth" + project_model "code.gitea.io/gitea/models/project" + "code.gitea.io/gitea/models/unittest" + api "code.gitea.io/gitea/modules/structs" + "code.gitea.io/gitea/tests" + "github.com/stretchr/testify/assert" +) + +func TestAPICreateProjectBoard(t *testing.T) { + defer tests.PrepareTestEnv(t)() + token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteIssue) + + link, _ := url.Parse(fmt.Sprintf("/api/v1/projects/%d/boards", 1)) + + req := NewRequestWithJSON(t, "POST", link.String(), &api.NewProjectBoardPayload{ + Title: "Unused", + }).AddTokenAuth(token) + resp := MakeRequest(t, req, http.StatusCreated) + + var apiProjectBoard *api.ProjectBoard + DecodeJSON(t, resp, &apiProjectBoard) + + assert.Equal(t, apiProjectBoard.Title, "Unused") + unittest.AssertExistsAndLoadBean(t, &project_model.Board{ID: apiProjectBoard.ID}) +} + +func TestAPIListProjectBoards(t *testing.T) { + defer tests.PrepareTestEnv(t)() + + token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteIssue) + + link, _ := url.Parse(fmt.Sprintf("/api/v1/projects/%d/boards", 1)) + + req := NewRequest(t, "GET", link.String()).AddTokenAuth(token) + resp := MakeRequest(t, req, http.StatusOK) + + var apiProjectBoards []*api.ProjectBoard + DecodeJSON(t, resp, &apiProjectBoards) + + assert.Len(t, apiProjectBoards, 4) +} + +func TestAPIGetProjectBoard(t *testing.T) { + defer tests.PrepareTestEnv(t)() + + token := getUserToken(t, "user2", auth_model.AccessTokenScopeReadIssue) + + link, _ := url.Parse(fmt.Sprintf("/api/v1/projects/boards/%d", 1)) + + req := NewRequest(t, "GET", link.String()).AddTokenAuth(token) + resp := MakeRequest(t, req, http.StatusOK) + + var apiProjectBoard *api.ProjectBoard + DecodeJSON(t, resp, &apiProjectBoard) + + assert.Equal(t, apiProjectBoard.Title, "To Do") +} + +func TestAPIUpdateProjectBoard(t *testing.T) { + defer tests.PrepareTestEnv(t)() + token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteIssue) + + link, _ := url.Parse(fmt.Sprintf("/api/v1/projects/boards/%d", 1)) + + req := NewRequestWithJSON(t, "PATCH", link.String(), &api.UpdateProjectBoardPayload{ + Title: "Unused", + }).AddTokenAuth(token) + resp := MakeRequest(t, req, http.StatusOK) + + var apiProjectBoard *api.ProjectBoard + DecodeJSON(t, resp, &apiProjectBoard) + + assert.Equal(t, apiProjectBoard.Title, "Unused") + dbboard := &project_model.Board{ID: apiProjectBoard.ID} + unittest.AssertExistsAndLoadBean(t, dbboard) + assert.Equal(t, dbboard.Title, "Unused") +} + +func TestAPIDeleteProjectBoard(t *testing.T) { + defer tests.PrepareTestEnv(t)() + + token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteIssue) + + link, _ := url.Parse(fmt.Sprintf("/api/v1/projects/boards/%d", 1)) + + req := NewRequest(t, "DELETE", link.String()).AddTokenAuth(token) + MakeRequest(t, req, http.StatusNoContent) + + unittest.AssertNotExistsBean(t, &project_model.Board{ID: 1}) +} diff --git a/tests/integration/api_project_test.go b/tests/integration/api_project_test.go new file mode 100644 index 0000000000000..175f51cfc7771 --- /dev/null +++ b/tests/integration/api_project_test.go @@ -0,0 +1,171 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package integration + +import ( + "fmt" + "net/http" + "net/url" + "testing" + + auth_model "code.gitea.io/gitea/models/auth" + project_model "code.gitea.io/gitea/models/project" + "code.gitea.io/gitea/models/unittest" + api "code.gitea.io/gitea/modules/structs" + "code.gitea.io/gitea/tests" + "github.com/stretchr/testify/assert" +) + +func TestAPICreateUserProject(t *testing.T) { + defer tests.PrepareTestEnv(t)() + const title, description, boardType = "project_name", "project_description", uint8(project_model.BoardTypeBasicKanban) + + token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteIssue, auth_model.AccessTokenScopeWriteUser) + + req := NewRequestWithJSON(t, "POST", "/api/v1/user/projects", &api.NewProjectPayload{ + Title: title, + Description: description, + BoardType: boardType, + }).AddTokenAuth(token) + resp := MakeRequest(t, req, http.StatusCreated) + var apiProject api.Project + DecodeJSON(t, resp, &apiProject) + assert.Equal(t, title, apiProject.Title) + assert.Equal(t, description, apiProject.Description) + assert.Equal(t, boardType, apiProject.BoardType) + assert.Equal(t, "user2", apiProject.Creator.UserName) +} + +func TestAPICreateOrgProject(t *testing.T) { + defer tests.PrepareTestEnv(t)() + const title, description, boardType = "project_name", "project_description", uint8(project_model.BoardTypeBasicKanban) + + orgName := "org17" + token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteIssue, auth_model.AccessTokenScopeWriteOrganization) + urlStr := fmt.Sprintf("/api/v1/orgs/%s/projects", orgName) + + req := NewRequestWithJSON(t, "POST", urlStr, &api.NewProjectPayload{ + Title: title, + Description: description, + BoardType: boardType, + }).AddTokenAuth(token) + resp := MakeRequest(t, req, http.StatusCreated) + var apiProject api.Project + DecodeJSON(t, resp, &apiProject) + assert.Equal(t, title, apiProject.Title) + assert.Equal(t, description, apiProject.Description) + assert.Equal(t, boardType, apiProject.BoardType) + assert.Equal(t, "org17", apiProject.Owner.UserName) + assert.Equal(t, "user2", apiProject.Creator.UserName) +} + +func TestAPICreateRepoProject(t *testing.T) { + defer tests.PrepareTestEnv(t)() + const title, description, boardType = "project_name", "project_description", uint8(project_model.BoardTypeBasicKanban) + + ownerName := "user2" + repoName := "repo1" + token := getUserToken(t, ownerName, auth_model.AccessTokenScopeWriteIssue, auth_model.AccessTokenScopeWriteOrganization) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/projects", ownerName, repoName) + + req := NewRequestWithJSON(t, "POST", urlStr, &api.NewProjectPayload{ + Title: title, + Description: description, + BoardType: boardType, + }).AddTokenAuth(token) + resp := MakeRequest(t, req, http.StatusCreated) + var apiProject api.Project + DecodeJSON(t, resp, &apiProject) + assert.Equal(t, title, apiProject.Title) + assert.Equal(t, description, apiProject.Description) + assert.Equal(t, boardType, apiProject.BoardType) + assert.Equal(t, "repo1", apiProject.Repo.Name) +} + +func TestAPIListUserProjects(t *testing.T) { + defer tests.PrepareTestEnv(t)() + + token := getUserToken(t, "user2", auth_model.AccessTokenScopeReadUser, auth_model.AccessTokenScopeReadIssue) + link, _ := url.Parse(fmt.Sprintf("/api/v1/user/projects")) + + req := NewRequest(t, "GET", link.String()).AddTokenAuth(token) + var apiProjects []*api.Project + + resp := MakeRequest(t, req, http.StatusOK) + DecodeJSON(t, resp, &apiProjects) + assert.Len(t, apiProjects, 1) +} + +func TestAPIListOrgProjects(t *testing.T) { + defer tests.PrepareTestEnv(t)() + + orgName := "org17" + token := getUserToken(t, "user2", auth_model.AccessTokenScopeReadOrganization, auth_model.AccessTokenScopeReadIssue) + link, _ := url.Parse(fmt.Sprintf("/api/v1/orgs/%s/projects", orgName)) + + req := NewRequest(t, "GET", link.String()).AddTokenAuth(token) + var apiProjects []*api.Project + + resp := MakeRequest(t, req, http.StatusOK) + DecodeJSON(t, resp, &apiProjects) + assert.Len(t, apiProjects, 1) +} + +func TestAPIListRepoProjects(t *testing.T) { + defer tests.PrepareTestEnv(t)() + + ownerName := "user2" + repoName := "repo1" + token := getUserToken(t, "user2", auth_model.AccessTokenScopeReadRepository, auth_model.AccessTokenScopeReadIssue) + link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/projects", ownerName, repoName)) + + req := NewRequest(t, "GET", link.String()).AddTokenAuth(token) + var apiProjects []*api.Project + + resp := MakeRequest(t, req, http.StatusOK) + DecodeJSON(t, resp, &apiProjects) + assert.Len(t, apiProjects, 1) +} + +func TestAPIGetProject(t *testing.T) { + defer tests.PrepareTestEnv(t)() + token := getUserToken(t, "user2", auth_model.AccessTokenScopeReadUser, auth_model.AccessTokenScopeReadIssue) + link, _ := url.Parse(fmt.Sprintf("/api/v1/projects/%d", 1)) + + req := NewRequest(t, "GET", link.String()).AddTokenAuth(token) + var apiProject *api.Project + + resp := MakeRequest(t, req, http.StatusOK) + DecodeJSON(t, resp, &apiProject) + assert.Equal(t, "First project", apiProject.Title) + assert.Equal(t, "repo1", apiProject.Repo.Name) + assert.Equal(t, "user2", apiProject.Creator.UserName) +} + +func TestAPIUpdateProject(t *testing.T) { + defer tests.PrepareTestEnv(t)() + token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteUser, auth_model.AccessTokenScopeWriteIssue) + link, _ := url.Parse(fmt.Sprintf("/api/v1/projects/%d", 1)) + + req := NewRequestWithJSON(t, "PATCH", link.String(), &api.UpdateProjectPayload{ + Title: "First project updated", + }).AddTokenAuth(token) + + var apiProject *api.Project + + resp := MakeRequest(t, req, http.StatusOK) + DecodeJSON(t, resp, &apiProject) + assert.Equal(t, "First project updated", apiProject.Title) +} + +func TestAPIDeleteProject(t *testing.T) { + defer tests.PrepareTestEnv(t)() + token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteUser, auth_model.AccessTokenScopeWriteIssue) + link, _ := url.Parse(fmt.Sprintf("/api/v1/projects/%d", 1)) + + req := NewRequest(t, "DELETE", link.String()).AddTokenAuth(token) + + MakeRequest(t, req, http.StatusNoContent) + unittest.AssertNotExistsBean(t, &project_model.Project{ID: 1}) +}