1
0
mirror of https://github.com/mattermost/focalboard.git synced 2025-01-11 18:13:52 +02:00

Merge branch 'main' into issue-2617

This commit is contained in:
Doug Lauder 2022-03-29 21:59:10 -04:00 committed by GitHub
commit 8541c3a356
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 1314 additions and 100 deletions

View File

@ -4,9 +4,7 @@ Thank you for your interest in contributing! Please read the [Focalboard Contrib
When you submit a pull request, it goes through a code review process outlined [here](https://developers.mattermost.com/contribute/getting-started/code-review/).
## Updating Changelog
After a noteable bug fix or improvement is merged, submit a pull request to the [CHANGELOG.md](https://github.com/mattermost/focalboard/blob/main/CHANGELOG.md) under the next release section.
After a noteable bug fix or improvement is merged, submit a pull request to the [CHANGELOG](CHANGELOG.md) under the next release section.
## Bug Reports

View File

@ -63,7 +63,7 @@ To run the server:
./bin/focalboard-server
```
Then navigate your browser to `[http://localhost:8000](http://localhost:8000)` to access your Focalboard server. The port is configured in `config.json`.
Then navigate your browser to [`http://localhost:8000`](http://localhost:8000) to access your Focalboard server. The port is configured in `config.json`.
Once the server is running, you can rebuild just the web app via `make webapp` in a separate terminal window. Reload your browser to see the changes.
@ -115,7 +115,7 @@ Help translate Focalboard! The app is already translated into several languages.
Are you interested in influencing the future of the Focalboard open source project? Here's how you can get involved:
* **Changelog**: See [CHANGELOG.md](CHANGELOG.md) for the latest updates
* **Changes**: See the [CHANGELOG](CHANGELOG.md) for the latest updates
* **GitHub Discussions**: Join the [Developer Discussion](https://github.com/mattermost/focalboard/discussions) board
* **Bug Reports**: [File a bug report](https://github.com/mattermost/focalboard/issues/new?assignees=&labels=bug&template=bug_report.md&title=)
* **Chat**: Join the [Focalboard community channel](https://community.mattermost.com/core/channels/focalboard)

View File

@ -189,8 +189,11 @@ export default class Plugin {
if (currentTeamID && currentTeamID !== prevTeamID) {
prevTeamID = currentTeamID
store.dispatch(setTeam(currentTeamID))
browserHistory.push(`/team/${currentTeamID}`)
wsClient.subscribeToTeam(currentTeamID)
if (window.location.pathname.startsWith(windowAny.frontendBaseURL || '')) {
console.log("REDIRECTING HERE")
browserHistory.push(`/team/${currentTeamID}`)
wsClient.subscribeToTeam(currentTeamID)
}
}
})

View File

@ -89,6 +89,7 @@ func (a *API) RegisterRoutes(r *mux.Router) {
apiv1.HandleFunc("/boards/{boardID}/blocks/{blockID}/undelete", a.sessionRequired(a.handleUndeleteBlock)).Methods("POST")
apiv1.HandleFunc("/boards/{boardID}/blocks/{blockID}/subtree", a.attachSession(a.handleGetSubTree, false)).Methods("GET")
apiv1.HandleFunc("/boards/{boardID}/blocks/{blockID}/duplicate", a.attachSession(a.handleDuplicateBlock, false)).Methods("POST")
apiv1.HandleFunc("/boards/{boardID}/metadata", a.sessionRequired(a.handleGetBoardMetadata)).Methods("GET")
// Import&Export APIs
apiv1.HandleFunc("/boards/{boardID}/blocks/export", a.sessionRequired(a.handleExport)).Methods("GET")
@ -2973,6 +2974,81 @@ func (a *API) handleDuplicateBlock(w http.ResponseWriter, r *http.Request) {
auditRec.Success()
}
func (a *API) handleGetBoardMetadata(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /api/v1/boards/{boardID}/metadata getBoardMetadata
//
// Returns a board's metadata
//
// ---
// produces:
// - application/json
// parameters:
// - name: boardID
// in: path
// description: Board ID
// required: true
// type: string
// security:
// - BearerAuth: []
// responses:
// '200':
// description: success
// schema:
// "$ref": "#/definitions/BoardMetadata"
// '404':
// description: board not found
// '501':
// description: required license not found
// default:
// description: internal error
// schema:
// "$ref": "#/definitions/ErrorResponse"
boardID := mux.Vars(r)["boardID"]
userID := getUserID(r)
board, boardMetadata, err := a.app.GetBoardMetadata(boardID)
if errors.Is(err, app.ErrInsufficientLicense) {
a.errorResponse(w, r.URL.Path, http.StatusNotImplemented, "", err)
return
}
if err != nil {
a.errorResponse(w, r.URL.Path, http.StatusInternalServerError, "", err)
return
}
if board == nil || boardMetadata == nil {
a.errorResponse(w, r.URL.Path, http.StatusNotFound, "", nil)
return
}
if board.Type == model.BoardTypePrivate {
if !a.permissions.HasPermissionToBoard(userID, boardID, model.PermissionViewBoard) {
a.errorResponse(w, r.URL.Path, http.StatusForbidden, "", PermissionError{"access denied to board"})
return
}
} else {
if !a.permissions.HasPermissionToTeam(userID, board.TeamID, model.PermissionViewTeam) {
a.errorResponse(w, r.URL.Path, http.StatusForbidden, "", PermissionError{"access denied to board"})
return
}
}
auditRec := a.makeAuditRecord(r, "getBoardMetadata", audit.Fail)
defer a.audit.LogRecord(audit.LevelRead, auditRec)
auditRec.AddMeta("boardID", boardID)
data, err := json.Marshal(boardMetadata)
if err != nil {
a.errorResponse(w, r.URL.Path, http.StatusInternalServerError, "", err)
return
}
// response
jsonBytesResponse(w, http.StatusOK, data)
auditRec.Success()
}
func (a *API) handleSearchBoards(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /api/v1/teams/{teamID}/boards/search searchBoards
//

View File

@ -3,6 +3,7 @@ package app
import (
"database/sql"
"errors"
"fmt"
"github.com/mattermost/focalboard/server/model"
"github.com/mattermost/focalboard/server/utils"
@ -11,6 +12,7 @@ import (
var (
ErrBoardMemberIsLastAdmin = errors.New("cannot leave a board with no admins")
ErrNewBoardCannotHaveID = errors.New("new board cannot have an ID")
ErrInsufficientLicense = errors.New("appropriate license required")
)
func (a *App) GetBoard(boardID string) (*model.Board, error) {
@ -24,6 +26,105 @@ func (a *App) GetBoard(boardID string) (*model.Board, error) {
return board, nil
}
func (a *App) GetBoardMetadata(boardID string) (*model.Board, *model.BoardMetadata, error) {
license := a.store.GetLicense()
if license == nil || !(*license.Features.Compliance) {
return nil, nil, ErrInsufficientLicense
}
board, err := a.GetBoard(boardID)
if err != nil {
return nil, nil, err
}
if board == nil {
// Board may have been deleted, retrieve most recent history instead
board, err = a.getBoardHistory(boardID, true)
if err != nil {
return nil, nil, err
}
}
if board == nil {
// Board not found
return nil, nil, nil
}
earliestTime, _, err := a.getBoardDescendantModifiedInfo(boardID, false)
if err != nil {
return nil, nil, err
}
latestTime, lastModifiedBy, err := a.getBoardDescendantModifiedInfo(boardID, true)
if err != nil {
return nil, nil, err
}
boardMetadata := model.BoardMetadata{
BoardID: boardID,
DescendantFirstUpdateAt: earliestTime,
DescendantLastUpdateAt: latestTime,
CreatedBy: board.CreatedBy,
LastModifiedBy: lastModifiedBy,
}
return board, &boardMetadata, nil
}
func (a *App) getBoardHistory(boardID string, latest bool) (*model.Board, error) {
opts := model.QueryBlockHistoryOptions{
Limit: 1,
Descending: latest,
}
boards, err := a.store.GetBoardHistory(boardID, opts)
if err != nil {
return nil, fmt.Errorf("could not get history for board: %w", err)
}
if len(boards) == 0 {
return nil, nil
}
return boards[0], nil
}
func (a *App) getBoardDescendantModifiedInfo(boardID string, latest bool) (int64, string, error) {
board, err := a.getBoardHistory(boardID, latest)
if err != nil {
return 0, "", err
}
if board == nil {
return 0, "", fmt.Errorf("history not found for board: %w", err)
}
var timestamp int64
modifiedBy := board.ModifiedBy
if latest {
timestamp = board.UpdateAt
} else {
timestamp = board.CreateAt
}
// use block_history to fetch blocks in case they were deleted and no longer exist in blocks table.
opts := model.QueryBlockHistoryOptions{
Limit: 1,
Descending: latest,
}
blocks, err := a.store.GetBlockHistoryDescendants(boardID, opts)
if err != nil {
return 0, "", fmt.Errorf("could not get blocks history descendants for board: %w", err)
}
if len(blocks) > 0 {
// Compare the board history info with the descendant block info, if it exists
block := &blocks[0]
if latest && block.UpdateAt > timestamp {
timestamp = block.UpdateAt
modifiedBy = block.ModifiedBy
} else if !latest && block.CreateAt < timestamp {
timestamp = block.CreateAt
modifiedBy = block.ModifiedBy
}
}
return timestamp, modifiedBy, nil
}
func (a *App) DuplicateBoard(boardID, userID, toTeam string, asTemplate bool) (*model.BoardsAndBlocks, []*model.BoardMember, error) {
bab, members, err := a.store.DuplicateBoard(boardID, userID, toTeam, asTemplate)
if err != nil {

View File

@ -176,6 +176,10 @@ func (c *Client) GetBoardRoute(boardID string) string {
return fmt.Sprintf("%s/%s", c.GetBoardsRoute(), boardID)
}
func (c *Client) GetBoardMetadataRoute(boardID string) string {
return fmt.Sprintf("%s/%s/metadata", c.GetBoardsRoute(), boardID)
}
func (c *Client) GetJoinBoardRoute(boardID string) string {
return fmt.Sprintf("%s/%s/join", c.GetBoardsRoute(), boardID)
}
@ -184,6 +188,10 @@ func (c *Client) GetBlocksRoute(boardID string) string {
return fmt.Sprintf("%s/blocks", c.GetBoardRoute(boardID))
}
func (c *Client) GetAllBlocksRoute(boardID string) string {
return fmt.Sprintf("%s/blocks?all=true", c.GetBoardRoute(boardID))
}
func (c *Client) GetBoardsAndBlocksRoute() string {
return "/boards-and-blocks"
}
@ -208,6 +216,16 @@ func (c *Client) GetBlocksForBoard(boardID string) ([]model.Block, *Response) {
return model.BlocksFromJSON(r.Body), BuildResponse(r)
}
func (c *Client) GetAllBlocksForBoard(boardID string) ([]model.Block, *Response) {
r, err := c.DoAPIGet(c.GetAllBlocksRoute(boardID), "")
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return model.BlocksFromJSON(r.Body), BuildResponse(r)
}
func (c *Client) PatchBlock(boardID, blockID string, blockPatch *model.BlockPatch) (bool, *Response) {
r, err := c.DoAPIPatch(c.GetBlockRoute(boardID, blockID), toJSON(blockPatch))
if err != nil {
@ -218,18 +236,21 @@ func (c *Client) PatchBlock(boardID, blockID string, blockPatch *model.BlockPatc
return true, BuildResponse(r)
}
func (c *Client) DuplicateBoard(boardID string, asTemplate bool, teamID string) (bool, *Response) {
func (c *Client) DuplicateBoard(boardID string, asTemplate bool, teamID string) (*model.BoardsAndBlocks, *Response) {
queryParams := "?asTemplate=false&"
if asTemplate {
queryParams = "?asTemplate=true"
}
if len(teamID) > 0 {
queryParams = queryParams + "&toTeam=" + teamID
}
r, err := c.DoAPIPost(c.GetBoardRoute(boardID)+"/duplicate"+queryParams, "")
if err != nil {
return false, BuildErrorResponse(r, err)
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return true, BuildResponse(r)
return model.BoardsAndBlocksFromJSON(r.Body), BuildResponse(r)
}
func (c *Client) DuplicateBlock(boardID, blockID string, asTemplate bool) (bool, *Response) {
@ -476,6 +497,21 @@ func (c *Client) GetBoard(boardID, readToken string) (*model.Board, *Response) {
return model.BoardFromJSON(r.Body), BuildResponse(r)
}
func (c *Client) GetBoardMetadata(boardID, readToken string) (*model.BoardMetadata, *Response) {
url := c.GetBoardMetadataRoute(boardID)
if readToken != "" {
url += fmt.Sprintf("?read_token=%s", readToken)
}
r, err := c.DoAPIGet(url, "")
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return model.BoardMetadataFromJSON(r.Body), BuildResponse(r)
}
func (c *Client) GetBoardsForTeam(teamID string) ([]*model.Board, *Response) {
r, err := c.DoAPIGet(c.GetTeamRoute(teamID)+"/boards", "")
if err != nil {
@ -627,3 +663,13 @@ func (c *Client) GetSubscriptions(subscriberID string) ([]*model.Subscription, *
return subs, BuildResponse(r)
}
func (c *Client) GetTemplatesForTeam(teamID string) ([]*model.Board, *Response) {
r, err := c.DoAPIGet(c.GetTeamRoute(teamID)+"/templates", "")
if err != nil {
return nil, BuildErrorResponse(r, err)
}
defer closeBody(r)
return model.BoardsFromJSON(r.Body), BuildResponse(r)
}

View File

@ -3,6 +3,7 @@ package integrationtests
import (
"encoding/json"
"testing"
"time"
"github.com/mattermost/focalboard/server/client"
"github.com/mattermost/focalboard/server/model"
@ -469,6 +470,185 @@ func TestGetBoard(t *testing.T) {
})
}
func TestGetBoardMetadata(t *testing.T) {
t.Run("a non authenticated user should be rejected", func(t *testing.T) {
th := SetupTestHelperWithLicense(t, LicenseEnterprise).InitBasic()
defer th.TearDown()
th.Logout(th.Client)
boardMetadata, resp := th.Client.GetBoardMetadata("boar-id", "")
th.CheckUnauthorized(resp)
require.Nil(t, boardMetadata)
})
t.Run("getBoardMetadata query is correct", func(t *testing.T) {
th := SetupTestHelperWithLicense(t, LicenseEnterprise).InitBasic()
defer th.TearDown()
th.Server.Config().EnablePublicSharedBoards = true
teamID := testTeamID
board := &model.Board{
Title: "public board where user1 is admin",
Type: model.BoardTypeOpen,
TeamID: teamID,
}
rBoard, err := th.Server.App().CreateBoard(board, th.GetUser1().ID, true)
require.NoError(t, err)
// Check metadata
boardMetadata, resp := th.Client.GetBoardMetadata(rBoard.ID, "")
th.CheckOK(resp)
require.NotNil(t, boardMetadata)
require.Equal(t, rBoard.CreatedBy, boardMetadata.CreatedBy)
require.Equal(t, rBoard.CreateAt, boardMetadata.DescendantFirstUpdateAt)
require.Equal(t, rBoard.UpdateAt, boardMetadata.DescendantLastUpdateAt)
require.Equal(t, rBoard.ModifiedBy, boardMetadata.LastModifiedBy)
// Insert card1
card1 := model.Block{
ID: "card1",
BoardID: rBoard.ID,
Title: "Card 1",
}
time.Sleep(20 * time.Millisecond)
require.NoError(t, th.Server.App().InsertBlock(card1, th.GetUser2().ID))
rCard1, err := th.Server.App().GetBlockByID(card1.ID)
require.NoError(t, err)
// Check updated metadata
boardMetadata, resp = th.Client.GetBoardMetadata(rBoard.ID, "")
th.CheckOK(resp)
require.NotNil(t, boardMetadata)
require.Equal(t, rBoard.CreatedBy, boardMetadata.CreatedBy)
require.Equal(t, rBoard.CreateAt, boardMetadata.DescendantFirstUpdateAt)
require.Equal(t, rCard1.UpdateAt, boardMetadata.DescendantLastUpdateAt)
require.Equal(t, rCard1.ModifiedBy, boardMetadata.LastModifiedBy)
// Insert card2
card2 := model.Block{
ID: "card2",
BoardID: rBoard.ID,
Title: "Card 2",
}
time.Sleep(20 * time.Millisecond)
require.NoError(t, th.Server.App().InsertBlock(card2, th.GetUser1().ID))
rCard2, err := th.Server.App().GetBlockByID(card2.ID)
require.NoError(t, err)
// Check updated metadata
boardMetadata, resp = th.Client.GetBoardMetadata(rBoard.ID, "")
th.CheckOK(resp)
require.NotNil(t, boardMetadata)
require.Equal(t, rBoard.CreatedBy, boardMetadata.CreatedBy)
require.Equal(t, rBoard.CreateAt, boardMetadata.DescendantFirstUpdateAt)
require.Equal(t, rCard2.UpdateAt, boardMetadata.DescendantLastUpdateAt)
require.Equal(t, rCard2.ModifiedBy, boardMetadata.LastModifiedBy)
t.Run("After delete board", func(t *testing.T) {
// Delete board
time.Sleep(20 * time.Millisecond)
require.NoError(t, th.Server.App().DeleteBoard(rBoard.ID, th.GetUser1().ID))
// Check updated metadata
boardMetadata, resp = th.Client.GetBoardMetadata(rBoard.ID, "")
th.CheckOK(resp)
require.NotNil(t, boardMetadata)
require.Equal(t, rBoard.CreatedBy, boardMetadata.CreatedBy)
require.Equal(t, rBoard.CreateAt, boardMetadata.DescendantFirstUpdateAt)
require.Greater(t, boardMetadata.DescendantLastUpdateAt, rCard2.UpdateAt)
require.Equal(t, th.GetUser1().ID, boardMetadata.LastModifiedBy)
})
})
t.Run("getBoardMetadata should fail with no license", func(t *testing.T) {
th := SetupTestHelperWithLicense(t, LicenseNone).InitBasic()
defer th.TearDown()
th.Server.Config().EnablePublicSharedBoards = true
teamID := testTeamID
board := &model.Board{
Title: "public board where user1 is admin",
Type: model.BoardTypeOpen,
TeamID: teamID,
}
rBoard, err := th.Server.App().CreateBoard(board, th.GetUser1().ID, true)
require.NoError(t, err)
// Check metadata
boardMetadata, resp := th.Client.GetBoardMetadata(rBoard.ID, "")
th.CheckNotImplemented(resp)
require.Nil(t, boardMetadata)
})
t.Run("getBoardMetadata should fail on Professional license", func(t *testing.T) {
th := SetupTestHelperWithLicense(t, LicenseProfessional).InitBasic()
defer th.TearDown()
th.Server.Config().EnablePublicSharedBoards = true
teamID := testTeamID
board := &model.Board{
Title: "public board where user1 is admin",
Type: model.BoardTypeOpen,
TeamID: teamID,
}
rBoard, err := th.Server.App().CreateBoard(board, th.GetUser1().ID, true)
require.NoError(t, err)
// Check metadata
boardMetadata, resp := th.Client.GetBoardMetadata(rBoard.ID, "")
th.CheckNotImplemented(resp)
require.Nil(t, boardMetadata)
})
t.Run("valid read token should not get the board metadata", func(t *testing.T) {
th := SetupTestHelperWithLicense(t, LicenseEnterprise).InitBasic()
defer th.TearDown()
th.Server.Config().EnablePublicSharedBoards = true
teamID := testTeamID
sharingToken := utils.NewID(utils.IDTypeToken)
userID := th.GetUser1().ID
board := &model.Board{
Title: "public board where user1 is admin",
Type: model.BoardTypeOpen,
TeamID: teamID,
}
rBoard, err := th.Server.App().CreateBoard(board, userID, true)
require.NoError(t, err)
sharing := &model.Sharing{
ID: rBoard.ID,
Enabled: true,
Token: sharingToken,
UpdateAt: 1,
}
success, resp := th.Client.PostSharing(sharing)
th.CheckOK(resp)
require.True(t, success)
// the client logs out
th.Logout(th.Client)
// we make sure that the client cannot currently retrieve the
// board with no session
boardMetadata, resp := th.Client.GetBoardMetadata(rBoard.ID, "")
th.CheckUnauthorized(resp)
require.Nil(t, boardMetadata)
// it should not be able to retrieve it with the read token either
boardMetadata, resp = th.Client.GetBoardMetadata(rBoard.ID, sharingToken)
th.CheckUnauthorized(resp)
require.Nil(t, boardMetadata)
})
}
func TestPatchBoard(t *testing.T) {
teamID := testTeamID
@ -1270,6 +1450,56 @@ func TestDeleteMember(t *testing.T) {
})
}
func TestGetTemplates(t *testing.T) {
t.Run("should be able to retrieve built-in templates", func(t *testing.T) {
th := SetupTestHelper(t).InitBasic()
defer th.TearDown()
teamID := "my-team-id"
rBoards, resp := th.Client.GetTemplatesForTeam("0")
th.CheckOK(resp)
require.NotNil(t, rBoards)
require.GreaterOrEqual(t, len(rBoards), 6)
t.Log("\n\n")
for _, board := range rBoards {
t.Logf("Test get template: %s - %s\n", board.Title, board.ID)
rBoard, resp := th.Client.GetBoard(board.ID, "")
th.CheckOK(resp)
require.NotNil(t, rBoard)
require.Equal(t, board, rBoard)
rBlocks, resp := th.Client.GetAllBlocksForBoard(board.ID)
th.CheckOK(resp)
require.NotNil(t, rBlocks)
require.Greater(t, len(rBlocks), 0)
t.Logf("Got %d block(s)\n", len(rBlocks))
rBoardsAndBlock, resp := th.Client.DuplicateBoard(board.ID, false, teamID)
th.CheckOK(resp)
require.NotNil(t, rBoardsAndBlock)
require.Greater(t, len(rBoardsAndBlock.Boards), 0)
require.Greater(t, len(rBoardsAndBlock.Blocks), 0)
rBoard2 := rBoardsAndBlock.Boards[0]
require.Contains(t, board.Title, rBoard2.Title)
require.False(t, rBoard2.IsTemplate)
t.Logf("Duplicate template: %s - %s, %d block(s)\n", rBoard2.Title, rBoard2.ID, len(rBoardsAndBlock.Blocks))
rBoard3, resp := th.Client.GetBoard(rBoard2.ID, "")
th.CheckOK(resp)
require.NotNil(t, rBoard3)
require.Equal(t, rBoard2, rBoard3)
rBlocks2, resp := th.Client.GetAllBlocksForBoard(rBoard2.ID)
th.CheckOK(resp)
require.NotNil(t, rBlocks2)
require.Equal(t, len(rBoardsAndBlock.Blocks), len(rBlocks2))
}
t.Log("\n\n")
})
}
func TestJoinBoard(t *testing.T) {
t.Run("create and join public board", func(t *testing.T) {
th := SetupTestHelper(t).InitBasic()

View File

@ -13,6 +13,7 @@ import (
"github.com/mattermost/focalboard/server/server"
"github.com/mattermost/focalboard/server/services/config"
"github.com/mattermost/focalboard/server/services/permissions/localpermissions"
"github.com/mattermost/focalboard/server/services/store"
"github.com/mattermost/focalboard/server/services/store/sqlstore"
"github.com/mattermost/mattermost-server/v6/shared/mlog"
@ -26,6 +27,14 @@ const (
password = "Pa$$word"
)
type LicenseType int
const (
LicenseNone LicenseType = iota // 0
LicenseProfessional // 1
LicenseEnterprise // 2
)
type TestHelper struct {
T *testing.T
Server *server.Server
@ -77,6 +86,10 @@ func getTestConfig() (*config.Configuration, error) {
}
func newTestServer(singleUserToken string) *server.Server {
return newTestServerWithLicense(singleUserToken, LicenseNone)
}
func newTestServerWithLicense(singleUserToken string, licenseType LicenseType) *server.Server {
cfg, err := getTestConfig()
if err != nil {
panic(err)
@ -86,11 +99,24 @@ func newTestServer(singleUserToken string) *server.Server {
if err = logger.Configure("", cfg.LoggingCfgJSON, nil); err != nil {
panic(err)
}
db, err := server.NewStore(cfg, logger)
innerStore, err := server.NewStore(cfg, logger)
if err != nil {
panic(err)
}
var db store.Store
switch licenseType {
case LicenseProfessional:
db = NewTestProfessionalStore(innerStore)
case LicenseEnterprise:
db = NewTestEnterpriseStore(innerStore)
case LicenseNone:
fallthrough
default:
db = innerStore
}
permissionsService := localpermissions.New(db, logger)
params := server.Params{
@ -119,8 +145,12 @@ func SetupTestHelperWithToken(t *testing.T) *TestHelper {
}
func SetupTestHelper(t *testing.T) *TestHelper {
return SetupTestHelperWithLicense(t, LicenseNone)
}
func SetupTestHelperWithLicense(t *testing.T, licenseType LicenseType) *TestHelper {
th := &TestHelper{T: t}
th.Server = newTestServer("")
th.Server = newTestServerWithLicense("", licenseType)
th.Client = client.NewClient(th.Server.Config().ServerRoot, "")
th.Client2 = client.NewClient(th.Server.Config().ServerRoot, "")
return th
@ -290,3 +320,8 @@ func (th *TestHelper) CheckRequestEntityTooLarge(r *client.Response) {
require.Equal(th.T, http.StatusRequestEntityTooLarge, r.StatusCode)
require.Error(th.T, r.Error)
}
func (th *TestHelper) CheckNotImplemented(r *client.Response) {
require.Equal(th.T, http.StatusNotImplemented, r.StatusCode)
require.Error(th.T, r.Error)
}

View File

@ -0,0 +1,110 @@
package integrationtests
import (
"github.com/mattermost/focalboard/server/services/store"
mmModel "github.com/mattermost/mattermost-server/v6/model"
)
type TestStore struct {
store.Store
license *mmModel.License
}
func NewTestEnterpriseStore(store store.Store) *TestStore {
usersValue := 10000
trueValue := true
falseValue := false
license := &mmModel.License{
Features: &mmModel.Features{
Users: &usersValue,
LDAP: &trueValue,
LDAPGroups: &trueValue,
MFA: &trueValue,
GoogleOAuth: &trueValue,
Office365OAuth: &trueValue,
OpenId: &trueValue,
Compliance: &trueValue,
Cluster: &trueValue,
Metrics: &trueValue,
MHPNS: &trueValue,
SAML: &trueValue,
Elasticsearch: &trueValue,
Announcement: &trueValue,
ThemeManagement: &trueValue,
EmailNotificationContents: &trueValue,
DataRetention: &trueValue,
MessageExport: &trueValue,
CustomPermissionsSchemes: &trueValue,
CustomTermsOfService: &trueValue,
GuestAccounts: &trueValue,
GuestAccountsPermissions: &trueValue,
IDLoadedPushNotifications: &trueValue,
LockTeammateNameDisplay: &trueValue,
EnterprisePlugins: &trueValue,
AdvancedLogging: &trueValue,
Cloud: &falseValue,
SharedChannels: &trueValue,
RemoteClusterService: &trueValue,
FutureFeatures: &trueValue,
},
}
testStore := &TestStore{
Store: store,
license: license,
}
return testStore
}
func NewTestProfessionalStore(store store.Store) *TestStore {
usersValue := 10000
trueValue := true
falseValue := false
license := &mmModel.License{
Features: &mmModel.Features{
Users: &usersValue,
LDAP: &falseValue,
LDAPGroups: &falseValue,
MFA: &trueValue,
GoogleOAuth: &trueValue,
Office365OAuth: &trueValue,
OpenId: &trueValue,
Compliance: &falseValue,
Cluster: &falseValue,
Metrics: &trueValue,
MHPNS: &trueValue,
SAML: &trueValue,
Elasticsearch: &trueValue,
Announcement: &trueValue,
ThemeManagement: &trueValue,
EmailNotificationContents: &trueValue,
DataRetention: &trueValue,
MessageExport: &trueValue,
CustomPermissionsSchemes: &trueValue,
CustomTermsOfService: &trueValue,
GuestAccounts: &trueValue,
GuestAccountsPermissions: &trueValue,
IDLoadedPushNotifications: &trueValue,
LockTeammateNameDisplay: &trueValue,
EnterprisePlugins: &falseValue,
AdvancedLogging: &trueValue,
Cloud: &falseValue,
SharedChannels: &trueValue,
RemoteClusterService: &falseValue,
FutureFeatures: &trueValue,
},
}
testStore := &TestStore{
Store: store,
license: license,
}
return testStore
}
func (s *TestStore) GetLicense() *mmModel.License {
return s.license
}

View File

@ -168,6 +168,30 @@ type BoardMember struct {
SchemeViewer bool `json:"schemeViewer"`
}
// BoardMetadata contains metadata for a Board
// swagger:model
type BoardMetadata struct {
// The ID for the board
// required: true
BoardID string `json:"boardId"`
// The most recent time a descendant of this board was added, modified, or deleted
// required: true
DescendantLastUpdateAt int64 `json:"descendantLastUpdateAt"`
// The earliest time a descendant of this board was added, modified, or deleted
// required: true
DescendantFirstUpdateAt int64 `json:"descendantFirstUpdateAt"`
// The ID of the user that created the board
// required: true
CreatedBy string `json:"createdBy"`
// The ID of the user that last modified the most recently modified descendant
// required: true
LastModifiedBy string `json:"lastModifiedBy"`
}
func BoardFromJSON(data io.Reader) *Board {
var board *Board
_ = json.NewDecoder(data).Decode(&board)
@ -192,6 +216,12 @@ func BoardMembersFromJSON(data io.Reader) []*BoardMember {
return boardMembers
}
func BoardMetadataFromJSON(data io.Reader) *BoardMetadata {
var boardMetadata *BoardMetadata
_ = json.NewDecoder(data).Decode(&boardMetadata)
return boardMetadata
}
// Patch returns an updated version of the board.
func (p *BoardPatch) Patch(board *Board) *Board {
if p.Type != nil {

View File

@ -19,6 +19,7 @@ import (
"github.com/mattermost/focalboard/server/model"
"github.com/mattermost/mattermost-server/v6/shared/mlog"
mmModel "github.com/mattermost/mattermost-server/v6/model"
)
{{range $index, $element := .Methods}}

View File

@ -12,6 +12,7 @@ import (
"github.com/mattermost/focalboard/server/services/store"
"github.com/mattermost/focalboard/server/utils"
mmModel "github.com/mattermost/mattermost-server/v6/model"
"github.com/mattermost/mattermost-server/v6/shared/mlog"
)
@ -385,3 +386,7 @@ func (s *MattermostAuthLayer) CreatePrivateWorkspace(userID string) (string, err
return channel.Id, nil
}
func (s *MattermostAuthLayer) GetLicense() *mmModel.License {
return s.pluginAPI.GetLicense()
}

View File

@ -10,6 +10,7 @@ import (
gomock "github.com/golang/mock/gomock"
model "github.com/mattermost/focalboard/server/model"
model0 "github.com/mattermost/mattermost-server/v6/model"
)
// MockStore is a mock of Store interface.
@ -383,6 +384,21 @@ func (mr *MockStoreMockRecorder) GetBlockHistory(arg0, arg1 interface{}) *gomock
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlockHistory", reflect.TypeOf((*MockStore)(nil).GetBlockHistory), arg0, arg1)
}
// GetBlockHistoryDescendants mocks base method.
func (m *MockStore) GetBlockHistoryDescendants(arg0 string, arg1 model.QueryBlockHistoryOptions) ([]model.Block, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetBlockHistoryDescendants", arg0, arg1)
ret0, _ := ret[0].([]model.Block)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetBlockHistoryDescendants indicates an expected call of GetBlockHistoryDescendants.
func (mr *MockStoreMockRecorder) GetBlockHistoryDescendants(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlockHistoryDescendants", reflect.TypeOf((*MockStore)(nil).GetBlockHistoryDescendants), arg0, arg1)
}
// GetBlocksForBoard mocks base method.
func (m *MockStore) GetBlocksForBoard(arg0 string) ([]model.Block, error) {
m.ctrl.T.Helper()
@ -505,6 +521,21 @@ func (mr *MockStoreMockRecorder) GetBoardAndCardByID(arg0 interface{}) *gomock.C
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBoardAndCardByID", reflect.TypeOf((*MockStore)(nil).GetBoardAndCardByID), arg0)
}
// GetBoardHistory mocks base method.
func (m *MockStore) GetBoardHistory(arg0 string, arg1 model.QueryBlockHistoryOptions) ([]*model.Board, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetBoardHistory", arg0, arg1)
ret0, _ := ret[0].([]*model.Board)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetBoardHistory indicates an expected call of GetBoardHistory.
func (mr *MockStoreMockRecorder) GetBoardHistory(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBoardHistory", reflect.TypeOf((*MockStore)(nil).GetBoardHistory), arg0, arg1)
}
// GetBoardMemberHistory mocks base method.
func (m *MockStore) GetBoardMemberHistory(arg0, arg1 string, arg2 uint64) ([]*model.BoardMemberHistoryEntry, error) {
m.ctrl.T.Helper()
@ -550,6 +581,20 @@ func (mr *MockStoreMockRecorder) GetCategory(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCategory", reflect.TypeOf((*MockStore)(nil).GetCategory), arg0)
}
// GetLicense mocks base method.
func (m *MockStore) GetLicense() *model0.License {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetLicense")
ret0, _ := ret[0].(*model0.License)
return ret0
}
// GetLicense indicates an expected call of GetLicense.
func (mr *MockStoreMockRecorder) GetLicense() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLicense", reflect.TypeOf((*MockStore)(nil).GetLicense))
}
// GetMemberForBoard mocks base method.
func (m *MockStore) GetMemberForBoard(arg0, arg1 string) (*model.BoardMember, error) {
m.ctrl.T.Helper()

View File

@ -18,6 +18,7 @@ import (
const (
maxSearchDepth = 50
descClause = " DESC "
)
type BoardIDNilError struct{}
@ -588,6 +589,7 @@ func (s *SQLStore) getBlock(db sq.BaseRunner, blockID string) (*model.Block, err
s.logger.Error(`GetBlock ERROR`, mlog.Err(err))
return nil, err
}
defer s.CloseRows(rows)
blocks, err := s.blocksFromRows(rows)
if err != nil {
@ -604,7 +606,7 @@ func (s *SQLStore) getBlock(db sq.BaseRunner, blockID string) (*model.Block, err
func (s *SQLStore) getBlockHistory(db sq.BaseRunner, blockID string, opts model.QueryBlockHistoryOptions) ([]model.Block, error) {
var order string
if opts.Descending {
order = " DESC "
order = descClause
}
query := s.getQueryBuilder(db).
@ -630,6 +632,41 @@ func (s *SQLStore) getBlockHistory(db sq.BaseRunner, blockID string, opts model.
s.logger.Error(`GetBlockHistory ERROR`, mlog.Err(err))
return nil, err
}
defer s.CloseRows(rows)
return s.blocksFromRows(rows)
}
func (s *SQLStore) getBlockHistoryDescendants(db sq.BaseRunner, boardID string, opts model.QueryBlockHistoryOptions) ([]model.Block, error) {
var order string
if opts.Descending {
order = descClause
}
query := s.getQueryBuilder(db).
Select(s.blockFields()...).
From(s.tablePrefix + "blocks_history").
Where(sq.Eq{"board_id": boardID}).
OrderBy("insert_at " + order + ", update_at" + order)
if opts.BeforeUpdateAt != 0 {
query = query.Where(sq.Lt{"update_at": opts.BeforeUpdateAt})
}
if opts.AfterUpdateAt != 0 {
query = query.Where(sq.Gt{"update_at": opts.AfterUpdateAt})
}
if opts.Limit != 0 {
query = query.Limit(opts.Limit)
}
rows, err := query.Query()
if err != nil {
s.logger.Error(`GetBlockHistory ERROR`, mlog.Err(err))
return nil, err
}
defer s.CloseRows(rows)
return s.blocksFromRows(rows)
}

View File

@ -38,7 +38,7 @@ func boardFields(prefix string) []string {
"is_template",
"template_version",
"COALESCE(properties, '{}')",
"COALESCE(card_properties, '{}')",
"COALESCE(card_properties, '[]')",
"COALESCE(column_calculations, '{}')",
"create_at",
"update_at",
@ -60,6 +60,31 @@ func boardFields(prefix string) []string {
return prefixedFields
}
func boardHistoryFields() []string {
fields := []string{
"id",
"team_id",
"COALESCE(channel_id, '')",
"COALESCE(created_by, '')",
"COALESCE(modified_by, '')",
"type",
"COALESCE(title, '')",
"COALESCE(description, '')",
"COALESCE(icon, '')",
"COALESCE(show_description, false)",
"COALESCE(is_template, false)",
"template_version",
"COALESCE(properties, '{}')",
"COALESCE(card_properties, '[]')",
"COALESCE(column_calculations, '{}')",
"COALESCE(create_at, 0)",
"COALESCE(update_at, 0)",
"COALESCE(delete_at, 0)",
}
return fields
}
var boardMemberFields = []string{
"board_id",
"user_id",
@ -274,6 +299,8 @@ func (s *SQLStore) insertBoard(db sq.BaseRunner, board *model.Board, userID stri
insertQuery := s.getQueryBuilder(db).Insert("").
Columns(boardFields("")...)
now := utils.GetMillis()
insertQueryValues := map[string]interface{}{
"id": board.ID,
"team_id": board.TeamID,
@ -291,12 +318,10 @@ func (s *SQLStore) insertBoard(db sq.BaseRunner, board *model.Board, userID stri
"card_properties": cardPropertiesBytes,
"column_calculations": columnCalculationsBytes,
"create_at": board.CreateAt,
"update_at": board.UpdateAt,
"update_at": now,
"delete_at": board.DeleteAt,
}
now := utils.GetMillis()
if existingBoard != nil {
query := s.getQueryBuilder(db).Update(s.tablePrefix+"boards").
Where(sq.Eq{"id": board.ID}).
@ -357,29 +382,49 @@ func (s *SQLStore) deleteBoard(db sq.BaseRunner, boardID, userID string) error {
board, err := s.getBoard(db, boardID)
if err != nil {
fmt.Printf("error on get board: %s\n", err)
return err
}
insertQuery := s.getQueryBuilder(db).Insert(s.tablePrefix+"boards_history").
Columns(
"team_id",
"id",
"type",
"modified_by",
"update_at",
"delete_at",
).
Values(
board.TeamID,
boardID,
board.Type,
userID,
now,
now,
)
propertiesBytes, err := json.Marshal(board.Properties)
if err != nil {
return err
}
cardPropertiesBytes, err := json.Marshal(board.CardProperties)
if err != nil {
return err
}
columnCalculationsBytes, err := json.Marshal(board.ColumnCalculations)
if err != nil {
return err
}
if _, err := insertQuery.Exec(); err != nil {
insertQueryValues := map[string]interface{}{
"id": board.ID,
"team_id": board.TeamID,
"channel_id": board.ChannelID,
"created_by": board.CreatedBy,
"modified_by": userID,
"type": board.Type,
"title": board.Title,
"description": board.Description,
"icon": board.Icon,
"show_description": board.ShowDescription,
"is_template": board.IsTemplate,
"template_version": board.TemplateVersion,
"properties": propertiesBytes,
"card_properties": cardPropertiesBytes,
"column_calculations": columnCalculationsBytes,
"create_at": board.CreateAt,
"update_at": now,
"delete_at": now,
}
// writing board history
insertQuery := s.getQueryBuilder(db).Insert("").
Columns(boardHistoryFields()...)
query := insertQuery.SetMap(insertQueryValues).Into(s.tablePrefix + "boards_history")
if _, err := query.Exec(); err != nil {
return err
}
@ -605,6 +650,40 @@ func (s *SQLStore) searchBoardsForUserAndTeam(db sq.BaseRunner, term, userID, te
return s.boardsFromRows(rows)
}
func (s *SQLStore) getBoardHistory(db sq.BaseRunner, boardID string, opts model.QueryBlockHistoryOptions) ([]*model.Board, error) {
var order string
if opts.Descending {
order = " DESC "
}
query := s.getQueryBuilder(db).
Select(boardHistoryFields()...).
From(s.tablePrefix + "boards_history").
Where(sq.Eq{"id": boardID}).
OrderBy("insert_at " + order + ", update_at" + order)
if opts.BeforeUpdateAt != 0 {
query = query.Where(sq.Lt{"update_at": opts.BeforeUpdateAt})
}
if opts.AfterUpdateAt != 0 {
query = query.Where(sq.Gt{"update_at": opts.AfterUpdateAt})
}
if opts.Limit != 0 {
query = query.Limit(opts.Limit)
}
rows, err := query.Query()
if err != nil {
s.logger.Error(`getBoardHistory ERROR`, mlog.Err(err))
return nil, err
}
defer s.CloseRows(rows)
return s.boardsFromRows(rows)
}
func (s *SQLStore) getBoardMemberHistory(db sq.BaseRunner, boardID, userID string, limit uint64) ([]*model.BoardMemberHistoryEntry, error) {
query := s.getQueryBuilder(db).
Select("board_id", "user_id", "action", "insert_at").

View File

@ -18,6 +18,7 @@ import (
"github.com/mattermost/focalboard/server/model"
mmModel "github.com/mattermost/mattermost-server/v6/model"
"github.com/mattermost/mattermost-server/v6/shared/mlog"
)
@ -269,6 +270,11 @@ func (s *SQLStore) GetBlockHistory(blockID string, opts model.QueryBlockHistoryO
}
func (s *SQLStore) GetBlockHistoryDescendants(boardID string, opts model.QueryBlockHistoryOptions) ([]model.Block, error) {
return s.getBlockHistoryDescendants(s.db, boardID, opts)
}
func (s *SQLStore) GetBlocksForBoard(boardID string) ([]model.Block, error) {
return s.getBlocksForBoard(s.db, boardID)
@ -309,6 +315,11 @@ func (s *SQLStore) GetBoardAndCardByID(blockID string) (*model.Board, *model.Blo
}
func (s *SQLStore) GetBoardHistory(boardID string, opts model.QueryBlockHistoryOptions) ([]*model.Board, error) {
return s.getBoardHistory(s.db, boardID, opts)
}
func (s *SQLStore) GetBoardMemberHistory(boardID string, userID string, limit uint64) ([]*model.BoardMemberHistoryEntry, error) {
return s.getBoardMemberHistory(s.db, boardID, userID, limit)
@ -324,6 +335,11 @@ func (s *SQLStore) GetCategory(id string) (*model.Category, error) {
}
func (s *SQLStore) GetLicense() *mmModel.License {
return s.getLicense(s.db)
}
func (s *SQLStore) GetMemberForBoard(boardID string, userID string) (*model.BoardMember, error) {
return s.getMemberForBoard(s.db, boardID, userID)

View File

@ -10,6 +10,7 @@ import (
"github.com/mattermost/focalboard/server/model"
"github.com/mattermost/mattermost-plugin-api/cluster"
mmModel "github.com/mattermost/mattermost-server/v6/model"
"github.com/mattermost/mattermost-server/v6/shared/mlog"
)
@ -92,3 +93,7 @@ func (s *SQLStore) escapeField(fieldName string) string { //nolint:unparam
}
return fieldName
}
func (s *SQLStore) getLicense(db sq.BaseRunner) *mmModel.License {
return nil
}

View File

@ -8,6 +8,7 @@ import (
"time"
"github.com/mattermost/focalboard/server/model"
mmModel "github.com/mattermost/mattermost-server/v6/model"
)
// Store represents the abstraction of the data storage.
@ -32,6 +33,8 @@ type Store interface {
// @withTransaction
PatchBlock(blockID string, blockPatch *model.BlockPatch, userID string) error
GetBlockHistory(blockID string, opts model.QueryBlockHistoryOptions) ([]model.Block, error)
GetBlockHistoryDescendants(boardID string, opts model.QueryBlockHistoryOptions) ([]model.Block, error)
GetBoardHistory(boardID string, opts model.QueryBlockHistoryOptions) ([]*model.Board, error)
GetBoardAndCardByID(blockID string) (board *model.Board, card *model.Block, err error)
GetBoardAndCard(block *model.Block) (board *model.Board, card *model.Block, err error)
// @withTransaction
@ -131,6 +134,8 @@ type Store interface {
DBType() string
IsErrNotFound(err error) bool
GetLicense() *mmModel.License
}
// ErrNotFound is an error type that can be returned by store APIs when a query unexpectedly fetches no records.

View File

@ -75,6 +75,11 @@ func StoreTestBlocksStore(t *testing.T, setup func(t *testing.T) (store.Store, f
defer tearDown()
testDuplicateBlock(t, store)
})
t.Run("GetBlockMetadata", func(t *testing.T) {
store, tearDown := setup(t)
defer tearDown()
testGetBlockMetadata(t, store)
})
}
func testInsertBlock(t *testing.T, store store.Store) {
@ -873,3 +878,188 @@ func testDuplicateBlock(t *testing.T, store store.Store) {
require.Nil(t, blocks)
})
}
func testGetBlockMetadata(t *testing.T, store store.Store) {
boardID := testBoardID
blocks, err := store.GetBlocksForBoard(boardID)
require.NoError(t, err)
blocksToInsert := []model.Block{
{
ID: "block1",
BoardID: boardID,
ParentID: "",
ModifiedBy: testUserID,
Type: "test",
},
{
ID: "block2",
BoardID: boardID,
ParentID: "block1",
ModifiedBy: testUserID,
Type: "test",
},
{
ID: "block3",
BoardID: boardID,
ParentID: "block1",
ModifiedBy: testUserID,
Type: "test",
},
{
ID: "block4",
BoardID: boardID,
ParentID: "block1",
ModifiedBy: testUserID,
Type: "test2",
},
{
ID: "block5",
BoardID: boardID,
ParentID: "block2",
ModifiedBy: testUserID,
Type: "test",
},
}
for _, v := range blocksToInsert {
time.Sleep(20 * time.Millisecond)
subBlocks := []model.Block{v}
InsertBlocks(t, store, subBlocks, testUserID)
}
defer DeleteBlocks(t, store, blocksToInsert, "test")
t.Run("get full block history", func(t *testing.T) {
opts := model.QueryBlockHistoryOptions{
Descending: false,
}
blocks, err = store.GetBlockHistoryDescendants(boardID, opts)
require.NoError(t, err)
require.Len(t, blocks, 5)
expectedBlock := blocksToInsert[0]
block := blocks[0]
require.Equal(t, expectedBlock.ID, block.ID)
})
t.Run("get full block history descending", func(t *testing.T) {
opts := model.QueryBlockHistoryOptions{
Descending: true,
}
blocks, err = store.GetBlockHistoryDescendants(boardID, opts)
require.NoError(t, err)
require.Len(t, blocks, 5)
expectedBlock := blocksToInsert[len(blocksToInsert)-1]
block := blocks[0]
require.Equal(t, expectedBlock.ID, block.ID)
})
t.Run("get limited block history", func(t *testing.T) {
opts := model.QueryBlockHistoryOptions{
Limit: 3,
Descending: false,
}
blocks, err = store.GetBlockHistoryDescendants(boardID, opts)
require.NoError(t, err)
require.Len(t, blocks, 3)
})
t.Run("get first block history", func(t *testing.T) {
opts := model.QueryBlockHistoryOptions{
Limit: 1,
Descending: false,
}
blocks, err = store.GetBlockHistoryDescendants(boardID, opts)
require.NoError(t, err)
require.Len(t, blocks, 1)
expectedBlock := blocksToInsert[0]
block := blocks[0]
require.Equal(t, expectedBlock.ID, block.ID)
})
t.Run("get last block history", func(t *testing.T) {
opts := model.QueryBlockHistoryOptions{
Limit: 1,
Descending: true,
}
blocks, err = store.GetBlockHistoryDescendants(boardID, opts)
require.NoError(t, err)
require.Len(t, blocks, 1)
expectedBlock := blocksToInsert[len(blocksToInsert)-1]
block := blocks[0]
require.Equal(t, expectedBlock.ID, block.ID)
})
t.Run("get block history after updateAt", func(t *testing.T) {
rBlocks, err2 := store.GetBlocksWithType(boardID, "test")
require.NoError(t, err2)
require.NotZero(t, rBlocks[2].UpdateAt)
opts := model.QueryBlockHistoryOptions{
AfterUpdateAt: rBlocks[2].UpdateAt,
Descending: false,
}
blocks, err = store.GetBlockHistoryDescendants(boardID, opts)
require.NoError(t, err)
require.Len(t, blocks, 2)
expectedBlock := blocksToInsert[3]
block := blocks[0]
require.Equal(t, expectedBlock.ID, block.ID)
})
t.Run("get block history before updateAt", func(t *testing.T) {
rBlocks, err2 := store.GetBlocksWithType(boardID, "test")
require.NoError(t, err2)
require.NotZero(t, rBlocks[2].UpdateAt)
opts := model.QueryBlockHistoryOptions{
BeforeUpdateAt: rBlocks[2].UpdateAt,
Descending: true,
}
blocks, err = store.GetBlockHistoryDescendants(boardID, opts)
require.NoError(t, err)
require.Len(t, blocks, 2)
expectedBlock := blocksToInsert[1]
block := blocks[0]
require.Equal(t, expectedBlock.ID, block.ID)
})
t.Run("get full block history after delete", func(t *testing.T) {
time.Sleep(20 * time.Millisecond)
err = store.DeleteBlock(blocksToInsert[0].ID, testUserID)
require.NoError(t, err)
opts := model.QueryBlockHistoryOptions{
Descending: true,
}
blocks, err = store.GetBlockHistoryDescendants(boardID, opts)
require.NoError(t, err)
require.Len(t, blocks, 6)
expectedBlock := blocksToInsert[0]
block := blocks[0]
require.Equal(t, expectedBlock.ID, block.ID)
})
t.Run("get full block history after undelete", func(t *testing.T) {
time.Sleep(20 * time.Millisecond)
err = store.UndeleteBlock(blocksToInsert[0].ID, testUserID)
require.NoError(t, err)
opts := model.QueryBlockHistoryOptions{
Descending: true,
}
blocks, err = store.GetBlockHistoryDescendants(boardID, opts)
require.NoError(t, err)
require.Len(t, blocks, 7)
expectedBlock := blocksToInsert[0]
block := blocks[0]
require.Equal(t, expectedBlock.ID, block.ID)
})
}

View File

@ -69,6 +69,11 @@ func StoreTestBoardStore(t *testing.T, setup func(t *testing.T) (store.Store, fu
defer tearDown()
testSearchBoardsForUserAndTeam(t, store)
})
t.Run("GetBoardHistory", func(t *testing.T) {
store, tearDown := setup(t)
defer tearDown()
testGetBoardHistory(t, store)
})
}
func testGetBoard(t *testing.T, store store.Store) {
@ -800,3 +805,107 @@ func testSearchBoardsForUserAndTeam(t *testing.T, store store.Store) {
})
}
}
func testGetBoardHistory(t *testing.T, store store.Store) {
userID := testUserID
t.Run("testGetBoardHistory: create board", func(t *testing.T) {
originalTitle := "Board: original title"
boardID := utils.NewID(utils.IDTypeBoard)
board := &model.Board{
ID: boardID,
Title: originalTitle,
TeamID: testTeamID,
Type: model.BoardTypeOpen,
}
rBoard1, err := store.InsertBoard(board, userID)
require.NoError(t, err)
opts := model.QueryBlockHistoryOptions{
Limit: 0,
Descending: false,
}
boards, err := store.GetBoardHistory(board.ID, opts)
require.NoError(t, err)
require.Len(t, boards, 1)
// wait to avoid hitting pk uniqueness constraint in history
time.Sleep(10 * time.Millisecond)
userID2 := "user-id-2"
newTitle := "Board: A new title"
newDescription := "A new description"
patch := &model.BoardPatch{Title: &newTitle, Description: &newDescription}
patchedBoard, err := store.PatchBoard(boardID, patch, userID2)
require.NoError(t, err)
// Updated history
boards, err = store.GetBoardHistory(board.ID, opts)
require.NoError(t, err)
require.Len(t, boards, 2)
require.Equal(t, boards[0].Title, originalTitle)
require.Equal(t, boards[1].Title, newTitle)
require.Equal(t, boards[1].Description, newDescription)
// Check history against latest board
rBoard2, err := store.GetBoard(board.ID)
require.NoError(t, err)
require.Equal(t, rBoard2.Title, newTitle)
require.Equal(t, rBoard2.Title, boards[1].Title)
require.NotZero(t, rBoard2.UpdateAt)
require.Equal(t, rBoard1.UpdateAt, boards[0].UpdateAt)
require.Equal(t, rBoard2.UpdateAt, patchedBoard.UpdateAt)
require.Equal(t, rBoard2.UpdateAt, boards[1].UpdateAt)
require.Equal(t, rBoard1, boards[0])
require.Equal(t, rBoard2, boards[1])
// wait to avoid hitting pk uniqueness constraint in history
time.Sleep(10 * time.Millisecond)
newTitle2 := "Board: A new title 2"
patch2 := &model.BoardPatch{Title: &newTitle2}
patchBoard2, err := store.PatchBoard(boardID, patch2, userID2)
require.NoError(t, err)
// Updated history
opts = model.QueryBlockHistoryOptions{
Limit: 1,
Descending: true,
}
boards, err = store.GetBoardHistory(board.ID, opts)
require.NoError(t, err)
require.Len(t, boards, 1)
require.Equal(t, boards[0].Title, newTitle2)
require.Equal(t, boards[0], patchBoard2)
// Delete board
time.Sleep(10 * time.Millisecond)
err = store.DeleteBoard(boardID, userID)
require.NoError(t, err)
// Updated history after delete
opts = model.QueryBlockHistoryOptions{
Limit: 0,
Descending: true,
}
boards, err = store.GetBoardHistory(board.ID, opts)
require.NoError(t, err)
require.Len(t, boards, 4)
require.NotZero(t, boards[0].UpdateAt)
require.Greater(t, boards[0].UpdateAt, patchBoard2.UpdateAt)
require.NotZero(t, boards[0].DeleteAt)
require.Greater(t, boards[0].DeleteAt, patchBoard2.UpdateAt)
})
t.Run("testGetBoardHistory: nonexisting board", func(t *testing.T) {
opts := model.QueryBlockHistoryOptions{
Limit: 0,
Descending: false,
}
boards, err := store.GetBoardHistory("nonexistent-id", opts)
require.NoError(t, err)
require.Len(t, boards, 0)
})
}

View File

@ -260,6 +260,39 @@ definitions:
- schemeViewer
type: object
x-go-package: github.com/mattermost/focalboard/server/model
BoardMetadata:
description: BoardMetadata contains metadata for a Board
properties:
boardId:
description: The ID for the board
type: string
x-go-name: BoardID
createdBy:
description: The ID of the user that created the board
type: string
x-go-name: CreatedBy
descendantFirstUpdateAt:
description: The earliest time a descendant of this board was added, modified, or deleted
format: int64
type: integer
x-go-name: DescendantFirstUpdateAt
descendantLastUpdateAt:
description: The most recent time a descendant of this board was added, modified, or deleted
format: int64
type: integer
x-go-name: DescendantLastUpdateAt
lastModifiedBy:
description: The ID of the user that last modified the most recently modified descendant
type: string
x-go-name: LastModifiedBy
required:
- boardId
- descendantLastUpdateAt
- descendantFirstUpdateAt
- createdBy
- lastModifiedBy
type: object
x-go-package: github.com/mattermost/focalboard/server/model
BoardPatch:
description: BoardPatch is a patch for modify boards
properties:
@ -1300,6 +1333,33 @@ paths:
$ref: '#/definitions/ErrorResponse'
security:
- BearerAuth: []
/api/v1/boards/{boardID}/metadata:
get:
description: Returns a board's metadata
operationId: getBoardMetadata
parameters:
- description: Board ID
in: path
name: boardID
required: true
type: string
produces:
- application/json
responses:
"200":
description: success
schema:
$ref: '#/definitions/BoardMetadata'
"404":
description: board not found
"501":
description: required license not found
default:
description: internal error
schema:
$ref: '#/definitions/ErrorResponse'
security:
- BearerAuth: []
/api/v1/boards/{boardID}/sharing:
get:
description: Returns sharing information for a board

View File

@ -15,7 +15,7 @@ declare namespace Cypress {
apiGetMe: () => Chainable<string>
apiChangePassword: (userId: string, oldPassword: string, newPassword: string) => Chainable
apiInitServer: () => Chainable
apiDeleteBlock: (id: string) => Chainable
apiDeleteBoard: (id: string) => Chainable
apiResetBoards: () => Chainable
apiSkipTour: (userID: string) => Chainable

View File

@ -97,7 +97,7 @@ describe('Card URL Property', () => {
const addView = (type: ViewType) => {
cy.log(`**Add ${type} view**`)
cy.findByRole('button', {name: 'View menu'}).click()
cy.findByText('Add view').click()
cy.findByText('Add view').realHover()
cy.findByRole('button', {name: type}).click()
cy.findByRole('textbox', {name: `${type} view`}).should('exist')
}

View File

@ -98,7 +98,7 @@ describe('Create and delete board / card', () => {
// Create table view
cy.log('**Create table view**')
cy.get('.ViewHeader').get('.DropdownIcon').first().parent().click()
cy.get('.ViewHeader').contains('Add view').click()
cy.get('.ViewHeader').contains('Add view').realHover()
cy.get('.ViewHeader').
contains('Add view').
parent().

View File

@ -11,7 +11,7 @@ describe('Login actions', () => {
cy.log('**Redirects to error then login page**')
cy.visit('/')
cy.location('pathname').should('eq', '/error')
cy.get('button').contains('Login').click()
cy.get('button').contains('Log in').click()
cy.location('pathname').should('eq', '/login')
cy.get('.LoginPage').contains('Log in')
cy.get('#login-username').should('exist')

View File

@ -52,32 +52,32 @@ Cypress.Commands.add('apiInitServer', () => {
return cy.apiRegisterUser(data, '', false).apiLoginUser(data)
})
Cypress.Commands.add('apiDeleteBlock', (id: string) => {
Cypress.Commands.add('apiDeleteBoard', (id: string) => {
return cy.request({
method: 'DELETE',
url: `/api/v1/workspaces/0/blocks/${encodeURIComponent(id)}`,
url: `/api/v1/boards/${encodeURIComponent(id)}`,
...headers(),
})
})
const deleteBlocks = (ids: string[]) => {
const deleteBoards = (ids: string[]) => {
if (ids.length === 0) {
return
}
const [id, ...other] = ids
cy.apiDeleteBlock(id).then(() => deleteBlocks(other))
cy.apiDeleteBoard(id).then(() => deleteBoards(other))
}
Cypress.Commands.add('apiResetBoards', () => {
return cy.request({
method: 'GET',
url: '/api/v1/workspaces/0/blocks?type=board',
url: '/api/v1/teams/0/boards',
...headers(),
}).then((response) => {
if (Array.isArray(response.body)) {
const boards = response.body as Board[]
const toDelete = boards.filter((b) => !b.isTemplate).map((b) => b.id)
deleteBlocks(toDelete)
deleteBoards(toDelete)
}
})
})

View File

@ -88,6 +88,8 @@ Object {
<div
class="MenuOption MenuSeparator menu-separator"
/>
</div>
<div>
<div
aria-label="Duplicate view"
class="MenuOption TextOption menu-option"
@ -105,6 +107,8 @@ Object {
class="noicon"
/>
</div>
</div>
<div>
<div
aria-label="Delete view"
class="MenuOption TextOption menu-option"
@ -122,6 +126,8 @@ Object {
class="noicon"
/>
</div>
</div>
<div>
<div
class="MenuOption SubMenuOption menu-option"
id="__addView"
@ -258,6 +264,8 @@ Object {
<div
class="MenuOption MenuSeparator menu-separator"
/>
</div>
<div>
<div
aria-label="Duplicate view"
class="MenuOption TextOption menu-option"
@ -275,6 +283,8 @@ Object {
class="noicon"
/>
</div>
</div>
<div>
<div
aria-label="Delete view"
class="MenuOption TextOption menu-option"
@ -292,6 +302,8 @@ Object {
class="noicon"
/>
</div>
</div>
<div>
<div
class="MenuOption SubMenuOption menu-option"
id="__addView"
@ -486,6 +498,9 @@ Object {
class="MenuOption MenuSeparator menu-separator"
/>
</div>
<div />
<div />
<div />
</div>
<div
class="menu-spacer hideOnWidescreen"
@ -600,6 +615,9 @@ Object {
class="MenuOption MenuSeparator menu-separator"
/>
</div>
<div />
<div />
<div />
</div>
<div
class="menu-spacer hideOnWidescreen"

View File

@ -160,3 +160,12 @@
left: calc(240px - 50px);
}
}
.team-sidebar + .product-wrapper {
.SidebarBoardItem {
.Menu.noselect.left {
right: calc(100% - 480px - 64px + 50px);
left: calc(64px + 240px - 50px);
}
}
}

View File

@ -257,6 +257,7 @@ exports[`components/table/TableHeaderMenu should match snapshot, title column 1`
/>
</div>
</div>
<div />
</div>
<div
class="menu-spacer hideOnWidescreen"

View File

@ -31,6 +31,7 @@ exports[`components/viewHeader/newCardButton return NewCardButton 1`] = `
<div
class="menu-options"
>
<div />
<div>
<div
aria-label="Empty card"
@ -154,6 +155,7 @@ exports[`components/viewHeader/newCardButton return NewCardButton and addCard 1`
<div
class="menu-options"
>
<div />
<div>
<div
aria-label="Empty card"
@ -277,6 +279,7 @@ exports[`components/viewHeader/newCardButton return NewCardButton and addCardTem
<div
class="menu-options"
>
<div />
<div>
<div
aria-label="Empty card"

View File

@ -403,6 +403,7 @@ exports[`components/viewHeader/viewHeaderGroupByMenu return groupBy menu 1`] = `
<div
class="menu-options"
>
<div />
<div>
<div
aria-label="Status"

View File

@ -24,6 +24,7 @@ exports[`components/viewHeader/viewHeaderPropertiesMenu return properties menu 1
<div
class="menu-options"
>
<div />
<div>
<div
aria-label="Status"

View File

@ -253,23 +253,29 @@ const ViewMenu = (props: Props) => {
/>))}
<BoardPermissionGate permissions={[Permission.ManageBoardProperties]}>
<Menu.Separator/>
{!props.readonly &&
</BoardPermissionGate>
{!props.readonly &&
<BoardPermissionGate permissions={[Permission.ManageBoardProperties]}>
<Menu.Text
id='__duplicateView'
name={duplicateViewText}
icon={<DuplicateIcon/>}
onClick={handleDuplicateView}
/>
}
{!props.readonly && views.length > 1 &&
</BoardPermissionGate>
}
{!props.readonly && views.length > 1 &&
<BoardPermissionGate permissions={[Permission.ManageBoardProperties]}>
<Menu.Text
id='__deleteView'
name={deleteViewText}
icon={<DeleteIcon/>}
onClick={handleDeleteView}
/>
}
{!props.readonly &&
</BoardPermissionGate>
}
{!props.readonly &&
<BoardPermissionGate permissions={[Permission.ManageBoardProperties]}>
<Menu.SubMenu
id='__addView'
name={addViewText}
@ -300,8 +306,8 @@ const ViewMenu = (props: Props) => {
onClick={handleAddViewCalendar}
/>
</Menu.SubMenu>
}
</BoardPermissionGate>
</BoardPermissionGate>
}
</Menu>
)
}

View File

@ -7,6 +7,7 @@ import {Card} from '../blocks/card'
import {IUser} from '../user'
import {Board} from '../blocks/board'
import {BoardView} from '../blocks/boardView'
import {CommentBlock} from '../blocks/commentBlock'
import {Utils} from '../utils'
import {Constants} from '../constants'
import {CardFilter} from '../cardFilter'
@ -14,6 +15,7 @@ import {CardFilter} from '../cardFilter'
import {loadBoardData, initialReadOnlyLoad} from './initialLoad'
import {getCurrentBoard} from './boards'
import {getBoardUsers} from './users'
import {getLastCommentByCard} from './comments'
import {getCurrentView} from './views'
import {getSearchText} from './searchText'
@ -157,7 +159,7 @@ function manualOrder(activeView: BoardView, cardA: Card, cardB: Card) {
return indexA - indexB
}
function sortCards(cards: Card[], board: Board, activeView: BoardView, usersById: {[key: string]: IUser}): Card[] {
function sortCards(cards: Card[], lastCommentByCard: {[key: string]: CommentBlock}, board: Board, activeView: BoardView, usersById: {[key: string]: IUser}): Card[] {
if (!activeView) {
return cards
}
@ -217,7 +219,9 @@ function sortCards(cards: Card[], board: Board, activeView: BoardView, usersById
} else if (template.type === 'createdTime') {
result = a.createAt - b.createAt
} else if (template.type === 'updatedTime') {
result = a.updateAt - b.updateAt
const aUpdateAt = Math.max(a.updateAt, lastCommentByCard[a.id]?.updateAt || 0)
const bUpdateAt = Math.max(b.updateAt, lastCommentByCard[b.id]?.updateAt || 0)
result = aUpdateAt - bUpdateAt
} else {
// Text-based sort
@ -292,11 +296,12 @@ function searchFilterCards(cards: Card[], board: Board, searchTextRaw: string):
export const getCurrentViewCardsSortedFilteredAndGrouped = createSelector(
getCurrentBoardCards,
getLastCommentByCard,
getCurrentBoard,
getCurrentView,
getSearchText,
getBoardUsers,
(cards, board, view, searchText, users) => {
(cards, lastCommentByCard, board, view, searchText, users) => {
if (!view || !board || !users || !cards) {
return []
}
@ -308,7 +313,7 @@ export const getCurrentViewCardsSortedFilteredAndGrouped = createSelector(
if (searchText) {
result = searchFilterCards(result, board, searchText)
}
result = sortCards(result, board, view, users)
result = sortCards(result, lastCommentByCard, board, view, users)
return result
},
)

View File

@ -1,7 +1,7 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {createSlice, PayloadAction} from '@reduxjs/toolkit'
import {createSlice, PayloadAction, createSelector} from '@reduxjs/toolkit'
import {CommentBlock} from '../blocks/commentBlock'
@ -92,3 +92,17 @@ export function getLastCardComment(cardId: string): (state: RootState) => Commen
return comments?.[comments?.length - 1]
}
}
export const getLastCommentByCard = createSelector(
(state: RootState) => state.comments?.commentsByCard || null,
(commentsByCard: {[key: string]: CommentBlock[]}|null): {[key: string]: CommentBlock} => {
const lastCommentByCard: {[key: string]: CommentBlock} = {}
Object.keys(commentsByCard || {}).forEach((cardId) => {
if (commentsByCard && commentsByCard[cardId]) {
const comments = commentsByCard[cardId]
lastCommentByCard[cardId] = comments?.[comments?.length - 1]
}
})
return lastCommentByCard
},
)

View File

@ -6,7 +6,7 @@ import SeparatorOption from './separatorOption'
import SwitchOption from './switchOption'
import TextOption from './textOption'
import ColorOption from './colorOption'
import SubMenuOption from './subMenuOption'
import SubMenuOption, {HoveringContext} from './subMenuOption'
import LabelOption from './labelOption'
import './menu.scss'
@ -27,7 +27,7 @@ export default class Menu extends React.PureComponent<Props> {
static Label = LabelOption
public state = {
hoveringIdx: -1,
hovering: null,
}
public render(): JSX.Element {
@ -36,16 +36,14 @@ export default class Menu extends React.PureComponent<Props> {
<div className={'Menu noselect ' + (position || 'bottom')}>
<div className='menu-contents'>
<div className='menu-options'>
{React.Children.map(children, (child, i) => {
return addChildMenuItem({
child,
onMouseEnter: () =>
this.setState({
hoveringIdx: i,
}),
isHovering: () => i === this.state.hoveringIdx,
})
})}
{React.Children.map(children, (child) => (
<div
onMouseEnter={() => this.setState({hovering: child})}
>
<HoveringContext.Provider value={child == this.state.hovering}>
{child}
</HoveringContext.Provider>
</div>))}
</div>
<div className='menu-spacer hideOnWidescreen'/>
@ -67,28 +65,3 @@ export default class Menu extends React.PureComponent<Props> {
// No need to do anything, as click bubbled up to MenuWrapper, which closes
}
}
function addChildMenuItem(props: {child: React.ReactNode, onMouseEnter: () => void, isHovering: () => boolean}): JSX.Element | null {
const {child, onMouseEnter, isHovering} = props
if (child !== null) {
if (React.isValidElement(child)) {
const castedChild = child as React.ReactElement
return (
<div
onMouseEnter={onMouseEnter}
>
{castedChild.type === SubMenuOption ? (
<castedChild.type
{...castedChild.props}
isHovering={isHovering}
/>
) : (
<castedChild.type {...castedChild.props}/>
)}
</div>
)
}
}
return (null)
}

View File

@ -1,6 +1,6 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import React, {useEffect, useState} from 'react'
import React, {useEffect, useState, useContext} from 'react'
import SubmenuTriangleIcon from '../icons/submenuTriangle'
@ -8,25 +8,27 @@ import Menu from '.'
import './subMenuOption.scss'
export const HoveringContext = React.createContext(false)
type SubMenuOptionProps = {
id: string
name: string
position?: 'bottom' | 'top' | 'left' | 'left-bottom'
icon?: React.ReactNode
children: React.ReactNode
isHovering?: boolean
}
function SubMenuOption(props: SubMenuOptionProps): JSX.Element {
const [isOpen, setIsOpen] = useState(false)
const isHovering = useContext(HoveringContext)
const openLeftClass = props.position === 'left' || props.position === 'left-bottom' ? ' open-left' : ''
useEffect(() => {
if (props.isHovering !== undefined) {
setIsOpen(props.isHovering)
if (isHovering !== undefined) {
setIsOpen(isHovering)
}
}, [props.isHovering])
}, [isHovering])
return (
<div