Allow 2-way sort, simplify bulk unsub, and other bulk unsub fixes#1071
Allow 2-way sort, simplify bulk unsub, and other bulk unsub fixes#1071
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughThis 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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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:onSearchis not in the dependency array.The throttled function captures
onSearchbut the dependency array is empty. IfonSearchchanges, 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 consistentShort‑circuiting on
data?.disabledto render a staticCardBasicbefore theLoadingContentpath 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 typedEmailActionStatsResponse, 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
expandedandshouldShowButton(which itself depends onexpanded). For better clarity, consider:Option 1: Include all primitive dependencies:
}, [expanded, toggleExpand, resultCount, collapsedLimit]);Option 2: Move
shouldShowButtoncalculation 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
expandedstate is simple, but if performance becomes a concern with frequent re-renders, wrapping the toggle inuseCallbackcould help. This is optional given the current scope.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 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 filesImport 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.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsxapps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.tsapps/web/app/api/user/stats/newsletters/route.tsapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsxapps/web/app/api/user/stats/email-actions/route.tsapps/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.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsxapps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.tsapps/web/app/api/user/stats/newsletters/route.tsapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsxapps/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.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsxapps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsxapps/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 theswrpackage
Useresult?.serverErrorwithtoastErrorfrom@/components/Toastfor 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 conventionuse[FeatureName]Enabledthat return a boolean fromuseFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming conventionuse[FeatureName]Variantthat define variant types, useuseFeatureFlagVariantKey()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
Useas constinstead of literal types and type annotations
Use eitherT[]orArray<T>consistently
Initialize each enum member value explicitly
Useexport typefor types
Use `impo...
Files:
apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsxapps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.tsapps/web/app/api/user/stats/newsletters/route.tsapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsxapps/web/app/api/user/stats/email-actions/route.tsapps/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 inpage.tsx, or in theapps/web/app/(app)/PAGE_NAMEfolder
If we're in a deeply nested component we will useswrto fetch via API
If you need to useonClickin a component, that component is a client component and file must start withuse client
Files:
apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsxapps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.tsapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsxapps/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/enumsinstead of@/generated/prisma/clientto avoid Next.js bundling errors in client componentsImport Prisma using the project's centralized utility:
import prisma from '@/utils/prisma'
Files:
apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsxapps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.tsapps/web/app/api/user/stats/newsletters/route.tsapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsxapps/web/app/api/user/stats/email-actions/route.tsapps/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
Usenext/imagepackage for images
For API GET requests to server, use theswrpackage with hooks likeuseSWRto fetch data
For text inputs, use theInputcomponent withregisterPropsfor form integration and error handling
Files:
apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsxapps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.tsapps/web/app/api/user/stats/newsletters/route.tsapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsxapps/web/app/api/user/stats/email-actions/route.tsapps/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.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsxapps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.tsapps/web/app/api/user/stats/newsletters/route.tsapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsxapps/web/app/api/user/stats/email-actions/route.tsapps/web/prisma.config.ts
**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)
**/*.tsx: Use theLoadingContentcomponent to handle loading states instead of manual loading state management
For text areas, use theInputcomponent withtype='text',autosizeTextareaprop set to true, andregisterPropsfor form integration
Files:
apps/web/app/(app)/[emailAccountId]/stats/EmailActionsAnalytics.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsxapps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsxapps/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 useaccessKeyattribute on any HTML element
Don't setaria-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 thescopeprop 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 assigntabIndexto non-interactive HTML elements
Don't use positive integers fortabIndexproperty
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 atitleelement 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
AssigntabIndexto non-interactive HTML elements witharia-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 atypeattribute for button elements
Make elements with interactive roles and handlers focusable
Give heading elements content that's accessible to screen readers (not hidden witharia-hidden)
Always include alangattribute on the html element
Always include atitleattribute for iframe elements
AccompanyonClickwith at least one of:onKeyUp,onKeyDown, oronKeyPress
AccompanyonMouseOver/onMouseOutwithonFocus/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.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsxapps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.tsapps/web/app/api/user/stats/newsletters/route.tsapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsxapps/web/app/api/user/stats/email-actions/route.tsapps/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 bothchildrenanddangerouslySetInnerHTMLprops 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 usetarget="_blank"withoutrel="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.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsxapps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsxapps/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.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsxapps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsxapps/web/prisma/schema.prismaversion.txtapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.tsapps/web/app/api/user/stats/newsletters/route.tsapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsxapps/web/prisma/migrations/20251204222441_fromname_index/migration.sqlapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsxapps/web/app/api/user/stats/email-actions/route.tsapps/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.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/SearchBar.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/common.tsxapps/web/app/(app)/[emailAccountId]/stats/useExpanded.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/hooks.tsapps/web/app/api/user/stats/newsletters/route.tsapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsxapps/web/app/api/user/stats/email-actions/route.tsapps/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'sselectoption. 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. AllfindUnique/findFirstcalls 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
AllfindManyqueries 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.tsapps/web/app/api/user/stats/newsletters/route.tsapps/web/app/api/user/stats/email-actions/route.tsapps/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 withwithAuthorwithEmailAccountmiddleware for authentication
Export response types from GET API routes usingAwaited<ReturnType<>>pattern for type-safe client usage
Files:
apps/web/app/api/user/stats/newsletters/route.tsapps/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 usingwithAuthorwithEmailAccountmiddleware inapps/web/app/api/*/route.ts, export response types asGetExampleResponsetype alias for client-side type safety
Always export response types from GET routes asGet[Feature]Responseusing type inference from the data fetching function for type-safe client consumption
Do NOT use POST API routes for mutations - always use server actions withnext-safe-actioninstead
Files:
apps/web/app/api/user/stats/newsletters/route.tsapps/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 withwithAuthorwithEmailAccountmiddleware for consistent error handling and authentication in Next.js App Router
Infer and export response type for GET API routes usingAwaited<ReturnType<typeof functionName>>pattern in Next.js
Use Prisma for database queries in GET API routes
Return responses usingNextResponse.json()in GET API routes
Do not use try/catch blocks in GET API route handlers when usingwithAuthorwithEmailAccountmiddleware, as the middleware handles error handling
Files:
apps/web/app/api/user/stats/newsletters/route.tsapps/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: UsecreateScopedLoggerfrom "@/utils/logger" for logging in backend code
Add thecreateScopedLoggerinstantiation 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, usecreateScopedLogger().with()to attach context once and reuse the logger without passing variables repeatedly
Files:
apps/web/app/api/user/stats/newsletters/route.tsapps/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.tsapps/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 usewithAuth,withEmailAccount, orwithErrormiddleware for authentication
All database queries must include user scoping withemailAccountIdoruserIdfiltering 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; throwSafeErrorinstead of exposing user IDs, resource IDs, or system information
API routes should only return necessary fields usingselectin database queries to prevent unintended information disclosure
Cron endpoints must usehasCronSecretorhasPostCronSecretto 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.tsapps/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: usewithEmailAccountfor email-scoped operations, usewithAuthfor user-scoped operations, or usewithErrorwith proper validation for public/custom auth endpoints
UsewithEmailAccountmiddleware for operations scoped to a specific email account, including reading/writing emails, rules, schedules, or any operation usingemailAccountId
UsewithAuthmiddleware for user-level operations such as user settings, API keys, and referrals that use onlyuserId
UsewithErrormiddleware only for public endpoints, custom authentication logic, or cron endpoints. For cron endpoints, MUST usehasCronSecret()orhasPostCronSecret()validation
Cron endpoints without proper authentication can be triggered by anyone. CRITICAL: All cron endpoints MUST validate cron secret usinghasCronSecret(request)orhasPostCronSecret(request)and capture unauthorized attempts withcaptureException()
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.tsapps/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.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeSection.tsxapps/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.tsxapps/web/app/(app)/[emailAccountId]/bulk-unsubscribe/BulkUnsubscribeDesktop.tsxapps/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.tsxapps/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 goodImporting
isTinybirdEnabledand 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 useswithEmailAccountandNextResponse.json, and theEmailActionStatsResponsealias remains correctly inferred fromgetEmailActionStats, 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
preventDefaulthandler 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
sortDirectionprop enables bi-directional sorting with appropriate visual feedback. The icon logic correctly shows:
ChevronUpIconfor ascending sortChevronDownIconfor descending sort (or when sorted but direction is undefined)ChevronsUpDownIconwhen not sortedapps/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
sortDirectionis conditionally passed only to the active sort column.
51-82: Sort direction passed correctly per column.Each
HeaderButtonreceivessortDirectiononly when that column is currently sorted (sortColumn === "column"), and delegates sorting to theonSortcallback. 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
NewsletterFilterTypevalue is cleaner and reduces state complexity. ThefiltersArrayderivation 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
filterOptionsarray is well-structured with type safety viaNewsletterFilterType. TheseparatorAfterproperty for "Unhandled" creates a logical grouping in the dropdown UI.
150-167: LGTM on sort handling logic.The
handleSortfunction correctly implements bi-directional sorting:
- Toggles between
ascanddescwhen clicking the same column- Defaults to
descwhen switching to a new column
308-335: LGTM on filter dropdown implementation.The dropdown follows shadcn/ui patterns correctly. The
CheckIconprovides 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 theorderDirectionparameter—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 togetOrderByClause()(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
orderDirectionparameter is properly validated with a Zod enum constraint and marked as optional, following the same pattern as theorderByfield.
183-189: LGTM!The enhanced search filter correctly searches both
from(email address) andfromNamefields using case-insensitive matching. TheCOALESCEfunction properly handles nullfromNamevalues, and the search term is safely parameterized viaPrisma.sqlto prevent SQL injection.
198-200: LGTM!The
orderDirectionparameter is correctly passed through togetOrderByClause, maintaining type safety via the validated Zod schema.
246-264: LGTM!The
getOrderByClausefunction 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
orderDirectionparameter by convertingnulltoundefined, 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/configat the top is a best practice for Prisma configuration files, ensuring that environment variables (likeDATABASE_URLandDIRECT_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:
emailAccountIdfirst ensures user-scoped queries,fromNamesecond 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
fromNamefield (line 689)The index will optimize queries like
WHERE emailAccountId = ? AND fromName LIKE 'prefix%'andWHERE emailAccountId = ? ORDER BY fromName.
| // 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); |
There was a problem hiding this comment.
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.
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
orderDirectionwired through UI and API, replace multi-toggle filters with a single-select dropdown, and update the newsletters stats endpoint to accept and applyorderDirectionwhile matchingfromandfromName. 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
throttledSearchis created withuseCallback(..., [])but closes overonSearch. IfonSearchchanges between renders, the throttled function will continue calling the staleonSearch, leading to incorrect behavior. IncludeonSearchin the dependency array and ensure you cancel the previous throttle when it changes to avoid orphaned timers. [ Low confidence ]throttlemay 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 invokingonSearchafter unmount. Add a cleanup to cancel it (e.g., store the throttled function and callthrottled.cancel()in auseEffectcleanup). [ Out of scope ]watch((data) => { ... })is invoked directly during render and its subscription is never cleaned up. In React Hook Form v7, callingwatchwith 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 thewatchcall inside auseEffectand 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
EmailActionsAnalyticsrenders the chart whendatais truthy, but passesdata.resulttoBarChartwithout verifying it’s an array. If the fetch returns a non-OK response that still parses as JSON (the defaultuseOrgSWRfetcher returnsres.json()regardless of status),datamay be an error object withoutresult, makingdata.resultundefined. Passing undefined to Rechartsdatamay cause runtime errors or empty/misleading charts. Add a guard to ensureArray.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
getEmailActionsByDaydoes not return an object with an arraydataproperty. The code does(...).data.map(...)without checking existence/type. Ifdataisundefined,null, or not an array, this will throw at runtime, causing a 500 response. Add a guard likeconst res = await getEmailActionsByDay(...); const rows = Array.isArray(res?.data) ? res.data : [];before mapping. [ Out of scope ]Summary by CodeRabbit
New Features
Improvements
✏️ Tip: You can customize this high-level summary in your review settings.