package v1 import ( "encoding/json" "fmt" "net/http" "net/http/httptest" "strconv" "strings" "sync" "testing" "time" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gorm.io/driver/sqlite" "gorm.io/gorm" "github.com/gochat/gochat/internal/model" "github.com/gochat/gochat/internal/repository" "github.com/gochat/gochat/internal/service" "github.com/gochat/gochat/internal/ws" ) func uintPtr(v uint) *uint { return &v } func setupNotificationDB(t *testing.T) *gorm.DB { t.Helper() db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) assert.NoError(t, err) err = db.AutoMigrate( &model.Notification{}, &model.User{}, &model.Account{}, &model.NotificationPreference{}, &model.Contact{}, &model.Inbox{}, &model.ContactInbox{}, &model.Conversation{}, &model.Message{}, &model.AgentBot{}, ) assert.NoError(t, err) return db } func setupNotificationHandler(t *testing.T, db *gorm.DB) *NotificationHandler { t.Helper() notifRepo := repository.NewNotificationRepo(db) prefRepo := repository.NewNotificationPreferenceRepo(db) ns := service.NewNotificationService(db, notifRepo, prefRepo) return NewNotificationHandler(ns) } type notificationEventHub struct { mu sync.Mutex accounts map[uint][]byte } func newNotificationEventHub() *notificationEventHub { return ¬ificationEventHub{accounts: map[uint][]byte{}} } func (h *notificationEventHub) SendToAccount(accountID uint, data []byte) { h.mu.Lock() defer h.mu.Unlock() h.accounts[accountID] = data } func (h *notificationEventHub) SendToRoom(_ string, _ []byte) {} func (h *notificationEventHub) accountData(accountID uint) []byte { h.mu.Lock() defer h.mu.Unlock() return h.accounts[accountID] } func decodeNotificationEvent(t *testing.T, hub *notificationEventHub, accountID uint) ws.WSMessage { t.Helper() data := hub.accountData(accountID) require.NotNil(t, data) var msg ws.WSMessage require.NoError(t, json.Unmarshal(data, &msg)) return msg } func setupNotificationRouter(handler *NotificationHandler) *gin.Engine { gin.SetMode(gin.TestMode) router := gin.New() // Middleware to set user_id in context — required by handlers that call getUserID(c) router.Use(func(c *gin.Context) { // Set a default user_id; individual tests can override via request header if uidStr := c.GetHeader("X-User-ID"); uidStr != "" { if uid, err := strconv.ParseUint(uidStr, 10, 64); err == nil { c.Set("user_id", uint(uid)) } } c.Next() }) router.GET("/api/v1/accounts/:account_id/notifications", handler.List) router.POST("/api/v1/accounts/:account_id/notifications/read_all", handler.MarkAllRead) router.GET("/api/v1/accounts/:account_id/notifications/unread_count", handler.UnreadCount) router.POST("/api/v1/accounts/:account_id/notifications/destroy_all", handler.DestroyAll) router.DELETE("/api/v1/accounts/:account_id/notifications/destroy_all", handler.DestroyAll) router.GET("/api/v1/accounts/:account_id/notifications/:notification_id", handler.Get) router.PUT("/api/v1/accounts/:account_id/notifications/:notification_id", handler.Update) router.DELETE("/api/v1/accounts/:account_id/notifications/:notification_id", handler.Destroy) // G8 extension routes router.POST("/api/v1/accounts/:account_id/notifications/:notification_id/snooze", handler.Snooze) router.POST("/api/v1/accounts/:account_id/notifications/:notification_id/unread", handler.Unread) return router } func TestNotificationList(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/1/notifications", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationListEmpty(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/1/notifications", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationHandler_List_ChatwootEnvelopeAndIncludes(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) user := &model.User{Name: "Envelope User", Email: "envelope@example.com", Password: "pass", AccountID: 1} require.NoError(t, db.Create(user).Error) accountID := uint(1) readAt := time.Now() snoozedUntil := time.Now().Add(time.Hour) unread := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "message_created", PrimaryActorType: "Conversation", PrimaryActorID: 101, AdditionalAttributes: []byte(`{"push_message_title":"New message","push_message_body":"Hello"}`)} read := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "conversation_assignment", PrimaryActorType: "Conversation", PrimaryActorID: 102, ReadAt: &readAt} snoozed := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "conversation_mention", PrimaryActorType: "Conversation", PrimaryActorID: 103, SnoozedUntil: &snoozedUntil} require.NoError(t, db.Create(unread).Error) require.NoError(t, db.Create(read).Error) require.NoError(t, db.Create(snoozed).Error) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/1/notifications", nil) req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10)) router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) var body map[string]any require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body)) data := body["data"].(map[string]any) meta := data["meta"].(map[string]any) payload := data["payload"].([]any) assert.Equal(t, float64(1), meta["count"]) assert.Equal(t, float64(1), meta["unread_count"]) require.Len(t, payload, 1) item := payload[0].(map[string]any) assert.Equal(t, "New message", item["push_message_title"]) assert.Equal(t, "Hello", item["push_message_body"]) assert.Equal(t, float64(101), item["primary_actor_id"]) assert.NotContains(t, body, "success") w = httptest.NewRecorder() req, _ = http.NewRequest("GET", "/api/v1/accounts/1/notifications?includes[]=read&includes[]=snoozed", nil) req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10)) router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body)) data = body["data"].(map[string]any) meta = data["meta"].(map[string]any) payload = data["payload"].([]any) assert.Equal(t, float64(3), meta["count"]) assert.Equal(t, float64(2), meta["unread_count"]) assert.Len(t, payload, 3) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationHandler_List_SerializesPushEventActors(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) accountID := uint(1) user := &model.User{Name: "Agent Smith", DisplayName: "Smith", Email: "smith@example.com", Password: "pass", AccountID: accountID, AvatarURL: "https://example.com/agent.png", Available: true} contact := &model.Contact{AccountID: accountID, Name: "Alice", Email: "alice@example.com", PhoneNumber: "+15551234567", AvatarURL: "https://example.com/alice.png", Identifier: "alice-1", AdditionalAttributes: []byte(`{"city":"Paris"}`), CustomAttributes: []byte(`{"tier":"gold"}`), Blocked: true} inbox := &model.Inbox{AccountID: accountID, Name: "Support", ChannelType: "Channel::Api", ChannelID: 1} require.NoError(t, db.Create(user).Error) require.NoError(t, db.Create(contact).Error) require.NoError(t, db.Create(inbox).Error) contactInbox := &model.ContactInbox{ContactID: contact.ID, InboxID: inbox.ID, SourceID: "source-1", HMACVerified: true} require.NoError(t, db.Create(contactInbox).Error) now := time.Now().Unix() displayID := uint(42) conversation := &model.Conversation{AccountID: accountID, InboxID: inbox.ID, ContactID: contact.ID, ContactInboxID: &contactInbox.ID, DisplayID: &displayID, ChannelType: "Channel::Api", Channel: "api", Status: "open", Priority: "urgent", LastActivityAt: &now} require.NoError(t, db.Create(conversation).Error) message := &model.Message{ConversationID: conversation.ID, AccountID: accountID, InboxID: inbox.ID, SenderID: &contact.ID, SenderType: string(model.SenderTypeContact), Content: "Hello", ContentType: "text", MessageType: "incoming", Status: "sent"} require.NoError(t, db.Create(message).Error) notification := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "assigned_conversation_new_message", PrimaryActorType: "Conversation", PrimaryActorID: conversation.ID, SecondaryActorType: "Contact", SecondaryActorID: contact.ID} require.NoError(t, db.Create(notification).Error) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/1/notifications", nil) req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10)) router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) var body map[string]any require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body)) payload := body["data"].(map[string]any)["payload"].([]any) require.Len(t, payload, 1) item := payload[0].(map[string]any) primary := item["primary_actor"].(map[string]any) assert.Equal(t, float64(displayID), primary["id"]) assert.Equal(t, "Channel::Api", primary["channel"]) assert.Equal(t, float64(inbox.ID), primary["inbox_id"]) assert.Equal(t, "open", primary["status"]) assert.Equal(t, float64(now), primary["last_activity_at"]) contactInboxPayload := primary["contact_inbox"].(map[string]any) assert.Equal(t, "source-1", contactInboxPayload["source_id"]) contactInboxInbox := contactInboxPayload["inbox"].(map[string]any) assert.Equal(t, float64(inbox.ID), contactInboxInbox["id"]) assert.Equal(t, "Support", contactInboxInbox["name"]) assert.Equal(t, "Channel::Api", contactInboxInbox["channel_type"]) assert.NotContains(t, contactInboxPayload, "contact_id") assert.NotContains(t, contactInboxPayload, "hmac_token") messages := primary["messages"].([]any) require.Len(t, messages, 1) assert.Equal(t, "Hello", messages[0].(map[string]any)["content"]) meta := primary["meta"].(map[string]any) sender := meta["sender"].(map[string]any) assert.Equal(t, float64(contact.ID), sender["id"]) assert.Equal(t, "alice@example.com", sender["email"]) assert.Equal(t, "+15551234567", sender["phone_number"]) secondary := item["secondary_actor"].(map[string]any) assert.Equal(t, "contact", secondary["type"]) assert.Equal(t, true, secondary["blocked"]) assert.Equal(t, "https://example.com/alice.png", secondary["thumbnail"]) serializedUser := item["user"].(map[string]any) assert.Equal(t, float64(user.ID), serializedUser["id"]) assert.Equal(t, "Agent Smith", serializedUser["name"]) assert.Equal(t, "Smith", serializedUser["available_name"]) assert.Equal(t, "https://example.com/agent.png", serializedUser["avatar_url"]) assert.Equal(t, "user", serializedUser["type"]) assert.Equal(t, "online", serializedUser["availability_status"]) assert.Equal(t, "https://example.com/agent.png", serializedUser["thumbnail"]) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationHandler_List_ActorSerializationIsAccountScoped(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) accountID := uint(1) otherAccountID := uint(2) user := &model.User{Name: "Scoped Agent", Email: "scoped-agent@example.com", Password: "pass", AccountID: accountID} otherContact := &model.Contact{AccountID: otherAccountID, Name: "Other Contact", Email: "other@example.com"} require.NoError(t, db.Create(user).Error) require.NoError(t, db.Create(otherContact).Error) notification := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "contact_created", PrimaryActorType: "Contact", PrimaryActorID: otherContact.ID} require.NoError(t, db.Create(notification).Error) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/1/notifications", nil) req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10)) router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) var body map[string]any require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body)) payload := body["data"].(map[string]any)["payload"].([]any) require.Len(t, payload, 1) primary := payload[0].(map[string]any)["primary_actor"].(map[string]any) assert.Equal(t, float64(otherContact.ID), primary["id"]) assert.Equal(t, "Contact", primary["type"]) assert.Equal(t, map[string]any{}, primary["meta"]) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationGet(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/1/notifications/10", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusNotFound, w.Code) // notification doesn't exist sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationGetDoesNotPublishRealtimeEvent(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) hub := newNotificationEventHub() handler.WithEventPublisher(ws.NewEventPublisherLocal(hub, nil)) router := setupNotificationRouter(handler) user := &model.User{Name: "Notification Get User", Email: "notification-get@example.com", Password: "pass", AccountID: 1} require.NoError(t, db.Create(user).Error) accountID := uint(1) notification := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "conversation_mention", PrimaryActorType: "Conversation", PrimaryActorID: 1} require.NoError(t, db.Create(notification).Error) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/1/notifications/%d", notification.ID), nil) req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10)) router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) require.Nil(t, hub.accountData(accountID)) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationGetDifferentID(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/5/notifications/42", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusNotFound, w.Code) // notification doesn't exist sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationMutationsAreScopedToCurrentUserAndAccount(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) user := &model.User{Name: "Scoped User", Email: "scoped@example.com", Password: "pass", AccountID: 1} otherUser := &model.User{Name: "Other User", Email: "scoped-other@example.com", Password: "pass", AccountID: 2} require.NoError(t, db.Create(user).Error) require.NoError(t, db.Create(otherUser).Error) accountID := uint(1) otherAccountID := uint(2) own := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "message_created", PrimaryActorType: "Conversation", PrimaryActorID: 1} otherAccount := &model.Notification{UserID: user.ID, AccountID: &otherAccountID, NotificationType: "message_created", PrimaryActorType: "Conversation", PrimaryActorID: 2} otherOwner := &model.Notification{UserID: otherUser.ID, AccountID: &accountID, NotificationType: "message_created", PrimaryActorType: "Conversation", PrimaryActorID: 3} require.NoError(t, db.Create(own).Error) require.NoError(t, db.Create(otherAccount).Error) require.NoError(t, db.Create(otherOwner).Error) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf("/api/v1/accounts/1/notifications/%d", otherAccount.ID), nil) req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10)) router.ServeHTTP(w, req) require.Equal(t, http.StatusNotFound, w.Code) w = httptest.NewRecorder() req, _ = http.NewRequest("PUT", fmt.Sprintf("/api/v1/accounts/1/notifications/%d", otherOwner.ID), nil) req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10)) router.ServeHTTP(w, req) require.Equal(t, http.StatusNotFound, w.Code) w = httptest.NewRecorder() req, _ = http.NewRequest("PUT", fmt.Sprintf("/api/v1/accounts/1/notifications/%d", own.ID), nil) req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10)) router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) var reloaded model.Notification require.NoError(t, db.First(&reloaded, own.ID).Error) assert.NotNil(t, reloaded.ReadAt) w = httptest.NewRecorder() req, _ = http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/1/notifications/%d", otherAccount.ID), nil) req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10)) router.ServeHTTP(w, req) require.Equal(t, http.StatusNotFound, w.Code) var otherAccountReloaded model.Notification require.NoError(t, db.First(&otherAccountReloaded, otherAccount.ID).Error) w = httptest.NewRecorder() req, _ = http.NewRequest("DELETE", fmt.Sprintf("/api/v1/accounts/1/notifications/%d", own.ID), nil) req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10)) router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) require.Error(t, db.First(&reloaded, own.ID).Error) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationUnreadCountIsAccountScoped(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) user := &model.User{Name: "Unread Scoped User", Email: "unread-scoped@example.com", Password: "pass", AccountID: 1} require.NoError(t, db.Create(user).Error) accountID := uint(1) otherAccountID := uint(2) require.NoError(t, db.Create(&model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "message_created"}).Error) require.NoError(t, db.Create(&model.Notification{UserID: user.ID, AccountID: &otherAccountID, NotificationType: "message_created"}).Error) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/1/notifications/unread_count", nil) req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10)) router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "1", strings.TrimSpace(w.Body.String())) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationReadAll(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) w := httptest.NewRecorder() req, _ := http.NewRequest("POST", "/api/v1/accounts/1/notifications/read_all", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationMarkRead(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) w := httptest.NewRecorder() req, _ := http.NewRequest("PATCH", "/api/v1/accounts/1/notifications/5/read", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusNotFound, w.Code) // notification doesn't exist sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationCRUDWithDB(t *testing.T) { db := setupNotificationDB(t) user := &model.User{Name: "Notif User", Email: "notif@example.com", Password: "pass", AccountID: 1} db.Create(user) // Create notification notif := &model.Notification{ UserID: user.ID, AccountID: uintPtr(1), NotificationType: "conversation_assignment", PrimaryActorType: "conversation", PrimaryActorID: 5, SecondaryActorType: "user", SecondaryActorID: 3, } err := db.Create(notif).Error assert.NoError(t, err) assert.NotEqual(t, 0, notif.ID) // Read notification var fetched model.Notification err = db.First(&fetched, notif.ID).Error assert.NoError(t, err) assert.Equal(t, "conversation_assignment", fetched.NotificationType) assert.Nil(t, fetched.ReadAt) // Mark as read now := time.Now() err = db.Model(&fetched).Update("read_at", &now).Error assert.NoError(t, err) err = db.First(&fetched, notif.ID).Error assert.NoError(t, err) assert.NotNil(t, fetched.ReadAt) // Delete notification err = db.Delete(&fetched).Error assert.NoError(t, err) err = db.First(&fetched, notif.ID).Error assert.Error(t, err) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationReadAllWithDB(t *testing.T) { db := setupNotificationDB(t) user := &model.User{Name: "Notif User2", Email: "notif2@example.com", Password: "pass", AccountID: 1} db.Create(user) // Create multiple unread notifications for i := 0; i < 5; i++ { notif := &model.Notification{ UserID: user.ID, AccountID: uintPtr(1), NotificationType: "message_created", PrimaryActorType: "message", PrimaryActorID: uint(i + 1), } err := db.Create(notif).Error assert.NoError(t, err) } // Verify all are unread var unreadCount int64 db.Model(&model.Notification{}).Where("user_id = ? AND read_at IS NULL", user.ID).Count(&unreadCount) assert.Equal(t, int64(5), unreadCount) // Mark all as read now := time.Now() db.Model(&model.Notification{}).Where("user_id = ? AND read_at IS NULL", user.ID).Update("read_at", &now) // Verify all are read db.Model(&model.Notification{}).Where("user_id = ? AND read_at IS NULL", user.ID).Count(&unreadCount) assert.Equal(t, int64(0), unreadCount) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationTypes(t *testing.T) { types := []string{ "conversation_assignment", "conversation_created", "message_created", "assigned_conversation_new_message", "conversation_mention", } for _, nt := range types { notif := model.Notification{NotificationType: nt} assert.Equal(t, nt, notif.NotificationType) } } func TestNotificationModelFields(t *testing.T) { notif := model.Notification{ UserID: 1, AccountID: uintPtr(2), NotificationType: "conversation_assignment", PrimaryActorType: "conversation", PrimaryActorID: 5, SecondaryActorType: "user", SecondaryActorID: 3, } assert.Equal(t, uint(1), notif.UserID) assert.Equal(t, uintPtr(2), notif.AccountID) assert.Equal(t, "conversation_assignment", notif.NotificationType) assert.Nil(t, notif.ReadAt) } func TestNotificationPagination(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/1/notifications?page=1&per_page=20", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationListByAccount(t *testing.T) { db := setupNotificationDB(t) user1 := &model.User{Name: "User1", Email: "u1@example.com", Password: "pass", AccountID: 1} user2 := &model.User{Name: "User2", Email: "u2@example.com", Password: "pass", AccountID: 2} db.Create(user1) db.Create(user2) for i := 0; i < 3; i++ { notif := &model.Notification{UserID: user1.ID, AccountID: uintPtr(1), NotificationType: "message_created", PrimaryActorType: "message", PrimaryActorID: uint(i + 1)} db.Create(notif) } for i := 0; i < 2; i++ { notif := &model.Notification{UserID: user2.ID, AccountID: uintPtr(2), NotificationType: "conversation_assignment", PrimaryActorType: "conversation", PrimaryActorID: uint(i + 1)} db.Create(notif) } var account1Notifs []model.Notification err := db.Where("account_id = ?", 1).Find(&account1Notifs).Error assert.NoError(t, err) assert.Equal(t, 3, len(account1Notifs)) var account2Notifs []model.Notification err = db.Where("account_id = ?", 2).Find(&account2Notifs).Error assert.NoError(t, err) assert.Equal(t, 2, len(account2Notifs)) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationGetInvalidID(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/api/v1/accounts/1/notifications/abc", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusBadRequest, w.Code) // invalid ID format sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationReadSpecificNotification(t *testing.T) { db := setupNotificationDB(t) user := &model.User{Name: "Specific User", Email: "specific@example.com", Password: "pass", AccountID: 1} db.Create(user) notif := &model.Notification{UserID: user.ID, AccountID: uintPtr(1), NotificationType: "message_created", PrimaryActorType: "message", PrimaryActorID: 1} db.Create(notif) // Read specific notification err := db.Model(notif).Update("ReadAt", time.Now()).Error assert.NoError(t, err) var fetched model.Notification db.First(&fetched, notif.ID) assert.NotNil(t, fetched.ReadAt) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationFilterByReadStatus(t *testing.T) { db := setupNotificationDB(t) user := &model.User{Name: "Filter User", Email: "filter@example.com", Password: "pass", AccountID: 1} db.Create(user) // Create mix of read and unread for i := 0; i < 5; i++ { var readAt *time.Time if i%2 == 0 { readAt = &time.Time{} } notif := &model.Notification{UserID: user.ID, AccountID: uintPtr(1), NotificationType: "message_created", PrimaryActorType: "message", PrimaryActorID: uint(i + 1), ReadAt: readAt} db.Create(notif) } var unread []model.Notification err := db.Where("user_id = ? AND read_at IS NULL", user.ID).Find(&unread).Error assert.NoError(t, err) assert.Equal(t, 2, len(unread)) // indices 1,3 are unread var read []model.Notification err = db.Where("user_id = ? AND read_at IS NOT NULL", user.ID).Find(&read).Error assert.NoError(t, err) assert.Equal(t, 3, len(read)) // indices 0,2,4 are read sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationSoftDelete(t *testing.T) { db := setupNotificationDB(t) user := &model.User{Name: "SoftDel Notif User", Email: "softdel@example.com", Password: "pass", AccountID: 1} db.Create(user) notif := &model.Notification{UserID: user.ID, AccountID: uintPtr(1), NotificationType: "message_created", PrimaryActorType: "message", PrimaryActorID: 1} db.Create(notif) err := db.Delete(notif).Error assert.NoError(t, err) var found model.Notification err = db.First(&found, notif.ID).Error assert.Error(t, err) err = db.Unscoped().First(&found, notif.ID).Error assert.NoError(t, err) sqlDB, _ := db.DB() sqlDB.Close() } // --- G8 extension handler tests: Snooze, Unread, DestroyAll --- // Reference: Chatwoot notifications_controller.rb#snooze, #unread, #destroy_all func TestNotificationHandler_SnoozeWithDB(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) user := &model.User{Name: "Snooze Handler User", Email: "snooze-handler@example.com", Password: "pass", AccountID: 1} db.Create(user) accountID := uint(1) notif := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "conversation_assignment", PrimaryActorType: "conversation", PrimaryActorID: 1} db.Create(notif) // Chatwoot DateRangeHelper parses snoozed_until as Unix seconds. snoozeUnix := time.Now().Add(2 * time.Hour).Unix() body := fmt.Sprintf(`{"snoozed_until":%d}`, snoozeUnix) w := httptest.NewRecorder() req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/1/notifications/%d/snooze", notif.ID), strings.NewReader(body)) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10)) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) // Verify notification has snoozed_until set var updated model.Notification require.NoError(t, db.First(&updated, notif.ID).Error) assert.NotNil(t, updated.SnoozedUntil) assert.Equal(t, snoozeUnix, updated.SnoozedUntil.Unix()) var meta map[string]any require.NoError(t, json.Unmarshal(updated.AdditionalAttributes, &meta)) assert.Contains(t, meta, "last_snoozed_at") sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationHandler_Snooze_InvalidID(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) snoozeTime := time.Now().Add(2 * time.Hour).Unix() body := fmt.Sprintf(`{"snoozed_until":%d}`, snoozeTime) w := httptest.NewRecorder() req, _ := http.NewRequest("POST", "/api/v1/accounts/1/notifications/abc/snooze", strings.NewReader(body)) req.Header.Set("Content-Type", "application/json") router.ServeHTTP(w, req) assert.Equal(t, http.StatusBadRequest, w.Code) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationHandler_Snooze_MissingBody(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) user := &model.User{Name: "Snooze Missing User", Email: "snooze-missing@example.com", Password: "pass", AccountID: 1} db.Create(user) accountID := uint(1) notif := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "conversation_assignment", PrimaryActorType: "conversation", PrimaryActorID: 1} db.Create(notif) w := httptest.NewRecorder() req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/1/notifications/%d/snooze", notif.ID), nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10)) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationHandler_UnreadWithDB(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) user := &model.User{Name: "Unread Handler User", Email: "unread-handler@example.com", Password: "pass", AccountID: 1} db.Create(user) accountID := uint(1) readTime := time.Now() notif := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "conversation_assignment", PrimaryActorType: "conversation", PrimaryActorID: 1, ReadAt: &readTime} db.Create(notif) // Mark it unread w := httptest.NewRecorder() req, _ := http.NewRequest("POST", fmt.Sprintf("/api/v1/accounts/1/notifications/%d/unread", notif.ID), nil) req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10)) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) // Verify notification read_at is cleared var updated model.Notification require.NoError(t, db.First(&updated, notif.ID).Error) assert.Nil(t, updated.ReadAt) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationHandler_MutationsPublishChatwootRealtimePayload(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) hub := newNotificationEventHub() handler.WithEventPublisher(ws.NewEventPublisherLocal(hub, nil)) router := setupNotificationRouter(handler) user := &model.User{Name: "Notification Realtime User", Email: "notification-realtime@example.com", Password: "pass", AccountID: 1} require.NoError(t, db.Create(user).Error) accountID := uint(1) now := time.Now() readNotification := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "conversation_assignment", PrimaryActorType: "Conversation", PrimaryActorID: 1} unreadNotification := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "conversation_mention", PrimaryActorType: "Conversation", PrimaryActorID: 2, ReadAt: &now} snoozeNotification := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "assigned_conversation_new_message", PrimaryActorType: "Conversation", PrimaryActorID: 3} deleteNotification := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "message_created", PrimaryActorType: "Conversation", PrimaryActorID: 4} require.NoError(t, db.Create(readNotification).Error) require.NoError(t, db.Create(unreadNotification).Error) require.NoError(t, db.Create(snoozeNotification).Error) require.NoError(t, db.Create(deleteNotification).Error) request := func(method, path, body string) ws.WSMessage { w := httptest.NewRecorder() req, _ := http.NewRequest(method, path, strings.NewReader(body)) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10)) router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code, w.Body.String()) return decodeNotificationEvent(t, hub, accountID) } msg := request(http.MethodPut, fmt.Sprintf("/api/v1/accounts/1/notifications/%d", readNotification.ID), "") require.Equal(t, ws.EventNotificationUpdated, msg.Event) data := msg.Data.(map[string]any) require.Equal(t, float64(2), data["unread_count"]) require.Equal(t, float64(4), data["count"]) notification := data["notification"].(map[string]any) require.Equal(t, float64(readNotification.ID), notification["id"]) require.NotNil(t, notification["read_at"]) msg = request(http.MethodPost, fmt.Sprintf("/api/v1/accounts/1/notifications/%d/unread", unreadNotification.ID), "") require.Equal(t, ws.EventNotificationUpdated, msg.Event) data = msg.Data.(map[string]any) notification = data["notification"].(map[string]any) require.Equal(t, float64(unreadNotification.ID), notification["id"]) require.Nil(t, notification["read_at"]) require.Equal(t, float64(3), data["unread_count"]) require.Equal(t, float64(4), data["count"]) snoozeUnix := time.Now().Add(time.Hour).Unix() msg = request(http.MethodPost, fmt.Sprintf("/api/v1/accounts/1/notifications/%d/snooze", snoozeNotification.ID), fmt.Sprintf(`{"snoozed_until":%d}`, snoozeUnix)) require.Equal(t, ws.EventNotificationUpdated, msg.Event) data = msg.Data.(map[string]any) require.Equal(t, float64(3), data["unread_count"]) require.Equal(t, float64(4), data["count"]) notification = data["notification"].(map[string]any) require.Equal(t, float64(snoozeNotification.ID), notification["id"]) require.NotNil(t, notification["snoozed_until"]) msg = request(http.MethodDelete, fmt.Sprintf("/api/v1/accounts/1/notifications/%d", deleteNotification.ID), "") require.Equal(t, ws.EventNotificationDeleted, msg.Event) data = msg.Data.(map[string]any) require.Equal(t, float64(2), data["unread_count"]) require.Equal(t, float64(3), data["count"]) notification = data["notification"].(map[string]any) require.Equal(t, float64(deleteNotification.ID), notification["id"]) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationHandler_Unread_InvalidID(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) w := httptest.NewRecorder() req, _ := http.NewRequest("POST", "/api/v1/accounts/1/notifications/abc/unread", nil) router.ServeHTTP(w, req) assert.Equal(t, http.StatusBadRequest, w.Code) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationHandler_DestroyAllWithDB(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) user := &model.User{Name: "DestroyAll Handler User", Email: "destroy-all-handler@example.com", Password: "pass", AccountID: 1} db.Create(user) accountID := uint(1) // Create multiple notifications for i := 0; i < 5; i++ { notif := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: fmt.Sprintf("type_%d", i), PrimaryActorType: "conversation", PrimaryActorID: uint(i + 1)} db.Create(notif) } // Verify they exist var count int64 db.Model(&model.Notification{}).Where("user_id = ? AND account_id = ?", user.ID, accountID).Count(&count) assert.Equal(t, int64(5), count) // Destroy all w := httptest.NewRecorder() req, _ := http.NewRequest("DELETE", "/api/v1/accounts/1/notifications/destroy_all", nil) req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10)) router.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) // Verify all deleted db.Model(&model.Notification{}).Where("user_id = ? AND account_id = ?", user.ID, accountID).Count(&count) assert.Equal(t, int64(0), count) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationHandler_DestroyAll_ReadOnly(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) user := &model.User{Name: "DestroyRead User", Email: "destroy-read@example.com", Password: "pass", AccountID: 1} require.NoError(t, db.Create(user).Error) accountID := uint(1) readAt := time.Now() readNotification := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "read", PrimaryActorType: "conversation", PrimaryActorID: 1, ReadAt: &readAt} unreadNotification := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "unread", PrimaryActorType: "conversation", PrimaryActorID: 2} require.NoError(t, db.Create(readNotification).Error) require.NoError(t, db.Create(unreadNotification).Error) w := httptest.NewRecorder() req, _ := http.NewRequest("POST", "/api/v1/accounts/1/notifications/destroy_all", strings.NewReader(`{"type":"read"}`)) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10)) router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) var count int64 require.NoError(t, db.Model(&model.Notification{}).Where("id = ?", readNotification.ID).Count(&count).Error) assert.Equal(t, int64(0), count) require.NoError(t, db.Model(&model.Notification{}).Where("id = ?", unreadNotification.ID).Count(&count).Error) assert.Equal(t, int64(1), count) sqlDB, _ := db.DB() sqlDB.Close() } func TestNotificationHandler_MarkAllRead_PrimaryActorOnly(t *testing.T) { db := setupNotificationDB(t) handler := setupNotificationHandler(t, db) router := setupNotificationRouter(handler) user := &model.User{Name: "Actor Read User", Email: "actor-read@example.com", Password: "pass", AccountID: 1} require.NoError(t, db.Create(user).Error) accountID := uint(1) matching := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "message_created", PrimaryActorType: "Conversation", PrimaryActorID: 1} other := &model.Notification{UserID: user.ID, AccountID: &accountID, NotificationType: "message_created", PrimaryActorType: "Conversation", PrimaryActorID: 2} require.NoError(t, db.Create(matching).Error) require.NoError(t, db.Create(other).Error) w := httptest.NewRecorder() req, _ := http.NewRequest("POST", "/api/v1/accounts/1/notifications/read_all", strings.NewReader(`{"primary_actor_type":"Conversation","primary_actor_id":1}`)) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-User-ID", strconv.FormatUint(uint64(user.ID), 10)) router.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code) var matchingReloaded model.Notification require.NoError(t, db.First(&matchingReloaded, matching.ID).Error) assert.NotNil(t, matchingReloaded.ReadAt) var otherReloaded model.Notification require.NoError(t, db.First(&otherReloaded, other.ID).Error) assert.Nil(t, otherReloaded.ReadAt) sqlDB, _ := db.DB() sqlDB.Close() }