Skip to content

Conversation

Innocent-Akim
Copy link
Contributor

@Innocent-Akim Innocent-Akim commented Feb 12, 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

  • New Features
    • Introduced a robust activity report feature that provides detailed timesheet analytics.
    • Added a new API endpoint to fetch and validate activity data, ensuring accurate reporting.
    • Enhanced dynamic updates so that activity reports automatically refresh when date ranges or filters change.
    • Improved system integration across client, server, and state management for more reliable report tracking.

- Add comprehensive activity report interfaces with proper TypeScript types
- Create enums for activity sources, log types, and grouping options
- Move IActivityReportParams to dedicated file
- Integrate with existing buildTimeLogParams utility
- Update getActivityReportRequest to use proper typing

Closes #[ticket-number]
- Add TimeLogType import for proper typing
- Cast source parameter to any[] temporarily
- Fix type assertions for logType parameter
- Ensure proper type handling in activity report endpoint

Part of activity report implementation
- Add getActivityReport function for fetching activity data
- Include comprehensive TypeScript interface for parameters
- Add proper query string handling with qs.stringify
- Set sensible defaults for optional parameters
- Include detailed JSDoc with usage example

Part of activity report implementation
- Add activity report state management
- Implement fetchActivityReport using shared fetchReport pattern
- Include activity report in filter updates
- Add loading state handling
- Update type definitions for queryFn

Part of activity report implementation
- Add activityReportState atom in time-logs store
- Replace local state with global atom in useReportActivity
- Update activity report typing with IActivityReport
- Clean up unused imports and formatting
- Comment out unused variable in AppUrls component

Part of activity report state management improvements
Copy link
Contributor

coderabbitai bot commented Feb 12, 2025

Walkthrough

The changes integrate an activity reporting feature throughout the application. A new GET endpoint was added to retrieve activity reports based on query parameters. The existing reporting hook was enhanced by adding state management and functions to fetch and update activity data. Additionally, new TypeScript interfaces and types were introduced for structured reporting data and timesheet statistics. Client and server services now include methods to request activity reports, and a new state atom was added for storing received reports.

Changes

File(s) Change Summary
apps/web/app/[locale]/.../page.tsx Added a commented-out declaration for rapportDailyActivity in the AppUrls component.
apps/web/app/api/.../route.ts Introduced a new GET handler for activity reports with query parameter validation and error handling.
apps/web/app/hooks/features/useReportActivity.ts Enhanced the hook by adding state for activity reports, a fetch function (fetchActivityReport), and integrated calls within update functions and an effect hook.
apps/web/app/interfaces/.../IActivityReport.ts Added interfaces and types related to activity reporting, including enums for grouping.
apps/web/app/interfaces/.../ITimerLog.ts Added a new interface ITimesheetStatisticsData to track timesheet statistics.
apps/web/app/services/client/api/.../timer-log.ts Added an asynchronous function getActivityReport to call the activity report GET endpoint.
apps/web/app/services/server/.../timesheet.ts Introduced a new interface IActivityRequestParams and a function getActivityReportRequest to fetch activity report data on the server.
apps/web/app/stores/time-logs.ts Added a new state atom activityReportState for storing an array of activity reports.

Sequence Diagram(s)

sequenceDiagram
  participant C as Component
  participant H as useReportActivity Hook
  participant A as Client API (getActivityReport)
  participant S as Server GET Handler

  C->>H: Update date range / filters
  H->>A: Call fetchActivityReport
  A->>S: Request GET /timesheet/activity/report with query params
  S-->>A: Return activity report data (200) or error (400/500)
  A-->>H: Provide fetched report data
  H-->>C: Update state with activity report results
Loading

Possibly related PRs

Suggested labels

feature, WEB, Timesheets, Improvement, Ever Teams

Suggested reviewers

  • evereq
  • Cedric921

Poem

I'm Bunny, hopping through the code garden fair,
With activity reports sprouting everywhere.
I munch on new endpoints and state atoms bright,
Skipping over bugs with delight in my sight.
A joyful nibble of changes, pure and keen,
Hopping on our updates like a coding machine!
🐰✨

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/hooks/features/useReportActivity.ts

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.

apps/web/app/interfaces/activity/IActivityReport.ts

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.

apps/web/app/[locale]/dashboard/app-url/[teamId]/page.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.

  • 5 others
✨ 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: 3

🧹 Nitpick comments (6)
apps/web/app/interfaces/activity/IActivityReport.ts (2)

54-54: Consider using string literal unions for better type safety.

The properties payPeriod and employeeLevel could benefit from more specific type definitions.

-    payPeriod: 'NONE' | 'TWICE_PER_MONTH';
+    payPeriod: PayPeriodType;
-    employeeLevel: 'A' | 'B' | 'C';
+    employeeLevel: EmployeeLevelType;

+export type PayPeriodType = 'NONE' | 'TWICE_PER_MONTH';
+export type EmployeeLevelType = 'A' | 'B' | 'C';

Also applies to: 58-58


85-85: Add validation for percentage format.

The duration_percentage property is typed as string but should include format validation.

-    duration_percentage: string;
+    duration_percentage: `${number}%`;
apps/web/app/api/timesheet/activity/report/route.ts (1)

73-80: Consider using custom error types for better error handling.

Using custom error types would allow for more specific error handling and responses.

