notify

package
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2026 License: AGPL-3.0 Imports: 23 Imported by: 0

Documentation

Overview

Package notify creates in-app notifications (A5 §3.12) and fans them out to the members who should see them. Delivery preferences (in-app and/or email per event type) are applied here; see EmailWorker for email delivery.

Index

Constants

View Source
const (
	FilterAll    = "all"
	FilterUnread = "unread"
)

Filters of the notification center tabs.

View Source
const (
	CategoryApprovals  = "approvals"
	CategorySending    = "sending"
	CategoryProviders  = "providers"
	CategoryTeam       = "team"
	CategoryHostRepute = "hostrepute"
	CategoryOther      = "other"
)

Categories of the notification center tabs.

View Source
const (
	KindApprovalRequested   = "approval_requested"
	KindApprovalDecided     = "approval_decided" // approved, rejected, changes requested
	KindApprovalInvalidated = "approval_invalidated"
	KindSendPaused          = "send_paused"
	KindSendBlocked         = "send_blocked" // the send-time recheck turned Blocked
	KindProviderDown        = "provider_down"
	KindProviderDegraded    = "provider_degraded"
	KindWebhooksSilent      = "webhooks_silent"
	KindInviteAccepted      = "invite_accepted"
	KindInviteRequested     = "invite_requested" // an invitee asked for a new invitation
	KindHostReputeAlert     = "hostrepute_alert"
	KindSendFinished        = "send_finished"
	KindJobFinished         = "job_finished" // imports, exports
)

Kinds of notifications. Preferences are stored per event type (see Events); several kinds can share one event type.

View Source
const RetentionDays = 90

RetentionDays is how long notifications are kept.

Variables

View Source
var Events = []EventType{
	{Key: KindApprovalRequested, Label: "Approval requested", Audience: "Only for approvers", Short: "approval requests", DefaultEmail: true, Kinds: []string{KindApprovalRequested}},
	{Key: KindApprovalDecided, Label: "Approval approved, rejected or changes requested", Audience: "Only for the author", Short: "approval decisions", DefaultEmail: true, Kinds: []string{KindApprovalDecided}},
	{Key: KindApprovalInvalidated, Label: "Approval invalidated", Audience: "Author and approvers", Short: "invalidated approvals", DefaultEmail: true, Kinds: []string{KindApprovalInvalidated}},
	{Key: KindSendPaused, Label: "Send auto-paused", Audience: "Everyone with campaigns:pause", Short: "auto-pauses", DefaultEmail: true, Urgent: true, Kinds: []string{KindSendPaused, KindSendBlocked}},
	{Key: KindProviderDown, Label: "Provider down or degraded", Audience: "Everyone with providers:view", Short: "provider down", DefaultEmail: true, Urgent: true, Kinds: []string{KindProviderDown, KindProviderDegraded}},
	{Key: KindWebhooksSilent, Label: "Webhooks silent", Short: "silent webhooks", DefaultEmail: false, Kinds: []string{KindWebhooksSilent}},
	{Key: KindInviteAccepted, Label: "Invite accepted", Audience: "Inviter only", Short: "invites", DefaultEmail: false, Kinds: []string{KindInviteAccepted, KindInviteRequested}},
	{Key: KindHostReputeAlert, Label: "HostRepute alerts", Audience: "Everyone with deliverability:view", Short: "HostRepute alerts", DefaultEmail: false, Kinds: []string{KindHostReputeAlert}},
}

Events lists the event types in the order of the preferences table.

Functions

func CategoryLabel

func CategoryLabel(c string) string

CategoryLabel is the tab name of a category.

func CategoryOf

func CategoryOf(kind string) string

CategoryOf returns the center tab a kind is listed under.

func KindsOf

func KindsOf(category string) []string

KindsOf returns the kinds of a category tab.

func MembersWith

func MembersWith(ctx context.Context, q store.DBTX, workspaceID uuid.UUID, perm authz.Permission) ([]uuid.UUID, error)

MembersWith returns the active members of a workspace who hold perm.

func Register

func Register(h huma.API, s *Service)

Register adds the notification center and preference operations.

func ToMembersWith

func ToMembersWith(ctx context.Context, q store.DBTX, workspaceID uuid.UUID, perm authz.Permission, n Notification) error

