notify

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: AGPL-3.0 Imports: 28 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"
	// CategoryIntegrations holds the integrations hub's notifications.
	CategoryIntegrations = "integrations"
	// CategoryTransactional holds transactional mail's delivery alerts and
	// the SMTP relay.
	CategoryTransactional = "transactional"
	// CategoryAI holds the AI assistant's cap and key notices.
	CategoryAI = "ai"
	// CategoryEarn holds payments and paid members.
	CategoryEarn = "earn"
	// CategoryWebsite holds the publication website's notifications.
	CategoryWebsite = "website"
	// CategoryGrow holds referrals' and partner links' notifications.
	CategoryGrow = "grow"
)

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"
	// KindComplaintWatch: complaints passed a limit during the watch after a
	// send (review GS-6); preferences are those of auto-pauses.
	KindComplaintWatch = "complaint_watch"
	// KindRenderFailed: the template failed for some recipients of a send
	// (review CO-4); preferences are those of auto-pauses.
	KindRenderFailed     = "render_failed"
	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
	// Integrations hub (design expansion, phase 2).
	KindIntegrationAttention = "integration_attention" // an integration needs attention
	KindWebhookFailing       = "webhook_failing"       // an outgoing webhook endpoint keeps failing (webhooks:manage; review 2026-11 IN-2)
	KindPostDraftCreated     = "post_draft_created"    // a WordPress post became a campaign draft
	// KindTransactionalAlert is a delivery alert of transactional mail: a
	// template's bounce rate, failed messages or the median delivery time
	// over the last hour passed its limit.
	KindTransactionalAlert = "transactional_alert"
	// KindSMTPRelayUnreachable tells instance admins the SMTP relay can't
	// be reached from the internet.
	KindSMTPRelayUnreachable = "smtp_relay_unreachable"
	// Contact scoring (design expansion, phase 4).
	KindScoreRecalculated = "score_recalculated" // every contact was scored again after a rule change
	// Recurring digests (design expansion, phase 3).
	KindDigestIssueHeld   = "digest_issue_held"   // Send Readiness blocked a digest issue: it waits for a person
	KindDigestPaused      = "digest_paused"       // a digest paused (by a person, its owner's permissions, the feed)
	KindDigestFeedFailing = "digest_feed_failing" // a digest's feed failed at preparation, then the issue was skipped
	// KindAutomationAttention: a flow's step keeps failing or its sending is
	// held (review 2026-11 EN-5).
	KindAutomationAttention = "automation_attention"
	KindDigestDraftReady    = "digest_draft_ready" // draft mode: an issue is a draft to send through Review & send
	// AI assistant (design expansion, phase 3).
	KindAIUsage       = "ai_usage"        // this month's AI use reached 80% of the cap, or the cap
	KindAIKeyRejected = "ai_key_rejected" // the model provider rejected the workspace's key
	// Earn (design expansion, phase 6).
	KindPaymentsAttention = "payments_attention"      // a payment provider's key rejected, webhook missing or silent
	KindUnmappedPrice     = "payments_unmapped_price" // a Stripe price isn't mapped to a tier
	KindPaidImportDone    = "paid_import_finished"    // a paid-members import finished
	KindFailedPayments    = "failed_payments_daily"   // the daily summary of failed payments (off by default)
	// Sponsorships (design expansion, phase 6).
	KindSponsorCreative = "sponsor_creative"        // a sponsor's creative is due tomorrow, or late
	KindSponsorPayment  = "sponsor_payment_overdue" // a sponsor's payment is past its due date
	// Address verification and placement tests (design expansion, phase 4).
	KindVerificationEnded      = "verification_ended"       // a verification job finished or stopped
	KindVerificationCreditsLow = "verification_credits_low" // a service's balance runs low
	KindPlacementFinished      = "placement_finished"       // a placement test finished
	KindSeedSignInFailed       = "seed_signin_failed"       // a seed mailbox's sign-in failed or expired
	// The publication website (design expansion, phase 7).
	KindWebsiteDomain = "website_domain" // the website's custom domain stopped checking out, or its certificate is failing
	// Digital products (design expansion, phase 7).
	KindProductDeliveryFailed = "product_delivery_failed" // an order's delivery email couldn't be sent
	KindOrderDisputed         = "order_disputed"          // a buyer disputed an order's payment in Stripe
	// Grow (design expansion, phase 5).
	KindReferralsHeld        = "referrals_held"         // referrals wait in the review queue (grow:review)
	KindRewardCodesLow       = "reward_codes_low"       // a code reward is running low or out of codes (grow:edit)
	KindRewardWebhookFailing = "reward_webhook_failing" // a webhook reward's endpoint keeps failing (grow:edit)
	KindPartnerLinkProblem   = "partner_link_problem"   // a partner link is invalid or unreachable (grow:connect)
	// SMS (design expansion, phase 8).
	KindSMSBudget       = "sms_budget"        // the month's SMS budget reached its alert level or ran out
	KindSMSRegistration = "sms_registration"  // a sender's registration was approved or rejected
	KindSMSProviderDown = "sms_provider_down" // an SMS provider is down, its credentials rejected, or its receipts silent
	KindSMSSendPaused   = "sms_send_paused"   // an SMS campaign auto-paused
	// Shopify and WooCommerce (design expansion, phase 7).
	KindStoreProblem = "store_problem" // a store disconnected, or its webhooks missing
	// Web push and WhatsApp (design expansion, phase 8).
	KindPushWorkerMissing  = "push_worker_missing" // a push site's service worker is missing or unreachable
	KindWhatsAppAttention  = "whatsapp_attention"  // a WhatsApp template was rejected, or the number's quality dropped
	KindWhatsAppTokenFails = "whatsapp_token"      // Meta rejected the WhatsApp access token: sends are held
	// Comments in the composer (review 2026-10, CO-10).
	KindCommentMention = "comment_mention" // someone @mentioned the member in a campaign's comments
	// KindResultsFinal: a campaign report's results are final, for someone
	// who asked to be emailed then ("Email me when it's final").
	KindResultsFinal = "results_final"
)

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: "People who can send campaigns", Short: "auto-pauses", DefaultEmail: true, Urgent: true, Kinds: []string{KindSendPaused, KindSendBlocked, KindComplaintWatch, KindRenderFailed}},
	{Key: KindProviderDown, Label: "Provider down or degraded", Audience: "People who can manage sending providers", Short: "provider down", DefaultEmail: true, Urgent: true, Kinds: []string{KindProviderDown, KindProviderDegraded}},
	{Key: KindWebhooksSilent, Label: "Webhooks silent", Audience: "People who can manage sending providers", 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: KindCommentMention, Label: "Mentioned in a comment", Audience: "When someone @mentions you in a campaign's comments", Short: "mentions", DefaultEmail: true, Kinds: []string{KindCommentMention}},
	{Key: KindHostReputeAlert, Label: "HostRepute alerts", Audience: "People who can view deliverability", Short: "HostRepute alerts", DefaultEmail: false, Kinds: []string{KindHostReputeAlert}},
	{Key: KindIntegrationAttention, Label: "Integration needs attention", Audience: "People who can manage integrations", Short: "integration problems", DefaultEmail: true, Kinds: []string{KindIntegrationAttention}},
	{Key: KindWebhookFailing, Label: "A webhook endpoint is failing", Audience: "People who manage webhooks · after an hour of failures, or a delivery given up on", Short: "failing webhook endpoints", DefaultEmail: true, Kinds: []string{KindWebhookFailing}},
	{Key: KindPostDraftCreated, Label: "Post draft created", Audience: "When a WordPress post-draft rule names you", Short: "post drafts", DefaultEmail: true, Kinds: []string{KindPostDraftCreated}},
	{Key: KindTransactionalAlert, Label: "Transactional delivery alert", Audience: "People who can view transactional email", Short: "transactional delivery alerts", DefaultEmail: true, Kinds: []string{KindTransactionalAlert}},
	{Key: KindSMTPRelayUnreachable, Label: "SMTP relay unreachable", Audience: "Instance admins only", Short: "SMTP relay outages", DefaultEmail: true, Urgent: true, Kinds: []string{KindSMTPRelayUnreachable}},
	{Key: KindScoreRecalculated, Label: "Score recalculation finished", Audience: "The person who changed the rules", Short: "score recalculations", DefaultEmail: false, Kinds: []string{KindScoreRecalculated}},

	{Key: KindDigestIssueHeld, Label: "Digest issue held", Audience: "The owner, and approvers with a request open", Short: "held digest issues", DefaultEmail: true, Kinds: []string{KindDigestIssueHeld}},
	{Key: KindDigestPaused, Label: "Digest paused", Audience: "The owner, or people who can send campaigns", Short: "paused digests", DefaultEmail: true, Kinds: []string{KindDigestPaused}},
	{Key: KindDigestFeedFailing, Label: "Digest feed failing", Audience: "The digest's owner", Short: "failing digest feeds", DefaultEmail: true, Kinds: []string{KindDigestFeedFailing}},
	{Key: KindAutomationAttention, Label: "Automation needs attention", Audience: "People who can edit automations", Short: "automation problems", DefaultEmail: true, Kinds: []string{KindAutomationAttention}},
	{Key: KindDigestDraftReady, Label: "Digest draft ready", Audience: "The owner and people who can send campaigns", Short: "digest drafts", DefaultEmail: true, Kinds: []string{KindDigestDraftReady}},

	{Key: KindResultsFinal, Label: "Report results final", Audience: "When you asked to be emailed", Short: "final report results", DefaultEmail: true, Kinds: []string{KindResultsFinal}},

	{Key: KindAIUsage, Label: "AI usage at 80% and cap reached", Audience: "People who can manage integrations", Short: "AI usage notices", DefaultEmail: true, Kinds: []string{KindAIUsage}},
	{Key: KindAIKeyRejected, Label: "AI key rejected by the provider", Audience: "People who can manage integrations", Short: "rejected AI keys", DefaultEmail: true, Kinds: []string{KindAIKeyRejected}},
	{Key: KindPaymentsAttention, Label: "Payments: key rejected, webhook missing or silent", Audience: "People who can manage payments", Short: "payment problems", DefaultEmail: true, Kinds: []string{KindPaymentsAttention}},
	{Key: KindUnmappedPrice, Label: "Payments: a Stripe price isn't mapped to a tier", Audience: "People who can manage payments", Short: "unmapped prices", DefaultEmail: false, Kinds: []string{KindUnmappedPrice}},
	{Key: KindPaidImportDone, Label: "Paid members import finished", Audience: "Whoever ran the import", Short: "paid-members imports", DefaultEmail: false, Kinds: []string{KindPaidImportDone}},
	{Key: KindSponsorCreative, Label: "Sponsor creative due tomorrow or late", Audience: "People who can manage sponsors", Short: "sponsor creatives", DefaultEmail: true, Kinds: []string{KindSponsorCreative}},
	{Key: KindSponsorPayment, Label: "Sponsor payment overdue", Audience: "People who can manage sponsors", Short: "overdue sponsor payments", DefaultEmail: false, Kinds: []string{KindSponsorPayment}},
	{Key: KindFailedPayments, Label: "Failed payments · daily summary", Audience: "People who can view revenue · off by default", Short: "failed payments", OffByDefault: true, Kinds: []string{KindFailedPayments}},
	{Key: KindVerificationEnded, Label: "Verification finished or stopped", Audience: "The person who started it", Short: "verification jobs", DefaultEmail: true, Kinds: []string{KindVerificationEnded}},
	{Key: KindVerificationCreditsLow, Label: "Verification credits low", Audience: "People who can manage integrations", Short: "low verification credits", DefaultEmail: true, Kinds: []string{KindVerificationCreditsLow}},
	{Key: KindPlacementFinished, Label: "Placement test finished", Audience: "The person who started it", Short: "placement tests", DefaultEmail: false, Kinds: []string{KindPlacementFinished}},
	{Key: KindSeedSignInFailed, Label: "Seed mailbox sign-in failed", Audience: "People who can manage seed mailboxes", Short: "seed sign-in failures", DefaultEmail: true, Kinds: []string{KindSeedSignInFailed}},

	{Key: KindWebsiteDomain, Label: "Website domain or certificate problem", Audience: "People who can manage the website", Short: "website domain problems", DefaultEmail: true, Kinds: []string{KindWebsiteDomain}},

	{Key: KindProductDeliveryFailed, Label: "Product delivery failed", Audience: "People who can manage orders", Short: "failed product deliveries", DefaultEmail: true, Kinds: []string{KindProductDeliveryFailed}},
	{Key: KindOrderDisputed, Label: "Dispute opened on an order", Audience: "People who can manage orders", Short: "order disputes", DefaultEmail: true, Kinds: []string{KindOrderDisputed}},

	{Key: KindReferralsHeld, Label: "Referrals held for review", Audience: "People who can review referrals · then at most once a day while the queue isn't empty", Short: "held referrals", DefaultEmail: true, Kinds: []string{KindReferralsHeld}},
	{Key: KindRewardCodesLow, Label: "Reward codes running low or out", Audience: "People who can edit the referral program", Short: "reward codes running low", DefaultEmail: true, Kinds: []string{KindRewardCodesLow}},
	{Key: KindRewardWebhookFailing, Label: "Reward webhook failing", Audience: "People who can edit the referral program", Short: "failing reward webhooks", DefaultEmail: true, Kinds: []string{KindRewardWebhookFailing}},
	{Key: KindPartnerLinkProblem, Label: "Partner link invalid or unreachable", Audience: "People who can connect partner links", Short: "partner link problems", DefaultEmail: true, Kinds: []string{KindPartnerLinkProblem}},

	{Key: KindSMSBudget, Label: "SMS budget at 80% or used up", Audience: "People who can manage sending providers", Short: "SMS budget alerts", DefaultEmail: true, Kinds: []string{KindSMSBudget}},
	{Key: KindSMSRegistration, Label: "Sender registration approved or rejected", Audience: "People who can view sending providers", Short: "sender registrations", DefaultEmail: true, Kinds: []string{KindSMSRegistration}},
	{Key: KindSMSProviderDown, Label: "SMS provider down or receipts silent", Audience: "People who can view sending providers", Short: "SMS provider problems", DefaultEmail: true, Urgent: true, Kinds: []string{KindSMSProviderDown}},
	{Key: KindSMSSendPaused, Label: "SMS campaign auto-paused", Audience: "People who can send campaigns", Short: "SMS auto-pauses", DefaultEmail: true, Urgent: true, Kinds: []string{KindSMSSendPaused}},
	{Key: KindStoreProblem, Label: "Store disconnected or its webhooks missing", Audience: "People who can manage integrations", Short: "store problems", DefaultEmail: true, Kinds: []string{KindStoreProblem}},

	{Key: KindPushWorkerMissing, Label: "Push service worker missing", Audience: "People who can view sending providers", Short: "missing push service workers", DefaultEmail: false, Kinds: []string{KindPushWorkerMissing}},
	{Key: KindWhatsAppAttention, Label: "WhatsApp template rejected or quality dropped", Audience: "People who can view sending providers", Short: "WhatsApp templates and quality", DefaultEmail: true, Kinds: []string{KindWhatsAppAttention, KindWhatsAppTokenFails}},
}

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, in English (messages/<locale>.json has it as category.<tab>, with its translations).

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 Localize

func Localize(l i18n.Lang, title, summary, body string, data []byte) (string, string, string)

Localize writes a stored notification in a reader's language, from its columns and its data: for readers outside this package, such as the Agency area's bell.

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 and Audience are the row's name and who gets the event, in
	// English. messages/<locale>.json has them as event.<Key> and
	// audience.<Key>, with their translations.
	Label    string
	Audience string
	// Short is the plural phrase used in summaries ("Approvals,
	// auto-pauses"), in English. messages/<locale>.json has it as
	// short.<Key>, with its translations.
	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
	// OffByDefault event types are neither in-app nor emailed until the
	// person turns them on, and summaries leave them out while off.
	OffByDefault 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 Kept

type Kept struct {
	Title   i18n.Text `json:"title,omitzero"`
	Summary i18n.Text `json:"summary,omitzero"`
	Body    i18n.Text `json:"body,omitzero"`
}

Kept is a notification's title, summary and body kept as messages.

func KeptIn

func KeptIn(data []byte) Kept

KeptIn reads the kept text of a stored notification's data. Data without it gives a zero Kept.

func (Kept) IsZero

func (k Kept) IsZero() bool

IsZero reports whether no part is kept as a message.

func (Kept) Localized

func (k Kept) Localized(l i18n.Lang, title, summary, body string) (string, string, string)

Localized is a stored notification's title, summary and body in a reader's language: each kept part in that language, and the English that was stored for the others.

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
	// TitleText, SummaryText and BodyText are the title, summary and body as
	// catalog messages kept with their arguments (msgs.M(key).Keep(args)),
	// so every member reads them in their own language (text.go). A part
	// given only as a message gets its English for the string above.
	TitleText   i18n.Text
	SummaryText i18n.Text
	BodyText    i18n.Text
	// 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,integrations,transactional,earn,website,grow"`
	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:"100"`
	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, in English.

func SummarizeIn

SummarizeIn describes preferences in one line per channel, in a language.

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