Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.
Go email-relayemail-routinghttp-to-smtpmail-deliverymailchimp-alternativemailgun-alternativemailsendermailservermailtemplatemailtestpostmark-alternativesend-emailsendgrid-alternativesendmailtransactional-emailtransactional-outbox
feat(notifications): add a per-user in-app inbox and make dashboard alerts dismissible Every notice Posta gave a user was either an email from a cron job or a banner recomputed from stats on each dashboard load.
Jonas Kaninda2a80684b8757
diff --git a/cmd/posta/server.go b/cmd/posta/server.goindex 0717d18..7adc929 100644--- a/cmd/posta/server.go+++ b/cmd/posta/server.go@@ -577,6 +577,7 @@ func initCronManager(producer,))}+ retentionJob.SetNotificationRepo(repositories.NewNotificationRepository(db))if cfg.MessagesEnabled {retentionJob.SetMessageRepo(repositories.NewMessageRepository(db))manager.Register(jobs.NewMessageDigestJob(diff --git a/internal/cron/jobs/retention.go b/internal/cron/jobs/retention.goindex 799e159..2c7bcbf 100644--- a/internal/cron/jobs/retention.go+++ b/internal/cron/jobs/retention.go@@ -26,6 +26,7 @@ type RetentionCleanupJob struct {trackingRepo *repositories.TrackingRepositoryinboundEmailRepo *repositories.InboundEmailRepositorymessageRepo *repositories.MessageRepository+ notificationRepo *repositories.NotificationRepositoryblobStore blob.Storesettings *settings.Provider}@@ -56,6 +57,13 @@ func (j *RetentionCleanupJob) SetMessageRepo(r *repositories.MessageRepository)j.messageRepo = r}+// SetNotificationRepo enables pruning of the in-app inbox. Only settled items+// are dropped; an unresolved, undismissed notification is still true however old+// it is, so age alone never removes it.+func (j *RetentionCleanupJob) SetNotificationRepo(r *repositories.NotificationRepository) {+ j.notificationRepo = r+}+// SetBlobStore configures the blob store so retention cleanup can also purge// attachment bytes (and raw .eml) before dropping DB rows. Nil disables blob// cleanup — DB rows are still purged, but blobs will leak.@@ -171,7 +179,21 @@ func minDays(a, b int) int {return b}+// notificationRetentionDays is how long a read-and-settled inbox item is kept.+// It is not operator-configurable: the inbox is a UI convenience, not a record,+// and the audit log is where history is meant to live.+const notificationRetentionDays = 90+func (j *RetentionCleanupJob) Run(_ context.Context, _ *asynq.Client) error {+ if j.notificationRepo != nil {+ before := time.Now().AddDate(0, 0, -notificationRetentionDays)+ if deleted, err := j.notificationRepo.Prune(before); err != nil {+ logger.Error("retention cleanup: failed to prune notifications", "error", err)+ } else if deleted > 0 {+ logger.Info("retention cleanup: pruned notifications", "count", deleted)+ }+ }+// Clean up email logs (and any blob-stored attachments).emailRetention := j.settings.RetentionDays()if emailRetention > 0 {diff --git a/internal/handlers/admin_announcement_handler.go b/internal/handlers/admin_announcement_handler.gonew file mode 100644index 0000000..068fc3a--- /dev/null+++ b/internal/handlers/admin_announcement_handler.go@@ -0,0 +1,115 @@+// SPDX-FileCopyrightText: 2026 Jonas Kaninda+// SPDX-License-Identifier: AGPL-3.0-or-later++package handlers++import (+ "strings"++ "github.com/goposta/posta/internal/dto"+ "github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/services/audit"+ "github.com/goposta/posta/internal/services/inbox"+ "github.com/jkaninda/okapi"+ "gorm.io/gorm"+)++// AdminAnnouncementHandler lets a platform administrator put a notice in every+// user's in-app inbox — planned maintenance, a breaking upgrade, a policy change.+//+// This is the platform's own voice, as opposed to the health alerts Posta+// derives per workspace, and it is the reason the inbox is not just a rendering+// of dashboard stats.+type AdminAnnouncementHandler struct {+ db *gorm.DB+ inbox *inbox.Service+ audit *audit.Logger+}++func NewAdminAnnouncementHandler(db *gorm.DB, svc *inbox.Service, auditLogger *audit.Logger) *AdminAnnouncementHandler {+ return &AdminAnnouncementHandler{db: db, inbox: svc, audit: auditLogger}+}++type CreateAnnouncementRequest struct {+ Body struct {+ Title string `json:"title" required:"true" max:"200"`+ Message string `json:"message" max:"2000"`+ Link string `json:"link" max:"500"`+ Severity string `json:"severity" enum:"info,warning,critical"`+ } `json:"body"`+}++type AnnouncementIDRequest struct {+ ID int `param:"id"`+}++type ListAnnouncementsRequest struct {+ Page int `query:"page" default:"0"`+ Size int `query:"size" default:"20"`+}++func (h *AdminAnnouncementHandler) List(c *okapi.Context, req *ListAnnouncementsRequest) error {+ page, size, offset := normalizePageParams(req.Page, req.Size)++ var total int64+ if err := h.db.Model(&models.Announcement{}).Count(&total).Error; err != nil {+ return c.AbortInternalServerError("failed to count announcements")+ }+ var rows []models.Announcement+ if err := h.db.Order("id DESC").Limit(size).Offset(offset).Find(&rows).Error; err != nil {+ return c.AbortInternalServerError("failed to list announcements")+ }+ return paginated(c, rows, total, page, size)+}++// Create broadcasts the announcement immediately. There is no draft state: an+// announcement nobody has received is just a note, and Retract exists for the+// case it went out wrong.+func (h *AdminAnnouncementHandler) Create(c *okapi.Context, req *CreateAnnouncementRequest) error {+ title := strings.TrimSpace(req.Body.Title)+ if title == "" {+ return c.AbortBadRequest("a title is required")+ }++ severity := models.NotificationSeverity(req.Body.Severity)+ if severity == "" {+ severity = models.NotificationInfo+ }++ a := &models.Announcement{+ Title: title,+ Message: strings.TrimSpace(req.Body.Message),+ Link: strings.TrimSpace(req.Body.Link),+ Severity: severity,+ CreatedBy: uint(c.GetInt("user_id")),+ AuthorName: c.GetString("user_name"),+ }+ if err := h.inbox.Announce(a); err != nil {+ return c.AbortInternalServerError("failed to broadcast the announcement")+ }++ h.audit.LogCtx(c, "admin.announcement.sent", "Broadcast \""+a.Title+"\"", map[string]any{+ "announcement_id": a.ID,+ "recipients": a.Recipients,+ "severity": string(a.Severity),+ })+ return created(c, a)+}++// Retract deletes the announcement and every delivery it made. An operator who+// broadcast the wrong thing should be able to take it back rather than append a+// correction to everybody's inbox.+func (h *AdminAnnouncementHandler) Retract(c *okapi.Context, req *AnnouncementIDRequest) error {+ var a models.Announcement+ if err := h.db.First(&a, req.ID).Error; err != nil {+ return c.AbortNotFound("announcement not found")+ }+ if err := h.inbox.Retract(a.ID); err != nil {+ return c.AbortInternalServerError("failed to retract the announcement")+ }++ h.audit.LogCtx(c, "admin.announcement.retracted", "Retracted \""+a.Title+"\"", map[string]any{+ "announcement_id": a.ID,+ })+ return ok(c, dto.MessageData{Message: "announcement retracted"})+}diff --git a/internal/handlers/announcement_bind_test.go b/internal/handlers/announcement_bind_test.gonew file mode 100644index 0000000..69fa8cd--- /dev/null+++ b/internal/handlers/announcement_bind_test.go@@ -0,0 +1,53 @@+// SPDX-FileCopyrightText: 2026 Jonas Kaninda+// SPDX-License-Identifier: AGPL-3.0-or-later++package handlers++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/jkaninda/okapi"+)++// The announcement payload has to survive okapi's body resolution. It did not+// once: the message field was called "body", which okapi read as another body+// envelope, so nothing was decoded and every request came back reporting the+// title missing. This binds the real struct through a real request.+func TestCreateAnnouncementRequestBinds(t *testing.T) {+ app := okapi.New()++ var got CreateAnnouncementRequest+ app.Register(okapi.RouteDefinition{+ Method: http.MethodPost,+ Path: "/announcements",+ Handler: okapi.H(func(c *okapi.Context, req *CreateAnnouncementRequest) error {+ got = *req+ return c.JSON(http.StatusOK, okapi.M{"ok": true})+ }),+ })++ payload := `{"title":"Scheduled maintenance","message":"Posta is down 02:00-03:00 UTC.","link":"/status","severity":"warning"}`+ req := httptest.NewRequest(http.MethodPost, "/announcements", strings.NewReader(payload))+ req.Header.Set("Content-Type", "application/json")+ rec := httptest.NewRecorder()+ app.ServeHTTP(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())+ }+ if got.Body.Title != "Scheduled maintenance" {+ t.Errorf("title did not bind: %q", got.Body.Title)+ }+ if got.Body.Message != "Posta is down 02:00-03:00 UTC." {+ t.Errorf("message did not bind: %q", got.Body.Message)+ }+ if got.Body.Link != "/status" {+ t.Errorf("link did not bind: %q", got.Body.Link)+ }+ if got.Body.Severity != "warning" {+ t.Errorf("severity did not bind: %q", got.Body.Severity)+ }+}diff --git a/internal/handlers/dashboard_handler.go b/internal/handlers/dashboard_handler.goindex a699255..e97fce6 100644--- a/internal/handlers/dashboard_handler.go+++ b/internal/handlers/dashboard_handler.go@@ -8,7 +8,9 @@ import ("github.com/goposta/posta/internal/models""github.com/goposta/posta/internal/services/cache"+ "github.com/goposta/posta/internal/services/inbox""github.com/goposta/posta/internal/storage/repositories"+ "github.com/jkaninda/logger""github.com/jkaninda/okapi""gorm.io/gorm")@@ -18,6 +20,7 @@ type DashboardHandler struct {cache *cache.CachewhDeliveryRepo *repositories.WebhookDeliveryRepositoryfeatures DashboardFeatures+ inbox *inbox.Service}type DashboardFeatures struct {@@ -77,6 +80,40 @@ func NewDashboardHandler(db *gorm.DB, c *cache.Cache, whDeliveryRepo *repositorifunc (h *DashboardHandler) SetFeatures(f DashboardFeatures) { h.features = f }+// SetInbox wires the in-app inbox so the dashboard read can reconcile the+// workspace's health alerts. It is optional: without it the dashboard still+// works, it just stops maintaining the banner.+func (h *DashboardHandler) SetInbox(s *inbox.Service) { h.inbox = s }++// syncInbox reconciles the health alerts for the requesting member against the+// snapshot that was just computed.+//+// It runs only when the stats were computed fresh, not on a cache hit, so the+// banner is exactly as current as the numbers printed above it and the write+// happens at most once per cache window. A failure here is not the user's+// problem: the dashboard is still correct without the banner.+func (h *DashboardHandler) syncInbox(c *okapi.Context, scope repositories.ResourceScope, stats *DashboardStats) {+ if h.inbox == nil || scope.WorkspaceID == nil {+ return+ }+ role := workspaceRole(c)+ if role == "" {+ return+ }+ snap := inbox.Snapshot{+ UnverifiedDomains: stats.UnverifiedDomains,+ ExpiringAPIKeys: stats.ExpiringAPIKeys,+ UnreadMessages: stats.UnreadMessages,+ TotalEmails: stats.TotalEmails,+ BounceRate: stats.BounceRate,+ FailureRate: stats.FailureRate,+ MessagesEnabled: h.features.Messages,+ }+ if err := h.inbox.SyncWorkspaceHealth(scope.UserID, *scope.WorkspaceID, role, snap); err != nil {+ logger.Warn("dashboard: failed to sync inbox alerts", "error", err, "workspace_id", *scope.WorkspaceID)+ }+}+func (h *DashboardHandler) Stats(c *okapi.Context) error {scope := getScope(c)ctx := c.Request().Context()@@ -203,5 +240,7 @@ func (h *DashboardHandler) Stats(c *okapi.Context) error {// Store in cacheh.cache.Set(ctx, cacheKey, stats, cache.DashboardStatsTTL)+ h.syncInbox(c, scope, &stats)+return ok(c, stats)}diff --git a/internal/handlers/enum_tag_test.go b/internal/handlers/enum_tag_test.goindex 690b70c..c01016f 100644--- a/internal/handlers/enum_tag_test.go+++ b/internal/handlers/enum_tag_test.go@@ -46,26 +46,68 @@ func walkEnumTags(t *testing.T, typ reflect.Type, path string) {}}+// enumCheckedRequests are the request structs the binding guards walk. Add new+// request types here.+var enumCheckedRequests = []any{+ CreateFormRequest{},+ UpdateFormRequest{},+ FormIDRequest{},+ MessageListRequest{},+ UpdateMessageStateRequest{},+ AssignMessageRequest{},+ MarkSpamRequest{},+ ReplyMessageRequest{},+ MessageAnalyticsRequest{},+ CreateMessageFilterRequest{},+ UpdateMessageFilterRequest{},+ TestMessageFilterRequest{},+ AdminListDomainsRequest{},+ AdminSetDomainVerificationRequest{},+ ListNotificationsRequest{},+ CreateAnnouncementRequest{},+ NotificationIDsRequest{},+}+func TestRequestEnumTagsOnlyOnStrings(t *testing.T) {- requests := []any{- CreateFormRequest{},- UpdateFormRequest{},- FormIDRequest{},- MessageListRequest{},- UpdateMessageStateRequest{},- AssignMessageRequest{},- MarkSpamRequest{},- ReplyMessageRequest{},- MessageAnalyticsRequest{},- CreateMessageFilterRequest{},- UpdateMessageFilterRequest{},- TestMessageFilterRequest{},- }- for _, req := range requests {+ for _, req := range enumCheckedRequests {assertEnumTagsAreStrings(t, req)}}+// okapi resolves a request's body by looking for a field named Body or tagged+// json:"body", then calls Bind on that field — which applies the same rule to+// the body's own fields. A payload with a field called "body" therefore binds as+// an empty struct: no JSON is decoded, and the failure surfaces as every+// required field being missing rather than as anything pointing at the cause.+//+// This walks the same request structs and fails on the shape that triggers it.+func TestRequestBodiesHaveNoBodyField(t *testing.T) {+ for _, req := range enumCheckedRequests {+ typ := reflect.TypeOf(req)+ for i := 0; i < typ.NumField(); i++ {+ field := typ.Field(i)+ if field.Name != "Body" && field.Tag.Get("json") != "body" {+ continue+ }+ body := field.Type+ for body.Kind() == reflect.Pointer {+ body = body.Elem()+ }+ if body.Kind() != reflect.Struct {+ continue+ }+ for j := 0; j < body.NumField(); j++ {+ inner := body.Field(j)+ if inner.Name == "Body" || inner.Tag.Get("json") == "body" {+ t.Errorf("%s.Body.%s is named Body or tagged json:\"body\"; okapi will treat it "++ "as another body envelope and bind nothing, so every request to this endpoint "++ "fails with the required fields missing", typ.Name(), inner.Name)+ }+ }+ }+ }+}+func TestParseNotifyMode(t *testing.T) {valid := map[string]string{"immediate": "immediate",diff --git a/internal/handlers/notification_handler.go b/internal/handlers/notification_handler.gonew file mode 100644index 0000000..382a9e1--- /dev/null+++ b/internal/handlers/notification_handler.go@@ -0,0 +1,128 @@+// SPDX-FileCopyrightText: 2026 Jonas Kaninda+// SPDX-License-Identifier: AGPL-3.0-or-later++package handlers++import (+ "github.com/goposta/posta/internal/dto"+ "github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/services/inbox"+ "github.com/goposta/posta/internal/storage/repositories"+ "github.com/jkaninda/okapi"+)++// NotificationHandler serves a user's in-app inbox: the header bell, the+// notifications page, and the alert banner on the workspace dashboard.+//+// Everything is scoped to the authenticated user. There is no cross-user read+// path here at all, so a notification cannot leak between accounts.+type NotificationHandler struct {+ repo *repositories.NotificationRepository+ inbox *inbox.Service+}++func NewNotificationHandler(repo *repositories.NotificationRepository, svc *inbox.Service) *NotificationHandler {+ return &NotificationHandler{repo: repo, inbox: svc}+}++type ListNotificationsRequest struct {+ Unread bool `query:"unread" doc:"Only notifications the user has not read"`+ Open bool `query:"open" doc:"Only live conditions the user has not dismissed"`+ Category string `query:"category" enum:"domains,deliverability,security,messages,platform"`+ Before int `query:"before" doc:"Keyset cursor: the id of the last row already seen"`+ Limit int `query:"limit" default:"30"`+ // Scoped restricts the listing to the active workspace. Platform+ // announcements have no workspace and are always included.+ Scoped bool `query:"scoped" doc:"Restrict to the active workspace"`+}++type NotificationIDsRequest struct {+ Body struct {+ IDs []uint `json:"ids"`+ } `json:"body"`+}++// NotificationCounts drives the bell badge and tells the dashboard whether the+// banner has anything to show without fetching it.+type NotificationCounts struct {+ Unread int64 `json:"unread"`+ Open int64 `json:"open"`+}++func (h *NotificationHandler) List(c *okapi.Context, req *ListNotificationsRequest) error {+ scope := getScope(c)++ filter := repositories.NotificationFilter{+ UnreadOnly: req.Unread,+ OpenOnly: req.Open,+ Category: models.NotificationCategory(req.Category),+ }+ if req.Scoped {+ filter.WorkspaceID = scope.WorkspaceID+ }++ items, err := h.repo.List(scope.UserID, filter, uint(req.Before), req.Limit)+ if err != nil {+ return c.AbortInternalServerError("failed to list notifications")+ }+ return ok(c, items)+}++// Counts returns the unread badge and how many live items the current workspace+// has. Unread is deliberately not workspace-scoped: a badge that hid news from+// another workspace would train people to ignore it.+func (h *NotificationHandler) Counts(c *okapi.Context) error {+ scope := getScope(c)+ unread, open, err := h.repo.Counts(scope.UserID, scope.WorkspaceID)+ if err != nil {+ return c.AbortInternalServerError("failed to count notifications")+ }+ return ok(c, NotificationCounts{Unread: unread, Open: open})+}++// Banner returns what the workspace dashboard shows above the fold: live,+// undismissed items for this workspace, worst first.+func (h *NotificationHandler) Banner(c *okapi.Context) error {+ scope := getScope(c)+ items, err := h.repo.Open(scope.UserID, scope.WorkspaceID)+ if err != nil {+ return c.AbortInternalServerError("failed to load notifications")+ }+ return ok(c, items)+}++func (h *NotificationHandler) MarkRead(c *okapi.Context, req *NotificationIDsRequest) error {+ if err := h.repo.MarkRead(getScope(c).UserID, req.Body.IDs); err != nil {+ return c.AbortInternalServerError("failed to mark notifications read")+ }+ return ok(c, dto.MessageData{Message: "notifications marked read"})+}++func (h *NotificationHandler) MarkAllRead(c *okapi.Context) error {+ if err := h.repo.MarkAllRead(getScope(c).UserID, nil); err != nil {+ return c.AbortInternalServerError("failed to mark notifications read")+ }+ return ok(c, dto.MessageData{Message: "all notifications marked read"})+}++// Dismiss hides items from the dashboard banner.+//+// A dismissal is not permanent silence: it is bound to the condition as it+// stands now, and the next scan re-arms the item if the condition materially+// changes. Dismissing "3 domains not verified" stays dismissed at three and+// comes back at four.+func (h *NotificationHandler) Dismiss(c *okapi.Context, req *NotificationIDsRequest) error {+ if err := h.repo.Dismiss(getScope(c).UserID, req.Body.IDs); err != nil {+ return c.AbortInternalServerError("failed to dismiss notifications")+ }+ return ok(c, dto.MessageData{Message: "notifications dismissed"})+}++// DismissAll clears the whole banner for the active workspace.+func (h *NotificationHandler) DismissAll(c *okapi.Context) error {+ scope := getScope(c)+ if err := h.repo.DismissAll(scope.UserID, scope.WorkspaceID); err != nil {+ return c.AbortInternalServerError("failed to dismiss notifications")+ }+ return ok(c, dto.MessageData{Message: "notifications dismissed"})+}diff --git a/internal/models/notification.go b/internal/models/notification.gonew file mode 100644index 0000000..f8148f3--- /dev/null+++ b/internal/models/notification.go@@ -0,0 +1,111 @@+// SPDX-FileCopyrightText: 2026 Jonas Kaninda+// SPDX-License-Identifier: AGPL-3.0-or-later++package models++import "time"++// NotificationKind separates the two things that reach a user's inbox: a health+// alert Posta derived on its own, and an announcement a platform administrator+// wrote and broadcast.+type NotificationKind string++const (+ NotificationKindAlert NotificationKind = "alert"+ NotificationKindAnnouncement NotificationKind = "announcement"+)++// NotificationSeverity ranks urgency. Only alerts carry warning/critical;+// announcements are info unless the operator says otherwise.+type NotificationSeverity string++const (+ NotificationInfo NotificationSeverity = "info"+ NotificationWarning NotificationSeverity = "warning"+ NotificationCritical NotificationSeverity = "critical"+)++// NotificationCategory groups items for filtering in the inbox.+type NotificationCategory string++const (+ NotificationCategoryDomains NotificationCategory = "domains"+ NotificationCategoryDeliverability NotificationCategory = "deliverability"+ NotificationCategorySecurity NotificationCategory = "security"+ NotificationCategoryMessages NotificationCategory = "messages"+ NotificationCategoryPlatform NotificationCategory = "platform"+)++// Notification is one item in a user's in-app inbox: the bell, the notifications+// page, and the alert banner on the workspace dashboard all read this table.+//+// It is per-user rather than per-workspace because read and dismissed state+// belong to a person, not to a team. A condition affecting a workspace fans out+// to one row per member.+type Notification struct {+ ID uint `json:"id" gorm:"primaryKey"`+ UserID uint `json:"user_id" gorm:"not null;index:idx_notification_user_open,priority:1"`+ // WorkspaceID is nil for platform-wide items, which follow the user rather+ // than any one workspace.+ WorkspaceID *uint `json:"workspace_id,omitempty" gorm:"index"`+ Kind NotificationKind `json:"kind" gorm:"not null;default:alert"`+ Category NotificationCategory `json:"category" gorm:"not null"`+ Severity NotificationSeverity `json:"severity" gorm:"not null;default:info"`++ Title string `json:"title" gorm:"not null"`+ Body string `json:"body"`+ Link string `json:"link,omitempty"`+ ActionText string `json:"action_text,omitempty"`++ // DedupKey names the condition, not the occurrence: "domains:unverified" for a+ // workspace's unverified domains. At most one unresolved row exists per+ // (user, workspace, dedup_key), so a condition that persists across scans+ // updates in place instead of filling the bell with duplicates.+ DedupKey string `json:"dedup_key" gorm:"not null;index:idx_notification_user_open,priority:2"`++ // Fingerprint captures the condition's current shape — the count, the bucketed+ // rate. It is what makes dismissal safe: a dismissal is bound to the+ // fingerprint it was made against, so dismissing "3 domains unverified" stays+ // dismissed at 3 and resurfaces at 4. Without it, dismissing once would+ // silence the condition forever, including as it gets worse.+ Fingerprint string `json:"-" gorm:"not null;default:''"`++ ReadAt *time.Time `json:"read_at,omitempty"`+ DismissedAt *time.Time `json:"dismissed_at,omitempty"`+ // ResolvedAt is set when the underlying condition clears. Resolved items stay+ // in the inbox as history but leave the dashboard banner.+ ResolvedAt *time.Time `json:"resolved_at,omitempty"`++ CreatedAt time.Time `json:"created_at" gorm:"index"`+ UpdatedAt time.Time `json:"updated_at"`+}++// Open reports whether the notification still describes a live condition the+// user has not dismissed — the set the dashboard banner renders.+func (n *Notification) Open() bool {+ return n.ResolvedAt == nil && n.DismissedAt == nil+}++// Announcement is a platform-wide notice written by an administrator. It is kept+// as its own row so the operator can see what was sent, and edit or retract it,+// independently of the per-user deliveries it produced.+type Announcement struct {+ ID uint `json:"id" gorm:"primaryKey"`+ Title string `json:"title" gorm:"not null"`+ // Message is the notice text. It is deliberately not called Body: okapi+ // resolves a request's body by looking for a field named Body or tagged+ // json:"body", and it applies that rule again to the body's own fields — so+ // a payload containing "body" binds as an empty struct rather than failing+ // loudly. See TestRequestBodiesHaveNoBodyField.+ Message string `json:"message"`+ Link string `json:"link,omitempty"`+ Severity NotificationSeverity `json:"severity" gorm:"not null;default:info"`+ CreatedBy uint `json:"created_by" gorm:"not null"`+ AuthorName string `json:"author_name"`+ // Recipients is how many inbox rows the broadcast produced.+ Recipients int `json:"recipients" gorm:"not null;default:0"`+ SentAt *time.Time `json:"sent_at,omitempty"`++ CreatedAt time.Time `json:"created_at" gorm:"index"`+ UpdatedAt time.Time `json:"updated_at"`+}diff --git a/internal/routes/admin_routes.go b/internal/routes/admin_routes.goindex 349041d..210c265 100644--- a/internal/routes/admin_routes.go+++ b/internal/routes/admin_routes.go@@ -286,6 +286,44 @@ func (r *Router) adminRoutes() []okapi.RouteDefinition {Response: &dto.Response[dto.MessageData]{},},+ // ==================== Announcements ====================+ {+ Method: http.MethodGet,+ Path: pathAnnouncements,+ Handler: okapi.H(r.h.announcement.List),+ Group: adminGroup,+ Summary: "List announcements",+ Description: "Platform notices that have been broadcast, newest first, with how many inboxes each reached.",+ Request: &handlers.ListAnnouncementsRequest{},+ Response: &dto.PageableResponse[models.Announcement]{},+ },+ {+ Method: http.MethodPost,+ Path: pathAnnouncements,+ Handler: okapi.H(r.h.announcement.Create),+ Group: adminGroup,+ Summary: "Broadcast an announcement",+ Description: "Delivers a notice to every active user's in-app inbox immediately. There is no draft state; use retract if it went out wrong.",+ Request: &handlers.CreateAnnouncementRequest{},+ Response: &dto.Response[models.Announcement]{},+ Options: []okapi.RouteOption{+ okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),+ },+ },+ {+ Method: http.MethodDelete,+ Path: pathAnnouncementByID,+ Handler: okapi.H(r.h.announcement.Retract),+ Group: adminGroup,+ Summary: "Retract an announcement",+ Description: "Deletes the announcement and every delivery it made, removing it from users' inboxes.",+ Response: &dto.Response[dto.MessageData]{},+ Options: []okapi.RouteOption{+ okapi.DocPathParam("id", "integer", "Announcement ID"),+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),+ },+ },+// ==================== Domains ===================={Method: http.MethodGet,diff --git a/internal/routes/paths.go b/internal/routes/paths.goindex 3baf750..3d6cd8a 100644--- a/internal/routes/paths.go+++ b/internal/routes/paths.go@@ -11,12 +11,15 @@ package routes// They live together because goconst counts occurrences per package, not per// file, and several are shared across route files.const (- pathBounces = "/bounces"- pathDomains = "/domains"- pathSettings = "/settings"- pathSuppressions = "/suppressions"- pathWebhooks = "/webhooks"+ pathBounces = "/bounces"+ pathNotifications = "/notifications"+ pathAnnouncements = "/announcements"+ pathDomains = "/domains"+ pathSettings = "/settings"+ pathSuppressions = "/suppressions"+ pathWebhooks = "/webhooks"+ pathAnnouncementByID = "/announcements/{id:int}"pathCampaignByID = "/campaigns/{id:int}"pathDomainByID = "/domains/{id:int}"pathFormByID = "/forms/{id:int}"diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex 6bd7332..b19a2b7 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -20,6 +20,7 @@ import ("github.com/goposta/posta/internal/services/emailverify""github.com/goposta/posta/internal/services/eventbus""github.com/goposta/posta/internal/services/inbound"+ "github.com/goposta/posta/internal/services/inbox""github.com/goposta/posta/internal/services/messages""github.com/goposta/posta/internal/services/notification""github.com/goposta/posta/internal/services/passwordreset"@@ -98,6 +99,8 @@ type routerHandlers struct {event *handlers.EventHandleranalytics *handlers.AnalyticsHandleradminDomain *handlers.AdminDomainHandler+ notification *handlers.NotificationHandler+ announcement *handlers.AdminAnnouncementHandlersetting *handlers.SettingHandleruserSetting *handlers.UserSettingHandlerworkspaceSetting *handlers.WorkspaceSettingHandler@@ -132,6 +135,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *cserverRepo := repositories.NewServerRepository(db)webhookRepo := repositories.NewWebhookRepository(db)domainRepo := repositories.NewDomainRepository(db)+ notificationRepo := repositories.NewNotificationRepository(db)bounceRepo := repositories.NewBounceRepository(db)suppressionRepo := repositories.NewSuppressionRepository(db)unsubListRepo := repositories.NewUnsubscribeListRepository(db)@@ -155,6 +159,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c// Servicesbus := eventbus.New(eventRepo)auditLogger := audit.NewLogger(bus)+ inboxService := inbox.NewService(db, notificationRepo)apiKeyService := auth.NewAPIKeyService(apiKeyRepo)settingsProvider := settings.NewProvider(settingRepo)planRepo := repositories.NewPlanRepository(db)@@ -254,6 +259,8 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *cdashboard: handlers.NewDashboardHandler(db, statsCache, webhookDeliveryRepo),domain: handlers.NewDomainHandler(domainRepo),adminDomain: handlers.NewAdminDomainHandler(db, domainRepo, auditLogger),+ notification: handlers.NewNotificationHandler(notificationRepo, inboxService),+ announcement: handlers.NewAdminAnnouncementHandler(db, inboxService, auditLogger),bounce: handlers.NewBounceHandler(bounceRepo, suppressionRepo, emailRepo, dispatcher),suppression: handlers.NewSuppressionHandler(suppressionRepo, unsubListRepo),unsubscribeList: handlers.NewUnsubscribeListHandler(unsubListRepo),@@ -309,6 +316,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *cInbound: cfg.InboundEnabled,Relay: cfg.SMTPRelayEnabled,})+ r.h.dashboard.SetInbox(inboxService)// Email content privacyr.h.email.SetSettings(settingsProvider)diff --git a/internal/routes/user_routes.go b/internal/routes/user_routes.goindex eeab713..2ac75b9 100644--- a/internal/routes/user_routes.go+++ b/internal/routes/user_routes.go@@ -200,6 +200,74 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {Request: &handlers.UpdateUserSettingsRequest{},Response: &dto.Response[models.UserSetting]{},},++ // In-app inbox. These sit under /users/me because a notification is+ // addressed to a person, not to a workspace: read and dismissed state+ // follow the user across every workspace they belong to.+ {+ Method: http.MethodGet,+ Path: pathNotifications,+ Handler: okapi.H(r.h.notification.List),+ Group: userGroup,+ Summary: "List notifications",+ Description: "The authenticated user's in-app inbox, newest first. Paginate with the `before` keyset cursor.",+ Request: &handlers.ListNotificationsRequest{},+ Response: &dto.Response[[]models.Notification]{},+ },+ {+ Method: http.MethodGet,+ Path: pathNotifications + "/counts",+ Handler: r.h.notification.Counts,+ Group: userGroup,+ Summary: "Get notification counts",+ Description: "Unread count for the header bell, and how many live items the active workspace has.",+ Response: &dto.Response[handlers.NotificationCounts]{},+ },+ {+ Method: http.MethodGet,+ Path: pathNotifications + "/banner",+ Handler: r.h.notification.Banner,+ Group: userGroup,+ Summary: "List dashboard banner notifications",+ Description: "Live, undismissed notifications for the active workspace, most severe first.",+ Response: &dto.Response[[]models.Notification]{},+ },+ {+ Method: http.MethodPost,+ Path: pathNotifications + "/read",+ Handler: okapi.H(r.h.notification.MarkRead),+ Group: userGroup,+ Summary: "Mark notifications read",+ Request: &handlers.NotificationIDsRequest{},+ Response: &dto.Response[dto.MessageData]{},+ },+ {+ Method: http.MethodPost,+ Path: pathNotifications + "/read-all",+ Handler: r.h.notification.MarkAllRead,+ Group: userGroup,+ Summary: "Mark all notifications read",+ Response: &dto.Response[dto.MessageData]{},+ },+ {+ Method: http.MethodPost,+ Path: pathNotifications + "/dismiss",+ Handler: okapi.H(r.h.notification.Dismiss),+ Group: userGroup,+ Summary: "Dismiss notifications",+ Description: "Hides items from the dashboard banner. A dismissal is bound to the condition as it currently stands: if the condition materially changes the item resurfaces, so dismissing is not permanent silence.",+ Request: &handlers.NotificationIDsRequest{},+ Response: &dto.Response[dto.MessageData]{},+ },+ {+ Method: http.MethodPost,+ Path: pathNotifications + "/dismiss-all",+ Handler: r.h.notification.DismissAll,+ Group: userGroup,+ Summary: "Dismiss all notifications",+ Description: "Clears the dashboard banner for the active workspace.",+ Response: &dto.Response[dto.MessageData]{},+ },}return routesdiff --git a/internal/services/inbox/health.go b/internal/services/inbox/health.gonew file mode 100644index 0000000..14e70a4--- /dev/null+++ b/internal/services/inbox/health.go@@ -0,0 +1,155 @@+// SPDX-FileCopyrightText: 2026 Jonas Kaninda+// SPDX-License-Identifier: AGPL-3.0-or-later++package inbox++import (+ "fmt"++ "github.com/goposta/posta/internal/models"+)++// Thresholds for the derived health rules. They match what the dashboard used to+// compute in the browser, so moving the rules to the server did not change when+// a workspace is told something is wrong.+const (+ minVolumeForRates = 20+ bounceRateAlert = 5.0+ failureRateAlert = 10.0+ rateFingerprintBand = 5.0+)++// Snapshot is the workspace health the rules read. The dashboard already+// computes every field for its own stats, so evaluating the rules costs nothing+// beyond the rule evaluation itself.+type Snapshot struct {+ UnverifiedDomains int64+ ExpiringAPIKeys int64+ UnreadMessages int64+ TotalEmails int64+ BounceRate float64+ FailureRate float64+ MessagesEnabled bool+}++// rule is one condition Posta watches on a workspace's behalf.+type rule struct {+ dedupKey string+ category models.NotificationCategory+ severity models.NotificationSeverity+ minRole models.WorkspaceRole+ title string+ body string+ link string+ action string+ // fingerprint captures the condition's magnitude, so a dismissal made at one+ // magnitude does not silence a worse one. See models.Notification.Fingerprint.+ fingerprint string+}++// evaluate returns the rules currently firing for a workspace.+func evaluate(s Snapshot) []rule {+ var out []rule++ if s.UnverifiedDomains > 0 {+ out = append(out, rule{+ dedupKey: "domains:unverified",+ category: models.NotificationCategoryDomains,+ severity: models.NotificationWarning,+ minRole: models.WorkspaceRoleEditor,+ title: fmt.Sprintf("%d domain%s not verified", s.UnverifiedDomains, plural(s.UnverifiedDomains)),+ body: "Mail from an unverified domain is far more likely to be filtered, and some routes refuse to send from one at all.",+ link: "/domains",+ action: "Verify domains",+ fingerprint: fmt.Sprintf("n=%d", s.UnverifiedDomains),+ })+ }++ // Rates are only meaningful once enough mail has gone out; below that a+ // single bounce reads as a catastrophe.+ if s.TotalEmails >= minVolumeForRates && s.BounceRate >= bounceRateAlert {+ out = append(out, rule{+ dedupKey: "deliverability:bounce-rate",+ category: models.NotificationCategoryDeliverability,+ severity: models.NotificationCritical,+ minRole: models.WorkspaceRoleEditor,+ title: fmt.Sprintf("Bounce rate is %.1f%%", s.BounceRate),+ body: "Sustained bounces above 5% damage sender reputation. Clean the recipient list before sending more.",+ link: "/bounces",+ action: "Review bounces",+ fingerprint: band(s.BounceRate),+ })+ }++ if s.TotalEmails >= minVolumeForRates && s.FailureRate >= failureRateAlert {+ out = append(out, rule{+ dedupKey: "deliverability:failure-rate",+ category: models.NotificationCategoryDeliverability,+ severity: models.NotificationCritical,+ minRole: models.WorkspaceRoleEditor,+ title: fmt.Sprintf("%.1f%% of sends are failing", s.FailureRate),+ body: "Check the SMTP server configuration and the most recent failures for a common cause.",+ link: "/emails?status=failed",+ action: "View failed emails",+ fingerprint: band(s.FailureRate),+ })+ }++ if s.ExpiringAPIKeys > 0 {+ out = append(out, rule{+ dedupKey: "security:expiring-api-keys",+ category: models.NotificationCategorySecurity,+ severity: models.NotificationWarning,+ minRole: models.WorkspaceRoleAdmin,+ title: fmt.Sprintf("%d API key%s expiring within 7 days", s.ExpiringAPIKeys, plural(s.ExpiringAPIKeys)),+ body: "Rotate them before they lapse, or the integrations using them will start failing.",+ link: "/api-keys",+ action: "Manage API keys",+ fingerprint: fmt.Sprintf("n=%d", s.ExpiringAPIKeys),+ })+ }++ if s.MessagesEnabled && s.UnreadMessages > 0 {+ out = append(out, rule{+ dedupKey: "messages:unread",+ category: models.NotificationCategoryMessages,+ severity: models.NotificationInfo,+ minRole: models.WorkspaceRoleViewer,+ title: fmt.Sprintf("%d unread message%s", s.UnreadMessages, plural(s.UnreadMessages)),+ body: "Someone filled in one of your web forms and is waiting for a reply.",+ link: "/messages",+ action: "Open inbox",+ fingerprint: fmt.Sprintf("n=%d", s.UnreadMessages),+ })+ }++ return out+}++// band buckets a rate so a dismissal is not undone by noise. A rate drifting+// from 5.1% to 5.4% is the same problem; crossing into the next band is not.+func band(rate float64) string {+ return fmt.Sprintf("band=%d", int(rate/rateFingerprintBand))+}++func plural(n int64) string {+ if n == 1 {+ return ""+ }+ return "s"+}++// roleRank orders workspace roles so a rule's minimum role can be compared+// against a member's.+func roleRank(r models.WorkspaceRole) int {+ switch r {+ case models.WorkspaceRoleOwner:+ return 3+ case models.WorkspaceRoleAdmin:+ return 2+ case models.WorkspaceRoleEditor:+ return 1+ default:+ return 0+ }+}diff --git a/internal/services/inbox/health_test.go b/internal/services/inbox/health_test.gonew file mode 100644index 0000000..adfb3a3--- /dev/null+++ b/internal/services/inbox/health_test.go@@ -0,0 +1,128 @@+// SPDX-FileCopyrightText: 2026 Jonas Kaninda+// SPDX-License-Identifier: AGPL-3.0-or-later++package inbox++import (+ "testing"++ "github.com/goposta/posta/internal/models"+)++func keys(rules []rule) map[string]rule {+ out := make(map[string]rule, len(rules))+ for _, r := range rules {+ out[r.dedupKey] = r+ }+ return out+}++func TestRatesNeedVolume(t *testing.T) {+ // A workspace with three sends and one bounce is at 33%, which means nothing.+ quiet := Snapshot{TotalEmails: 3, BounceRate: 33, FailureRate: 33}+ if got := keys(evaluate(quiet)); len(got) != 0 {+ t.Fatalf("expected no rate alerts below the volume floor, got %v", got)+ }++ busy := Snapshot{TotalEmails: minVolumeForRates, BounceRate: 33, FailureRate: 33}+ got := keys(evaluate(busy))+ if _, ok := got["deliverability:bounce-rate"]; !ok {+ t.Fatal("expected a bounce rate alert once there is enough volume")+ }+ if _, ok := got["deliverability:failure-rate"]; !ok {+ t.Fatal("expected a failure rate alert once there is enough volume")+ }+}++// A rate wobbling inside its band is the same problem, so a dismissal must+// survive it. Crossing into the next band is new information.+func TestRateFingerprintIsBanded(t *testing.T) {+ at := func(rate float64) string {+ r := keys(evaluate(Snapshot{TotalEmails: 100, BounceRate: rate}))["deliverability:bounce-rate"]+ return r.fingerprint+ }++ if at(5.1) != at(5.9) {+ t.Fatalf("noise inside a band must not resurface a dismissal: %s vs %s", at(5.1), at(5.9))+ }+ if at(5.1) == at(12.0) {+ t.Fatal("crossing a band must resurface a dismissal")+ }+}++func TestCountFingerprintTracksTheCount(t *testing.T) {+ three := keys(evaluate(Snapshot{UnverifiedDomains: 3}))["domains:unverified"]+ four := keys(evaluate(Snapshot{UnverifiedDomains: 4}))["domains:unverified"]++ if three.fingerprint == four.fingerprint {+ t.Fatal("one more unverified domain is new information and must resurface")+ }+ if three.title != "3 domains not verified" {+ t.Fatalf("unexpected title %q", three.title)+ }+}++func TestMessagesRuleRespectsTheFeatureFlag(t *testing.T) {+ off := keys(evaluate(Snapshot{UnreadMessages: 5, MessagesEnabled: false}))+ if _, ok := off["messages:unread"]; ok {+ t.Fatal("the messages rule must not fire when the feature is disabled")+ }+ on := keys(evaluate(Snapshot{UnreadMessages: 5, MessagesEnabled: true}))+ if _, ok := on["messages:unread"]; !ok {+ t.Fatal("the messages rule should fire when the feature is enabled")+ }+}++func TestSingularTitles(t *testing.T) {+ one := keys(evaluate(Snapshot{UnverifiedDomains: 1, ExpiringAPIKeys: 1}))+ if one["domains:unverified"].title != "1 domain not verified" {+ t.Fatalf("unexpected title %q", one["domains:unverified"].title)+ }+ if one["security:expiring-api-keys"].title != "1 API key expiring within 7 days" {+ t.Fatalf("unexpected title %q", one["security:expiring-api-keys"].title)+ }+}++// A viewer cannot verify a domain or rotate a key, so the rules that need+// action are gated above them.+func TestRoleGating(t *testing.T) {+ all := evaluate(Snapshot{+ UnverifiedDomains: 1,+ ExpiringAPIKeys: 1,+ UnreadMessages: 1,+ MessagesEnabled: true,+ TotalEmails: 100,+ BounceRate: 9,+ })++ visible := func(role models.WorkspaceRole) map[string]bool {+ out := map[string]bool{}+ for _, r := range all {+ if roleRank(role) >= roleRank(r.minRole) {+ out[r.dedupKey] = true+ }+ }+ return out+ }++ viewer := visible(models.WorkspaceRoleViewer)+ if !viewer["messages:unread"] {+ t.Fatal("a viewer should still be told about unread messages")+ }+ if viewer["domains:unverified"] || viewer["security:expiring-api-keys"] {+ t.Fatal("a viewer cannot act on domains or API keys and should not be alerted")+ }++ editor := visible(models.WorkspaceRoleEditor)+ if !editor["domains:unverified"] || !editor["deliverability:bounce-rate"] {+ t.Fatal("an editor should see the domain and deliverability alerts")+ }+ if editor["security:expiring-api-keys"] {+ t.Fatal("API key expiry is an admin concern")+ }++ owner := visible(models.WorkspaceRoleOwner)+ if len(owner) != len(all) {+ t.Fatalf("an owner should see everything: %d of %d", len(owner), len(all))+ }+}diff --git a/internal/services/inbox/service.go b/internal/services/inbox/service.gonew file mode 100644index 0000000..883590a--- /dev/null+++ b/internal/services/inbox/service.go@@ -0,0 +1,133 @@+// SPDX-FileCopyrightText: 2026 Jonas Kaninda+// SPDX-License-Identifier: AGPL-3.0-or-later++package inbox++import (+ "fmt"+ "time"++ "github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/storage/repositories"+ "gorm.io/gorm"+)++// Service maintains the in-app inbox: the health alerts Posta derives for a+// workspace, and the announcements a platform administrator broadcasts.+//+// It is deliberately separate from services/notification, which sends email.+// The two answer different questions — email is a push into somebody's day, the+// inbox is what the product says about itself when you open it — and a condition+// worth a banner is usually not worth a mail.+type Service struct {+ db *gorm.DB+ repo *repositories.NotificationRepository+}++func NewService(db *gorm.DB, repo *repositories.NotificationRepository) *Service {+ return &Service{db: db, repo: repo}+}++// SyncWorkspaceHealth reconciles one member's alerts for one workspace against+// the current snapshot: firing rules are upserted, and anything that was firing+// and no longer is gets resolved.+//+// It runs on the dashboard read rather than on a timer because the snapshot is+// already in hand there, and because a banner that lags the numbers printed next+// to it would be worse than no banner.+func (s *Service) SyncWorkspaceHealth(userID uint, workspaceID uint, role models.WorkspaceRole, snap Snapshot) error {+ ws := workspaceID+ firing := evaluate(snap)++ keep := make([]string, 0, len(firing))+ for _, r := range firing {+ if roleRank(role) < roleRank(r.minRole) {+ // A viewer cannot verify a domain or rotate a key. Telling them is+ // noise they have no way to clear.+ continue+ }+ keep = append(keep, r.dedupKey)+ n := &models.Notification{+ UserID: userID,+ WorkspaceID: &ws,+ Kind: models.NotificationKindAlert,+ Category: r.category,+ Severity: r.severity,+ Title: r.title,+ Body: r.body,+ Link: r.link,+ ActionText: r.action,+ DedupKey: r.dedupKey,+ Fingerprint: r.fingerprint,+ }+ if err := s.repo.Upsert(n); err != nil {+ return err+ }+ }++ return s.repo.ResolveExcept(userID, &ws, keep)+}++// Announce broadcasts a platform notice to every user who can sign in, and+// records how many deliveries it produced.+//+// Fan-out writes one row per user rather than a single shared row so that read+// and dismissed state stay per-person, which is the whole point of the inbox.+// Posta is self-hosted and user counts are small; the insert is batched.+func (s *Service) Announce(a *models.Announcement) error {+ var users []models.User+ if err := s.db.Model(&models.User{}).Select("id").Where("active = ?", true).Find(&users).Error; err != nil {+ return err+ }++ now := time.Now().UTC()+ a.SentAt = &now+ a.Recipients = len(users)+ if err := s.db.Create(a).Error; err != nil {+ return err+ }++ rows := make([]models.Notification, 0, len(users))+ for i := range users {+ rows = append(rows, models.Notification{+ UserID: users[i].ID,+ Kind: models.NotificationKindAnnouncement,+ Category: models.NotificationCategoryPlatform,+ Severity: a.Severity,+ Title: a.Title,+ Body: a.Message,+ Link: a.Link,+ DedupKey: AnnouncementKey(a.ID),+ Fingerprint: fmt.Sprintf("announcement=%d", a.ID),+ })+ }+ if err := s.repo.CreateBatch(rows); err != nil {+ return err+ }+ return nil+}++// Retract removes an announcement and the deliveries it made. An operator who+// broadcast the wrong thing should be able to take it back, not just append a+// correction to everyone's inbox.+func (s *Service) Retract(id uint) error {+ if _, err := s.repo.DeleteForAnnouncement(AnnouncementKey(id)); err != nil {+ return err+ }+ return s.db.Delete(&models.Announcement{}, id).Error+}++// Deliver posts a single item to one user. Cron jobs that already email a user+// about a condition use it so the same news is waiting in the UI.+func (s *Service) Deliver(userID uint, workspaceID *uint, n models.Notification) error {+ n.UserID = userID+ n.WorkspaceID = workspaceID+ if n.Kind == "" {+ n.Kind = models.NotificationKindAlert+ }+ return s.repo.Upsert(&n)+}++// AnnouncementKey is the dedup key every delivery of one announcement shares,+// which is also how a retraction finds them again.+func AnnouncementKey(id uint) string { return fmt.Sprintf("announcement:%d", id) }diff --git a/internal/storage/migration/constraints.go b/internal/storage/migration/constraints.goindex 942205d..6065840 100644--- a/internal/storage/migration/constraints.go+++ b/internal/storage/migration/constraints.go@@ -48,6 +48,16 @@ func runConstraints(db *gorm.DB) {rebuildUniqueIndexes(db)+ // Partial unique index: at most one unresolved notification per user and+ // condition. It is what makes a recurring condition update the existing+ // inbox item instead of adding a row on every dashboard load, and it holds+ // even if two requests race.+ db.Exec(`DO $$ BEGIN+ CREATE UNIQUE INDEX IF NOT EXISTS idx_notification_open+ ON notifications (user_id, workspace_id, dedup_key) WHERE resolved_at IS NULL;+ EXCEPTION WHEN others THEN NULL;+ END $$`)+// Partial unique index: at most one ownership-verified row per domain name// (case-insensitive). Prevents two tenants from both verifying the same domain.db.Exec(`DO $$ BEGINdiff --git a/internal/storage/migration/migrate_smoke_test.go b/internal/storage/migration/migrate_smoke_test.gonew file mode 100644index 0000000..5f22845--- /dev/null+++ b/internal/storage/migration/migrate_smoke_test.go@@ -0,0 +1,36 @@+// SPDX-FileCopyrightText: 2026 Jonas Kaninda+// SPDX-License-Identifier: AGPL-3.0-or-later++package migration++import (+ "os"+ "testing"++ "gorm.io/driver/postgres"+ "gorm.io/gorm"+ gl "gorm.io/gorm/logger"+)++// TestMigrateSmoke runs the full schema migration against a scratch database.+// It is skipped unless MIGRATION_SMOKE_DSN is set.+func TestMigrateSmoke(t *testing.T) {+ dsn := os.Getenv("MIGRATION_SMOKE_DSN")+ if dsn == "" {+ t.Skip("set MIGRATION_SMOKE_DSN to run")+ }+ db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: gl.Default.LogMode(gl.Silent)})+ if err != nil {+ t.Fatalf("open: %v", err)+ }+ if err := Run(db); err != nil {+ t.Fatalf("migrate: %v", err)+ }++ var idx string+ if err := db.Raw(`SELECT indexdef FROM pg_indexes WHERE indexname = 'idx_notification_open'`).+ Scan(&idx).Error; err != nil || idx == "" {+ t.Fatalf("partial unique index missing: %v (%q)", err, idx)+ }+ t.Logf("index: %s", idx)+}diff --git a/internal/storage/migration/migration.go b/internal/storage/migration/migration.goindex 4f68afb..f07efd0 100644--- a/internal/storage/migration/migration.go+++ b/internal/storage/migration/migration.go@@ -61,6 +61,8 @@ func Run(db *gorm.DB) error {&models.Message{},&models.MessageReply{},&models.MessageFilter{},+ &models.Notification{},+ &models.Announcement{},&models.UpgradeStep{},&models.UpdateStatus{},); err != nil {diff --git a/internal/storage/repositories/notification_repo.go b/internal/storage/repositories/notification_repo.gonew file mode 100644index 0000000..112a3b1--- /dev/null+++ b/internal/storage/repositories/notification_repo.go@@ -0,0 +1,232 @@+// SPDX-FileCopyrightText: 2026 Jonas Kaninda+// SPDX-License-Identifier: AGPL-3.0-or-later++package repositories++import (+ "errors"+ "time"++ "github.com/goposta/posta/internal/models"+ "gorm.io/gorm"+ "gorm.io/gorm/clause"+)++// NotificationRepository persists the per-user in-app inbox. It is unrelated to+// services/notification, which sends email.+type NotificationRepository struct {+ db *gorm.DB+}++func NewNotificationRepository(db *gorm.DB) *NotificationRepository {+ return &NotificationRepository{db: db}+}++// NotificationFilter narrows the inbox listing.+type NotificationFilter struct {+ WorkspaceID *uint+ UnreadOnly bool+ OpenOnly bool+ Category models.NotificationCategory+}++// Upsert writes one delivery, folding it into the existing unresolved row for the+// same (user, workspace, dedup key) when there is one.+//+// A dismissal survives only while the condition looks the same. When the+// fingerprint changes the row is re-armed — undismissed and marked unread — so a+// worsening condition comes back rather than staying silenced by a dismissal the+// user made when it was smaller.+func (r *NotificationRepository) Upsert(n *models.Notification) error {+ // Two dashboard loads racing would both find nothing and both insert. The+ // partial unique index would reject the loser, so let the database arbitrate+ // and fall through to the update path when it does.+ if err := r.upsertOnce(n); errors.Is(err, errRaceLost) {+ return r.upsertOnce(n)+ } else if err != nil {+ return err+ }+ return nil+}++var errRaceLost = errors.New("notification upsert lost an insert race")++func (r *NotificationRepository) upsertOnce(n *models.Notification) error {+ return r.db.Transaction(func(tx *gorm.DB) error {+ var existing models.Notification+ q := tx.Where("user_id = ? AND dedup_key = ? AND resolved_at IS NULL", n.UserID, n.DedupKey)+ q = scopeWorkspace(q, n.WorkspaceID)++ err := q.First(&existing).Error+ if errors.Is(err, gorm.ErrRecordNotFound) {+ created := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(n)+ if created.Error != nil {+ return created.Error+ }+ if created.RowsAffected == 0 {+ return errRaceLost+ }+ return nil+ }+ if err != nil {+ return err+ }++ changed := existing.Fingerprint != n.Fingerprint+ existing.Title = n.Title+ existing.Body = n.Body+ existing.Link = n.Link+ existing.ActionText = n.ActionText+ existing.Severity = n.Severity+ existing.Category = n.Category+ existing.Fingerprint = n.Fingerprint+ if changed {+ existing.DismissedAt = nil+ existing.ReadAt = nil+ }+ if err := tx.Save(&existing).Error; err != nil {+ return err+ }+ *n = existing+ return nil+ })+}++// ResolveExcept closes every unresolved alert for the user and workspace whose+// dedup key is no longer in keep — the conditions that have cleared since the+// last scan. Resolved rows stay in the inbox as history but drop off the banner.+func (r *NotificationRepository) ResolveExcept(userID uint, workspaceID *uint, keep []string) error {+ q := r.db.Model(&models.Notification{}).+ Where("user_id = ? AND kind = ? AND resolved_at IS NULL", userID, models.NotificationKindAlert)+ q = scopeWorkspace(q, workspaceID)+ if len(keep) > 0 {+ q = q.Where("dedup_key NOT IN ?", keep)+ }+ return q.Update("resolved_at", time.Now().UTC()).Error+}++// List returns a page of the user's inbox, newest first. before is a keyset+// cursor: pass the id of the last row seen.+func (r *NotificationRepository) List(userID uint, f NotificationFilter, before uint, limit int) ([]models.Notification, error) {+ q := r.query(userID, f)+ if before > 0 {+ q = q.Where("id < ?", before)+ }+ if limit <= 0 || limit > 100 {+ limit = 30+ }+ var out []models.Notification+ err := q.Order("id DESC").Limit(limit).Find(&out).Error+ return out, err+}++// Counts returns the bell badge and the number of open items, in one round trip+// each rather than loading the rows.+func (r *NotificationRepository) Counts(userID uint, workspaceID *uint) (unread, open int64, err error) {+ unreadQ := r.db.Model(&models.Notification{}).+ Where("user_id = ? AND read_at IS NULL AND resolved_at IS NULL", userID)+ if err = unreadQ.Count(&unread).Error; err != nil {+ return 0, 0, err+ }+ openQ := r.db.Model(&models.Notification{}).+ Where("user_id = ? AND resolved_at IS NULL AND dismissed_at IS NULL", userID)+ openQ = scopeWorkspace(openQ, workspaceID)+ err = openQ.Count(&open).Error+ return unread, open, err+}++// Open returns the items the workspace dashboard banner renders: live, not+// dismissed, and belonging to this workspace or to no workspace at all.+func (r *NotificationRepository) Open(userID uint, workspaceID *uint) ([]models.Notification, error) {+ q := r.db.Where("user_id = ? AND resolved_at IS NULL AND dismissed_at IS NULL", userID)+ if workspaceID != nil {+ q = q.Where("workspace_id IS NULL OR workspace_id = ?", *workspaceID)+ }+ var out []models.Notification+ err := q.Order("CASE severity WHEN 'critical' THEN 0 WHEN 'warning' THEN 1 ELSE 2 END, id DESC").+ Limit(10).Find(&out).Error+ return out, err+}++func (r *NotificationRepository) MarkRead(userID uint, ids []uint) error {+ if len(ids) == 0 {+ return nil+ }+ return r.db.Model(&models.Notification{}).+ Where("user_id = ? AND id IN ? AND read_at IS NULL", userID, ids).+ Update("read_at", time.Now().UTC()).Error+}++func (r *NotificationRepository) MarkAllRead(userID uint, workspaceID *uint) error {+ q := r.db.Model(&models.Notification{}).Where("user_id = ? AND read_at IS NULL", userID)+ q = scopeWorkspace(q, workspaceID)+ return q.Update("read_at", time.Now().UTC()).Error+}++// Dismiss hides one item from the banner. It also marks it read: a user who+// dismissed something has seen it, and leaving the bell badge lit would be noise.+func (r *NotificationRepository) Dismiss(userID uint, ids []uint) error {+ if len(ids) == 0 {+ return nil+ }+ now := time.Now().UTC()+ return r.db.Model(&models.Notification{}).+ Where("user_id = ? AND id IN ? AND dismissed_at IS NULL", userID, ids).+ Updates(map[string]any{"dismissed_at": now, "read_at": gorm.Expr("COALESCE(read_at, ?)", now)}).Error+}++// DismissAll clears the banner in one action.+func (r *NotificationRepository) DismissAll(userID uint, workspaceID *uint) error {+ now := time.Now().UTC()+ q := r.db.Model(&models.Notification{}).+ Where("user_id = ? AND dismissed_at IS NULL AND resolved_at IS NULL", userID)+ q = scopeWorkspace(q, workspaceID)+ return q.Updates(map[string]any{"dismissed_at": now, "read_at": gorm.Expr("COALESCE(read_at, ?)", now)}).Error+}++// Prune drops notifications older than the cutoff. Open items are kept whatever+// their age: an unresolved condition is still true, however long it has been.+func (r *NotificationRepository) Prune(before time.Time) (int64, error) {+ res := r.db.Where("created_at < ? AND (resolved_at IS NOT NULL OR dismissed_at IS NOT NULL)", before).+ Delete(&models.Notification{})+ return res.RowsAffected, res.Error+}++// DeleteForAnnouncement removes the deliveries a retracted announcement produced.+func (r *NotificationRepository) DeleteForAnnouncement(dedupKey string) (int64, error) {+ res := r.db.Where("dedup_key = ? AND kind = ?", dedupKey, models.NotificationKindAnnouncement).+ Delete(&models.Notification{})+ return res.RowsAffected, res.Error+}++// CreateBatch inserts many deliveries at once — the announcement fan-out.+func (r *NotificationRepository) CreateBatch(rows []models.Notification) error {+ if len(rows) == 0 {+ return nil+ }+ return r.db.CreateInBatches(rows, 200).Error+}++func (r *NotificationRepository) query(userID uint, f NotificationFilter) *gorm.DB {+ q := r.db.Model(&models.Notification{}).Where("user_id = ?", userID)+ q = scopeWorkspace(q, f.WorkspaceID)+ if f.UnreadOnly {+ q = q.Where("read_at IS NULL")+ }+ if f.OpenOnly {+ q = q.Where("resolved_at IS NULL AND dismissed_at IS NULL")+ }+ if f.Category != "" {+ q = q.Where("category = ?", f.Category)+ }+ return q+}++// scopeWorkspace restricts to one workspace while keeping platform-wide items,+// which belong to the user in every workspace they open.+func scopeWorkspace(q *gorm.DB, workspaceID *uint) *gorm.DB {+ if workspaceID == nil {+ return q+ }+ return q.Where("workspace_id IS NULL OR workspace_id = ?", *workspaceID)+}diff --git a/internal/storage/repositories/notification_repo_test.go b/internal/storage/repositories/notification_repo_test.gonew file mode 100644index 0000000..6b632a0--- /dev/null+++ b/internal/storage/repositories/notification_repo_test.go@@ -0,0 +1,276 @@+// SPDX-FileCopyrightText: 2026 Jonas Kaninda+// SPDX-License-Identifier: AGPL-3.0-or-later++package repositories++import (+ "testing"++ "github.com/goposta/posta/internal/models"+ "gorm.io/gorm"+)++func notificationDB(t *testing.T) *gorm.DB {+ t.Helper()+ db := testDB(t)+ if err := db.AutoMigrate(&models.Notification{}); err != nil {+ t.Skipf("skipping: cannot migrate notifications: %v", err)+ }+ return db+}++func alert(userID uint, wsID *uint, fingerprint, title string) *models.Notification {+ return &models.Notification{+ UserID: userID,+ WorkspaceID: wsID,+ Kind: models.NotificationKindAlert,+ Category: models.NotificationCategoryDomains,+ Severity: models.NotificationWarning,+ Title: title,+ DedupKey: "domains:unverified",+ Fingerprint: fingerprint,+ }+}++func mustUpsert(t *testing.T, r *NotificationRepository, n *models.Notification) *models.Notification {+ t.Helper()+ if err := r.Upsert(n); err != nil {+ t.Fatalf("upsert: %v", err)+ }+ return n+}++func reload(t *testing.T, tx *gorm.DB, id uint) models.Notification {+ t.Helper()+ var got models.Notification+ if err := tx.First(&got, id).Error; err != nil {+ t.Fatalf("reload: %v", err)+ }+ return got+}++// A condition that persists unchanged must fold into the existing row rather+// than adding one on every dashboard load.+func TestUpsertFoldsRepeatedCondition(t *testing.T) {+ db := notificationDB(t)+ tx := db.Begin()+ t.Cleanup(func() { tx.Rollback() })++ userID := createUser(t, tx, "[email protected]")+ ws := uintPtr(4001)+ repo := &NotificationRepository{db: tx}++ first := mustUpsert(t, repo, alert(userID, ws, "n=3", "3 domains not verified"))+ second := mustUpsert(t, repo, alert(userID, ws, "n=3", "3 domains not verified"))++ if first.ID != second.ID {+ t.Fatalf("expected the same row, got %d then %d", first.ID, second.ID)+ }++ var count int64+ tx.Model(&models.Notification{}).Where("user_id = ?", userID).Count(&count)+ if count != 1 {+ t.Fatalf("expected 1 notification, got %d", count)+ }+}++// Dismissal is bound to the condition as it stood. An unchanged condition stays+// dismissed: this is what stops the banner reappearing on every page load.+func TestDismissSurvivesUnchangedCondition(t *testing.T) {+ db := notificationDB(t)+ tx := db.Begin()+ t.Cleanup(func() { tx.Rollback() })++ userID := createUser(t, tx, "[email protected]")+ ws := uintPtr(4002)+ repo := &NotificationRepository{db: tx}++ n := mustUpsert(t, repo, alert(userID, ws, "n=3", "3 domains not verified"))+ if err := repo.Dismiss(userID, []uint{n.ID}); err != nil {+ t.Fatalf("dismiss: %v", err)+ }++ mustUpsert(t, repo, alert(userID, ws, "n=3", "3 domains not verified"))++ got := reload(t, tx, n.ID)+ if got.DismissedAt == nil {+ t.Fatal("an unchanged condition must stay dismissed")+ }+ if got.ReadAt == nil {+ t.Fatal("dismissing should also mark the item read")+ }+}++// The other half of the same rule: a condition that materially worsens re-arms+// the item, so dismissing once does not silence it forever.+func TestDismissResurfacesOnChangedCondition(t *testing.T) {+ db := notificationDB(t)+ tx := db.Begin()+ t.Cleanup(func() { tx.Rollback() })++ userID := createUser(t, tx, "[email protected]")+ ws := uintPtr(4003)+ repo := &NotificationRepository{db: tx}++ n := mustUpsert(t, repo, alert(userID, ws, "n=3", "3 domains not verified"))+ if err := repo.Dismiss(userID, []uint{n.ID}); err != nil {+ t.Fatalf("dismiss: %v", err)+ }++ mustUpsert(t, repo, alert(userID, ws, "n=4", "4 domains not verified"))++ got := reload(t, tx, n.ID)+ if got.DismissedAt != nil {+ t.Fatal("a worsened condition must resurface")+ }+ if got.ReadAt != nil {+ t.Fatal("a resurfaced item must be unread again")+ }+ if got.Title != "4 domains not verified" {+ t.Fatalf("expected the title to update in place, got %q", got.Title)+ }+}++// A condition that clears is resolved, leaves the banner, and stays in the+// inbox as history.+func TestResolveExceptClosesClearedConditions(t *testing.T) {+ db := notificationDB(t)+ tx := db.Begin()+ t.Cleanup(func() { tx.Rollback() })++ userID := createUser(t, tx, "[email protected]")+ ws := uintPtr(4004)+ repo := &NotificationRepository{db: tx}++ n := mustUpsert(t, repo, alert(userID, ws, "n=3", "3 domains not verified"))++ if err := repo.ResolveExcept(userID, ws, nil); err != nil {+ t.Fatalf("resolve: %v", err)+ }++ got := reload(t, tx, n.ID)+ if got.ResolvedAt == nil {+ t.Fatal("a cleared condition must be resolved")+ }++ open, err := repo.Open(userID, ws)+ if err != nil {+ t.Fatalf("open: %v", err)+ }+ if len(open) != 0 {+ t.Fatalf("a resolved item must leave the banner, got %d", len(open))+ }++ // Resolved, then firing again: a new row, because the old one is history.+ again := mustUpsert(t, repo, alert(userID, ws, "n=1", "1 domain not verified"))+ if again.ID == n.ID {+ t.Fatal("a condition that fires after resolving should open a new item")+ }+}++// The banner is workspace-scoped, but platform announcements have no workspace+// and must reach the user wherever they are.+func TestOpenIncludesPlatformItemsAndExcludesOtherWorkspaces(t *testing.T) {+ db := notificationDB(t)+ tx := db.Begin()+ t.Cleanup(func() { tx.Rollback() })++ userID := createUser(t, tx, "[email protected]")+ here, elsewhere := uintPtr(4005), uintPtr(4006)+ repo := &NotificationRepository{db: tx}++ mustUpsert(t, repo, alert(userID, here, "n=1", "here"))+ mustUpsert(t, repo, alert(userID, elsewhere, "n=1", "elsewhere"))+ mustUpsert(t, repo, &models.Notification{+ UserID: userID,+ Kind: models.NotificationKindAnnouncement,+ Category: models.NotificationCategoryPlatform,+ Severity: models.NotificationInfo,+ Title: "platform",+ DedupKey: "announcement:1",+ Fingerprint: "announcement=1",+ })++ open, err := repo.Open(userID, here)+ if err != nil {+ t.Fatalf("open: %v", err)+ }++ seen := map[string]bool{}+ for _, n := range open {+ seen[n.Title] = true+ }+ if !seen["here"] || !seen["platform"] {+ t.Fatalf("expected the workspace item and the platform item, got %v", seen)+ }+ if seen["elsewhere"] {+ t.Fatal("another workspace's alert must not appear on this banner")+ }+}++// One user's inbox is not another's, including for mark-read and dismiss.+func TestInboxIsScopedToTheUser(t *testing.T) {+ db := notificationDB(t)+ tx := db.Begin()+ t.Cleanup(func() { tx.Rollback() })++ mine := createUser(t, tx, "[email protected]")+ theirs := createUser(t, tx, "[email protected]")+ ws := uintPtr(4007)+ repo := &NotificationRepository{db: tx}++ n := mustUpsert(t, repo, alert(theirs, ws, "n=1", "not yours"))++ if err := repo.Dismiss(mine, []uint{n.ID}); err != nil {+ t.Fatalf("dismiss: %v", err)+ }+ if reload(t, tx, n.ID).DismissedAt != nil {+ t.Fatal("a user must not be able to dismiss another user's notification")+ }++ if err := repo.MarkRead(mine, []uint{n.ID}); err != nil {+ t.Fatalf("mark read: %v", err)+ }+ if reload(t, tx, n.ID).ReadAt != nil {+ t.Fatal("a user must not be able to read another user's notification")+ }+}++// Pruning keeps live conditions whatever their age; an unresolved alert is+// still true however long it has been open.+func TestPruneKeepsOpenItems(t *testing.T) {+ db := notificationDB(t)+ tx := db.Begin()+ t.Cleanup(func() { tx.Rollback() })++ userID := createUser(t, tx, "[email protected]")+ ws := uintPtr(4008)+ repo := &NotificationRepository{db: tx}++ open := mustUpsert(t, repo, alert(userID, ws, "n=1", "still true"))+ settled := mustUpsert(t, repo, &models.Notification{+ UserID: userID,+ WorkspaceID: ws,+ Kind: models.NotificationKindAlert,+ Category: models.NotificationCategorySecurity,+ Severity: models.NotificationWarning,+ Title: "settled",+ DedupKey: "security:expiring-api-keys",+ Fingerprint: "n=1",+ })+ if err := repo.Dismiss(userID, []uint{settled.ID}); err != nil {+ t.Fatalf("dismiss: %v", err)+ }++ ancient := open.CreatedAt.AddDate(0, 0, 1)+ if _, err := repo.Prune(ancient); err != nil {+ t.Fatalf("prune: %v", err)+ }++ if err := tx.First(&models.Notification{}, open.ID).Error; err != nil {+ t.Fatalf("an open item must survive pruning: %v", err)+ }+ if err := tx.First(&models.Notification{}, settled.ID).Error; err == nil {+ t.Fatal("a settled item older than the cutoff must be pruned")+ }+}diff --git a/web/src/api/admin.ts b/web/src/api/admin.tsindex 00b05dd..6873178 100644--- a/web/src/api/admin.ts+++ b/web/src/api/admin.ts@@ -4,8 +4,19 @@ import type {UserDetailMetrics, CronJob, AdminWorkspace, UpdateInfo,Domain, AdminDomainRow, AdminDomainDetail, AdminDomainVerifyResult,} from './types'+import type { Announcement, AnnouncementInput } from './inbox'export const adminApi = {+ // ---- Announcements (platform-wide in-app notices) ----+ listAnnouncements(page = 0, size = 20) {+ return api.get<PaginatedResponse<Announcement>>('/admin/announcements', { params: { page, size } })+ },+ createAnnouncement(input: AnnouncementInput) {+ return api.post<ApiResponse<Announcement>>('/admin/announcements', input)+ },+ retractAnnouncement(id: number) {+ return api.delete<ApiResponse<{ message: string }>>(`/admin/announcements/${id}`)+ },listUsers(page = 0, size = 20, search = '') {return api.get<PaginatedResponse<User>>('/admin/users', { params: { page, size, search: search || undefined } })},diff --git a/web/src/api/inbox.ts b/web/src/api/inbox.tsnew file mode 100644index 0000000..0fd21d4--- /dev/null+++ b/web/src/api/inbox.ts@@ -0,0 +1,85 @@+import api from "./client";+import type { ApiResponse } from "./types";++export type NotificationSeverity = "info" | "warning" | "critical";+export type NotificationKind = "alert" | "announcement";+export type NotificationCategory =+ | "domains"+ | "deliverability"+ | "security"+ | "messages"+ | "platform";++export interface InboxNotification {+ id: number;+ user_id: number;+ workspace_id?: number | null;+ kind: NotificationKind;+ category: NotificationCategory;+ severity: NotificationSeverity;+ title: string;+ body: string;+ link?: string;+ action_text?: string;+ dedup_key: string;+ read_at?: string | null;+ dismissed_at?: string | null;+ resolved_at?: string | null;+ created_at: string;+}++export interface NotificationCounts {+ unread: number;+ open: number;+}++export interface InboxListParams {+ unread?: boolean;+ open?: boolean;+ category?: NotificationCategory;+ before?: number;+ limit?: number;+ scoped?: boolean;+}++const base = "/users/me/notifications";++export const inboxApi = {+ list: (params: InboxListParams = {}) =>+ api.get<ApiResponse<InboxNotification[]>>(base, {+ params: {+ ...(params.unread ? { unread: true } : {}),+ ...(params.open ? { open: true } : {}),+ ...(params.category ? { category: params.category } : {}),+ ...(params.before ? { before: params.before } : {}),+ ...(params.limit ? { limit: params.limit } : {}),+ ...(params.scoped ? { scoped: true } : {}),+ },+ }),+ counts: () => api.get<ApiResponse<NotificationCounts>>(`${base}/counts`),+ banner: () => api.get<ApiResponse<InboxNotification[]>>(`${base}/banner`),+ markRead: (ids: number[]) => api.post<ApiResponse<{ message: string }>>(`${base}/read`, { ids }),+ markAllRead: () => api.post<ApiResponse<{ message: string }>>(`${base}/read-all`),+ dismiss: (ids: number[]) => api.post<ApiResponse<{ message: string }>>(`${base}/dismiss`, { ids }),+ dismissAll: () => api.post<ApiResponse<{ message: string }>>(`${base}/dismiss-all`),+};++export interface Announcement {+ id: number;+ title: string;+ message: string;+ link?: string;+ severity: NotificationSeverity;+ created_by: number;+ author_name: string;+ recipients: number;+ sent_at?: string | null;+ created_at: string;+}++export interface AnnouncementInput {+ title: string;+ message: string;+ link?: string;+ severity: NotificationSeverity;+}diff --git a/web/src/components/NotificationBell.vue b/web/src/components/NotificationBell.vuenew file mode 100644index 0000000..0713ff0--- /dev/null+++ b/web/src/components/NotificationBell.vue@@ -0,0 +1,303 @@+<script setup lang="ts">+import { onBeforeUnmount, onMounted, ref } from "vue";+import { storeToRefs } from "pinia";+import { useRouter } from "vue-router";+import { useInboxStore } from "../stores/inbox";+import type { InboxNotification } from "../api/inbox";++const store = useInboxStore();+const { unread, badge, items, loading } = storeToRefs(store);+const router = useRouter();++const open = ref(false);++function toggle() {+ open.value = !open.value;+ if (open.value) void store.loadRecent();+}++async function activate(n: InboxNotification) {+ if (!n.read_at) await store.markRead([n.id]);+ open.value = false;+ if (n.link) router.push(n.link);+}++function onDocClick(e: MouseEvent) {+ if (open.value && !(e.target as HTMLElement).closest?.(".bell")) open.value = false;+}++function timeAgo(iso: string): string {+ const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);+ if (s < 60) return "just now";+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;+ if (s < 2592000) return `${Math.floor(s / 86400)}d ago`;+ return new Date(iso).toLocaleDateString();+}++onMounted(() => {+ store.start();+ document.addEventListener("click", onDocClick);+});++onBeforeUnmount(() => {+ document.removeEventListener("click", onDocClick);+ // The bell mounts with the authenticated layout, so unmounting means leaving+ // it — a logout, usually. Clear the inbox rather than just stopping the poll:+ // if a different account signs in without a reload, the previous user's+ // notifications must not still be sitting in the store.+ store.reset();+});+</script>++<template>+ <div class="bell">+ <button+ class="bell-btn"+ type="button"+ :aria-label="unread > 0 ? `Notifications, ${unread} unread` : 'Notifications'"+ :aria-expanded="open"+ @click.stop="toggle"+ >+ <svg+ width="18"+ height="18"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="1.8"+ stroke-linecap="round"+ stroke-linejoin="round"+ aria-hidden="true"+ >+ <path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9" />+ <path d="M13.73 21a2 2 0 01-3.46 0" />+ </svg>+ <span v-if="unread > 0" class="bell-badge">{{ badge }}</span>+ </button>++ <div v-if="open" class="bell-panel" @click.stop>+ <div class="bell-head">+ <span>Notifications</span>+ <button v-if="unread > 0" class="bell-link" type="button" @click="store.markAllRead()">+ Mark all read+ </button>+ </div>++ <div class="bell-list">+ <div v-if="loading && !items.length" class="bell-empty">+ <div class="spinner"></div>+ </div>+ <div v-else-if="!items.length" class="bell-empty">+ <p>You're all caught up.</p>+ </div>+ <button+ v-for="n in items"+ :key="n.id"+ type="button"+ class="bell-item"+ :class="{ unread: !n.read_at }"+ @click="activate(n)"+ >+ <span class="bell-sev" :class="`sev-${n.severity}`" aria-hidden="true"></span>+ <span class="bell-body">+ <span class="bell-title">{{ n.title }}</span>+ <span class="bell-sub">{{ n.body }}</span>+ <span class="bell-meta">+ {{ timeAgo(n.created_at) }}+ <template v-if="n.resolved_at"> · resolved</template>+ </span>+ </span>+ </button>+ </div>++ <div class="bell-foot">+ <RouterLink to="/notifications" class="bell-link" @click="open = false">+ View all notifications+ </RouterLink>+ </div>+ </div>+ </div>+</template>++<style scoped>+.bell {+ position: relative;+}++.bell-btn {+ position: relative;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 34px;+ height: 34px;+ border-radius: 8px;+ border: 1px solid transparent;+ background: none;+ color: var(--text-secondary);+ cursor: pointer;+}++.bell-btn:hover {+ background: var(--bg-hover);+ color: var(--text-primary);+}++.bell-badge {+ position: absolute;+ top: 2px;+ right: 1px;+ min-width: 16px;+ height: 16px;+ padding: 0 4px;+ border-radius: 8px;+ background: var(--danger-600);+ color: #fff;+ font-size: 10px;+ font-weight: 700;+ line-height: 16px;+ text-align: center;+}++.bell-panel {+ position: absolute;+ top: calc(100% + 8px);+ right: 0;+ width: 360px;+ max-width: calc(100vw - 24px);+ background: var(--bg-primary);+ border: 1px solid var(--border-primary);+ border-radius: var(--radius-lg);+ box-shadow: var(--shadow-lg);+ z-index: 60;+ overflow: hidden;+}++.bell-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 12px 14px;+ border-bottom: 1px solid var(--border-secondary);+ font-size: 13px;+ font-weight: 600;+ color: var(--text-primary);+}++.bell-link {+ border: 0;+ background: none;+ padding: 0;+ font: inherit;+ font-size: 12px;+ font-weight: 500;+ color: var(--primary-600);+ cursor: pointer;+ text-decoration: none;+}++.bell-link:hover {+ text-decoration: underline;+}++.bell-list {+ max-height: 380px;+ overflow-y: auto;+}++.bell-empty {+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 32px 14px;+ font-size: 13px;+ color: var(--text-tertiary);+}++.bell-item {+ display: flex;+ gap: 10px;+ width: 100%;+ padding: 12px 14px;+ border: 0;+ border-bottom: 1px solid var(--border-secondary);+ background: none;+ font: inherit;+ text-align: left;+ cursor: pointer;+}++.bell-item:last-child {+ border-bottom: 0;+}++.bell-item:hover {+ background: var(--bg-hover);+}++.bell-item.unread {+ background: var(--primary-50);+}++.bell-item.unread:hover {+ background: var(--bg-hover);+}++.bell-sev {+ flex: none;+ width: 8px;+ height: 8px;+ margin-top: 5px;+ border-radius: 50%;+ background: var(--text-tertiary);+}++.sev-warning {+ background: var(--warning-500);+}++.sev-critical {+ background: var(--danger-600);+}++.sev-info {+ background: var(--primary-500);+}++.bell-body {+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+}++.bell-title {+ font-size: 13px;+ font-weight: 600;+ color: var(--text-primary);+}++.bell-sub {+ font-size: 12px;+ color: var(--text-secondary);+ line-height: 1.5;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+}++.bell-meta {+ font-size: 11px;+ color: var(--text-tertiary);+ margin-top: 2px;+}++.bell-foot {+ padding: 10px 14px;+ border-top: 1px solid var(--border-secondary);+ text-align: center;+}+</style>diff --git a/web/src/layouts/DashboardLayout.vue b/web/src/layouts/DashboardLayout.vueindex 89adcef..1462b88 100644--- a/web/src/layouts/DashboardLayout.vue+++ b/web/src/layouts/DashboardLayout.vue@@ -6,6 +6,7 @@ import { useThemeStore } from '../stores/theme'import { useWorkspaceStore } from '../stores/workspace'import { infoApi, type AppInfo } from '../api/info'import { adminApi } from '../api/admin'+import NotificationBell from '../components/NotificationBell.vue'import type { UpdateInfo } from '../api/types'import EmailVerificationBanner from '../components/EmailVerificationBanner.vue'@@ -228,6 +229,7 @@ const navSections: NavSection[] = [{ name: 'Plans', path: '/admin/plans', icon: 'layers' },{ name: 'Shared Servers', path: '/admin/servers', icon: 'server' },{ name: 'Domains', path: '/admin/domains', icon: 'globe' },+ { name: 'Announcements', path: '/admin/announcements', icon: 'bell' },{ name: 'OAuth', path: '/admin/oauth', icon: 'shield' },{ name: 'Jobs', path: '/admin/jobs', icon: 'clock' },{ name: 'Events', path: '/admin/events', icon: 'zap' },@@ -344,6 +346,7 @@ function getIcon(name: string): string {'key': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M15.5 2.5l-2 2m1 1l-2 2-3-3 2-2m-3.18 3.18a4 4 0 10-5.64 5.64 4 4 0 005.64-5.64z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>','file-text': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M10.5 1.5H4.5a1.5 1.5 0 00-1.5 1.5v12a1.5 1.5 0 001.5 1.5h9a1.5 1.5 0 001.5-1.5V6l-4.5-4.5z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M10.5 1.5V6H15M12 9.75H6M12 12.75H6M7.5 6.75H6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>','server': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><rect x="2" y="2" width="14" height="5" rx="1.5" stroke="currentColor" stroke-width="1.5"/><rect x="2" y="11" width="14" height="5" rx="1.5" stroke="currentColor" stroke-width="1.5"/><circle cx="5" cy="4.5" r="0.75" fill="currentColor"/><circle cx="5" cy="13.5" r="0.75" fill="currentColor"/></svg>',+ 'bell': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M13.5 6a4.5 4.5 0 10-9 0c0 5.25-2.25 6.75-2.25 6.75h13.5S13.5 11.25 13.5 6z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M10.3 15.75a1.5 1.5 0 01-2.6 0" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>','globe': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.5"/><path d="M2 9h14M9 2a11.05 11.05 0 013 7 11.05 11.05 0 01-3 7 11.05 11.05 0 01-3-7 11.05 11.05 0 013-7z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>','link': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M7.5 10.5a3.75 3.75 0 005.3.45l2.25-2.25a3.75 3.75 0 00-5.3-5.3l-1.29 1.28" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M10.5 7.5a3.75 3.75 0 00-5.3-.45L2.96 9.3a3.75 3.75 0 005.3 5.3l1.28-1.28" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>','alert-triangle': '<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M7.86 2.87L1.21 14.25a1.31 1.31 0 001.14 1.97h13.3a1.31 1.31 0 001.14-1.97L10.14 2.87a1.31 1.31 0 00-2.28 0z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M9 6.75v3M9 12.75h.007" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>',@@ -472,6 +475,7 @@ function getIcon(name: string): string {</button></div><div class="topbar-right">+ <NotificationBell /><div class="user-menu" @click="userMenuOpen = !userMenuOpen"><div class="user-avatar">{{ user?.name?.charAt(0)?.toUpperCase() || '?' }}</div><div class="user-menu-info">diff --git a/web/src/router/index.ts b/web/src/router/index.tsindex 723a1d9..cf61ef9 100644--- a/web/src/router/index.ts+++ b/web/src/router/index.ts@@ -101,12 +101,14 @@ const routes = [{ path: 'profile', name: 'profile', component: () => import('../views/auth/Profile.vue'), meta: { title: 'Profile' } },{ path: 'change-password', redirect: '/profile' },// Admin+ { path: 'notifications', name: 'notifications', component: () => import('../views/Notifications.vue'), meta: { title: 'Notifications' } },{ path: 'admin/users', name: 'admin-users', component: () => import('../views/admin/Users.vue'), meta: { admin: true, title: 'Admin · Users' } },{ path: 'admin/users/:id', name: 'admin-user-detail', component: () => import('../views/admin/UserDetail.vue'), meta: { admin: true, title: 'Admin · User' } },{ path: 'admin/dashboard', name: 'admin-dashboard', component: () => import('../views/admin/Dashboard.vue'), meta: { admin: true, title: 'Admin · Dashboard' } },// The page was called Metrics until it grew a health summary and quick// links; keep the old path working for bookmarks and muscle memory.{ path: 'admin/metrics', redirect: '/admin/dashboard' },+ { path: 'admin/announcements', name: 'admin-announcements', component: () => import('../views/admin/Announcements.vue'), meta: { admin: true, title: 'Admin · Announcements' } },{ path: 'admin/domains', name: 'admin-domains', component: () => import('../views/admin/Domains.vue'), meta: { admin: true, title: 'Admin · Domains' } },{ path: 'admin/domains/:id', name: 'admin-domain-detail', component: () => import('../views/admin/DomainDetail.vue'), meta: { admin: true, title: 'Admin · Domain' } },{ path: 'admin/events', name: 'admin-events', component: () => import('../views/admin/Events.vue'), meta: { admin: true, title: 'Admin · Events' } },diff --git a/web/src/stores/inbox.ts b/web/src/stores/inbox.tsnew file mode 100644index 0000000..a898f55--- /dev/null+++ b/web/src/stores/inbox.ts@@ -0,0 +1,125 @@+import { defineStore } from "pinia";+import { computed, ref } from "vue";+import { inboxApi, type InboxNotification } from "../api/inbox";++// The user's in-app inbox: the header bell and the dashboard alert banner read+// from here. Distinct from stores/notification, which is transient toasts.+//+// There is no push channel; the counts are polled and the banner refreshes with+// the dashboard. An inbox item is never urgent enough to justify a socket, and a+// poll degrades gracefully when the tab is backgrounded.+const POLL_MS = 60_000;++export const useInboxStore = defineStore("inbox", () => {+ const unread = ref(0);+ const items = ref<InboxNotification[]>([]);+ const banner = ref<InboxNotification[]>([]);+ const loading = ref(false);+ let timer: ReturnType<typeof setInterval> | null = null;++ const badge = computed(() => (unread.value > 99 ? "99+" : String(unread.value)));++ async function loadCounts() {+ try {+ unread.value = (await inboxApi.counts()).data.data?.unread ?? 0;+ } catch {+ /* transient; the badge is not worth an error toast */+ }+ }++ async function loadRecent(limit = 20) {+ loading.value = true;+ try {+ items.value = (await inboxApi.list({ limit })).data.data ?? [];+ } catch {+ items.value = [];+ } finally {+ loading.value = false;+ }+ }++ async function loadBanner() {+ try {+ banner.value = (await inboxApi.banner()).data.data ?? [];+ } catch {+ banner.value = [];+ }+ }++ function start() {+ if (timer) return;+ void loadCounts();+ timer = setInterval(() => void loadCounts(), POLL_MS);+ }++ function stop() {+ if (timer) clearInterval(timer);+ timer = null;+ }++ function stamp(list: InboxNotification[], ids: number[], field: "read_at" | "dismissed_at") {+ const now = new Date().toISOString();+ for (const n of list) {+ if (ids.includes(n.id) && !n[field]) n[field] = now;+ }+ }++ async function markRead(ids: number[]) {+ if (!ids.length) return;+ stamp(items.value, ids, "read_at");+ await inboxApi.markRead(ids);+ await loadCounts();+ }++ async function markAllRead() {+ stamp(+ items.value,+ items.value.map((n) => n.id),+ "read_at"+ );+ unread.value = 0;+ await inboxApi.markAllRead();+ }++ // Dismissal removes the item from the banner optimistically. The server binds+ // it to the condition as it currently stands, so it comes back on its own if+ // the condition materially worsens.+ async function dismiss(id: number) {+ banner.value = banner.value.filter((n) => n.id !== id);+ stamp(items.value, [id], "dismissed_at");+ stamp(items.value, [id], "read_at");+ await inboxApi.dismiss([id]);+ await loadCounts();+ }++ async function dismissAll() {+ banner.value = [];+ await inboxApi.dismissAll();+ await loadCounts();+ }++ function reset() {+ stop();+ unread.value = 0;+ items.value = [];+ banner.value = [];+ }++ return {+ unread,+ badge,+ items,+ banner,+ loading,+ start,+ stop,+ reset,+ loadCounts,+ loadRecent,+ loadBanner,+ markRead,+ markAllRead,+ dismiss,+ dismissAll,+ };+});diff --git a/web/src/views/Notifications.vue b/web/src/views/Notifications.vuenew file mode 100644index 0000000..bb8cad2--- /dev/null+++ b/web/src/views/Notifications.vue@@ -0,0 +1,379 @@+<script setup lang="ts">+import { computed, onMounted, ref } from "vue";+import { useRouter } from "vue-router";+import { inboxApi, type InboxNotification, type NotificationCategory } from "../api/inbox";+import { useInboxStore } from "../stores/inbox";+import { useNotificationStore } from "../stores/notification";+import { apiMessage } from "../composables/apiError";++const router = useRouter();+const store = useInboxStore();+const notify = useNotificationStore();++const items = ref<InboxNotification[]>([]);+const loading = ref(true);+const loadingMore = ref(false);+const exhausted = ref(false);+const filter = ref<"all" | "unread" | "open">("all");+const category = ref<NotificationCategory | "">("");++const PAGE = 30;++const categories: { value: NotificationCategory | ""; label: string }[] = [+ { value: "", label: "All categories" },+ { value: "platform", label: "Platform" },+ { value: "domains", label: "Domains" },+ { value: "deliverability", label: "Deliverability" },+ { value: "security", label: "Security" },+ { value: "messages", label: "Messages" },+];++const unreadCount = computed(() => items.value.filter((n) => !n.read_at).length);++function params(before?: number) {+ return {+ unread: filter.value === "unread",+ open: filter.value === "open",+ category: category.value || undefined,+ before,+ limit: PAGE,+ };+}++async function load() {+ loading.value = true;+ exhausted.value = false;+ try {+ const res = await inboxApi.list(params());+ items.value = res.data.data ?? [];+ exhausted.value = items.value.length < PAGE;+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to load notifications"));+ } finally {+ loading.value = false;+ }+}++async function loadMore() {+ const last = items.value[items.value.length - 1];+ if (!last || loadingMore.value) return;+ loadingMore.value = true;+ try {+ const res = await inboxApi.list(params(last.id));+ const page = res.data.data ?? [];+ items.value = items.value.concat(page);+ exhausted.value = page.length < PAGE;+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to load more"));+ } finally {+ loadingMore.value = false;+ }+}++function setFilter(f: "all" | "unread" | "open") {+ filter.value = f;+ void load();+}++async function open(n: InboxNotification) {+ if (!n.read_at) {+ n.read_at = new Date().toISOString();+ await store.markRead([n.id]);+ }+ if (n.link) router.push(n.link);+}++async function markAllRead() {+ try {+ await store.markAllRead();+ const now = new Date().toISOString();+ for (const n of items.value) if (!n.read_at) n.read_at = now;+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to mark all read"));+ }+}++async function dismiss(n: InboxNotification) {+ try {+ await store.dismiss(n.id);+ const now = new Date().toISOString();+ n.dismissed_at = now;+ n.read_at = n.read_at || now;+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to dismiss"));+ }+}++function state(n: InboxNotification) {+ if (n.resolved_at) return { label: "Resolved", cls: "badge-success" };+ if (n.dismissed_at) return { label: "Dismissed", cls: "badge-neutral" };+ return { label: "Open", cls: n.severity === "critical" ? "badge-danger" : "badge-warning" };+}++function formatDate(iso: string) {+ return new Date(iso).toLocaleString();+}++onMounted(load);+</script>++<template>+ <div>+ <div class="page-header">+ <div>+ <h1>Notifications</h1>+ <p class="page-subtitle">+ What Posta noticed about your workspaces, and notices from the platform.+ </p>+ </div>+ <div class="header-actions">+ <button class="btn btn-secondary" :disabled="!unreadCount" @click="markAllRead">+ Mark all read+ </button>+ </div>+ </div>++ <div class="toolbar">+ <div class="chips">+ <button+ v-for="f in (['all', 'unread', 'open'] as const)"+ :key="f"+ class="chip"+ :class="{ active: filter === f }"+ type="button"+ @click="setFilter(f)"+ >+ {{ f === "all" ? "All" : f === "unread" ? "Unread" : "Needs attention" }}+ </button>+ </div>+ <select v-model="category" class="form-select" @change="load">+ <option v-for="c in categories" :key="c.value" :value="c.value">{{ c.label }}</option>+ </select>+ </div>++ <div v-if="loading" class="loading-page"><div class="spinner"></div></div>++ <div v-else-if="!items.length" class="card">+ <div class="empty-state">+ <h3>Nothing here</h3>+ <p>+ Posta writes to this inbox when something about a workspace needs attention — an+ unverified domain, a climbing bounce rate, an API key about to lapse.+ </p>+ </div>+ </div>++ <div v-else class="card">+ <ul class="feed">+ <li v-for="n in items" :key="n.id" class="row" :class="{ unread: !n.read_at }">+ <span class="dot" :class="`sev-${n.severity}`" aria-hidden="true"></span>+ <div class="row-body">+ <div class="row-head">+ <button class="row-title" type="button" @click="open(n)">{{ n.title }}</button>+ <span class="badge" :class="state(n).cls">{{ state(n).label }}</span>+ </div>+ <p class="row-text">{{ n.body }}</p>+ <div class="row-meta">+ <span>{{ formatDate(n.created_at) }}</span>+ <span class="sep">·</span>+ <span>{{ n.category }}</span>+ <template v-if="n.link">+ <span class="sep">·</span>+ <button class="row-link" type="button" @click="open(n)">+ {{ n.action_text || "Open" }}+ </button>+ </template>+ </div>+ </div>+ <button+ v-if="!n.dismissed_at && !n.resolved_at"+ class="row-dismiss"+ type="button"+ :aria-label="`Dismiss: ${n.title}`"+ title="Dismiss. Comes back if the condition gets worse."+ @click="dismiss(n)"+ >+ Dismiss+ </button>+ </li>+ </ul>++ <div v-if="!exhausted" class="feed-foot">+ <button class="btn btn-secondary" :disabled="loadingMore" @click="loadMore">+ {{ loadingMore ? "Loading…" : "Load more" }}+ </button>+ </div>+ </div>+ </div>+</template>++<style scoped>+.page-subtitle {+ font-size: 13px;+ color: var(--text-tertiary);+ margin-top: 4px;+}++.toolbar {+ display: flex;+ align-items: center;+ gap: 12px;+ flex-wrap: wrap;+ margin-bottom: 16px;+}++.chips {+ display: flex;+ gap: 6px;+}++.chip {+ padding: 6px 12px;+ border: 1px solid var(--border-primary);+ border-radius: 999px;+ background: var(--bg-primary);+ font-size: 12px;+ font-weight: 500;+ color: var(--text-secondary);+ cursor: pointer;+}++.chip.active {+ background: var(--primary-600);+ border-color: var(--primary-600);+ color: #fff;+}++.toolbar .form-select {+ width: auto;+ min-width: 180px;+}++.feed {+ list-style: none;+ margin: 0;+ padding: 0;+}++.row {+ display: flex;+ align-items: flex-start;+ gap: 12px;+ padding: 14px 16px;+ border-bottom: 1px solid var(--border-secondary);+}++.row:last-child {+ border-bottom: 0;+}++.row.unread {+ background: var(--primary-50);+}++.dot {+ flex: none;+ width: 8px;+ height: 8px;+ margin-top: 6px;+ border-radius: 50%;+ background: var(--text-tertiary);+}++.sev-warning {+ background: var(--warning-500);+}++.sev-critical {+ background: var(--danger-600);+}++.sev-info {+ background: var(--primary-500);+}++.row-body {+ flex: 1;+ min-width: 0;+}++.row-head {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-wrap: wrap;+}++.row-title {+ border: 0;+ background: none;+ padding: 0;+ font: inherit;+ font-size: 14px;+ font-weight: 600;+ color: var(--text-primary);+ cursor: pointer;+ text-align: left;+}++.row-title:hover {+ color: var(--primary-600);+}++.row-text {+ margin: 4px 0 0;+ font-size: 13px;+ color: var(--text-secondary);+ line-height: 1.6;+}++.row-meta {+ display: flex;+ align-items: center;+ gap: 6px;+ flex-wrap: wrap;+ margin-top: 6px;+ font-size: 12px;+ color: var(--text-tertiary);+}++.sep {+ color: var(--border-primary);+}++.row-link {+ border: 0;+ background: none;+ padding: 0;+ font: inherit;+ font-size: 12px;+ color: var(--primary-600);+ cursor: pointer;+}++.row-link:hover {+ text-decoration: underline;+}++.row-dismiss {+ flex: none;+ border: 0;+ background: none;+ padding: 0;+ font: inherit;+ font-size: 12px;+ color: var(--text-tertiary);+ cursor: pointer;+}++.row-dismiss:hover {+ color: var(--text-primary);+ text-decoration: underline;+}++.feed-foot {+ padding: 14px 16px;+ text-align: center;+ border-top: 1px solid var(--border-secondary);+}+</style>diff --git a/web/src/views/admin/Announcements.vue b/web/src/views/admin/Announcements.vuenew file mode 100644index 0000000..8277354--- /dev/null+++ b/web/src/views/admin/Announcements.vue@@ -0,0 +1,210 @@+<script setup lang="ts">+import { onMounted, ref } from "vue";+import { adminApi } from "../../api/admin";+import type { Announcement, NotificationSeverity } from "../../api/inbox";+import { useNotificationStore } from "../../stores/notification";+import { useConfirm } from "../../composables/useConfirm";+import { apiMessage } from "../../composables/apiError";++const notify = useNotificationStore();+const { confirm } = useConfirm();++const items = ref<Announcement[]>([]);+const loading = ref(true);+const sending = ref(false);++const title = ref("");+const message = ref("");+const link = ref("");+const severity = ref<NotificationSeverity>("info");++async function load() {+ loading.value = true;+ try {+ items.value = (await adminApi.listAnnouncements(0, 50)).data.data ?? [];+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to load announcements"));+ } finally {+ loading.value = false;+ }+}++async function send() {+ if (!title.value.trim()) return;+ const confirmed = await confirm({+ title: "Broadcast to every user",+ message:+ "This puts the notice in every active user's inbox immediately. You can retract it afterwards, which also removes it from their inboxes.",+ confirmText: "Broadcast",+ });+ if (!confirmed) return;++ sending.value = true;+ try {+ const res = await adminApi.createAnnouncement({+ title: title.value.trim(),+ message: message.value.trim(),+ link: link.value.trim() || undefined,+ severity: severity.value,+ });+ notify.success(`Delivered to ${res.data.data.recipients} user${res.data.data.recipients === 1 ? "" : "s"}`);+ title.value = "";+ message.value = "";+ link.value = "";+ severity.value = "info";+ await load();+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to broadcast"));+ } finally {+ sending.value = false;+ }+}++async function retract(a: Announcement) {+ const confirmed = await confirm({+ title: "Retract announcement",+ message: `"${a.title}" will be removed from every inbox it was delivered to.`,+ confirmText: "Retract",+ variant: "danger",+ });+ if (!confirmed) return;+ try {+ await adminApi.retractAnnouncement(a.id);+ notify.success("Announcement retracted");+ await load();+ } catch (e: any) {+ notify.error(apiMessage(e, "Failed to retract"));+ }+}++function formatDate(iso?: string | null) {+ return iso ? new Date(iso).toLocaleString() : "—";+}++onMounted(load);+</script>++<template>+ <div>+ <div class="page-header">+ <div>+ <h1>Announcements</h1>+ <p class="page-subtitle">+ Put a notice in every user's in-app inbox — planned maintenance, a breaking upgrade, a+ policy change.+ </p>+ </div>+ </div>++ <div class="card" style="margin-bottom: 20px">+ <div class="card-header"><h2>New announcement</h2></div>+ <div class="card-body">+ <div class="form-group">+ <label class="form-label" for="ann-title">Title</label>+ <input id="ann-title" v-model="title" class="form-input" maxlength="200" placeholder="Scheduled maintenance on Sunday" />+ </div>+ <div class="form-group">+ <label class="form-label" for="ann-message">Message</label>+ <textarea id="ann-message" v-model="message" class="form-input" rows="3" maxlength="2000"+ placeholder="Posta will be unavailable between 02:00 and 03:00 UTC while the database is upgraded."></textarea>+ </div>+ <div class="form-row">+ <div class="form-group">+ <label class="form-label" for="ann-link">Link</label>+ <input id="ann-link" v-model="link" class="form-input" placeholder="/status (optional)" />+ <span class="form-hint">Where the notice takes the reader. Leave empty for a notice with no action.</span>+ </div>+ <div class="form-group">+ <label class="form-label" for="ann-sev">Severity</label>+ <select id="ann-sev" v-model="severity" class="form-select">+ <option value="info">Info</option>+ <option value="warning">Warning</option>+ <option value="critical">Critical</option>+ </select>+ <span class="form-hint">Warning and critical also appear on the workspace dashboard.</span>+ </div>+ </div>+ <button class="btn btn-primary" :disabled="sending || !title.trim()" @click="send">+ {{ sending ? "Broadcasting…" : "Broadcast" }}+ </button>+ </div>+ </div>++ <div class="card">+ <div class="card-header"><h2>Sent</h2></div>+ <div v-if="loading" class="loading-page"><div class="spinner"></div></div>+ <div v-else-if="!items.length" class="empty-state">+ <h3>Nothing broadcast yet</h3>+ </div>+ <table v-else>+ <thead>+ <tr>+ <th>Title</th>+ <th>Severity</th>+ <th>Recipients</th>+ <th>Sent</th>+ <th>By</th>+ <th></th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="a in items" :key="a.id">+ <td>+ <div class="ann-title">{{ a.title }}</div>+ <div class="ann-body">{{ a.message }}</div>+ </td>+ <td>+ <span class="badge" :class="a.severity === 'critical' ? 'badge-danger' : a.severity === 'warning' ? 'badge-warning' : 'badge-neutral'">+ {{ a.severity }}+ </span>+ </td>+ <td>{{ a.recipients }}</td>+ <td>{{ formatDate(a.sent_at) }}</td>+ <td>{{ a.author_name || `#${a.created_by}` }}</td>+ <td class="right">+ <button class="btn btn-secondary btn-sm" @click="retract(a)">Retract</button>+ </td>+ </tr>+ </tbody>+ </table>+ </div>+ </div>+</template>++<style scoped>+.page-subtitle {+ font-size: 13px;+ color: var(--text-tertiary);+ margin-top: 4px;+}++.form-row {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));+ gap: 16px;+}++.ann-title {+ font-weight: 600;+ color: var(--text-primary);+}++.ann-body {+ font-size: 12px;+ color: var(--text-tertiary);+ margin-top: 2px;+ max-width: 460px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.right {+ text-align: right;+}++.btn-sm {+ padding: 5px 12px;+ font-size: 12px;+}+</style>diff --git a/web/src/views/dashboard/HealthAlerts.vue b/web/src/views/dashboard/HealthAlerts.vueindex 2f8b97c..3ab8a52 100644--- a/web/src/views/dashboard/HealthAlerts.vue+++ b/web/src/views/dashboard/HealthAlerts.vue@@ -1,91 +1,41 @@<script setup lang="ts">-import { computed } from "vue";+import { computed, onMounted, watch } from "vue";+import { storeToRefs } from "pinia";import { useRouter } from "vue-router";+import { useInboxStore } from "../../stores/inbox";+import type { InboxNotification } from "../../api/inbox";import type { DashboardStats } from "../../api/types";+const props = defineProps<{ stats: DashboardStats }>();+const router = useRouter();+const store = useInboxStore();+const { banner } = storeToRefs(store);++const alerts = computed(() => banner.value);++function tone(n: InboxNotification) {+ return n.severity === "critical" ? "danger" : n.severity === "warning" ? "warning" : "info";+}-interface Alert {- key: string;- tone: "danger" | "warning";- title: string;- detail: string;- action: string;- to: string;+function act(n: InboxNotification) {+ if (n.link) router.push(n.link);}-const alerts = computed<Alert[]>(() => {- const s = props.stats;- const out: Alert[] = [];-- if (s.unverified_domains > 0) {- out.push({- key: "domains",- tone: "warning",- title: `${s.unverified_domains} domain${s.unverified_domains === 1 ? "" : "s"} not verified`,- detail:- "Mail from an unverified domain is far more likely to be filtered, and some routes refuse to send from one at all.",- action: "Verify domains",- to: "/domains",- });- }-- if (s.total_emails >= 20 && s.bounce_rate >= 5) {- out.push({- key: "bounces",- tone: "danger",- title: `Bounce rate is ${s.bounce_rate.toFixed(1)}%`,- detail:- "Sustained bounces above 5% damage sender reputation. Clean the recipient list before sending more.",- action: "Review bounces",- to: "/bounces",- });- }-- if (s.total_emails >= 20 && s.failure_rate >= 10) {- out.push({- key: "failures",- tone: "danger",- title: `${s.failure_rate.toFixed(1)}% of sends are failing`,- detail:- "Check the SMTP server configuration and the most recent failures for a common cause.",- action: "View failed emails",- to: "/emails?status=failed",- });- }-- if (s.expiring_api_keys > 0) {- out.push({- key: "keys",- tone: "warning",- title: `${s.expiring_api_keys} API key${s.expiring_api_keys === 1 ? "" : "s"} expiring within 7 days`,- detail: "Rotate them before they lapse, or the integrations using them will start failing.",- action: "Manage API keys",- to: "/api-keys",- });- }-- if (s.features?.messages && s.unread_messages > 0) {- out.push({- key: "messages",- tone: "warning",- title: `${s.unread_messages} unread message${s.unread_messages === 1 ? "" : "s"}`,- detail: "Someone filled in one of your web forms and is waiting for a reply.",- action: "Open inbox",- to: "/messages",- });- }-- return out;-});--defineExpose({ alerts });+onMounted(() => void store.loadBanner());+watch(() => props.stats, () => void store.loadBanner());</script><template><div v-if="alerts.length" class="alerts">- <div v-for="a in alerts" :key="a.key" class="alert-banner" :class="`alert-${a.tone}`" role="status">+ <div+ v-for="a in alerts"+ :key="a.id"+ class="alert-banner"+ :class="`alert-${tone(a)}`"+ role="status"+ ><svgclass="ab-icon"viewBox="0 0 24 24"@@ -96,15 +46,35 @@ defineExpose({ alerts });stroke-linejoin="round"aria-hidden="true">- <path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />- <line x1="12" y1="9" x2="12" y2="13" />- <line x1="12" y1="17" x2="12.01" y2="17" />+ <template v-if="a.kind === 'announcement'">+ <circle cx="12" cy="12" r="10" />+ <line x1="12" y1="16" x2="12" y2="12" />+ <line x1="12" y1="8" x2="12.01" y2="8" />+ </template>+ <template v-else>+ <path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />+ <line x1="12" y1="9" x2="12" y2="13" />+ <line x1="12" y1="17" x2="12.01" y2="17" />+ </template></svg><div class="ab-text"><strong>{{ a.title }}</strong>- <span>{{ a.detail }}</span>+ <span>{{ a.body }}</span></div>- <button class="btn btn-secondary btn-sm" @click="router.push(a.to)">{{ a.action }}</button>+ <button v-if="a.link" class="btn btn-secondary btn-sm" @click="act(a)">+ {{ a.action_text || "Open" }}+ </button>+ <button+ class="ab-dismiss"+ type="button"+ :aria-label="`Dismiss: ${a.title}`"+ title="Dismiss. Comes back if this gets worse."+ @click="store.dismiss(a.id)"+ >+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true">+ <path d="M4 4l8 8M12 4l-8 8" />+ </svg>+ </button></div></div></template>@@ -139,6 +109,12 @@ defineExpose({ alerts });color: var(--warning-600);}+.alert-info {+ background: var(--primary-50);+ border-color: var(--primary-500);+ color: var(--primary-600);+}+.ab-icon {width: 20px;height: 20px;@@ -164,4 +140,29 @@ defineExpose({ alerts });padding: 5px 12px;font-size: 12px;}++.ab-dismiss {+ flex: none;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 26px;+ height: 26px;+ padding: 0;+ border: 0;+ border-radius: 6px;+ background: none;+ color: var(--text-tertiary);+ cursor: pointer;+}++.ab-dismiss svg {+ width: 14px;+ height: 14px;+}++.ab-dismiss:hover {+ background: var(--bg-hover);+ color: var(--text-primary);+}</style>