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

diet preference options with kebab case value #9821

Closed

Conversation

arhamathar
Copy link
Contributor

@arhamathar arhamathar commented Jan 7, 2025

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

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

Summary by CodeRabbit

Based on the comprehensive summary of changes, here are the high-level release notes:

  • New Features

    • Added questionnaire editing functionality
    • Enhanced patient context management
    • Improved internationalization support
    • Added new patient navigation components
  • Improvements

    • Streamlined authentication and token management
    • Updated routing for patient and facility navigation
    • Refined allergy and encounter tracking
    • Improved form handling and validation
  • Bug Fixes

    • Updated error handling in various components
    • Fixed data fetching and context management issues
  • Localization

    • Added new translation keys
    • Implemented internationalization across components
  • Performance

    • Optimized context and state management
    • Simplified component logic and data retrieval

@arhamathar arhamathar requested a review from a team as a code owner January 7, 2025 10:23
Copy link
Contributor

coderabbitai bot commented Jan 7, 2025

Walkthrough

This pull request introduces several significant changes across multiple components and files, focusing on improving patient data management, questionnaire handling, and authentication processes. The primary modifications include updating diet preference handling, refactoring context management for patient and authentication tokens, enhancing localization support, and streamlining component structures. The changes aim to improve code maintainability, user experience, and data consistency across the application.

Changes

File/Group Change Summary
src/components/Questionnaire/QuestionTypes/EncounterQuestion.tsx Replaced hardcoded diet preference options with dynamically generated SelectItem components using DIET_PREFERENCE_OPTIONS
src/common/constants.tsx Added DIET_PREFERENCE_OPTIONS array with diet preference configurations
Authentication & Context Files Replaced local storage token management with context-based authentication in multiple components
Routing Files Updated routing configurations, removed some routes, added new navigation components
Localization Files Added new translation keys for error messages and UI elements
Patient & Encounter Components Enhanced patient data handling, added patientId to various components

Assessment against linked issues

Objective Addressed Explanation
Update encounters with diet preferences Added DIET_PREFERENCE_OPTIONS to handle diet preference selection
Resolve diet preference update errors Centralized diet preference options for consistent handling

Possibly related issues

  • cleanup CarePatientTokenKey #9828: Cleanup of CarePatientTokenKey - This PR partially addresses this by replacing local storage token management with context-based approaches

Possibly related PRs

Suggested labels

needs review, tested

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

🥕 A Rabbit's Refactoring Tale 🐰

In lines of code, a transformation springs,
Context replaces tokens, how my heart sings!
Diet preferences dance with newfound grace,
Localization blooms in every space.
CodeRabbit's magic, clean and bright! 🌟


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

Deploy Preview for care-ohc ready!

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

Comment on lines 395 to 397
<SelectItem value="diary-free">Dairy Free</SelectItem>
<SelectItem value="nut-free">Nut Free</SelectItem>
<SelectItem value="gluten-free">Gluten Free</SelectItem>
Copy link
Member

Choose a reason for hiding this comment

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

All of these should be moved to constans

Copy link
Member

Choose a reason for hiding this comment

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

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@rithviknishad Shall I create a new PR as you have closed the issues as Not Planned

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

🔭 Outside diff range comments (2)
src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx (1)

Line range hint 27-32: Remove unused question prop from interface

The question prop has been removed from the component's parameters but is still defined in the interface. This creates an inconsistency between the interface and implementation.

Apply this diff to fix the interface:

 interface MedicationStatementQuestionProps {
-  question: Question;
   questionnaireResponse: QuestionnaireResponse;
   updateQuestionnaireResponseCB: (response: QuestionnaireResponse) => void;
   disabled?: boolean;
 }
src/components/Questionnaire/structured/types.ts (1)

Line range hint 1-1: ❌ PR Changes Don't Match Stated Objective

The PR's objective is to update diet preference values from snake case to kebab case (issue #9817). However, the reviewed files contain unrelated changes:

  1. Authentication token management refactoring
  2. Questionnaire UI improvements
  3. Allergy intolerance data structure updates

Please either:

  1. Update the PR description to accurately reflect all changes
  2. Split the unrelated changes into separate PRs
  3. Include the missing diet preference formatting changes
🧹 Nitpick comments (21)
src/pages/Facility/components/UserCard.tsx (2)

34-37: Simplify token validation logic and extract magic number

The token validation logic can be simplified and made more maintainable.

Consider this improvement:

+ const TOKEN_EXPIRY_MINUTES = 14;
  if (
-   tokenData &&
-   Object.keys(tokenData).length > 0 &&
+   tokenData?.createdAt &&
-   dayjs(tokenData.createdAt).isAfter(dayjs().subtract(14, "minutes"))
+   dayjs(tokenData.createdAt).isAfter(dayjs().subtract(TOKEN_EXPIRY_MINUTES, "minutes"))
  )

Line range hint 74-78: Consider moving user data to context

While the component moved away from localStorage for authentication, it's still using localStorage for user data. Consider maintaining consistency by moving this to context as well.

Consider creating a user context or extending the existing context to handle this data:

const { setSelectedUser } = useUserContext();  // New context
// Then in onClick:
setSelectedUser(user);
navigate(returnLink);
src/types/questionnaire/questionnaire.ts (1)

20-22: Add documentation and consider type refinement.

While the interface extension is clean, consider these improvements:

  1. Add JSDoc documentation to explain the purpose of the QuestionnaireUpdate interface
  2. Consider using a more specific type for organization IDs if they follow a particular format

Example documentation:

+/**
+ * Represents an updated questionnaire with associated organizations
+ * @extends {QuestionnaireDetail}
+ */
 export interface QuestionnaireUpdate extends QuestionnaireDetail {
   organizations: string[];
 }
src/components/Auth/Login.tsx (1)

153-153: Consider abstracting the redirect URL into a configuration or constant.

The redirect path '/patient/home' is hard-coded. For better maintainability and to avoid magic strings, consider defining it as a constant or retrieving it from a configuration file.

Apply this diff to abstract the redirect URL:

 const tokenData: TokenData = {
   token: access,
   phoneNumber: `+91${phone}`,
   createdAt: new Date().toISOString(),
 };
-patientLogin(tokenData, `/patient/home`);
+const PATIENT_HOME_URL = '/patient/home';
+patientLogin(tokenData, PATIENT_HOME_URL);

And define PATIENT_HOME_URL at the top or in a configuration file.

src/components/Questionnaire/QuestionnaireEditor.tsx (1)

487-487: Specify correct type for dragHandleProps

Using any reduces type safety. Specify a more precise type for dragHandleProps.

Apply this diff to specify the correct type:

+import { DraggableProvidedDragHandleProps } from "@hello-pangea/dnd";

 interface QuestionEditorProps {
   // ...
-  dragHandleProps?: any;
+  dragHandleProps?: DraggableProvidedDragHandleProps;
   // ...
 }
src/components/ui/sidebar/org-nav.tsx (2)

5-9: LGTM! Consider adding icon type constraint.

The NavigationLink interface is well-defined, but consider constraining the icon type to specific icon names for better type safety.

 interface NavigationLink {
   name: string;
   url: string;
-  icon?: string;
+  icon?: 'home' | 'user' | 'settings' | string; // Add commonly used icons
 }

15-22: LGTM! Consider adding URL validation.

The generateOrganizationLinks function is clean and focused. Consider adding URL validation for the organization IDs.

 function generateOrganizationLinks(
   organizations: Organization[],
 ): NavigationLink[] {
   return organizations.map((org) => ({
     name: org.name,
-    url: `/organization/${org.id}`,
+    url: `/organization/${encodeURIComponent(org.id)}`,
   }));
 }
src/types/emr/allergyIntolerance/allergyIntolerance.ts (1)

20-22: Improve comment clarity.

The comment "Added optional id here as this type is used only in one place" could be more descriptive:

  1. Specify where this type is used
  2. Explain why id is optional here but required in the base interface
-// Added optional id here as this type is used only in one place
+// Optional id in request type as it's only used in AllergyQuestion component
+// where new allergies don't have an id until saved
src/components/Questionnaire/QuestionLabel.tsx (2)

11-12: Consider moving style constants to a shared styles file

The style constants could be moved to a shared styles file to maintain consistency across components.


21-33: Enhance accessibility of the visual indicator

The visual indicator div should have an ARIA label for screen readers.

-        {groupLabel && <div className="h-1 w-4 rounded-full bg-indigo-600" />}
+        {groupLabel && (
+          <div 
+            className="h-1 w-4 rounded-full bg-indigo-600" 
+            role="presentation" 
+            aria-hidden="true" 
+          />
+        )}
src/components/ui/sidebar/patient-nav.tsx (2)

11-15: Consider extending NavigationLink interface.

The interface could benefit from additional properties for better type safety and future extensibility.

 interface NavigationLink {
   name: string;
   url: string;
   icon?: string;
+  isExternal?: boolean;
+  disabled?: boolean;
 }

23-30: Consider extracting organization traversal logic.

The organization traversal logic could be moved to a separate utility function for better reusability and testing.

