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

[Hotfix] Fix current org change #2402

Merged
merged 5 commits into from
Jan 24, 2025
Merged

[Hotfix] Fix current org change #2402

merged 5 commits into from
Jan 24, 2025

Conversation

Codebmk
Copy link
Member

@Codebmk Codebmk commented Jan 24, 2025

Summary of Changes (What does this PR do?)

  • Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change.

Status of maturity (all need to be checked before merging):

  • I've tested this locally
  • I consider this code done
  • This change ready to hit production in its current state
  • The title of the PR states what changed and the related issues number (used for the release note).
  • I've included issue number in the "Closes #ISSUE-NUMBER" part of the "What are the relevant tickets?" section to link the issue.
  • I've updated corresponding documentation for the changes in this PR.
  • I have written unit and/or e2e tests for my change(s).

How should this be manually tested?

  • Please include the steps to be done inorder to setup and test this PR.

What are the relevant tickets?

Screenshots (optional)

Summary by CodeRabbit

  • Bug Fixes

    • Improved loading state handling across multiple components to provide more accurate visual feedback during data fetching.
    • Enhanced organization dropdown selection process for a more immediate response.
    • Refined active group detection and loading mechanism.
  • Refactor

    • Streamlined data fetching and state management logic.
    • Removed unnecessary local storage parsing and error handling.
    • Updated dependency management for React hooks.

Copy link

coderabbitai bot commented Jan 24, 2025

Warning

Rate limit exceeded

@Codebmk has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 10 minutes and 38 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between a4f28e9 and 4d78bb3.

📒 Files selected for processing (1)
  • platform/src/core/hooks/useGetActiveGroupId.jsx (2 hunks)
📝 Walkthrough

Walkthrough

The pull request introduces modifications to several components related to active group management and loading states. The changes primarily focus on enhancing the conditional rendering and data fetching logic across AQNumberCard, OrganizationDropdown, DataDownload, and useGetActiveGroupId components. The modifications improve how the application handles loading states and group selection, particularly by synchronizing user interface responses with data fetching processes.

Changes

File Change Summary
platform/src/common/components/AQNumberCard/index.jsx Updated conditional rendering to include isFetchingActiveGroup in loading state check.
platform/src/common/components/Dropdowns/OrganizationDropdown.jsx Streamlined handleUpdatePreferences and handleDropdownSelect functions, removing error handling and updating organization name synchronously.
platform/src/common/components/Modal/dataDownload/modules/DataDownload.jsx Added isFetchingActiveGroup loading state and modified useEffect to prevent sites summary fetching during active group loading.
platform/src/core/hooks/useGetActiveGroupId.jsx Removed useMemo for active group from storage, introduced new activeGroup state, and updated group selection logic.

Sequence Diagram

sequenceDiagram
    participant User
    participant OrganizationDropdown
    participant ActiveGroupHook
    participant DataComponents

    User->>OrganizationDropdown: Select Organization
    OrganizationDropdown->>ActiveGroupHook: Update Active Group
    ActiveGroupHook-->>DataComponents: Trigger Loading State
    DataComponents->>DataComponents: Render Loading Skeletons
    ActiveGroupHook->>DataComponents: Provide Active Group Data
    DataComponents->>DataComponents: Render Actual Content
Loading

Possibly related PRs

Suggested Reviewers

  • OchiengPaul442
  • Baalmart

Poem

🔄 Loading states dance and sway,
Components sync in their ballet,
Groups transition, smooth and light,
Code refactored, future bright!
A digital waltz of pure delight 🌟


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 or @coderabbitai title 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

@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

🧹 Nitpick comments (2)
platform/src/core/hooks/useGetActiveGroupId.jsx (1)

39-41: Consistent string comparison.
Here, both sides use lowercase, which is good. However, ensure lines 17-19 match this convention for uniformity.

platform/src/common/components/Dropdowns/OrganizationDropdown.jsx (1)

62-62: Consider enhancing user feedback on errors.
Right now, errors are only logged to the console. Providing a user-facing error or a toast could improve the experience if updateUserPreferences fails.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b50166a and 28a29c3.

📒 Files selected for processing (4)
  • platform/src/common/components/AQNumberCard/index.jsx (1 hunks)
  • platform/src/common/components/Dropdowns/OrganizationDropdown.jsx (2 hunks)
  • platform/src/common/components/Modal/dataDownload/modules/DataDownload.jsx (2 hunks)
  • platform/src/core/hooks/useGetActiveGroupId.jsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test-analytics-platform-changes
  • GitHub Check: build-push-deploy-analytics-platform-preview
🔇 Additional comments (14)
platform/src/core/hooks/useGetActiveGroupId.jsx (8)

1-1: Import statement looks good.


5-5: State initialization is straightforward.
Using a null default for activeGroup is clear and easy to maintain.


10-12: Potential loading state ambiguity.
This approach sets loading to false as soon as userInfo changes, which may cause UI flicker if userInfo isn’t fully retrieved. Consider verifying that all relevant data is available before setting loading to false.


15-16: Reactivating loading while searching is appropriate.
This ensures the UI reflects the new fetching operation in progress.


21-21: No issues with setting the active group.
The fallback logic below handles scenarios where no matching group is found.


23-23: Dependency array usage.
Properly references chartData?.organizationName.


29-30: Optional chaining is well-implemented.
This prevents runtime errors when activeGroup is null.


37-37: Organizational name check is valid.
Helps ensure we only proceed if chartData.organizationName is truthy.

platform/src/common/components/Dropdowns/OrganizationDropdown.jsx (1)

89-89: Callback closure is correct.
No issues with the dependency array or function references.

platform/src/common/components/AQNumberCard/index.jsx (1)

333-333: Unified loading condition is sensible.
Displaying a skeleton when either loading or isFetchingActiveGroup is true prevents partial rendering.

platform/src/common/components/Modal/dataDownload/modules/DataDownload.jsx (4)

61-61: Tracking active group loading is a valuable addition.
Using isFetchingActiveGroup here keeps load states in sync across components.


132-133: Guard clause prevents partial data fetch.
Avoids calling fetchSitesSummary prematurely if the active group is still being determined.


136-138: Consistent case handling for group name.
Lowercasing the organization string for fetching is a solid approach to avoid mismatch errors.


141-141: Effect closure is correct.
The hook’s dependencies are properly accounted for.

Comment on lines 17 to 19
const matchingGroup = userInfo?.groups?.find(
(group) => group.grp_title.toLowerCase() === chartData?.organizationName,
);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Case-insensitive matching discrepancy.
Currently, only group.grp_title is converted to lowercase. This may fail if chartData.organizationName contains uppercase letters.

Apply this fix to unify case handling:

- (group) => group.grp_title.toLowerCase() === chartData?.organizationName,
+ (group) => group.grp_title.toLowerCase() === chartData?.organizationName?.toLowerCase(),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const matchingGroup = userInfo?.groups?.find(
(group) => group.grp_title.toLowerCase() === chartData?.organizationName,
);
const matchingGroup = userInfo?.groups?.find(
(group) => group.grp_title.toLowerCase() === chartData?.organizationName?.toLowerCase(),
);

Comment on lines +81 to +85
// Immediately update organization name
dispatch(setOrganizationName(group.grp_title));
localStorage.setItem('activeGroup', JSON.stringify(group));

// Dispatch preferences update asynchronously
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Synchronizing local and remote states.
Immediately updating local storage and Redux could lead to mismatches if the update request fails. Consider deferring local storage updates until the dispatch call succeeds, or handle failures more robustly.

Copy link
Contributor

New next-platform changes available for preview here

Copy link

@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 (2)
platform/src/core/hooks/useGetActiveGroupId.jsx (2)

1-9: Consider adding TypeScript or PropTypes for better type safety.

The hook handles complex state management and Redux interactions. Adding type definitions would improve maintainability and catch potential issues early.


Line range hint 1-89: Consider implementing a more robust state management pattern.

The current implementation mixes multiple concerns:

  1. Loading state management
  2. Group matching logic
  3. Fallback handling
  4. Redux state access

Consider splitting this into smaller, more focused hooks:

  • useGroupLoading for loading state
  • useGroupMatcher for group matching logic
  • useGroupFallback for fallback handling

This would improve testability and maintenance.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 28a29c3 and a4f28e9.

📒 Files selected for processing (1)
  • platform/src/core/hooks/useGetActiveGroupId.jsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build-push-deploy-analytics-platform-preview
🔇 Additional comments (1)
platform/src/core/hooks/useGetActiveGroupId.jsx (1)

17-21: ⚠️ Potential issue

Add null checks to prevent potential runtime errors.

The group matching logic could throw if chartData.organizationName is undefined.

    const matchingGroup = userInfo?.groups?.find(
      (group) =>
        group.grp_title.toLowerCase() ===
-        chartData?.organizationName.toLowerCase(),
+        chartData?.organizationName?.toLowerCase() ?? '',
    );

Likely invalid or redundant comment.

Comment on lines 31 to 32
id: activeGroup?.id || null,
title: activeGroup?.grp_title || null,
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Inconsistent ID property access across the hook.

The hook uses both _id and id properties when returning group data. This inconsistency could lead to bugs.

- id: activeGroup?.id || null,
+ id: activeGroup?._id || null,

Also, consider consolidating the return object creation into a helper function to ensure consistency:

const createReturnObject = (group, loading, userInfo) => ({
  loading,
  id: group?._id || null,
  title: group?.grp_title || null,
  userID: userInfo?._id || null,
  groupList: userInfo?.groups || [],
});

Also applies to: 49-52

Comment on lines 10 to 12
useEffect(() => {
setLoading(false);
}, [userInfo]);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential race condition in loading state management.

The first useEffect blindly sets loading to false whenever userInfo changes, which could interfere with the loading state managed by the second useEffect. Consider removing this useEffect and handling loading state only in the group matching logic.

-  useEffect(() => {
-    setLoading(false);
-  }, [userInfo]);

Comment on lines 39 to 44
if (chartData.organizationName) {
const storedGroupInUserGroups = userInfo.groups.find(
(group) => group._id === activeGroupFromStorage._id,
(group) =>
group.grp_title.toLowerCase() ===
chartData.organizationName.toLowerCase(),
);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Duplicate group matching logic detected.

The case-insensitive group matching logic is duplicated. Consider extracting it into a helper function.

+ const findGroupByOrgName = (groups, orgName) => 
+   groups?.find(group => 
+     group.grp_title.toLowerCase() === orgName?.toLowerCase()
+   );

- const storedGroupInUserGroups = userInfo.groups.find(
-   (group) =>
-     group.grp_title.toLowerCase() ===
-     chartData.organizationName.toLowerCase(),
- );
+ const storedGroupInUserGroups = findGroupByOrgName(
+   userInfo.groups, 
+   chartData.organizationName
+ );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (chartData.organizationName) {
const storedGroupInUserGroups = userInfo.groups.find(
(group) => group._id === activeGroupFromStorage._id,
(group) =>
group.grp_title.toLowerCase() ===
chartData.organizationName.toLowerCase(),
);
const findGroupByOrgName = (groups, orgName) =>
groups?.find(group =>
group.grp_title.toLowerCase() === orgName?.toLowerCase()
);
if (chartData.organizationName) {
const storedGroupInUserGroups = findGroupByOrgName(
userInfo.groups,
chartData.organizationName
);

Copy link
Contributor

New next-platform changes available for preview here

Copy link
Contributor

New next-platform changes available for preview here

Copy link
Contributor

New next-platform changes available for preview here

@Baalmart Baalmart merged commit 68854d0 into staging Jan 24, 2025
30 of 31 checks passed
@Baalmart Baalmart deleted the hotfix-demo-feedback branch January 24, 2025 05:16
@Baalmart Baalmart mentioned this pull request Jan 24, 2025
1 task
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