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

Draft PR: Multi-select for departments in locations #10809

Conversation

DonXavierdev
Copy link
Contributor

@DonXavierdev DonXavierdev commented Feb 25, 2025

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features
    • Enhanced the linking interface to allow selecting and adding multiple organizations at once, with updated success messaging.
    • Introduced a hierarchical organization selector that provides multi-level, localized options for choosing facility organizations, improving the overall user experience.

@DonXavierdev DonXavierdev requested a review from a team as a code owner February 25, 2025 12:53
Copy link
Contributor

coderabbitai bot commented Feb 25, 2025

Walkthrough

This pull request updates the LinkDepartmentsSheet component to support multiple organization selections by changing the state from a single string to an array of strings, updating the mutation logic to send multiple organization IDs, and adjusting the UI messages and button state accordingly. Additionally, it introduces a new component, MultiFacilityOrganizationSelector, to allow hierarchical multi-selection of facility organizations with data fetching and dynamic dropdown rendering. These changes streamline multi-organization handling in the application.

Changes

File(s) Change Summary
src/components/Patient/LinkDepartmentsSheet.tsx Updated state handling: changed selectedOrg from string to string[]; modified mutation function to use Promise.all for multiple calls; adjusted success messaging and button disable logic; replaced FacilityOrganizationSelector with MultiFacilityOrganizationSelector.
src/pages/Facility/settings/organizations/components/MultiFacilityOrganizationSelector.tsx Introduced a new hierarchical multi-select component that utilizes React Query for data fetching, supports multiple levels of organization selection, and handles multi-select dropdown UI rendering.

Sequence Diagram(s)

sequenceDiagram
    participant UI as LinkDepartmentsSheet
    participant Selector as MultiFacilityOrganizationSelector
    participant API as Organization API

    UI->>Selector: Render multi-select dropdown(s)
    Selector-->>UI: Return selected organizations (array)
    UI->>API: Trigger addOrganization (Promise.all for each org)
    API-->>UI: Return success for each organization
    UI->>UI: Reset selectedOrg state to empty array
Loading

Possibly related PRs

Suggested labels

needs testing, needs review

Suggested reviewers

  • Jacobjeevan
  • rithviknishad

Poem

In the meadow of code I hop with glee,
Selecting organizations, one, two, and three.
From single strings to arrays that shine,
My multi-select leaps into design.
A hopping tune in every commit,
A rabbit's joy—coding is lit!
🐇✨

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

@DonXavierdev DonXavierdev marked this pull request as draft February 25, 2025 12:53
Copy link

netlify bot commented Feb 25, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit e210f12
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67bdbd4423f4f70009e3b111
😎 Deploy Preview https://deploy-preview-10809.preview.ohc.network
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

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

🧹 Nitpick comments (4)
src/pages/Facility/settings/organizations/components/MultiFacilityOrganizationSelector.tsx (3)

1-17: Clean up commented and unused imports

I notice there are commented out imports on lines 2 and 6 that should be removed for cleaner code.

-// import { Building } from "lucide-react";
-// import CareIcon from "@/CAREUI/icons/CareIcon";

79-79: Remove console.log statement before production

There's a console.log statement that should be removed before merging to production.

-console.log(selectedLevels);

53-70: Handle edge case when no value is selected

The handleLevelChange function has an early return if selectedOrgs.length is 0, but it doesn't update the state or notify the parent component. This could lead to a mismatch between the parent's value and the component's internal state when all selections are cleared.

const handleLevelChange = (values: string[], level: number) => {
  let orgList: FacilityOrganization[] | undefined;

  if (level === 0) {
    orgList = rootOrganizations?.results;
  } else if (level - 1 < organizationQueries.length) {
    orgList = organizationQueries[level - 1].data?.results;
  }

  const selectedOrgs =
    orgList?.filter((org) => values.includes(org.id)) || [];
-  if (!selectedOrgs.length) return;
+  
  const newLevels = selectedLevels.slice(0, level);
-  newLevels.push(...selectedOrgs);
+  if (selectedOrgs.length) {
+    newLevels.push(...selectedOrgs);
+  }
  setSelectedLevels(newLevels);
  onChange(newLevels.map((org) => org.id));
};
src/components/Patient/LinkDepartmentsSheet.tsx (1)

100-118: Optimize multiple organization API calls with error handling

The current implementation uses Promise.all which will fail completely if any single organization addition fails. Consider using Promise.allSettled for more robust error handling.

Also, there appears to be redundant data being sent in the mutation call.

mutationFn: async () => {
  if (!selectedOrg.length) return;
  const { route, pathParams } = getMutationParams(
    entityType,
    entityId,
    facilityId,
    true,
  );

  // Send each organization separately
-  await Promise.all(
+  const results = await Promise.allSettled(
    selectedOrg.map((orgId) =>
      mutate(route, {
        pathParams,
        body: { organization: orgId },
-      })({ organization: orgId }),
+      })(),
    ),
  );
+  
+  // Check for any failed requests
+  const failures = results.filter(r => r.status === 'rejected');
+  if (failures.length > 0) {
+    throw new Error(`Failed to add ${failures.length} organizations`);
+  }
},
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dfeda14 and e210f12.

📒 Files selected for processing (2)
  • src/components/Patient/LinkDepartmentsSheet.tsx (3 hunks)
  • src/pages/Facility/settings/organizations/components/MultiFacilityOrganizationSelector.tsx (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
src/pages/Facility/settings/organizations/components/MultiFacilityOrganizationSelector.tsx (1)
Learnt from: Jacobjeevan
PR: ohcnetwork/care_fe#10104
File: src/pages/FacilityOrganization/components/FacilityOrganizationSelector.tsx:118-118
Timestamp: 2025-02-04T07:18:45.806Z
Learning: The project uses flat translation keys in locale files (e.g., "select_department", "has_sub_departments") without nesting (e.g., "facility.organization.select_department").
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Redirect rules - care-ohc
  • GitHub Check: Header rules - care-ohc
  • GitHub Check: Pages changed - care-ohc
  • GitHub Check: Test
  • GitHub Check: CodeQL-Build
  • GitHub Check: cypress-run (1)
  • GitHub Check: lint
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (6)
src/pages/Facility/settings/organizations/components/MultiFacilityOrganizationSelector.tsx (2)

88-92: LGTM: Root organizations selector implementation

The MultiSelect component is well-implemented with proper data binding and event handling for the root level organizations.


93-106: LGTM: Sub-department selection implementation

The implementation for selecting sub-departments is elegant and handles the hierarchical nature of the data well. The conditional rendering based on has_children is a good approach.

src/components/Patient/LinkDepartmentsSheet.tsx (4)

96-96: State updated to support multi-selection

Good update to change the state from a string to an array of strings to support multiple organization selections.


122-122: Success message updated for multiple organizations

Good update to the success message to reflect that multiple organizations can now be added.


188-192: Component updated to use the new multi-select implementation

Good replacement of the previous selector with the new MultiFacilityOrganizationSelector component that supports multi-selection.


196-197: Button state correctly handles multi-selection

The button's click handler and disabled state have been properly updated to work with the array-based selection state.

Comment on lines +25 to +27
export default function FacilityOrganizationSelector(
props: FacilityOrganizationSelectorProps,
) {
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Component export name doesn't match imported name

The component is exported as FacilityOrganizationSelector but imported as MultiFacilityOrganizationSelector in LinkDepartmentsSheet.tsx. This mismatch could cause confusion for other developers.

-export default function FacilityOrganizationSelector(
+export default function MultiFacilityOrganizationSelector(
  props: FacilityOrganizationSelectorProps,
)
📝 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
export default function FacilityOrganizationSelector(
props: FacilityOrganizationSelectorProps,
) {
export default function MultiFacilityOrganizationSelector(
props: FacilityOrganizationSelectorProps,
) {

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.

Feature: Multi-select of departments in locations
1 participant