ToMembersWith notifies every active member of the workspace who holds perm (everyone when perm is empty).

func ToUser

func ToUser(ctx context.Context, q store.DBTX, userID uuid.UUID, n Notification) error

ToUser stores a notification for one person, honouring their preferences: nothing is stored when both in-app and email are off for the event type.

Types

type CleanupArgs

type CleanupArgs struct{}

CleanupArgs deletes notifications past retention.

func (CleanupArgs) InsertOpts

func (CleanupArgs) InsertOpts() river.InsertOpts

InsertOpts runs cleanup on the maintenance queue.

func (CleanupArgs) Kind

func (CleanupArgs) Kind() string

Kind implements river.JobArgs.

type CleanupWorker

type CleanupWorker struct {
	river.WorkerDefaults[CleanupArgs]
	Pool *pgxpool.Pool
	Log  *slog.Logger
}

CleanupWorker keeps notifications for RetentionDays.

func (*CleanupWorker) Work

Work implements river.Worker.

type EmailArgs

type EmailArgs struct{}

EmailArgs is the periodic job that emails notifications to the people who asked for email.

func (EmailArgs) InsertOpts

func (EmailArgs) InsertOpts() river.InsertOpts

InsertOpts keeps one delivery run at a time on the System queue.

func (EmailArgs) Kind

func (EmailArgs) Kind() string

Kind implements river.JobArgs.

type EmailWorker

type EmailWorker struct {
	river.WorkerDefaults[EmailArgs]
	Pool *pgxpool.Pool
	// Mail is read at run time: the system mailer is wired after the workers.
	Mail func() mailer.Sender
	// PublicURL returns the instance's public URL for links in emails.
	PublicURL func(context.Context) string
	Log       *slog.Logger
	Now       func() time.Time
}

EmailWorker delivers pending notification emails through the System stream. Urgent events (auto-pauses, provider outages) go out at once; others respect the person's quiet hours and digest setting. Without a System-stream provider the emails are skipped silently: the in-app notification is already there.

func (*EmailWorker) Work

func (w *EmailWorker) Work(ctx context.Context, _ *river.Job[EmailArgs]) error

Work implements river.Worker.

type EventType

type EventType struct {
	Key      string
	Label    string
	Audience string
	// Short is the plural phrase used in summaries ("Approvals, auto-pauses").
	Short string
	// DefaultEmail is used until the person saves their preferences.
	DefaultEmail bool
	// Urgent emails ignore quiet hours and digests ("Auto-pauses and
	// provider outages always send immediately").
	Urgent bool
	Kinds  []string
}

EventType is one row of the notification preferences: the person chooses in-app and/or email per event type.

func EventFor

func EventFor(kind string) EventType

EventFor returns the event type a notification kind belongs to.

type Notification

type Notification struct {
	WorkspaceID *uuid.UUID
	Kind        string
	Severity    string // info, ok, warn, bad
	Title       string
	// Summary is the short line shown in the bell popover; Body is used when
	// it is empty. Body is the full sentence in the notification center and
	// in the email.
	Summary string
	Body    string
	// Link is an app path such as "/w/acme-newsletter/campaigns/<id>/live".
	Link string
	Data map[string]any
}

Notification is what appears in the notification center.

type NotificationEmailDelivery

type NotificationEmailDelivery struct {
	Available bool `json:"available"`
	// Provider is the sending provider of the System stream ("Postmark").
	Provider string `json:"provider,omitempty"`
}

NotificationEmailDelivery says whether notification emails can go out right now.

type NotificationEventChoice

type NotificationEventChoice struct {
	Type  string `json:"type" maxLength:"64"`
	InApp bool   `json:"inApp"`
	Email bool   `json:"email"`
}

NotificationEventChoice turns one event type's channels on or off.

type NotificationEventPreference

type NotificationEventPreference struct {
	Type     string `json:"type"`
	Label    string `json:"label"`
	Audience string `json:"audience,omitempty"`
	InApp    bool   `json:"inApp"`
	Email    bool   `json:"email"`
}

NotificationEventPreference is one row of the preferences table.

type NotificationItem

