Skip to content

Conversation

@ameer2468
Copy link
Contributor

@ameer2468 ameer2468 commented Aug 8, 2025

This PR:

  • On clicking/opening a notification it will automatically be marked as read.

Summary by CodeRabbit

  • New Features

    • Added the ability to mark individual notifications as read directly from the notification list.
  • Refactor

    • Unified the notification marking actions, allowing both single and bulk marking as read through a single function.
    • Updated notification UI components to use the new notification marking logic.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 8, 2025

Walkthrough

The changes remove the previous bulk notification marking action and replace it with a unified markAsRead function that can mark either a single notification or all notifications as read. UI components are updated to use this new action, with handlers and imports adjusted accordingly. Error handling and cache revalidation are preserved.

Changes

Cohort / File(s) Change Summary
Server Action Refactor
apps/web/actions/notifications/mark-all-as-read.ts, apps/web/actions/notifications/mark-as-read.ts
Removes the old markAllAsRead action and introduces a new markAsRead function that can mark one or all notifications as read, with updated error handling and cache revalidation.
Notification Header UI Update
apps/web/app/(org)/dashboard/_components/Notifications/NotificationHeader.tsx
Updates imports and handler logic to use the new markAsRead action instead of the removed markAllAsRead.
Notification Item Marking
apps/web/app/(org)/dashboard/_components/Notifications/NotificationItem.tsx
Adds a handler to mark individual notifications as read when clicked, using the new markAsRead action.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant NotificationHeader
    participant NotificationItem
    participant markAsRead (Server)
    participant Database
    participant Cache

    User->>NotificationHeader: Click "Mark all as read"
    NotificationHeader->>markAsRead: markAsRead()
    markAsRead->>Database: Update all notifications (readAt)
    markAsRead->>Cache: Revalidate "/dashboard"
    markAsRead-->>NotificationHeader: Success/Error

    User->>NotificationItem: Click notification
    NotificationItem->>markAsRead: markAsRead(notificationId)
    markAsRead->>Database: Update notification (readAt)
    markAsRead->>Cache: Revalidate "/dashboard"
    markAsRead-->>NotificationItem: Success/Error
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Poem

In the burrows of code, a change hops through,
Old ways of reading are bid adieu.
Now with a tap or a gentle click,
Each notice or all—mark them read, take your pick!
The dashboard refreshed, the inbox anew,
A rabbit’s delight in what devs do! 🐇✨

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch mark-as-read-on-click

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@ameer2468 ameer2468 merged commit 17d9c59 into main Aug 8, 2025
6 of 7 checks passed
@ameer2468 ameer2468 deleted the mark-as-read-on-click branch August 8, 2025 15:00
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (2)
apps/web/app/(org)/dashboard/_components/Notifications/NotificationItem.tsx (1)

1-1: Missing "use client" directive

This component attaches event handlers; it must be a Client Component.

+"use client";
+
 import { faComment, faEye, faReply } from "@fortawesome/free-solid-svg-icons";
apps/web/app/(org)/dashboard/_components/Notifications/NotificationHeader.tsx (1)

1-1: Missing "use client" directive

Hooks (useState, useQueryClient) require this to be a Client Component.

+"use client";
+
 import { faCheckDouble } from "@fortawesome/free-solid-svg-icons";
🧹 Nitpick comments (4)
apps/web/actions/notifications/mark-as-read.ts (2)

28-31: Use console.error for errors (and keep the generic message for clients)

Log as an error for better observability. Keeping a generic thrown message is fine.

-  } catch (error) {
-    console.log(error);
-    throw new Error("Error marking notification(s) as read");
-  }
+  } catch (error) {
+    console.error("Error marking notification(s) as read", error);
+    throw new Error("Error marking notification(s) as read");
+  }

33-34: Consider revalidating an additional path or tag if notifications render outside /dashboard

If notifications are shown elsewhere (e.g., a global drawer or a different route), also revalidate that path or switch to revalidateTag with route segment-level caching.

apps/web/app/(org)/dashboard/_components/Notifications/NotificationItem.tsx (1)

29-35: Fire-and-forget the mark-as-read call to avoid delaying navigation (and handle middle-click)

Awaiting inside onClick is unnecessary and may slightly impact perceived navigation. Fire-and-forget with a catch, and optionally handle auxiliary clicks (middle-click) to mark as read when opening in a new tab.

-  const markAsReadHandler = async () => {
-    try {
-      await markAsRead(notification.id);
-    } catch (error) {
-      console.error("Error marking notification as read:", error);
-    }
-  };
+  const markAsReadHandler = () => {
+    // Fire-and-forget; do not block navigation.
+    markAsRead(notification.id).catch((error) => {
+      console.error("Error marking notification as read:", error);
+    });
+  };
     <Link
       href={link}
-      onClick={markAsReadHandler}
+      onClick={markAsReadHandler}
+      onAuxClick={markAsReadHandler}
       className={clsx(

Also applies to: 38-41

apps/web/app/(org)/dashboard/_components/Notifications/NotificationHeader.tsx (1)

14-18: Guard against double invocations while loading

Prevent re-entrancy if a user double-clicks.

-  const markAsReadHandler = async () => {
+  const markAsReadHandler = async () => {
+    if (loading) return;
     try {
       setLoading(true);
       await markAsRead();
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a83ee6a and 3b187d0.

📒 Files selected for processing (4)
  • apps/web/actions/notifications/mark-all-as-read.ts (0 hunks)
  • apps/web/actions/notifications/mark-as-read.ts (1 hunks)
  • apps/web/app/(org)/dashboard/_components/Notifications/NotificationHeader.tsx (3 hunks)
  • apps/web/app/(org)/dashboard/_components/Notifications/NotificationItem.tsx (2 hunks)
💤 Files with no reviewable changes (1)
  • apps/web/actions/notifications/mark-all-as-read.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Build Desktop (aarch64-apple-darwin, macos-latest)
  • GitHub Check: Clippy
  • GitHub Check: Build Desktop (x86_64-pc-windows-msvc, windows-latest)

import { getCurrentUser } from "@cap/database/auth/session";
import { notifications } from "@cap/database/schema";
import { db } from "@cap/database";
import { eq } from "drizzle-orm";
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Scope single-item update to the current user and update only unread notifications

Currently, the single-item branch updates by ID only, allowing any authenticated user to mark any notification as read if they know its ID. Also, both branches overwrite readAt for already read notifications. Tighten authorization and update only unread rows.

Apply:

-import { eq } from "drizzle-orm";
+import { and, eq, isNull } from "drizzle-orm";
-    if (notificationId) {
-      await db()
-        .update(notifications)
-        .set({ readAt: now })
-        .where(eq(notifications.id, notificationId));
-    } else {
-      await db()
-        .update(notifications)
-        .set({ readAt: now })
-        .where(eq(notifications.recipientId, currentUser.id));
-    }
+    if (notificationId) {
+      await db()
+        .update(notifications)
+        .set({ readAt: now })
+        .where(
+          and(
+            eq(notifications.id, notificationId),
+            eq(notifications.recipientId, currentUser.id),
+            isNull(notifications.readAt)
+          )
+        );
+    } else {
+      await db()
+        .update(notifications)
+        .set({ readAt: now })
+        .where(
+          and(
+            eq(notifications.recipientId, currentUser.id),
+            isNull(notifications.readAt)
+          )
+        );
+    }

Also applies to: 17-27

🤖 Prompt for AI Agents
In apps/web/actions/notifications/mark-as-read.ts around lines 6 and 17 to 27,
the update operation currently allows any authenticated user to mark any
notification as read by ID alone and overwrites the readAt timestamp even for
already read notifications. To fix this, modify the update queries to include a
condition that the notification belongs to the current user and that readAt is
null (unread). This will restrict updates to only unread notifications owned by
the user, tightening authorization and preventing unnecessary overwrites.

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.

2 participants