Open platform to collect and prioritize feedback
feature: implement web notifications (#271)
Guilherme Oenning9dcb5ca21349
diff --git a/app/handlers/notification.go b/app/handlers/notification.gonew file mode 100644index 000000000..970f53d09--- /dev/null+++ b/app/handlers/notification.go@@ -0,0 +1,67 @@+package handlers++import (+ "net/http"++ "github.com/getfider/fider/app/pkg/web"+)++// TotalUnreadNotifications returns the total number of unread notifications+func TotalUnreadNotifications() web.HandlerFunc {+ return func(c web.Context) error {+ total, err := c.Services().Notifications.TotalUnread()+ if err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{+ "total": total,+ })+ }+}++// Notifications is the home for unread and recent notifications+func Notifications() web.HandlerFunc {+ return func(c web.Context) error {+ notifications, err := c.Services().Notifications.GetActiveNotifications()+ if err != nil {+ return c.Failure(err)+ }++ return c.Page(web.Map{+ "notifications": notifications,+ })+ }+}++// ReadNotification marks it as read and redirect to its content+func ReadNotification() web.HandlerFunc {+ return func(c web.Context) error {+ id, err := c.ParamAsInt("id")+ if err != nil {+ return c.Failure(err)+ }++ notification, err := c.Services().Notifications.GetNotification(id)+ if err != nil {+ return c.Failure(err)+ }++ if err = c.Services().Notifications.MarkAsRead(notification.ID); err != nil {+ return c.Failure(err)+ }++ return c.Redirect(http.StatusTemporaryRedirect, c.BaseURL()+notification.Link)+ }+}++// ReadAllNotifications marks all unread notifications as read+func ReadAllNotifications() web.HandlerFunc {+ return func(c web.Context) error {+ if err := c.Services().Notifications.MarkAllAsRead(); err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{})+ }+}diff --git a/app/handlers/notification_test.go b/app/handlers/notification_test.gonew file mode 100644index 000000000..27b1fd91f--- /dev/null+++ b/app/handlers/notification_test.go@@ -0,0 +1,81 @@+package handlers_test++import (+ "net/http"+ "testing"++ "github.com/getfider/fider/app/handlers"+ "github.com/getfider/fider/app/pkg/mock"+ . "github.com/onsi/gomega"+)++func TestTotalUnreadNotificationsHandler(t *testing.T) {+ RegisterTestingT(t)++ server, services := mock.NewServer()+ services.SetCurrentUser(mock.JonSnow)+ services.Notifications.Insert(mock.JonSnow, "Title", "http://example.com", 1, mock.AryaStark.ID)++ code, query := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ ExecuteAsJSON(handlers.TotalUnreadNotifications())++ Expect(code).To(Equal(http.StatusOK))+ Expect(query.Int32("total")).To(Equal(1))+}++func TestNotificationsHandler(t *testing.T) {+ RegisterTestingT(t)++ server, services := mock.NewServer()+ services.SetCurrentUser(mock.JonSnow)+ services.Notifications.Insert(mock.JonSnow, "Title", "http://example.com", 1, mock.AryaStark.ID)+ services.Notifications.Insert(mock.JonSnow, "Title 2", "http://example.com", 1, mock.AryaStark.ID)++ code, _ := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ ExecuteAsJSON(handlers.Notifications())++ Expect(code).To(Equal(http.StatusOK))+}++func TestReadNotificationHandler(t *testing.T) {+ RegisterTestingT(t)++ server, services := mock.NewServer()+ services.SetCurrentUser(mock.JonSnow)+ not1, _ := services.Notifications.Insert(mock.JonSnow, "Title", "/abc", 1, mock.AryaStark.ID)+ not2, _ := services.Notifications.Insert(mock.JonSnow, "Title 2", "/def", 1, mock.AryaStark.ID)++ code, resp := server.+ OnTenant(mock.DemoTenant).+ WithURL("http://example.com").+ AsUser(mock.JonSnow).+ AddParam("id", not2.ID).+ Execute(handlers.ReadNotification())++ Expect(code).To(Equal(http.StatusTemporaryRedirect))+ Expect(resp.Header().Get("Location")).To(Equal("http://example.com/def"))+ Expect(not1.Read).To(BeFalse())+ Expect(not2.Read).To(BeTrue())+}++func TestReadAllNotificationsHandler(t *testing.T) {+ RegisterTestingT(t)++ server, services := mock.NewServer()+ services.SetCurrentUser(mock.JonSnow)+ not1, _ := services.Notifications.Insert(mock.JonSnow, "Title", "/abc", 1, mock.AryaStark.ID)+ not2, _ := services.Notifications.Insert(mock.JonSnow, "Title 2", "/def", 1, mock.AryaStark.ID)++ code, _ := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ Execute(handlers.ReadAllNotifications())++ Expect(code).To(Equal(http.StatusOK))+ Expect(not1.Read).To(BeTrue())+ Expect(not2.Read).To(BeTrue())+}diff --git a/app/middlewares/setup.go b/app/middlewares/setup.goindex 3e2f4908f..622841323 100644--- a/app/middlewares/setup.go+++ b/app/middlewares/setup.go@@ -36,11 +36,12 @@ func WorkerSetup(logger log.Logger) worker.MiddlewareFunc {}c.SetServices(&app.Services{- Tenants: postgres.NewTenantStorage(trx),- Users: postgres.NewUserStorage(trx),- Ideas: postgres.NewIdeaStorage(trx),- Tags: postgres.NewTagStorage(trx),- Emailer: emailer,+ Tenants: postgres.NewTenantStorage(trx),+ Users: postgres.NewUserStorage(trx),+ Ideas: postgres.NewIdeaStorage(trx),+ Tags: postgres.NewTagStorage(trx),+ Notifications: postgres.NewNotificationStorage(trx),+ Emailer: emailer,})defer func() {@@ -85,12 +86,13 @@ func WebSetup(logger log.Logger) web.MiddlewareFunc {c.SetActiveTransaction(trx)c.SetServices(&app.Services{- Tenants: postgres.NewTenantStorage(trx),- OAuth: &oauth.HTTPService{},- Users: postgres.NewUserStorage(trx),- Ideas: postgres.NewIdeaStorage(trx),- Tags: postgres.NewTagStorage(trx),- Emailer: emailer,+ Tenants: postgres.NewTenantStorage(trx),+ OAuth: &oauth.HTTPService{},+ Users: postgres.NewUserStorage(trx),+ Ideas: postgres.NewIdeaStorage(trx),+ Tags: postgres.NewTagStorage(trx),+ Notifications: postgres.NewNotificationStorage(trx),+ Emailer: emailer,})defer func() {diff --git a/app/models/infra.go b/app/models/infra.goindex 47fa7c2e7..724c4a20b 100644--- a/app/models/infra.go+++ b/app/models/infra.go@@ -1,5 +1,9 @@package models+import (+ "time"+)+// SystemSettings is the system-wide settingstype SystemSettings struct {Mode string `json:"mode"`@@ -10,3 +14,12 @@ type SystemSettings struct {Compiler string `json:"compiler"`Domain string `json:"domain"`}++// Notification is the system generated notification entity+type Notification struct {+ ID int `json:"id" db:"id"`+ Title string `json:"title" db:"title"`+ Link string `json:"link" db:"link"`+ Read bool `json:"read" db:"read"`+ CreatedOn time.Time `json:"createdOn" db:"created_on"`+}diff --git a/app/pkg/jsonq/jsonq.go b/app/pkg/jsonq/jsonq.goindex 799a27300..8f8e1a217 100644--- a/app/pkg/jsonq/jsonq.go+++ b/app/pkg/jsonq/jsonq.go@@ -37,6 +37,17 @@ func (q *Query) String(key string) (string, error) {return "", nil}+//Int32 returns a integer value from the json object based on its key+func (q *Query) Int32(key string) (int, error) {+ data := q.get(key)+ if data != nil {+ var num int+ err := json.Unmarshal(*data, &num)+ return num, err+ }+ return 0, nil+}+//IsArray returns true if the json object is an arrayfunc (q *Query) IsArray() bool {return q.m == nildiff --git a/app/pkg/jsonq/jsonq_test.go b/app/pkg/jsonq/jsonq_test.goindex dbc1f0dbe..6848059a0 100644--- a/app/pkg/jsonq/jsonq_test.go+++ b/app/pkg/jsonq/jsonq_test.go@@ -7,11 +7,12 @@ import (. "github.com/onsi/gomega")-func TestGetString(t *testing.T) {+func TestGet(t *testing.T) {RegisterTestingT(t)- query := jsonq.New(`{ "name": "Jon Snow" }`)+ query := jsonq.New(`{ "name": "Jon Snow", "age": 23 }`)Expect(query.String("name")).To(Equal("Jon Snow"))+ Expect(query.Int32("age")).To(Equal(23))}func TestGetStringNested(t *testing.T) {diff --git a/app/pkg/mock/setup.go b/app/pkg/mock/setup.goindex 34ebb97a5..a21a7cb19 100644--- a/app/pkg/mock/setup.go+++ b/app/pkg/mock/setup.go@@ -47,12 +47,13 @@ func NewWorker() (*Worker, *app.Services) {func createServices(seed bool) *app.Services {services := &app.Services{- Tenants: &inmemory.TenantStorage{},- Users: &inmemory.UserStorage{},- Tags: inmemory.NewTagStorage(),- Ideas: inmemory.NewIdeaStorage(),- OAuth: &OAuthService{},- Emailer: email.NewNoopSender(),+ Tenants: &inmemory.TenantStorage{},+ Users: &inmemory.UserStorage{},+ Tags: inmemory.NewTagStorage(),+ Notifications: inmemory.NewNotificationStorage(),+ Ideas: inmemory.NewIdeaStorage(),+ OAuth: &OAuthService{},+ Emailer: email.NewNoopSender(),}if seed {diff --git a/app/services.go b/app/services.goindex cbb9f80c9..4d622ace0 100644--- a/app/services.go+++ b/app/services.go@@ -13,12 +13,13 @@ import (// Services holds reference to all Fider servicestype Services struct {- OAuth oauth.Service- Users storage.User- Tags storage.Tag- Tenants storage.Tenant- Ideas storage.Idea- Emailer email.Sender+ OAuth oauth.Service+ Users storage.User+ Tags storage.Tag+ Tenants storage.Tenant+ Notifications storage.Notification+ Ideas storage.Idea+ Emailer email.Sender}// SetCurrentTenant to current context@@ -27,6 +28,7 @@ func (s *Services) SetCurrentTenant(tenant *models.Tenant) {s.Tags.SetCurrentTenant(tenant)s.Tenants.SetCurrentTenant(tenant)s.Ideas.SetCurrentTenant(tenant)+ s.Notifications.SetCurrentTenant(tenant)}// SetCurrentUser to current context@@ -35,6 +37,7 @@ func (s *Services) SetCurrentUser(user *models.User) {s.Tags.SetCurrentUser(user)s.Tenants.SetCurrentUser(user)s.Ideas.SetCurrentUser(user)+ s.Notifications.SetCurrentUser(user)}//NewEmailer creates a new emailer based on system configurationdiff --git a/app/storage/inmemory/notifications.go b/app/storage/inmemory/notifications.gonew file mode 100644index 000000000..b1ca7a02e--- /dev/null+++ b/app/storage/inmemory/notifications.go@@ -0,0 +1,114 @@+package inmemory++import (+ "time"++ "github.com/getfider/fider/app"+ "github.com/getfider/fider/app/models"+)++// NotificationStorage contains read and write operations for notifications+type NotificationStorage struct {+ lastID int+ tenant *models.Tenant+ user *models.User+ notifications map[*models.User][]*models.Notification+}++// NewNotificationStorage creates a new NotificationStorage+func NewNotificationStorage() *NotificationStorage {+ return &NotificationStorage{+ lastID: 0,+ notifications: make(map[*models.User][]*models.Notification, 0),+ }+}++// SetCurrentTenant to current context+func (s *NotificationStorage) SetCurrentTenant(tenant *models.Tenant) {+ s.tenant = tenant+}++// SetCurrentUser to current context+func (s *NotificationStorage) SetCurrentUser(user *models.User) {+ s.user = user+}++// Insert notification for given user+func (s *NotificationStorage) Insert(user *models.User, title, link string, ideaID, authorID int) (*models.Notification, error) {+ s.lastID = s.lastID + 1+ newNotification := &models.Notification{+ ID: s.lastID,+ Title: title,+ Link: link,+ Read: false,+ CreatedOn: time.Now(),+ }+ all, ok := s.notifications[s.user]+ if !ok {+ all = make([]*models.Notification, 0)+ }+ s.notifications[s.user] = append(all, newNotification)+ return newNotification, nil+}++// TotalUnread returns the number of unread notifications for current user+func (s *NotificationStorage) TotalUnread() (int, error) {+ all, ok := s.notifications[s.user]+ if !ok {+ return 0, nil+ }+ return len(all), nil+}++// MarkAsRead given id of current user+func (s *NotificationStorage) MarkAsRead(id int) error {+ all, ok := s.notifications[s.user]+ if !ok {+ return nil+ }++ for _, notification := range all {+ if notification.ID == id {+ notification.Read = true+ }+ }+ return nil+}++// MarkAllAsRead of current user+func (s *NotificationStorage) MarkAllAsRead() error {+ all, ok := s.notifications[s.user]+ if !ok {+ return nil+ }++ for _, notification := range all {+ notification.Read = true+ }++ return nil+}++// GetActiveNotifications returns all unread notifications and last 30 days of read notifications+func (s *NotificationStorage) GetActiveNotifications() ([]*models.Notification, error) {+ all, ok := s.notifications[s.user]+ if !ok {+ return make([]*models.Notification, 0), nil+ }+ return all, nil+}++// GetNotification returns notification by id+func (s *NotificationStorage) GetNotification(id int) (*models.Notification, error) {+ all, ok := s.notifications[s.user]+ if !ok {+ return nil, app.ErrNotFound+ }++ for _, notification := range all {+ if notification.ID == id {+ return notification, nil+ }+ }+ return nil, app.ErrNotFound+}diff --git a/app/storage/postgres/notifications.go b/app/storage/postgres/notifications.gonew file mode 100644index 000000000..e6018a467--- /dev/null+++ b/app/storage/postgres/notifications.go@@ -0,0 +1,119 @@+package postgres++import (+ "time"++ "github.com/getfider/fider/app/models"+ "github.com/getfider/fider/app/pkg/dbx"+)++// NotificationStorage contains read and write operations for notifications+type NotificationStorage struct {+ trx *dbx.Trx+ tenant *models.Tenant+ user *models.User+}++// NewNotificationStorage creates a new NotificationStorage+func NewNotificationStorage(trx *dbx.Trx) *NotificationStorage {+ return &NotificationStorage{+ trx: trx,+ }+}++// SetCurrentTenant to current context+func (s *NotificationStorage) SetCurrentTenant(tenant *models.Tenant) {+ s.tenant = tenant+}++// SetCurrentUser to current context+func (s *NotificationStorage) SetCurrentUser(user *models.User) {+ s.user = user+}++// Insert notification for given user+func (s *NotificationStorage) Insert(user *models.User, title, link string, ideaID, authorID int) (*models.Notification, error) {+ if user.ID == authorID {+ return nil, nil+ }++ now := time.Now()+ notification := &models.Notification{+ Title: title,+ Link: link,+ CreatedOn: now,+ Read: false,+ }+ err := s.trx.Get(¬ification.ID, `+ INSERT INTO notifications (tenant_id, user_id, title, link, read, idea_id, author_id, created_on, updated_on)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $8)+ RETURNING id+ `, s.tenant.ID, user.ID, title, link, false, ideaID, authorID, now)+ if err != nil {+ return nil, err+ }+ return notification, nil+}++// TotalUnread returns the number of unread notifications for current user+func (s *NotificationStorage) TotalUnread() (int, error) {+ total := 0+ if s.user != nil {+ err := s.trx.Scalar(&total, "SELECT COUNT(*) FROM notifications WHERE tenant_id = $1 AND user_id = $2 AND read = false", s.tenant.ID, s.user.ID)+ if err != nil {+ return 0, err+ }+ }+ return total, nil+}++// MarkAsRead given id of current user+func (s *NotificationStorage) MarkAsRead(id int) error {+ if s.user == nil {+ return nil+ }+ return s.trx.Execute(`+ UPDATE notifications SET read = true, updated_on = $1+ WHERE id = $2 AND tenant_id = $3 AND user_id = $4 AND read = false+ `, time.Now(), id, s.tenant.ID, s.user.ID)+}++// MarkAllAsRead of current user+func (s *NotificationStorage) MarkAllAsRead() error {+ if s.user == nil {+ return nil+ }+ return s.trx.Execute(`+ UPDATE notifications SET read = true, updated_on = $1+ WHERE tenant_id = $2 AND user_id = $3 AND read = false+ `, time.Now(), s.tenant.ID, s.user.ID)+}++// GetActiveNotifications returns all unread notifications and last 30 days of read notifications+func (s *NotificationStorage) GetActiveNotifications() ([]*models.Notification, error) {+ notifications := []*models.Notification{}+ err := s.trx.Select(¬ifications, `+ SELECT id, title, link, read, created_on+ FROM notifications+ WHERE tenant_id = $1 AND user_id = $2+ AND (read = false OR updated_on > CURRENT_DATE - INTERVAL '30 days')+ `, s.tenant.ID, s.user.ID)+ if err != nil {+ return nil, err+ }+ return notifications, nil+}++// GetNotification returns notification by id+func (s *NotificationStorage) GetNotification(id int) (*models.Notification, error) {+ notification := &models.Notification{}+ err := s.trx.Get(notification, `+ SELECT id, title, link, read, created_on+ FROM notifications+ WHERE id = $1 AND tenant_id = $2 AND user_id = $3+ `, id, s.tenant.ID, s.user.ID)+ if err != nil {+ return nil, err+ }+ return notification, nil+}diff --git a/app/storage/postgres/notifications_test.go b/app/storage/postgres/notifications_test.gonew file mode 100644index 000000000..1ff6b0f0a--- /dev/null+++ b/app/storage/postgres/notifications_test.go@@ -0,0 +1,134 @@+package postgres_test++import (+ "testing"+ "time"++ "github.com/getfider/fider/app"++ . "github.com/onsi/gomega"+)++func TestNotificationStorage_TotalCount(t *testing.T) {+ SetupDatabaseTest(t)+ defer TeardownDatabaseTest()++ notifications.SetCurrentTenant(demoTenant)++ notifications.SetCurrentUser(jonSnow)+ Expect(notifications.TotalUnread()).To(Equal(0))++ notifications.SetCurrentUser(nil)+ Expect(notifications.TotalUnread()).To(Equal(0))+}++func TestNotificationStorage_Insert_Read_Count(t *testing.T) {+ SetupDatabaseTest(t)+ defer TeardownDatabaseTest()++ ideas.SetCurrentTenant(demoTenant)+ notifications.SetCurrentTenant(demoTenant)+ idea, _ := ideas.Add("Title", "Description", jonSnow.ID)++ not1, err := notifications.Insert(aryaStark, "Hello World", "http://www.google.com.br", idea.ID, jonSnow.ID)+ Expect(err).To(BeNil())+ not2, err := notifications.Insert(aryaStark, "Another thing happened", "http://www.google.com.br", idea.ID, jonSnow.ID)+ Expect(err).To(BeNil())++ notifications.SetCurrentUser(aryaStark)+ Expect(notifications.TotalUnread()).To(Equal(2))++ Expect(notifications.MarkAsRead(not1.ID)).To(BeNil())+ Expect(notifications.TotalUnread()).To(Equal(1))+ Expect(notifications.MarkAsRead(not2.ID)).To(BeNil())+ Expect(notifications.TotalUnread()).To(Equal(0))+}++func TestNotificationStorage_GetActiveNotifications(t *testing.T) {+ SetupDatabaseTest(t)+ defer TeardownDatabaseTest()++ ideas.SetCurrentTenant(demoTenant)+ idea, _ := ideas.Add("Title", "Description", jonSnow.ID)++ notifications.SetCurrentTenant(demoTenant)+ notifications.SetCurrentUser(aryaStark)++ notifications.Insert(aryaStark, "Hello World", "http://www.google.com.br", idea.ID, jonSnow.ID)+ notifications.Insert(aryaStark, "Another thing happened", "http://www.google.com.br", idea.ID, jonSnow.ID)++ allNotifications, err := notifications.GetActiveNotifications()+ Expect(err).To(BeNil())+ Expect(allNotifications).To(HaveLen(2))++ notifications.MarkAsRead(allNotifications[0].ID)+ notifications.MarkAsRead(allNotifications[1].ID)+ trx.Execute("UPDATE notifications SET updated_on = $1 WHERE id = $2", time.Now().AddDate(0, 0, -31), allNotifications[0].ID)++ allNotifications, err = notifications.GetActiveNotifications()+ Expect(err).To(BeNil())+ Expect(allNotifications).To(HaveLen(1))+ Expect(allNotifications[0].Read).To(BeTrue())+}++func TestNotificationStorage_ReadAll(t *testing.T) {+ SetupDatabaseTest(t)+ defer TeardownDatabaseTest()++ ideas.SetCurrentTenant(demoTenant)+ idea, _ := ideas.Add("Title", "Description", jonSnow.ID)++ notifications.SetCurrentTenant(demoTenant)+ notifications.SetCurrentUser(aryaStark)++ notifications.Insert(aryaStark, "Hello World", "http://www.google.com.br", idea.ID, jonSnow.ID)+ notifications.Insert(aryaStark, "Another thing happened", "http://www.google.com.br", idea.ID, jonSnow.ID)++ allNotifications, err := notifications.GetActiveNotifications()+ Expect(err).To(BeNil())+ Expect(allNotifications).To(HaveLen(2))++ notifications.MarkAllAsRead()++ allNotifications, err = notifications.GetActiveNotifications()+ Expect(err).To(BeNil())+ Expect(allNotifications).To(HaveLen(2))+ Expect(allNotifications[0].Read).To(BeTrue())+ Expect(allNotifications[1].Read).To(BeTrue())+}++func TestNotificationStorage_GetNotificationById(t *testing.T) {+ SetupDatabaseTest(t)+ defer TeardownDatabaseTest()++ ideas.SetCurrentTenant(demoTenant)+ idea, _ := ideas.Add("Title", "Description", jonSnow.ID)++ notifications.SetCurrentTenant(demoTenant)+ notifications.SetCurrentUser(aryaStark)++ not1, err := notifications.Insert(aryaStark, "Hello World", "http://www.google.com.br", idea.ID, jonSnow.ID)+ Expect(err).To(BeNil())+ not1, err = notifications.GetNotification(not1.ID)+ Expect(err).To(BeNil())+ Expect(not1.Title).To(Equal("Hello World"))+ Expect(not1.Link).To(Equal("http://www.google.com.br"))+ Expect(not1.Read).To(BeFalse())+}++func TestNotificationStorage_GetNotificationById_OtherUser(t *testing.T) {+ SetupDatabaseTest(t)+ defer TeardownDatabaseTest()++ ideas.SetCurrentTenant(demoTenant)+ idea, _ := ideas.Add("Title", "Description", jonSnow.ID)++ notifications.SetCurrentTenant(demoTenant)+ not1, err := notifications.Insert(jonSnow, "Hello World", "http://www.google.com.br", idea.ID, aryaStark.ID)+ Expect(err).To(BeNil())++ notifications.SetCurrentUser(aryaStark)+ not1, err = notifications.GetNotification(not1.ID)+ Expect(err).To(Equal(app.ErrNotFound))+ Expect(not1).To(BeNil())+}diff --git a/app/storage/postgres/setup_test.go b/app/storage/postgres/setup_test.goindex 37384b49f..b1d1ef957 100644--- a/app/storage/postgres/setup_test.go+++ b/app/storage/postgres/setup_test.go@@ -17,6 +17,7 @@ var tenants *postgres.TenantStoragevar users *postgres.UserStoragevar ideas *postgres.IdeaStoragevar tags *postgres.TagStorage+var notifications *postgres.NotificationStoragevar demoTenant *models.Tenantvar avengersTenant *models.Tenant@@ -33,6 +34,7 @@ func SetupDatabaseTest(t *testing.T) {users = postgres.NewUserStorage(trx)ideas = postgres.NewIdeaStorage(trx)tags = postgres.NewTagStorage(trx)+ notifications = postgres.NewNotificationStorage(trx)demoTenant, _ = tenants.GetByDomain("demo")avengersTenant, _ = tenants.GetByDomain("avengers")diff --git a/app/storage/storage.go b/app/storage/storage.goindex a5eb43d6d..19cf569cd 100644--- a/app/storage/storage.go+++ b/app/storage/storage.go@@ -79,3 +79,14 @@ type Tag interface {UnassignTag(tagID, ideaID int) errorGetAll() ([]*models.Tag, error)}++// Notification contains read and write operations for notifications+type Notification interface {+ Base+ Insert(user *models.User, title, link string, ideaID, authorID int) (*models.Notification, error)+ MarkAsRead(id int) error+ MarkAllAsRead() error+ TotalUnread() (int, error)+ GetActiveNotifications() ([]*models.Notification, error)+ GetNotification(id int) (*models.Notification, error)+}diff --git a/app/tasks/tasks.go b/app/tasks/tasks.goindex 070dadccd..daec0c3f5 100644--- a/app/tasks/tasks.go+++ b/app/tasks/tasks.go@@ -6,7 +6,6 @@ import ("github.com/getfider/fider/app/models""github.com/getfider/fider/app/pkg/email"- "github.com/getfider/fider/app/pkg/env""github.com/getfider/fider/app/pkg/markdown""github.com/getfider/fider/app/pkg/worker")@@ -65,12 +64,22 @@ func SendChangeEmailConfirmation(model *models.ChangeUserEmail) worker.Task {//NotifyAboutNewIdea sends a notification (web and email) to subscribersfunc NotifyAboutNewIdea(idea *models.Idea) worker.Task {return describe("Notify about new idea", func(c *worker.Context) error {- if env.GetEnvOrDefault("NOTIFICATIONS_ENABLED", "true") == "false" {- c.Logger().Warnf("Notifications is currently disabled.")- return nil+ // Web notification+ users, err := c.Services().Ideas.GetActiveSubscribers(idea.Number, models.NotificationChannelWeb, models.NotificationEventNewIdea)+ if err != nil {+ return err+ }++ title := fmt.Sprintf("New idea: **%s**", idea.Title)+ link := fmt.Sprintf("/ideas/%d/%s", idea.Number, idea.Slug)+ for _, user := range users {+ if _, err = c.Services().Notifications.Insert(user, title, link, idea.ID, c.User().ID); err != nil {+ return err+ }}- users, err := c.Services().Ideas.GetActiveSubscribers(idea.Number, models.NotificationChannelEmail, models.NotificationEventNewIdea)+ // Email notification+ users, err = c.Services().Ideas.GetActiveSubscribers(idea.Number, models.NotificationChannelEmail, models.NotificationEventNewIdea)if err != nil {return err}@@ -96,12 +105,22 @@ func NotifyAboutNewIdea(idea *models.Idea) worker.Task {//NotifyAboutNewComment sends a notification (web and email) to subscribersfunc NotifyAboutNewComment(idea *models.Idea, comment *models.NewComment) worker.Task {return describe("Notify about new comment", func(c *worker.Context) error {- if env.GetEnvOrDefault("NOTIFICATIONS_ENABLED", "true") == "false" {- c.Logger().Warnf("Notifications is currently disabled.")- return nil+ // Web notification+ users, err := c.Services().Ideas.GetActiveSubscribers(idea.Number, models.NotificationChannelWeb, models.NotificationEventNewComment)+ if err != nil {+ return err+ }++ title := fmt.Sprintf("**%s** left a comment on **%s**", c.User().Name, idea.Title)+ link := fmt.Sprintf("/ideas/%d/%s", idea.Number, idea.Slug)+ for _, user := range users {+ if _, err = c.Services().Notifications.Insert(user, title, link, idea.ID, c.User().ID); err != nil {+ return err+ }}- users, err := c.Services().Ideas.GetActiveSubscribers(comment.Number, models.NotificationChannelEmail, models.NotificationEventNewComment)+ // Email notification+ users, err = c.Services().Ideas.GetActiveSubscribers(idea.Number, models.NotificationChannelEmail, models.NotificationEventNewComment)if err != nil {return err}@@ -128,17 +147,27 @@ func NotifyAboutNewComment(idea *models.Idea, comment *models.NewComment) worker//NotifyAboutStatusChange sends a notification (web and email) to subscribersfunc NotifyAboutStatusChange(idea *models.Idea, response *models.SetResponse) worker.Task {return describe("Notify about idea status change", func(c *worker.Context) error {- if env.GetEnvOrDefault("NOTIFICATIONS_ENABLED", "true") == "false" {- c.Logger().Warnf("Notifications is currently disabled.")- return nil- }-//Don't notify if status is the sameif idea.Status == response.Status {return nil}- users, err := c.Services().Ideas.GetActiveSubscribers(response.Number, models.NotificationChannelEmail, models.NotificationEventChangeStatus)+ // Web notification+ users, err := c.Services().Ideas.GetActiveSubscribers(idea.Number, models.NotificationChannelWeb, models.NotificationEventChangeStatus)+ if err != nil {+ return err+ }++ title := fmt.Sprintf("**%s** changed status of **%s** to **%s**", c.User().Name, idea.Title, models.GetIdeaStatusName(response.Status))+ link := fmt.Sprintf("/ideas/%d/%s", idea.Number, idea.Slug)+ for _, user := range users {+ if _, err = c.Services().Notifications.Insert(user, title, link, idea.ID, c.User().ID); err != nil {+ return err+ }+ }++ // Email notification+ users, err = c.Services().Ideas.GetActiveSubscribers(idea.Number, models.NotificationChannelEmail, models.NotificationEventChangeStatus)if err != nil {return err}diff --git a/migrations/201802241348_create_webnotification_tables.up.sql b/migrations/201802241348_create_webnotification_tables.up.sqlnew file mode 100644index 000000000..aa1ec343d--- /dev/null+++ b/migrations/201802241348_create_webnotification_tables.up.sql@@ -0,0 +1,17 @@+create table if not exists notifications (+ id serial not null,+ tenant_id int not null,+ user_id int not null,+ title varchar(160) not null,+ link varchar(2048) null,+ read boolean not null,+ idea_id int not null,+ author_id int not null,+ created_on timestamptz not null default now(),+ updated_on timestamptz not null default now(),+ primary key (id),+ foreign key (tenant_id) references tenants(id),+ foreign key (user_id) references users(id),+ foreign key (author_id) references users(id),+ foreign key (idea_id) references ideas(id)+);\ No newline at end of filediff --git a/public/assets/styles/main.scss b/public/assets/styles/main.scssindex a523e8089..767ed4fa5 100644--- a/public/assets/styles/main.scss+++ b/public/assets/styles/main.scss@@ -36,6 +36,20 @@ body {height: 40px;border-radius: 0px;+ .unread-dot {+ width: 10px;+ height: 10px;+ border-radius: 5px;+ margin-left: -10px;+ margin-top: -25px;+ background-color: #db2828;+ border: 1px solid #fff !important;+ }++ .name.header {+ min-width: 150px;+ }+div, a {color: textColorFor($menu-color);}@@ -190,7 +204,7 @@ code {}.fdr-avatar {- margin-left: 0.5em;+ margin-left: 3px;}span.date {diff --git a/public/components/common/Header.tsx b/public/components/common/Header.tsxindex be0056750..3cc1992d4 100644--- a/public/components/common/Header.tsx+++ b/public/components/common/Header.tsx@@ -1,7 +1,7 @@import * as React from 'react';import { SystemSettings, CurrentUser, Tenant } from '@fider/models';import { SignInControl, EnvironmentInfo, Gravatar } from '@fider/components/common';-import { page } from '@fider/services';+import { page, actions } from '@fider/services';interface HeaderProps {user?: CurrentUser;@@ -9,10 +9,27 @@ interface HeaderProps {tenant: Tenant;}-export class Header extends React.Component<HeaderProps, {}> {+interface HeaderState {+ unreadNotifications: number;+}++export class Header extends React.Component<HeaderProps, HeaderState> {constructor(props: HeaderProps) {super(props);+ this.state = {+ unreadNotifications: 0+ };+ }++ public componentDidMount(): void {+ if (this.props.user) {+ actions.getTotalUnreadNotifications().then((result) => {+ if (result.ok && result.data > 0) {+ this.setState({ unreadNotifications: result.data });+ }+ });+ }}private showModal() {@@ -23,12 +40,16 @@ export class Header extends React.Component<HeaderProps, {}> {public render() {const items = this.props.user && (- <div className="menu">+ <div className="ui vertical menu"><div className="name header"><i className="user icon" />{this.props.user.name}</div><a href="/settings" className="item">Settings</a>+ <a href="/notifications" className="item">+ Notifications+ {this.state.unreadNotifications > 0 && <div className="ui mini circular red label">{this.state.unreadNotifications}</div>}+ </a><div className="divider" />{this.props.user.isCollaborator && [@@ -56,6 +77,7 @@ export class Header extends React.Component<HeaderProps, {}> {</a><div onClick={() => this.showModal()} className={`ui right simple dropdown item signin ${!this.props.user && 'subtitle'}`}>{this.props.user && <Gravatar user={this.props.user} />}+ {this.state.unreadNotifications > 0 && <div className="unread-dot" />}{!this.props.user && 'Sign in'} {this.props.user && <i className="dropdown icon" />}{items}</div>diff --git a/public/models/index.ts b/public/models/index.tsindex 6021329b4..4a0af17e0 100644--- a/public/models/index.ts+++ b/public/models/index.ts@@ -1,3 +1,4 @@export * from './idea';export * from './identity';export * from './settings';+export * from './notification';diff --git a/public/models/notification.ts b/public/models/notification.tsnew file mode 100644index 000000000..b6f15b6bf--- /dev/null+++ b/public/models/notification.ts@@ -0,0 +1,8 @@++export interface Notification {+ id: number;+ title: string;+ link: string;+ read: boolean;+ createdOn: string;+}diff --git a/public/pages/site/UserNotificationsPage/UserNotificationsPage.scss b/public/pages/site/UserNotificationsPage/UserNotificationsPage.scssnew file mode 100644index 000000000..239cd8466--- /dev/null+++ b/public/pages/site/UserNotificationsPage/UserNotificationsPage.scss@@ -0,0 +1,26 @@+@import '~@fider/assets/styles/variables.scss';++#fdr-user-notifications {+ .mark-as-read {+ float: right;+ color: $link-color;+ font-size: 10px;+ cursor: pointer;+ font-weight: normal;++ &:hover {+ text-decoration: underline;+ }+ }+ .ui.list {+ .item {+ a {+ padding: 5px;+ display: inline-block;+ }+ &:hover {+ background-color: #f1f8ff;+ }+ }+ }+}\ No newline at end of filediff --git a/public/pages/site/UserNotificationsPage/UserNotificationsPage.tsx b/public/pages/site/UserNotificationsPage/UserNotificationsPage.tsxnew file mode 100644index 000000000..3d4a3049a--- /dev/null+++ b/public/pages/site/UserNotificationsPage/UserNotificationsPage.tsx@@ -0,0 +1,100 @@+import * as React from 'react';++import { CurrentUser, Notification } from '@fider/models';+import { MultiLineText, Moment } from '@fider/components';+import { page, actions } from '@fider/services';++import './UserNotificationsPage.scss';++interface UserNotificationsPageProps {+ notifications: Notification[];+}++interface UserNotificationsPageState {+ unread: Notification[];+ recent: Notification[];+}++export class UserNotificationsPage extends React.Component<UserNotificationsPageProps, UserNotificationsPageState> {++ constructor(props: UserNotificationsPageProps) {+ super(props);++ const [ unread, recent ] = (this.props.notifications || []).reduce((result, item) => {+ result[item.read ? 1 : 0].push(item);+ return result;+ }, [ [] as Notification[], [] as Notification[] ]);++ this.state = {+ unread,+ recent,+ };+ }++ private items(notifications: Notification[]): JSX.Element[] {+ return notifications.map((n) => {+ return (+ <span key={n.id} className="item">+ <a href={`/notifications/${n.id}`}>+ <MultiLineText text={n.title} style="simple" />+ <span className="info">+ <Moment date={n.createdOn} />+ </span>+ </a>+ </span>+ );+ });+ }++ private async markAllAsRead(): Promise<void> {+ const response = await actions.markAllAsRead();+ if (response.ok) {+ page.refresh();+ }+ }++ public render() {+ return (+ <div className="page ui container">+ <h2 className="ui header">+ <i className="circular id bell icon" />+ <div className="content">+ Notifications+ <div className="sub header">Stay up to date with what's happening</div>+ </div>+ </h2>++ <div className="ui grid">+ <div className="ten wide computer sixteen wide mobile column">+ <h4>+ Unread+ {+ this.state.unread.length > 0 &&+ <span+ className="mark-as-read"+ onClick={() => this.markAllAsRead()}+ >+ Mark All as Read+ </span>+ }+ </h4>+ <div className="ui list">+ {this.state.unread.length > 0 && this.items(this.state.unread)}+ {this.state.unread.length === 0 && <span className="info">No unread notifications.</span>}+ </div>+ {+ this.state.recent.length > 0 &&+ <>+ <h4>Read on last 30 days</h4>+ <div className="ui list">+ {this.items(this.state.recent)}+ </div>+ </>+ }+ </div>+ </div>++ </div>+ );+ }+}diff --git a/public/pages/site/UserNotificationsPage/index.ts b/public/pages/site/UserNotificationsPage/index.tsnew file mode 100644index 000000000..4a590d088--- /dev/null+++ b/public/pages/site/UserNotificationsPage/index.ts@@ -0,0 +1 @@+export * from './UserNotificationsPage';diff --git a/public/pages/site/UserSettingsPage/NotificationSettings.tsx b/public/pages/site/UserSettingsPage/NotificationSettings.tsxindex a73d1ac95..6d3e2c50d 100644--- a/public/pages/site/UserSettingsPage/NotificationSettings.tsx+++ b/public/pages/site/UserSettingsPage/NotificationSettings.tsx@@ -104,11 +104,6 @@ export class NotificationSettings extends React.Component<NotificationSettingsPr{this.icon('event_notification_change_status', EmailChannel)}</p></div>- <div className="ui segment">- <p className="info">- * web notifications are comming soon!- </p>- </div></div></>);diff --git a/public/router.tsx b/public/router.tsxindex 3889526fb..5af23e2e9 100644--- a/public/router.tsx+++ b/public/router.tsx@@ -6,6 +6,7 @@ import { ManageTagsPage } from '@fider/pages/admin/ManageTagsPage';import { HomePage } from '@fider/pages/site/HomePage';import { ShowIdeaPage } from '@fider/pages/site/ShowIdeaPage';import { UserSettingsPage } from '@fider/pages/site/UserSettingsPage';+import { UserNotificationsPage } from '@fider/pages/site/UserNotificationsPage';import { CompleteSignInProfilePage } from '@fider/pages/site/CompleteSignInProfilePage';import { SignUpPage } from '@fider/pages/signup/SignUpPage';@@ -33,6 +34,7 @@ const pathRegex = [route('/admin', AdminHomePage, 'fdr-admin-page', true),route('/signup', SignUpPage, 'fdr-signup-page', false),route('/signin/verify', CompleteSignInProfilePage, 'fdr-complete-signin-profile', true),+ route('/notifications', UserNotificationsPage, 'fdr-user-notifications', true),route('/settings', UserSettingsPage, 'fdr-user-settings', true),];diff --git a/public/services/actions/index.ts b/public/services/actions/index.tsindex ae642b98d..030346fe5 100644--- a/public/services/actions/index.ts+++ b/public/services/actions/index.ts@@ -2,4 +2,5 @@ export * from './user';export * from './tag';export * from './idea';export * from './tenant';+export * from './notification';export { Failure } from '@fider/services/http';diff --git a/public/services/actions/notification.ts b/public/services/actions/notification.tsnew file mode 100644index 000000000..d6171b5e7--- /dev/null+++ b/public/services/actions/notification.ts@@ -0,0 +1,15 @@+import { http, Result } from '@fider/services';++export const getTotalUnreadNotifications = async (): Promise<Result<number>> => {+ return http.get<{ total: number}>('/api/notifications/unread/total').then((result) => {+ return {+ ok: result.ok,+ error: result.error,+ data: result.data ? result.data.total : 0,+ };+ });+};++export const markAllAsRead = async (): Promise<Result> => {+ return await http.post('/api/notifications/read-all');+};diff --git a/public/services/page.ts b/public/services/page.tsindex b760d379e..ea4a5d556 100644--- a/public/services/page.ts+++ b/public/services/page.ts@@ -1,3 +1,7 @@+export const refresh = (): void => {+ document.location.reload();+};+export const setTitle = (title: string): void => {document.title = title;};diff --git a/routes.go b/routes.goindex d3c06a0c5..cb85ed402 100644--- a/routes.go+++ b/routes.go@@ -77,6 +77,8 @@ func GetMainEngine(settings *models.SystemSettings) *web.Engine {{private.Use(middlewares.IsAuthenticated())private.Get("/settings", handlers.UserSettings())+ private.Get("/notifications", handlers.Notifications())+ private.Get("/notifications/:id", handlers.ReadNotification())private.Get("/change-email/verify", handlers.VerifyChangeEmailKey())private.Post("/api/ideas", handlers.PostIdea())@@ -91,6 +93,8 @@ func GetMainEngine(settings *models.SystemSettings) *web.Engine {private.Delete("/api/ideas/:number/tags/:slug", handlers.UnassignTag())private.Post("/api/user/settings", handlers.UpdateUserSettings())private.Post("/api/user/change-email", handlers.ChangeUserEmail())+ private.Post("/api/notifications/read-all", handlers.ReadAllNotifications())+ private.Get("/api/notifications/unread/total", handlers.TotalUnreadNotifications())private.Use(middlewares.IsAuthorized(models.RoleAdministrator))