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

Resources redesign #10308

Merged

Conversation

Jacobjeevan
Copy link
Contributor

@Jacobjeevan Jacobjeevan commented Jan 30, 2025

Proposed Changes

image image

@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

Summary by CodeRabbit

Release Notes

  • Localization

    • Added comprehensive translations for resource statuses in English and other languages.
    • Removed "transfer in progress" translations in multiple languages.
  • Resource Management

    • Updated resource status constants with icons.
    • Introduced new resource list view with card-based layout.
    • Enhanced empty state handling for resources.
  • UI/UX Improvements

    • Refined resource filtering and display mechanisms.
    • Improved internationalization support.
  • Code Refactoring

    • Removed several resource-related components.
    • Updated routing for resource views to include facility context.

Copy link
Contributor

coderabbitai bot commented Jan 30, 2025

Walkthrough

This pull request introduces comprehensive changes to the resources management system, focusing on localization, routing, and component restructuring. The modifications span multiple files, including locale JSON files, routing configurations, and React components. The changes aim to enhance the resource management interface by updating status representations, improving localization support, and refactoring the resource list and related components.

Changes

File Change Summary
public/locale/en.json Added new localization entries for resource statuses, filters, and resource titles.
public/locale/hi.json, kn.json, ta.json Removed transfer_in_progress translation.
src/Routers/routes/ResourceRoutes.tsx Updated resource route to use ResourceList instead of previous View component.
src/common/constants.tsx Replaced RESOURCE_CHOICES with RESOURCE_STATUS_CHOICES, adding icons to status representations.
Deleted Components Removed ResourceBadges.tsx, ResourceBlock.tsx, ResourceBoard.tsx, ResourceCommons.tsx, ResourceFilter.tsx.
src/components/Resource/ResourceList.tsx Completely refactored component with new rendering approach and query handling.
src/components/Resource/ResourceDetailsUpdate.tsx Updated to use new RESOURCE_STATUS_CHOICES and improved localization.

Assessment against linked issues

Objective Addressed Explanation
Redesign resources page (10285)
Follow encounters format (10285)

Possibly related PRs

  • Design of List View layout in Resource Page #9096: This PR adds new key-value pairs in the public/locale/en.json file for localization, including entries for resource statuses like "Approved" and "Pending," which are directly related to the changes made in the main PR that also modifies localization entries for resource statuses.
  • Feat: Display total no. of entities with heading in Organization #10092: This PR introduces new entries for entity counts in the public/locale/en.json file, which aligns with the localization enhancements made in the main PR, focusing on improving the internationalization of the application.
  • added * to all mandatory fields in resource request form #10314: While this PR primarily focuses on adding visual indicators for mandatory fields in the resource request form, it also emphasizes the importance of maintaining UI text in internationalization files, which is a common theme with the localization changes in the main PR.

Suggested labels

needs review, needs testing, P1

Suggested reviewers

  • rithviknishad

Poem

🐰 Hop, hop, resources in line,
Status badges now shine so fine!
Locales updated with care,
A rabbit's touch everywhere!
Code refactored, clean and bright,
Resources dancing with 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 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

netlify bot commented Jan 30, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit db0f427
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/679cc54be8446d00093089d6
😎 Deploy Preview https://deploy-preview-10308--care-ohc.netlify.app
📱 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: 0

🧹 Nitpick comments (6)
src/components/Resource/ResourceList.tsx (5)

2-2: Consider using the useTranslation hook for better context alignment.
Directly importing t from "i18next" can work, but using the useTranslation hook from react-i18next often provides more robust context management and can help avoid unexpected behavior if multiple i18n instances are in use.


42-45: Avoid basing logic on display text.
COMPLETED and ACTIVE are derived by filtering the text field of RESOURCE_STATUS_CHOICES. Depending on translations or display text for logic can be fragile. Consider using IDs or status codes instead.


85-97: Add explicit error handling for the query.
While the isLoading state is handled, consider adding an onError callback or conditional rendering for errors to improve resiliency and user feedback when requests fail.


200-221: Reuse existing translation keys if applicable.
Based on prior learnings from AnveshNalimela, there's a recommendation to unify status translations under certain keys (e.g. "consent__status"). Verify whether reusing those keys (instead of "resource_status__${statusOption}") aligns with your global i18n strategy.


