Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

feature: allow comments to be deleted (#583)

Guilherme Oenning03861b83b070
diff --git a/app/actions/post.go b/app/actions/post.go
index 4c5705085..d1bf9aa69 100644
--- a/app/actions/post.go
+++ b/app/actions/post.go
@@ -241,3 +241,29 @@ func (input *EditComment) Validate(user *models.User, services *app.Services) *v
return result
}
+
+// DeleteComment represents the action of deleting an existing comment
+type DeleteComment struct {
+ Model *models.DeleteComment
+}
+
+// Initialize the model
+func (input *DeleteComment) Initialize() interface{} {
+ input.Model = new(models.DeleteComment)
+ return input.Model
+}
+
+// IsAuthorized returns true if current user is authorized to perform this action
+func (input *DeleteComment) IsAuthorized(user *models.User, services *app.Services) bool {
+ comment, err := services.Posts.GetCommentByID(input.Model.CommentID)
+ if err != nil {
+ return false
+ }
+
+ return user.ID == comment.User.ID || user.IsCollaborator()
+}
+
+// Validate if current model is valid
+func (input *DeleteComment) Validate(user *models.User, services *app.Services) *validate.Result {
+ return validate.Success()
+}
diff --git a/app/actions/post_test.go b/app/actions/post_test.go
index 57f0cc277..36ca0aabc 100644
--- a/app/actions/post_test.go
+++ b/app/actions/post_test.go
@@ -75,3 +75,27 @@ func TestDeletePost_WhenIsBeingReferenced(t *testing.T) {
model.Number = post1.Number
ExpectFailed(action.Validate(nil, services))
}
+
+func TestDeleteComment(t *testing.T) {
+ RegisterT(t)
+
+ author := &models.User{ID: 1, Role: models.RoleVisitor}
+ notAuthor := &models.User{ID: 2, Role: models.RoleVisitor}
+ administrator := &models.User{ID: 3, Role: models.RoleAdministrator}
+
+ services.SetCurrentUser(author)
+ post1, _ := services.Posts.Add("Post #1", "")
+ commentID, _ := services.Posts.AddComment(post1, "Comment #1")
+
+ action := &actions.DeleteComment{
+ Model: &models.DeleteComment{
+ CommentID: commentID,
+ },
+ }
+
+ authorized := action.IsAuthorized(notAuthor, services)
+ Expect(authorized).IsFalse()
+
+ authorized = action.IsAuthorized(administrator, services)
+ Expect(authorized).IsTrue()
+}
diff --git a/app/cmd/routes.go b/app/cmd/routes.go
index 180c06c81..808402326 100644
--- a/app/cmd/routes.go
+++ b/app/cmd/routes.go
@@ -161,6 +161,7 @@ func routes(r *web.Engine) *web.Engine {
api.Post("/api/v1/posts", apiv1.CreatePost())
api.Post("/api/v1/posts/:number/comments", apiv1.PostComment())
api.Put("/api/v1/posts/:number/comments/:id", apiv1.UpdateComment())
+ api.Delete("/api/v1/posts/:number/comments/:id", apiv1.DeleteComment())
api.Post("/api/v1/posts/:number/votes", apiv1.AddVote())
api.Delete("/api/v1/posts/:number/votes", apiv1.RemoveVote())
api.Post("/api/v1/posts/:number/subscription", apiv1.Subscribe())
diff --git a/app/handlers/apiv1/post.go b/app/handlers/apiv1/post.go
index 81e85b530..c4bc958a7 100644
--- a/app/handlers/apiv1/post.go
+++ b/app/handlers/apiv1/post.go
@@ -180,6 +180,23 @@ func UpdateComment() web.HandlerFunc {
}
}
+// DeleteComment deletes an existing comment by its ID
+func DeleteComment() web.HandlerFunc {
+ return func(c web.Context) error {
+ input := new(actions.DeleteComment)
+ if result := c.BindTo(input); !result.Ok {
+ return c.HandleValidation(result)
+ }
+
+ err := c.Services().Posts.DeleteComment(input.Model.CommentID)
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ return c.Ok(web.Map{})
+ }
+}
+
// AddVote adds current user to given post list of votes
func AddVote() web.HandlerFunc {
return func(c web.Context) error {
diff --git a/app/models/feedback.go b/app/models/feedback.go
index 4c2fce2a7..15fafa82c 100644
--- a/app/models/feedback.go
+++ b/app/models/feedback.go
@@ -59,6 +59,12 @@ type EditComment struct {
Content string `json:"content"`
}
+// DeleteComment represents a request to delete an existing comment
+type DeleteComment struct {
+ PostNumber int `route:"number"`
+ CommentID int `route:"id"`
+}
+
// SetResponse represents the action to update an post response
type SetResponse struct {
Number int `route:"number"`
diff --git a/app/storage/inmemory/post.go b/app/storage/inmemory/post.go
index bec998f58..aab66757a 100644
--- a/app/storage/inmemory/post.go
+++ b/app/storage/inmemory/post.go
@@ -128,6 +128,21 @@ func (s *PostStorage) AddComment(post *models.Post, content string) (int, error)
return s.lastCommentID, nil
}
+// DeleteComment by its id
+func (s *PostStorage) DeleteComment(id int) error {
+ for _, p := range s.posts {
+ if comments, ok := s.postComments[p.ID]; ok {
+ for idx, comment := range comments {
+ if comment.ID == id {
+ s.postComments[p.ID] = append(comments[:idx], comments[idx+1:]...)
+ }
+ }
+ }
+ }
+
+ return nil
+}
+
// GetCommentByID returns a comment by given ID
func (s *PostStorage) GetCommentByID(id int) (*models.Comment, error) {
for _, comments := range s.postComments {
diff --git a/app/storage/postgres/post.go b/app/storage/postgres/post.go
index e1f663560..66f267b45 100644
--- a/app/storage/postgres/post.go
+++ b/app/storage/postgres/post.go
@@ -136,6 +136,7 @@ var (
ON posts.id = comments.post_id
AND posts.tenant_id = comments.tenant_id
WHERE posts.tenant_id = $1
+ AND comments.deleted_at IS NULL
GROUP BY post_id
),
agg_votes AS (
@@ -352,6 +353,7 @@ func (s *PostStorage) GetCommentsByPost(post *models.Post) ([]*models.Comment, e
AND e.tenant_id = c.tenant_id
WHERE p.id = $1
AND p.tenant_id = $2
+ AND c.deleted_at IS NULL
ORDER BY c.created_at ASC`, post.ID, s.tenant.ID)
if err != nil {
return nil, errors.Wrap(err, "failed get comments of post with id '%d'", post.ID)
@@ -405,9 +407,11 @@ func (s *PostStorage) Add(title, description string) (*models.Post, error) {
// AddComment places a new comment on an post
func (s *PostStorage) AddComment(post *models.Post, content string) (int, error) {
var id int
- if err := s.trx.Get(&id,
- "INSERT INTO comments (tenant_id, post_id, content, user_id, created_at) VALUES ($1, $2, $3, $4, $5) RETURNING id",
- s.tenant.ID, post.ID, content, s.user.ID, time.Now()); err != nil {
+ if err := s.trx.Get(&id, `
+ INSERT INTO comments (tenant_id, post_id, content, user_id, created_at)
+ VALUES ($1, $2, $3, $4, $5)
+ RETURNING id
+ `, s.tenant.ID, post.ID, content, s.user.ID, time.Now()); err != nil {
return 0, errors.Wrap(err, "failed add new comment")
}
@@ -418,6 +422,17 @@ func (s *PostStorage) AddComment(post *models.Post, content string) (int, error)
return id, nil
}
+// DeleteComment by its id
+func (s *PostStorage) DeleteComment(id int) error {
+ if _, err := s.trx.Execute(
+ "UPDATE comments SET deleted_at = $1, deleted_by_id = $2 WHERE id = $3 AND tenant_id = $4",
+ time.Now(), s.user.ID, id, s.tenant.ID,
+ ); err != nil {
+ return errors.Wrap(err, "failed delete comment")
+ }
+ return nil
+}
+
// GetCommentByID returns a comment by given ID
func (s *PostStorage) GetCommentByID(id int) (*models.Comment, error) {
comment := dbComment{}
@@ -444,7 +459,8 @@ func (s *PostStorage) GetCommentByID(id int) (*models.Comment, error) {
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)
+ AND c.tenant_id = $2
+ AND c.deleted_at IS NULL`, id, s.tenant.ID)
if err != nil {
return nil, err
diff --git a/app/storage/postgres/post_test.go b/app/storage/postgres/post_test.go
index 3fc611f5f..7e4af52a9 100644
--- a/app/storage/postgres/post_test.go
+++ b/app/storage/postgres/post_test.go
@@ -156,6 +156,26 @@ func TestPostStorage_AddGetUpdateComment(t *testing.T) {
Expect(comment.EditedBy.ID).Equals(aryaStark.ID)
}
+func TestPostStorage_AddDeleteComment(t *testing.T) {
+ SetupDatabaseTest(t)
+ defer TeardownDatabaseTest()
+
+ posts.SetCurrentTenant(demoTenant)
+ posts.SetCurrentUser(jonSnow)
+ post, err := posts.Add("My new post", "with this description")
+ Expect(err).IsNil()
+
+ commentID, err := posts.AddComment(post, "Comment #1")
+ Expect(err).IsNil()
+
+ err = posts.DeleteComment(commentID)
+ Expect(err).IsNil()
+
+ comment, err := posts.GetCommentByID(commentID)
+ Expect(err).Equals(app.ErrNotFound)
+ Expect(comment).IsNil()
+}
+
func TestPostStorage_AddAndGet_DifferentTenants(t *testing.T) {
SetupDatabaseTest(t)
defer TeardownDatabaseTest()
diff --git a/app/storage/storage.go b/app/storage/storage.go
index 149d67dd1..d94f2a36a 100644
--- a/app/storage/storage.go
+++ b/app/storage/storage.go
@@ -27,6 +27,7 @@ type Post interface {
AddComment(post *models.Post, content string) (int, error)
GetCommentByID(id int) (*models.Comment, error)
UpdateComment(id int, content string) error
+ DeleteComment(id int) error
AddVote(post *models.Post, user *models.User) error
RemoveVote(post *models.Post, user *models.User) error
AddSubscriber(post *models.Post, user *models.User) error
diff --git a/migrations/201810152035_add_comment_deleted.sql b/migrations/201810152035_add_comment_deleted.sql
new file mode 100644
index 000000000..3e28eacb3
--- /dev/null
+++ b/migrations/201810152035_add_comment_deleted.sql
@@ -0,0 +1,7 @@
+ALTER TABLE comments ADD deleted_at TIMESTAMPTZ NULL;
+ALTER TABLE comments ADD deleted_by_id INT NULL;
+
+ALTER TABLE comments
+ ADD CONSTRAINT comments_deleted_by_id_fkey
+ FOREIGN KEY (deleted_by_id, tenant_id)
+ REFERENCES users(id, tenant_id);
\ No newline at end of file
diff --git a/public/components/common/DropDown.tsx b/public/components/common/DropDown.tsx
index 528cc3e92..5ac17bc5b 100644
--- a/public/components/common/DropDown.tsx
+++ b/public/components/common/DropDown.tsx
@@ -17,6 +17,7 @@ export interface DropDownProps {
placeholder?: string;
searchable?: boolean;
inline?: boolean;
+ highlightSelected?: boolean;
header?: string;
direction?: "left" | "right";
onChange?: (item: DropDownItem) => void;
@@ -33,7 +34,8 @@ export class DropDown extends React.Component<DropDownProps, DropDownState> {
private mounted = false;
public static defaultProps: Partial<DropDownProps> = {
- direction: "right"
+ direction: "right",
+ highlightSelected: true
};
constructor(props: DropDownProps) {
@@ -105,7 +107,7 @@ export class DropDown extends React.Component<DropDownProps, DropDownState> {
public renderItem = (item: DropDownItem) => {
const { label, value } = item;
- const isSelected = this.state.selected && value === this.state.selected.value;
+ const isSelected = this.props.highlightSelected && this.state.selected && value === this.state.selected.value;
const className = classSet({
"c-dropdown-item": true,
"is-selected": isSelected
diff --git a/public/pages/Home/components/TagsFilter.scss b/public/pages/Home/components/TagsFilter.scss
index 4503ee28b..c106675a1 100644
--- a/public/pages/Home/components/TagsFilter.scss
+++ b/public/pages/Home/components/TagsFilter.scss
@@ -6,8 +6,4 @@
cursor: pointer;
border-bottom: 1px dashed $gray-darker;
}
- &.c-dropdown .c-dropdown-menu .c-dropdown-item.is-selected {
- font-weight: normal;
- background-color: transparent;
- }
}
\ No newline at end of file
diff --git a/public/pages/Home/components/TagsFilter.tsx b/public/pages/Home/components/TagsFilter.tsx
index 7337f22e7..84b196cb0 100644
--- a/public/pages/Home/components/TagsFilter.tsx
+++ b/public/pages/Home/components/TagsFilter.tsx
@@ -70,6 +70,7 @@ export class TagsFilter extends React.Component<TagsFilterProps, TagsFilterState
<DropDown
className="l-tags-filter"
inline={true}
+ highlightSelected={false}
items={items}
renderText={this.renderText}
onChange={this.onChange}
diff --git a/public/pages/ShowPost/components/ShowComment.tsx b/public/pages/ShowPost/components/ShowComment.tsx
index b56332b97..ffc630a48 100644
--- a/public/pages/ShowPost/components/ShowComment.tsx
+++ b/public/pages/ShowPost/components/ShowComment.tsx
@@ -9,9 +9,10 @@ import {
Button,
MultiLineText,
DropDown,
- DropDownItem
+ DropDownItem,
+ Modal
} from "@fider/components";
-import { formatDate, Failure, actions, Fider } from "@fider/services";
+import { formatDate, Failure, actions, Fider, navigator } from "@fider/services";
interface ShowCommentProps {
post: Post;
@@ -23,6 +24,7 @@ interface ShowCommentState {
isEditing: boolean;
newContent: string;
error?: Failure;
+ showDeleteConfirmation: boolean;
}
export class ShowComment extends React.Component<ShowCommentProps, ShowCommentState> {
@@ -31,7 +33,8 @@ export class ShowComment extends React.Component<ShowCommentProps, ShowCommentSt
this.state = {
comment: props.comment,
isEditing: false,
- newContent: ""
+ newContent: "",
+ showDeleteConfirmation: false
};
}
@@ -73,12 +76,47 @@ export class ShowComment extends React.Component<ShowCommentProps, ShowCommentSt
return <i className="ellipsis horizontal icon" />;
};
+ private closeModal = async () => {
+ this.setState({ showDeleteConfirmation: false });
+ };
+
+ private deleteComment = async () => {
+ const response = await actions.deleteComment(this.props.post.number, this.props.comment.id);
+ if (response.ok) {
+ location.reload();
+ }
+ };
+
private onActionSelected = (item: DropDownItem) => {
if (item.value === "edit") {
this.setState({ isEditing: true, newContent: this.state.comment.content, error: undefined });
+ } else if (item.value === "delete") {
+ this.setState({ showDeleteConfirmation: true });
}
};
+ private modal() {
+ return (
+ <Modal.Window isOpen={this.state.showDeleteConfirmation} center={false} size="small">
+ <Modal.Header>Delete Comment</Modal.Header>
+ <Modal.Content>
+ <p>
+ This process is irreversible. <strong>Are you sure?</strong>
+ </p>
+ </Modal.Content>
+
+ <Modal.Footer>
+ <Button color="danger" onClick={this.deleteComment}>
+ Delete
+ </Button>
+ <Button color="cancel" onClick={this.closeModal}>
+ Cancel
+ </Button>
+ </Modal.Footer>
+ </Modal.Window>
+ );
+ }
+
public render() {
const c = this.state.comment;
@@ -93,6 +131,7 @@ export class ShowComment extends React.Component<ShowCommentProps, ShowCommentSt
return (
<div className="c-comment">
+ {this.modal()}
<Gravatar user={c.user} />
<div className="c-comment-content">
<UserName user={c.user} />
@@ -105,7 +144,11 @@ export class ShowComment extends React.Component<ShowCommentProps, ShowCommentSt
<DropDown
className="l-more-actions"
direction="left"
- items={[{ label: "Edit", value: "edit" }]}
+ highlightSelected={false}
+ items={[
+ { label: "Edit", value: "edit" },
+ { label: "Delete", value: "delete", render: <span style={{ color: "red" }}>Delete</span> }
+ ]}
onChange={this.onActionSelected}
renderText={this.renderEllipsis}
/>
diff --git a/public/services/actions/post.ts b/public/services/actions/post.ts
index a9e5d8e9c..d4f16203b 100644
--- a/public/services/actions/post.ts
+++ b/public/services/actions/post.ts
@@ -57,6 +57,10 @@ export const updateComment = async (postNumber: number, commentID: number, conte
.then(http.event("comment", "update"));
};
+export const deleteComment = async (postNumber: number, commentID: number): Promise<Result> => {
+ return http.delete(`/api/v1/posts/${postNumber}/comments/${commentID}`).then(http.event("comment", "delete"));
+};
+
interface SetResponseInput {
status: string;
text: string;