Skip to content

feat(notifications): notify requesters of request status changes - #143

Merged
Quick104 merged 1 commit into
mainfrom
feat/request-notifications
Jun 12, 2026
Merged

Quick104 merged 1 commit into
mainfrom
feat/request-notifications

Conversation

@Quick104

@Quick104 Quick104 commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Request lifecycle events were community-facing only: submitted/approved/declined posted to admin server channels, and only fulfilled reached the requester personally. A user whose request was approved or declined never heard about it unless they checked the requests page. Server-channel request posts also had no way to tag the requesting user on Discord.

What this does

Personal approved/declined notifications. New request.approved / request.declined delivery types ride the existing operational dispatch path to the requesting profile — inbox, websocket toast, email, Discord DM, personal webhooks (gated by the existing per-webhook notify_requests flag), and web push. Submitted deliberately stays broadcast-only: the requester performed that action themselves. Since no catalog item exists pre-fulfillment, title/year/decline-reason travel in reason_flags and every renderer reads them from there. The admin's decline reason is shown on all channels.

Immediate delivery, even for digest users. Request status changes are transactional: a digest-mode recipient with one pending gets an off-schedule early send within seconds instead of waiting for the digest hour. The early send keeps full watermark durability and does not stamp last_digest_at, so the daily schedule is unaffected. Applies to both Discord DMs and email via the shared account-channel engine; per-episode recipients were already immediate via the dispatch nudge.

Requester @mentions in server channels. Opt-in server setting (notifications.server_channels.mention_requesters, default off, in the Server Channels admin card): Discord request posts @mention the requester via their OAuth-linked Discord identity. Resolved lazily in the sweep worker only when a Discord destination is about to receive the event, pinged via content-level mention with pinned allowed_mentions (embed mentions never ping; implicit parsing stays disabled so user-derived text can never ping roles/@everyone). Unlinked accounts fall back to the plain username; the Discord ID never leaks into generic webhook payloads.

Dedupe migration. 20260612100000_request_lifecycle_notifications.sql adds a partial unique index per (profile, request, type), mirroring the fulfilled pattern, so API retries or multi-node races can't double-notify.

Why this approach

Extending the delivery pipeline (rather than a Discord-specific side channel) lights up every notification channel at once and inherits the existing durability, dedupe, and preference gating. The transactional early-send is expressed at the engine level so both account channels share it and future transactional types just join the list.

Risks / follow-ups

  • silo-android / silo-apple render the two new inbox types with their generic fallback until they add them (type strings + reason_flags documented in web/src/api/types.ts).
  • request.fulfilled keeps its current digest-mode timing; making it transactional is a one-line change if desired.
  • Decline reason reaches the notifier via a transient Request.DeclineReason field; the durable copy remains in media_request_events.

Testing

  • New unit tests: Discord embed + generic webhook rendering for approved/declined (incl. reason field and no-leak assertions), email collation/dedupe across mixed request types, subject lines, server-channel mention payload (allowed_mentions pinning, plain-username fallback).
  • Full internal/... test sweep, go vet, gofmt, web ESLint/Prettier/tsc, and all 1059 web tests pass.

AI use

Implemented with Claude Code (design discussed and decided with the maintainer; all code AI-written, human-reviewed).

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features

    • Request approved and declined notifications alongside fulfillment notifications
    • Optional Discord mentions for request approvals and declines
    • Transactional notifications bypass daily digest waiting period
    • Email notifications distinguish between approved, declined, and fulfilled requests with distinct messaging
    • Toast notifications in the web interface for request status changes
  • Improvements

    • Richer notification context includes request titles, years, and decline reasons

Requests previously only notified the community server channels for
submitted/approved/declined and the requester personally for fulfilled.
This closes the gap and makes request posts addressable:

- New request.approved / request.declined delivery types ride the
  operational dispatch path to the requesting profile: inbox, websocket
  toast, email, Discord DM, personal webhooks (gated by the existing
  notify_requests flag), and web push. Submitted stays broadcast-only
  (the requester performed the action themselves). Title/year/decline
  reason travel in reason_flags since no catalog item exists yet.