228-299: Consider splitting the rendering block into smaller components.
The mapping logic for resources, empty-state handling, and pagination result in a large JSX block. Refactoring into smaller subcomponents could improve readability and maintainability.

src/components/Resource/ResourceDetailsUpdate.tsx (1)

206-208: Confirm accurate translation keys for resource statuses.
optionLabel={(option) => t(\resource_status__${option}`)}` may require matching keys in your localization files. Use a stable ID/key rather than a user-facing string if your translations or statuses diverge in the future. Also consider adopting past recommendations from retrieved learnings about unifying status translation keys.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 81a6257 and a964e29.

📒 Files selected for processing (14)
  • public/locale/en.json (5 hunks)
  • public/locale/hi.json (0 hunks)
  • public/locale/kn.json (0 hunks)
  • public/locale/ml.json (0 hunks)
  • public/locale/ta.json (0 hunks)
  • src/Routers/routes/ResourceRoutes.tsx (1 hunks)
  • src/common/constants.tsx (1 hunks)
  • src/components/Resource/ResourceBadges.tsx (0 hunks)
  • src/components/Resource/ResourceBlock.tsx (0 hunks)
  • src/components/Resource/ResourceBoard.tsx (0 hunks)
  • src/components/Resource/ResourceCommons.tsx (0 hunks)
  • src/components/Resource/ResourceDetailsUpdate.tsx (2 hunks)
  • src/components/Resource/ResourceFilter.tsx (0 hunks)
  • src/components/Resource/ResourceList.tsx (1 hunks)
💤 Files with no reviewable changes (9)
  • src/components/Resource/ResourceBoard.tsx
  • src/components/Resource/ResourceBadges.tsx
  • public/locale/ta.json
  • src/components/Resource/ResourceBlock.tsx
  • src/components/Resource/ResourceCommons.tsx
  • src/components/Resource/ResourceFilter.tsx
  • public/locale/ml.json
  • public/locale/hi.json
  • public/locale/kn.json
🧰 Additional context used
📓 Learnings (1)
src/components/Resource/ResourceDetailsUpdate.tsx (1)
Learnt from: AnveshNalimela
PR: ohcnetwork/care_fe#9096
File: src/components/Resource/ResourceList.tsx:245-245
Timestamp: 2024-11-13T12:33:52.373Z
Learning: When displaying the resource status in `ResourceList.tsx`, use `{t("consent__status")}` instead of adding a new translation key `{t("resource_status")}`.
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Redirect rules - care-ohc
  • GitHub Check: Header rules - care-ohc
  • GitHub Check: Pages changed - care-ohc
  • GitHub Check: cypress-run (1)
  • GitHub Check: CodeQL-Build
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (5)
src/components/Resource/ResourceList.tsx (1)

47-59: Nice UX improvement with the new EmptyState component!
This is a clean, self-contained implementation for an empty-state view. It helps users easily see when no resources exist.

src/Routers/routes/ResourceRoutes.tsx (1)

3-8: Clean route definition transition.
Switching from <View> to <ResourceList> is straightforward and appears consistent with the new design. Double-check that all references to ListView have been removed in case they are still called in other files.

✅ Verification successful

Clean transition confirmed - no remaining ListView references
The codebase shows a complete transition to ResourceList with no remaining references to the old ListView or View components.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find any references to the old `ListView` or `View` usage in the repo.

rg -A 2 "ListView" 
rg -A 2 "View name=\"resource\""

Length of output: 51


Script:

#!/bin/bash
# First verify we can access the codebase
ls src/Routers/routes/ResourceRoutes.tsx

# Search for any View-related components with broader patterns
rg -i "view" src/
rg "from.*View" src/
rg "import.*View" src/

# Search for potential resource-related view components
rg -i "resource.*view" src/
rg -i "view.*resource" src/

Length of output: 26090

src/common/constants.tsx (1)

165-173: Well-structured resource status mapping with semantic icons!

The constant provides a clear mapping between status values and their visual representations, with semantically meaningful icons that enhance UX.

public/locale/en.json (2)

1734-1740: Comprehensive status translations with proper formatting!

The translations for resource statuses are well-structured and maintain consistency with the status values defined in the constants.


326-326: Clear empty state messages for better UX!

The empty state messages provide clear guidance to users when no resources are found and suggest next actions.

Also applies to: 1367-1367

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

🧹 Nitpick comments (1)
src/components/Resource/ResourceList.tsx (1)

265-359: Consider adding error boundary for the resource list.

The card grid implementation looks good, but it could benefit from error handling for failed resource loads.

+import { ErrorBoundary } from "@/components/ErrorBoundary";

 <div
   className="grid gap-4 sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3"
   data-cy="resource-list-cards"
 >
+  <ErrorBoundary>
     {isLoading ? (
       <CardGridSkeleton count={6} />
     ) : resources.length === 0 ? (
       <div className="col-span-full">
         <EmptyState />
       </div>
     ) : (
       // ... rest of the code
     )}
+  </ErrorBoundary>
 </div>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a964e29 and d3580a9.

📒 Files selected for processing (8)
  • public/locale/en.json (7 hunks)
  • src/Routers/routes/ResourceRoutes.tsx (1 hunks)
  • src/components/Patient/PatientDetailsTab/ResourceRequests.tsx (1 hunks)
  • src/components/Resource/ResourceCreate.tsx (1 hunks)
  • src/components/Resource/ResourceDetails.tsx (5 hunks)
  • src/components/Resource/ResourceDetailsUpdate.tsx (5 hunks)
  • src/components/Resource/ResourceList.tsx (1 hunks)
  • src/components/ui/sidebar/facility-nav.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Resource/ResourceDetailsUpdate.tsx
🧰 Additional context used
📓 Learnings (2)
src/components/Resource/ResourceCreate.tsx (1)
Learnt from: Jacobjeevan
PR: ohcnetwork/care_fe#9062
File: src/Routers/routes/ResourceRoutes.tsx:19-21
Timestamp: 2024-12-10T02:49:05.600Z
Learning: In the `ResourceCreate` component, `facilityId` can be optional.
src/Routers/routes/ResourceRoutes.tsx (1)
Learnt from: Jacobjeevan
PR: ohcnetwork/care_fe#9062
File: src/Routers/routes/ResourceRoutes.tsx:19-21
Timestamp: 2024-12-10T02:49:05.600Z
Learning: In the `ResourceCreate` component, `facilityId` can be optional.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: cypress-run (1)
🔇 Additional comments (11)
src/components/ui/sidebar/facility-nav.tsx (1)

38-42: LGTM!

The change correctly aligns the resource URL with other facility-scoped links by incorporating the baseUrl. This ensures proper facility context in resource navigation.

src/components/Patient/PatientDetailsTab/ResourceRequests.tsx (1)

115-119: LGTM!

The change correctly updates the resource detail URL to include the origin facility's ID, maintaining proper facility context in navigation.

src/components/Resource/ResourceDetails.tsx (2)

206-212: LGTM!

The component's props have been correctly updated to include the required facilityId, aligning with the facility-scoped resource redesign.


272-274: Improved localization for resource status.

The status badge now uses a translation key format that better supports localization.

src/components/Resource/ResourceCreate.tsx (2)

133-133: LGTM!

The change correctly updates the post-creation navigation to include the facility ID, maintaining proper facility context.


Line range hint 47-49: Consider making facilityId optional.

According to the retrieved learnings from PR #9062, facilityId can be optional in the ResourceCreate component. However, the current interface declares it as a required number.

✅ Verification successful

Make facilityId optional and change type to string for consistency

The suggestion to make facilityId optional is valid and should be implemented along with changing its type from number to string for consistency with other components. The code already handles the optional case in the facility query with enabled: !!facilityId.

  • Change the interface to use facilityId?: string
  • Remove String() conversions as they won't be needed anymore
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify if facilityId is optional in other components
# Test: Search for components that make facilityId optional
rg -A 5 'facilityId\?' src/

Length of output: 5894


Script:

#!/bin/bash
# Check interface definition and usage of facilityId in ResourceCreate
ast-grep --pattern 'interface $_Props {
  $$$
  facilityId: $_
  $$$
}'  src/components/Resource/ResourceCreate.tsx

echo "=== Usage patterns ==="
rg -A 3 'facilityId' src/components/Resource/ResourceCreate.tsx

Length of output: 1316

src/Routers/routes/ResourceRoutes.tsx (1)

8-16: LGTM! Routes are properly scoped to facilities.

The route changes correctly implement facility-scoped resource management by:

  1. Including facilityId parameter in all resource routes
  2. Passing facilityId prop to all resource components

Note: Based on past learnings from PR #9062, facilityId can be optional in the ResourceCreate component, but it's correctly required here in the routes where facility context is needed.

src/components/Resource/ResourceList.tsx (3)

1-46: LGTM! Well-structured imports and constants.

The imports are properly organized by type (external libraries, utils, components) and the constants for status management are clearly defined.


48-60: LGTM! EmptyState component follows best practices.

The EmptyState component is well-implemented with:

  • Clear visual hierarchy
  • Proper use of icons and spacing
  • Internationalized text

62-101: LGTM! Data fetching implementation is robust.

The component properly:

  • Uses React Query for efficient data fetching
  • Handles pagination
  • Manages filter state
  • Scopes requests to the facility
public/locale/en.json (1)

326-326: LGTM! Comprehensive localization coverage.

The added localization strings provide complete coverage for:

  • Resource statuses
  • Search functionality
  • Empty states
  • Incoming/Outgoing filters

Also applies to: 1075-1075, 1368-1368, 1443-1443, 1736-1743

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

🧹 Nitpick comments (2)
src/components/Resource/ResourceList.tsx (2)

62-77: Consider extracting search options to a constant.

The search options configuration could be moved outside the component to improve reusability and reduce re-renders.

+const RESOURCE_SEARCH_OPTIONS = [
+  {
+    key: "title",
+    label: "Title",
+    type: "text" as const,
+    placeholder: t("search_by_resource_title"),
+  },
+];

 export default function ResourceList({ facilityId }: { facilityId: string }) {
   const searchOptions = [
-    {
-      key: "title",
-      label: "Title",
-      type: "text" as const,
-      placeholder: t("search_by_resource_title"),
-      value: title || "",
-    },
+    {
+      ...RESOURCE_SEARCH_OPTIONS[0],
+      value: title || "",
+    },
   ];

329-335: Enhance link accessibility and user experience.

The "View Details" link should include more context for screen readers and better hover states.

 <Link
   href={`/facility/${resource.origin_facility.id}/resource/${resource.id}`}
+  aria-label={t("view_resource_details", { title: resource.title })}
   className="items-center self-end p-2 pb-3 text-sm text-primary hover:underline text-right flex justify-end group-hover:translate-x-1 transition-transform"
 >
-  View Details
+  {t("view_details")}
   <CareIcon icon="l-arrow-right" className="ml-1 h-4 w-4" />
 </Link>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4cd3ec0 and 090f5fc.

📒 Files selected for processing (1)
  • src/components/Resource/ResourceList.tsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: cypress-run (1)
🔇 Additional comments (2)
src/components/Resource/ResourceList.tsx (2)

1-46: LGTM! Well-organized imports and constants.

The imports are logically grouped and the status constants provide clear separation of concerns for resource state management.


48-60: LGTM! Well-implemented empty state component.

The EmptyState component follows best practices with:

  • Clear visual hierarchy using design system components
  • Proper internationalization of user-facing text
  • Helpful guidance for users when no resources are found

Comment on lines +86 to +101
const { data: queryResources, isLoading } = useQuery<
PaginatedResponse<ResourceRequest>
>({
queryKey: ["resources", facilityId, qParams],
queryFn: query.debounced(routes.listResourceRequests, {
queryParams: {
status: currentStatus,
title,
limit: resultsPerPage,
offset: ((qParams.page || 1) - 1) * resultsPerPage,
...(outgoing
? { origin_facility: facilityId }
: { assigned_facility: facilityId }),
},
}),
});
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

Add error handling for the query.

The query implementation should handle error states to provide feedback to users when the request fails.

-  const { data: queryResources, isLoading } = useQuery<
+  const { data: queryResources, isLoading, error } = useQuery<
     PaginatedResponse<ResourceRequest>
   >({
     queryKey: ["resources", facilityId, qParams],
     queryFn: query.debounced(routes.listResourceRequests, {
       queryParams: {
         status: currentStatus,
         title,
         limit: resultsPerPage,
         offset: ((qParams.page || 1) - 1) * resultsPerPage,
         ...(outgoing
           ? { origin_facility: facilityId }
           : { assigned_facility: facilityId }),
       },
     }),
+    retry: 2,
   });

+  if (error) {
+    return (
+      <div className="text-red-500">
+        {t("error_loading_resources")}
+      </div>
+    );
+  }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +112 to +160
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
size="sm"
className={cn(
"h-8 min-w-[120px] justify-start",
title &&
"bg-primary/10 text-primary hover:bg-primary/20",
)}
>
<CareIcon icon="l-search" className="mr-2 h-4 w-4" />
{title ? (
<span className="truncate">{title}</span>
) : (
t("search")
)}
</Button>
</PopoverTrigger>
<PopoverContent
className="w-[20rem] p-3"
align="start"
onEscapeKeyDown={(event) => event.preventDefault()}
>
<span className="mr-1">
<CareIcon icon="l-truck" />
</span>
{t(`${resource.status}`)}
</Badge>
</dt>
) : (
<dt
title={t("resource_status")}
className="w-fit mt-1 h-fit flex h-5 shrink-0 items-center rounded-full leading-4"
>
<Badge
variant={
resource.status === "APPROVED" ? "primary" : "secondary"
}
className={`text-lg font-bold rounded-full uppercase ${
resource.status === "APPROVED"
? "bg-sky-200"
: "bg-yellow-200"
}`}
<div className="space-y-4">
<h4 className="font-medium leading-none">
{t("search_resource")}
</h4>
<SearchByMultipleFields
id="resource-search"
options={searchOptions}
initialOptionIndex={0}
onFieldChange={() =>
updateQuery({
status: currentStatus,
title: undefined,
})
}
onSearch={(key, value) =>
updateQuery({
status: currentStatus,
[key]: value || undefined,
})
}
className="w-full border-none shadow-none"
/>
</div>
</PopoverContent>
</Popover>
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

Enhance search popover accessibility.

The search popover implementation should include ARIA labels and keyboard navigation improvements.

 <Popover>
   <PopoverTrigger asChild>
     <Button
       variant="outline"
       size="sm"
+      aria-label={t("search_resources")}
       className={cn(
         "h-8 min-w-[120px] justify-start",
         title &&
           "bg-primary/10 text-primary hover:bg-primary/20",
       )}
     >
       <CareIcon icon="l-search" className="mr-2 h-4 w-4" />
       {title ? (
         <span className="truncate">{title}</span>
       ) : (
         t("search")
       )}
     </Button>
   </PopoverTrigger>
   <PopoverContent
     className="w-[20rem] p-3"
     align="start"
+    role="dialog"
+    aria-label={t("search_resource")}
     onEscapeKeyDown={(event) => event.preventDefault()}
   >
📝 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
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
size="sm"
className={cn(
"h-8 min-w-[120px] justify-start",
title &&
"bg-primary/10 text-primary hover:bg-primary/20",
)}
>
<CareIcon icon="l-search" className="mr-2 h-4 w-4" />
{title ? (
<span className="truncate">{title}</span>
) : (
t("search")
)}
</Button>
</PopoverTrigger>
<PopoverContent
className="w-[20rem] p-3"
align="start"
onEscapeKeyDown={(event) => event.preventDefault()}
>
<span className="mr-1">
<CareIcon icon="l-truck" />
</span>
{t(`${resource.status}`)}
</Badge>
</dt>
) : (
<dt
title={t("resource_status")}
className="w-fit mt-1 h-fit flex h-5 shrink-0 items-center rounded-full leading-4"
>
<Badge
variant={
resource.status === "APPROVED" ? "primary" : "secondary"
}
className={`text-lg font-bold rounded-full uppercase ${
resource.status === "APPROVED"
? "bg-sky-200"
: "bg-yellow-200"
}`}
<div className="space-y-4">
<h4 className="font-medium leading-none">
{t("search_resource")}
</h4>
<SearchByMultipleFields
id="resource-search"
options={searchOptions}
initialOptionIndex={0}
onFieldChange={() =>
updateQuery({
status: currentStatus,
title: undefined,
})
}
onSearch={(key, value) =>
updateQuery({
status: currentStatus,
[key]: value || undefined,
})
}
className="w-full border-none shadow-none"
/>
</div>
</PopoverContent>
</Popover>
<Popover>
<PopoverTrigger asChild>
<Button
variant="outline"
size="sm"
aria-label={t("search_resources")}
className={cn(
"h-8 min-w-[120px] justify-start",
title &&
"bg-primary/10 text-primary hover:bg-primary/20",
)}
>
<CareIcon icon="l-search" className="mr-2 h-4 w-4" />
{title ? (
<span className="truncate">{title}</span>
) : (
t("search")
)}
</Button>
</PopoverTrigger>
<PopoverContent
className="w-[20rem] p-3"
align="start"
role="dialog"
aria-label={t("search_resource")}
onEscapeKeyDown={(event) => event.preventDefault()}
>
<div className="space-y-4">
<h4 className="font-medium leading-none">
{t("search_resource")}
</h4>
<SearchByMultipleFields
id="resource-search"
options={searchOptions}
initialOptionIndex={0}
onFieldChange={() =>
updateQuery({
status: currentStatus,
title: undefined,
})
}
onSearch={(key, value) =>
updateQuery({
status: currentStatus,
[key]: value || undefined,
})
}
className="w-full border-none shadow-none"
/>
</div>
</PopoverContent>
</Popover>

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Jan 31, 2025
Copy link

👋 Hi, @Jacobjeevan,
Conflicts have been detected against the base branch. Please rebase your branch against the base branch.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 090f5fc and db0f427.

📒 Files selected for processing (6)
  • public/locale/en.json (7 hunks)
  • src/Routers/routes/ResourceRoutes.tsx (1 hunks)
  • src/common/constants.tsx (1 hunks)
  • src/components/Resource/ResourceCreate.tsx (1 hunks)
  • src/components/Resource/ResourceDetails.tsx (5 hunks)
  • src/components/Resource/ResourceList.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/components/Resource/ResourceCreate.tsx
  • public/locale/en.json
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: cypress-run (1)
🔇 Additional comments (4)
src/Routers/routes/ResourceRoutes.tsx (1)

9-11: LGTM!

The resource list route correctly includes the facilityId parameter and passes it to the ResourceList component.

src/components/Resource/ResourceDetails.tsx (1)

171-173: LGTM!

The status translation is correctly implemented using a dynamic key based on the status value.

src/components/Resource/ResourceList.tsx (2)

86-101: Add error handling for the query.

The query implementation should handle error states to provide feedback to users when the request fails.


112-160: Enhance search popover accessibility.

The search popover implementation should include ARIA labels and keyboard navigation improvements.

Comment on lines +165 to +173
export const RESOURCE_STATUS_CHOICES = [
{ icon: "l-clock", text: "pending" },
{ icon: "l-check", text: "approved" },
{ icon: "l-ban", text: "rejected" },
{ icon: "l-file-slash", text: "cancelled" },
{ icon: "l-truck", text: "transportation_to_be_arranged" },
{ icon: "l-spinner", text: "transfer_in_progress" },
{ icon: "l-check-circle", text: "completed" },
] as const;
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Inconsistent status value casing found in resource components

The new RESOURCE_STATUS_CHOICES uses lowercase values, but some components still use uppercase status values. This inconsistency should be fixed in:

  • src/components/Resource/ResourceCreate.tsx: Uses "PENDING"
  • src/components/Resource/PrintResourceLetter.tsx: Uses "PENDING" and "REJECTED"
🔗 Analysis chain

LGTM! The new resource status choices are well-structured.

The changes improve the code in several ways:

  • Added icons for better visual representation in the UI
  • Uses lowercase values for consistency
  • Marked with as const for better type safety
  • Clear status workflow from pending to completed

Let's verify the usage of these new status choices:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the new resource status choices and check for any remaining references to the old constant.

# Test 1: Search for any remaining references to the old constant
echo "Checking for any remaining references to RESOURCE_CHOICES..."
rg "RESOURCE_CHOICES" -A 5

# Test 2: Search for components using the new constant
echo "Checking components using RESOURCE_STATUS_CHOICES..."
rg "RESOURCE_STATUS_CHOICES" -A 5

# Test 3: Search for any hardcoded status values that should use the constant
echo "Checking for hardcoded status values..."
rg -i "status.*['\"](?:pending|approved|rejected|cancelled|completed)['\"]" --type ts --type tsx

Length of output: 3463


Script:

#!/bin/bash
# Description: Check for hardcoded status values with correct file type specification

# Search for hardcoded status values in TypeScript and TSX files
echo "Checking for hardcoded status values..."
rg -t typescript -t tsx -i "status.*['\"](?:pending|approved|rejected|cancelled|completed)['\"]"

# Also check for transportation and transfer status values
echo "Checking for transportation status values..."
rg -t typescript -t tsx -i "status.*['\"](?:transportation_to_be_arranged|transfer_in_progress)['\"]"

Length of output: 468


Script:

#!/bin/bash
# Description: Check for hardcoded status values with correct ripgrep file types

# Search in .ts files
echo "Checking .ts files for hardcoded status values..."
rg --type-add 'ts:*.ts' -t ts -i "status.*['\"](?:pending|approved|rejected|cancelled|completed|transportation_to_be_arranged|transfer_in_progress)['\"]"

# Search in .tsx files
echo "Checking .tsx files for hardcoded status values..."
rg --type-add 'tsx:*.tsx' -t tsx -i "status.*['\"](?:pending|approved|rejected|cancelled|completed|transportation_to_be_arranged|transfer_in_progress)['\"]"

Length of output: 2830

Comment on lines +18 to +20
"/facility/:facilityId/resource/:id/print": ({ id }) => (
<PrintResourceLetter id={id} />
),
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

Add facilityId prop to PrintResourceLetter component.

The PrintResourceLetter component should receive the facilityId prop for consistency with other resource routes.

-  "/facility/:facilityId/resource/:id/print": ({ id }) => (
-    <PrintResourceLetter id={id} />
+  "/facility/:facilityId/resource/:id/print": ({ facilityId, id }) => (
+    <PrintResourceLetter facilityId={facilityId} id={id} />
📝 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
"/facility/:facilityId/resource/:id/print": ({ id }) => (
<PrintResourceLetter id={id} />
),
"/facility/:facilityId/resource/:id/print": ({ facilityId, id }) => (
<PrintResourceLetter facilityId={facilityId} id={id} />
),

Comment on lines 114 to 118
const { data, isLoading } = useQuery({
queryKey: ["resource_request", props.id],
queryKey: ["resource_request", id],
queryFn: query(routes.getResourceDetails, {
pathParams: { id: props.id },
pathParams: { id },
}),
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

Add error handling for the query.

The query implementation should handle error states to provide feedback to users when the request fails.

-  const { data, isLoading } = useQuery({
+  const { data, isLoading, error } = useQuery({
     queryKey: ["resource_request", id],
     queryFn: query(routes.getResourceDetails, {
       pathParams: { id },
     }),
   });

+  if (error) {
+    return (
+      <div className="flex items-center justify-center p-4 text-red-500">
+        {t("error_loading_resource_details")}
+      </div>
+    );
+  }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +329 to +331
<Link
href={`/facility/${resource.origin_facility.id}/resource/${resource.id}`}
className="items-center self-end pt-2 pr-4 pb-3 text-sm text-primary hover:underline text-right flex justify-end group-hover:translate-x-1 transition-transform"
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use the provided facilityId prop for navigation.

The resource detail link is using origin_facility.id instead of the provided facilityId prop, which could lead to inconsistent navigation.

-      href={`/facility/${resource.origin_facility.id}/resource/${resource.id}`}
+      href={`/facility/${facilityId}/resource/${resource.id}`}
📝 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
<Link
href={`/facility/${resource.origin_facility.id}/resource/${resource.id}`}
className="items-center self-end pt-2 pr-4 pb-3 text-sm text-primary hover:underline text-right flex justify-end group-hover:translate-x-1 transition-transform"
<Link
href={`/facility/${facilityId}/resource/${resource.id}`}
className="items-center self-end pt-2 pr-4 pb-3 text-sm text-primary hover:underline text-right flex justify-end group-hover:translate-x-1 transition-transform"

@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Jan 31, 2025
@bodhish bodhish merged commit 5a7bdb8 into ohcnetwork:develop Jan 31, 2025
15 of 16 checks passed
Copy link

@Jacobjeevan Your efforts have helped advance digital healthcare and TeleICU systems. 🚀 Thank you for taking the time out to make CARE better. We hope you continue to innovate and contribute; your impact is immense! 🙌

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.

Rework Resources Page
3 participants