Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

feature: edit comments (#312)

Guilherme Oenning1c0bc63a0e4c
diff --git a/app/actions/actions.go b/app/actions/actions.go
index 8f3cbf423..8905fd00c 100644
--- a/app/actions/actions.go
+++ b/app/actions/actions.go
@@ -9,6 +9,6 @@ import (
// Actionable is any action that the user can perform using the web app
type Actionable interface {
Initialize() interface{}
+ IsAuthorized(user *models.User, services *app.Services) bool
Validate(user *models.User, services *app.Services) *validate.Result
- IsAuthorized(user *models.User) bool
}
diff --git a/app/actions/idea.go b/app/actions/idea.go
index 419ff15c9..436ec81cd 100644
--- a/app/actions/idea.go
+++ b/app/actions/idea.go
@@ -22,7 +22,7 @@ func (input *CreateNewIdea) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *CreateNewIdea) IsAuthorized(user *models.User) bool {
+func (input *CreateNewIdea) IsAuthorized(user *models.User, services *app.Services) bool {
return user != nil
}
@@ -64,7 +64,7 @@ func (input *UpdateIdea) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *UpdateIdea) IsAuthorized(user *models.User) bool {
+func (input *UpdateIdea) IsAuthorized(user *models.User, services *app.Services) bool {
return user != nil && user.IsCollaborator()
}
@@ -111,7 +111,7 @@ func (input *AddNewComment) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *AddNewComment) IsAuthorized(user *models.User) bool {
+func (input *AddNewComment) IsAuthorized(user *models.User, services *app.Services) bool {
return user != nil
}
@@ -139,7 +139,7 @@ func (input *SetResponse) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *SetResponse) IsAuthorized(user *models.User) bool {
+func (input *SetResponse) IsAuthorized(user *models.User, services *app.Services) bool {
return user != nil && user.IsCollaborator()
}
@@ -173,3 +173,35 @@ func (input *SetResponse) Validate(user *models.User, services *app.Services) *v
return result
}
+
+// EditComment represents the action to update an existing comment
+type EditComment struct {
+ Model *models.EditComment
+}
+
+// Initialize the model
+func (input *EditComment) Initialize() interface{} {
+ input.Model = new(models.EditComment)
+ return input.Model
+}
+
+// IsAuthorized returns true if current user is authorized to perform this action
+func (input *EditComment) IsAuthorized(user *models.User, services *app.Services) bool {
+ comment, err := services.Ideas.GetCommentByID(input.Model.ID)
+ if err != nil {
+ return false
+ }
+
+ return user.ID == comment.User.ID || user.IsCollaborator()
+}
+
+// Validate if current model is valid
+func (input *EditComment) Validate(user *models.User, services *app.Services) *validate.Result {
+ result := validate.Success()
+
+ if input.Model.Content == "" {
+ result.AddFieldFailure("content", "Comment is required.")
+ }
+
+ return result
+}
diff --git a/app/actions/settings.go b/app/actions/settings.go
index f04caddae..1a589a38e 100644
--- a/app/actions/settings.go
+++ b/app/actions/settings.go
@@ -20,7 +20,7 @@ func (input *UpdateUserSettings) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *UpdateUserSettings) IsAuthorized(user *models.User) bool {
+func (input *UpdateUserSettings) IsAuthorized(user *models.User, services *app.Services) bool {
return user != nil
}
diff --git a/app/actions/signin.go b/app/actions/signin.go
index 101942989..b5c306714 100644
--- a/app/actions/signin.go
+++ b/app/actions/signin.go
@@ -22,7 +22,7 @@ func (input *SignInByEmail) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *SignInByEmail) IsAuthorized(user *models.User) bool {
+func (input *SignInByEmail) IsAuthorized(user *models.User, services *app.Services) bool {
return true
}
@@ -59,7 +59,7 @@ func (input *CompleteProfile) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *CompleteProfile) IsAuthorized(user *models.User) bool {
+func (input *CompleteProfile) IsAuthorized(user *models.User, services *app.Services) bool {
return true
}
diff --git a/app/actions/tag.go b/app/actions/tag.go
index 991834e89..85be8a3ed 100644
--- a/app/actions/tag.go
+++ b/app/actions/tag.go
@@ -24,7 +24,7 @@ func (input *CreateEditTag) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *CreateEditTag) IsAuthorized(user *models.User) bool {
+func (input *CreateEditTag) IsAuthorized(user *models.User, services *app.Services) bool {
return user != nil && user.IsAdministrator()
}
@@ -76,7 +76,7 @@ func (input *DeleteTag) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *DeleteTag) IsAuthorized(user *models.User) bool {
+func (input *DeleteTag) IsAuthorized(user *models.User, services *app.Services) bool {
return user != nil && user.IsAdministrator()
}
@@ -105,7 +105,7 @@ func (input *AssignUnassignTag) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *AssignUnassignTag) IsAuthorized(user *models.User) bool {
+func (input *AssignUnassignTag) IsAuthorized(user *models.User, services *app.Services) bool {
return user != nil && user.IsCollaborator()
}
diff --git a/app/actions/tenant.go b/app/actions/tenant.go
index 678d2ad72..22e7df9b3 100644
--- a/app/actions/tenant.go
+++ b/app/actions/tenant.go
@@ -24,7 +24,7 @@ func (input *CreateTenant) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *CreateTenant) IsAuthorized(user *models.User) bool {
+func (input *CreateTenant) IsAuthorized(user *models.User, services *app.Services) bool {
return true
}
@@ -86,7 +86,7 @@ func (input *UpdateTenantSettings) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *UpdateTenantSettings) IsAuthorized(user *models.User) bool {
+func (input *UpdateTenantSettings) IsAuthorized(user *models.User, services *app.Services) bool {
return user != nil && user.Role == models.RoleAdministrator
}
diff --git a/app/actions/tenant_test.go b/app/actions/tenant_test.go
index 6f0837851..1ad2e9e88 100644
--- a/app/actions/tenant_test.go
+++ b/app/actions/tenant_test.go
@@ -74,9 +74,9 @@ func TestUpdateTenantSettings_Unauthorized(t *testing.T) {
action := actions.UpdateTenantSettings{}
action.Initialize()
- Expect(action.IsAuthorized(admin)).To(BeTrue())
- Expect(action.IsAuthorized(collaborator)).To(BeFalse())
- Expect(action.IsAuthorized(nil)).To(BeFalse())
+ Expect(action.IsAuthorized(admin, nil)).To(BeTrue())
+ Expect(action.IsAuthorized(collaborator, nil)).To(BeFalse())
+ Expect(action.IsAuthorized(nil, nil)).To(BeFalse())
}
func TestUpdateTenantSettings_EmptyTitle(t *testing.T) {
diff --git a/app/actions/user.go b/app/actions/user.go
index df6ec1816..2a3fc1f16 100644
--- a/app/actions/user.go
+++ b/app/actions/user.go
@@ -21,7 +21,7 @@ func (input *ChangeUserRole) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *ChangeUserRole) IsAuthorized(user *models.User) bool {
+func (input *ChangeUserRole) IsAuthorized(user *models.User, services *app.Services) bool {
if user == nil {
return false
}
@@ -60,7 +60,7 @@ func (input *ChangeUserEmail) Initialize() interface{} {
}
// IsAuthorized returns true if current user is authorized to perform this action
-func (input *ChangeUserEmail) IsAuthorized(user *models.User) bool {
+func (input *ChangeUserEmail) IsAuthorized(user *models.User, services *app.Services) bool {
return user != nil
}
diff --git a/app/actions/user_test.go b/app/actions/user_test.go
index b5891bb21..3da9983af 100644
--- a/app/actions/user_test.go
+++ b/app/actions/user_test.go
@@ -17,7 +17,7 @@ func TestChangeUserRole_Unauthorized(t *testing.T) {
&models.User{ID: 2, Role: models.RoleAdministrator},
} {
action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: 2}}
- Expect(action.IsAuthorized(user)).To(BeFalse())
+ Expect(action.IsAuthorized(user, nil)).To(BeFalse())
}
}
@@ -26,7 +26,7 @@ func TestChangeUserRole_Authorized(t *testing.T) {
user := &models.User{ID: 2, Role: models.RoleAdministrator}
action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: 1}}
- Expect(action.IsAuthorized(user)).To(BeTrue())
+ Expect(action.IsAuthorized(user, nil)).To(BeTrue())
}
func TestChangeUserRole_InvalidRole(t *testing.T) {
@@ -47,7 +47,7 @@ func TestChangeUserRole_InvalidRole(t *testing.T) {
services.Users.Register(currentUser)
action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: targetUser.ID, Role: 4}}
- action.IsAuthorized(currentUser)
+ action.IsAuthorized(currentUser, nil)
result := action.Validate(currentUser, services)
ExpectFailed(result, "role")
}
@@ -61,7 +61,7 @@ func TestChangeUserRole_InvalidUser(t *testing.T) {
}
action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: 999, Role: models.RoleAdministrator}}
- action.IsAuthorized(currentUser)
+ action.IsAuthorized(currentUser, nil)
result := action.Validate(currentUser, services)
ExpectFailed(result, "user_id")
}
@@ -81,7 +81,7 @@ func TestChangeUserRole_InvalidUser_Tenant(t *testing.T) {
services.Users.Register(currentUser)
action := actions.ChangeUserRole{Model: &models.ChangeUserRole{UserID: targetUser.ID, Role: models.RoleAdministrator}}
- action.IsAuthorized(currentUser)
+ action.IsAuthorized(currentUser, nil)
result := action.Validate(currentUser, services)
ExpectFailed(result, "user_id")
}
diff --git a/app/handlers/idea.go b/app/handlers/idea.go
index 9be859e12..a82101c2c 100644
--- a/app/handlers/idea.go
+++ b/app/handlers/idea.go
@@ -77,7 +77,7 @@ func PostIdea() web.HandlerFunc {
}
}
-// UpdateIdea updates an existing ideaof current tenant
+// UpdateIdea updates an existing idea of current tenant
func UpdateIdea() web.HandlerFunc {
return func(c web.Context) error {
input := new(actions.UpdateIdea)
@@ -156,6 +156,23 @@ func PostComment() web.HandlerFunc {
}
}
+// UpdateComment changes an existing comment with new content
+func UpdateComment() web.HandlerFunc {
+ return func(c web.Context) error {
+ input := new(actions.EditComment)
+ if result := c.BindTo(input); !result.Ok {
+ return c.HandleValidation(result)
+ }
+
+ err := c.Services().Ideas.UpdateComment(input.Model.ID, input.Model.Content)
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ return c.Ok(web.Map{})
+ }
+}
+
// SetResponse changes current idea staff response
func SetResponse() web.HandlerFunc {
return func(c web.Context) error {
diff --git a/app/handlers/idea_test.go b/app/handlers/idea_test.go
index 27efa3e06..56433c4d0 100644
--- a/app/handlers/idea_test.go
+++ b/app/handlers/idea_test.go
@@ -334,3 +334,62 @@ func TestSetResponseHandler_Duplicate_Itself(t *testing.T) {
Expect(code).To(Equal(http.StatusBadRequest))
}
+
+func TestAddCommentHandler(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, services := mock.NewServer()
+ idea, _ := services.Ideas.Add("The Idea #1", "The Description #1", mock.AryaStark.ID)
+
+ code, _ := server.
+ OnTenant(mock.DemoTenant).
+ AsUser(mock.JonSnow).
+ AddParam("number", idea.Number).
+ ExecutePost(handlers.PostComment(), `{ "content": "My first comment" }`)
+
+ Expect(code).To(Equal(http.StatusOK))
+ comments, _ := services.Ideas.GetCommentsByIdea(idea.Number)
+ Expect(comments).To(HaveLen(1))
+}
+
+func TestUpdateCommentHandler_Authorized(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, services := mock.NewServer()
+ services.SetCurrentTenant(mock.DemoTenant)
+ services.SetCurrentUser(mock.AryaStark)
+ idea, _ := services.Ideas.Add("The Idea #1", "The Description #1", mock.AryaStark.ID)
+ commentId, _ := services.Ideas.AddComment(idea.Number, "My first comment", mock.AryaStark.ID)
+
+ code, _ := server.
+ OnTenant(mock.DemoTenant).
+ AsUser(mock.AryaStark).
+ AddParam("number", idea.Number).
+ AddParam("id", commentId).
+ ExecutePost(handlers.UpdateComment(), `{ "content": "My first comment has been edited" }`)
+
+ Expect(code).To(Equal(http.StatusOK))
+ comment, _ := services.Ideas.GetCommentByID(commentId)
+ Expect(comment.Content).To(Equal("My first comment has been edited"))
+}
+
+func TestUpdateCommentHandler_Unauthorized(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, services := mock.NewServer()
+ services.SetCurrentTenant(mock.DemoTenant)
+ services.SetCurrentUser(mock.JonSnow)
+ idea, _ := services.Ideas.Add("The Idea #1", "The Description #1", mock.JonSnow.ID)
+ commentId, _ := services.Ideas.AddComment(idea.Number, "My first comment", mock.JonSnow.ID)
+
+ code, _ := server.
+ OnTenant(mock.DemoTenant).
+ AsUser(mock.AryaStark).
+ AddParam("number", idea.Number).
+ AddParam("id", commentId).
+ ExecutePost(handlers.UpdateComment(), `{ "content": "My first comment has been edited" }`)
+
+ Expect(code).To(Equal(http.StatusForbidden))
+ comment, _ := services.Ideas.GetCommentByID(commentId)
+ Expect(comment.Content).To(Equal("My first comment"))
+}
diff --git a/app/models/feedback.go b/app/models/feedback.go
index ed2e95f7f..466065ceb 100644
--- a/app/models/feedback.go
+++ b/app/models/feedback.go
@@ -46,6 +46,13 @@ type NewComment struct {
Content string `json:"content"`
}
+// EditComment represents a request to edit existing comment
+type EditComment struct {
+ IdeaNumber int `route:"number"`
+ ID int `route:"id"`
+ Content string `json:"content"`
+}
+
// SetResponse represents the action to update an idea response
type SetResponse struct {
Number int `route:"number"`
@@ -72,10 +79,12 @@ type OriginalIdea struct {
//Comment represents an user comment on an idea
type Comment struct {
- ID int `json:"id"`
- Content string `json:"content"`
- CreatedOn time.Time `json:"createdOn"`
- User *User `json:"user"`
+ ID int `json:"id"`
+ Content string `json:"content"`
+ CreatedOn time.Time `json:"createdOn"`
+ User *User `json:"user"`
+ EditedOn *time.Time `json:"editedOn"`
+ EditedBy *User `json:"editedBy"`
}
//Tag represents a simple tag
diff --git a/app/pkg/validate/validation.go b/app/pkg/validate/validation.go
index 917a50938..096d0b097 100644
--- a/app/pkg/validate/validation.go
+++ b/app/pkg/validate/validation.go
@@ -8,7 +8,7 @@ import (
// Validatable defines which models can be validated against context
type Validatable interface {
Validate(user *models.User, services *app.Services) *Result
- IsAuthorized(user *models.User) bool
+ IsAuthorized(user *models.User, services *app.Services) bool
}
// Result is returned after each validation
diff --git a/app/pkg/web/context.go b/app/pkg/web/context.go
index d4c6a68c5..70a840dd7 100644
--- a/app/pkg/web/context.go
+++ b/app/pkg/web/context.go
@@ -109,7 +109,7 @@ func (ctx *Context) BindTo(i actions.Actionable) *validate.Result {
if err != nil {
return validate.Error(err)
}
- if !i.IsAuthorized(ctx.User()) {
+ if !i.IsAuthorized(ctx.User(), ctx.Services()) {
return validate.Unauthorized()
}
return i.Validate(ctx.User(), ctx.Services())
diff --git a/app/storage/inmemory/idea.go b/app/storage/inmemory/idea.go
index 4e700b8a4..4f47cb2df 100644
--- a/app/storage/inmemory/idea.go
+++ b/app/storage/inmemory/idea.go
@@ -13,9 +13,11 @@ import (
// IdeaStorage contains read and write operations for ideas
type IdeaStorage struct {
lastID int
+ lastCommentID int
ideas []*models.Idea
ideasSupportedBy map[int][]int
ideaSubscribers map[int][]int
+ ideaComments map[int][]*models.Comment
tenant *models.Tenant
user *models.User
}
@@ -26,6 +28,7 @@ func NewIdeaStorage() *IdeaStorage {
ideas: make([]*models.Idea, 0),
ideasSupportedBy: make(map[int][]int, 0),
ideaSubscribers: make(map[int][]int, 0),
+ ideaComments: make(map[int][]*models.Comment, 0),
}
}
@@ -95,9 +98,13 @@ func (s *IdeaStorage) Search(query, filter string, tags []string) ([]*models.Ide
return s.ideas, nil
}
-// GetCommentsByIdea returns all coments from given idea
+// GetCommentsByIdea returns all comments from given idea
func (s *IdeaStorage) GetCommentsByIdea(number int) ([]*models.Comment, error) {
- return make([]*models.Comment, 0), nil
+ idea, err := s.GetByNumber(number)
+ if err != nil {
+ return nil, err
+ }
+ return s.ideaComments[idea.ID], nil
}
// Add a new idea in the database
@@ -120,7 +127,47 @@ func (s *IdeaStorage) Add(title, description string, userID int) (*models.Idea,
// AddComment places a new comment on an idea
func (s *IdeaStorage) AddComment(number int, content string, userID int) (int, error) {
- return 0, nil
+ idea, err := s.GetByNumber(number)
+ if err != nil {
+ return 0, err
+ }
+ s.lastCommentID++
+ s.ideaComments[idea.ID] = append(s.ideaComments[idea.ID], &models.Comment{
+ ID: s.lastCommentID,
+ Content: content,
+ CreatedOn: time.Now(),
+ User: &models.User{
+ ID: userID,
+ Tenant: s.tenant,
+ },
+ })
+
+ return s.lastCommentID, nil
+}
+
+// GetCommentByID returns a comment by given ID
+func (s *IdeaStorage) GetCommentByID(id int) (*models.Comment, error) {
+ for _, comments := range s.ideaComments {
+ for _, comment := range comments {
+ if comment.ID == id && comment.User.Tenant == s.tenant {
+ return comment, nil
+ }
+ }
+ }
+ return nil, app.ErrNotFound
+}
+
+// UpdateComment with given ID and content
+func (s *IdeaStorage) UpdateComment(id int, content string) error {
+ now := time.Now()
+ comment, err := s.GetCommentByID(id)
+ if err != nil {
+ return err
+ }
+ comment.Content = content
+ comment.EditedOn = &now
+ comment.EditedBy = s.user
+ return nil
}
// AddSupporter adds user to idea list of supporters
diff --git a/app/storage/postgres/idea.go b/app/storage/postgres/idea.go
index 778e20f5a..7779cba47 100644
--- a/app/storage/postgres/idea.go
+++ b/app/storage/postgres/idea.go
@@ -72,19 +72,26 @@ func (i *dbIdea) toModel() *models.Idea {
}
type dbComment struct {
- ID int `db:"id"`
- Content string `db:"content"`
- CreatedOn time.Time `db:"created_on"`
- User *dbUser `db:"user"`
+ ID int `db:"id"`
+ Content string `db:"content"`
+ CreatedOn time.Time `db:"created_on"`
+ User *dbUser `db:"user"`
+ EditedOn dbx.NullTime `db:"edited_on"`
+ EditedBy *dbUser `db:"edited_by"`
}
func (c *dbComment) toModel() *models.Comment {
- return &models.Comment{
+ comment := &models.Comment{
ID: c.ID,
Content: c.Content,
CreatedOn: c.CreatedOn,
User: c.User.toModel(),
}
+ if c.EditedOn.Valid {
+ comment.EditedBy = c.EditedBy.toModel()
+ comment.EditedOn = &c.EditedOn.Time
+ }
+ return comment
}
type dbStatusCount struct {
@@ -296,10 +303,15 @@ func (s *IdeaStorage) GetCommentsByIdea(number int) ([]*models.Comment, error) {
`SELECT c.id,
c.content,
c.created_on,
+ c.edited_on,
u.id AS user_id,
u.name AS user_name,
u.email AS user_email,
- u.role AS user_role
+ u.role AS user_role,
+ e.id AS edited_by_id,
+ e.name AS edited_by_name,
+ e.email AS edited_by_email,
+ e.role AS edited_by_role
FROM comments c
INNER JOIN ideas i
ON i.id = c.idea_id
@@ -307,6 +319,9 @@ func (s *IdeaStorage) GetCommentsByIdea(number int) ([]*models.Comment, error) {
INNER JOIN users u
ON u.id = c.user_id
AND u.tenant_id = c.tenant_id
+ LEFT JOIN users e
+ ON e.id = c.edited_by_id
+ AND e.tenant_id = c.tenant_id
WHERE i.number = $1
AND i.tenant_id = $2
ORDER BY c.created_on ASC`, number, s.tenant.ID)
@@ -376,6 +391,45 @@ func (s *IdeaStorage) AddComment(number int, content string, userID int) (int, e
return id, nil
}
+// GetCommentByID returns a comment by given ID
+func (s *IdeaStorage) GetCommentByID(id int) (*models.Comment, error) {
+ comment := dbComment{}
+ err := s.trx.Get(&comment,
+ `SELECT c.id,
+ c.content,
+ c.created_on,
+ c.edited_on,
+ u.id AS user_id,
+ u.name AS user_name,
+ u.email AS user_email,
+ u.role AS user_role,
+ e.id AS edited_by_id,
+ e.name AS edited_by_name,
+ e.email AS edited_by_email,
+ e.role AS edited_by_role
+ FROM comments c
+ INNER JOIN users u
+ ON u.id = c.user_id
+ AND u.tenant_id = c.tenant_id
+ LEFT JOIN users e
+ ON e.id = c.edited_by_id
+ AND e.tenant_id = c.tenant_id
+ WHERE c.id = $1
+ AND c.tenant_id = $2`, id, s.tenant.ID)
+
+ if err != nil {
+ return nil, err
+ }
+
+ return comment.toModel(), nil
+}
+
+// UpdateComment with given ID and content
+func (s *IdeaStorage) UpdateComment(id int, content string) error {
+ return s.trx.Execute(`UPDATE comments SET content = $1, edited_on = $2, edited_by_id = $3
+ WHERE id = $4 AND tenant_id = $5`, content, time.Now(), s.user.ID, id, s.tenant.ID)
+}
+
// AddSupporter adds user to idea list of supporters
func (s *IdeaStorage) AddSupporter(number, userID int) error {
idea, err := s.GetByNumber(number)
diff --git a/app/storage/postgres/idea_test.go b/app/storage/postgres/idea_test.go
index 387912208..7d1802414 100644
--- a/app/storage/postgres/idea_test.go
+++ b/app/storage/postgres/idea_test.go
@@ -114,6 +114,38 @@ func TestIdeaStorage_AddAndReturnComments(t *testing.T) {
Expect(comments[1].User.Name).To(Equal("Arya Stark"))
}
+func TestIdeaStorage_AddGetUpdateComment(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ ideas.SetCurrentTenant(demoTenant)
+ idea, err := ideas.Add("My new idea", "with this description", jonSnow.ID)
+ Expect(err).To(BeNil())
+
+ commentId, err := ideas.AddComment(idea.Number, "Comment #1", jonSnow.ID)
+ Expect(err).To(BeNil())
+
+ comment, err := ideas.GetCommentByID(commentId)
+ Expect(err).To(BeNil())
+ Expect(comment.ID).To(Equal(commentId))
+ Expect(comment.Content).To(Equal("Comment #1"))
+ Expect(comment.User.ID).To(Equal(jonSnow.ID))
+ Expect(comment.EditedOn).To(BeNil())
+ Expect(comment.EditedBy).To(BeNil())
+
+ ideas.SetCurrentUser(aryaStark)
+ err = ideas.UpdateComment(commentId, "Comment #1 with edit")
+ Expect(err).To(BeNil())
+
+ comment, err = ideas.GetCommentByID(commentId)
+ Expect(err).To(BeNil())
+ Expect(comment.ID).To(Equal(commentId))
+ Expect(comment.Content).To(Equal("Comment #1 with edit"))
+ Expect(comment.User.ID).To(Equal(jonSnow.ID))
+ Expect(comment.EditedOn).NotTo(BeNil())
+ Expect(comment.EditedBy.ID).To(Equal(aryaStark.ID))
+}
+
func TestIdeaStorage_AddAndGet_DifferentTenants(t *testing.T) {
SetupDatabaseTest(t)
defer TeardownDatabaseTest()
diff --git a/app/storage/storage.go b/app/storage/storage.go
index bfe2c1b97..d134a714d 100644
--- a/app/storage/storage.go
+++ b/app/storage/storage.go
@@ -25,6 +25,8 @@ type Idea interface {
Add(title, description string, userID int) (*models.Idea, error)
Update(number int, title, description string) (*models.Idea, error)
AddComment(number int, content string, userID int) (int, error)
+ GetCommentByID(id int) (*models.Comment, error)
+ UpdateComment(id int, content string) error
AddSupporter(number, userID int) error
RemoveSupporter(number, userID int) error
AddSubscriber(number, userID int) error
diff --git a/migrations/201803110836_edit_comment_columns.up.sql b/migrations/201803110836_edit_comment_columns.up.sql
new file mode 100644
index 000000000..38ab38b83
--- /dev/null
+++ b/migrations/201803110836_edit_comment_columns.up.sql
@@ -0,0 +1,8 @@
+-- add tenant_id
+ALTER TABLE comments ADD edited_on TIMESTAMPTZ NULL;
+ALTER TABLE comments ADD edited_by_id INT NULL;
+
+ALTER TABLE comments
+ ADD CONSTRAINT comments_edited_by_id_fkey
+ FOREIGN KEY (edited_by_id, tenant_id)
+ REFERENCES users(id, tenant_id);
\ No newline at end of file
diff --git a/public/components/common/Button.scss b/public/components/common/Button.scss
index 318a9ec0f..0849744f4 100644
--- a/public/components/common/Button.scss
+++ b/public/components/common/Button.scss
@@ -56,6 +56,18 @@
font-size: $font-size-large;
}
+ &.as-link {
+ background-color: transparent;
+ padding: 0;
+ font-weight: 400;
+ color: rgba($text-color, 0.6);
+
+ &:hover {
+ color: $text-color;
+ text-decoration: underline;
+ }
+ }
+
&.fluid {
display: block;
width: 100%;
diff --git a/public/components/common/Button.tsx b/public/components/common/Button.tsx
index aa2c736b4..234abe860 100644
--- a/public/components/common/Button.tsx
+++ b/public/components/common/Button.tsx
@@ -68,10 +68,9 @@ export class Button extends React.Component<ButtonProps, ButtonState> {
}
public render() {
- // TODO: as-link if simple === true
-
const className = classSet({
'c-button': true,
+ 'as-link': this.props.simple,
'fluid': this.props.fluid,
[this.props.size!]: this.props.size,
[this.props.color!]: this.props.color,
diff --git a/public/components/common/Moment.tsx b/public/components/common/Moment.tsx
index 363671da5..7b7266530 100644
--- a/public/components/common/Moment.tsx
+++ b/public/components/common/Moment.tsx
@@ -1,66 +1,10 @@
import * as React from 'react';
+import { formatDate, timeSince } from '@fider/services';
interface MomentText {
date: Date | string;
}
-const templates: { [key: string]: string } = {
- seconds: 'less than a minute',
- minute: 'about a minute',
- minutes: '%d minutes',
- hour: 'about an hour',
- hours: 'about %d hours',
- day: 'a day',
- days: '%d days',
- month: 'about a month',
- months: '%d months',
- year: 'about a year',
- years: '%d years'
-};
-
-const template = (t: string, n: number): string => {
- return templates[t] && templates[t].replace(/%d/i, Math.abs(Math.round(n)).toString());
-};
-
-const monthNames = [
- 'January', 'February', 'March',
- 'April', 'May', 'June', 'July',
- 'August', 'September', 'October',
- 'November', 'December'
-];
-
-function format(date: Date) {
-
- const day = date.getDate();
- const monthIndex = date.getMonth();
- const year = date.getFullYear();
-
- return `${monthNames[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()} · ${date.getHours()}:${date.getMinutes()}`;
-}
-
-function timeSince(now: Date, date: Date) {
-
- const seconds = (now.getTime() - date.getTime()) / 1000;
- const minutes = seconds / 60;
- const hours = minutes / 60;
- const days = hours / 24;
- const years = days / 365;
-
- return (
- seconds < 45 && template('seconds', seconds) ||
- seconds < 90 && template('minute', 1) ||
- minutes < 45 && template('minutes', minutes) ||
- minutes < 90 && template('hour', 1) ||
- hours < 24 && template('hours', hours) ||
- hours < 42 && template('day', 1) ||
- days < 30 && template('days', days) ||
- days < 45 && template('month', 1) ||
- days < 365 && template('months', days / 30) ||
- years < 1.5 && template('year', 1) ||
- template('years', years)
- ) + ' ago';
-}
-
export const Moment = (props: MomentText) => {
if (!props.date) {
return <span />;
@@ -70,14 +14,10 @@ export const Moment = (props: MomentText) => {
const date = props.date instanceof Date ? props.date : new Date(props.date);
const diff = (now.getTime() - date.getTime()) / (60 * 60 * 24 * 1000);
-
- // const m = moment(props.date);
- // const diff = m.diff(new Date(), 'years');
- // const display = (diff !== 0) ? m.format('MMMM D, YYYY') : m.fromNow();
- const display = (diff >= 365) ? format(date) : timeSince(now, date);
+ const display = (diff >= 365) ? formatDate(props.date) : timeSince(now, date);
return (
- <span className="date" title={format(date)}>
+ <span className="date" title={formatDate(props.date)}>
{display}
</span>
);
diff --git a/public/models/idea.ts b/public/models/idea.ts
index 4f5ef96b5..07d7503a0 100644
--- a/public/models/idea.ts
+++ b/public/models/idea.ts
@@ -68,6 +68,8 @@ export interface Comment {
content: string;
createdOn: string;
user: User;
+ editedOn?: string;
+ editedBy?: User;
}
export interface Tag {
diff --git a/public/pages/ShowIdea/ShowIdea.page.scss b/public/pages/ShowIdea/ShowIdea.page.scss
index 694555e7b..8a28fec67 100644
--- a/public/pages/ShowIdea/ShowIdea.page.scss
+++ b/public/pages/ShowIdea/ShowIdea.page.scss
@@ -12,6 +12,12 @@
height: 24px;
}
}
+
+ .page {
+ .subtitle {
+ margin-top: 1em;
+ }
+ }
@media only screen and (min-width: 768px) {
.header-col,
@@ -32,9 +38,6 @@
@media only screen and (min-width: 768px) {
width: 200px;
}
- .subtitle {
- margin-top: 1em;
- }
.ui.list {
margin: 0.5em 0em;
}
@@ -72,13 +75,12 @@
.comment > .content {
display: inline-block;
- max-width: 85%;
+ width: 85%;
}
}
.comment-input {
- margin-top: 0.3em;
-
+ margin-top: 15px;
textarea {
margin-top: 5px;
}
diff --git a/public/pages/ShowIdea/ShowIdea.page.tsx b/public/pages/ShowIdea/ShowIdea.page.tsx
index 79058f925..19c28727d 100644
--- a/public/pages/ShowIdea/ShowIdea.page.tsx
+++ b/public/pages/ShowIdea/ShowIdea.page.tsx
@@ -5,7 +5,7 @@ import * as React from 'react';
import { CurrentUser, Comment, Idea, Tag } from '@fider/models';
import { page, actions, Failure } from '@fider/services';
-import { TagsPanel, CommentInput, CommentList, ResponseForm, NotificationsPanel } from './';
+import { TagsPanel, DiscussionPanel, ResponseForm, NotificationsPanel } from './';
import { SupportCounter, ShowIdeaResponse, DisplayError, Button, Textarea, UserName, Gravatar, Moment, MultiLineText } from '@fider/components';
interface ShowIdeaPageProps {
@@ -134,13 +134,7 @@ export class ShowIdeaPage extends React.Component<ShowIdeaPageProps, ShowIdeaPag
<NotificationsPanel user={this.props.user} idea={this.props.idea} subscribed={this.props.subscribed} />
</div>
- <div className="comments-col">
- <div className="ui comments">
- <span className="subtitle">Discussion</span>
- <CommentList comments={this.props.comments} />
- <CommentInput user={this.props.user} idea={this.props.idea} />
- </div>
- </div>
+ <DiscussionPanel user={this.props.user} idea={this.props.idea} comments={this.props.comments} />
</div>
);
}
diff --git a/public/pages/ShowIdea/components/CommentList.tsx b/public/pages/ShowIdea/components/CommentList.tsx
index 66996baad..a044db951 100644
--- a/public/pages/ShowIdea/components/CommentList.tsx
+++ b/public/pages/ShowIdea/components/CommentList.tsx
@@ -1,30 +1,113 @@
import * as React from 'react';
-import { Comment } from '@fider/models';
-import { UserName, Gravatar, Moment, MultiLineText } from '@fider/components/common';
+import { Idea, Comment, CurrentUser } from '@fider/models';
+import { Failure, actions, formatDate } from '@fider/services';
+import { DisplayError, Textarea, Button, UserName, Gravatar, Moment, MultiLineText } from '@fider/components/common';
interface CommentListProps {
+ idea: Idea;
comments: Comment[];
+ user?: CurrentUser;
+ onStartEdit?: () => void;
+ onStopEdit?: () => void;
}
-export class CommentList extends React.Component<CommentListProps, {}> {
+interface CommentListState {
+ editingComment?: Comment;
+ editCommentNewContent: string;
+ error?: Failure;
+}
+
+export class CommentList extends React.Component<CommentListProps, CommentListState> {
constructor(props: CommentListProps) {
super(props);
+ this.state = {
+ editCommentNewContent: '',
+ };
+ }
+
+ private async startEdit(comment: Comment): Promise<void> {
+ this.setState({
+ editingComment: comment,
+ editCommentNewContent: comment.content,
+ error: undefined,
+ });
+
+ if (this.props.onStartEdit) {
+ this.props.onStartEdit();
+ }
+ }
+
+ private async cancelEdit(): Promise<void> {
+ this.setState({
+ editingComment: undefined,
+ editCommentNewContent: '',
+ error: undefined,
+ });
+
+ if (this.props.onStopEdit) {
+ this.props.onStopEdit();
+ }
+ }
+
+ private async confirmEdit(): Promise<void> {
+ if (this.state.editingComment) {
+ const response = await actions.updateComment(this.props.idea.number, this.state.editingComment.id, this.state.editCommentNewContent);
+ if (response.ok) {
+ this.state.editingComment.content = this.state.editCommentNewContent;
+ this.state.editingComment.editedOn = new Date().toISOString();
+ this.state.editingComment.editedBy = this.props.user;
+ this.cancelEdit();
+ } else {
+ this.setState({ error: response.error });
+ }
+ }
+ }
+
+ private canEditComment(comment: Comment): boolean {
+ if (this.props.user) {
+ return this.props.user.isCollaborator || comment.user.id === this.props.user.id;
+ }
+ return false;
}
public render() {
- return this.props.comments.map((c) => (
- <div key={c.id} className="comment">
- <Gravatar user={c.user} />
- <div className="content">
- <UserName user={c.user} />
- <div className="metadata">
- · <Moment date={c.createdOn} />
- </div>
- <div className="text">
- <MultiLineText text={c.content} style="simple" />
+ return this.props.comments.map((c) => {
+ return (
+ <div key={c.id} className="comment">
+ <Gravatar user={c.user} />
+ <div className="content">
+ <UserName user={c.user} />
+ <div className="metadata">
+ · <Moment date={c.createdOn} />
+ </div>
+ { !!c.editedOn && !!c.editedBy && <div className="metadata">
+ · <span title={`This comment has been edited by ${c.editedBy!.name} on ${formatDate(c.editedOn)}`}>edited</span>
+ </div> }
+ { this.canEditComment(c) && <div className="metadata">
+ · <Button simple={true} size="small" onClick={() => this.startEdit(c)}>edit</Button>
+ </div> }
+ <div className="text">
+ {
+ c === this.state.editingComment
+ ? <div className="ui form">
+ <DisplayError error={this.state.error} />
+ <div className="field">
+ <Textarea
+ rows={1}
+ defaultValue={c.content}
+ placeholder={c.content}
+ onChange={(e) => this.setState({ editCommentNewContent: e.currentTarget.value })}
+ />
+ </div>
+ <Button size="tiny" onClick={() => this.confirmEdit()} color="green">Save</Button>
+ <Button size="tiny" onClick={() => this.cancelEdit()}>Cancel</Button>
+ </div>
+ : <MultiLineText text={c.content} style="simple" />
+ }
+ </div>
</div>
</div>
- </div>
- ));
+ );
+ });
}
}
diff --git a/public/pages/ShowIdea/components/DiscussionPanel.tsx b/public/pages/ShowIdea/components/DiscussionPanel.tsx
new file mode 100644
index 000000000..b0e5f4cc9
--- /dev/null
+++ b/public/pages/ShowIdea/components/DiscussionPanel.tsx
@@ -0,0 +1,45 @@
+import * as React from 'react';
+import { CurrentUser, Comment, Idea } from '@fider/models';
+import { CommentList, CommentInput } from '../';
+import { actions } from '@fider/services';
+
+interface DiscussionPanelProps {
+ user?: CurrentUser;
+ idea: Idea;
+ comments: Comment[];
+}
+
+interface DiscussionPanelState {
+ isEditing: boolean;
+}
+
+export class DiscussionPanel extends React.Component<DiscussionPanelProps, DiscussionPanelState> {
+
+ constructor(props: DiscussionPanelProps) {
+ super(props);
+ this.state = {
+ isEditing: false,
+ };
+ }
+
+ public render() {
+ return (
+ <div className="comments-col">
+ <div className="ui comments">
+ <span className="subtitle">Discussion</span>
+ <CommentList
+ idea={this.props.idea}
+ user={this.props.user}
+ comments={this.props.comments}
+ onStartEdit={() => this.setState({ isEditing: true })}
+ onStopEdit={() => this.setState({ isEditing: false })}
+ />
+ { !this.state.isEditing && <CommentInput
+ user={this.props.user}
+ idea={this.props.idea}
+ /> }
+ </div>
+ </div>
+ );
+ }
+}
diff --git a/public/pages/ShowIdea/index.ts b/public/pages/ShowIdea/index.ts
index 8ad113a49..4ed3a20e8 100644
--- a/public/pages/ShowIdea/index.ts
+++ b/public/pages/ShowIdea/index.ts
@@ -5,3 +5,4 @@ export * from './components/CommentList';
export * from './components/IdeaSearch';
export * from './components/TagsPanel';
export * from './components/NotificationsPanel';
+export * from './components/DiscussionPanel';
diff --git a/public/services/actions/idea.ts b/public/services/actions/idea.ts
index be782a373..bd0617bd9 100644
--- a/public/services/actions/idea.ts
+++ b/public/services/actions/idea.ts
@@ -29,6 +29,10 @@ export const createComment = async (ideaNumber: number, content: string): Promis
return http.post(`/api/ideas/${ideaNumber}/comments`, { content }).then(http.event('comment', 'create'));
};
+export const updateComment = async (ideaNumber: number, commentId: number, content: string): Promise<Result> => {
+ return http.post(`/api/ideas/${ideaNumber}/comments/${commentId}`, { content }).then(http.event('comment', 'update'));
+};
+
interface SetResponseInput {
status: number;
text: string;
diff --git a/public/services/utils.ts b/public/services/utils.ts
index 9c407f63e..26c7a9b88 100644
--- a/public/services/utils.ts
+++ b/public/services/utils.ts
@@ -14,3 +14,67 @@ export const classSet = (input?: any): string => {
}
return '';
};
+
+const monthNames = [
+ 'January', 'February', 'March',
+ 'April', 'May', 'June', 'July',
+ 'August', 'September', 'October',
+ 'November', 'December'
+];
+
+const twoDigits = (value: number): string => {
+ return value < 9 ? `0${value}` : value.toString();
+};
+
+export const formatDate = (input: Date | string): string => {
+ const date = input instanceof Date ? input : new Date(input);
+
+ const day = date.getDate();
+ const monthIndex = date.getMonth();
+ const year = date.getFullYear();
+ const hours = twoDigits(date.getHours());
+ const minutes = twoDigits(date.getMinutes());
+
+ return `${monthNames[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()} · ${hours}:${minutes}`;
+};
+
+const templates: { [key: string]: string } = {
+ seconds: 'less than a minute',
+ minute: 'about a minute',
+ minutes: '%d minutes',
+ hour: 'about an hour',
+ hours: 'about %d hours',
+ day: 'a day',
+ days: '%d days',
+ month: 'about a month',
+ months: '%d months',
+ year: 'about a year',
+ years: '%d years'
+};
+
+const template = (t: string, n: number): string => {
+ return templates[t] && templates[t].replace(/%d/i, Math.abs(Math.round(n)).toString());
+};
+
+export const timeSince = (now: Date, date: Date): string => {
+
+ const seconds = (now.getTime() - date.getTime()) / 1000;
+ const minutes = seconds / 60;
+ const hours = minutes / 60;
+ const days = hours / 24;
+ const years = days / 365;
+
+ return (
+ seconds < 45 && template('seconds', seconds) ||
+ seconds < 90 && template('minute', 1) ||
+ minutes < 45 && template('minutes', minutes) ||
+ minutes < 90 && template('hour', 1) ||
+ hours < 24 && template('hours', hours) ||
+ hours < 42 && template('day', 1) ||
+ days < 30 && template('days', days) ||
+ days < 45 && template('month', 1) ||
+ days < 365 && template('months', days / 30) ||
+ years < 1.5 && template('year', 1) ||
+ template('years', years)
+ ) + ' ago';
+};
diff --git a/routes.go b/routes.go
index cb85ed402..0d95e6c6f 100644
--- a/routes.go
+++ b/routes.go
@@ -84,6 +84,7 @@ func GetMainEngine(settings *models.SystemSettings) *web.Engine {
private.Post("/api/ideas", handlers.PostIdea())
private.Post("/api/ideas/:number", handlers.UpdateIdea())
private.Post("/api/ideas/:number/comments", handlers.PostComment())
+ private.Post("/api/ideas/:number/comments/:id", handlers.UpdateComment())
private.Post("/api/ideas/:number/status", handlers.SetResponse())
private.Post("/api/ideas/:number/support", handlers.AddSupporter())
private.Post("/api/ideas/:number/unsupport", handlers.RemoveSupporter())