Open platform to collect and prioritize feedback
enhancement: notify subscribers about posts being deleted (#625)
Guilherme Oenning0ae8d1a5fa1d
diff --git a/app/handlers/apiv1/post.go b/app/handlers/apiv1/post.goindex 5963294da..8cfa1085a 100644--- a/app/handlers/apiv1/post.go+++ b/app/handlers/apiv1/post.go@@ -54,7 +54,7 @@ func CreatePost() web.HandlerFunc {// GetPost retrieves the existing post by numberfunc GetPost() web.HandlerFunc {- return func(c web.Context) error {+ return func(c web.Context) error {number, err := c.ParamAsInt("number")if err != nil {return c.NotFound()@@ -128,6 +128,11 @@ func DeletePost() web.HandlerFunc {return c.Failure(err)}+ if input.Model.Text != "" {+ // Only send notification if user wrote a comment.+ c.Enqueue(tasks.NotifyAboutDeletedPost(input.Post))+ }+return c.Ok(web.Map{})}}diff --git a/app/storage/inmemory/post.go b/app/storage/inmemory/post.goindex aab66757a..6016b11db 100644--- a/app/storage/inmemory/post.go+++ b/app/storage/inmemory/post.go@@ -61,7 +61,7 @@ func (s *PostStorage) Update(post *models.Post, title, description string) (*mod// GetByNumber returns post by tenant and numberfunc (s *PostStorage) GetByNumber(number int) (*models.Post, error) {for _, post := range s.posts {- if post.Number == number {+ if post.Number == number && post.Status != models.PostDeleted {return post, nil}}@@ -71,7 +71,7 @@ func (s *PostStorage) GetByNumber(number int) (*models.Post, error) {// GetBySlug returns post by tenant and slugfunc (s *PostStorage) GetBySlug(slug string) (*models.Post, error) {for _, post := range s.posts {- if post.Slug == slug {+ if post.Slug == slug && post.Status != models.PostDeleted {return post, nil}}@@ -189,17 +189,13 @@ func (s *PostStorage) RemoveVote(post *models.Post, user *models.User) error {// SetResponse changes current post responsefunc (s *PostStorage) SetResponse(post *models.Post, text string, status models.PostStatus) error {- for i, storedPost := range s.posts {+ for _, storedPost := range s.posts {if storedPost.Number == post.Number {- if status == models.PostDeleted {- s.posts = append(s.posts[:i], s.posts[i+1:]...)- } else {- storedPost.Status = status- storedPost.Response = &models.PostResponse{- Text: text,- User: s.user,- RespondedAt: time.Now(),- }+ storedPost.Status = status+ storedPost.Response = &models.PostResponse{+ Text: text,+ User: s.user,+ RespondedAt: time.Now(),}}}@@ -257,10 +253,17 @@ func (s *PostStorage) RemoveSubscriber(post *models.Post, user *models.User) err// GetActiveSubscribers based on input and settingsfunc (s *PostStorage) GetActiveSubscribers(number int, channel models.NotificationChannel, event models.NotificationEvent) ([]*models.User, error) {- post, err := s.GetByNumber(number)- if err != nil {- return nil, err+ var post *models.Post+ for _, p := range s.posts {+ if p.Number == number {+ post = p+ }}++ if post == nil {+ return nil, app.ErrNotFound+ }+subscribers, ok := s.postSubscribers[post.ID]if ok {users := make([]*models.User, len(subscribers))diff --git a/app/storage/postgres/post.go b/app/storage/postgres/post.goindex 66f267b45..7e66def52 100644--- a/app/storage/postgres/post.go+++ b/app/storage/postgres/post.go@@ -549,12 +549,10 @@ func (s *PostStorage) RemoveSubscriber(post *models.Post, user *models.User) err// GetActiveSubscribers based on input and settingsfunc (s *PostStorage) GetActiveSubscribers(number int, channel models.NotificationChannel, event models.NotificationEvent) ([]*models.User, error) {- post, err := s.GetByNumber(number)- if err != nil {- return make([]*models.User, 0), err- }-- var users []*dbUser+ var (+ users []*dbUser+ err error+ )if len(event.RequiresSubscriptionUserRoles) == 0 {err = s.trx.Select(&users, `@@ -583,8 +581,11 @@ func (s *PostStorage) GetActiveSubscribers(number int, channel models.NotificatiFROM users uLEFT JOIN post_subscribers subON sub.user_id = u.id- AND sub.post_id = $1AND sub.tenant_id = u.tenant_id+ LEFT JOIN posts p+ ON p.id = sub.post_id+ AND p.tenant_id = u.tenant_id+ AND p.number = $1LEFT JOIN user_settings setON set.user_id = u.idAND set.key = $3@@ -597,7 +598,7 @@ func (s *PostStorage) GetActiveSubscribers(number int, channel models.NotificatiOR CAST(set.value AS integer) & $6 > 0)ORDER by u.id`,- post.ID,+ number,models.SubscriberActive,event.UserSettingsKeyName,s.tenant.ID,diff --git a/app/storage/postgres/subscription_test.go b/app/storage/postgres/subscription_test.goindex c08d14fe7..09f9cbc86 100644--- a/app/storage/postgres/subscription_test.go+++ b/app/storage/postgres/subscription_test.go@@ -288,3 +288,28 @@ func TestSubscription_DisabledEverything(t *testing.T) {Expect(err).IsNil()Expect(subscribers).HasLen(0)}++func TestSubscription_DeletedPost(t *testing.T) {+ SetupDatabaseTest(t)+ defer TeardownDatabaseTest()++ posts.SetCurrentTenant(demoTenant)+ posts.SetCurrentUser(aryaStark)++ post1, _ := posts.Add("Post #1", "Description #1")+ posts.SetResponse(post1, "Invalid Post!", models.PostDeleted)++ subscribers, err := posts.GetActiveSubscribers(post1.Number, models.NotificationChannelWeb, models.NotificationEventNewComment)+ Expect(err).IsNil()+ Expect(subscribers).HasLen(2)++ users.SetCurrentUser(jonSnow)+ subscribed, err := users.HasSubscribedTo(post1.ID)+ Expect(err).IsNil()+ Expect(subscribed).IsTrue()++ users.SetCurrentUser(aryaStark)+ subscribed, err = users.HasSubscribedTo(post1.ID)+ Expect(err).IsNil()+ Expect(subscribed).IsTrue()+}diff --git a/app/tasks/tasks.go b/app/tasks/tasks.goindex f50e32c4c..d8f8cbd00 100644--- a/app/tasks/tasks.go+++ b/app/tasks/tasks.go@@ -220,6 +220,49 @@ func NotifyAboutStatusChange(post *models.Post, prevStatus models.PostStatus) wo})}+//NotifyAboutDeletedPost sends a notification (web and email) to subscribers of the post that has been deleted+func NotifyAboutDeletedPost(post *models.Post) worker.Task {+ return describe("Notify about deleted post", func(c *worker.Context) error {++ // Web notification+ users, err := c.Services().Posts.GetActiveSubscribers(post.Number, models.NotificationChannelWeb, models.NotificationEventChangeStatus)+ if err != nil {+ return c.Failure(err)+ }++ title := fmt.Sprintf("**%s** deleted **%s**", c.User().Name, post.Title)+ for _, user := range users {+ if user.ID != c.User().ID {+ if _, err = c.Services().Notifications.Insert(user, title, "", post.ID); err != nil {+ return c.Failure(err)+ }+ }+ }++ // Email notification+ users, err = c.Services().Posts.GetActiveSubscribers(post.Number, models.NotificationChannelEmail, models.NotificationEventChangeStatus)+ if err != nil {+ return c.Failure(err)+ }++ to := make([]email.Recipient, 0)+ for _, user := range users {+ if user.ID != c.User().ID {+ to = append(to, email.NewRecipient(user.Name, user.Email, email.Params{}))+ }+ }++ params := email.Params{+ "title": post.Title,+ "tenantName": c.Tenant().Name,+ "content": markdown.Parse(post.Response.Text),+ "change": linkWithText("change your notification settings", c.BaseURL(), "/settings"),+ }++ return c.Services().Emailer.BatchSend(c, "delete_post", params, c.User().Name, to)+ })+}+//SendInvites sends one email to each invited recipientfunc SendInvites(subject, message string, invitations []*models.UserInvitation) worker.Task {return describe("Send invites", func(c *worker.Context) error {diff --git a/app/tasks/tasks_test.go b/app/tasks/tasks_test.goindex 69d25fb8a..ccd4cf32d 100644--- a/app/tasks/tasks_test.go+++ b/app/tasks/tasks_test.go@@ -262,6 +262,52 @@ func TestNotifyAboutStatusChangeTask(t *testing.T) {Expect(notifications[0].Title).Equals("**Jon Snow** changed status of **Add support for TypeScript** to **planned**")}+func TestNotifyAboutDeletePostTask(t *testing.T) {+ RegisterT(t)++ worker, services := mock.NewWorker()+ services.SetCurrentUser(mock.AryaStark)+ post, _ := services.Posts.Add("Add support for TypeScript", "TypeScript is great, please add support for it")+ services.Posts.SetResponse(post, "Invalid post!", models.PostDeleted)++ emailer := services.Emailer.(*noop.Sender)+ task := tasks.NotifyAboutDeletedPost(post)++ err := worker.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ WithBaseURL("http://domain.com").+ Execute(task)++ Expect(err).IsNil()+ Expect(emailer.Requests).HasLen(1)+ Expect(emailer.Requests[0].TemplateName).Equals("delete_post")+ Expect(emailer.Requests[0].Context.Tenant()).Equals(mock.DemoTenant)+ Expect(emailer.Requests[0].Params).Equals(email.Params{+ "title": "Add support for TypeScript",+ "tenantName": "Demonstration",+ "content": template.HTML("<p>Invalid post!</p>"),+ "change": template.HTML("<a href='http://domain.com/settings'>change your notification settings</a>"),+ })+ Expect(emailer.Requests[0].From).Equals("Jon Snow")+ Expect(emailer.Requests[0].To).HasLen(1)+ Expect(emailer.Requests[0].To[0]).Equals(email.Recipient{+ Name: "Arya Stark",+ Address: "[email protected]",+ Params: email.Params{},+ })++ services.SetCurrentUser(mock.AryaStark)+ notifications, err := services.Notifications.GetActiveNotifications()+ Expect(err).IsNil()+ Expect(notifications).HasLen(1)+ Expect(notifications[0].ID).Equals(1)+ Expect(notifications[0].CreatedAt).TemporarilySimilar(time.Now(), 5*time.Second)+ Expect(notifications[0].Link).Equals("")+ Expect(notifications[0].Read).IsFalse()+ Expect(notifications[0].Title).Equals("**Jon Snow** deleted **Add support for TypeScript**")+}+func TestNotifyAboutStatusChangeTask_Duplicate(t *testing.T) {RegisterT(t)diff --git a/migrations/201811071547_increase_link_size.sql b/migrations/201811071547_increase_link_size.sqlnew file mode 100644index 000000000..05e81e22b--- /dev/null+++ b/migrations/201811071547_increase_link_size.sql@@ -0,0 +1 @@+ALTER TABLE notifications ALTER COLUMN title TYPE VARCHAR(400);diff --git a/public/pages/Home/components/PostInput.tsx b/public/pages/Home/components/PostInput.tsxindex 16257d1d9..ff6051852 100644--- a/public/pages/Home/components/PostInput.tsx+++ b/public/pages/Home/components/PostInput.tsx@@ -1,7 +1,7 @@import React from "react";import { Button, ButtonClickEvent, Input, Form, TextArea } from "@fider/components";import { SignInModal } from "@fider/components";-import { cache, actions, Failure, Fider } from "@fider/services";+import { cache, actions, Failure, Fider, device } from "@fider/services";interface PostInputProps {placeholder: string;@@ -37,7 +37,7 @@ export class PostInput extends React.Component<PostInputProps, PostInputState> {}public componentDidMount() {- if (Fider.session.isAuthenticated && this.title) {+ if (Fider.session.isAuthenticated && this.title && !device.isTouch()) {this.title.focus();}}diff --git a/views/templates/delete_post.tpl b/views/templates/delete_post.tplnew file mode 100644index 000000000..01e39b9e6--- /dev/null+++ b/views/templates/delete_post.tpl@@ -0,0 +1,24 @@+subject: [{{ .tenantName }}] {{ .title }}+body:+<tr>+ <td>+ <strong>{{ .title }}</strong> has been <strong>deleted</strong>.+ </td>+</tr>+<tr>+ <td></td>+ <td height="10" style="line-height:1px;"> </td>+ <td></td>+</tr>+<tr>+ <td style="border-top:1px solid #efefef;">{{ .content }}</td>+</tr>+<tr>+ <td>+ <span style="color:#666;font-size:11px">+ — <br />+ You are receiving this because you are subscribed to this thread. <br />+ {{ .change }}.+ </span>+ </td>+</tr>\ No newline at end of file