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

[Fix]: Handle Timesheet Update #3384

Merged
merged 6 commits into from
Nov 30, 2024
Merged

[Fix]: Handle Timesheet Update #3384

merged 6 commits into from
Nov 30, 2024

Conversation

Innocent-Akim
Copy link
Contributor

@Innocent-Akim Innocent-Akim commented Nov 30, 2024

Description

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

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 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 previous status

Current screenshots

Please add here videos or images of previous status

Summary by CodeRabbit

  • New Features

    • Enhanced AddTaskModal with improved time calculation functionality, including validation for overlapping shifts.
    • Updated EditTaskModal for better state management and streamlined handling of time entries.
    • Introduced new optional defaultValue property in CustomCombobox and ManageOrMemberComponent for default selections.
    • Modified TimeSheet component to manage loading states more effectively with a new property.
  • Bug Fixes

    • Improved validation for time entry in AddTaskModal to ensure start time is less than end time.
  • Documentation

    • Updated interfaces to reflect new properties and functionalities across various components.

Copy link
Contributor

coderabbitai bot commented Nov 30, 2024

Walkthrough

This pull request introduces significant updates to various components related to timesheet management. Key changes include enhancements to the AddTaskModal and EditTaskModal for improved time entry and state management, the addition of a showPageSkeleton property in the TimeSheet component, and modifications to time formatting in the useTimelogFilterOptions hook. Additionally, interfaces in ITimerLog.ts have been updated for better date handling, and new optional defaultValue properties have been added to the CustomCombobox and ManageOrMemberComponent components.

Changes

