Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Caution Review failedThe pull request is closed. Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. WalkthroughAdds two new stats controllers (by-period and response-time) with Zod validation, registers v1 OpenAPI routes, refactors user routes to delegate to controllers, updates helper to return email account IDs, and updates frontend types to use the new controller/validation exports. Changes
Sequence Diagram(s)sequenceDiagram
participant Client as API Client
participant Route as v1/response-time Route
participant Controller as Response-Time Controller
participant Provider as Email Provider
participant DB as Prisma/Database
participant Calc as Response Calculator
Client->>Route: GET /stats/response-time (fromDate,toDate,email,provider)
Route->>Route: Validate API key & query schema
Route->>Route: Resolve emailAccountId
Route->>Controller: getResponseTimeStats({fromDate,toDate,emailAccountId,provider,logger})
Controller->>Provider: Fetch recent sent message IDs (limit MAX_SENT_MESSAGES)
Provider-->>Controller: Sent message IDs
Controller->>DB: Load cached response-time entries for sent message IDs
DB-->>Controller: Cached entries
Controller->>Controller: Identify uncached message IDs
Controller->>Calc: calculateResponseTimes(uncached messages via Provider)
Calc-->>Controller: Calculated response-time entries
Controller->>DB: Persist new entries (skip duplicates)
DB-->>Controller: Stored entries
Controller->>Controller: Combine cached + new, filter by dates, compute summary/distribution/trend
Controller-->>Route: ResponseTimeResponse
Route-->>Client: 200 JSON
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
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: 3
♻️ Duplicate comments (1)
apps/web/app/api/user/stats/by-period/controller.ts (1)
23-30: Validate date values before constructing Date objects.The truthy check for
fromDate/toDatewill ignore epoch 0 (unlikely to matter in practice), but more importantly, invalid numeric values likeInfinityor out-of-range timestamps will produceInvalid Dateobjects passed to SQL.// Build date conditions without starting with AND const dateConditions: Prisma.Sql[] = []; - if (fromDate) { - dateConditions.push(Prisma.sql`date >= ${new Date(fromDate)}`); + if (fromDate != null) { + const date = new Date(fromDate); + if (!Number.isNaN(date.getTime())) { + dateConditions.push(Prisma.sql`date >= ${date}`); + } } - if (toDate) { - dateConditions.push(Prisma.sql`date <= ${new Date(toDate)}`); + if (toDate != null) { + const date = new Date(toDate); + if (!Number.isNaN(date.getTime())) { + dateConditions.push(Prisma.sql`date <= ${date}`); + } }
🧹 Nitpick comments (3)
apps/web/app/api/user/stats/by-period/route.ts (1)
5-7: Missing exported response type for client-side type safety.Per coding guidelines, GET routes should export response types using the
Get[Feature]Responsepattern. Consider adding:// Re-export types for backwards compatibility export type { StatsByPeriodQuery as StatsByWeekParams } from "./controller"; export type { StatsByPeriodResponse as StatsByWeekResponse } from "./controller"; + +// Export response type for client consumption +export type GetStatsByPeriodResponse = StatsByPeriodResponse;Based on learnings, API routes should export response types as
Get[Feature]Responsefor type-safe client consumption.apps/web/app/api/user/stats/by-period/controller.ts (1)
8-12: Consider using.optional()instead of.nullish()for consistency with v1 validation.The v1 validation schema at
apps/web/app/api/v1/stats/by-period/validation.tsuses.optional()while this controller uses.nullish(). This creates subtle behavioral differences -.nullish()accepts bothnullandundefined, while.optional()only acceptsundefined.export const statsByPeriodQuerySchema = z.object({ period: zodPeriod, - fromDate: z.coerce.number().nullish(), - toDate: z.coerce.number().nullish(), + fromDate: z.coerce.number().optional(), + toDate: z.coerce.number().optional(), });apps/web/app/api/v1/stats/response-time/route.ts (1)
9-9: Consider using.with()for request-scoped context.Per coding guidelines, use
.with()method to attach context variables within specific functions rather than using a global logger. For request-scoped logging with request identifiers, consider creating the logger inside the handler.-const logger = createScopedLogger("api/v1/stats/response-time"); +const baseLogger = createScopedLogger("api/v1/stats/response-time"); export const GET = withError(async (request) => { + const logger = baseLogger.with({ /* request context if needed */ });Based on learnings, using
.with()to attach context within functions is preferred over global loggers.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (9)
apps/web/app/api/user/stats/by-period/controller.ts(1 hunks)apps/web/app/api/user/stats/by-period/route.ts(1 hunks)apps/web/app/api/user/stats/response-time/controller.ts(1 hunks)apps/web/app/api/user/stats/response-time/route.ts(1 hunks)apps/web/app/api/v1/openapi/route.ts(2 hunks)apps/web/app/api/v1/stats/by-period/route.ts(1 hunks)apps/web/app/api/v1/stats/by-period/validation.ts(1 hunks)apps/web/app/api/v1/stats/response-time/route.ts(1 hunks)apps/web/app/api/v1/stats/response-time/validation.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (17)
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/api/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/route.tsapps/web/app/api/user/stats/response-time/controller.tsapps/web/app/api/user/stats/by-period/controller.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/api/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/route.tsapps/web/app/api/user/stats/response-time/controller.tsapps/web/app/api/user/stats/by-period/controller.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/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/route.tsapps/web/app/api/user/stats/response-time/controller.tsapps/web/app/api/user/stats/by-period/controller.ts
**/*.{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/api/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/route.tsapps/web/app/api/user/stats/response-time/controller.tsapps/web/app/api/user/stats/by-period/controller.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/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/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/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/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/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/route.tsapps/web/app/api/user/stats/response-time/controller.tsapps/web/app/api/user/stats/by-period/controller.ts
**/*.{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/api/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/route.tsapps/web/app/api/user/stats/response-time/controller.tsapps/web/app/api/user/stats/by-period/controller.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/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/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/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/route.tsapps/web/app/api/user/stats/response-time/controller.tsapps/web/app/api/user/stats/by-period/controller.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/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/route.tsapps/web/app/api/user/stats/response-time/controller.tsapps/web/app/api/user/stats/by-period/controller.ts
**/*.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/api/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/route.tsapps/web/app/api/user/stats/response-time/controller.tsapps/web/app/api/user/stats/by-period/controller.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/api/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/route.tsapps/web/app/api/user/stats/response-time/controller.tsapps/web/app/api/user/stats/by-period/controller.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/api/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/route.tsapps/web/app/api/user/stats/response-time/controller.tsapps/web/app/api/user/stats/by-period/controller.ts
**/*.{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/api/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/route.tsapps/web/app/api/user/stats/response-time/controller.tsapps/web/app/api/user/stats/by-period/controller.ts
!(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/api/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/route.tsapps/web/app/api/user/stats/response-time/controller.tsapps/web/app/api/user/stats/by-period/controller.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/api/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/route.tsapps/web/app/api/user/stats/response-time/controller.tsapps/web/app/api/user/stats/by-period/controller.ts
🧠 Learnings (36)
📚 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/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
Applied to files:
apps/web/app/api/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/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
Applied to files:
apps/web/app/api/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Infer and export the response type for GET API routes using `export type GetResponse = Awaited<ReturnType<typeof getData>>` pattern in Next.js
Applied to files:
apps/web/app/api/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.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/app/api/**/*.ts : Wrap GET API routes with `withAuth` or `withEmailAccount` middleware for authentication
Applied to files:
apps/web/app/api/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/response-time/route.ts
📚 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/app/api/**/route.ts : Always export response types from GET routes as `Get[Feature]Response` using type inference from the data fetching function for type-safe client consumption
Applied to files:
apps/web/app/api/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Use `withAuth` middleware to get the authenticated user or `withEmailAccount` middleware to get the currently active email account in GET API routes
Applied to files:
apps/web/app/api/v1/stats/by-period/route.ts
📚 Learning: 2025-11-25T14:37:22.822Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:22.822Z
Learning: Applies to **/app/**/route.ts : Infer and export response type for GET API routes using `Awaited<ReturnType<typeof functionName>>` pattern in Next.js
Applied to files:
apps/web/app/api/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.822Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:22.822Z
Learning: Applies to **/app/**/route.ts : Do not use try/catch blocks in GET API route handlers when using `withAuth` or `withEmailAccount` middleware, as the middleware handles error handling
Applied to files:
apps/web/app/api/v1/stats/by-period/route.ts
📚 Learning: 2025-11-25T14:37:22.822Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:22.822Z
Learning: Applies to **/app/**/route.ts : Use Prisma for database queries in GET API routes
Applied to files:
apps/web/app/api/v1/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.822Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:22.822Z
Learning: Applies to **/app/**/route.ts : Return responses using `NextResponse.json()` in GET API routes
Applied to files:
apps/web/app/api/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/response-time/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 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/v1/stats/by-period/route.tsapps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/by-period/controller.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Do not use try/catch blocks in GET API route handlers as `withAuth` and `withEmailAccount` middleware handle error handling
Applied to files:
apps/web/app/api/v1/stats/by-period/route.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/utils/actions/**/*.validation.ts : Use Zod schemas for validation and export both schema and inferred types in validation files
Applied to files:
apps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/openapi/route.ts
📚 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/utils/actions/*.validation.ts : Define Zod validation schemas in separate `*.validation.ts` files and export both the schema and inferred type (e.g., `CreateExampleBody`)
Applied to files:
apps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/openapi/route.ts
📚 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/*.validation.ts : Define input validation schemas using Zod in `.validation.ts` files and export both the schema and its inferred TypeScript type
Applied to files:
apps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/openapi/route.ts
📚 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/utils/actions/*.validation.ts : Export types from Zod schemas using `z.infer<>` to maintain type safety between validation and client usage
Applied to files:
apps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/openapi/route.ts
📚 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/*.validation.ts : Create separate validation files for server actions using the naming convention `apps/web/utils/actions/NAME.validation.ts` containing Zod schemas and inferred types
Applied to files:
apps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.ts
📚 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 **/*.validation.ts : Define validation schemas using Zod
Applied to files:
apps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/openapi/route.ts
📚 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 **/*.validation.{ts,tsx} : Define validation schemas using Zod
Applied to files:
apps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/openapi/route.ts
📚 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 `.schema()` method with Zod validation schemas from corresponding `.validation.ts` files in next-safe-action configuration
Applied to files:
apps/web/app/api/v1/stats/by-period/validation.ts
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : Always define a Zod schema for LLM response validation and make schemas as specific as possible to guide the LLM output
Applied to files:
apps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.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 : Always validate request bodies using Zod schemas to ensure type safety and prevent invalid data from reaching database operations
Applied to files:
apps/web/app/api/v1/stats/by-period/validation.tsapps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/openapi/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 app/api/**/*.ts : All input parameters must be validated - check for presence, type, and format before use; use Zod schemas to validate request bodies with type guards and constraints
Applied to files:
apps/web/app/api/v1/stats/response-time/validation.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} : Request bodies should use Zod schemas for validation to ensure type safety and prevent injection attacks
Applied to files:
apps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/v1/openapi/route.ts
📚 Learning: 2025-11-25T14:39:04.892Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-11-25T14:39:04.892Z
Learning: Applies to apps/web/app/api/**/route.ts : Use Zod schemas for request body validation in API routes
Applied to files:
apps/web/app/api/v1/stats/response-time/validation.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/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/app/**/[!.]*/route.{ts,tsx} : Use kebab-case for route directories in Next.js App Router (e.g., `api/hello-world/route`)
Applied to files:
apps/web/app/api/v1/stats/response-time/route.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/app/api/**/*.ts : Export response types from GET API routes using `Awaited<ReturnType<>>` pattern for type-safe client usage
Applied to files:
apps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:36:36.276Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/data-fetching.mdc:0-0
Timestamp: 2025-11-25T14:36:36.276Z
Learning: Applies to **/*.{ts,tsx} : For API GET requests to server, use the `swr` package
Applied to files:
apps/web/app/api/v1/stats/response-time/route.tsapps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:39:04.892Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-11-25T14:39:04.892Z
Learning: Applies to apps/web/app/api/**/route.ts : API responses should use `select` to return only necessary fields and avoid exposing sensitive data
Applied to files:
apps/web/app/api/user/stats/response-time/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 : Maintain consistent error response format across all API routes to avoid information disclosure while providing meaningful error feedback
Applied to files:
apps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/v1/openapi/route.ts
📚 Learning: 2025-11-25T14:39:04.892Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-11-25T14:39:04.892Z
Learning: Applies to apps/web/app/api/**/route.ts : API responses should use a consistent error response format across all endpoints
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 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/api/user/stats/response-time/route.ts
📚 Learning: 2025-08-10T22:03:30.507Z
Learnt from: elie222
Repo: elie222/inbox-zero PR: 667
File: apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx:18-25
Timestamp: 2025-08-10T22:03:30.507Z
Learning: In Next.js 15, both `params` and `searchParams` passed to page components in the App Router are Promises that need to be awaited. They should be typed as `Promise<{...}>` and accessed using `await` in server components or React's `use()` hook in client components. This is different from Next.js 14 where they were plain objects.
Applied to files:
apps/web/app/api/user/stats/response-time/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/response-time/route.ts
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : LLM feature functions must import from `zod` for schema validation, use `createScopedLogger` from `@/utils/logger`, `chatCompletionObject` and `createGenerateObject` from `@/utils/llms`, and import `EmailAccountWithAI` type from `@/utils/llms/types`
Applied to files:
apps/web/app/api/v1/openapi/route.tsapps/web/app/api/user/stats/by-period/controller.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/by-period/controller.ts
🧬 Code graph analysis (6)
apps/web/app/api/v1/stats/by-period/validation.ts (2)
apps/web/app/api/user/stats/by-period/controller.ts (1)
statsByPeriodQuerySchema(8-12)packages/tinybird/src/query.ts (1)
zodPeriod(4-4)
apps/web/app/api/v1/stats/response-time/route.ts (4)
apps/web/app/api/user/stats/response-time/route.ts (1)
GET(9-24)apps/web/utils/api-auth.ts (1)
validateApiKeyAndGetEmailProvider(66-87)apps/web/app/api/user/stats/response-time/controller.ts (2)
responseTimeQuerySchema(17-20)getResponseTimeStats(40-147)apps/web/app/api/v1/stats/response-time/validation.ts (1)
responseTimeQuerySchema(3-7)
apps/web/app/api/user/stats/by-period/route.ts (1)
apps/web/app/api/user/stats/by-period/controller.ts (1)
statsByPeriodQuerySchema(8-12)
apps/web/app/api/user/stats/response-time/route.ts (3)
apps/web/app/api/v1/stats/response-time/route.ts (1)
GET(11-51)apps/web/app/api/user/stats/response-time/controller.ts (1)
responseTimeQuerySchema(17-20)apps/web/app/api/v1/stats/response-time/validation.ts (1)
responseTimeQuerySchema(3-7)
apps/web/app/api/v1/openapi/route.ts (2)
apps/web/app/api/v1/stats/by-period/validation.ts (2)
statsByPeriodQuerySchema(4-9)statsByPeriodResponseSchema(11-27)apps/web/app/api/v1/stats/response-time/validation.ts (2)
responseTimeQuerySchema(3-7)responseTimeResponseSchema(9-39)
apps/web/app/api/user/stats/by-period/controller.ts (3)
apps/web/app/api/v1/stats/by-period/validation.ts (1)
statsByPeriodQuerySchema(4-9)packages/tinybird/src/query.ts (1)
zodPeriod(4-4)apps/web/app/api/user/stats/by-period/route.ts (2)
StatsByPeriodQuery(6-6)StatsByPeriodResponse(7-7)
⏰ 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: test
- GitHub Check: Review for correctness
🔇 Additional comments (12)
apps/web/app/api/user/stats/by-period/route.ts (1)
9-27: LGTM!The route handler correctly uses
withEmailAccountmiddleware, validates query parameters with the Zod schema, and delegates to the controller. TheallowOrgAdminsoption is appropriately configured.apps/web/app/api/user/stats/by-period/controller.ts (2)
50-64: Raw SQL usage is safe due to Zod enum validation.The
periodvalue is interpolated usingPrisma.raw(), but this is safe becausezodPeriodconstrains it to the enum["day", "week", "month", "year"]. TheemailAccountIdis properly parameterized. The query structure is sound.
67-103: LGTM!The
getStatsByPeriodfunction correctly transforms raw SQL results to the expected format, handles bigint-to-number conversion for JSON compatibility, and uses lodash's specific import pattern as per coding guidelines.apps/web/app/api/v1/stats/by-period/route.ts (1)
8-47: LGTM!The v1 route correctly implements API key authentication via
validateApiKeyAndGetEmailProvider, validates query parameters withsafeParse, handles errors gracefully, and delegates to the shared controller. The use ofwithErrormiddleware is appropriate for API-key authenticated endpoints.apps/web/app/api/v1/stats/response-time/route.ts (1)
11-50: LGTM!The route handler correctly validates API key authentication, parses query parameters, resolves the email account, and delegates to the controller with all required parameters including
emailProviderandlogger.apps/web/app/api/v1/stats/by-period/validation.ts (1)
1-29: LGTM!The validation schemas are well-structured with proper Zod definitions. The response schema correctly captures the expected output shape, and the inferred type export follows project conventions.
apps/web/app/api/v1/openapi/route.ts (1)
59-99: LGTM!The new OpenAPI path registrations are well-structured with appropriate descriptions, security schemes, query schemas, and response schemas. This provides good API documentation for consumers.
apps/web/app/api/v1/stats/response-time/validation.ts (1)
1-41: LGTM!The validation schemas comprehensively define the request query parameters and the full response structure including summary statistics, distribution buckets, and trend data. The type export follows project conventions.
apps/web/app/api/user/stats/response-time/route.ts (2)
5-7: Missing exported response type for client-side type safety.Similar to the by-period route, consider adding a
GetResponseTimeResponseexport alias for client consumption:// Re-export types for backwards compatibility export type { ResponseTimeQuery as ResponseTimeParams } from "./controller"; export type { ResponseTimeResponse as GetResponseTimeResponse } from "./controller";The current re-export as
GetResponseTimeResponsealready follows the naming convention, which is good. This comment is just confirmation that the pattern is correct.
9-24: LGTM!The route correctly uses
withEmailProvidermiddleware which provides the email provider, authentication context, and scoped logger. Query parameters are validated and the controller is invoked with all required dependencies.apps/web/app/api/user/stats/response-time/controller.ts (2)
64-114: Excellent caching strategy!The implementation efficiently caches response-time calculations and only computes uncached messages. Database queries are properly scoped with
emailAccountId, andskipDuplicates: trueprevents race conditions.
149-196: Helper functions look good!
calculateTrendproperly groups response times by week, calculates medians, and sorts chronologically.getEmptyStatsprovides a consistent empty response structure. Both implementations are correct.
| export const responseTimeQuerySchema = z.object({ | ||
| fromDate: z.coerce.number().nullish(), | ||
| toDate: z.coerce.number().nullish(), | ||
| }); | ||
| export type ResponseTimeQuery = z.infer<typeof responseTimeQuerySchema>; |
There was a problem hiding this comment.
Validate that coerced date values produce valid Date objects.
The schema coerces values to numbers but doesn't validate that they're finite or within valid timestamp ranges. Values like Infinity, NaN, or extremely large numbers will pass validation but produce Invalid Date objects when passed to new Date() at lines 54-55.
Apply this diff to add validation:
export const responseTimeQuerySchema = z.object({
- fromDate: z.coerce.number().nullish(),
- toDate: z.coerce.number().nullish(),
+ fromDate: z.coerce
+ .number()
+ .finite()
+ .refine((val) => val === null || val === undefined || !isNaN(new Date(val).getTime()), {
+ message: "Invalid date timestamp",
+ })
+ .nullish(),
+ toDate: z.coerce
+ .number()
+ .finite()
+ .refine((val) => val === null || val === undefined || !isNaN(new Date(val).getTime()), {
+ message: "Invalid date timestamp",
+ })
+ .nullish(),
});Committable suggestion skipped: line range outside the PR's diff.
| // 1. Fetch sent message IDs (lightweight - just id and threadId) | ||
| const sentMessages = await emailProvider.getSentMessageIds({ | ||
| maxResults: MAX_SENT_MESSAGES, | ||
| ...(fromDate ? { after: new Date(fromDate) } : {}), | ||
| ...(toDate ? { before: new Date(toDate) } : {}), | ||
| }); |
There was a problem hiding this comment.
Fix truthy checks and validate Date construction to prevent dropping valid timestamps and Invalid Date errors.
Two critical issues:
-
Truthy checks drop valid epoch timestamp: Using
fromDate ?at lines 54-55 treats0(Unix epoch, Jan 1 1970) as falsy and skips it, even though it's a valid timestamp. -
No validation of Date construction: Directly calling
new Date(fromDate)without checking if the result is valid can passInvalid Dateobjects toemailProvider.getSentMessageIds, potentially causing downstream errors.
Based on learnings, use explicit null/undefined checks instead of truthy checks, and validate Date objects before use.
Apply this diff:
// 1. Fetch sent message IDs (lightweight - just id and threadId)
+ const afterDate = fromDate !== null && fromDate !== undefined ? new Date(fromDate) : undefined;
+ const beforeDate = toDate !== null && toDate !== undefined ? new Date(toDate) : undefined;
+
+ if (afterDate && isNaN(afterDate.getTime())) {
+ throw new Error("Invalid fromDate timestamp");
+ }
+ if (beforeDate && isNaN(beforeDate.getTime())) {
+ throw new Error("Invalid toDate timestamp");
+ }
+
const sentMessages = await emailProvider.getSentMessageIds({
maxResults: MAX_SENT_MESSAGES,
- ...(fromDate ? { after: new Date(fromDate) } : {}),
- ...(toDate ? { before: new Date(toDate) } : {}),
+ ...(afterDate ? { after: afterDate } : {}),
+ ...(beforeDate ? { before: beforeDate } : {}),
});🤖 Prompt for AI Agents
In apps/web/app/api/user/stats/response-time/controller.ts around lines 51 to
56, the current truthy checks (e.g. fromDate ? ...) drop valid epoch 0 values
and unconditionally call new Date(...) which can produce Invalid Date; change
the conditions to explicit null/undefined checks (e.g. fromDate !== null &&
fromDate !== undefined) and construct Date objects into local variables,
validate each Date with Number.isNaN(date.getTime()) (or similar) before
including them in the getSentMessageIds options; if a Date is invalid, reject
the request or omit the parameter with a clear error/log so you never pass
Invalid Date to emailProvider.getSentMessageIds.
| const allEntries = combinedEntries.filter((entry) => { | ||
| const sentTime = entry.sentAt.getTime(); | ||
| if (fromDate && sentTime < fromDate) return false; | ||
| if (toDate && sentTime > toDate) return false; | ||
| return true; | ||
| }); |
There was a problem hiding this comment.
Fix truthy checks in date range filtering to prevent dropping valid epoch timestamp.
Lines 125-126 use truthy checks (fromDate &&, toDate &&) that will skip timestamp 0 (Unix epoch, Jan 1 1970), even though it's a valid filter boundary. This is inconsistent with the intended date range filtering.
Apply this diff:
// Filter to only include response times within the requested date range
const allEntries = combinedEntries.filter((entry) => {
const sentTime = entry.sentAt.getTime();
- if (fromDate && sentTime < fromDate) return false;
- if (toDate && sentTime > toDate) return false;
+ if (fromDate !== null && fromDate !== undefined && sentTime < fromDate) return false;
+ if (toDate !== null && toDate !== undefined && sentTime > toDate) return false;
return true;
});🤖 Prompt for AI Agents
In apps/web/app/api/user/stats/response-time/controller.ts around lines 123 to
128, the filter uses truthy checks (fromDate &&, toDate &&) which incorrectly
treat 0 as "no filter"; change those checks to explicit null/undefined checks
(e.g., fromDate !== undefined && fromDate !== null or fromDate != null) so epoch
timestamp 0 is treated as a valid boundary and sentTime comparisons work
correctly; update both fromDate and toDate checks accordingly.
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
apps/web/app/api/user/stats/response-time/route.ts (1)
1-21: Export response type for client-side type safety.Coding guidelines require GET API routes to export their response type using the
Get[Feature]Responsepattern for type-safe client consumption.Add this export after the route handler:
import type { ResponseTimeStats } from "@/app/api/user/stats/response-time/controller"; // ... existing code ... export type GetResponseTimeResponse = ResponseTimeStats;As per coding guidelines: Always export response types from GET routes using type inference for type-safe client consumption.
apps/web/app/api/user/stats/by-period/route.ts (1)
1-25: Export response type for client-side type safety.Coding guidelines require GET API routes to export their response type for type-safe client consumption.
Add this export:
import type { StatsByPeriodResponse } from "@/app/api/user/stats/by-period/controller"; // ... existing code ... export type GetStatsByPeriodResponse = StatsByPeriodResponse;As per coding guidelines: Always export response types from GET routes as
Get[Feature]Responseusing type inference.
♻️ Duplicate comments (1)
apps/web/app/api/user/stats/by-period/controller.ts (1)
18-23: Use explicit null/undefined checks to handle epoch 0.The truthy checks
if (fromDate)andif (toDate)will reject valid timestamp0(Unix epoch). This matches the concern from previous reviews and PR objectives.Apply this diff:
const dateConditions: Prisma.Sql[] = []; - if (fromDate) { + if (fromDate != null) { dateConditions.push(Prisma.sql`date >= ${new Date(fromDate)}`); } - if (toDate) { + if (toDate != null) { dateConditions.push(Prisma.sql`date <= ${new Date(toDate)}`); }This ensures that
0(epoch) is treated as a valid timestamp while still filtering outnullandundefined.
🧹 Nitpick comments (4)
apps/web/app/api/user/stats/response-time/route.ts (1)
3-4: Use consistent import style.Line 3 uses a relative import (
"./controller") while Line 4 uses an absolute path alias. For consistency with coding guidelines, prefer the@/path alias for all imports.Apply this diff:
-import { getResponseTimeStats } from "./controller"; +import { getResponseTimeStats } from "@/app/api/user/stats/response-time/controller";apps/web/app/api/user/stats/by-period/route.ts (1)
3-4: Use consistent import style.Line 3 uses a relative import while Line 4 uses an absolute path alias. For consistency, prefer the
@/path alias for all imports.Apply this diff:
-import { getStatsByPeriod } from "./controller"; +import { getStatsByPeriod } from "@/app/api/user/stats/by-period/controller";apps/web/app/api/user/stats/by-period/controller.ts (2)
44-57: Add defensive validation for period parameter.Line 46 uses
Prisma.raw(\'${period}'`)with string interpolation. Whileperiod` is constrained by the Zod enum at the route level, the controller should not rely solely on upstream validation. Add a defensive check to explicitly verify the value.Add validation at the start of the function:
async function getEmailStatsByPeriod( options: StatsByPeriodQuery & { emailAccountId: string }, ) { const { period, fromDate, toDate, emailAccountId } = options; // Defensive validation const validPeriods = ["day", "week", "month", "year"] as const; if (!validPeriods.includes(period)) { throw new Error(`Invalid period: ${period}`); } // ... rest of functionThis provides defense-in-depth and makes the code more maintainable if validation logic changes upstream.
69-87: Document assumption about email count limits.Lines 74-79 and 84-87 convert
bigintaggregation results toNumber. JavaScript numbers have 53-bit precision (safe up to ~9 quadrillion). While email counts are unlikely to exceed this, consider documenting this assumption or adding a runtime check for very large values.If you want to be defensive, add a helper:
function safeNumberConversion(value: bigint, fieldName: string): number { const num = Number(value); if (num > Number.MAX_SAFE_INTEGER) { throw new Error(`${fieldName} exceeds safe integer range: ${value}`); } return num; }Alternatively, document the assumption that email counts will remain within safe integer bounds.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
apps/web/app/api/user/stats/by-period/controller.ts(1 hunks)apps/web/app/api/user/stats/by-period/route.ts(1 hunks)apps/web/app/api/user/stats/by-period/validation.ts(1 hunks)apps/web/app/api/user/stats/response-time/controller.ts(1 hunks)apps/web/app/api/user/stats/response-time/route.ts(1 hunks)apps/web/app/api/user/stats/response-time/validation.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/web/app/api/user/stats/response-time/controller.ts
🧰 Additional context used
📓 Path-based instructions (17)
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/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/controller.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/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/controller.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/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/controller.ts
**/*.{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/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/controller.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/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/controller.ts
**/*.{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/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/controller.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/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/controller.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/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/controller.ts
**/*.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/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/controller.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/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/controller.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/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/controller.ts
**/*.{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/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/controller.ts
!(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/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/controller.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/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.tsapps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.tsapps/web/app/api/user/stats/by-period/controller.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/by-period/route.tsapps/web/app/api/user/stats/response-time/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/by-period/route.tsapps/web/app/api/user/stats/response-time/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/by-period/route.tsapps/web/app/api/user/stats/response-time/route.ts
🧠 Learnings (31)
📚 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/utils/actions/**/*.validation.ts : Use Zod schemas for validation and export both schema and inferred types in validation files
Applied to files:
apps/web/app/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.ts
📚 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/*.validation.ts : Define input validation schemas using Zod in `.validation.ts` files and export both the schema and its inferred TypeScript type
Applied to files:
apps/web/app/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.ts
📚 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/utils/actions/*.validation.ts : Export types from Zod schemas using `z.infer<>` to maintain type safety between validation and client usage
Applied to files:
apps/web/app/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.ts
📚 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/utils/actions/*.validation.ts : Define Zod validation schemas in separate `*.validation.ts` files and export both the schema and inferred type (e.g., `CreateExampleBody`)
Applied to files:
apps/web/app/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.ts
📚 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 **/*.validation.ts : Define validation schemas using Zod
Applied to files:
apps/web/app/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.ts
📚 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/*.validation.ts : Create separate validation files for server actions using the naming convention `apps/web/utils/actions/NAME.validation.ts` containing Zod schemas and inferred types
Applied to files:
apps/web/app/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.ts
📚 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 **/*.validation.{ts,tsx} : Define validation schemas using Zod
Applied to files:
apps/web/app/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.ts
📚 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 `.schema()` method with Zod validation schemas from corresponding `.validation.ts` files in next-safe-action configuration
Applied to files:
apps/web/app/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.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 app/api/**/*.ts : All input parameters must be validated - check for presence, type, and format before use; use Zod schemas to validate request bodies with type guards and constraints
Applied to files:
apps/web/app/api/user/stats/by-period/validation.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 : Always validate request bodies using Zod schemas to ensure type safety and prevent invalid data from reaching database operations
Applied to files:
apps/web/app/api/user/stats/by-period/validation.tsapps/web/app/api/user/stats/response-time/validation.ts
📚 Learning: 2025-11-25T14:38:07.606Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-11-25T14:38:07.606Z
Learning: Applies to apps/web/utils/ai/**/*.ts : Always define a Zod schema for LLM response validation and make schemas as specific as possible to guide the LLM output
Applied to files:
apps/web/app/api/user/stats/response-time/validation.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} : Request bodies should use Zod schemas for validation to ensure type safety and prevent injection attacks
Applied to files:
apps/web/app/api/user/stats/response-time/validation.ts
📚 Learning: 2025-11-25T14:39:04.892Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-11-25T14:39:04.892Z
Learning: Applies to apps/web/app/api/**/route.ts : Use Zod schemas for request body validation in API routes
Applied to files:
apps/web/app/api/user/stats/response-time/validation.ts
📚 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/app/api/**/route.ts : Always export response types from GET routes as `Get[Feature]Response` using type inference from the data fetching function for type-safe client consumption
Applied to files:
apps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.822Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:22.822Z
Learning: Applies to **/app/**/route.ts : Use Prisma for database queries in GET API routes
Applied to files:
apps/web/app/api/user/stats/by-period/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/app/**/[!.]*/route.{ts,tsx} : Use kebab-case for route directories in Next.js App Router (e.g., `api/hello-world/route`)
Applied to files:
apps/web/app/api/user/stats/by-period/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Use Prisma for all database queries in GET API routes
Applied to files:
apps/web/app/api/user/stats/by-period/route.ts
📚 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/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
Applied to files:
apps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Infer and export the response type for GET API routes using `export type GetResponse = Awaited<ReturnType<typeof getData>>` pattern in Next.js
Applied to files:
apps/web/app/api/user/stats/by-period/route.tsapps/web/app/api/user/stats/response-time/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 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/by-period/route.tsapps/web/app/api/user/stats/by-period/controller.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/by-period/route.tsapps/web/app/api/user/stats/by-period/controller.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/app/api/**/*.ts : Export response types from GET API routes using `Awaited<ReturnType<>>` pattern for type-safe client usage
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:22.822Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:22.822Z
Learning: Applies to **/app/**/route.ts : Infer and export response type for GET API routes using `Awaited<ReturnType<typeof functionName>>` pattern in Next.js
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:39:04.892Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-11-25T14:39:04.892Z
Learning: Applies to apps/web/app/api/**/route.ts : API responses should use `select` to return only necessary fields and avoid exposing sensitive data
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/app/**/route.ts : Return responses using `NextResponse.json()` in GET API routes
Applied to files:
apps/web/app/api/user/stats/response-time/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 : Maintain consistent error response format across all API routes to avoid information disclosure while providing meaningful error feedback
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:39:04.892Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-11-25T14:39:04.892Z
Learning: Applies to apps/web/app/api/**/route.ts : Request parameters must be validated before use; direct parameter usage without validation is prohibited
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:36:36.276Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/data-fetching.mdc:0-0
Timestamp: 2025-11-25T14:36:36.276Z
Learning: Applies to **/*.{ts,tsx} : For API GET requests to server, use the `swr` package
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-08-10T22:03:30.507Z
Learnt from: elie222
Repo: elie222/inbox-zero PR: 667
File: apps/web/app/(app)/[emailAccountId]/onboarding/page.tsx:18-25
Timestamp: 2025-08-10T22:03:30.507Z
Learning: In Next.js 15, both `params` and `searchParams` passed to page components in the App Router are Promises that need to be awaited. They should be typed as `Promise<{...}>` and accessed using `await` in server components or React's `use()` hook in client components. This is different from Next.js 14 where they were plain objects.
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 Learning: 2025-11-25T14:37:11.434Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/get-api-route.mdc:0-0
Timestamp: 2025-11-25T14:37:11.434Z
Learning: Applies to **/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
Applied to files:
apps/web/app/api/user/stats/response-time/route.ts
📚 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/api/user/stats/response-time/route.ts
🧬 Code graph analysis (4)
apps/web/app/api/user/stats/by-period/validation.ts (1)
packages/tinybird/src/query.ts (1)
zodPeriod(4-4)
apps/web/app/api/user/stats/by-period/route.ts (3)
apps/web/app/api/v1/stats/by-period/route.ts (1)
GET(8-47)apps/web/utils/middleware.ts (1)
withEmailAccount(398-416)apps/web/app/api/user/stats/by-period/validation.ts (1)
statsByPeriodQuerySchema(4-8)
apps/web/app/api/user/stats/response-time/route.ts (3)
apps/web/app/api/v1/stats/response-time/route.ts (1)
GET(11-51)apps/web/utils/middleware.ts (1)
withEmailProvider(426-439)apps/web/app/api/user/stats/response-time/validation.ts (1)
responseTimeQuerySchema(3-6)
apps/web/app/api/user/stats/by-period/controller.ts (1)
apps/web/app/api/user/stats/by-period/validation.ts (1)
StatsByPeriodQuery(9-9)
⏰ 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: test
- GitHub Check: Review for correctness
🔇 Additional comments (4)
apps/web/app/api/user/stats/response-time/route.ts (1)
6-21: LGTM!The route handler correctly uses
withEmailProvidermiddleware, validates query parameters with the schema, delegates to the controller, and returns the result. Error handling is properly managed by the middleware.apps/web/app/api/user/stats/by-period/route.ts (1)
6-25: LGTM!The route handler correctly uses
withEmailAccountmiddleware with appropriate options, validates query parameters with defaults, and delegates to the controller.apps/web/app/api/user/stats/by-period/controller.ts (2)
1-5: LGTM!Imports follow best practices: specific lodash function import, centralized Prisma utility, and proper type imports.
7-9: LGTM!Response type correctly exported using
Awaited<ReturnType<>>pattern for type-safe client consumption.
| export const statsByPeriodQuerySchema = z.object({ | ||
| period: zodPeriod, | ||
| fromDate: z.coerce.number().nullish(), | ||
| toDate: z.coerce.number().nullish(), | ||
| }); |
There was a problem hiding this comment.
Add validation to reject NaN and ensure valid timestamps.
z.coerce.number() can produce NaN from invalid input (e.g., "abc"), which passes validation but creates Invalid Date downstream in the controller.
Apply this diff:
export const statsByPeriodQuerySchema = z.object({
period: zodPeriod,
- fromDate: z.coerce.number().nullish(),
- toDate: z.coerce.number().nullish(),
+ fromDate: z.coerce.number().finite().nullish(),
+ toDate: z.coerce.number().finite().nullish(),
});📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export const statsByPeriodQuerySchema = z.object({ | |
| period: zodPeriod, | |
| fromDate: z.coerce.number().nullish(), | |
| toDate: z.coerce.number().nullish(), | |
| }); | |
| export const statsByPeriodQuerySchema = z.object({ | |
| period: zodPeriod, | |
| fromDate: z.coerce.number().finite().nullish(), | |
| toDate: z.coerce.number().finite().nullish(), | |
| }); |
🤖 Prompt for AI Agents
In apps/web/app/api/user/stats/by-period/validation.ts around lines 4 to 8, the
z.coerce.number() fields can produce NaN from invalid input which then becomes
Invalid Date downstream; update fromDate and toDate to reject NaN and ensure
they are valid timestamps by adding a refinement (after coercion) that checks
Number.isFinite(value) and that the value is an integer and within a sensible
timestamp range (e.g., > 0, optionally <= Date.now()), returning a clear error
message on failure so malformed inputs are rejected at validation time.
| export const responseTimeQuerySchema = z.object({ | ||
| fromDate: z.coerce.number().nullish(), | ||
| toDate: z.coerce.number().nullish(), | ||
| }); |
There was a problem hiding this comment.
Add validation to reject NaN and ensure valid timestamps.
z.coerce.number() accepts any input and can produce NaN (e.g., from "abc"), which will pass validation but create Invalid Date in downstream code. Additionally, the schema doesn't validate that timestamps are finite or reasonable.
Apply this diff to add proper numeric validation:
export const responseTimeQuerySchema = z.object({
- fromDate: z.coerce.number().nullish(),
- toDate: z.coerce.number().nullish(),
+ fromDate: z.coerce.number().finite().nullish(),
+ toDate: z.coerce.number().finite().nullish(),
});This ensures that only finite numbers (excluding NaN, Infinity, -Infinity) are accepted, preventing invalid dates from reaching the controller.
| @@ -0,0 +1,7 @@ | |||
| import { z } from "zod"; | |||
|
|
|||
| export const responseTimeQuerySchema = z.object({ | |||
There was a problem hiding this comment.
email is used after safeParse but isn’t in responseTimeQuerySchema, and Zod drops unknown keys. This makes email always undefined. Consider adding an email field (e.g., optional string) to the schema, or document that email is intentionally ignored.
+ email: z.string().optional(),🚀 Reply to ask Macroscope to explain or update this suggestion.
👍 Helpful? React to give us feedback.
|
Review the following changes in direct dependencies. Learn more about Socket for GitHub.
|
Add stats API by introducing v1 GET
/api/v1/stats/by-periodand/api/v1/stats/response-timeendpoints and wiring controllers, validation, and OpenAPI registrationAdd v1 stats endpoints with controllers that compute period-based email counts and response-time metrics, move query validation to dedicated zod modules, and update UI components to consume new response/query types.
📍Where to Start
Start with the v1 route handlers:
GET /api/v1/stats/by-periodin apps/web/app/api/v1/stats/by-period/route.ts andGET /api/v1/stats/response-timein apps/web/app/api/v1/stats/response-time/route.ts; then review their controllers in apps/web/app/api/user/stats/by-period/controller.ts and apps/web/app/api/user/stats/response-time/controller.ts.📊 Macroscope summarized cff16b4. 15 files reviewed, 11 issues evaluated, 11 issues filtered, 0 comments posted
🗂️ Filtered Issues
apps/web/app/(app)/[emailAccountId]/stats/MainStatChart.tsx — 0 comments posted, 1 evaluated, 1 filtered
MainStatChartparsesstartOfPeriodusingparse(item.startOfPeriod, "MMM dd, yyyy", new Date())(line 37), butgetStatsByPeriodformatsstartOfPeriodasformat(stat.startOfPeriod, "LLL dd, y"). The tokensLLLvsMMMandyvsyyyyare not guaranteed to be interchangeable across locales in date-fns. This mismatch can causeparseto return an invalid date, and the subsequentformat(date, "yyyy-MM-dd")on line 38 will throw at runtime. Ensure the parse format exactly matches the format used to produce the string (or pass a machine-parseable value like ISO date). [ Low confidence ]apps/web/app/api/user/stats/by-period/validation.ts — 0 comments posted, 3 evaluated, 3 filtered
fromDateis defined asz.coerce.number().nullish()which acceptsInfinityand-Infinityby default in Zod. These values will pass validation and reachnew Date(fromDate)in the controller, producing anInvalid Datethat is then sent to Prisma, likely causing a runtime error during SQL parameter serialization. Add.finite()to reject non-finite numbers. [ Already posted ]fromDatepermits any finite number, including values outside the valid JS Date range (approximately ±8.64e15 ms). Extremely large/small finite values will pass validation, butnew Date(fromDate)yields anInvalid Date, leading to runtime errors when used as a SQL parameter. Add range constraints (e.g.,.min(-8640000000000000).max(8640000000000000)) or validate resultingDatevalidity. [ Already posted ]toDatehas the same issues asfromDate: it allowsInfinity/-Infinity(no.finite()) and any out-of-range finite number, both of which lead tonew Date(toDate)producingInvalid Dateand runtime failures during SQL parameterization. Mirror the same.finite()and range constraints ontoDate. [ Already posted ]apps/web/app/api/user/stats/response-time/validation.ts — 0 comments posted, 3 evaluated, 3 filtered
z.coerce.number()will accept the string values'Infinity'/'-Infinity'(and numericInfinity/-Infinity) as valid numbers. Because.finite()is not applied,fromDateandtoDatecan beInfinity/-Infinity, which are nonsensical for dates/timestamps and likely to break downstream logic that expects real numeric timestamps. [ Already posted ]z.coerce.number()will coerce many non-numeric query values into numbers without error: e.g., an empty string""or" "becomes0, andtrue/falsebecome1/0. This means inputs like?fromDate=or?fromDate=trueare silently accepted as0/1, which is likely unintended for date/timestamp filters and can cause incorrect range queries. [ Already posted ]fromDatealso apply totoDatebecause it uses the samez.coerce.number().nullish()pipeline, sotoDatecan also beInfinity/-Infinityor silently accept empty/boolean values as0/1. [ Already posted ]apps/web/app/api/v1/stats/by-period/route.ts — 0 comments posted, 2 evaluated, 2 filtered
validateApiKeyAndGetEmailProvider(request)creates an email provider and enforces presence/refresh of access tokens, but the endpoint only needs the user/account identity to compute DB stats. This introduces unnecessary side effects and failure modes (e.g., missing/expired tokens) causing 401/other errors even though the stats query doesn’t require provider access. UsevalidateApiKeyto authenticate without creating the provider, or defer provider creation until needed. [ Low confidence ]accountIdobtained fromvalidateApiKeyAndGetEmailProvider(which returns the user OAuth account'sid) is passed intogetEmailAccountId({ accountId })which looks upprisma.emailAccount.findUnique({ where: { accountId, userId } }). Unless the OAuth Accountidis guaranteed to equalEmailAccount.accountId(an external provider ID) this lookup will fail and returnundefined, causing a 400 "Email account not found" even for valid API keys. Fix by passing the correct external account identifier thatemailAccount.accountIdexpects (or changegetEmailAccountIdto accept the current value), or passemailexplicitly. [ Already posted ]apps/web/app/api/v1/stats/response-time/route.ts — 0 comments posted, 2 evaluated, 2 filtered
getEmailAccountId: theaccountIdprovided byvalidateApiKeyAndGetEmailProvideris the internal account recordid, butgetEmailAccountIdexpects an external provideraccountId(and queriesprisma.emailAccount.findUnique({ where: { accountId, userId } })). This will typically fail to find the account, returning 400 "Email account not found" even for valid API keys. Either change the helper to support internalidin a separate parameter/path or pass the correct externalaccountId(or omit the param when not needed) and, for the selected account, recreate the provider as needed. [ Already posted ]emailquery param targets a different account than the one used to createemailProvider, the handler passes a provider tied to the first account (validateApiKeyAndGetEmailProvider) together with a differentemailAccountIdtogetResponseTimeStats. This can compute stats from one mailbox while attributing them to another, causing incorrect results or data contamination. Fix by deriving the provider from the resolvedemailAccountId(and its provider type) after line 33, or by ensuring the API key selection aligns with the requested account and recreating the provider accordingly before callinggetResponseTimeStats. [ Low confidence ]Summary by CodeRabbit
New Features
Refactor
Chores
✏️ Tip: You can customize this high-level summary in your review settings.