type NotificationItem struct {
	ID            string    `json:"id"`
	Kind          string    `json:"kind"`
	Category      string    `json:"category" enum:"approvals,sending,providers,team,hostrepute,other"`
	CategoryLabel string    `json:"categoryLabel" example:"Approvals"`
	Severity      string    `json:"severity" enum:"info,ok,warn,bad"`
	Title         string    `json:"title" example:"Approval requested"`
	Summary       string    `json:"summary" doc:"Short line for the bell popover"`
	Body          string    `json:"body" doc:"Full sentence for the notification center"`
	Link          string    `json:"link" doc:"App path of the screen where you can act"`
	CreatedAt     time.Time `json:"createdAt"`
	Read          bool      `json:"read"`
}

NotificationItem is one entry of the notification center.

type NotificationList

type NotificationList struct {
	Items []NotificationItem `json:"items"`
	// Unread counts every unread notification in the workspace (all tabs).
	Unread int64 `json:"unread"`
	// Total counts the notifications matching the filter.
	Total         int64  `json:"total"`
	NextCursor    string `json:"nextCursor,omitempty"`
	RetentionDays int    `json:"retentionDays"`
}

NotificationList is a page of the notification center.

type NotificationPreferences

type NotificationPreferences struct {
	Events     []NotificationEventPreference `json:"events"`
	QuietHours *NotificationQuietHours       `json:"quietHours,omitempty"`
	Digest     string                        `json:"digest" enum:"immediate,hourly,daily"`
	Timezone   string                        `json:"timezone"`
	Email      NotificationEmailDelivery     `json:"email"`
}

NotificationPreferences are the person's notification settings.

type NotificationPreferencesInput

type NotificationPreferencesInput struct {
	Events     []NotificationEventChoice `json:"events" maxItems:"20"`
	QuietHours *NotificationQuietHours   `json:"quietHours,omitempty" doc:"Omit or null to turn quiet hours off"`
	Digest     string                    `json:"digest" enum:"immediate,hourly,daily"`
}

NotificationPreferencesInput is PUT /me/notification-preferences.

type NotificationQuietHours

type NotificationQuietHours struct {
	Start string `json:"start" pattern:"^([01][0-9]|2[0-3]):[0-5][0-9]$" example:"22:00"`
	End   string `json:"end" pattern:"^([01][0-9]|2[0-3]):[0-5][0-9]$" example:"07:00"`
}

NotificationQuietHours hold back non-urgent emails, in the person's timezone.

type NotificationSummary

type NotificationSummary struct {
	InApp      string `json:"inApp" example:"All events"`
	Email      string `json:"email" example:"Approvals, auto-pauses, provider down"`
	QuietHours string `json:"quietHours" example:"22:00–07:00 America/New_York, email only"`
}

NotificationSummary is the Notification preferences card in Account & security.

func Summarize

Summarize describes preferences in one line per channel.

type NotificationsMarked

type NotificationsMarked struct {
	Marked int64 `json:"marked"`
}

NotificationsMarked says how many notifications were marked as read.

type Service

type Service struct {
	Pool  *pgxpool.Pool
	Q     *store.Queries
	Audit *audit.Logger
	// Mail reports whether email can go out (System stream connected).
	Mail func() mailer.Sender
}

Service serves the notification center and the delivery preferences.

func (*Service) List

func (s *Service) List(ctx context.Context, filter, cursor string, limit int) (NotificationList, error)

List returns the caller's notifications in the current workspace, unread first, then newest first.

func (*Service) MarkAllRead

func (s *Service) MarkAllRead(ctx context.Context) (int64, error)

MarkAllRead marks every notification of the workspace as read.

func (*Service) MarkRead

func (s *Service) MarkRead(ctx context.Context, id uuid.UUID) error

MarkRead marks one notification as read (opening it from the list). Read state is personal UI state, like a session's last-seen time, so it is not written to the workspace audit log.

func (*Service) Preferences

func (s *Service) Preferences(ctx context.Context, user store.User, workspaceID *uuid.UUID) (NotificationPreferences, error)

Preferences returns a person's notification settings. workspaceID, when set, names the workspace whose System-stream provider is shown.

func (*Service) SavePreferences

func (s *Service) SavePreferences(ctx context.Context, user store.User, in NotificationPreferencesInput) error

SavePreferences stores the person's notification settings.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL