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

Fixed : Delete Button in Schedules #9739

Closed
wants to merge 4 commits into from

Conversation

Jeffrin2005
Copy link
Contributor

@Jeffrin2005 Jeffrin2005 commented Jan 4, 2025

Proposed Changes

Delete_button.mp4

@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 schedule templates management with improved state handling
    • Added delete functionality for schedule templates
    • Implemented internationalization for user interface text, including button labels and error messages
  • Bug Fixes

    • Improved error handling for API requests and missing facility ID scenarios
  • Refactor

    • Updated component state management using React hooks
    • Improved loading state and data fetching mechanism

@Jeffrin2005 Jeffrin2005 requested a review from a team as a code owner January 4, 2025 12:17
Copy link
Contributor

coderabbitai bot commented Jan 4, 2025

Walkthrough

The pull request introduces state management improvements and internationalization updates in two components: ScheduleTemplatesList and UserAvailabilityTab. In ScheduleTemplatesList, a new state management system is implemented using React hooks to handle schedule templates, including loading states, API fetching, and template deletion. The UserAvailabilityTab component receives internationalization updates, replacing hardcoded strings with translatable keys.

Changes

File Change Summary
src/components/Schedule/ScheduleTemplatesList.tsx - Added state hooks for scheduleTemplates and isLoading
- Implemented handleDelete function for template deletion
- Introduced deleteMutation for managing deletions
- Updated component to fetch templates dynamically
- Added error handling and loading states
- Internationalized text strings
src/components/Users/UserAvailabilityTab.tsx - Added useTranslation hook
- Replaced hardcoded strings with translatable keys
- Updated useEffect dependency array

Assessment against linked issues