+class ActivityReportError extends Error {
+    constructor(
+        message: string,
+        public statusCode: number = 500
+    ) {
+        super(message);
+        this.name = 'ActivityReportError';
+    }
+}

         return new Response(
             JSON.stringify({
                 message: 'Internal server error',
-                error: error instanceof Error ? error.message : 'Unknown error'
+                error: error instanceof ActivityReportError 
+                    ? error.message 
+                    : 'Unknown error'
             }),
apps/web/app/hooks/features/useReportActivity.ts (2)

217-218: Consider adding error handling for individual promises.

The Promise.all() calls in updateDateRange and updateFilters could fail silently if any individual promise rejects.

Consider handling individual promise failures:

-Promise.all([
-  fetchReportActivity(newProps),
-  fetchDailyReport(newProps),
-  fetchStatisticsCounts(newProps),
-  fetchActivityReport(newProps)
-]).catch(console.error);
+Promise.allSettled([
+  fetchReportActivity(newProps).catch(err => console.error('Failed to fetch report activity:', err)),
+  fetchDailyReport(newProps).catch(err => console.error('Failed to fetch daily report:', err)),
+  fetchStatisticsCounts(newProps).catch(err => console.error('Failed to fetch statistics:', err)),
+  fetchActivityReport(newProps).catch(err => console.error('Failed to fetch activity report:', err))
+]);

Also applies to: 229-230


238-243: Consider adding retry logic for initial data fetching.

The initial data fetching in useEffect could benefit from retry logic to handle temporary network issues.

Consider implementing a retry mechanism:

const retryFetch = async (fn: () => Promise<any>, retries = 3, delay = 1000) => {
  try {
    return await fn();
  } catch (error) {
    if (retries > 0) {
      await new Promise(resolve => setTimeout(resolve, delay));
      return retryFetch(fn, retries - 1, delay * 2);
    }
    throw error;
  }
};

// Usage in useEffect
if (user) {
  Promise.allSettled([
    retryFetch(() => fetchReportActivity()),
    retryFetch(() => fetchDailyReport()),
    retryFetch(() => fetchStatisticsCounts()),
    retryFetch(() => fetchActivityReport())
  ]).catch(console.error);
}
apps/web/app/services/client/api/timer/timer-log.ts (1)

369-415: Add input validation and consider using a type-safe query builder.

The function could benefit from input validation and a more type-safe approach to query building.

Consider these improvements:

// Add input validation
if (!organizationId || !tenantId || !startDate || !endDate) {
  throw new Error('Required parameters missing: organizationId, tenantId, startDate, and endDate are required');
}

// Validate activity level range
if (activityLevel.start < 0 || activityLevel.end > 100 || activityLevel.start >= activityLevel.end) {
  throw new Error('Invalid activity level range');
}

// Use a type-safe query builder
const queryParams = {
  activityLevel,
  organizationId,
  tenantId,
  startDate: startDate instanceof Date ? startDate.toISOString() : startDate,
  endDate: endDate instanceof Date ? endDate.toISOString() : endDate,
  timeZone,
  groupBy,
  ...(projectIds?.length > 0 && { projectIds }),
  ...(employeeIds?.length > 0 && { employeeIds }),
  ...(source?.length > 0 && { source }),
  ...(logType?.length > 0 && { logType })
};
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e0aff5c and 48bfdb4.

📒 Files selected for processing (8)
  • apps/web/app/[locale]/dashboard/app-url/[teamId]/page.tsx (1 hunks)
  • apps/web/app/api/timesheet/activity/report/route.ts (1 hunks)
  • apps/web/app/hooks/features/useReportActivity.ts (5 hunks)
  • apps/web/app/interfaces/activity/IActivityReport.ts (1 hunks)
  • apps/web/app/interfaces/timer/ITimerLog.ts (1 hunks)
  • apps/web/app/services/client/api/timer/timer-log.ts (2 hunks)
  • apps/web/app/services/server/requests/timesheet.ts (3 hunks)
  • apps/web/app/stores/time-logs.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/web/app/[locale]/dashboard/app-url/[teamId]/page.tsx
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: deploy
🔇 Additional comments (11)
apps/web/app/stores/time-logs.ts (1)

4-4: LGTM! Clean integration of activity report state.

The new state atom follows the established patterns and is well-integrated with the existing state management structure.

Also applies to: 31-31

apps/web/app/interfaces/activity/IActivityReport.ts (1)

112-124: Great documentation with example usage!

The example usage in the comments is very helpful for developers implementing the interface.

apps/web/app/interfaces/timer/ITimerLog.ts (1)

277-284: LGTM! Well-structured statistics interface.

The new ITimesheetStatisticsData interface is well-documented and follows the established patterns in the codebase.

apps/web/app/services/server/requests/timesheet.ts (3)

6-6: LGTM!

Clean import of the activity report interface.


176-184: LGTM!

Well-documented interface that extends the base interface with additional optional parameters for activity report filtering.


269-287: LGTM!

The function is well-documented and follows the established pattern of using buildTimeLogParams for parameter construction.

apps/web/app/hooks/features/useReportActivity.ts (3)

4-4: LGTM!

Clean integration of activity report functionality with proper imports and state management.

Also applies to: 12-12, 65-65


74-74: LGTM!

Consistent query hook setup for activity report.


175-179: LGTM!

Well-structured fetch function for activity report that follows the established pattern.

apps/web/app/services/client/api/timer/timer-log.ts (2)

5-5: LGTM!

Clean import of the activity report interface.


354-368: LGTM!

Excellent JSDoc documentation with clear examples.

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

Successfully merging this pull request may close these issues.

2 participants