Skip to content

Comments

Centralize date filtering with useDateFilters hook#87

Merged
izadoesdev merged 1 commit intodatabuddy-analytics:stagingfrom
sbansal1999:create-date-filters-hook
Aug 15, 2025
Merged

Centralize date filtering with useDateFilters hook#87
izadoesdev merged 1 commit intodatabuddy-analytics:stagingfrom
sbansal1999:create-date-filters-hook

Conversation

@sbansal1999
Copy link
Contributor

@sbansal1999 sbansal1999 commented Aug 15, 2025

Summary by CodeRabbit

  • Refactor
    • Consolidated date and time range filtering across analytics, errors, funnels, goals, map, profiles, revenue, and sessions pages for a more consistent experience.
    • Streamlined how date ranges and granularity are applied to data queries without altering page layouts or controls.
    • Maintains existing toolbar and filter behavior; selections continue to drive all related analytics and lists uniformly.

@vercel
Copy link

vercel bot commented Aug 15, 2025

@sbansal1999 is attempting to deploy a commit to the Databuddy Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 15, 2025

Walkthrough

Replaces scattered Jotai-based date/granularity handling with a centralized useDateFilters hook. Multiple dashboard pages/components now consume dateRange and granularity from this hook. Some analytics hook invocations were updated to accept the unified dateRange. No public component signatures changed; the new hook is added.

Changes

Cohort / File(s) Summary of changes
New date filter hook
apps/dashboard/hooks/use-date-filters.ts
Added useDateFilters hook that reads/writes Jotai atoms, memoizes a dateRange (start_date, end_date, granularity, timezone), and exposes setters/actions.
Toolbar refactor to hook
apps/dashboard/app/(main)/websites/[id]/_components/analytics-toolbar.tsx
Replaced direct atom usage with useDateFilters; derives selected range and updates via setDateRangeAction; toggles granularity via hook setter.
Pages/components switched to hook
apps/dashboard/app/(main)/websites/[id]/errors/_components/errors-page-content.tsx, .../(main)/websites/[id]/funnels/page.tsx, .../(main)/websites/[id]/goals/page.tsx, .../(main)/websites/[id]/map/page.tsx, .../(main)/websites/[id]/page.tsx, .../(main)/websites/[id]/profiles/_components/profiles-list.tsx, .../(main)/websites/[id]/revenue/page.tsx, .../(main)/websites/[id]/sessions/_components/sessions-list.tsx
Removed formattedDateRangeAtom/timeGranularityAtom construction and useMemo; now destructure dateRange (and where needed formattedDateRangeState/granularity) from useDateFilters and pass to data hooks/components. Minor import and className adjustments. Funnels/goals update analytics hook calls to accept dateRange.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant Toolbar as AnalyticsToolbar
  participant Hook as useDateFilters
  participant Atoms as Jotai atoms
  participant Consumers as Pages/Components

  User->>Toolbar: Select quick range / custom dates / toggle granularity
  Toolbar->>Hook: setDateRangeAction / setCurrentGranularityAtomState
  Hook->>Atoms: Update dateRange/granularity atoms
  Atoms-->>Hook: Current dateRange/granularity/timezone
  Hook-->>Toolbar: currentDateRange/currentGranularity
  Atoms-->>Consumers: Trigger re-render with new dateRange
  Consumers->>Data Hooks: Call with dateRange
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Status, Documentation and Community

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

@graphite-app
Copy link
Contributor

graphite-app bot commented Aug 15, 2025

How to use the Graphite Merge Queue

Add the label Main to this PR to add it to the merge queue.

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

@sbansal1999 sbansal1999 changed the base branch from main to staging August 15, 2025 13:49
@izadoesdev
Copy link
Member

perfect refactor, well done

@izadoesdev izadoesdev merged commit 5016750 into databuddy-analytics:staging Aug 15, 2025
5 of 9 checks passed
@sbansal1999 sbansal1999 deleted the create-date-filters-hook branch August 15, 2025 13:58
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🔭 Outside diff range comments (3)
apps/dashboard/app/(main)/websites/[id]/profiles/_components/profiles-list.tsx (1)

82-88: Pass undefined when no filters to minimize payload and match other call sites

Align with other data hooks by avoiding empty arrays for filters.

Apply this diff:

-  const { profiles, pagination, isLoading, isError, error } = useProfilesData(
-    websiteId,
-    dateRange,
-    25,
-    page,
-    filters
-  );
+  const { profiles, pagination, isLoading, isError, error } = useProfilesData(
+    websiteId,
+    dateRange,
+    25,
+    page,
+    filters.length > 0 ? filters : undefined
+  );
apps/dashboard/app/(main)/websites/[id]/revenue/page.tsx (1)

116-127: Action: include timezone in the revenue query or confirm intentional omission

DateRange (packages/shared/src/types/analytics.ts) includes timezone, but useWebsiteRevenue currently ignores it — neither buildParams nor the queryKey include timezone. This can lead to caching/staleness or incorrect server timezone handling.

Files to update / inspect:

  • packages/shared/src/types/analytics.ts — DateRange has timezone?: string
  • apps/dashboard/app/(main)/websites/[id]/revenue/hooks/use-website-revenue.ts
    • buildParams: appends start_date, end_date, granularity but not timezone
    • queryKey: uses start_date, end_date, granularity (omits timezone)
    • fetchWebsiteRevenue: passes DateRange to the fetcher but the built URL lacks timezone param

Suggested minimal fixes:

  • Add timezone to request params:
// in buildParams(...)
if (dateRange?.timezone) {
  params.append('timezone', dateRange.timezone);
}
  • Add timezone to the cache key so changes trigger refetch:
queryKey: [
  'website-revenue',
  websiteId,
  dateRange.start_date,
  dateRange.end_date,
  dateRange.granularity,
  dateRange.timezone,
],

If omission was intentional, document the reason and ensure the server derives/receives timezone via headers or user preferences. Otherwise, apply the changes above.

apps/dashboard/app/(main)/websites/[id]/funnels/page.tsx (1)

321-328: Optional: Standardize referrer analytics to the same dateRange object

You’re still constructing { start_date, end_date } from formattedDateRangeState for FunnelAnalyticsByReferrer. Consider updating that consumer to accept the unified dateRange for consistency (it can ignore extra fields), reducing duplication and potential drift.

Apply locally in this block:

-<FunnelAnalyticsByReferrer
-  data={referrerAnalyticsData}
-  dateRange={{
-    start_date: formattedDateRangeState.startDate,
-    end_date: formattedDateRangeState.endDate,
-  }}
+<FunnelAnalyticsByReferrer
+  data={referrerAnalyticsData}
+  dateRange={dateRange}
📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between b74bed9 and 9e110d9.

📒 Files selected for processing (10)
  • apps/dashboard/app/(main)/websites/[id]/_components/analytics-toolbar.tsx (2 hunks)
  • apps/dashboard/app/(main)/websites/[id]/errors/_components/errors-page-content.tsx (3 hunks)
  • apps/dashboard/app/(main)/websites/[id]/funnels/page.tsx (5 hunks)
  • apps/dashboard/app/(main)/websites/[id]/goals/page.tsx (4 hunks)
  • apps/dashboard/app/(main)/websites/[id]/map/page.tsx (3 hunks)
  • apps/dashboard/app/(main)/websites/[id]/page.tsx (4 hunks)
  • apps/dashboard/app/(main)/websites/[id]/profiles/_components/profiles-list.tsx (4 hunks)
  • apps/dashboard/app/(main)/websites/[id]/revenue/page.tsx (2 hunks)
  • apps/dashboard/app/(main)/websites/[id]/sessions/_components/sessions-list.tsx (2 hunks)
  • apps/dashboard/hooks/use-date-filters.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{jsx,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)

**/*.{jsx,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't pass children as props.
Don't use the return value of React.render.
Make sure all dependencies are correctly specified in React hooks.
Make sure all React hooks are called from the top level of component functions.
Don't forget key props in iterators and collection literals.
Don't destructure props inside JSX components in Solid projects.
Don't define React components inside other components.
Don't use event handlers on non-interactive elements.
Don't assign to React component props.
Don't use both children and dangerouslySetInnerHTML props on the same element.
Don't use dangerous JSX props.
Don't use Array index in keys.
Don't insert comments as text nodes.
Don't assign JSX properties multiple times.
Don't add extra closing tags for components without children.
Use <>...</> instead of ....
Watch out for possible "wrong" semicolons inside JSX elements.
Don't use accessKey attribute on any HTML element.
Don't set aria-hidden="true" on focusable elements.
Don't add ARIA roles, states, and properties to elements that don't support them.
Don't use distracting elements like or .
Only use the scope prop on elements.
Don't assign non-interactive ARIA roles to interactive HTML elements.
Make sure label elements have text content and are associated with an input.
Don't assign interactive ARIA roles to non-interactive HTML elements.
Don't assign tabIndex to non-interactive HTML elements.
Don't use positive integers for tabIndex property.
Don't include "image", "picture", or "photo" in img alt prop.
Don't use explicit role property that's the same as the implicit/default role.
Make static elements with click handlers use a valid role attribute.
Always include a title element for SVG elements.
Give all elements requiring alt text meaningful information for screen readers.
Make sure anchors have content that's accessible ...

Files:

  • apps/dashboard/app/(main)/websites/[id]/revenue/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/map/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/sessions/_components/sessions-list.tsx
  • apps/dashboard/app/(main)/websites/[id]/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/_components/analytics-toolbar.tsx
  • apps/dashboard/app/(main)/websites/[id]/errors/_components/errors-page-content.tsx
  • apps/dashboard/app/(main)/websites/[id]/profiles/_components/profiles-list.tsx
  • apps/dashboard/app/(main)/websites/[id]/goals/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/funnels/page.tsx
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)

**/*.{js,ts,jsx,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't use global eval().
Don't use var.
Don't use console.
Don't use debugger.
Don't assign directly to document.cookie.
Don't use duplicate case labels.
Don't use duplicate class members.
Don't use duplicate function parameter names.
Don't use empty block statements and static blocks.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Use for...of statements instead of Array.forEach.
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names that aren't base 10 or use underscore separators.
Remove redundant terms from logical expressions.
Use while loops instead of for loops when you don't need initializer and update expressions.
Don't reassign const variables.
Don't use constant expressions in conditions.
Don't use Math.min and Math.max to clamp values when the result is constant.
Don't return a value from a constructor.
Don't use empty character classes in regular expression literals.
Don't use empty destructuring patterns.
Don't call global object properties as functions.
Don't declare functions and vars that are accessible outside their block.
Don't use variables and function parameters before they're declared.
Don't use 8 and 9 escape sequences in string literals.
Don't use literal numbers that lose precision.
Don't use duplicate conditions in if-else-if chains.
Don't use two keys with the same name inside objects...

Files:

  • apps/dashboard/app/(main)/websites/[id]/revenue/page.tsx
  • apps/dashboard/hooks/use-date-filters.ts
  • apps/dashboard/app/(main)/websites/[id]/map/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/sessions/_components/sessions-list.tsx
  • apps/dashboard/app/(main)/websites/[id]/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/_components/analytics-toolbar.tsx
  • apps/dashboard/app/(main)/websites/[id]/errors/_components/errors-page-content.tsx
  • apps/dashboard/app/(main)/websites/[id]/profiles/_components/profiles-list.tsx
  • apps/dashboard/app/(main)/websites/[id]/goals/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/funnels/page.tsx
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use TypeScript namespaces.
Don't use the TypeScript directive @ts-ignore.
Don't use any type.
Don't use implicit any type on variable declarations.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't declare empty interfaces.
Use export type for types.
Use import type for types.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.

**/*.{ts,tsx}: Ensure TypeScript type-safety; avoid any unless absolutely necessary
Create proper interfaces/types for APIs, responses, and components; place them in shared types folders rather than in the same file

Files:

  • apps/dashboard/app/(main)/websites/[id]/revenue/page.tsx
  • apps/dashboard/hooks/use-date-filters.ts
  • apps/dashboard/app/(main)/websites/[id]/map/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/sessions/_components/sessions-list.tsx
  • apps/dashboard/app/(main)/websites/[id]/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/_components/analytics-toolbar.tsx
  • apps/dashboard/app/(main)/websites/[id]/errors/_components/errors-page-content.tsx
  • apps/dashboard/app/(main)/websites/[id]/profiles/_components/profiles-list.tsx
  • apps/dashboard/app/(main)/websites/[id]/goals/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/funnels/page.tsx
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc)

**/*.{js,jsx,ts,tsx}: Use bun <file> instead of node <file> or ts-node <file>
Do not use dotenv; Bun automatically loads .env files
Do not use express; use Bun.serve() for HTTP servers
Do not use better-sqlite3; use bun:sqlite for SQLite
Do not use ioredis; use Bun.redis for Redis
Do not use pg or postgres.js; use Bun.sql for Postgres
Do not use ws; use built-in WebSocket
Prefer Bun.file over node:fs's readFile/writeFile
Use Bun.$ instead of execa for running shell commands

Files:

  • apps/dashboard/app/(main)/websites/[id]/revenue/page.tsx
  • apps/dashboard/hooks/use-date-filters.ts
  • apps/dashboard/app/(main)/websites/[id]/map/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/sessions/_components/sessions-list.tsx
  • apps/dashboard/app/(main)/websites/[id]/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/_components/analytics-toolbar.tsx
  • apps/dashboard/app/(main)/websites/[id]/errors/_components/errors-page-content.tsx
  • apps/dashboard/app/(main)/websites/[id]/profiles/_components/profiles-list.tsx
  • apps/dashboard/app/(main)/websites/[id]/goals/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/funnels/page.tsx
**/*.{tsx,jsx}

📄 CodeRabbit Inference Engine (.cursor/rules/01-MUST-DO.mdc)

**/*.{tsx,jsx}: In Tailwind CSS usage, use rounded only; do not use rounded-md or rounded-xl
Use Phosphor icons, not Lucide; default to weight="duotone", use fill for arrows, and for plus icons do not set weight
In view components, decouple state management, data transformations, and API interactions from the React lifecycle
Simplify data flow in components to avoid prop drilling and callback chains
Prioritize modularity and testability in all React components
Use React Error Boundaries appropriately
Avoid useEffect in React unless it is truly critical

Files:

  • apps/dashboard/app/(main)/websites/[id]/revenue/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/map/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/sessions/_components/sessions-list.tsx
  • apps/dashboard/app/(main)/websites/[id]/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/_components/analytics-toolbar.tsx
  • apps/dashboard/app/(main)/websites/[id]/errors/_components/errors-page-content.tsx
  • apps/dashboard/app/(main)/websites/[id]/profiles/_components/profiles-list.tsx
  • apps/dashboard/app/(main)/websites/[id]/goals/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/funnels/page.tsx
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit Inference Engine (.cursor/rules/01-MUST-DO.mdc)

**/*.{ts,tsx,js,jsx}: Use console methods appropriately (e.g., console.error, console.time, console.table, console.json)
Use Dayjs instead of date-fns
Use TanStack Query for hooks; do not use SWR
When adding debugging, use JSON.stringify() for structured output

Files:

  • apps/dashboard/app/(main)/websites/[id]/revenue/page.tsx
  • apps/dashboard/hooks/use-date-filters.ts
  • apps/dashboard/app/(main)/websites/[id]/map/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/sessions/_components/sessions-list.tsx
  • apps/dashboard/app/(main)/websites/[id]/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/_components/analytics-toolbar.tsx
  • apps/dashboard/app/(main)/websites/[id]/errors/_components/errors-page-content.tsx
  • apps/dashboard/app/(main)/websites/[id]/profiles/_components/profiles-list.tsx
  • apps/dashboard/app/(main)/websites/[id]/goals/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/funnels/page.tsx
**/*.{tsx,jsx,ts,js}

📄 CodeRabbit Inference Engine (.cursor/rules/01-MUST-DO.mdc)

When using Phosphor React icons, append 'Icon' to component names (e.g., CaretIcon, not Caret)

Files:

  • apps/dashboard/app/(main)/websites/[id]/revenue/page.tsx
  • apps/dashboard/hooks/use-date-filters.ts
  • apps/dashboard/app/(main)/websites/[id]/map/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/sessions/_components/sessions-list.tsx
  • apps/dashboard/app/(main)/websites/[id]/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/_components/analytics-toolbar.tsx
  • apps/dashboard/app/(main)/websites/[id]/errors/_components/errors-page-content.tsx
  • apps/dashboard/app/(main)/websites/[id]/profiles/_components/profiles-list.tsx
  • apps/dashboard/app/(main)/websites/[id]/goals/page.tsx
  • apps/dashboard/app/(main)/websites/[id]/funnels/page.tsx
**/*.{js,ts}

📄 CodeRabbit Inference Engine (.cursor/rules/ultracite.mdc)

**/*.{js,ts}: Make sure to use the "use strict" directive in script files.
Don't have redundant "use strict".
Make sure to use the "use strict" directive in script files.

Files:

  • apps/dashboard/hooks/use-date-filters.ts
**/*.{html,ts,css}

📄 CodeRabbit Inference Engine (.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc)

Use bun build <file.html|file.ts|file.css> instead of webpack or esbuild

Files:

  • apps/dashboard/hooks/use-date-filters.ts
🧬 Code Graph Analysis (10)
apps/dashboard/app/(main)/websites/[id]/revenue/page.tsx (1)
apps/dashboard/hooks/use-date-filters.ts (1)
  • useDateFilters (11-38)
apps/dashboard/hooks/use-date-filters.ts (1)
apps/dashboard/stores/jotai/filterAtoms.ts (4)
  • timezoneAtom (64-66)
  • formattedDateRangeAtom (25-35)
  • timeGranularityAtom (40-40)
  • setDateRangeAndAdjustGranularityAtom (46-61)
apps/dashboard/app/(main)/websites/[id]/map/page.tsx (2)
apps/dashboard/hooks/use-date-filters.ts (1)
  • useDateFilters (11-38)
apps/dashboard/hooks/use-dynamic-query.ts (1)
  • useMapLocationData (499-521)
apps/dashboard/app/(main)/websites/[id]/sessions/_components/sessions-list.tsx (1)
apps/dashboard/hooks/use-date-filters.ts (1)
  • useDateFilters (11-38)
apps/dashboard/app/(main)/websites/[id]/page.tsx (1)
apps/dashboard/hooks/use-date-filters.ts (1)
  • useDateFilters (11-38)
apps/dashboard/app/(main)/websites/[id]/_components/analytics-toolbar.tsx (1)
apps/dashboard/hooks/use-date-filters.ts (1)
  • useDateFilters (11-38)
apps/dashboard/app/(main)/websites/[id]/errors/_components/errors-page-content.tsx (1)
apps/dashboard/hooks/use-date-filters.ts (1)
  • useDateFilters (11-38)
apps/dashboard/app/(main)/websites/[id]/profiles/_components/profiles-list.tsx (1)
apps/dashboard/hooks/use-date-filters.ts (1)
  • useDateFilters (11-38)
apps/dashboard/app/(main)/websites/[id]/goals/page.tsx (2)
apps/dashboard/hooks/use-date-filters.ts (1)
  • useDateFilters (11-38)
apps/dashboard/hooks/use-goals.ts (1)
  • useBulkGoalAnalytics (117-132)
apps/dashboard/app/(main)/websites/[id]/funnels/page.tsx (2)
apps/dashboard/hooks/use-date-filters.ts (1)
  • useDateFilters (11-38)
apps/dashboard/hooks/use-funnels.ts (1)
  • useFunnelAnalytics (171-186)
⏰ 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). (1)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (26)
apps/dashboard/app/(main)/websites/[id]/map/page.tsx (2)

14-14: Good switch to centralized date filters

Importing and consuming useDateFilters here aligns with the PR objective and removes local atom coupling.


48-48: Top-level hook usage is correct

Destructuring dateRange from useDateFilters() at the component top level is correct and ensures consistent date inputs across data hooks.

apps/dashboard/app/(main)/websites/[id]/sessions/_components/sessions-list.tsx (2)

7-7: Import of useDateFilters is appropriate

Centralizing date-range sourcing via the new hook is the right direction.


70-84: No change needed — sessions-list already avoids sending empty filters

Verified: apps/dashboard/app/(main)/websites/[id]/sessions/_components/sessions-list.tsx already uses
filters: filters.length > 0 ? filters : undefined (around lines ~70–79), so no change is required.

Files located:

  • apps/dashboard/app/(main)/websites/[id]/sessions/_components/sessions-list.tsx — conditional filters usage (~line 78)

If you want cross-repo consistency, I can update other places that default to [] (examples: apps/docs/app/(home)/api/query-builder.ts, apps/api/src/routes/query.ts, apps/dashboard/hooks/use-goals.ts). Would you like me to standardize those?

apps/dashboard/app/(main)/websites/[id]/page.tsx (5)

3-3: Type import location looks good

Moving DynamicQueryFilter type import to the top keeps import ordering clean.


14-14: Adoption of useDateFilters

Using useDateFilters() here removes local atom plumbing and unifies date handling across tabs.


86-86: dateRange sourcing is correct

Destructuring dateRange and threading it through tab props achieves the centralization goal.


160-160: Correct dependency tracking

Including dateRange in renderTabContent's dependency list ensures updates propagate when date filters change.


121-124: WebsiteDataTabProps already includes dateRange — no change needed

Verified: WebsiteDataTabProps extends BaseTabProps, and BaseTabProps declares dateRange: DateRange.

Files to note:

  • apps/dashboard/app/(main)/websites/[id]/_components/utils/types.ts — BaseTabProps { dateRange: DateRange } (≈ lines 13–16) and WebsiteDataTabProps extends BaseTabProps (≈ lines 25–28).
  • apps/dashboard/app/(main)/websites/[id]/page.tsx — passing dateRange in settingsProps: WebsiteDataTabProps (≈ lines 119–124).
apps/dashboard/hooks/use-date-filters.ts (1)

11-38: Apply shared DateRange type; rename setter but update call sites

Shared DateRange (packages/shared/src/types/analytics.ts) includes timezone?: string — safe to import and use. Renaming the setter is fine but will break call sites; update them as shown.

Files to change

  • apps/dashboard/hooks/use-date-filters.ts — import type, annotate dateRange, rename setter in destructure and return.
  • Update all call sites that destructure the old name from useDateFilters(), e.g.:
    • apps/dashboard/app/(main)/websites/[id]/_components/analytics-toolbar.tsx (replace setCurrentGranularityAtomState usages).

Proposed diffs:

apps/dashboard/hooks/use-date-filters.ts

+import type { DateRange } from '@databuddy/shared';
@@
-	const [currentGranularity, setCurrentGranularityAtomState] =
+	const [currentGranularity, setCurrentGranularity] =
 		useAtom(timeGranularityAtom);
@@
-const dateRange = useMemo(
+const dateRange: DateRange = useMemo(
   () => ({
     start_date: formattedDateRangeState.startDate,
     end_date: formattedDateRangeState.endDate,
     granularity: currentGranularity,
     timezone,
   }),
   [formattedDateRangeState, currentGranularity, timezone]
 );
@@
   return {
     currentDateRange,
     setCurrentDateRange,
     formattedDateRangeState,
     currentGranularity,
-    setCurrentGranularityAtomState,
+    setCurrentGranularity,
     dateRange,
     setDateRangeAction,
   };

apps/dashboard/app/(main)/websites/[id]/_components/analytics-toolbar.tsx

-	const {
-		...,
-		setCurrentGranularityAtomState,
-		setDateRangeAction,
-	} = useDateFilters();
+	const {
+		...,
+		setCurrentGranularity,
+		setDateRangeAction,
+	} = useDateFilters();
@@
-	onClick={() => setCurrentGranularityAtomState('daily')}
+	onClick={() => setCurrentGranularity('daily')}
@@
-	onClick={() => setCurrentGranularityAtomState('hourly')}
+	onClick={() => setCurrentGranularity('hourly')}

[tag: fix_required]

apps/dashboard/app/(main)/websites/[id]/profiles/_components/profiles-list.tsx (2)

70-71: Centralized date range usage is correct

Switching to useDateFilters() and passing dateRange into useProfilesData aligns this component with the new pattern.


95-100: Good: dependency array keys on primitive date fields

Watching dateRange.start_date, end_date, and granularity avoids unnecessary resets due to object identity changes. Nicely done.

apps/dashboard/app/(main)/websites/[id]/revenue/page.tsx (2)

11-11: Imports streamlined; lazy/Suspense/useCallback/useState only — LGTM

Removing unused useMemo and keeping only what’s needed is correct.


15-17: Adoption of useDateFilters while retaining isAnalyticsRefreshingAtom — LGTM

This aligns with the PR goal to centralize date filters.

apps/dashboard/app/(main)/websites/[id]/_components/analytics-toolbar.tsx (2)

10-10: Switch to useDateFilters — LGTM

Import and usage are consistent with the centralization approach.


32-37: Date/granularity state centralized — LGTM

Using currentDateRange, currentGranularity, and setDateRangeAction from the hook keeps this toolbar in sync with the rest of the app.

apps/dashboard/app/(main)/websites/[id]/goals/page.tsx (3)

15-15: Introduce useDateFilters — LGTM

The import is correct and local atom usage is removed.


94-94: Use centralized dateRange — LGTM

Consuming dateRange from the hook will keep analytics consistent with other pages.


116-117: useBulkGoalAnalytics(dateRange) — verified OK

useBulkGoalAnalytics expects { start_date: string; end_date: string } and only reads dateRange?.start_date and dateRange?.end_date. useDateFilters returns dateRange with extra fields (granularity, timezone). Structural typing allows extra properties and the hook contains no runtime validation or exact-type enforcement — passing dateRange is safe.

  • apps/dashboard/hooks/use-goals.ts
    • Signature: export function useBulkGoalAnalytics(..., dateRange: { start_date: string; end_date: string }, ...)
    • Mapping: startDate: dateRange?.start_date, endDate: dateRange?.end_date
  • apps/dashboard/hooks/use-date-filters.ts
    • Returned dateRange: { start_date, end_date, granularity, timezone }
  • Call site: apps/dashboard/app/(main)/websites/[id]/goals/page.tsx — useBulkGoalAnalytics(websiteId, goalIds, dateRange)
apps/dashboard/app/(main)/websites/[id]/funnels/page.tsx (3)

8-8: Adopt useDateFilters for funnels — LGTM

The import matches the refactor pattern across pages.


97-97: Derive formattedDateRangeState and dateRange from the hook — LGTM

This preserves access to raw start/end for components that need it while passing the unified dateRange elsewhere.


116-118: useFunnelAnalytics now consumes centralized dateRange — LGTM

Options with enabled: !!expandedFunnelId are preserved; query will re-run as expected when dateRange changes.

apps/dashboard/app/(main)/websites/[id]/errors/_components/errors-page-content.tsx (4)

3-3: Trim DateRange import — LGTM

Importing only DynamicQueryFilter avoids unused types after the change.


11-11: Introduce useDateFilters — LGTM

Hook import aligns this component with the centralized date handling.


306-306: Minor container spacing change — LGTM

Visual tweak; no behavioral impact.


34-35: useEnhancedErrorData expects DateRange — passing dateRange is correct

Verified: the hook signature is export function useEnhancedErrorData(websiteId: string, dateRange: DateRange, ...) so passing the centralized dateRange from useDateFilters() is correct; no changes required.

Files/locations:

  • apps/dashboard/hooks/use-dynamic-query.ts — export function useEnhancedErrorData(... dateRange: DateRange ...) (around lines 523–526)
  • apps/dashboard/app/(main)/websites/[id]/errors/_components/errors-page-content.tsx — call: useEnhancedErrorData(websiteId, dateRange, { ... }) (line 75)

Likely an incorrect or invalid review comment.

Comment on lines +60 to +64
const { isLoading, getDataForQuery } = useMapLocationData(
id,
dateRange,
filters
);
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Avoid sending empty filter arrays; pass undefined when no filters

useMapLocationData forwards filters into each query. Passing an empty array adds unnecessary payload and may complicate server-side handling. Pass undefined when no filters are applied for consistency with other call sites.

Apply this diff:

- const { isLoading, getDataForQuery } = useMapLocationData(
-   id,
-   dateRange,
-   filters
- );
+ const { isLoading, getDataForQuery } = useMapLocationData(
+   id,
+   dateRange,
+   filters.length > 0 ? filters : undefined
+ );
📝 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.

Suggested change
const { isLoading, getDataForQuery } = useMapLocationData(
id,
dateRange,
filters
);
const { isLoading, getDataForQuery } = useMapLocationData(
id,
dateRange,
filters.length > 0 ? filters : undefined
);
🤖 Prompt for AI Agents
In apps/dashboard/app/(main)/websites/[id]/map/page.tsx around lines 60 to 64,
the call to useMapLocationData currently forwards an empty filters array which
should instead be undefined when no filters are applied; update the argument so
you pass filters if it has items otherwise undefined (e.g. compute a filtersArg
= filters && filters.length ? filters : undefined and pass filtersArg into
useMapLocationData) to avoid sending empty arrays to downstream queries.

export function SessionsList({ websiteId }: SessionsListProps) {
const [formattedDateRange] = useAtom(formattedDateRangeAtom);
const [granularity] = useAtom(timeGranularityAtom);
const { dateRange } = useDateFilters();
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Reset pagination and accumulated data when date range or filters change

Now that dateRange is centralized, the list should reset paging and accumulated sessions when dateRange or filters change to avoid mixing different ranges in one list.

Add this effect (outside the shown range) to reset state:

// Reset on date range or filters change
useEffect(() => {
  setPage(1);
  setAllSessions([]);
  setExpandedSessionId(null);
}, [
  dateRange.start_date,
  dateRange.end_date,
  dateRange.granularity,
  JSON.stringify(filters),
]);
🤖 Prompt for AI Agents
In
apps/dashboard/app/(main)/websites/[id]/sessions/_components/sessions-list.tsx
around line 61, add an effect to reset pagination and accumulated session state
when the centralized dateRange or filters change: call setPage(1),
setAllSessions([]) and setExpandedSessionId(null) inside a useEffect tied to
dependencies dateRange.start_date, dateRange.end_date, dateRange.granularity and
JSON.stringify(filters) so the list does not mix sessions from different ranges
or filter sets.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants