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] #8360 Last time slot #8448

Merged
merged 7 commits into from
Oct 18, 2024
Merged

[Fix] #8360 Last time slot #8448

merged 7 commits into from
Oct 18, 2024

Conversation

adkif
Copy link
Contributor

@adkif adkif commented Oct 16, 2024

PR

Please note: we will close your PR without comment if you do not check the boxes above and provide ALL requested information.


resolves #8360

Summary by CodeRabbit

  • New Features

    • Added a method to handle image display in the time tracker, enhancing user interaction with screenshots.
    • Introduced a new logging method for warning messages in the logger service.
  • Bug Fixes

    • Improved error handling in the time tracker component, providing clearer feedback when no screenshots are available.
  • Refactor

    • Updated data handling for time slots to focus on single instances rather than arrays, improving caching efficiency.
    • Refined internal logic for managing screenshots and time slots for better readability and maintainability.
    • Enhanced type safety in the time tracker service's methods.

adkif added 4 commits October 16, 2024 22:23
…Slot> instead of AbstractCacheService<ITimeSlot[]> and adjust type parameters in constructor.
@adkif adkif requested review from evereq and rahul-rocket October 16, 2024 20:26
Copy link
Contributor

coderabbitai bot commented Oct 16, 2024

Walkthrough

The pull request introduces modifications to the TimeSlotCacheService, TimeTrackerComponent, TimeTrackerService, and LoggerService. The TimeSlotCacheService now handles a single time slot instead of an array, improving type specificity. The TimeTrackerComponent enhances screenshot handling and user interface elements, while the TimeTrackerService improves type safety and internal logic. Additionally, a new logging method is added to the LoggerService. These changes collectively refine the management of time slots and enhance the robustness of the timer functionality.

Changes

File Path Change Summary
packages/desktop-ui-lib/src/lib/services/time-slot-cache.service.ts Updated TimeSlotCacheService to extend AbstractCacheService with ITimeSlot instead of ITimeSlot[]. Constructor parameter type changed from StorageService<ITimeSlot[]> to StorageService<ITimeSlot>.
packages/desktop-ui-lib/src/lib/time-tracker/time-tracker.component.ts Added showImage() method; refined screenshot handling methods; improved error handling and refactored existing logic.
packages/desktop-ui-lib/src/lib/time-tracker/time-tracker.service.ts Updated getTimeSlot method to return Promise<ITimeSlot>; added logging for empty timeSlotId; modified request object parameter order.
packages/desktop-ui-lib/src/lib/electron/services/electron/logger.service.ts Introduced warn method to LoggerService for logging warning messages using electron-log.

Assessment against linked issues

Objective Addressed Explanation
Ensure timer makes an API call to fetch the last worked interval and screenshot when it starts ( #8360)
Display retrieved screenshot in the timer or handle case where no screenshot exists ( #8360)
Ensure no local screenshot data is used if the user removed intervals/screenshots ( #8360) Local data handling is still not fully addressed.

Possibly related PRs

Suggested reviewers

  • evereq
  • rahul-rocket

Poem

🐰 In the meadow where time does flow,
A tracker hops, with a new glow.
Screenshots dance, icons play,
Fetching data in a clever way.
With every tick, the timer's bright,
Hopping forward, a joyful sight! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 90d15d0 and a0c6c71.

📒 Files selected for processing (1)
  • packages/desktop-ui-lib/src/lib/time-tracker/time-tracker.component.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/desktop-ui-lib/src/lib/time-tracker/time-tracker.component.ts

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.

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

🧹 Outside diff range and nitpick comments (10)
packages/desktop-ui-lib/src/lib/time-tracker/time-tracker.component.html (1)

116-119: Approve changes with a minor suggestion for accessibility

The modification to conditionally display either an 'eye' or 'eye-slash' icon based on the availability of screenshots is a good improvement. It provides clear visual feedback to the user about the state of the screenshots.

To enhance accessibility, consider adding an aria-label to the button that changes based on the icon:

<button (click)="showImage()" nbButton status="basic"
  [attr.aria-label]="screenshots.length > 0 ? 'View screenshots' : 'No screenshots available'">
  <nb-icon
    [icon]="screenshots.length > 0 ? 'eye' : 'eye-slash'"
    pack="font-awesome"
  ></nb-icon>
</button>

This change will provide context to screen reader users about the button's function and state.

packages/desktop-ui-lib/src/lib/time-tracker/time-tracker.service.ts (1)

408-408: Remove Redundant 'WARN:' Prefix in Log Message

Since log.warn already indicates a warning, the 'WARN:' prefix in the message is unnecessary.

Apply this diff:

- this._loggerService.log.warn('WARN: Time Slot ID should not be empty');
+ this._loggerService.log.warn('Time Slot ID should not be empty');
packages/desktop-ui-lib/src/lib/time-tracker/time-tracker.component.ts (8)

1820-1820: Localize user-facing messages

The message 'Attempted to open an empty image gallery.' is hard-coded in English. To support internationalization and provide a better user experience for users in different locales, please use the translation service to localize this message.

Apply this diff to localize the message:

- const message = 'Attempted to open an empty image gallery.';
+ const message = this._translateService.instant('TIMER_TRACKER.MESSAGES.EMPTY_IMAGE_GALLERY');

Also, ensure that the translation key 'TIMER_TRACKER.MESSAGES.EMPTY_IMAGE_GALLERY' is added to your localization files with the appropriate translations.


Line range hint 1619-1631: Ensure errors are correctly propagated in uploadsScreenshot

In the uploadsScreenshot method, if an error occurs during the execution of this.timeTrackerService.uploadImages(...), the error is caught and logged, but not rethrown or returned. This could lead to undefined being returned, which may cause unexpected behavior in the calling code. It's important to either rethrow the error or return a meaningful value to indicate that the operation failed.

Apply this diff to rethrow the error:

 } catch (error) {
     this._loggerService.error(error);
+    throw error;
 }

Or, if you prefer to return a default value:

 } catch (error) {
     this._loggerService.error(error);
+    return null;
 }

Ensure that the calling code handles the possibility of an error or a null return value appropriately.


Line range hint 1543-1545: Add error handling for IPC calls in startTimer

In the startTimer method, the IPC call this.electronService.ipcRenderer.send('update_tray_start'); is wrapped in a try...catch block that only logs the error to the console. Consider adding proper error handling or user feedback to inform the user if the IPC call fails.

Optionally, you can update the error handling to use your error handler service:

 try {
     this.electronService.ipcRenderer.send('update_tray_start');
-} catch (error) {
-    console.log('Error in update_tray_start', error);
+} catch (error) {
+    this._errorHandlerService.handleError(error);
+    this.toastrService.show('Failed to update tray icon', 'Error', { status: 'danger' });
 }

Line range hint 1693-1704: Improve error handling in refreshTimer method

In the refreshTimer method, errors caught in the catch block are logged using console.log. To maintain consistent error handling throughout the application, consider using the _errorHandlerService to handle errors.

Apply this diff to use the error handler service:

 } catch (err) {
-    console.log('Error', err);
+    this._errorHandlerService.handleError(err);
 } finally {
     this.loading = false;
 }

Line range hint 187-189: Consider marking the private properties as readonly where applicable

The private properties like _lastTotalWorkedToday$, _lastTotalWorkedWeek$, and others are only assigned once and not modified afterwards. Marking them as readonly can prevent accidental reassignment and improve code safety.

Example:

-private _lastTotalWorkedToday$: BehaviorSubject<number> = new BehaviorSubject(0);
+private readonly _lastTotalWorkedToday$: BehaviorSubject<number> = new BehaviorSubject(0);

Line range hint 942-958: Avoid deeply nested if...else blocks for better readability

In the _passedAllAuthorizations method, the nested if...else statements can be refactored for better readability and maintainability. Consider using early returns to reduce nesting depth.

Refactor the method as follows:

 private _passedAllAuthorizations(): boolean {
-    let isPassed = false;
-    // Verify if tracking is enabled
-    if (!this.userData?.employee?.isTrackingEnabled) {
-        this.toastrService.show(this._translateService.instant('TIMER_TRACKER.TOASTR.CANT_RUN_TIMER'), `Warning`, {
-            status: 'danger'
-        });
-        isPassed = false;
-    }
-    // Verify work status of user
-    else if (
-        !this.userData?.employee?.startedWorkOn ||
-        !this.userData?.employee?.isActive ||
-        this.userData?.employee?.workStatus
-    ) {
-        // Additional checks and toastr messages
-        isPassed = false;
-    } else isPassed = true;
-    return isPassed;
+    // Verify if tracking is enabled
+    if (!this.userData?.employee?.isTrackingEnabled) {
+        this.toastrService.show(
+            this._translateService.instant('TIMER_TRACKER.TOASTR.CANT_RUN_TIMER'),
+            `Warning`,
+            { status: 'danger' }
+        );
+        return false;
+    }
+    // Verify work status of user
+    if (
+        !this.userData?.employee?.startedWorkOn ||
+        !this.userData?.employee?.isActive ||
+        this.userData?.employee?.workStatus
+    ) {
+        // Additional checks and toastr messages
+        return false;
+    }
+    return true;
 }

Line range hint 1264-1271: Avoid potential confusion with redundant conditionals in _toggle method

Within the _toggle method, the variable isStarted seems to be used in conditions along with its negation, leading to potential confusion. Re-expressing the logic or adding comments can improve clarity.

Consider reviewing the logic to ensure it's clear and maintainable.


Line range hint 1911-1915: Initialize the tabs$ BehaviorSubject in the constructor

The tabs$ BehaviorSubject is initialized with translated titles, but translations may not be available at the time of property initialization. To ensure that translations are loaded, consider initializing tabs$ in the constructor or an appropriate lifecycle hook after the translations have been loaded.

Example:

-export class TimeTrackerComponent implements OnInit, AfterViewInit {
+export class TimeTrackerComponent implements OnInit, AfterViewInit, OnDestroy {
     // ...
-    public tabs$ = new BehaviorSubject<NbRouteTab[]>([
-        {
-            title: this._translateService.instant('MENU.TASKS'),
-            // ...
-        },
-        // ...
-    ]);
+    public tabs$ = new BehaviorSubject<NbRouteTab[]>([]);
+
+    constructor(
+        // ...
+    ) {
+        // ...
+        this.initializeTabs();
+    }
+
+    private initializeTabs() {
+        this.tabs$.next([
+            {
+                title: this._translateService.instant('MENU.TASKS'),
+                // ...
+            },
+            // ...
+        ]);
+    }
}

Ensure that the translations are loaded before initializing the tabs.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0656dc2 and 8a3cf14.

📒 Files selected for processing (4)
  • packages/desktop-ui-lib/src/lib/services/time-slot-cache.service.ts (1 hunks)
  • packages/desktop-ui-lib/src/lib/time-tracker/time-tracker.component.html (1 hunks)
  • packages/desktop-ui-lib/src/lib/time-tracker/time-tracker.component.ts (3 hunks)
  • packages/desktop-ui-lib/src/lib/time-tracker/time-tracker.service.ts (2 hunks)
🧰 Additional context used
🔇 Additional comments (4)
packages/desktop-ui-lib/src/lib/services/time-slot-cache.service.ts (1)

12-12: LGTM. Constructor parameter type is consistent.

The change in the constructor parameter type from StorageService<ITimeSlot[]> to StorageService<ITimeSlot> is consistent with the class signature change. This ensures type safety throughout the class.

packages/desktop-ui-lib/src/lib/time-tracker/time-tracker.service.ts (3)

22-23: Imports updated appropriately

The addition of ITimeSlot to the imports ensures type safety for the updated method.


416-422: Verify Nested Ordering in Query Parameters Works as Intended

Ensure that the API supports nested ordering for relations like screenshots.recordedAt. Some APIs or ORM frameworks may not support this pattern, which could lead to unexpected results.


424-424: ⚠️ Potential issue

Use Consistent Variable When Setting Cache

For consistency and clarity, use the destructured timeSlotId variable instead of values.timeSlotId when setting the cache.

Apply this diff:

- this._timeSlotCacheService.setValue(timeSlots$, values.timeSlotId);
+ this._timeSlotCacheService.setValue(timeSlots$, timeSlotId);

Likely invalid or redundant comment.

Copy link

nx-cloud bot commented Oct 16, 2024

☁️ Nx Cloud Report

CI is running/has finished running commands for commit a0c6c71. As they complete they will appear below. Click to see the status, the terminal output, and the build insights.

📂 See all runs for this CI Pipeline Execution


🟥 Failed Commands
nx build desktop --prod --base-href ./
nx build gauzy -c=production --prod --verbose
✅ Successfully ran 1 target

Sent with 💌 from NxCloud.

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)
packages/desktop-ui-lib/src/lib/electron/services/electron/logger.service.ts (2)

38-40: LGTM! Consider using a more specific type for improved type safety.

The new warn method is well-implemented and consistent with the existing logging methods. It correctly checks for the existence of this._log before using it, which prevents potential runtime errors.

For improved type safety, consider using a more specific type for the message parameter instead of any[]. You could use unknown[] which is safer than any[] while still allowing flexibility. Here's a suggested change:

- public warn(...message: any[]): void {
+ public warn(...message: unknown[]): void {
    if (this._log) this._log.warn(...message);
  }

This change would maintain the flexibility of accepting any type of argument while providing better type safety.


Line range hint 1-40: Overall improvement to logging capabilities

The addition of the warn method to the LoggerService class enhances its functionality by providing a complete set of standard logging levels (debug, info, warn, error). This change:

  1. Improves error handling capabilities, aligning with the PR objectives.
  2. Maintains consistency with the existing code structure and patterns.
  3. Provides developers with more granular control over log message severity.

Consider adding a log method that takes a log level as a parameter, allowing for more flexible logging:

public log(level: 'debug' | 'info' | 'warn' | 'error', ...message: unknown[]): void {
  if (this._log && this._log[level]) {
    this._log[level](...message);
  }
}

This would provide a unified interface for all logging levels while still maintaining the specific methods for convenience.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8a3cf14 and 3d556b2.

📒 Files selected for processing (3)
  • packages/desktop-ui-lib/src/lib/electron/services/electron/logger.service.ts (1 hunks)
  • packages/desktop-ui-lib/src/lib/time-tracker/time-tracker.component.ts (3 hunks)
  • packages/desktop-ui-lib/src/lib/time-tracker/time-tracker.service.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/desktop-ui-lib/src/lib/time-tracker/time-tracker.component.ts
🧰 Additional context used
🔇 Additional comments (2)
packages/desktop-ui-lib/src/lib/time-tracker/time-tracker.service.ts (2)

416-422: LGTM!

The addition of the relations and order parameters enhances the data retrieval by including screenshots and ensuring they are sorted correctly.


405-410: ⚠️ Potential issue

Consider throwing an error when timeSlotId is missing

Returning null when timeSlotId is missing may lead to null reference errors in the calling code. Throwing an error ensures that the absence of timeSlotId is handled appropriately and makes it clear that this is an exceptional situation.

Apply this diff to throw an error instead:

if (!timeSlotId) {
-    this._loggerService.log.warn('WARN: Time Slot ID should not be empty');
-    return null;
+    throw new Error('Time Slot ID is required');
}

@rahul-rocket rahul-rocket merged commit feb8d46 into develop Oct 18, 2024
17 of 20 checks passed
@rahul-rocket rahul-rocket deleted the fix/#8360-last-timeslot branch October 18, 2024 10:21
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.

[Fix] Error in Timer due to Missing Last Screenshot
3 participants