File Path Change Summary
apps/web/app/[locale]/timesheet/[memberId]/components/AddTaskModal.tsx Updated modal styling, added time calculation functions (convertToMinutesHour, calculateTotalHoursHour), replaced calculateTotalHours, refined overlapping shift logic.
apps/web/app/[locale]/timesheet/[memberId]/components/EditTaskModal.tsx Restructured state management, introduced timeRange state, added updateTime and handleUpdateSubmit functions, adjusted rendering logic for new state structure.
apps/web/app/[locale]/timesheet/[memberId]/page.tsx Added showPageSkeleton property to the withAuthentication export for the TimeSheet component.
apps/web/app/hooks/features/useTimelogFilterOptions.ts Modified generateTimeOptions function to format time in a 12-hour format with AM/PM notation.
apps/web/app/interfaces/timer/ITimerLog.ts Updated startedAt and stoppedAt properties to accept `string
apps/web/lib/components/combobox/index.tsx Added defaultValue property to ComboboxProps, updated CustomCombobox function signature to accept defaultValue.
apps/web/lib/features/manual-time/manage-member-component.tsx Added defaultValue property to ManageOrMemberComponentProps, passed it to CustomCombobox.

Possibly related PRs

Suggested labels

feature

Suggested reviewers

  • evereq
  • Cedric921

🐰 In the meadow, tasks now flow,
With hours counted, watch them grow.
Alerts for overlaps, clear and bright,
In our modal, all feels right!
A combobox with defaults set,
Time management, the best yet! 🌼

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]/timesheet/[memberId]/components/AddTaskModal.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.


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 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.

@Innocent-Akim Innocent-Akim self-assigned this Nov 30, 2024
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: 7

🧹 Outside diff range and nitpick comments (9)
apps/web/app/hooks/features/useTimelogFilterOptions.ts (2)

22-27: Time formatting logic looks good, but consider handling edge cases

The conversion from 24-hour to 12-hour format is implemented correctly. However, there are a few suggestions for improvement:

Consider these enhancements:

 const totalMinutes = i * interval;
 const hour24 = Math.floor(totalMinutes / 60);
-const hour12 = hour24 % 12 || 12; // Convert to 12-hour format
+const hour12 = hour24 === 0 ? 12 : hour24 > 12 ? hour24 - 12 : hour24;
 const minutes = (totalMinutes % 60).toString().padStart(2, '0');
 const period = hour24 < 12 ? 'AM' : 'PM'; // Determine AM/PM
-return `${hour12.toString().padStart(2, '0')}:${minutes} ${period}`;
+// Ensure valid time range
+if (hour24 >= 24) return null;
+return `${hour12.toString().padStart(2, '0')}:${minutes} ${period}`;

The changes above:

  1. Make the 12-hour conversion more explicit
  2. Add validation to prevent invalid times (beyond 24 hours)

30-30: Consider adding JSDoc documentation

The empty line at 30 could be utilized to add JSDoc documentation for the generateTimeOptions function, explaining its purpose and parameters.

Add documentation like this:

+/**
+ * Generates an array of time options in 12-hour format (AM/PM)
+ * @param interval - The interval in minutes between time options (default: 15)
+ * @returns Array of formatted time strings or null for invalid times
+ */
 const generateTimeOptions = (interval = 15) => {
apps/web/app/interfaces/timer/ITimerLog.ts (1)

120-121: Maintain consistency with date handling

The date type changes here match those in TimesheetLog. If you implement the suggested date standardization, ensure it's applied consistently across both interfaces.

Consider creating a common type for timesheet dates:

type TimesheetDateTime = string | Date;  // Or just Date if standardizing

interface TimesheetDateFields {
  startedAt: TimesheetDateTime;
  stoppedAt: TimesheetDateTime;
}

Then use this in both interfaces:

interface TimesheetLog extends BaseEntity, TimesheetDateFields {
  // ... other fields
}

interface UpdateTimesheetStatus extends BaseEntity, TimesheetDateFields {
  // ... other fields
}
apps/web/lib/features/manual-time/manage-member-component.tsx (1)

80-81: Add JSDoc documentation for the new properties.

For consistency with other interface properties, please add JSDoc documentation for classNameTitle and defaultValue properties.

+    /**
+     * Optional CSS class name for the title element.
+     * @type {string}
+     */
     classNameTitle?: string;
+    /**
+     * Optional default value for the combobox fields.
+     * @type {string}
+     */
     defaultValue?: string
apps/web/app/[locale]/timesheet/[memberId]/page.tsx (2)

Line range hint 52-67: Optimize filtering logic for better performance and safety

The current implementation of filterDataTimesheet has potential performance and safety concerns:

  1. Multiple toLowerCase() calls on each iteration
  2. Missing null checks for nested properties
  3. Unnecessary array creation on each filter

Consider this optimization:

 const filterDataTimesheet = useMemo(() => {
+    if (!timesheet.length || !lowerCaseSearch) return timesheet;
     const filteredTimesheet =
         timesheet
             .filter((v) =>
                 v.tasks.some(
                     (task) => {
+                        const title = task.task?.title?.toLowerCase() ?? '';
+                        const fullName = task.employee?.fullName?.toLowerCase() ?? '';
+                        const projectName = task.project?.name?.toLowerCase() ?? '';
+                        return (
-                            task.task?.title?.toLowerCase()?.includes(lowerCaseSearch) ||
-                            task.employee?.fullName?.toLowerCase()?.includes(lowerCaseSearch) ||
-                            task.project?.name?.toLowerCase()?.includes(lowerCaseSearch)
+                            title.includes(lowerCaseSearch) ||
+                            fullName.includes(lowerCaseSearch) ||
+                            projectName.includes(lowerCaseSearch)
+                        );
                     }
                 )
             );
     return filteredTimesheet;
 }, [timesheet, lowerCaseSearch]);

Line range hint 213-227: Enhance ViewToggleButton component

The component is well-implemented but could benefit from:

  1. Moving to a separate file for better code organization
  2. Adding accessibility attributes for better user experience

Consider these enhancements:

 const ViewToggleButton: React.FC<ViewToggleButtonProps> = ({ mode, active, icon, onClick, t }) => (
     <button
         onClick={onClick}
+        role="tab"
+        aria-selected={active}
+        aria-controls={`${mode.toLowerCase()}-panel`}
         className={clsxm(
             'text-[#7E7991]  font-medium w-[191px] h-[40px] flex items-center gap-x-4 text-[14px] px-2 rounded',
             active &&
             'border-b-primary text-primary border-b-2 dark:text-primary-light dark:border-b-primary-light bg-[#F1F5F9] dark:bg-gray-800 font-bold'
         )}
     >
         {icon}
         <span>{mode === 'ListView' ? t('pages.timesheet.VIEWS.LIST') : t('pages.timesheet.VIEWS.CALENDAR')}</span>
     </button>
 );

Consider moving this component to a separate file like components/ViewToggleButton.tsx.

apps/web/app/[locale]/timesheet/[memberId]/components/EditTaskModal.tsx (1)

173-175: Use dynamic label for date picker

The label prop in DatePickerFilter is hardcoded as "Oct 01 2024". It's better to display the selected date dynamically to reflect the user's current selection.

Suggested fix:

 <DatePickerFilter
   date={dateRange.date}
   setDate={handleFromChange}
-  label="Oct 01 2024"
+  label={dateRange.date ? dateRange.date.toLocaleDateString() : ''}
 />
apps/web/app/[locale]/timesheet/[memberId]/components/AddTaskModal.tsx (2)

290-290: Translate comments and alert messages for consistency

The comment // Détection des chevauchements and the alert message 'Le shift modifié chevauche un autre shift existant.' are in French. Translating them to English or implementing localization enhances maintainability and user experience.

Apply this diff to translate the comment and alert message:

- // Détection des chevauchements
+ // Detect overlapping shifts

...

- alert('Le shift modifié chevauche un autre shift existant.');
+ alert('The modified shift overlaps with an existing shift.');
🧰 Tools
🪛 GitHub Check: Cspell

[warning] 290-290:
Unknown word (Détection)


[warning] 290-290:
Unknown word (chevauchements)


282-282: Translate comments to English for consistency

The comment // Validation des données is in French. For clarity and consistency with the rest of the codebase, please translate it to English.

Apply this diff:

- // Validation des données
+ // Data validation
🧰 Tools
🪛 GitHub Check: Cspell

[warning] 282-282:
Unknown word (données)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0ae8dcb and c5ff83d.

📒 Files selected for processing (7)
  • apps/web/app/[locale]/timesheet/[memberId]/components/AddTaskModal.tsx (4 hunks)
  • apps/web/app/[locale]/timesheet/[memberId]/components/EditTaskModal.tsx (11 hunks)
  • apps/web/app/[locale]/timesheet/[memberId]/page.tsx (1 hunks)
  • apps/web/app/hooks/features/useTimelogFilterOptions.ts (1 hunks)
  • apps/web/app/interfaces/timer/ITimerLog.ts (2 hunks)
  • apps/web/lib/components/combobox/index.tsx (3 hunks)
  • apps/web/lib/features/manual-time/manage-member-component.tsx (3 hunks)
🧰 Additional context used
🪛 GitHub Check: Cspell
apps/web/app/[locale]/timesheet/[memberId]/components/AddTaskModal.tsx

[warning] 282-282:
Unknown word (données)


[warning] 286-286:
Unknown word (L’heure)


[warning] 286-286:
Unknown word (début)


[warning] 286-286:
Unknown word (être)


[warning] 286-286:
Unknown word (inférieure)


[warning] 286-286:
Unknown word (l’heure)


[warning] 290-290:
Unknown word (Détection)


[warning] 290-290:
Unknown word (chevauchements)


[warning] 306-306:
Unknown word (modifié)


[warning] 306-306:
Unknown word (chevauche)

🔇 Additional comments (9)
apps/web/app/hooks/features/useTimelogFilterOptions.ts (1)

22-27: Verify the impact of time format changes

The change from 24-hour to 12-hour format might affect components that consume these time options.

Let's check for any components that might be affected:

✅ Verification successful

Time format changes are safe to proceed

The verification shows that the time options are only used for display purposes in select dropdowns and no time parsing or comparison operations depend on the format:

  • The time options are used in AddTaskModal.tsx only for populating select dropdowns
  • TimeSheetFilterPopover.tsx uses the hook but doesn't directly interact with the time format
  • Other components using dates work with Date objects and ISO strings, not the formatted time strings
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for components using generateTimeOptions or timeOptions
rg -l "generateTimeOptions|timeOptions" --type ts --type tsx

# Search for time format patterns to identify potential conflicts
rg -l "(\d{2}:\d{2})\s*(AM|PM|am|pm)" --type ts --type tsx

Length of output: 179


Script:

#!/bin/bash
# Search for components using generateTimeOptions or timeOptions without file type restrictions
rg -l "generateTimeOptions|timeOptions"

# Search for files that import or use the useTimelogFilterOptions hook
rg -l "useTimelogFilterOptions"

# Search for time format patterns to identify potential conflicts
rg -l "(\d{2}:\d{2})\s*(AM|PM|am|pm)"

Length of output: 739


Script:

#!/bin/bash
# Check how the time options are being used in components
rg -A 5 "timeOptions" "apps/web/app/[locale]/timesheet/[memberId]/components/AddTaskModal.tsx"
rg -A 5 "useTimelogFilterOptions" "apps/web/app/[locale]/timesheet/[memberId]/components/TimeSheetFilterPopover.tsx"

# Check if there's any time format parsing or comparison
rg "new Date|Date\.parse|format.*time|parse.*time" "apps/web/lib/features/integrations/calendar/table-time-sheet.tsx"
rg "new Date|Date\.parse|format.*time|parse.*time" "apps/web/app/hooks/features/useTimesheet.ts"

Length of output: 3941

apps/web/lib/components/combobox/index.tsx (1)

Line range hint 1-115: Well-structured component implementation

The overall component implementation is clean and follows React best practices:

  • Proper TypeScript generics usage
  • Clean UI state management
  • Effective use of React hooks
  • Good handling of dynamic width calculations
apps/web/app/interfaces/timer/ITimerLog.ts (3)

Line range hint 137-157: Verify type compatibility with UpdateTimesheet interface

The UpdateTimesheet interface uses Pick to select fields from TimesheetLog. Ensure that consumers of this interface are compatible with the new date types and constrained enum values.

Let's check the usage:

✅ Verification successful

Based on the search results, I can now generate the final response:

The UpdateTimesheet interface usage is consistent with its definition

The interface is used correctly across the codebase:

  • In API calls (createTimesheetFromApi, updateTimesheetFromAPi)
  • In hooks (useTimesheet.ts)
  • In server requests (createTimesheetRequest, updateTimesheetRequest)

All usages properly handle the required fields and maintain type compatibility. No type mismatches or incompatibilities were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for UpdateTimesheet interface usage
rg "UpdateTimesheet.*[{<]" -A 3

# Check for any type errors in related files
ast-grep --pattern 'const $_ : UpdateTimesheet = {
  $$$
}'

Length of output: 5283


88-89: Consider standardizing date type handling

The dual type string | Date for startedAt and stoppedAt could lead to inconsistent date handling across the application. Consider:

  1. Using a single type (preferably Date) and handling string conversion at API boundaries
  2. Adding validation to ensure consistent date format when strings are used

Let's check how dates are handled across the codebase:


91-92: Verify impact of constrained enum values

The hardcoded values TimeLogType.MANUAL and TimerSource.BROWSER make this interface specific to manual browser entries.

Let's verify if this constraint is compatible with all usage scenarios:

✅ Verification successful

Let's fix the syntax and search more broadly to understand the interface and enum definitions, along with their usages. This will help us verify if the constrained enum values are appropriate for all scenarios.


Hardcoded enum values are intentional and correct for this interface

The constrained enum values are appropriate here as this interface specifically represents manual time entries from the browser. This is evidenced by:

  1. The TimerSource enum shows multiple sources (MOBILE, BROWSER, DESKTOP, etc.), but this interface is specifically for browser-based entries
  2. The usage in useManualTime.ts confirms this is the correct pattern for manual time entries from the browser
  3. The TimeLogType enum includes different types (TRACKED, MANUAL, IDLE, RESUMED), but this interface specifically handles manual entries

The constraints help enforce type safety for manual browser-based time entries, which is the intended use case for this interface.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for TimesheetLog implementations to verify enum usage
ast-grep --pattern 'interface $_ extends TimesheetLog {
  $$$
}'

# Check for direct TimesheetLog object creations
rg "TimesheetLog.*=.*{" -A 5

Length of output: 197


Script:

#!/bin/bash
# Search for interface definitions and usages
rg "interface.*TimesheetLog" -A 5

# Search for enum definitions
rg "enum TimeLogType|enum TimerSource" -A 10

# Search for usages of these specific enum values
rg "TimeLogType\.MANUAL|TimerSource\.BROWSER" -A 2

Length of output: 3620

apps/web/lib/features/manual-time/manage-member-component.tsx (2)

98-99: LGTM!

The props destructuring is correctly implemented and maintains consistency with the interface definition.


80-81: Verify the impact on existing implementations.

The addition of the defaultValue prop might affect existing implementations of this component, particularly in timesheet-related features.

Also applies to: 98-99, 127-127

✅ Verification successful

Let me check the actual usage of this component to understand if the changes impact existing implementations.


Changes are safe and backward compatible

The verification shows that the new props (defaultValue and classNameTitle) are optional and the existing implementations remain compatible:

  • EditTaskModal.tsx already uses both props
  • AddTaskModal.tsx and add-manual-time-modal.tsx use only the required props
  • No breaking changes are introduced as the new props are optional
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of ManageOrMemberComponent in timesheet-related files
rg -l "ManageOrMemberComponent" | rg -i "time|sheet"

# Check specific usage patterns
ast-grep --pattern 'ManageOrMemberComponent $props'

Length of output: 371


Script:

#!/bin/bash
# Check how ManageOrMemberComponent is used in the timesheet files
rg -A 5 "ManageOrMemberComponent" apps/web/lib/features/manual-time/add-manual-time-modal.tsx apps/web/app/\[locale\]/timesheet/\[memberId\]/components/EditTaskModal.tsx apps/web/app/\[locale\]/timesheet/\[memberId\]/components/AddTaskModal.tsx

Length of output: 4612

apps/web/app/[locale]/timesheet/[memberId]/page.tsx (1)

211-211: Verify loading state behavior with showPageSkeleton

The addition of showPageSkeleton: true might result in duplicate loading indicators since the component already handles loading state via loadingTimesheet. Please ensure this doesn't create a jarring user experience.

apps/web/app/[locale]/timesheet/[memberId]/components/AddTaskModal.tsx (1)

285-288: ⚠️ Potential issue

Use 'convertToMinutesHour' for 12-hour time format comparison

The function convertToMinutes is designed for 24-hour time formats, but the times are in 12-hour format with AM/PM. Using convertToMinutesHour ensures accurate comparisons.

Apply this diff to fix the issue:

- if (convertToMinutes(startTime) >= convertToMinutes(endTime)) {
+ if (convertToMinutesHour(startTime) >= convertToMinutesHour(endTime)) {

Likely invalid or redundant comment.

🧰 Tools
🪛 GitHub Check: Cspell

[warning] 286-286:
Unknown word (L’heure)


[warning] 286-286:
Unknown word (début)


[warning] 286-286:
Unknown word (être)


[warning] 286-286:
Unknown word (inférieure)


[warning] 286-286:
Unknown word (l’heure)

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 and nitpick comments (2)
apps/web/app/[locale]/timesheet/[memberId]/components/EditTaskModal.tsx (2)

215-234: Improve form validation UX

The current validation approach for the notes field could be improved:

  1. The red border on empty notes is premature if the field hasn't been touched
  2. Character count could show remaining characters instead of current count
 <textarea
   value={timesheetData.notes}
   onChange={(e) => setTimesheetData((prev) => ({
     ...prev,
     notes: e.target.value,
   }))}
   placeholder="Insert notes here..."
   className={clsxm(
     "bg-transparent focus:border-transparent focus:ring-2 focus:ring-transparent",
     "placeholder-gray-300 placeholder:font-normal resize-none p-2 grow w-full",
     "border border-gray-200 dark:border-slate-600 dark:bg-dark--theme-light rounded-md h-40 bg-[#FBB6500D]",
-    timesheetData.notes.trim().length === 0 && "border-red-500"
+    touched.notes && timesheetData.notes.trim().length === 0 && "border-red-500"
   )}
   maxLength={120}
   minLength={0}
   aria-label="Insert notes here"
   required
 />
 <div className="text-sm text-[#282048] dark:text-gray-500 text-right">
-  {timesheetData.notes.length}/{120}
+  {120 - timesheetData.notes.length} characters remaining
 </div>

Line range hint 1-268: Consider using a form management library

The component handles complex form state and validation logic. Consider using a form management library like React Hook Form or Formik to:

  1. Centralize form state management
  2. Handle validation more effectively
  3. Manage form submission states
  4. Reduce boilerplate code
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c5ff83d and ccfc70b.

📒 Files selected for processing (2)
  • apps/web/app/[locale]/timesheet/[memberId]/components/AddTaskModal.tsx (4 hunks)
  • apps/web/app/[locale]/timesheet/[memberId]/components/EditTaskModal.tsx (11 hunks)
🔇 Additional comments (4)
apps/web/app/[locale]/timesheet/[memberId]/components/EditTaskModal.tsx (2)

31-34: ⚠️ Potential issue

Initialize timeRange with values from dataTimesheet

The timeRange state is initialized with empty strings, which could lead to validation issues when submitting the form. This is a known issue from previous reviews.

 const [timeRange, setTimeRange] = useState<{ startTime: string; endTime: string }>({
-  startTime: '',
-  endTime: '',
+  startTime: dataTimesheet.timesheet?.startedAt 
+    ? new Date(dataTimesheet.timesheet.startedAt).toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit' })
+    : '',
+  endTime: dataTimesheet.timesheet?.stoppedAt
+    ? new Date(dataTimesheet.timesheet.stoppedAt).toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit' })
+    : '',
 });

66-87: ⚠️ Potential issue

Add validation and error handling to form submission

The form submission handler needs additional validation and error handling:

  1. Validate that end time is after start time
  2. Add error handling for the updateTimesheet call
  3. Add loading state during submission
 const handleUpdateSubmit = useCallback(async (e: FormEvent<HTMLFormElement>) => {
   e.preventDefault();
+  try {
     const startedAt = new Date(dateRange.date ?? new Date());
     const stoppedAt = new Date(dateRange.date ?? new Date());
     const [startHours, startMinutes] = timeRange.startTime.split(':').map(Number);
     startedAt.setHours(startHours, startMinutes);
     const [endHours, endMinutes] = timeRange.endTime.split(':').map(Number);
     stoppedAt.setHours(endHours, endMinutes);
+    
+    if (stoppedAt <= startedAt) {
+      throw new Error('End time must be after start time');
+    }
+
     await updateTimesheet({
       // ... existing properties
     });
+    closeModal();
+  } catch (error) {
+    console.error('Failed to update timesheet:', error);
+    // Add error notification here
+  }
 }, [dateRange, timeRange, timesheetData, dataTimesheet, updateTimesheet]);

Likely invalid or redundant comment.

apps/web/app/[locale]/timesheet/[memberId]/components/AddTaskModal.tsx (2)

63-63: Resolve conflicting width classes in modal styling

The className includes both md:w-40 (width of 10rem at medium breakpoints) and md:min-w-[32rem] (minimum width of 32rem at medium breakpoints). This conflict may cause unintended layout issues. Consider removing md:w-40 to let md:min-w-[32rem] control the modal's width.

Apply this diff to fix the conflict:

- className="bg-light--theme-light dark:bg-dark--theme-light p-5 rounded-xl w-full md:w-40 md:min-w-[32rem] justify-start h-[auto]"
+ className="bg-light--theme-light dark:bg-dark--theme-light p-5 rounded-xl w-full md:min-w-[32rem] justify-start h-[auto]"

210-210: ClassName configuration is appropriate

The styling for the SelectItem component looks good.

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

🧹 Outside diff range and nitpick comments (1)
apps/web/app/[locale]/timesheet/[memberId]/components/EditTaskModal.tsx (1)

211-235: Consider optimizing state updates

Multiple separate state updates could be combined for better performance, especially for form fields that often change together.

Consider using a single state update:

-onClick={() => setTimesheetData((prev) => ({
-  ...prev,
-  isBillable: true,
-}))}
+onClick={() => setTimesheetData((prev) => {
+  const updates = {
+    isBillable: true,
+    // Add other related fields that might change together
+  };
+  return { ...prev, ...updates };
+})}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ccfc70b and 65ca615.

📒 Files selected for processing (3)
  • apps/web/app/[locale]/timesheet/[memberId]/components/AddTaskModal.tsx (4 hunks)
  • apps/web/app/[locale]/timesheet/[memberId]/components/EditTaskModal.tsx (9 hunks)
  • apps/web/lib/features/manual-time/manage-member-component.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/web/lib/features/manual-time/manage-member-component.tsx
  • apps/web/app/[locale]/timesheet/[memberId]/components/AddTaskModal.tsx
🔇 Additional comments (1)
apps/web/app/[locale]/timesheet/[memberId]/components/EditTaskModal.tsx (1)

159-163: Time input validation looks good!

The implementation includes proper HTML5 validation attributes as previously suggested.

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

🧹 Outside diff range and nitpick comments (2)
apps/web/app/[locale]/timesheet/[memberId]/components/AddTaskModal.tsx (2)

246-259: Add JSDoc documentation for the total hours calculation

The function logic is correct, but adding documentation would improve maintainability.

Consider adding JSDoc:

+/**
+ * Calculates the total hours between two times in 12-hour format
+ * @param start - Start time in "HH:MM AM/PM" format
+ * @param end - End time in "HH:MM AM/PM" format
+ * @returns Total duration in "HH:MMh" format
+ * @example
+ * calculateTotalHoursHour("09:00 AM", "05:00 PM") // Returns "08:00h"
+ * calculateTotalHoursHour("10:00 PM", "02:00 AM") // Returns "04:00h"
+ */
 const calculateTotalHoursHour = React.useCallback(
   (start: string, end: string): string => {
     // ... existing implementation
   },
   []
 );

271-302: Refactor shift change handler for better separation of concerns

The function handles multiple responsibilities and could benefit from being split into smaller, focused functions.

Consider this refactoring:

+const isValidTimeRange = (startTime: string, endTime: string): boolean => {
+    if (!startTime || !endTime) return false;
+    return convertToMinutesHour(startTime) < convertToMinutesHour(endTime);
+};
+
+const hasOverlappingShifts = (
+    shifts: Shift[],
+    currentIndex: number,
+    startTime: string,
+    endTime: string
+): boolean => {
+    return shifts.some((shift, i) => {
+        if (i === currentIndex || !shift.startTime || !shift.endTime) return false;
+        const currentStart = convertToMinutesHour(startTime);
+        const currentEnd = convertToMinutesHour(endTime);
+        const shiftStart = convertToMinutesHour(shift.startTime);
+        const shiftEnd = convertToMinutesHour(shift.endTime);
+        return (
+            (currentStart < shiftEnd && currentEnd > shiftStart) ||
+            (currentStart === shiftStart && currentEnd === shiftEnd)
+        );
+    });
+};

 const handleShiftChange = (index: number, field: keyof Shift, value: string) => {
     const updatedShifts = [...shifts];
     updatedShifts[index][field] = value;
 
     if (field === 'startTime' || field === 'endTime') {
         const { startTime, endTime } = updatedShifts[index];
 
-        if (!startTime || !endTime) return;
-        if (convertToMinutesHour(startTime) >= convertToMinutesHour(endTime)) {
-            return;
-        }
+        if (!isValidTimeRange(startTime, endTime)) return;
 
         updatedShifts[index].totalHours = calculateTotalHoursHour(startTime, endTime);
 
-        const isOverlapping = shifts.some((shift, i) => {
-            if (i === index || !shift.startTime || !shift.endTime) return false;
-            const currentStart = convertToMinutesHour(startTime);
-            const currentEnd = convertToMinutesHour(endTime);
-            const shiftStart = convertToMinutesHour(shift.startTime);
-            const shiftEnd = convertToMinutesHour(shift.endTime);
-            return (
-                (currentStart < shiftEnd && currentEnd > shiftStart) ||
-                (currentStart === shiftStart && currentEnd === shiftEnd)
-            );
-        });
+        const isOverlapping = hasOverlappingShifts(shifts, index, startTime, endTime);
 
         if (isOverlapping) return;
     }
 
     setShifts(updatedShifts);
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 65ca615 and d1d5389.

📒 Files selected for processing (2)
  • apps/web/app/[locale]/timesheet/[memberId]/components/AddTaskModal.tsx (4 hunks)
  • apps/web/app/[locale]/timesheet/[memberId]/components/EditTaskModal.tsx (9 hunks)
🔇 Additional comments (5)
apps/web/app/[locale]/timesheet/[memberId]/components/EditTaskModal.tsx (4)

Line range hint 136-295: Implementation looks good with proper form handling

The form implementation follows React best practices with:

  • Proper form submission handling
  • Input validation
  • Error states
  • Accessibility attributes

33-38: ⚠️ Potential issue

Fix unsafe time string manipulation

The current implementation of time string formatting is unsafe and could fail across different timezones or date formats.

Use a more robust approach with proper date formatting:

 const [timeRange, setTimeRange] = useState<{ startTime: string; endTime: string }>({
   startTime: dataTimesheet.timesheet?.startedAt
-    ? dataTimesheet.timesheet.startedAt.toString().slice(0, 5)
+    ? new Date(dataTimesheet.timesheet.startedAt)
+        .toLocaleTimeString('en-US', { 
+          hour: '2-digit', 
+          minute: '2-digit',
+          hour12: false 
+        })
     : '',
   endTime: dataTimesheet.timesheet?.stoppedAt
-    ? dataTimesheet.timesheet.stoppedAt.toString().slice(0, 5)
+    ? new Date(dataTimesheet.timesheet.stoppedAt)
+        .toLocaleTimeString('en-US', {
+          hour: '2-digit',
+          minute: '2-digit',
+          hour12: false
+        })
     : '',
 });

69-110: ⚠️ Potential issue

Add validation for time order

While the time format validation is good, there's no check to ensure the end time is after the start time.

Add time order validation:

 const handleUpdateSubmit = useCallback(async (e: FormEvent<HTMLFormElement>) => {
   e.preventDefault();
   if (!timeRange.startTime || !timeRange.endTime) {
     alert('Please enter valid start and end times.');
     return;
   }
   if (!/^\d{2}:\d{2}$/.test(timeRange.startTime) || !/^\d{2}:\d{2}$/.test(timeRange.endTime)) {
     alert('Time format should be HH:MM.');
     return;
   }
+  const [startHours, startMinutes] = timeRange.startTime.split(':').map(Number);
+  const [endHours, endMinutes] = timeRange.endTime.split(':').map(Number);
+  const startMinutesTotal = startHours * 60 + startMinutes;
+  const endMinutesTotal = endHours * 60 + endMinutes;
+  if (endMinutesTotal <= startMinutesTotal) {
+    alert('End time must be after start time');
+    return;
+  }

   const baseDate = dateRange.date ?? new Date();
   // ... rest of the code

241-260: ⚠️ Potential issue

Enhance notes field validation

While the UI shows validation state for empty notes, it doesn't prevent submission of whitespace-only notes.

Add proper validation:

 <textarea
   value={timesheetData.notes}
   onChange={(e) => setTimesheetData((prev) => ({
     ...prev,
     notes: e.target.value,
   }))}
   placeholder="Insert notes here..."
   className={clsxm(
     "bg-transparent focus:border-transparent focus:ring-2 focus:ring-transparent",
     "placeholder-gray-300 placeholder:font-normal resize-none p-2 grow w-full",
     "border border-gray-200 dark:border-slate-600 dark:bg-dark--theme-light rounded-md h-40 bg-[#FBB6500D]",
-    timesheetData.notes.trim().length === 0 && "border-red-500"
+    (!timesheetData.notes || timesheetData.notes.trim().length === 0) && "border-red-500"
   )}
   maxLength={120}
   minLength={0}
   aria-label="Insert notes here"
   required
+  onBlur={(e) => {
+    const trimmed = e.target.value.trim();
+    setTimesheetData(prev => ({
+      ...prev,
+      notes: trimmed
+    }));
+  }}
 />

Also add validation in the submit handler:

 const handleUpdateSubmit = useCallback(async (e: FormEvent<HTMLFormElement>) => {
   e.preventDefault();
+  const trimmedNotes = timesheetData.notes.trim();
+  if (trimmedNotes.length === 0) {
+    alert('Notes field cannot be empty');
+    return;
+  }
   // ... rest of the code
 }, [dateRange, timeRange, timesheetData, dataTimesheet, updateTimesheet]);
apps/web/app/[locale]/timesheet/[memberId]/components/AddTaskModal.tsx (1)

63-63: Resolve conflicting width classes in modal styling

The className still includes conflicting width classes: md:w-40 and md:min-w-[32rem].

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