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

Support for rescheduling appointment #9956

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from

Conversation

rithviknishad
Copy link
Member

@rithviknishad rithviknishad commented Jan 14, 2025

Required Backends

Proposed Changes

  • Support for rescheduling appointment
  • Disabled selecting slots in the past time even if same day
  • Public Appointments: Close popup upon cancelling a booking and show toast notifications
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

Release Notes

  • New Features

    • Added appointment rescheduling functionality.
    • Introduced new appointment slot picker for easier scheduling.
  • Improvements

    • Enhanced appointment management with flexible rescheduling options.
    • Updated user interface for selecting appointment slots.
  • Translations

    • Added new localization messages for appointment management, including cancellation and rescheduling notifications.
  • User Experience

    • Simplified appointment booking workflow.
    • Added visual indicators for slot availability.

@rithviknishad rithviknishad requested a review from a team as a code owner January 14, 2025 11:03
Copy link
Contributor

coderabbitai bot commented Jan 14, 2025

Walkthrough

This pull request introduces enhancements to the appointment management system, specifically focusing on rescheduling functionality. It includes updates to locale translations, modifications to components, and new type definitions. A new AppointmentSlotPicker component is added for selecting appointment slots, while the AppointmentDetail component is updated to support the rescheduling process. The changes also involve the addition of a new API endpoint for rescheduling appointments and updates to existing interfaces to accommodate the new functionality.

Changes

File Change Summary
public/locale/en.json Added translations for appointment rescheduling: "appointment_cancelled", "appointment_rescheduled", "appointment_rescheduled_successfully", "reschedule_appointment", "rescheduled", and "rescheduling"
src/pages/Appointments/AppointmentDetail.tsx Introduced rescheduling functionality with new state variables, mutation, and UI components for slot selection
src/pages/Appointments/BookAppointment.tsx Removed calendar-related imports and logic; introduced AppointmentSlotPicker component for slot selection
src/pages/Appointments/components/AppointmentSlotPicker.tsx New component for selecting appointment slots with availability visualization
src/types/facility/facility.ts Added FacilityBareMinimum interface with id and name properties
src/types/scheduling/schedule.ts Updated Appointment interface with a new facility property; added "rescheduled" status to AppointmentCancelledStatuses
src/types/scheduling/scheduleApis.ts Added new reschedule API endpoint for rescheduling appointments
src/pages/Patient/index.tsx Integrated AppointmentFinalStatuses into appointment dialog logic, modifying button rendering based on appointment status

Possibly related PRs

Suggested labels

needs review, tested

Suggested reviewers

  • Jacobjeevan

Poem

🐰 A rabbit's tale of scheduling delight,
Slots dancing with precision, oh so bright!
Reschedule with ease, no need to fret,
A calendar magic, a technological pet!
Appointments transformed, smooth as can be! 🗓️

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.

Copy link

netlify bot commented Jan 14, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 943781a
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/678736c1b400ad0008c5696e
😎 Deploy Preview https://deploy-preview-9956--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

cloudflare-workers-and-pages bot commented Jan 14, 2025

Deploying care-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 943781a
Status: ✅  Deploy successful!
Preview URL: https://b8343f96.care-fe.pages.dev
Branch Preview URL: https://appointment-reschedule.care-fe.pages.dev

View logs

Copy link

cypress bot commented Jan 14, 2025

CARE    Run #4319

Run Properties:  status check passed Passed #4319  •  git commit 943781a2b6: Support for rescheduling appointment
Project CARE
Branch Review appointment-reschedule
Run status status check passed Passed #4319
Run duration 01m 46s
Commit git commit 943781a2b6: Support for rescheduling appointment
Committer Rithvik Nishad
View all properties for this run ↗︎

Test results
Tests that failed  Failures 0
Tests that were flaky  Flaky 0
Tests that did not run due to a developer annotating a test with .skip  Pending 0
Tests that did not run due to a failure in a mocha hook  Skipped 0
Tests that passed  Passing 4
View all changes introduced in this 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

🧹 Nitpick comments (6)
src/types/facility/facility.ts (1)

3-7: Consider renaming FacilityBareMinimum for consistency

The interface FacilityBareMinimum could be renamed to align with naming conventions. Consider using a name like FacilitySummary or MinimalFacility for improved clarity and consistency.

src/pages/Appointments/components/AppointmentSlotPicker.tsx (2)

37-53: Consider error handling for data fetching.

While the queries are well-structured, there's no explicit error handling UI for failed queries.

 const slotsQuery = useQuery({
   queryKey: ["slots", facilityId, resourceId, dateQueryString(selectedDate)],
   queryFn: query(scheduleApis.slots.getSlotsForDay, {
     pathParams: { facility_id: facilityId },
     body: {
       user: resourceId ?? "",
       day: dateQueryString(selectedDate),
     },
   }),
   enabled: !!resourceId && !!selectedDate,
+  retry: 2,
 });

+// Add error state handling
+if (slotsQuery.error || heatmapQuery.error) {
+  return (
+    <div className="text-red-500">
+      {t("error_fetching_slots_data")}
+    </div>
+  );
+}

157-171: Consider adding loading states.

The component should show loading indicators while data is being fetched.

 <div className="max-h-96">
+  {(slotsQuery.isLoading || heatmapQuery.isLoading) && (
+    <div className="flex items-center justify-center py-32">
+      <LoadingSpinner />
+    </div>
+  )}
   {slotsQuery.data == null && !slotsQuery.isLoading && (
     <div className="flex items-center justify-center py-32 border-2 border-gray-200 border-dashed rounded-lg text-center">
src/pages/Appointments/AppointmentDetail.tsx (2)

422-441: Consider optimistic updates for better UX.

The mutation could use optimistic updates to provide instant feedback to users.

 const { mutate: rescheduleAppointment, isPending: isRescheduling } =
   useMutation({
     mutationFn: mutate(scheduleApis.appointments.reschedule, {
       pathParams: {
         facility_id: facilityId,
         id: appointment.id,
       },
     }),
+    onMutate: async (newAppointment) => {
+      await queryClient.cancelQueries({ queryKey: ["appointment", appointment.id] });
+      const previousAppointment = queryClient.getQueryData(["appointment", appointment.id]);
+      queryClient.setQueryData(["appointment", appointment.id], old => ({
+        ...old,
+        token_slot: { ...old.token_slot, id: newAppointment.new_slot }
+      }));
+      return { previousAppointment };
+    },
+    onError: (err, newAppointment, context) => {
+      queryClient.setQueryData(
+        ["appointment", appointment.id],
+        context.previousAppointment
+      );
+    },
     onSuccess: (newAppointment: Appointment) => {
       queryClient.invalidateQueries({
         queryKey: ["appointment", appointment.id],
       });

475-519: Add confirmation dialog for rescheduling.

Consider adding a confirmation dialog before rescheduling to prevent accidental changes.

+import {
+  AlertDialog,
+  AlertDialogAction,
+  AlertDialogCancel,
+  AlertDialogContent,
+  AlertDialogDescription,
+  AlertDialogFooter,
+  AlertDialogHeader,
+  AlertDialogTitle,
+  AlertDialogTrigger,
+} from "@/components/ui/alert-dialog";

 <Sheet open={isRescheduleOpen} onOpenChange={setIsRescheduleOpen}>
   {/* ... */}
-  <Button
-    variant="default"
-    disabled={!selectedSlotId || isRescheduling}
-    onClick={() => {
-      if (selectedSlotId) {
-        rescheduleAppointment({ new_slot: selectedSlotId });
-      }
-    }}
-  >
-    {isRescheduling ? t("rescheduling") : t("reschedule")}
-  </Button>
+  <AlertDialog>
+    <AlertDialogTrigger asChild>
+      <Button
+        variant="default"
+        disabled={!selectedSlotId || isRescheduling}
+      >
+        {isRescheduling ? t("rescheduling") : t("reschedule")}
+      </Button>
+    </AlertDialogTrigger>
+    <AlertDialogContent>
+      <AlertDialogHeader>
+        <AlertDialogTitle>{t("reschedule_appointment")}</AlertDialogTitle>
+        <AlertDialogDescription>
+          {t("reschedule_appointment_confirmation")}
+        </AlertDialogDescription>
+      </AlertDialogHeader>
+      <AlertDialogFooter>
+        <AlertDialogCancel>{t("cancel")}</AlertDialogCancel>
+        <AlertDialogAction
+          onClick={() => {
+            if (selectedSlotId) {
+              rescheduleAppointment({ new_slot: selectedSlotId });
+            }
+          }}
+        >
+          {t("confirm")}
+        </AlertDialogAction>
+      </AlertDialogFooter>
+    </AlertDialogContent>
+  </AlertDialog>
public/locale/en.json (1)

400-400: Add translation for rescheduling confirmation.

Add a translation key for the rescheduling confirmation dialog.

   "appointment_rescheduled_successfully": "Appointment rescheduled successfully",
+  "reschedule_appointment_confirmation": "Are you sure you want to reschedule this appointment? The patient will be notified of this change.",
   "reschedule_appointment": "Reschedule Appointment",
   "rescheduling": "Rescheduling...",

Also applies to: 1723-1724

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1021155 and 4527502.

📒 Files selected for processing (7)
  • public/locale/en.json (2 hunks)
  • src/pages/Appointments/AppointmentDetail.tsx (6 hunks)
  • src/pages/Appointments/BookAppointment.tsx (3 hunks)
  • src/pages/Appointments/components/AppointmentSlotPicker.tsx (1 hunks)
  • src/types/facility/facility.ts (1 hunks)
  • src/types/scheduling/schedule.ts (3 hunks)
  • src/types/scheduling/scheduleApis.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: care-fe
🔇 Additional comments (7)
src/pages/Appointments/BookAppointment.tsx (4)

27-27: Imported utilities are correctly utilized

The formatDisplayName and formatName utilities are imported and used appropriately.


30-31: Imported AppointmentSlotPicker component successfully

The AppointmentSlotPicker component is correctly imported and ready for use.


42-42: State management for selectedSlotId implemented correctly

The useState hook is properly used to manage selectedSlotId, ensuring the selected slot ID is tracked properly.


154-159: AppointmentSlotPicker component integrated effectively

The AppointmentSlotPicker is correctly integrated with all necessary props, facilitating proper slot selection functionality.

src/types/scheduling/schedule.ts (1)

142-142: Added facility property to Appointment interface appropriately

The inclusion of the facility property of type FacilityBareMinimum enhances the Appointment interface by providing essential facility details.

src/types/scheduling/scheduleApis.ts (1)

146-151: Well-defined API endpoint for rescheduling!

The reschedule endpoint follows RESTful conventions and maintains consistency with other appointment endpoints.

src/pages/Appointments/components/AppointmentSlotPicker.tsx (1)

20-25: Well-structured props interface!

The props interface is clear and properly typed with optional properties where appropriate.

src/types/scheduling/schedule.ts Show resolved Hide resolved
@@ -137,6 +139,7 @@
reason_for_visit: string;
user: UserBase;
booked_by: UserBase | null; // This is null if the appointment was booked by the patient itself.
facility: FacilityBareMinimum;
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

Update Appointment interface status property type

The status property in the Appointment interface is currently typed as AppointmentNonCancelledStatus, which does not include "rescheduled". To accommodate all possible statuses, including "rescheduled", consider changing the type of status to AppointmentStatus.

Comment on lines +181 to +182
const percentage =
slot.allocated / availability.tokens_per_slot;
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

Similar division by zero risk in slot percentage calculation.

The calculation of slot allocation percentage needs a safety check.

-const percentage = slot.allocated / availability.tokens_per_slot;
+const percentage = availability.tokens_per_slot > 0 
+  ? slot.allocated / availability.tokens_per_slot 
+  : 1;
📝 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 percentage =
slot.allocated / availability.tokens_per_slot;
const percentage = availability.tokens_per_slot > 0
? slot.allocated / availability.tokens_per_slot
: 1;

Comment on lines +85 to +88
const { booked_slots, total_slots } = availability;
const bookedPercentage = booked_slots / total_slots;
const tokensLeft = total_slots - booked_slots;
const isFullyBooked = tokensLeft <= 0;
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

Potential division by zero risk.

The calculation of bookedPercentage could result in division by zero if total_slots is 0.

-const bookedPercentage = booked_slots / total_slots;
+const bookedPercentage = total_slots > 0 ? booked_slots / total_slots : 1;
📝 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 { booked_slots, total_slots } = availability;
const bookedPercentage = booked_slots / total_slots;
const tokensLeft = total_slots - booked_slots;
const isFullyBooked = tokensLeft <= 0;
const { booked_slots, total_slots } = availability;
const bookedPercentage = total_slots > 0 ? booked_slots / total_slots : 1;
const tokensLeft = total_slots - booked_slots;
const isFullyBooked = tokensLeft <= 0;

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/pages/Appointments/AppointmentDetail.tsx (1)

476-520: Add aria-labels for better accessibility.

The rescheduling UI implementation is well structured, but could benefit from accessibility improvements.

Add aria-labels to the buttons:

-          <Button variant="outline" size="lg">
+          <Button variant="outline" size="lg" aria-label={t("reschedule")}>
             <CalendarIcon className="size-4 mr-2" />
             {t("reschedule")}
           </Button>

-              <Button
+              <Button
+               aria-label={t("cancel")}
                variant="outline"
                onClick={() => {
                  setIsRescheduleOpen(false);
                  setSelectedSlotId(undefined);
                }}
               >
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4527502 and 8c6072f.

📒 Files selected for processing (2)
  • public/locale/en.json (2 hunks)
  • src/pages/Appointments/AppointmentDetail.tsx (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: cypress-run (1)
  • GitHub Check: Cloudflare Pages: care-fe
🔇 Additional comments (5)
src/pages/Appointments/AppointmentDetail.tsx (4)

47-53: LGTM! Import statements are properly organized.

The new imports for Sheet components and AppointmentSlotPicker are correctly added and align with the rescheduling feature requirements.

Also applies to: 80-80


244-244: LGTM! Status mapping is correctly updated.

The "rescheduled" status is properly added to the badge variant mapping with the appropriate "secondary" variant.


423-442: LGTM! Reschedule mutation is well implemented.

The implementation follows best practices:

  • Proper type safety with useMutation
  • Appropriate cache invalidation
  • User feedback via toast notification
  • Clean state management
  • Correct navigation to the new appointment

444-444: LGTM! Status check is properly updated.

The condition correctly uses AppointmentCancelledStatuses to include the rescheduled status in the cancelled states check.

public/locale/en.json (1)

400-400: LGTM! Translations are complete and consistent.

All required translations for the rescheduling feature are properly added:

  • appointment_rescheduled_successfully
  • reschedule_appointment
  • rescheduled
  • rescheduling

Also applies to: 1723-1725

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

♻️ Duplicate comments (2)
src/types/scheduling/schedule.ts (2)

117-117: 🛠️ Refactor suggestion

Reevaluate inclusion of "rescheduled" in cancelled statuses

A rescheduled appointment isn't really cancelled - it's moved to a new time. Consider creating a separate status category for rescheduled appointments.


149-149: ⚠️ Potential issue

Update Appointment interface status type

The status property should allow all possible statuses including "rescheduled".

- status: AppointmentNonCancelledStatus;
+ status: AppointmentStatus;
🧹 Nitpick comments (1)
src/pages/Appointments/AppointmentDetail.tsx (1)

477-521: Improve accessibility of rescheduling sheet

Add ARIA labels and keyboard navigation support to the rescheduling sheet.

  <Sheet open={isRescheduleOpen} onOpenChange={setIsRescheduleOpen}>
-   <SheetTrigger asChild>
+   <SheetTrigger asChild aria-label={t("reschedule_appointment")}>
      <Button variant="outline" size="lg">
        <CalendarIcon className="size-4 mr-2" />
        {t("reschedule")}
      </Button>
    </SheetTrigger>
-   <SheetContent className="w-full sm:max-w-xl">
+   <SheetContent 
+     className="w-full sm:max-w-xl"
+     role="dialog"
+     aria-labelledby="reschedule-title"
+   >
      <SheetHeader>
-       <SheetTitle>{t("reschedule_appointment")}</SheetTitle>
+       <SheetTitle id="reschedule-title">{t("reschedule_appointment")}</SheetTitle>
      </SheetHeader>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8c6072f and 699fefe.

📒 Files selected for processing (4)
  • public/locale/en.json (2 hunks)
  • src/pages/Appointments/AppointmentDetail.tsx (7 hunks)
  • src/pages/Patient/index.tsx (4 hunks)
  • src/types/scheduling/schedule.ts (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: care-fe
🔇 Additional comments (1)
public/locale/en.json (1)

397-402: Translation keys look good!

All necessary translation keys for the rescheduling feature have been added with clear and consistent wording.

Also applies to: 1725-1727

Comment on lines 31 to 33
Appointment,
ApppointmentCompletedStatuses,
} from "@/types/scheduling/schedule";
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

Fix typo in imported type name

The imported type name has a typo: ApppointmentCompletedStatuses has 3 'p's.

- import { Appointment, ApppointmentCompletedStatuses } from "@/types/scheduling/schedule";
+ import { Appointment, AppointmentCompletedStatuses } from "@/types/scheduling/schedule";
📝 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
Appointment,
ApppointmentCompletedStatuses,
} from "@/types/scheduling/schedule";
Appointment,
AppointmentCompletedStatuses,
} from "@/types/scheduling/schedule";

Comment on lines +168 to +170
<Button variant="secondary">
<span>{t("reschedule")}</span>
</Button>
Copy link
Contributor

@coderabbitai coderabbitai bot Jan 14, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add click handler for reschedule button

The reschedule button is missing an onClick handler, making it non-functional.

- <Button variant="secondary">
+ <Button 
+   variant="secondary"
+   onClick={() => navigate(`/facility/${facilityId}/appointments/${appointment.id}/reschedule`)}
+ >
    <span>{t("reschedule")}</span>
  </Button>

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

Copy link
Member Author

@rithviknishad rithviknishad Jan 15, 2025

Choose a reason for hiding this comment

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

this would be addressed by @Jacobjeevan in his PR

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

@@ -62,6 +66,9 @@
},
}),
onSuccess: () => {
setSelectedAppointment(undefined);
setAppointmentDialogOpen(false);
toast.success(t("appointment_cancelled"));
Copy link
Contributor

@coderabbitai coderabbitai bot Jan 14, 2025

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 in multiple locale files

The translation key "appointment_cancelled" is only present in en.json but appears to be missing in other locale files (ta.json, mr.json, ml.json, hi.json, kn.json). This could lead to missing translations when users switch languages.

  • Add the "appointment_cancelled" translation key to all locale files in public/locale/
🔗 Analysis chain

Verify toast message translation key

Verify that the translation key "appointment_cancelled" exists in the locale files.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the translation key exists
rg -F "\"appointment_cancelled\":" public/locale/

Length of output: 133


Script:

#!/bin/bash
# List all locale files
fd . public/locale/ -e json -x echo "=== {} ===" \; cat {} \; echo

Length of output: 450


Script:

#!/bin/bash
# Search for the translation key in all locale files with context
rg -F "appointment_cancelled" public/locale/ --json | jq -r '.data.lines.text' 2>/dev/null

Length of output: 154

Copy link
Member Author

Choose a reason for hiding this comment

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

Read README, we add only for en locale through PRs. Crowdin handles it.

Copy link
Contributor

Choose a reason for hiding this comment

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

@rithviknishad Thank you for the correction. I've checked the README and understand now - only English translations should be added through PRs, while other languages are managed through Crowdin.

🔗 Analysis chain

@rithviknishad I apologize for the confusion. I understand now that only English (en) locale files are managed through PRs, while Crowdin handles other locales.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check README for localization/translation information
fd README -e md -X cat {}

Length of output: 19459


✏️ Learnings added
Learnt from: rithviknishad
PR: ohcnetwork/care_fe#9956
File: src/pages/Patient/index.tsx:71-71
Timestamp: 2025-01-15T04:16:14.876Z
Learning: In this project, new translation strings must only be added to the English locale (en.json) through pull requests. Translations for other languages (ta.json, mr.json, ml.json, hi.json, kn.json, etc.) are managed through Crowdin (https://crowdin.com/project/ohccarefe) and should not be modified directly in PRs.

Learnt from: rithviknishad
PR: ohcnetwork/care_fe#9956
File: src/pages/Patient/index.tsx:71-71
Timestamp: 2025-01-15T04:16:14.876Z
Learning: In this project, translations are only added to the English locale (en.json) through pull requests. Other locale files are managed through Crowdin and should not be modified directly in PRs.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Comment on lines 125 to 130
export const ApppointmentCompletedStatuses: AppointmentStatus[] = [
"fulfilled",
"cancelled",
"entered_in_error",
"rescheduled",
];
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

Fix typo and consider renaming constant

  1. Fix the typo in the constant name (3 p's)
  2. Consider a more appropriate name like AppointmentFinalStatuses since these are terminal states
- export const ApppointmentCompletedStatuses: AppointmentStatus[] = [
+ export const AppointmentFinalStatuses: AppointmentStatus[] = [
📝 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 const ApppointmentCompletedStatuses: AppointmentStatus[] = [
"fulfilled",
"cancelled",
"entered_in_error",
"rescheduled",
];
export const AppointmentFinalStatuses: AppointmentStatus[] = [
"fulfilled",
"cancelled",
"entered_in_error",
"rescheduled",
];

src/pages/Appointments/AppointmentDetail.tsx Show resolved Hide resolved
@github-actions github-actions bot added the Deploy-Failed Deplyment is not showing preview label Jan 14, 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 (2)
src/pages/Appointments/components/AppointmentSlotPicker.tsx (2)

85-88: ⚠️ Potential issue

Division by zero risk in booking percentage calculation.

The bookedPercentage calculation could result in division by zero.

-const bookedPercentage = booked_slots / total_slots;
+const bookedPercentage = total_slots > 0 ? booked_slots / total_slots : 1;

181-182: ⚠️ Potential issue

Division by zero risk in slot percentage calculation.

The percentage calculation could result in division by zero.

-const percentage = slot.allocated / availability.tokens_per_slot;
+const percentage = availability.tokens_per_slot > 0 
+  ? slot.allocated / availability.tokens_per_slot 
+  : 1;
🧹 Nitpick comments (5)
src/pages/Appointments/components/AppointmentSlotPicker.tsx (5)

34-35: Consider initializing dates to the first available slot.

Currently, both dates are initialized to the current date, which might not be an available appointment date. Consider fetching and initializing to the first available date instead.

-const [selectedMonth, setSelectedMonth] = useState(new Date());
-const [selectedDate, setSelectedDate] = useState(new Date());
+const [selectedMonth, setSelectedMonth] = useState<Date>(() => {
+  const today = new Date();
+  return today;
+});
+const [selectedDate, setSelectedDate] = useState<Date | null>(null);

43-53: Add error handling for failed slot fetching.

The query implementation looks good, but there's no handling of error states. Consider adding error feedback for users.

 const slotsQuery = useQuery({
   queryKey: ["slots", facilityId, resourceId, dateQueryString(selectedDate)],
   queryFn: query(scheduleApis.slots.getSlotsForDay, {
     pathParams: { facility_id: facilityId },
     body: {
       user: resourceId ?? "",
       day: dateQueryString(selectedDate),
     },
   }),
   enabled: !!resourceId && !!selectedDate,
+  retry: 2,
+  onError: (error) => {
+    console.error('Failed to fetch slots:', error);
+    // Add user feedback mechanism here
+  }
 });

67-82: Remove onClick handler from disabled button.

The disabled button shouldn't have an onClick handler as it will never be called.

 <button
   disabled
-  onClick={() => {
-    setSelectedDate(date);
-    onSlotSelect(undefined);
-  }}
   className={cn(

188-227: Improve accessibility and code readability of slot buttons.

The slot button needs accessibility improvements and the nested ternary operators could be simplified.

 <Button
   key={slot.id}
   size="lg"
   variant={selectedSlotId === slot.id ? "outline_primary" : "outline"}
+  aria-label={`Select appointment slot at ${format(slot.start_datetime, "HH:mm")}, ${availability.tokens_per_slot - slot.allocated} slots remaining`}
   onClick={() => {
     onSlotSelect(selectedSlotId === slot.id ? undefined : slot.id);
   }}
   disabled={slot.allocated === availability.tokens_per_slot || isPastSlot}
   className="flex flex-col items-center group gap-0"
 >
   <span className="font-semibold">
     {format(slot.start_datetime, "HH:mm")}
   </span>
   <span
     className={cn(
       "text-xs group-hover:text-inherit",
-      percentage >= 1
-        ? "text-gray-400"
-        : percentage >= 0.8
-          ? "text-red-600"
-          : percentage >= 0.6
-            ? "text-yellow-600"
-            : "text-green-600",
+      getColorClassForPercentage(percentage)
     )}
   >
     {availability.tokens_per_slot - slot.allocated} left
   </span>
 </Button>

Consider extracting the color logic to a separate function:

function getColorClassForPercentage(percentage: number): string {
  if (percentage >= 1) return "text-gray-400";
  if (percentage >= 0.8) return "text-red-600";
  if (percentage >= 0.6) return "text-yellow-600";
  return "text-green-600";
}

27-32: Add JSDoc documentation for the component.

Since this is a new component for appointment rescheduling, consider adding JSDoc documentation to explain its purpose and usage.

+/**
+ * A component that allows users to select appointment slots for scheduling or rescheduling.
+ * Displays a calendar view with availability indicators and a list of available time slots.
+ *
+ * @param facilityId - The ID of the facility where the appointment will take place
+ * @param resourceId - Optional. The ID of the resource (e.g., doctor) for the appointment
+ * @param onSlotSelect - Callback function called when a slot is selected or deselected
+ * @param selectedSlotId - Optional. The currently selected slot ID
+ */
 export function AppointmentSlotPicker({
   facilityId,
   resourceId,
   onSlotSelect,
   selectedSlotId,
 }: AppointmentSlotPickerProps) {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 699fefe and 3332a70.

📒 Files selected for processing (1)
  • src/pages/Appointments/components/AppointmentSlotPicker.tsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: cypress-run (1)
  • GitHub Check: Cloudflare Pages: care-fe
🔇 Additional comments (1)
src/pages/Appointments/components/AppointmentSlotPicker.tsx (1)

20-25: Well-structured interface definition!

The props interface is well-defined with proper types and optional parameters.

@rithviknishad rithviknishad removed the Deploy-Failed Deplyment is not showing preview label Jan 14, 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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3332a70 and 943781a.

📒 Files selected for processing (3)
  • src/pages/Appointments/AppointmentDetail.tsx (7 hunks)
  • src/pages/Patient/index.tsx (4 hunks)
  • src/types/scheduling/schedule.ts (3 hunks)
🧰 Additional context used
📓 Learnings (2)
src/pages/Patient/index.tsx (2)
Learnt from: rithviknishad
PR: ohcnetwork/care_fe#9956
File: src/pages/Patient/index.tsx:71-71
Timestamp: 2025-01-15T04:16:14.978Z
Learning: In this project, new translation strings must only be added to the English locale (en.json) through pull requests. Translations for other languages (ta.json, mr.json, ml.json, hi.json, kn.json, etc.) are managed through Crowdin (https://crowdin.com/project/ohccarefe) and should not be modified directly in PRs.
Learnt from: rithviknishad
PR: ohcnetwork/care_fe#9956
File: src/pages/Patient/index.tsx:71-71
Timestamp: 2025-01-15T04:16:14.978Z
Learning: In this project, translations are only added to the English locale (en.json) through pull requests. Other locale files are managed through Crowdin and should not be modified directly in PRs.
src/pages/Appointments/AppointmentDetail.tsx (1)
Learnt from: rithviknishad
PR: ohcnetwork/care_fe#9956
File: src/pages/Appointments/AppointmentDetail.tsx:424-443
Timestamp: 2025-01-15T04:14:29.514Z
Learning: The codebase implements a global error handler that manages toast notifications and other necessary actions based on HttpError. Explicit error handling in mutations is not required as errors are handled globally.
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: cypress-run (1)
  • GitHub Check: CodeQL-Build
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (8)
src/types/scheduling/schedule.ts (2)

5-5: LGTM!

The import follows the project's conventions and is used in the Appointment interface.


117-117: Reevaluate inclusion of "rescheduled" in AppointmentCancelledStatuses

Including "rescheduled" in AppointmentCancelledStatuses may not accurately represent its state. Typically, a rescheduled appointment is active rather than canceled. Consider whether "rescheduled" should be part of AppointmentNonCancelledStatuses or handled separately to reflect its true status.

src/pages/Patient/index.tsx (3)

6-6: LGTM!

The toast notification is correctly implemented to provide user feedback after canceling an appointment.

Also applies to: 71-71


69-70: LGTM!

The dialog state management is correctly implemented to close the dialog after successful cancellation.


154-172: Add click handler for reschedule button

The reschedule button is missing an onClick handler, making it non-functional.

src/pages/Appointments/AppointmentDetail.tsx (3)

403-404: LGTM!

The state management for the reschedule dialog and slot selection is well-implemented.


424-443: LGTM!

The reschedule mutation is well-implemented with proper success handling. The global error handler will manage any errors.


477-521: LGTM!

The reschedule UI is well-implemented with proper state management, slot picker integration, and button states.

Comment on lines +125 to +130
export const AppointmentFinalStatuses: AppointmentStatus[] = [
"fulfilled",
"cancelled",
"entered_in_error",
"rescheduled",
];
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

Remove "rescheduled" from AppointmentFinalStatuses

A rescheduled appointment is not a terminal state but rather a transition state that leads to a new appointment. Including it in AppointmentFinalStatuses could prevent users from performing valid actions on rescheduled appointments.

Apply this diff to fix the issue:

 export const AppointmentFinalStatuses: AppointmentStatus[] = [
   "fulfilled",
   "cancelled",
   "entered_in_error",
-  "rescheduled",
 ];
📝 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 const AppointmentFinalStatuses: AppointmentStatus[] = [
"fulfilled",
"cancelled",
"entered_in_error",
"rescheduled",
];
export const AppointmentFinalStatuses: AppointmentStatus[] = [
"fulfilled",
"cancelled",
"entered_in_error",
];

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