Objective Addressed Explanation
Delete Schedule Template [#9663]
Remove Item from List [#9663]

Possibly related PRs

  • fixes address and patient note card multi-line issue #9607: This PR involves internationalization improvements related to the display of patient notes, aligning with the localization efforts in the main PR that integrates internationalization using the useTranslation hook.
  • Fix: Notification close button added #9675: This PR enhances the notification system by adding a close button to toast notifications, relevant to the main PR's integration of toast notifications for error handling during the deletion of schedule templates.

Suggested labels

good to merge, needs review, tested

Suggested reviewers

  • Jacobjeevan

Poem

🐰 Hop, hop, hooray! Code's in play!
Templates dance, errors fade away
State management's new, translations bright
Deletion works with pure delight
A rabbit's code review, what a sight! 🔍


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 4, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 3d1aa5a
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/677a89061f7d100008a95278
😎 Deploy Preview https://deploy-preview-9739--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: 2

🧹 Nitpick comments (3)
src/components/Users/UserAvailabilityTab.tsx (1)

53-53: Dependency array might cause unnecessary calls
Including t in the dependency array causes re-rendering if the translation function changes (e.g., language switch). This is often desired for up-to-date translations, but ensure it doesn't trigger undesired extra calls.

src/components/Schedule/ScheduleTemplatesList.tsx (2)

47-90: Data fetching approach
Consider adding retry logic or user prompts (e.g., “Retry” button) in case of transient network failures.


130-135: Internationalization consistency
For better maintainability, consider using a key-based translation for “No schedule templates found for this month.” rather than passing the full sentence to t().

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 68c4c3d and d01a17b.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (2)
  • src/components/Schedule/ScheduleTemplatesList.tsx (6 hunks)
  • src/components/Users/UserAvailabilityTab.tsx (5 hunks)
🔇 Additional comments (15)
src/components/Users/UserAvailabilityTab.tsx (5)

3-3: Proper import for i18n
The addition of the useTranslation import is well-structured and consistent with React-i18next usage.


45-45: Standard usage of translation hook
Using destructuring to retrieve the t function from useTranslation is clear and idiomatic.


164-164: Internationalizing “Add Exception”
Using the t function helps maintain consistency with your localization efforts.


230-230: Internationalizing “Schedule”
Good adoption of t to ensure the text is translated.


240-240: Internationalizing “Exceptions”
This change aligns with the app's multilingual goals by removing hard-coded strings.

src/components/Schedule/ScheduleTemplatesList.tsx (10)

3-3: No issues with the new import
Your import of useState and useEffect is necessary for the new stateful logic.


18-18: Import of ScheduleAPIs looks good
This import is properly set up to handle schedule-related API endpoints.


29-30: Hooks usage
Leveraging useSlug and useToast for retrieving the facility ID and managing toast notifications is a clean approach.


39-42: State initialization
Initializing scheduleTemplates with items is concise and ensures existing data is readily available without extra fetches.


141-143: Clean list rendering
Mapping over scheduleTemplates is straightforward and well-structured.


150-152: Interface extension
ScheduleTemplateItemProps extends ScheduleTemplate and adds an onDelete callback, which keeps the component interface cohesive.


Line range hint 154-190: Verify slot_type range
Check that (slot.slot_type as unknown as number) is reliably ≥ 1. If it can be 0 or negative, you might get an out-of-bounds error.


219-219: Use of “slots_of”
No issues with the translation key usage here; it follows established patterns.


232-235: Date formatting
Well done using format from date-fns in tandem with the translation placeholder.


32-33: Request library usage
Ensure that the request utility provides robust error handling for timeouts and network failures.

Here’s a shell script to check for consistent error handling in all request calls:

✅ Verification successful

Let me check the request utility implementation to verify error handling.


Let me try a different approach to find the request utility implementation.


Let me check for the error handling implementation.


Based on the examination of the request utility implementation and error handling, I can now provide the final response:

The request utility has robust error handling in place

The implementation includes comprehensive error handling for:

  • Network failures and timeouts (through native fetch API error handling)
  • HTTP error status codes (400-599)
  • Authentication failures with session expiry handling
  • Bad requests with detailed error messages
  • Content type handling for different response types
  • Silent mode option for controlled error notifications

The review comment's concern about error handling is addressed by the existing implementation in:

  • src/Utils/request/request.ts (main request utility)
  • src/Utils/request/handleResponse.ts (centralized error handling)

The implementation properly catches errors, provides appropriate notifications, and handles edge cases like authentication failures gracefully.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Searching for request calls to confirm consistent error handling across the repo
rg -A 5 'request\(' 

Length of output: 19206


Script:

#!/bin/bash
# Check the request utility implementation
ast-grep --pattern 'export $_ function request' -A 30

Length of output: 55


Script:

#!/bin/bash
# Find and examine the request utility file
fd request.ts --type f --exec cat {}

Length of output: 7015


Script:

#!/bin/bash
# Find and examine the handleResponse utility
fd handleResponse.ts --type f --exec cat {}

Length of output: 1183

useEffect(() => {
if (!facilityId) {
toast.error("User needs to be linked to a home facility");
toast.error(t("user_needs_to_be_linked_to_home_facility"));
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

Missing translation key detected

The translation key user_needs_to_be_linked_to_home_facility is not found in any of the locale files (en, hi, kn, ml, mr, ta) under public/locale/, but it is being used in src/components/Users/UserAvailabilityTab.tsx. This will likely result in missing text or fallback issues in the UI.

  • Add the translation key and its corresponding text to all locale files under public/locale/
  • Start with public/locale/en.json for the English text, then ensure translations are added to other language files
🔗 Analysis chain

Ensure translation key is defined
It's best practice to verify that the key "user_needs_to_be_linked_to_home_facility" is present in your translation resources to avoid missing-text fallback issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the translation key is present in the locale files
rg "user_needs_to_be_linked_to_home_facility"

Length of output: 156


Script:

#!/bin/bash
# Search for translation files in common locations
fd -e json -e yaml -e yml translations
fd -e json -e yaml -e yml locales
fd -e json -e yaml -e yml i18n

# Let's also check the content of these files if found
fd -e json -e yaml -e yml "translations|locales|i18n" --exec cat {}

Length of output: 181


Script:

#!/bin/bash
# Let's try a broader search for translation files and keys
# First, let's find all json/yaml files that might contain translations
fd -e json -e yaml -e yml . 

# Also search for any file that might contain this specific translation key
rg -l "user_needs_to_be_linked_to_home_facility" --type json --type yaml --type typescript --type javascript

Length of output: 773


Script:

#!/bin/bash
# Let's check the content of locale files to find the translation key
cat public/locale/en.json | grep -i "user_needs_to_be_linked_to_home_facility"
cat public/locale/hi.json | grep -i "user_needs_to_be_linked_to_home_facility"
cat public/locale/kn.json | grep -i "user_needs_to_be_linked_to_home_facility"
cat public/locale/ml.json | grep -i "user_needs_to_be_linked_to_home_facility"
cat public/locale/mr.json | grep -i "user_needs_to_be_linked_to_home_facility"
cat public/locale/ta.json | grep -i "user_needs_to_be_linked_to_home_facility"

Length of output: 473

Comment on lines 91 to 124
const handleDelete = async (id: string) => {
if (!scheduleTemplates || !facilityId) return;

try {
const { error } = await request(ScheduleAPIs.templates.delete, {
pathParams: { facility_id: facilityId, id },
});

if (error) {
throw new Error(t("failed_to_delete_template"));
}

setScheduleTemplates((prevTemplates) =>
prevTemplates
? prevTemplates.filter((template) => template.id !== id)
: [],
);

toast({
title: t("success"),
description: t("schedule_template_deleted_successfully"),
variant: "default",
});
} catch (error) {
console.error(t("failed_to_delete_schedule_template"), error);
toast({
title: t("error"),
description: t(
"an_error_occurred_while_deleting_the_schedule_template",
),
variant: "destructive",
});
}
};
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

Deletion confirmation
Ensure users can’t accidentally delete a schedule template by adding a confirmation dialog.

Here’s a possible approach:

+const handleDelete = async (id: string) => {
+  if (!window.confirm("Are you sure you want to delete this item?")) {
+    return;
+  }
+  // Existing code
+};

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

Copy link
Member

@rithviknishad rithviknishad left a comment

Choose a reason for hiding this comment

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

use useMutation instead

@rithviknishad
Copy link
Member

rithviknishad commented Jan 4, 2025

most of the changes present here seems to be unrelated to solve the issue. closing it

@rithviknishad rithviknishad added the invalid This doesn't seem right label Jan 4, 2025
@github-actions github-actions bot added needs-triage question Further information is requested labels Jan 4, 2025
@Jeffrin2005
Copy link
Contributor Author

@rithviknishad, Used useMutation. Do I need to create a new PR, or can you reopen this PR again?

@rithviknishad rithviknishad reopened this Jan 4, 2025
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 (4)
src/components/Schedule/ScheduleTemplatesList.tsx (4)

4-4: Importing React
Since React 17+, importing React is optional for JSX transforms, but having it is not harmful and can improve clarity.


49-73: Well-handled delete mutation
Using a React Query mutation with onSuccess and onError callbacks is an excellent pattern for consistent feedback to users. Consider adding a success toast for user confirmation as well.


93-93: Internationalization string handling
Directly passing a sentence string to t is acceptable, though some projects prefer using unique keys (e.g., t("no_schedule_templates_found_for_this_month")). This is a minor nitpick and depends on your i18n conventions.


100-102: Prop spreading in ScheduleTemplateItem
Using the spread operator ({...template}) is concise. Consider explicitly passing only the needed props to make the component API clearer.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d01a17b and 09a1e04.

📒 Files selected for processing (1)
  • src/components/Schedule/ScheduleTemplatesList.tsx (7 hunks)
🔇 Additional comments (12)
src/components/Schedule/ScheduleTemplatesList.tsx (12)

2-2: Good usage of @tanstack/react-query imports
Leveraging useMutation and useQueryClient promotes a clean approach to data updates throughout your application.


19-19: Consistent use of ScheduleAPIs
Pulling in the ScheduleAPIs aligns with the rest of the codebase. Looks good.


30-34: Usage of custom hooks
Good job integrating useSlug, useToast, and request from your utility modules. Ensure these hooks and utilities are well-tested to avoid edge cases.


40-48: Proper initialization of local state
Initializing scheduleTemplates and isLoading based on the incoming items prop is logical. This approach ensures your component handles both loaded and pending states appropriately.


74-77: Revisit confirmation flow before deletion
Adding a prompt to confirm deletion would help prevent accidental removals of schedule templates.


78-83: Check for potential re-render conditions
The useEffect updates the state whenever items changes. This is a good pattern to ensure consistency, but verify that subsequent re-renders won't override any unsaved local modifications to scheduleTemplates.


85-89: Clear loading state management
Conditionally rendering <Loading /> is a straightforward way to handle asynchronous data. The logic is clean and easy to read.


109-111: Well-defined interface
Extending ScheduleTemplate with onDelete is simple and integrates nicely with the existing data structure.


113-116: Extracting onDelete and applying translation
Destructuring onDelete and adding t ensures a straightforward and properly localized component. This is a clean implementation.


139-149: Consider user confirmation for destructive action
Right now, the "Delete" action is triggered immediately on this menu item click. A confirmation step here would reduce user mistakes.


178-178: Time slot labeling
Your use of t("slots_of") clarifies the label for translated audiences. Ensure related time units are consistently localized (e.g., "mins").


191-195: Consistent date range display
Wrapping date outputs in strong is a nice way to highlight key information. The translation usage for "valid_from" and "till" is straightforward and effective.

Copy link
Member

@rithviknishad rithviknishad left a comment

Choose a reason for hiding this comment

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

Most of the changes are still irrelavant. Also DO NOT use request within useQuery. request does not throw for HTTP Errors, but useQuery needs such things to be thrown in order to handle toast notifications accordingly.

Refer: https://docs.ohc.network/docs/care/development/data-fetching-in-care/

Also PLEASE DISCARD LOCKFILE CHANGES WHEN MAKING PR UNLESS NECESSARY. I guess this has been flagged in most of your PRs by now.

@Jeffrin2005
Copy link
Contributor Author

@rithviknishad, I have made changes like removing request and removed notification for deletion(toast), Could you please check it out by re-opening the PR, if there are any other unnecessary codes.

@rithviknishad rithviknishad reopened this Jan 5, 2025
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

♻️ Duplicate comments (1)
src/components/Schedule/ScheduleTemplatesList.tsx (1)

47-66: ⚠️ Potential issue

Add error handling and user confirmation for delete operation

The delete mutation implementation is good, but there are two important improvements needed:

  1. Add error handling to show feedback when deletion fails
  2. Add confirmation dialog before deletion (as previously suggested)

Here's how to improve the implementation:

  const deleteMutation = useMutation({
    mutationFn: (id: string) =>
      mutate(ScheduleAPIs.templates.delete, {
        pathParams: { facility_id: facilityId!, id },
      })({}),
    onSuccess: (_, variables) => {
      setScheduleTemplates((prevTemplates) =>
        prevTemplates
          ? prevTemplates.filter((template) => template.id !== variables)
          : [],
      );
      queryClient.invalidateQueries({
        queryKey: ["scheduleTemplates", facilityId],
      });
    },
+   onError: (error) => {
+     // Assuming you have a toast notification system
+     toast.error(t("Failed to delete schedule template"));
+   },
  });
  const handleDelete = (id: string) => {
    if (!scheduleTemplates || !facilityId) return;
+   if (!window.confirm(t("Are you sure you want to delete this template?"))) {
+     return;
+   }
    deleteMutation.mutate(id);
  };
🧹 Nitpick comments (3)
src/components/Schedule/ScheduleTemplatesList.tsx (3)

39-72: Consider adding cleanup for state updates

While the state management is well-implemented, there's a potential race condition in the useEffect hook. If the component unmounts while items are being loaded, you might have state updates on an unmounted component.

Consider adding a cleanup function:

  useEffect(() => {
+   let mounted = true;
    if (items !== undefined) {
-     setScheduleTemplates(items);
-     setIsLoading(false);
+     if (mounted) {
+       setScheduleTemplates(items);
+       setIsLoading(false);
+     }
    }
+   return () => {
+     mounted = false;
+   };
  }, [items]);

Line range hint 98-138: Show loading and error states during deletion

The component interface and i18n implementation look good, but the UI should reflect the mutation state during deletion operations.

Consider updating the delete button to show loading state:

  <DropdownMenuItem
    className="cursor-pointer"
+   disabled={deleteMutation.isPending}
    onClick={() => onDelete(props.id)}
  >
-   {t("delete")}
+   {deleteMutation.isPending ? t("deleting...") : t("delete")}
  </DropdownMenuItem>

Line range hint 1-191: Overall implementation feedback

The implementation successfully addresses the delete functionality with good practices for state management, TypeScript usage, and i18n support. However, before merging, please address the following critical items:

  1. Add confirmation dialog for delete operations
  2. Implement error handling with user feedback
  3. Show loading states during deletion
  4. Add cleanup in useEffect to prevent memory leaks

The changes align well with the PR objectives and maintain good code quality.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 09a1e04 and 3d1aa5a.

📒 Files selected for processing (1)
  • src/components/Schedule/ScheduleTemplatesList.tsx (7 hunks)
🔇 Additional comments (1)
src/components/Schedule/ScheduleTemplatesList.tsx (1)

2-4: Well-structured imports!

The added imports are appropriate for implementing the delete functionality with proper state management and internationalization support.

Also applies to: 19-19, 30-32

@rithviknishad
Copy link
Member

rithviknishad commented Jan 5, 2025

  1. You've still not discard the changes to the lockfile.
  2. This is still not the right way to do it. I don't understand why we need so much complications just for a simple "delete" and "query invalidation" to be implemented.
  3. This is not the right way to handle i18n translations either. Please read readme

Taking it up myself, as I've done this in my upcoming PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
changes required invalid This doesn't seem right needs-triage question Further information is requested
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Unable to Delete Items: Button Not Working
2 participants