- Request status notices are transactional: digest-mode recipients get
  an off-schedule early send (watermark-durable, last_digest_at left
  alone) instead of waiting for the digest hour. Per-episode recipients
  were already immediate via the dispatch nudge.
- At-most-once per (profile, request, type) via a partial unique index
  (migration 20260612100000), mirroring the fulfilled dedupe.
- Server-channel Discord request posts can @mention the requester via
  their OAuth-linked identity (notifications.server_channels.
  mention_requesters, default off). Resolved lazily in the sweep worker
  only when a Discord destination is about to receive the event; the
  ping uses content-level mention with pinned allowed_mentions, and the
  Discord identity never leaks into generic webhook payloads.

Android/Apple clients render the new inbox types with their generic
fallback until they add them.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

This PR extends the notification system to handle request lifecycle events (approved/declined) in addition to fulfillment. It introduces transactional notification support to bypass daily digest delays, adds Discord mention rendering for requesters, and updates all notification delivery formats (email, webhooks, web push) to render lifecycle events with appropriate metadata.

Changes

Request lifecycle notifications

Layer / File(s) Summary
Core request lifecycle infrastructure
internal/requests/types.go, internal/requests/service.go, internal/notifications/request_notifier.go
RequestFlags structure unifies request metadata (id, TMDB id, media type, title, year, decline reason). RequestLifecycleNotifier posts server-channel events for submitted/approved/declined and dispatches personal operational deliveries to requesting profiles asynchronously. DeclineReason field on request captures the decline text.
Transactional notification bypass for daily digest
internal/notifications/account_channel_engine.go, internal/notifications/delivery_repo.go, internal/notifications/discord_dm.go, internal/notifications/email_digest.go
transactionalDeliveryTypes list marks approved/declined as transactional. Channel interface extends with hasTransactionalPendingSince hook. Sweep and processRecipient logic check for transactional pending rows and trigger off-schedule send without updating digest timestamp. HasTransactionalForUserSince and HasTransactionalForProfileSince repository methods check cursor-based pending status.
Email rendering for request lifecycle events
internal/notifications/email_compose.go, internal/notifications/email_logic_test.go
Email collation groups fulfilled/approved/declined request rows using type-inclusive deduplication keys from ReasonFlags. requestLine renders approved/declined messages with titles from parsed flags or SeriesTitle, and "is now available" for fulfilled. Email subject and section heading conditionally use "request ready" vs "request update" based on whether all rows are fulfilled.
Discord requester mention resolution
internal/notifications/settings.go, internal/notifications/server_channel_request_notifier.go, internal/notifications/server_channel_types.go, internal/notifications/server_channel_worker.go, internal/notifications/system.go, internal/notifications/server_channel_logic_test.go
SettingServerChannelMentionRequesters setting controls whether to mention requesters. System.requesterDiscordID conditionally resolves Discord ID from stored preferences when mentions are enabled. RequestEventInfo carries RequesterUserID and RequesterDiscordID. Server-channel worker resolves requester Discord ID once per event when posting to Discord channels.
Discord webhook mention payload and rendering
internal/notifications/webhook_payload_discord.go
discordAllowedMentions type restricts mention parsing to a single user. BuildServerChannelRequestDiscord populates webhook Content with Discord mention ping and sets AllowedMentions. discordEmbedAuthorLine returns explicit text for request approved/declined. buildDiscordEmbed parses request flags for lifecycle types and derives provider IDs from flags. Embed includes request "Type" and "Reason" fields.
Generic webhook and web push payloads
internal/notifications/webhook_payload_generic.go, internal/notifications/webpush_sender.go, internal/notifications/webhook_logic_test.go
Generic webhook request section extends with title, year, reason fields populated from parsed RequestFlags for fulfilled/approved/declined. Web push cases for request approved/decline render payload title and body from flags. Tests validate declined request payloads include expected metadata.
Web UI and API types
web/src/api/types.ts, web/src/components/RealtimeEventsProvider.tsx, web/src/pages/Notifications.tsx, web/src/lib/adminSettingsSearch.ts, web/src/pages/admin-settings/NotificationsAdminSettings.tsx
NotificationReasonFlags API type includes request metadata fields. Real-time provider shows toasts for approved/declined with optional reason. Notification pages display approved/declined titles and descriptions. Admin settings add toggle for Discord mention feature and update settings search index.
Database and routing
migrations/sql/20260612100000_request_lifecycle_notifications.sql, internal/api/router.go
Migration creates unique partial index on notification_deliveries for approved/declined to enforce at-most-once delivery per profile/request. Router wires RequestLifecycleNotifier.

Sequence Diagram(s)

sequenceDiagram
  participant RequestService as Request Service
  participant Notifier as RequestLifecycleNotifier
  participant SCWorker as ServerChannelWorker
  participant Dispatch as DeliveryDispatcher
  participant DiscordAPI as Discord API
  RequestService->>Notifier: RequestApproved(ctx, request)
  Notifier->>SCWorker: PostRequestEvent(approved event)
  SCWorker->>DiscordAPI: POST webhook with mention + embed
  Notifier->>Dispatch: dispatchRequestLifecycle(async)
  Dispatch->>Dispatch: Build RequestFlags with title/year
  Dispatch->>Dispatch: Marshal to reason_flags
  Note over Dispatch: Send personal operational delivery to profile
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 48.65% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding personal notifications for request lifecycle status changes (approved/declined). It is concise, specific, and directly reflects the primary objective of the PR.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/request-notifications

Comment @coderabbitai help to get the list of available commands and usage tips.

@Quick104
Quick104 merged commit 37d6198 into main Jun 12, 2026
1 check was pending
@Quick104
Quick104 deleted the feat/request-notifications branch June 12, 2026 20:20

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 373a338a66

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

err := r.pool.QueryRow(ctx, `
SELECT EXISTS (
SELECT 1 FROM notification_deliveries
WHERE profile_id = $1 AND (created_at, id) > ($2, $3) AND type = ANY($4)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Filter read request updates before bypassing digests

For digest-only recipients, this transactional pre-check ignores read_at, but processRecipient later filters read rows out for ChannelModeDailyDigest. If a user opens/marks a request.approved or request.declined inbox notification before the email/Discord worker runs while older unread episode rows are still behind the watermark, the read request row still triggers the off-schedule digest bypass and sends those unrelated rows immediately instead of at the digest hour. Add the same unread condition to the transactional existence checks (and the user-level variant above) or otherwise only bypass when an unread transactional row will actually be delivered.

Useful? React with 👍 / 👎.

Comment on lines +154 to +155
if flags.Reason != "" {
line += " — " + flags.Reason

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep decline notes out of email subjects

When a declined request is the only item in a per-episode email, emailSubject returns requestLine(...), so this appends the full admin-supplied decline note to the email Subject. The decline textarea/API do not cap this value, so a long note can produce oversized headers and make the SMTP send fail or be rejected, causing the requester to miss the notification; keep the note in the body or truncate it before it can become the subject.

Useful? React with 👍 / 👎.

Quick104 added a commit that referenced this pull request Jun 17, 2026
Requests previously only notified the community server channels for
submitted/approved/declined and the requester personally for fulfilled.
This closes the gap and makes request posts addressable:

- New request.approved / request.declined delivery types ride the
  operational dispatch path to the requesting profile: inbox, websocket
  toast, email, Discord DM, personal webhooks (gated by the existing
  notify_requests flag), and web push. Submitted stays broadcast-only
  (the requester performed the action themselves). Title/year/decline
  reason travel in reason_flags since no catalog item exists yet.
- Request status notices are transactional: digest-mode recipients get
  an off-schedule early send (watermark-durable, last_digest_at left
  alone) instead of waiting for the digest hour. Per-episode recipients
  were already immediate via the dispatch nudge.
- At-most-once per (profile, request, type) via a partial unique index
  (migration 20260612100000), mirroring the fulfilled dedupe.
- Server-channel Discord request posts can @mention the requester via
  their OAuth-linked identity (notifications.server_channels.
  mention_requesters, default off). Resolved lazily in the sweep worker
  only when a Discord destination is about to receive the event; the
  ping uses content-level mention with pinned allowed_mentions, and the
  Discord identity never leaks into generic webhook payloads.

Android/Apple clients render the new inbox types with their generic
fallback until they add them.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant