Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feat]: Implement report activity filters and loading state #3536

Merged
merged 1 commit into from
Jan 22, 2025

Conversation

Innocent-Akim
Copy link
Contributor

@Innocent-Akim Innocent-Akim commented Jan 22, 2025

Description

Please include a summary of the changes and the related issues.

Type of Change

  • Bug fix
  • New feature
  • Breaking change
  • Documentation update

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my code
  • I have commented on my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings

Previous screenshots

Please add here videos or images of the previous status

Current screenshots

Please add here videos or images of the current (new) status

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced dashboard with interactive date range and filter selection
    • Added dynamic team stats chart with toggleable activity lines
  • Improvements

    • Implemented more flexible activity reporting mechanism
    • Improved data visualization and user interaction in team dashboard
  • Performance

    • Optimized data fetching and state management for activity reports

Copy link
Contributor

coderabbitai bot commented Jan 22, 2025

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/dashboard-header.tsx

Oops! Something went wrong! :(

ESLint: 8.46.0

ESLint couldn't find the config "next/core-web-vitals" to extend from. Please check that the name of the config is correct.

The config "next/core-web-vitals" was referenced from the config file in "/apps/web/.eslintrc.json".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.

Walkthrough

This pull request introduces significant enhancements to the team dashboard functionality, focusing on improving date range and filter interactions. The changes span multiple files, including the dashboard header, team stats chart, page component, and a new report activity hook. The modifications enable more dynamic and interactive data visualization, allowing users to customize their view of team activities through flexible date range selection and filter options.

Changes

File Change Summary
apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/dashboard-header.tsx Added DashboardHeaderProps interface, updated component to accept onUpdateDateRange and onUpdateFilters props, introduced handler functions for date range and filter changes
apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/team-stats-chart.tsx Added TeamStatsChartProps interface, updated component to accept rapportChartActivity and isLoading props, implemented dynamic line visibility for chart
apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/page.tsx Integrated useReportActivity hook, updated DashboardHeader and TeamStatsChart with new props, adjusted layout and component interactions
apps/web/app/hooks/features/useReportActivity.ts Refactored hook to manage internal state, added updateDateRange and updateFilters functions, modified report activity fetching logic

Sequence Diagram

sequenceDiagram
    participant User
    participant DashboardHeader
    participant TeamDashboard
    participant UseReportActivity
    participant TeamStatsChart

    User->>DashboardHeader: Select Date Range/Filter
    DashboardHeader->>TeamDashboard: onUpdateDateRange/onUpdateFilters
    TeamDashboard->>UseReportActivity: Update Date/Filters
    UseReportActivity-->>UseReportActivity: Fetch Report Activity
    UseReportActivity->>TeamStatsChart: Update Chart Data
    TeamStatsChart->>User: Render Updated Chart
Loading

Possibly related PRs

Suggested Labels

feature, WEB, Ever Teams, Improvement

Suggested Reviewers

  • evereq
  • Cedric921

Poem

🐰 In the dashboard's digital dance,
Lines of data take their stance,
Filters twirl, dates pirouette,
A rabbit's code, a perfect set!
Metrics leap with joyful glee,
Tracking time so gracefully! 🕰️

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

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: 0

🔭 Outside diff range comments (1)
apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/dashboard-header.tsx (1)

Export functionality is incomplete and needs to be implemented

The export Select component is currently non-functional:

  • No onValueChange handler is implemented for the export options
  • Export options (CSV, PDF, Excel) are defined but have no associated actions
  • The UI elements should either be connected to export functionality or removed to avoid confusion
🔗 Analysis chain

Line range hint 68-79: Implement export functionality or remove if not needed.

The export functionality appears to be incomplete as it doesn't handle the export actions.

Let's check if there are any existing export implementations:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for export-related functionality
rg -g '!*.{json,lock}' -i "export.*\.(csv|pdf|excel)" -A 5

Length of output: 60


Script:

#!/bin/bash
# Search for export-related functions and handlers
rg -g '!*.{json,lock}' -i "function.*export|export.*function|onExport|handleExport" -A 5

# Search for Select onChange handlers in the dashboard-header file
rg -g "dashboard-header.tsx" "onChange" -A 5

# Search for any export-related utilities
rg -g '!*.{json,lock,md}' -i "export.*util|export.*helper|export.*service" -A 5

Length of output: 121816


Script:

#!/bin/bash
# Search for Select component implementation in dashboard-header
ast-grep --pattern 'Select $$$' apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/dashboard-header.tsx

# Search for export-related functions
rg -g '!*.{json,lock}' -i "function.*export|handleExport|downloadExport" -A 5

Length of output: 2165


Script:

#!/bin/bash
# Get the full implementation of dashboard-header.tsx
cat apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/dashboard-header.tsx

Length of output: 2398

🧹 Nitpick comments (6)
apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/dashboard-header.tsx (2)

26-46: Consider extracting filter logic and improving date calculations.

The date calculations in handleFilterChange could be improved to ensure consistent behavior across timezones.

Consider this implementation:

 const handleFilterChange = (value: string) => {
-    const today = new Date();
-    let startDate = new Date();
-    const endDate = today;
+    const endDate = new Date();
+    endDate.setHours(23, 59, 59, 999);
+    
+    let startDate = new Date(endDate);
+    startDate.setHours(0, 0, 0, 0);

     switch (value) {
         case 'today':
-            startDate = today;
             break;
         case 'week':
-            startDate.setDate(today.getDate() - 7);
+            startDate.setDate(endDate.getDate() - 7);
             break;
         case 'month':
-            startDate.setMonth(today.getMonth() - 1);
+            startDate.setMonth(endDate.getMonth() - 1);
             break;
         default:
             return;
     }

Line range hint 53-67: Extract filter options to constants.

The filter options are currently hardcoded in the JSX. Consider extracting them to a constants file for better maintainability.

Example implementation:

// constants/filters.ts
export const DASHBOARD_FILTERS = {
  TODAY: 'today',
  WEEK: 'week',
  MONTH: 'month'
} as const;

export const DASHBOARD_FILTER_OPTIONS = [
  { value: DASHBOARD_FILTERS.TODAY, label: 'Today' },
  { value: DASHBOARD_FILTERS.WEEK, label: 'This Week' },
  { value: DASHBOARD_FILTERS.MONTH, label: 'This Month' }
];
apps/web/app/hooks/features/useReportActivity.ts (2)

11-20: Extract date manipulation to a utility function.

The date string manipulation logic could be moved to a utility function for reusability and consistency.

Consider this implementation:

// utils/date.ts
export const formatDateToISODate = (date: Date): string => 
  date.toISOString().split('T')[0];

export const getDefaultDateRange = (daysBack: number = 7) => {
  const endDate = new Date();
  const startDate = new Date();
  startDate.setDate(startDate.getDate() - daysBack);
  
  return {
    startDate: formatDateToISODate(startDate),
    endDate: formatDateToISODate(endDate)
  };
};

35-61: Enhance error handling with specific error types.

The error handling could be more robust by handling specific error types and providing more context.

Consider this implementation:

 const fetchReportActivity = useCallback(async (customProps?: Partial<UseReportActivityProps>) => {
     if (!user) return;
     try {
         const mergedProps = {
             ...defaultProps,
             ...currentFilters,
             ...(customProps || {}),
             organizationId: user?.employee.organizationId,
             tenantId: user?.tenantId ?? ''
         };
         const { data } = await queryTimeLogReportDailyChart(mergedProps);
         if (data) {
             setRapportChartActivity(data);
             if (customProps) {
                 setCurrentFilters(prev => ({
                     ...prev,
                     ...customProps
                 }));
             }
         } else {
             setRapportChartActivity([]);
         }
     } catch (err) {
-        console.error('Failed to fetch activity report:', err);
+        const error = err as Error;
+        console.error('Failed to fetch activity report:', {
+            message: error.message,
+            filters: customProps,
+            userId: user.id
+        });
+        // Optionally, you could emit an error event or notify an error tracking service
         setRapportChartActivity([]);
     }
 }, [user, queryTimeLogReportDailyChart, currentFilters, setRapportChartActivity]);
apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/team-stats-chart.tsx (2)

39-61: Extract chart configuration to constants.

The line colors and initial visibility state could be extracted to constants for better maintainability.

Consider this implementation:

const CHART_COLORS = {
  TRACKED: '#2563eb',
  MANUAL: '#dc2626',
  IDLE: '#eab308',
  RESUMED: '#34c759'
} as const;

const INITIAL_LINE_VISIBILITY = {
  tracked: true,
  manual: true,
  idle: true,
  resumed: true
} as const;

export function TeamStatsChart({ rapportChartActivity, isLoading }: TeamStatsChartProps) {
  const [visibleLines, setVisibleLines] = useState(INITIAL_LINE_VISIBILITY);
  // ...
}

63-69: Enhance loading state with a progress indicator.

The loading state could be more informative by showing a progress message.

Consider this implementation:

 if (isLoading) {
     return (
         <div className="flex justify-center items-center h-[250px]">
-            <Spinner />
+            <div className="flex flex-col items-center gap-2">
+                <Spinner />
+                <p className="text-sm text-gray-500">Loading activity data...</p>
+            </div>
         </div>
     );
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1be1d7c and cccd49e.

📒 Files selected for processing (4)
  • apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/dashboard-header.tsx (1 hunks)
  • apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/components/team-stats-chart.tsx (3 hunks)
  • apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/page.tsx (3 hunks)
  • apps/web/app/hooks/features/useReportActivity.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: deploy
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (1)
apps/web/app/[locale]/dashboard/team-dashboard/[teamId]/page.tsx (1)

56-65: LGTM! Clean integration of the report activity feature.

The integration of useReportActivity hook and the props passing to child components is well-structured and follows React best practices.

@Innocent-Akim Innocent-Akim requested a review from evereq January 22, 2025 20:50
@evereq evereq merged commit 5f147a0 into develop Jan 22, 2025
13 checks passed
@evereq evereq deleted the feat/report-activity-filters branch January 22, 2025 23:24
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