Skip to content

Allow 2-way sort, simplify bulk unsub, and other bulk unsub fixes#1071

Merged
elie222 merged 5 commits intomainfrom
feat/two-way-sort
Dec 5, 2025
Merged

Allow 2-way sort, simplify bulk unsub, and other bulk unsub fixes#1071
elie222 merged 5 commits intomainfrom
feat/two-way-sort

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Dec 4, 2025

Add 2‑way sort to Bulk Unsubscribe lists and switch filter to single‑select dropdown across newsletters UI

Implement header click toggling for ascending/descending sort with orderDirection wired through UI and API, replace multi-toggle filters with a single-select dropdown, and update the newsletters stats endpoint to accept and apply orderDirection while matching from and fromName. Include disabled gating for email actions analytics and load env for Prisma. Key entry points: BulkUnsubscribeSection.tsx, route.ts, and BulkUnsubscribeDesktop.tsx.

📍Where to Start

Start with the list behavior and sorting flow in BulkUnsubscribeSection.tsx, then follow API changes in apps/web/app/api/user/stats/newsletters/route.ts and the header UI in BulkUnsubscribeDesktop.tsx.


📊 Macroscope summarized 21ccfe8. 9 files reviewed, 5 issues evaluated, 5 issues filtered, 0 comments posted

🗂️ Filtered Issues

apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx — 0 comments posted, 3 evaluated, 3 filtered
  • line 30: throttledSearch is created with useCallback(..., []) but closes over onSearch. If onSearch changes between renders, the throttled function will continue calling the stale onSearch, leading to incorrect behavior. Include onSearch in the dependency array and ensure you cancel the previous throttle when it changes to avoid orphaned timers. [ Low confidence ]
  • line 30: The throttled function created by throttle may schedule a trailing call that fires after the component unmounts. There is no cleanup to cancel pending calls, which can produce unexpected side effects by invoking onSearch after unmount. Add a cleanup to cancel it (e.g., store the throttled function and call throttled.cancel() in a useEffect cleanup). [ Out of scope ]
  • line 37: watch((data) => { ... }) is invoked directly during render and its subscription is never cleaned up. In React Hook Form v7, calling watch with a callback returns a subscription that must be unsubscribed, otherwise a new subscription is created on every render, causing memory leaks and duplicate callbacks. Move the watch call inside a useEffect and unsubscribe in the cleanup: const subscription = watch(cb); return () => subscription.unsubscribe();. Offending code at lines 37–41. [ Out of scope ]
apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx — 0 comments posted, 1 evaluated, 1 filtered
  • line 44: EmailActionsAnalytics renders the chart when data is truthy, but passes data.result to BarChart without verifying it’s an array. If the fetch returns a non-OK response that still parses as JSON (the default useOrgSWR fetcher returns res.json() regardless of status), data may be an error object without result, making data.result undefined. Passing undefined to Recharts data may cause runtime errors or empty/misleading charts. Add a guard to ensure Array.isArray(data.result) before rendering, or handle non-OK responses in the fetcher by throwing on !res.ok. Offending usage at line 44. [ Out of scope ]
apps/web/app/api/user/stats/email-actions/route.ts — 0 comments posted, 1 evaluated, 1 filtered
  • line 16: Potential crash if getEmailActionsByDay does not return an object with an array data property. The code does (...).data.map(...) without checking existence/type. If data is undefined, null, or not an array, this will throw at runtime, causing a 500 response. Add a guard like const res = await getEmailActionsByDay(...); const rows = Array.isArray(res?.data) ? res.data : []; before mapping. [ Out of scope ]

Summary by CodeRabbit

  • New Features

    • Added filter dropdown menu with predefined filter options (All, Unhandled, Unsubscribed, Skip Inbox, Approved)
  • Improvements

    • Enhanced search functionality to include sender names in results
    • Improved sort controls with directional indicators
    • Optimized database performance with query indexing

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel
Copy link

vercel bot commented Dec 4, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Updated (UTC)
inbox-zero Canceled Canceled Dec 4, 2025 11:58pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 4, 2025

Walkthrough

This PR refactors the bulk-unsubscribe feature's sorting and filtering mechanisms, shifting from internal state management to external controls and replacing boolean-flag filters with a single string-based filter type. Backend API support is added for explicit sort direction and enhanced email search via fromName field. Database schema is updated with a composite index on emailAccountId and fromName. Version bumped from v2.21.46 to v2.21.47.

Changes

Cohort / File(s) Summary
Bulk-unsubscribe UI Components
apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsx, BulkUnsubscribeSection.tsx
Refactored sorting to use external state (sortDirection, onSort props) instead of internal setSortColumn. BulkUnsubscribeSection now uses dropdown-based filter UI, integrates sorting controls, and replaces client-side "Only unhandled" toggle with backend-driven filtering. SearchBar integrated into action bar.
Sort, Filter & State Management
apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx, hooks.ts, SearchBar.tsx
HeaderButton component now conditionally displays ChevronUpIcon/ChevronDownIcon based on sortDirection prop. useNewsletterFilter hook refactored from boolean-flag map to single string union type (NewsletterFilterType). SearchBar adds form submission preventDefault.
Backend API Updates
apps/web/app/api/user/stats/email-actions/route.ts, newsletters/route.ts
Email-actions route adds Tinybird disabled check, returning disabled flag in response. Newsletters route adds optional orderDirection parameter ("asc" | "desc"), updates search logic to query both from and fromName fields with COALESCE, and threads orderDirection through order-by clause construction.
Database Schema & Indexing
apps/web/prisma/schema.prisma, prisma/migrations/20251204222441_fromname_index/migration.sql
Added composite index on EmailMessage model covering [emailAccountId, fromName]. Migration creates corresponding database index.
Stats Components & Utilities
apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx, useExpanded.tsx
EmailActionsAnalytics adds early return for disabled feature state. useExpanded hook accepts options parameter with resultCount and collapsedLimit (default 50), conditionally rendering UI based on shouldShowButton logic.
Configuration & Version
apps/web/prisma.config.ts, version.txt
Added dotenv/config import to prisma.config.ts for automatic environment variable loading. Version incremented from v2.21.46 to v2.21.47.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Focus areas requiring attention:
    • BulkUnsubscribeSection: substantial refactoring of filter dropdown UI, sort state integration, and state management overhaul—verify all filter/sort combinations work correctly and that backend query parameters are correctly threaded
    • useNewsletterFilter hook: state representation changed from object to string union; confirm all downstream consumers of filtersArray derive correct values
    • Newsletters route orderDirection logic: verify search behavior combining from and fromName fields with COALESCE works as intended and doesn't regress existing queries
    • BulkUnsubscribeDesktop prop signature change: ensure parent component passes new sortDirection and onSort props correctly

Possibly related PRs

Poem

🐰 Filters and sorts now dance as one,
State flows outward—refactoring's done!
From booleans to strings, the schema grows wise,
With indexes that sparkle and orderDirection's prize.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately reflects the main changes: implementing 2-way sorting, simplifying bulk unsubscribe UI, and addressing related fixes across multiple components.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/two-way-sort

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx (1)

30-35: Stale closure: onSearch is not in the dependency array.

The throttled function captures onSearch but the dependency array is empty. If onSearch changes, the throttled function will still use the original callback.

   const throttledSearch = useCallback(
     throttle((value: string) => {
       onSearch(value.trim());
     }, 300),
-    [],
+    [onSearch],
   );
🧹 Nitpick comments (3)
apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx (1)

22-31: Early-return UX for disabled state is correct and consistent

Short‑circuiting on data?.disabled to render a static CardBasic before the LoadingContent path fits the new API contract and avoids confusing loading/error states for a feature that’s globally disabled. The copy stays consistent with the chart view, and consumers still use the typed EmailActionStatsResponse, so this is a clean, non‑breaking UI adjustment.

apps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsx (1)

23-48: Consider making dependencies more explicit.

The current dependency array works correctly but includes both expanded and shouldShowButton (which itself depends on expanded). For better clarity, consider:

Option 1: Include all primitive dependencies:

}, [expanded, toggleExpand, resultCount, collapsedLimit]);

Option 2: Move shouldShowButton calculation inside the useMemo:

const extra = useMemo(() => {
  const shouldShowButton =
    expanded || (resultCount !== undefined && resultCount >= collapsedLimit);
  
  if (!shouldShowButton) return null;
  // ... rest of the logic
}, [expanded, toggleExpand, resultCount, collapsedLimit]);

Either approach makes the dependencies more explicit and easier to understand.

apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx (1)

175-175: Consider memoizing the expanded state toggle.

The expanded state is simple, but if performance becomes a concern with frequent re-renders, wrapping the toggle in useCallback could help. This is optional given the current scope.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 635f990 and 21ccfe8.

📒 Files selected for processing (13)
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsx (2 hunks)
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx (6 hunks)
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx (1 hunks)
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx (3 hunks)
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts (1 hunks)
  • apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx (1 hunks)
  • apps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsx (2 hunks)
  • apps/web/app/api/user/stats/email-actions/route.ts (2 hunks)
  • apps/web/app/api/user/stats/newsletters/route.ts (5 hunks)
  • apps/web/prisma.config.ts (1 hunks)
  • apps/web/prisma/migrations/20251204222441_fromname_index/migration.sql (1 hunks)
  • apps/web/prisma/schema.prisma (1 hunks)
  • version.txt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (22)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Use @/ path aliases for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Follow consistent naming conventions using PascalCase for components
Centralize shared types in dedicated type files

Import specific lodash functions rather than entire lodash library to minimize bundle size (e.g., import groupBy from 'lodash/groupBy')

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/api/user/stats/newsletters/route.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
  • apps/web/app/api/user/stats/email-actions/route.ts
  • apps/web/prisma.config.ts
apps/web/app/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

Follow NextJS app router structure with (app) directory

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/api/user/stats/newsletters/route.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
  • apps/web/app/api/user/stats/email-actions/route.ts
apps/web/**/*.tsx

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.tsx: Follow tailwindcss patterns with prettier-plugin-tailwindcss for class sorting
Prefer functional components with hooks over class components
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach
Use LoadingContent component for async data with loading and error states

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/data-fetching.mdc)

**/*.{ts,tsx}: For API GET requests to server, use the swr package
Use result?.serverError with toastError from @/components/Toast for error handling in async operations

**/*.{ts,tsx}: Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls

**/*.{ts,tsx}: For early access feature flags, create hooks using the naming convention use[FeatureName]Enabled that return a boolean from useFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming convention use[FeatureName]Variant that define variant types, use useFeatureFlagVariantKey() with type casting, and provide a default "control" fallback
Use kebab-case for PostHog feature flag keys (e.g., inbox-cleaner, pricing-options-2)
Always define types for A/B test variant flags (e.g., type PricingVariant = "control" | "variant-a" | "variant-b") and provide type safety through type casting

**/*.{ts,tsx}: Don't use primitive type aliases or misleading types
Don't use empty type parameters in type aliases and interfaces
Don't use this and super in static contexts
Don't use any or unknown as type constraints
Don't use the TypeScript directive @ts-ignore
Don't use TypeScript enums
Don't export imported variables
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions
Don't use TypeScript namespaces
Don't use non-null assertions with the ! postfix operator
Don't use parameter properties in class constructors
Don't use user-defined types
Use as const instead of literal types and type annotations
Use either T[] or Array<T> consistently
Initialize each enum member value explicitly
Use export type for types
Use `impo...

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/api/user/stats/newsletters/route.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
  • apps/web/app/api/user/stats/email-actions/route.ts
  • apps/web/prisma.config.ts
apps/web/app/(app)/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

apps/web/app/(app)/**/*.{ts,tsx}: Components for the page are either put in page.tsx, or in the apps/web/app/(app)/PAGE_NAME folder
If we're in a deeply nested component we will use swr to fetch via API
If you need to use onClick in a component, that component is a client component and file must start with use client

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/prisma-enum-imports.mdc)

Always import Prisma enums from @/generated/prisma/enums instead of @/generated/prisma/client to avoid Next.js bundling errors in client components

Import Prisma using the project's centralized utility: import prisma from '@/utils/prisma'

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/api/user/stats/newsletters/route.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
  • apps/web/app/api/user/stats/email-actions/route.ts
  • apps/web/prisma.config.ts
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)

**/*.{tsx,ts}: Use Shadcn UI and Tailwind for components and styling
Use next/image package for images
For API GET requests to server, use the swr package with hooks like useSWR to fetch data
For text inputs, use the Input component with registerProps for form integration and error handling

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/api/user/stats/newsletters/route.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
  • apps/web/app/api/user/stats/email-actions/route.ts
  • apps/web/prisma.config.ts
**/*.{tsx,ts,css}

📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)

Implement responsive design with Tailwind CSS using a mobile-first approach

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/api/user/stats/newsletters/route.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
  • apps/web/app/api/user/stats/email-actions/route.ts
  • apps/web/prisma.config.ts
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)

**/*.tsx: Use the LoadingContent component to handle loading states instead of manual loading state management
For text areas, use the Input component with type='text', autosizeTextarea prop set to true, and registerProps for form integration

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use accessKey attribute on any HTML element
Don't set aria-hidden="true" on focusable elements
Don't add ARIA roles, states, and properties to elements that don't support them
Don't use distracting elements like <marquee> or <blink>
Only use the scope prop on <th> elements
Don't assign non-interactive ARIA roles to interactive HTML elements
Make sure label elements have text content and are associated with an input
Don't assign interactive ARIA roles to non-interactive HTML elements
Don't assign tabIndex to non-interactive HTML elements
Don't use positive integers for tabIndex property
Don't include "image", "picture", or "photo" in img alt prop
Don't use explicit role property that's the same as the implicit/default role
Make static elements with click handlers use a valid role attribute
Always include a title element for SVG elements
Give all elements requiring alt text meaningful information for screen readers
Make sure anchors have content that's accessible to screen readers
Assign tabIndex to non-interactive HTML elements with aria-activedescendant
Include all required ARIA attributes for elements with ARIA roles
Make sure ARIA properties are valid for the element's supported roles
Always include a type attribute for button elements
Make elements with interactive roles and handlers focusable
Give heading elements content that's accessible to screen readers (not hidden with aria-hidden)
Always include a lang attribute on the html element
Always include a title attribute for iframe elements
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress
Accompany onMouseOver/onMouseOut with onFocus/onBlur
Include caption tracks for audio and video elements
Use semantic elements instead of role attributes in JSX
Make sure all anchors are valid and navigable
Ensure all ARIA properties (aria-*) are valid
Use valid, non-abstract ARIA roles for elements with ARIA roles
Use valid AR...

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/api/user/stats/newsletters/route.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
  • apps/web/app/api/user/stats/email-actions/route.ts
  • apps/web/prisma.config.ts
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{jsx,tsx}: Don't use unnecessary fragments
Don't pass children as props
Don't use the return value of React.render
Make sure all dependencies are correctly specified in React hooks
Make sure all React hooks are called from the top level of component functions
Don't forget key props in iterators and collection literals
Don't define React components inside other components
Don't use event handlers on non-interactive elements
Don't assign to React component props
Don't use both children and dangerouslySetInnerHTML props on the same element
Don't use dangerous JSX props
Don't use Array index in keys
Don't insert comments as text nodes
Don't assign JSX properties multiple times
Don't add extra closing tags for components without children
Use <>...</> instead of <Fragment>...</Fragment>
Watch out for possible "wrong" semicolons inside JSX elements
Make sure void (self-closing) elements don't have children
Don't use target="_blank" without rel="noopener"
Don't use <img> elements in Next.js projects
Don't use <head> elements in Next.js projects

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
!(pages/_document).{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

Don't use the next/head module in pages/_document.js on Next.js projects

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsx
  • apps/web/prisma/schema.prisma
  • version.txt
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/api/user/stats/newsletters/route.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsx
  • apps/web/prisma/migrations/20251204222441_fromname_index/migration.sql
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
  • apps/web/app/api/user/stats/email-actions/route.ts
  • apps/web/prisma.config.ts
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/utilities.mdc)

**/*.{js,ts,jsx,tsx}: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size (e.g., import groupBy from 'lodash/groupBy')

Files:

  • apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx
  • apps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/api/user/stats/newsletters/route.ts
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
  • apps/web/app/api/user/stats/email-actions/route.ts
  • apps/web/prisma.config.ts
**/prisma/schema.prisma

📄 CodeRabbit inference engine (.cursor/rules/prisma.mdc)

Use PostgreSQL as the database system with Prisma

Files:

  • apps/web/prisma/schema.prisma
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/security.mdc)

**/*.ts: ALL database queries MUST be scoped to the authenticated user/account by including user/account filtering in WHERE clauses to prevent unauthorized data access
Always validate that resources belong to the authenticated user before performing operations, using ownership checks in WHERE clauses or relationships
Always validate all input parameters for type, format, and length before using them in database queries
Use SafeError for error responses to prevent information disclosure. Generic error messages should not reveal internal IDs, logic, or resource ownership details
Only return necessary fields in API responses using Prisma's select option. Never expose sensitive data such as password hashes, private keys, or system flags
Prevent Insecure Direct Object References (IDOR) by validating resource ownership before operations. All findUnique/findFirst calls MUST include ownership filters
Prevent mass assignment vulnerabilities by explicitly whitelisting allowed fields in update operations instead of accepting all user-provided data
Prevent privilege escalation by never allowing users to modify system fields, ownership fields, or admin-only attributes through user input
All findMany queries MUST be scoped to the user's data by including appropriate WHERE filters to prevent returning data from other users
Use Prisma relationships for access control by leveraging nested where clauses (e.g., emailAccount: { id: emailAccountId }) to validate ownership

Files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
  • apps/web/app/api/user/stats/newsletters/route.ts
  • apps/web/app/api/user/stats/email-actions/route.ts
  • apps/web/prisma.config.ts
apps/web/app/api/**/*.ts

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/app/api/**/*.ts: Wrap GET API routes with withAuth or withEmailAccount middleware for authentication
Export response types from GET API routes using Awaited<ReturnType<>> pattern for type-safe client usage

Files:

  • apps/web/app/api/user/stats/newsletters/route.ts
  • apps/web/app/api/user/stats/email-actions/route.ts
apps/web/app/api/**/route.ts

📄 CodeRabbit inference engine (.cursor/rules/fullstack-workflow.mdc)

apps/web/app/api/**/route.ts: Create GET API routes using withAuth or withEmailAccount middleware in apps/web/app/api/*/route.ts, export response types as GetExampleResponse type alias for client-side type safety
Always export response types from GET routes as Get[Feature]Response using type inference from the data fetching function for type-safe client consumption
Do NOT use POST API routes for mutations - always use server actions with next-safe-action instead

Files:

  • apps/web/app/api/user/stats/newsletters/route.ts
  • apps/web/app/api/user/stats/email-actions/route.ts
**/app/**/route.ts

📄 CodeRabbit inference engine (.cursor/rules/get-api-route.mdc)

**/app/**/route.ts: Always wrap GET API route handlers with withAuth or withEmailAccount middleware for consistent error handling and authentication in Next.js App Router
Infer and export response type for GET API routes using Awaited<ReturnType<typeof functionName>> pattern in Next.js
Use Prisma for database queries in GET API routes
Return responses using NextResponse.json() in GET API routes
Do not use try/catch blocks in GET API route handlers when using withAuth or withEmailAccount middleware, as the middleware handles error handling

Files:

  • apps/web/app/api/user/stats/newsletters/route.ts
  • apps/web/app/api/user/stats/email-actions/route.ts
**/{server,api,actions,utils}/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/{server,api,actions,utils}/**/*.ts: Use createScopedLogger from "@/utils/logger" for logging in backend code
Add the createScopedLogger instantiation at the top of the file with an appropriate scope name
Use .with() method to attach context variables only within specific functions, not on global loggers
For large functions with reused variables, use createScopedLogger().with() to attach context once and reuse the logger without passing variables repeatedly

Files:

  • apps/web/app/api/user/stats/newsletters/route.ts
  • apps/web/app/api/user/stats/email-actions/route.ts
apps/web/app/**/[!.]*/route.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Use kebab-case for route directories in Next.js App Router (e.g., api/hello-world/route)

Files:

  • apps/web/app/api/user/stats/newsletters/route.ts
  • apps/web/app/api/user/stats/email-actions/route.ts
apps/web/app/api/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/security-audit.mdc)

apps/web/app/api/**/*.{ts,tsx}: API routes must use withAuth, withEmailAccount, or withError middleware for authentication
All database queries must include user scoping with emailAccountId or userId filtering in WHERE clauses
Request parameters must be validated before use; avoid direct parameter usage without type checking
Use generic error messages instead of revealing internal details; throw SafeError instead of exposing user IDs, resource IDs, or system information
API routes should only return necessary fields using select in database queries to prevent unintended information disclosure
Cron endpoints must use hasCronSecret or hasPostCronSecret to validate cron requests and prevent unauthorized access
Request bodies should use Zod schemas for validation to ensure type safety and prevent injection attacks

Files:

  • apps/web/app/api/user/stats/newsletters/route.ts
  • apps/web/app/api/user/stats/email-actions/route.ts
**/app/api/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/security.mdc)

**/app/api/**/*.ts: ALL API routes that handle user data MUST use appropriate middleware: use withEmailAccount for email-scoped operations, use withAuth for user-scoped operations, or use withError with proper validation for public/custom auth endpoints
Use withEmailAccount middleware for operations scoped to a specific email account, including reading/writing emails, rules, schedules, or any operation using emailAccountId
Use withAuth middleware for user-level operations such as user settings, API keys, and referrals that use only userId
Use withError middleware only for public endpoints, custom authentication logic, or cron endpoints. For cron endpoints, MUST use hasCronSecret() or hasPostCronSecret() validation
Cron endpoints without proper authentication can be triggered by anyone. CRITICAL: All cron endpoints MUST validate cron secret using hasCronSecret(request) or hasPostCronSecret(request) and capture unauthorized attempts with captureException()
Always validate request bodies using Zod schemas to ensure type safety and prevent invalid data from reaching database operations
Maintain consistent error response format across all API routes to avoid information disclosure while providing meaningful error feedback

Files:

  • apps/web/app/api/user/stats/newsletters/route.ts
  • apps/web/app/api/user/stats/email-actions/route.ts
🧠 Learnings (42)
📚 Learning: 2025-11-25T14:39:49.448Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-11-25T14:39:49.448Z
Learning: Applies to apps/web/utils/actions/*.ts : Use `actionClient` when both authenticated user context and a specific emailAccountId are needed, with emailAccountId bound when calling from the client

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
  • apps/web/app/api/user/stats/email-actions/route.ts
📚 Learning: 2025-07-08T13:14:07.449Z
Learnt from: elie222
Repo: elie222/inbox-zero PR: 537
File: apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx:30-34
Timestamp: 2025-07-08T13:14:07.449Z
Learning: The clean onboarding page in apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx is intentionally Gmail-specific and should show an error for non-Google email accounts rather than attempting to support multiple providers.

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsx
📚 Learning: 2025-11-25T14:36:53.147Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-11-25T14:36:53.147Z
Learning: Applies to **/*Form.{ts,tsx} : Validate form inputs before submission

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
📚 Learning: 2025-06-05T09:49:12.168Z
Learnt from: elie222
Repo: elie222/inbox-zero PR: 485
File: apps/web/app/(landing)/login/page.tsx:41-43
Timestamp: 2025-06-05T09:49:12.168Z
Learning: In Next.js App Router, components that use the `useSearchParams` hook require a Suspense boundary to handle the asynchronous nature of search parameter access. The Suspense wrapper is necessary and should not be removed when a component uses useSearchParams.

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
📚 Learning: 2025-11-25T14:37:09.306Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-11-25T14:37:09.306Z
Learning: Applies to apps/web/components/**/*Form*.tsx : Handle form submission results using `result?.serverError` to show error toasts and `toastSuccess` to show success messages after server action completion

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
📚 Learning: 2025-11-25T14:36:51.389Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/form-handling.mdc:0-0
Timestamp: 2025-11-25T14:36:51.389Z
Learning: Applies to **/*Form.{ts,tsx} : Validate form inputs before submission using React Hook Form and Zod resolver

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
📚 Learning: 2025-11-25T14:42:08.869Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ultracite.mdc:0-0
Timestamp: 2025-11-25T14:42:08.869Z
Learning: Applies to **/*.{jsx,tsx} : Don't use event handlers on non-interactive elements

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
📚 Learning: 2025-11-25T14:40:13.649Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-11-25T14:40:13.649Z
Learning: Applies to **/*.{tsx,ts,jsx,js} : For text inputs in forms, use the `Input` component with `type='email'`, `name`, `label`, `registerProps` from react-hook-form, and `error` props

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
📚 Learning: 2025-11-25T14:40:13.649Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-11-25T14:40:13.649Z
Learning: Applies to **/*.{tsx,ts,jsx,js} : For text areas in forms, use the `Input` component with `type='text'`, `autosizeTextarea` prop, `rows`, `name`, `placeholder`, `registerProps` from react-hook-form, and `error` props

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
📚 Learning: 2025-11-25T14:40:15.063Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-11-25T14:40:15.063Z
Learning: Applies to **/*.{tsx,ts} : For text inputs, use the `Input` component with `registerProps` for form integration and error handling

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx
📚 Learning: 2024-08-23T11:37:26.779Z
Learnt from: aryanprince
Repo: elie222/inbox-zero PR: 210
File: apps/web/app/(app)/stats/NewsletterModal.tsx:2-4
Timestamp: 2024-08-23T11:37:26.779Z
Learning: `MoreDropdown` is a React component and `useUnsubscribeButton` is a custom React hook, and they should not be imported using `import type`.

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsx
  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
📚 Learning: 2025-11-25T14:38:32.328Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/posthog-feature-flags.mdc:0-0
Timestamp: 2025-11-25T14:38:32.328Z
Learning: Centralize all feature flag hooks in `apps/web/hooks/useFeatureFlags.ts` rather than scattering them across multiple files

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
📚 Learning: 2025-11-25T14:38:32.328Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/posthog-feature-flags.mdc:0-0
Timestamp: 2025-11-25T14:38:32.328Z
Learning: Applies to apps/web/hooks/useFeatureFlags.ts : Feature flag hooks should be defined in `apps/web/hooks/useFeatureFlags.ts` with two patterns: boolean flags using `useFeatureFlagEnabled("key")` and variant flags using `useFeatureFlagVariantKey("key")` with type casting

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
📚 Learning: 2025-11-25T14:38:27.988Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/posthog-feature-flags.mdc:0-0
Timestamp: 2025-11-25T14:38:27.988Z
Learning: Applies to apps/web/hooks/useFeatureFlags.ts : All feature flag hooks should be defined in `apps/web/hooks/useFeatureFlags.ts`

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts
📚 Learning: 2025-11-25T14:39:08.150Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-11-25T14:39:08.150Z
Learning: Applies to apps/web/app/api/**/*.{ts,tsx} : All database queries must include user scoping with `emailAccountId` or `userId` filtering in WHERE clauses

Applied to files:

  • apps/web/app/api/user/stats/newsletters/route.ts
📚 Learning: 2025-11-25T14:39:27.909Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:27.909Z
Learning: Applies to **/*.ts : Use Prisma relationships for access control by leveraging nested where clauses (e.g., `emailAccount: { id: emailAccountId }`) to validate ownership

Applied to files:

  • apps/web/app/api/user/stats/newsletters/route.ts
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to **/*.ts : ALL database queries MUST be scoped to the authenticated user/account - include user/account filtering in `where` clauses (e.g., `emailAccountId`, `userId`) to ensure users only access their own resources

Applied to files:

  • apps/web/app/api/user/stats/newsletters/route.ts
📚 Learning: 2025-11-25T14:37:30.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-11-25T14:37:30.660Z
Learning: Applies to apps/web/hooks/use*.ts : Create dedicated hooks for specific data types (e.g., `useAccounts`, `useLabels`) that wrap `useSWR`, handle the API endpoint URL, and return data, loading state, error state, and the `mutate` function

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
📚 Learning: 2025-11-25T14:37:35.343Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-11-25T14:37:35.343Z
Learning: Applies to apps/web/hooks/use*.ts : Create dedicated hooks for specific data types (e.g., `useAccounts`, `useLabels`) to wrap `useSWR` for individual API endpoints

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
📚 Learning: 2025-11-25T14:40:13.649Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-11-25T14:40:13.649Z
Learning: Applies to **/*.{tsx,ts,jsx,js} : For API get requests to server, use the `swr` package with `useSWR` hook

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
📚 Learning: 2025-11-25T14:38:18.874Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/page-structure.mdc:0-0
Timestamp: 2025-11-25T14:38:18.874Z
Learning: Applies to apps/web/app/(app)/**/*.tsx : If nested deeply in components, use `swr` to fetch via API instead of loading data directly

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
📚 Learning: 2025-11-25T14:38:56.992Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/project-structure.mdc:0-0
Timestamp: 2025-11-25T14:38:56.992Z
Learning: Use `swr` for data fetching in deeply nested components

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
📚 Learning: 2025-11-25T14:37:30.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-11-25T14:37:30.660Z
Learning: Applies to apps/web/hooks/use*.ts : For data fetching, prefer using `useSWR` and follow the data-fetching guidelines

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
📚 Learning: 2025-11-25T14:36:18.416Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-11-25T14:36:18.416Z
Learning: Applies to apps/web/**/*.tsx : Use shadcn/ui components when available

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
📚 Learning: 2025-11-25T14:37:35.343Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/hooks.mdc:0-0
Timestamp: 2025-11-25T14:37:35.343Z
Learning: Applies to apps/web/hooks/use*.ts : For data fetching in custom hooks, prefer using `useSWR` and wrap it to handle API endpoint URL, returning data, loading state, error state, and potentially the `mutate` function

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
📚 Learning: 2025-11-25T14:40:15.063Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/ui-components.mdc:0-0
Timestamp: 2025-11-25T14:40:15.063Z
Learning: Applies to **/*.{tsx,ts} : For API GET requests to server, use the `swr` package with hooks like `useSWR` to fetch data

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
📚 Learning: 2025-11-25T14:42:11.919Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/utilities.mdc:0-0
Timestamp: 2025-11-25T14:42:11.919Z
Learning: Applies to utils/**/*.{js,ts,jsx,tsx} : The `utils` folder contains core app logic such as Next.js Server Actions and Gmail API requests

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
  • apps/web/app/api/user/stats/email-actions/route.ts
📚 Learning: 2025-11-25T14:38:56.992Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/project-structure.mdc:0-0
Timestamp: 2025-11-25T14:38:56.992Z
Learning: Applies to apps/web/components/ui/**/*.tsx : Shadcn UI components are located in `components/ui` directory

Applied to files:

  • apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to app/api/**/*.ts : Use `withEmailAccount` middleware for operations scoped to a specific email account (reading/writing emails, rules, schedules, etc.) - provides `emailAccountId`, `userId`, and `email` in `request.auth`

Applied to files:

  • apps/web/app/api/user/stats/email-actions/route.ts
📚 Learning: 2025-11-25T14:37:22.660Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/gmail-api.mdc:0-0
Timestamp: 2025-11-25T14:37:22.660Z
Learning: Applies to **/*.{ts,tsx} : Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls

Applied to files:

  • apps/web/app/api/user/stats/email-actions/route.ts
📚 Learning: 2025-11-25T14:39:27.909Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:27.909Z
Learning: Applies to **/app/api/**/*.ts : Use `withEmailAccount` middleware for operations scoped to a specific email account, including reading/writing emails, rules, schedules, or any operation using `emailAccountId`

Applied to files:

  • apps/web/app/api/user/stats/email-actions/route.ts
📚 Learning: 2025-11-25T14:42:16.602Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/utilities.mdc:0-0
Timestamp: 2025-11-25T14:42:16.602Z
Learning: The `utils` folder contains core app logic such as Next.js Server Actions and Gmail API requests

Applied to files:

  • apps/web/app/api/user/stats/email-actions/route.ts
📚 Learning: 2025-11-25T14:38:42.022Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/prisma.mdc:0-0
Timestamp: 2025-11-25T14:38:42.022Z
Learning: Applies to **/*.{ts,tsx,js,jsx} : Import Prisma using the project's centralized utility: `import prisma from '@/utils/prisma'`

Applied to files:

  • apps/web/prisma.config.ts
📚 Learning: 2025-11-25T14:36:45.807Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/environment-variables.mdc:0-0
Timestamp: 2025-11-25T14:36:45.807Z
Learning: Applies to apps/web/env.ts : Add client-side environment variables to `apps/web/env.ts` under the `client` object with `NEXT_PUBLIC_` prefix and Zod schema validation

Applied to files:

  • apps/web/prisma.config.ts
📚 Learning: 2025-11-25T14:36:18.416Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-11-25T14:36:18.416Z
Learning: Applies to apps/web/**/{.env.example,env.ts,turbo.json} : Add environment variables to `.env.example`, `env.ts`, and `turbo.json`

Applied to files:

  • apps/web/prisma.config.ts
📚 Learning: 2025-11-25T14:36:43.454Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/environment-variables.mdc:0-0
Timestamp: 2025-11-25T14:36:43.454Z
Learning: Applies to apps/web/env.ts : Define environment variables in `apps/web/env.ts` using Zod schema validation, organizing them into `server` and `client` sections

Applied to files:

  • apps/web/prisma.config.ts
📚 Learning: 2025-11-25T14:36:45.807Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/environment-variables.mdc:0-0
Timestamp: 2025-11-25T14:36:45.807Z
Learning: Applies to apps/web/env.ts : Add client-side environment variables to `apps/web/env.ts` under the `experimental__runtimeEnv` object to enable runtime access

Applied to files:

  • apps/web/prisma.config.ts
📚 Learning: 2025-11-25T14:38:37.508Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/prisma-enum-imports.mdc:0-0
Timestamp: 2025-11-25T14:38:37.508Z
Learning: Applies to **/*.{ts,tsx,js,jsx} : Always import Prisma enums from `@/generated/prisma/enums` instead of `@/generated/prisma/client` to avoid Next.js bundling errors in client components

Applied to files:

  • apps/web/prisma.config.ts
📚 Learning: 2025-11-25T14:36:45.807Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/environment-variables.mdc:0-0
Timestamp: 2025-11-25T14:36:45.807Z
Learning: Applies to apps/web/env.ts : Add server-only environment variables to `apps/web/env.ts` under the `server` object with Zod schema validation

Applied to files:

  • apps/web/prisma.config.ts
📚 Learning: 2025-11-25T14:40:00.833Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-25T14:40:00.833Z
Learning: Applies to **/*.test.{ts,tsx} : Mock Prisma using `vi.mock("@/utils/prisma")` and import the mock from `@/utils/__mocks__/prisma`

Applied to files:

  • apps/web/prisma.config.ts
📚 Learning: 2025-11-25T14:36:43.454Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/environment-variables.mdc:0-0
Timestamp: 2025-11-25T14:36:43.454Z
Learning: Applies to apps/web/env.ts : For client-side environment variables in `apps/web/env.ts`, prefix them with `NEXT_PUBLIC_` and add them to both the `client` and `experimental__runtimeEnv` sections

Applied to files:

  • apps/web/prisma.config.ts
📚 Learning: 2025-11-25T14:39:27.909Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:27.909Z
Learning: Applies to **/*.ts : Only return necessary fields in API responses using Prisma's `select` option. Never expose sensitive data such as password hashes, private keys, or system flags

Applied to files:

  • apps/web/prisma.config.ts
🧬 Code graph analysis (3)
apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsx (1)
apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx (1)
  • HeaderButton (510-535)
apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx (5)
apps/web/components/new-landing/icons/Newsletter.tsx (1)
  • Newsletter (1-18)
apps/web/app/api/user/stats/newsletters/route.ts (2)
  • NewsletterStatsResponse (36-38)
  • NewsletterStatsQuery (35-35)
apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts (2)
  • NewsletterFilterType (659-664)
  • useNewsletterFilter (666-685)
apps/web/components/DatePickerWithRange.tsx (1)
  • DatePickerWithRange (37-115)
apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx (1)
  • SearchBar (14-64)
apps/web/app/api/user/stats/email-actions/route.ts (1)
packages/tinybird/src/client.ts (1)
  • isTinybirdEnabled (8-10)
⏰ 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). (2)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Review for correctness
🔇 Additional comments (22)
apps/web/app/api/user/stats/email-actions/route.ts (1)

3-22: Clean disabled-path handling and response shape look good

Importing isTinybirdEnabled and short‑circuiting to { result: [], disabled: true as const } keeps the route cheap when Tinybird is off, and the { result, disabled: false as const } shape is a nice discriminated union for the client. The handler still uses withEmailAccount and NextResponse.json, and the EmailActionStatsResponse alias remains correctly inferred from getEmailActionStats, so this aligns with the API and security guidelines for app routes.

apps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsx (2)

5-10: LGTM! Well-structured hook signature with clear documentation.

The optional options parameter with JSDoc comments makes the API clear and type-safe.


11-11: LGTM! Safe destructuring with proper defaults.

The nullish coalescing and default value handling is correct.

apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsx (1)

52-60: LGTM on form submission prevention.

The preventDefault handler correctly prevents page reload when the user presses Enter in the search input, allowing the throttled search to handle the query.

apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsx (1)

510-535: LGTM on HeaderButton sort direction support.

The optional sortDirection prop enables bi-directional sorting with appropriate visual feedback. The icon logic correctly shows:

  • ChevronUpIcon for ascending sort
  • ChevronDownIcon for descending sort (or when sorted but direction is undefined)
  • ChevronsUpDownIcon when not sorted
apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsx (2)

25-39: LGTM on externalized sort control.

The component correctly transitions to a controlled pattern where sort state is managed by the parent. The prop types are well-defined and the sortDirection is conditionally passed only to the active sort column.


51-82: Sort direction passed correctly per column.

Each HeaderButton receives sortDirection only when that column is currently sorted (sortColumn === "column"), and delegates sorting to the onSort callback. This correctly implements the 2-way sort UI.

apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.ts (1)

659-685: LGTM on simplified filter state management.

The refactor from multiple boolean flags to a single NewsletterFilterType value is cleaner and reduces state complexity. The filtersArray derivation maintains API compatibility by expanding "all" to include all filter options.

apps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsx (5)

71-99: LGTM on filter options definition.

The filterOptions array is well-structured with type safety via NewsletterFilterType. The separatorAfter property for "Unhandled" creates a logical grouping in the dropdown UI.


150-167: LGTM on sort handling logic.

The handleSort function correctly implements bi-directional sorting:

  • Toggles between asc and desc when clicking the same column
  • Defaults to desc when switching to a new column

308-335: LGTM on filter dropdown implementation.

The dropdown follows shadcn/ui patterns correctly. The CheckIcon provides clear visual feedback for the selected filter, and the separator after "Unhandled" improves grouping.


384-406: Show more/less condition looks correct.

The condition (expanded || (rows && rows.length >= 50)) ensures the button appears when:

  • Currently expanded (to allow collapsing)
  • Or when there are 50+ results (suggesting more may be available)

This provides a reasonable UX for pagination control.


177-186: Backend correctly handles the orderDirection parameter—no action needed.

The API route defines orderDirection: z.enum(["asc", "desc"]).optional() in the schema (line 21), extracts it from query parameters (line 278), and passes it to getOrderByClause() (line 199), which applies the direction to the SQL ORDER BY clause (lines 246–264). The implementation is type-safe and properly integrated.

apps/web/app/api/user/stats/newsletters/route.ts (5)

21-21: LGTM!

The orderDirection parameter is properly validated with a Zod enum constraint and marked as optional, following the same pattern as the orderBy field.


183-189: LGTM!

The enhanced search filter correctly searches both from (email address) and fromName fields using case-insensitive matching. The COALESCE function properly handles null fromName values, and the search term is safely parameterized via Prisma.sql to prevent SQL injection.


198-200: LGTM!

The orderDirection parameter is correctly passed through to getOrderByClause, maintaining type safety via the validated Zod schema.


246-264: LGTM!

The getOrderByClause function correctly implements dynamic sort direction while maintaining security:

  • Input validation is enforced via Zod enums before reaching this function
  • The use of Prisma.raw() is safe here since all inputs are validated and no user string interpolation occurs
  • Sorting logic is correct for all three order types (emails, unread, unarchived)
  • The default fallback to "DESC" maintains backward compatibility

278-278: LGTM!

The query parameter parsing correctly handles the optional orderDirection parameter by converting null to undefined, which aligns with Zod's .optional() expectation.

version.txt (1)

1-1: LGTM! Version bump to v2.21.47.

The patch version increment is appropriate for this release.

apps/web/prisma/migrations/20251204222441_fromname_index/migration.sql (1)

1-2: LGTM! Migration correctly adds the composite index.

The CREATE INDEX statement is well-formed and aligns with the schema change. The index on (emailAccountId, fromName) will optimize queries that filter by emailAccountId and search/sort by fromName, supporting the bulk unsubscribe enhancements mentioned in the PR.

apps/web/prisma.config.ts (1)

1-1: LGTM! Ensures environment variables are loaded early.

Adding dotenv/config at the top is a best practice for Prisma configuration files, ensuring that environment variables (like DATABASE_URL and DIRECT_URL) are available during Prisma client generation, migrations, and schema introspection.

apps/web/prisma/schema.prisma (1)

705-705: LGTM! Composite index optimizes fromName queries.

The new index on (emailAccountId, fromName) is well-designed:

  • Correct column order: emailAccountId first ensures user-scoped queries, fromName second enables efficient search and sorting by sender name
  • Complements existing indexes without redundancy
  • Supports the bulk unsubscribe enhancements and 2-way sorting mentioned in the PR
  • Works correctly with nullable fromName field (line 689)

The index will optimize queries like WHERE emailAccountId = ? AND fromName LIKE 'prefix%' and WHERE emailAccountId = ? ORDER BY fromName.

Comment on lines +18 to +21
// Only show "Show more" if we have exactly the limit (meaning there might be more)
// Only show "Show less" if expanded
const shouldShowButton =
expanded || (resultCount !== undefined && resultCount >= collapsedLimit);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Update comment to match the implementation.

The comment says "exactly the limit" but the code uses >=. The >= check is correct (handles cases where there might be more results), but the comment should be updated for accuracy.

Apply this diff:

-  // Only show "Show more" if we have exactly the limit (meaning there might be more)
+  // Only show "Show more" if we have at least the limit (meaning there might be more)
🤖 Prompt for AI Agents
In apps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsx around lines 18 to
21, update the inline comment to match the implementation: replace "Only show
'Show more' if we have exactly the limit (meaning there might be more)" with a
comment stating that we show "Show more" when the resultCount is greater than or
equal to the collapsedLimit (to handle cases where there might be more results),
keeping the second comment about showing "Show less" if expanded unchanged.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

No issues found across 12 files

@elie222 elie222 merged commit f084f8b into main Dec 5, 2025
18 checks passed
@elie222 elie222 deleted the feat/two-way-sort branch December 18, 2025 23:05
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

Comments