+function findParentOrganization(organization: any) {
+  let parent = organization?.parent;
+  while (parent?.parent) {
+    if (parent.level_cache === 1) {
+      return parent;
+    }
+    parent = parent.parent;
+  }
+  return parent;
+}
+
 function generatePatientLinks(
   selectedUser: AppointmentPatient | null,
   t: TFunction,
 ): NavigationLink[] {
   if (!selectedUser) return [];

   const { geo_organization } = selectedUser;
-  let parentOrganization = geo_organization?.parent;
-  while (parentOrganization?.parent) {
-    if (parentOrganization.level_cache === 1) {
-      break;
-    }
-    parentOrganization = parentOrganization.parent;
-  }
+  const parentOrganization = findParentOrganization(geo_organization);
src/Providers/PatientUserProvider.tsx (2)

19-21: Consider adding error boundary for token validation.

The token validation and navigation logic could benefit from an error boundary to handle edge cases more gracefully.

+class TokenErrorBoundary extends React.Component {
+  componentDidCatch(error: Error) {
+    navigate("/");
+  }
+}

 export default function PatientUserProvider({ children }: Props) {
   // ... existing code ...

   if (!tokenData) {
-    navigate("/");
-    return null;
+    throw new Error("Invalid token");
   }

   return (
+    <TokenErrorBoundary>
       <PatientUserContext.Provider value={{...}}>
         {children}
       </PatientUserContext.Provider>
+    </TokenErrorBoundary>
   );
 }

Also applies to: 32-32, 58-61


35-41: Consider adding retry logic for failed queries.

The query configuration could benefit from retry logic for better resilience.

 const { data: userData } = useQuery({
   queryKey: ["patients", tokenData],
   queryFn: query(routes.otp.getPatient, {
     headers: {
       Authorization: `Bearer ${tokenData?.token}`,
     },
   }),
   enabled: !!tokenData?.token,
+  retry: 3,
+  retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
 });
src/components/ui/sidebar/patient-switcher.tsx (1)

Line range hint 46-51: Consider moving localStorage logic to context

The direct usage of localStorage within the component could be moved to the context to centralize patient data management.

- if (patient) {
-   patientUserContext.setSelectedPatient(patient);
-   localStorage.setItem("selectedPatient", JSON.stringify(patient));
- }
+ if (patient) {
+   patientUserContext.setSelectedPatient(patient);
+ }
src/components/Questionnaire/structured/handlers.ts (1)

30-44: LGTM! Efficient batch processing implementation.

The consolidation of allergy requests into a single batch operation is a good optimization. The implementation follows the same pattern as other handlers and maintains type safety.

Consider adding a batch size limit to prevent potential issues with very large arrays:

 getRequests: (allergies, { patientId, encounterId }) => {
+  const BATCH_SIZE = 100;
+  const batches = [];
+  for (let i = 0; i < allergies.length; i += BATCH_SIZE) {
+    const batch = allergies.slice(i, i + BATCH_SIZE);
+    batches.push({
+      url: `/api/v1/patient/${patientId}/allergy_intolerance/upsert/`,
+      method: "POST",
+      body: {
+        datapoints: batch.map((allergy) => ({
+          ...allergy,
+          encounter: encounterId,
+        })),
+      },
+      reference_id: `allergy_intolerance_batch_${i/BATCH_SIZE}`,
+    });
+  }
+  return batches;
 }
src/pages/Appoinments/PatientSelect.tsx (1)

Line range hint 33-37: Consider migrating remaining localStorage usage to context.

The component still uses localStorage for selectedSlot and reason. Consider moving these to the patient context as well for consistency.

-  const selectedSlot = JSON.parse(
-    localStorage.getItem("selectedSlot") ?? "",
-  ) as SlotAvailability;
-  const reason = localStorage.getItem("reason");
+  const { selectedSlot, reason } = patientUserContext?.appointmentData ?? {};
src/components/Facility/ConsultationDetails/QuestionnaireResponsesList.tsx (1)

211-244: Improve null checks in questionnaire response rendering.

The questionnaire response rendering logic has good null checks, but consider adding error boundaries to handle potential runtime errors gracefully.

Consider wrapping the questionnaire response section with an error boundary:

import { ErrorBoundary } from '@/components/Common/ErrorBoundary';

// Inside the render logic
<ErrorBoundary fallback={<div>Error loading questionnaire response</div>}>
  {item.questionnaire && (
    <div className="mt-3 border-t pt-3">
      // ... existing code
    </div>
  )}
</ErrorBoundary>
src/pages/Appoinments/auth/PatientLogin.tsx (1)

Line range hint 92-102: Enhance error handling in OTP mutation.

While the loading state handling is good, consider adding retry logic for network failures.

Add retry configuration to the mutation:

const { mutate: sendOTP, isPending: isSendOTPLoading } = useMutation({
  mutationFn: (phoneNumber: string) => // ... existing code,
  retry: 3,
  retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
  // ... rest of the config
});
src/components/Patient/PatientRegistration.tsx (2)

317-332: Improved form field implementation with proper accessibility.

The form fields are well-structured with:

  • Proper label associations
  • Required field indicators
  • Clear error messaging

However, the error handling could be optimized.

Consider using optional chaining for cleaner error handling:

-              {errors["name"] &&
-                errors["name"].map((error, i) => (
+              {errors["name"]?.map((error, i) => (
                   <div key={i} className="text-red-500 text-xs">
                     {error}
                   </div>
                 ))}

Also applies to: 334-358

🧰 Tools
🪛 Biome (1.9.4)

[error] 326-331: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


490-557: Comprehensive date input implementation.

The date input fields are well-implemented with:

  • Proper validation constraints
  • Clear labeling
  • Proper error handling

However, consider adding aria-labels for better screen reader support.

 <Input
   placeholder="DD"
   type="number"
+  aria-label={t("day")}
   value={form.date_of_birth?.split("-")[2] || ""}
   // ... other props
 />
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8deec25 and fc303d0.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (54)
  • crowdin.yml (1 hunks)
  • cypress/e2e/patient_spec/patient_search.cy.ts (1 hunks)
  • public/locale/en.json (6 hunks)
  • src/Providers/AuthUserProvider.tsx (5 hunks)
  • src/Providers/PatientUserProvider.tsx (3 hunks)
  • src/Routers/PatientRouter.tsx (2 hunks)
  • src/Routers/PublicRouter.tsx (0 hunks)
  • src/Routers/routes/ConsultationRoutes.tsx (1 hunks)
  • src/Routers/routes/questionnaireRoutes.tsx (1 hunks)
  • src/common/constants.tsx (1 hunks)
  • src/components/Auth/Login.tsx (1 hunks)
  • src/components/Facility/ConsultationDetails/QuestionnaireResponsesList.tsx (1 hunks)
  • src/components/Facility/ConsultationDetails/StructuredResponseView.tsx (0 hunks)
  • src/components/Patient/PatientInfoCard.tsx (5 hunks)
  • src/components/Patient/PatientRegistration.tsx (6 hunks)
  • src/components/Patient/allergy/list.tsx (3 hunks)
  • src/components/Questionnaire/QuestionLabel.tsx (1 hunks)
  • src/components/Questionnaire/QuestionRenderer.tsx (3 hunks)
  • src/components/Questionnaire/QuestionTypes/AllergyQuestion.tsx (11 hunks)
  • src/components/Questionnaire/QuestionTypes/EncounterQuestion.tsx (2 hunks)
  • src/components/Questionnaire/QuestionTypes/FollowUpAppointmentQuestion.tsx (1 hunks)
  • src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx (2 hunks)
  • src/components/Questionnaire/QuestionTypes/QuestionGroup.tsx (6 hunks)
  • src/components/Questionnaire/QuestionTypes/QuestionInput.tsx (3 hunks)
  • src/components/Questionnaire/QuestionnaireEditor.tsx (1 hunks)
  • src/components/Questionnaire/QuestionnaireForm.tsx (1 hunks)
  • src/components/Questionnaire/structured/handlers.ts (1 hunks)
  • src/components/Questionnaire/structured/types.ts (3 hunks)
  • src/components/ui/errors.tsx (0 hunks)
  • src/components/ui/input-with-error.tsx (0 hunks)
  • src/components/ui/sidebar/app-sidebar.tsx (3 hunks)
  • src/components/ui/sidebar/facility-nav.tsx (1 hunks)
  • src/components/ui/sidebar/nav-user.tsx (2 hunks)
  • src/components/ui/sidebar/org-nav.tsx (1 hunks)
  • src/components/ui/sidebar/patient-nav.tsx (1 hunks)
  • src/components/ui/sidebar/patient-switcher.tsx (1 hunks)
  • src/hooks/useAuthOrPatientUser.ts (0 hunks)
  • src/hooks/useAuthUser.ts (1 hunks)
  • src/hooks/usePatientSignOut.ts (1 hunks)
  • src/hooks/usePatientUser.ts (1 hunks)
  • src/pages/Appoinments/PatientRegistration.tsx (2 hunks)
  • src/pages/Appoinments/PatientSelect.tsx (2 hunks)
  • src/pages/Appoinments/Schedule.tsx (2 hunks)
  • src/pages/Appoinments/Success.tsx (3 hunks)
  • src/pages/Appoinments/auth/PatientLogin.tsx (9 hunks)
  • src/pages/Encounters/tabs/EncounterUpdatesTab.tsx (2 hunks)
  • src/pages/Facility/components/UserCard.tsx (5 hunks)
  • src/pages/FacilityOrganization/components/FacilityOrganizationSelector.tsx (4 hunks)
  • src/pages/Organization/components/OrganizationSelector.tsx (2 hunks)
  • src/pages/Patient/index.tsx (1 hunks)
  • src/types/emr/allergyIntolerance/allergyIntolerance.ts (2 hunks)
  • src/types/questionnaire/form.ts (2 hunks)
  • src/types/questionnaire/questionnaire.ts (1 hunks)
  • src/types/questionnaire/questionnaireApi.ts (2 hunks)
💤 Files with no reviewable changes (5)
  • src/components/ui/input-with-error.tsx
  • src/hooks/useAuthOrPatientUser.ts
  • src/Routers/PublicRouter.tsx
  • src/components/ui/errors.tsx
  • src/components/Facility/ConsultationDetails/StructuredResponseView.tsx
✅ Files skipped from review due to trivial changes (1)
  • src/components/Questionnaire/QuestionTypes/FollowUpAppointmentQuestion.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Questionnaire/QuestionTypes/EncounterQuestion.tsx
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/Patient/PatientRegistration.tsx

[error] 326-331: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 352-357: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 397-402: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 437-442: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 464-469: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 585-590: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 620-625: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 672-677: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 709-714: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (54)
src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx (2)

Line range hint 112-139: LGTM! Clean fragment usage

The return statement has been properly restructured to use React fragments (<>...</>) instead of unnecessary div containers, which helps reduce DOM nesting. The conditional rendering of medications and the ValueSetSelect component is well-organized.


Line range hint 112-139: Verify accessibility after question label removal

With the removal of the question prop and its associated label, please ensure that:

  1. The form field remains accessible to screen readers
  2. Users can still understand the purpose of this input field
  3. The parent component properly associates this field with its question text

Consider using ARIA labels or other accessibility attributes if the question text is rendered elsewhere.

Run this script to check for accessibility attributes in parent components:

src/pages/Facility/components/UserCard.tsx (2)

2-2: LGTM! Clean import changes

The imports have been appropriately updated to support the shift from local storage to context-based authentication management.

Also applies to: 14-14


30-30: LGTM! Improved state management

Good improvement replacing localStorage access with the context hook. This centralizes authentication state management and follows React best practices.

src/components/ui/sidebar/app-sidebar.tsx (2)

15-35: Good use of modular components and state management.

The introduction of the FacilityNav, OrgNav, and PatientNav components, along with the SidebarFor enum, enhances the modularity and readability of the code. This approach makes the sidebar easier to maintain and extend.


120-130: Conditional rendering logic is clear and effective.

The updated rendering logic for the sidebar content and footer components based on sidebarFor and selectedOrganization is well-organized. It ensures that the correct navigation components are displayed depending on the context.

src/components/Questionnaire/QuestionTypes/AllergyQuestion.tsx (3)

Line range hint 523-531: Ensure proper date format in the allergy table row.

Similar to the previous comment, verify that the allergy.last_occurrence value is in the correct format for the date input in the AllergyTableRow component to avoid potential issues.

Consider applying the date formatting here as well.


17-18: Avoid importing default exports directly from libraries.

It's recommended to import only the necessary functions or components to keep the bundle size optimized. However, in this case, the imports are correctly specifying the required functions from their respective libraries.


377-387: Verify date format compatibility in the Input component.

When using the <Input type="date" /> component, make sure that allergy.last_occurrence is in a format compatible with the HTML date input (YYYY-MM-DD). If the date is stored in a different format (e.g., ISO string with time), consider formatting it accordingly to prevent issues with date selection and display.

You can format the date using a utility function before setting it as the value:

import { format } from 'date-fns';

<Input
  type="date"
  value={allergy.last_occurrence ? format(new Date(allergy.last_occurrence), 'yyyy-MM-dd') : ''}
  onChange={(e) =>
    handleUpdateAllergy(index, {
      last_occurrence: e.target.value,
    })
  }
  disabled={disabled}
  className="h-8 mt-1"
/>
src/components/Auth/Login.tsx (2)

153-153: Confirm that patientLogin correctly manages authentication state.

The replacement of the local storage operation with the patientLogin function enhances the authentication flow. Ensure that patientLogin properly handles token storage and updates the authentication context so that the patient session is maintained throughout the application.


153-153: LGTM!

The updates to the login flow improve security by centralizing token management within the authentication context.

src/components/Questionnaire/QuestionnaireEditor.tsx (1)

1126-1126: Ensure browser compatibility for crypto.randomUUID()

This is a duplicate of a previous comment regarding crypto.randomUUID() usage.

src/hooks/usePatientUser.ts (1)

1-13: Implementation of usePatientContext hook is correct

The usePatientContext hook is properly implemented, ensuring context is used within the provider.

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

2-2: New route for QuestionnaireEditor added correctly

The import and addition of the edit route for questionnaires are correctly implemented.

Also applies to: 10-10

src/hooks/usePatientSignOut.ts (1)

4-4: LGTM! Consider splitting unrelated changes.

The change to use LocalStorageKeys constant improves maintainability. However, this change appears unrelated to the PR's objective of updating diet preference values from snake case to kebab case.

Consider moving this change to a separate PR focused on storage key refactoring.

Also applies to: 12-12

src/types/emr/allergyIntolerance/allergyIntolerance.ts (1)

6-6: LGTM! Breaking change detected.

Making previously optional fields required is a breaking change that might affect existing code. Ensure all consumers of this interface are updated accordingly.

Run this script to find potential impacts:

Also applies to: 8-11

src/hooks/useAuthUser.ts (1)

7-7: Verify token management refactoring impact

The shift from local storage to context-based token management is a good architectural improvement. However, this change might have broader implications across the application.

Also applies to: 15-16

✅ Verification successful

Token management refactoring is properly implemented

The changes represent a well-structured architectural improvement with:

  • Centralized token management in AuthUserProvider
  • Consistent type usage across components
  • Clean separation between storage and context layers
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining local storage usage of patient tokens
rg -i "localStorage.*(patient.*token|token.*patient)"

# Search for direct patientToken usage
rg "patientToken\." 

Length of output: 817


Script:

#!/bin/bash
# Check TokenData type usage
ast-grep --pattern 'TokenData'

# Check AuthContext usage patterns
rg "useAuth|AuthContext" -A 2

# Check for any token-related type definitions
fd "token" --type f --exec rg -l "interface|type.*Token"

Length of output: 12938

src/types/questionnaire/form.ts (1)

3-3: Verify the impact of AllergyIntoleranceRequest changes

The switch to AllergyIntoleranceRequest might affect existing implementations. Let's verify all usage points.

Also applies to: 32-32

✅ Verification successful

Import change is correct and properly implemented

The switch to AllergyIntoleranceRequest in the form types is appropriate as it's specifically designed for request payloads, omitting server-side fields like created_by and making id optional. The change maintains type safety and follows the established pattern of separating request/response types.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for AllergyIntolerance usage that might need updating
rg "AllergyIntolerance[^R]"

# Search for places where the response value is consumed
rg "ResponseValue.*allergy_intolerance"

Length of output: 1128


Script:

#!/bin/bash
# Check the type definitions and usage
ast-grep --pattern 'interface AllergyIntoleranceRequest'

# Look for direct usage of AllergyIntoleranceRequest
rg "AllergyIntoleranceRequest"

# Check the file content to understand the context
cat src/types/emr/allergyIntolerance/allergyIntolerance.ts

Length of output: 2489

src/pages/Encounters/tabs/EncounterUpdatesTab.tsx (1)

19-22: Verify AllergyList integration with parent components.

The component integration looks correct, but let's ensure it's properly typed and the props are being used correctly.

✅ Verification successful

AllergyList component integration is properly implemented

The component is correctly typed, exported, and integrated. Props are properly passed and match the interface definition. The same component is successfully reused across multiple parts of the application.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check AllergyList component implementation
ast-grep --pattern 'interface AllergyListProps {
  $$$
}'

# Check for any existing tests
fd -e test.tsx -e spec.tsx allergy

Length of output: 344


Script:

#!/bin/bash
# Check import statement and component export
ast-grep --pattern 'import { AllergyList } from $path'

# Verify export of AllergyList
ast-grep --pattern 'export $_ AllergyList'

Length of output: 101


Script:

#!/bin/bash
# Check for any import statements related to AllergyList
rg "import.*AllergyList" -A 1

# Look for the component definition
ast-grep --pattern 'const AllergyList = $_'

# Try finding default export
ast-grep --pattern 'export default $_AllergyList'

# Find the actual component implementation
rg "function AllergyList" -A 2

Length of output: 880

src/components/Questionnaire/QuestionRenderer.tsx (1)

19-19: LGTM! Clean implementation of patientId propagation

The addition of the patientId prop and its propagation through the component hierarchy is well-implemented, maintaining type safety and following React's props drilling pattern.

Also applies to: 32-32, 75-75

src/components/ui/sidebar/patient-switcher.tsx (1)

13-14: LGTM! Clean refactor to use React Context

The migration from prop drilling to React Context using the usePatientContext hook is well-implemented, with proper null checks to prevent rendering when the context is unavailable.

Also applies to: 23-31

src/components/Questionnaire/QuestionTypes/QuestionGroup.tsx (2)

23-23: LGTM! Consistent patientId propagation

The addition and propagation of the patientId prop through the component hierarchy is well-implemented and consistent with the overall changes.

Also applies to: 87-87, 106-106, 151-151


117-119: Verify the removal of border and padding styles

The removal of border p-4 classes might affect the visual presentation of the component. Please confirm if this is intentional and aligns with the design requirements.

✅ Verification successful

Style removal is intentional and follows the component's design pattern

The removal of border p-4 from the base styles is correct as these styles can be applied through styling_metadata.classes when needed. This approach:

  • Maintains the essential structure with space-y-4 and rounded-lg
  • Allows for flexible styling through the metadata system
  • Follows the component's pattern of customization
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any design-related comments or documentation
rg -i "group.*styling|border.*padding" --type md

Length of output: 50


Script:

#!/bin/bash
# Search for styling patterns in question components
rg -l "QuestionGroup" --type tsx | xargs rg "border|p-[0-9]|padding|space-y"

# Look for styling_metadata usage
ast-grep --pattern 'styling_metadata?.classes'

# Check for any global styling or theme configurations
fd "tailwind|theme|style" --extension tsx --extension ts --extension css

Length of output: 107768


Script:

#!/bin/bash
# Search for QuestionGroup component references
rg -A 5 -B 5 "QuestionGroup" --type tsx

# Look for styling patterns in question components
ast-grep --pattern 'className="space-y-4'

# Find styling_metadata usage in question components
ast-grep --pattern 'styling_metadata?.classes'

Length of output: 160


Script:

#!/bin/bash
# Search for QuestionGroup component and its usage
rg -l "QuestionGroup" | xargs rg -A 5 -B 5 "QuestionGroup"

# Look for styling patterns in the components directory
rg "className=.*space-y-4|className=.*border.*p-4" src/components/

# Search for styling_metadata usage
rg "styling_metadata" src/components/

Length of output: 17386

src/components/Patient/allergy/list.tsx (2)

24-24: LGTM! Well-structured changes to support encounter-specific allergy lists.

The addition of the optional encounterId prop and its integration with the query parameters is clean and type-safe.

Also applies to: 27-27, 29-29, 32-32


89-89: Verify translation key availability.

The static strings have been correctly replaced with translation keys. However, ensure these keys exist in the i18n files.

Also applies to: 95-99

✅ Verification successful

Translation keys verified and available

All required translation keys (allergies, allergen, category, status, criticality, created_by) are present in the translation files for all supported languages (en, hi, kn, ml, mr, ta).

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the translation keys exist in i18n files
rg -l "\"allergies\":|\"allergen\":|\"category\":|\"status\":|\"criticality\":|\"created_by\":" public/locales/

Length of output: 157


Script:

#!/bin/bash
# First, find potential translation files
echo "=== Finding translation files ==="
fd -e json -e yaml -e yml . | grep -i "locale\|translation\|i18n\|lang"

# Then find any file containing these translation keys
echo -e "\n=== Searching for translation keys ==="
rg -l "\"allergies\":|\"allergen\":|\"category\":|\"status\":|\"criticality\":|\"created_by\":" .

Length of output: 607


Script:

#!/bin/bash
# Check content of English translation file
echo "=== English translations ==="
cat public/locale/en.json | grep -A 1 "\"allergies\"\|\"allergen\"\|\"category\"\|\"status\"\|\"criticality\"\|\"created_by\""

Length of output: 556

src/Providers/AuthUserProvider.tsx (3)

32-35: LGTM! Improved type safety for token handling.

The state initialization properly handles the nullable TokenData type and safely parses the stored token.


129-129: LGTM! Safe token access implementation.

The optional chaining for token access and proper exposure through context is well implemented.

Also applies to: 143-143


78-85: Verify token persistence across page reloads.

The token handling logic looks correct, but we should verify that the token persists correctly across page reloads and browser sessions.

✅ Verification successful

Token persistence implementation is correct and comprehensive

The token handling implementation properly maintains persistence across page reloads and browser sessions through:

  • Initialization from localStorage on mount
  • Consistent storage in both state and localStorage
  • Proper cleanup during logout
  • Clear separation between patient and access tokens
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all places where patientTokenKey is accessed
rg "patientTokenKey" --type ts --type tsx

Length of output: 69


Script:

#!/bin/bash
# Search for LocalStorageKeys and patientTokenKey
rg "LocalStorageKeys|patientTokenKey" --type typescript --type tsx

# Search for localStorage operations
rg "localStorage\.(get|set)Item.*Token" --type typescript --type tsx

Length of output: 209


Script:

#!/bin/bash
# Search for LocalStorageKeys and token-related patterns
rg "LocalStorageKeys|patientTokenKey" --type ts

# Search for localStorage operations with tokens
rg "localStorage\.(get|set)Item" --type ts -A 2

# Search for potential token initialization
rg "useEffect.*localStorage" --type ts -A 3

Length of output: 11080

src/pages/Organization/components/OrganizationSelector.tsx (2)

114-117: LGTM! Improved accessibility with proper labels.

The Label component implementation with the required indicator improves accessibility and user experience.


140-158: Verify translation key format.

The translation key construction for organization types looks good, but verify the key format consistency.

✅ Verification successful

Translation key format is consistent with codebase patterns

The translation key format SYSTEM__govt_org_type__${type} follows the established pattern in the codebase, using double underscores as separators and proper fallback to "default".

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check the format of govt_org_type translation keys
rg "SYSTEM__govt_org_type__" --type ts --type tsx -A 1

Length of output: 82


Script:

#!/bin/bash
# Search for govt_org_type translation keys in all files
rg "SYSTEM__govt_org_type" -t ts -t typescript -t tsx

# Search for similar SYSTEM__ prefixed keys for comparison
rg "SYSTEM__" -t ts -t typescript -t tsx | grep -v "node_modules" | head -n 20

# Search for translation function calls
ast-grep --pattern 't($STR)' --lang typescript

Length of output: 949

src/components/Questionnaire/QuestionTypes/QuestionInput.tsx (2)

39-39: LGTM! Type definition is properly extended.

The addition of the patientId prop to QuestionInputProps interface is well-typed and maintains type safety.


51-51: LGTM! Props are correctly propagated.

The patientId prop is properly destructured from props and correctly passed down via commonProps.

Also applies to: 88-88

src/pages/FacilityOrganization/components/FacilityOrganizationSelector.tsx (2)

3-3: LGTM! I18n support properly implemented.

The useTranslation hook is correctly imported and initialized.

Also applies to: 35-35


111-115: LGTM! Label structure maintains accessibility.

The new label structure preserves accessibility with proper styling and required field indication.

src/components/ui/sidebar/nav-user.tsx (1)

119-126: LGTM! Context integration improves state management.

The component correctly uses the patient context hook and properly handles optional values with null checks.

src/pages/Appoinments/PatientSelect.tsx (1)

42-44: LGTM! Token management improved with context.

The change from localStorage to context-based token management improves type safety and centralization of auth state.

src/components/Facility/ConsultationDetails/QuestionnaireResponsesList.tsx (1)

188-204: Verify the impact of submit_type conditional rendering.

The conditional rendering logic for creator information looks correct, but it seems unrelated to the PR's objective of updating diet preference values from snake case to kebab case.

Please confirm if this change was intentional or if it should be in a separate PR focused on creator information display.

src/pages/Appoinments/auth/PatientLogin.tsx (2)

67-68: LGTM! Good migration to context-based auth management.

The switch from local storage to useAuthContext is a good architectural improvement.


146-147: LGTM! Clean implementation of patient login with navigation.

The login implementation with navigation looks clean and follows good practices.

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

24-24: LGTM! Clean up of import paths.

The update to import usePatientContext from a dedicated hook file improves code organization.

src/pages/Appoinments/Schedule.tsx (1)

46-47: LGTM! Good migration to context-based token management.

The switch from localStorage to usePatientContext for token management improves security and maintainability.

src/components/Questionnaire/QuestionnaireForm.tsx (1)

353-353: LGTM! Prop addition is well-integrated.

The patientId prop is correctly passed to the QuestionRenderer component, maintaining proper prop drilling for patient-specific data handling.

src/components/Patient/PatientInfoCard.tsx (3)

41-54: Well-structured constant definition.

The QUESTIONNAIRE_OPTIONS constant is well-defined with clear slugs and titles. The use of as const ensures type safety.


67-78: Proper mutation implementation with error handling.

The encounter update mutation is well-implemented with:

  • Proper error handling
  • Success notifications
  • Query cache invalidation

322-346: Enhanced UI with dropdown menu.

The dropdown menu implementation improves user experience by:

  • Grouping related actions
  • Providing clear visual hierarchy
  • Maintaining accessibility with proper ARIA attributes
src/pages/Appoinments/PatientRegistration.tsx (1)

83-84: Good migration to context-based state management.

Replacing local storage access with the usePatientContext hook improves:

  • State management consistency
  • Type safety
  • Testing capabilities
src/components/Patient/PatientRegistration.tsx (1)

360-377: Well-implemented checkbox with label association.

The checkbox implementation follows best practices:

  • Proper label association using htmlFor
  • Clear, descriptive text
  • Proper state management
crowdin.yml (1)

2-3: LGTM!

The changes to source and translation paths are correct and well-structured.

public/locale/en.json (1)

362-362: Verify diet preference translations

The new keys look good, but we need to ensure diet preference translations exist and match the new kebab case values.

Let's check for existing diet preference translations:

Also applies to: 654-654, 834-834, 905-905, 1635-1635

src/Routers/PatientRouter.tsx (4)

4-5: LGTM: Imported sidebar components correctly

The necessary sidebar components (SidebarProvider, SidebarTrigger, AppSidebar, SidebarFor) have been imported to enhance the application's sidebar functionality.


42-64: LGTM: New appointment routes added

The AppointmentRoutes object correctly defines routes for appointment-related pages. The parameters and component mappings are appropriately set, enhancing the application's routing capabilities.


80-110: LGTM: Integrated sidebar into patient router

The main content is now wrapped with SidebarProvider, and the AppSidebar component is correctly included. The layout adjustments and component hierarchy improvements enhance the user interface and maintain consistency.


Line range hint 22-28: Ensure all references to PatientRoutes are updated to DashboardRoutes

The PatientRoutes object has been renamed to DashboardRoutes. Please verify that all references to PatientRoutes in the codebase have been updated to prevent any unresolved references or runtime errors.

Run the following script to check for any remaining references to PatientRoutes:

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

72-75: ⚠️ Potential issue

Verify if facilityId is needed in QuestionnaireResponseView

The route includes :facilityId, but facilityId is not included in the destructured parameters or passed to the QuestionnaireResponseView component. Please verify if facilityId is required by the component to ensure correct functionality.

@@ -58,7 +57,7 @@ export function UserCard({ user, className, facilityId }: Props) {

{user.qualification && (
<>
<p className="text-xs mt-3">Education: </p>
<p className="text-xs mt-3">{t("education")}: </p>
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 translations in non-English locale files

The translation keys "education" and "book_appointment" are only defined in English (en.json) but missing in:

  • hi.json (Hindi)
  • kn.json (Kannada)
  • ml.json (Malayalam)
  • mr.json (Marathi)
  • ta.json (Tamil)
🔗 Analysis chain

Verify translation key existence

The internationalization of UI text is good, but let's ensure the translation keys exist.

Let's verify the translation keys are defined:

Also applies to: 79-79

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for "education" and "book_appointment" keys in translation files
rg -g '*.json' -g '*.yaml' -g '*.yml' '"education":|"book_appointment":' 

Length of output: 188


Script:

#!/bin/bash
# List all locale files
fd . 'public/locale' -e json -e yml -e yaml

Length of output: 175


Script:

#!/bin/bash
# Check for education and book_appointment keys in all locale files
for file in public/locale/*.json; do
  echo "=== $file ==="
  jq '.education, .book_appointment' "$file"
done

Length of output: 1058

Comment on lines +30 to 31
TRes: Type<QuestionnaireUpdate>(),
TBody: Type<QuestionnaireDetail>(),
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

Type mismatch confirmed between request and response types

The review comment is correct. QuestionnaireUpdate extends QuestionnaireDetail and adds the organizations: string[] field. This mismatch could lead to undefined data in the response or require backend compensation.

  • In src/types/questionnaire/questionnaireApi.ts: Update TBody to use QuestionnaireUpdate to ensure request body includes all fields required for the response.
🔗 Analysis chain

Potential type mismatch between request body and response.

The update method's request body type (TBody) is QuestionnaireDetail while the response type (TRes) is QuestionnaireUpdate. This might cause type inconsistencies as the request doesn't include the organizations field but the response does.

Consider updating TBody to match QuestionnaireUpdate if organizations should be included in the request:

    TRes: Type<QuestionnaireUpdate>(),
-   TBody: Type<QuestionnaireDetail>(),
+   TBody: Type<QuestionnaireUpdate>(),
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for QuestionnaireDetail and QuestionnaireUpdate type definitions
ast-grep --pattern 'type QuestionnaireDetail = $_'
ast-grep --pattern 'interface QuestionnaireDetail $_'
ast-grep --pattern 'type QuestionnaireUpdate = $_'
ast-grep --pattern 'interface QuestionnaireUpdate $_'

# Fallback search using ripgrep
echo "=== Ripgrep search ==="
rg "(?:type|interface)\s+(QuestionnaireDetail|QuestionnaireUpdate)" -A 10

Length of output: 1545

Comment on lines +20 to +22
export interface QuestionnaireUpdate extends QuestionnaireDetail {
organizations: string[];
}
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

Breaking change confirmed: organizations field addition requires updates

The addition of the required organizations field in QuestionnaireUpdate is a breaking change that needs attention:

  • The base QuestionnaireDetail interface doesn't include the organizations field
  • Current implementation in QuestionnaireEditor.tsx doesn't handle the organizations field
  • All questionnaire update operations will need modification to include this new required field

Recommendations:

  1. Consider making the field optional (organizations?: string[]) for backward compatibility
  2. Update the editor component to include organizations in the update payload
  3. Add a migration strategy for existing questionnaires
🔗 Analysis chain

Verify impact on existing questionnaire updates.

The addition of the required organizations field in QuestionnaireUpdate might break existing questionnaire update operations. Please ensure that:

  1. All update operations are modified to include the organizations field
  2. Migration strategy is in place for existing questionnaires

Run this script to find potentially affected update operations:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for questionnaire update operations that might need modification
rg -l 'questionnaireApi.*update' src/

Length of output: 92


Script:

#!/bin/bash
# Examine the questionnaire update implementation
rg -A 10 'questionnaireApi.*update' src/components/Questionnaire/QuestionnaireEditor.tsx

Length of output: 357


Script:

#!/bin/bash
# Examine QuestionnaireDetail interface and payload construction
echo "=== QuestionnaireDetail Interface ==="
rg -A 10 "interface QuestionnaireDetail" src/

echo -e "\n=== Payload Construction in Editor ==="
ast-grep --pattern 'const $_ = {
  $$$
  organizations: $_,
  $$$
}' src/components/Questionnaire/QuestionnaireEditor.tsx

Length of output: 1027

Comment on lines 29 to 31
facilitySidebar?: boolean;
patientUserContext?: PatientUserContextType;
sidebarFor?: SidebarFor;
}
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

Remove the unused facilitySidebar prop from AppSidebarProps.

The facilitySidebar prop in the AppSidebarProps interface appears to be obsolete since you're now using the sidebarFor prop to determine the sidebar context. Removing facilitySidebar can prevent confusion and potential inconsistencies.

Apply this diff to remove the unused prop:

 interface AppSidebarProps extends React.ComponentProps<typeof Sidebar> {
   user?: UserModel;
-  facilitySidebar?: boolean;
   sidebarFor?: SidebarFor;
 }
📝 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
facilitySidebar?: boolean;
patientUserContext?: PatientUserContextType;
sidebarFor?: SidebarFor;
}
interface AppSidebarProps extends React.ComponentProps<typeof Sidebar> {
user?: UserModel;
sidebarFor?: SidebarFor;
}

Comment on lines +135 to +138
toast.info(
`Showing first ${patientAllergies.results.length} of ${patientAllergies.count} allergies`,
);
}
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

Internationalize the toast message for localization support.

The toast message in the useEffect hook is hard-coded in English. To support localization, please use the translation function (e.g., t) to wrap the message, ensuring the application is accessible to users in different languages.

Apply this diff to internationalize the message:

           if (patientAllergies.count > patientAllergies.results.length) {
-            toast.info(
-              `Showing first ${patientAllergies.results.length} of ${patientAllergies.count} allergies`,
-            );
+            toast.info(
+              t("showing_first_allergies", {
+                count: patientAllergies.results.length,
+                total: patientAllergies.count,
+              }),
+            );
           }

Ensure that the translation key showing_first_allergies is added to your localization files:

{
  "showing_first_allergies": "Showing first {{count}} of {{total}} allergies"
}

@@ -1,33 +1,24 @@
import { useQuery } from "@tanstack/react-query";
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

Critical: PR changes do not match objectives.

The reviewed files contain significant changes related to navigation components, authentication handling, and UI updates, but none of these changes appear to be related to the stated PR objective of updating diet preference values from snake case to kebab case. This suggests either:

  1. The wrong files were provided for review
  2. The PR description needs to be updated
  3. The diet preference changes are missing from this PR

Please clarify the discrepancy between the PR objectives and the actual changes.

Comment on lines +49 to +54
const appointmentTime = dayjs(appointmentData?.token_slot.start_datetime)
.add(-5, "hours")
.add(-30, "minutes")
.toISOString();
const appointmentDate = format(new Date(appointmentTime), "do MMMM");
const appointmentTimeSlot = format(new Date(appointmentTime), "hh:mm a");
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

Avoid hardcoding timezone offsets

The hardcoded adjustment of -5 hours and -30 minutes could cause issues with daylight saving time and different timezones. Consider using proper timezone handling.

- const appointmentTime = dayjs(appointmentData?.token_slot.start_datetime)
-   .add(-5, "hours")
-   .add(-30, "minutes")
-   .toISOString();
+ const appointmentTime = dayjs(appointmentData?.token_slot.start_datetime)
+   .tz(process.env.REACT_APP_TIMEZONE || "Asia/Kolkata")
+   .toISOString();

Also, add the following to your dependencies:

+ "dayjs-timezone": "^1.0.0"

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

Comment on lines +1766 to +1775
export const DIET_PREFERENCE_OPTIONS = [
{ label: "Vegetarian", value: "vegetarian" },
{ label: "Dairy Free", value: "diary_free" },
{ label: "Nut Free", value: "nut_free" },
{ label: "Gluten Free", value: "gluten_free" },
{ label: "Vegan", value: "vegan" },
{ label: "Halal", value: "halal" },
{ label: "Kosher", value: "kosher" },
{ label: "None", value: "none" },
] 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.

⚠️ Potential issue

Fix typo and update values to use kebab case

  1. There's a typo in the value: "diary_free" should be "dairy-free"
  2. Values should use kebab case (with hyphens) instead of snake case (with underscores) to align with PR objective.

Apply this diff to fix the issues:

 export const DIET_PREFERENCE_OPTIONS = [
   { label: "Vegetarian", value: "vegetarian" },
-  { label: "Dairy Free", value: "diary_free" },
-  { label: "Nut Free", value: "nut_free" },
-  { label: "Gluten Free", value: "gluten_free" },
+  { label: "Dairy Free", value: "dairy-free" },
+  { label: "Nut Free", value: "nut-free" },
+  { label: "Gluten Free", value: "gluten-free" },
   { label: "Vegan", value: "vegan" },
   { label: "Halal", value: "halal" },
   { label: "Kosher", value: "kosher" },
   { label: "None", value: "none" },
 ] as const;
📝 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 DIET_PREFERENCE_OPTIONS = [
{ label: "Vegetarian", value: "vegetarian" },
{ label: "Dairy Free", value: "diary_free" },
{ label: "Nut Free", value: "nut_free" },
{ label: "Gluten Free", value: "gluten_free" },
{ label: "Vegan", value: "vegan" },
{ label: "Halal", value: "halal" },
{ label: "Kosher", value: "kosher" },
{ label: "None", value: "none" },
] as const;
export const DIET_PREFERENCE_OPTIONS = [
{ label: "Vegetarian", value: "vegetarian" },
{ label: "Dairy Free", value: "dairy-free" },
{ label: "Nut Free", value: "nut-free" },
{ label: "Gluten Free", value: "gluten-free" },
{ label: "Vegan", value: "vegan" },
{ label: "Halal", value: "halal" },
{ label: "Kosher", value: "kosher" },
{ label: "None", value: "none" },
] as const;

Comment on lines +13 to +15
import { PatientRegistration } from "@/pages/Appoinments/PatientRegistration";
import PatientSelect from "@/pages/Appoinments/PatientSelect";
import { ScheduleAppointment } from "@/pages/Appoinments/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

Correct the import paths: 'Appointments' is misspelled

The directory name 'Appointments' is misspelled as 'Appoinments' in the import paths, which will lead to module resolution errors.

Apply this diff to fix the import paths:

-import { PatientRegistration } from "@/pages/Appoinments/PatientRegistration";
+import { PatientRegistration } from "@/pages/Appointments/PatientRegistration";
-import PatientSelect from "@/pages/Appoinments/PatientSelect";
+import PatientSelect from "@/pages/Appointments/PatientSelect";
-import { ScheduleAppointment } from "@/pages/Appoinments/Schedule";
+import { ScheduleAppointment } from "@/pages/Appointments/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
import { PatientRegistration } from "@/pages/Appoinments/PatientRegistration";
import PatientSelect from "@/pages/Appoinments/PatientSelect";
import { ScheduleAppointment } from "@/pages/Appoinments/Schedule";
import { PatientRegistration } from "@/pages/Appointments/PatientRegistration";
import PatientSelect from "@/pages/Appointments/PatientSelect";
import { ScheduleAppointment } from "@/pages/Appointments/Schedule";

Comment on lines +84 to +95
"/facility/:facilityId/patient/:patientId/encounterId/:id/files/": ({
facilityId,
patientId,
id,
}) => (
<FileUploadPage
facilityId={facilityId}
patientId={patientId}
encounterId={id}
type="encounter"
/>
),
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

Correct the route parameter and variable name

The route path uses encounterId/:id, which is inconsistent with other routes and may cause confusion. Additionally, the parameter id is used where encounterId would be more appropriate. This inconsistency can lead to errors in route matching and parameter handling.

Apply this diff to correct the route and parameter names:

-  "/facility/:facilityId/patient/:patientId/encounterId/:id/files/": ({
+  "/facility/:facilityId/patient/:patientId/encounter/:encounterId/files/": ({
     facilityId,
     patientId,
-    id,
+    encounterId,
   }) => (
     <FileUploadPage
       facilityId={facilityId}
       patientId={patientId}
-      encounterId={id}
+      encounterId={encounterId}
       type="encounter"
     />
   ),
📝 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/patient/:patientId/encounterId/:id/files/": ({
facilityId,
patientId,
id,
}) => (
<FileUploadPage
facilityId={facilityId}
patientId={patientId}
encounterId={id}
type="encounter"
/>
),
"/facility/:facilityId/patient/:patientId/encounter/:encounterId/files/": ({
facilityId,
patientId,
encounterId,
}) => (
<FileUploadPage
facilityId={facilityId}
patientId={patientId}
encounterId={encounterId}
type="encounter"
/>
),

@Jacobjeevan
Copy link
Contributor

Looks like this includes commits from develop/wasn't merged properly 🤔 How did you merge to the latest? @arhamathar

https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging

@Jacobjeevan Jacobjeevan added the invalid This doesn't seem right label Jan 9, 2025
@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Jan 9, 2025
Copy link

github-actions bot commented Jan 9, 2025

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


This message is automatically generated by prince-chrismc/label-merge-conflicts-action so don't hesitate to report issues/improvements there.

@rithviknishad
Copy link
Member

closing due to no activity for 2 days

@arhamathar
Copy link
Contributor Author

Hi @rithviknishad I have moved the snake_case values to constants. Should I create a new PR now?

@github-actions github-actions bot added needs-triage question Further information is requested labels Jan 9, 2025
@rithviknishad
Copy link
Member

Go ahead

@arhamathar arhamathar deleted the issues/9817/diet-preference branch January 9, 2025 10:53
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 merge conflict pull requests with merge conflict needs-triage question Further information is requested
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Failed to update encounters on selecting certain diet preference
9 participants