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

Fixes UI Bug Issue in Symptom Editor #9270

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

Conversation

JavidSumra
Copy link
Contributor

@JavidSumra JavidSumra commented Dec 2, 2024

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

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

Summary by CodeRabbit

  • New Features

    • Enhanced accessibility of the date input field with a tooltip on hover.
    • Improved layout and presentation of the Autocomplete Multiselect dropdown.
    • Updated styling for the DateFormField component.
    • Minor layout adjustments in the ModelCrudEditor component.
  • Bug Fixes

    • Clarified default behavior for max and min date props in the DateFormField.

@JavidSumra JavidSumra requested a review from a team as a code owner December 2, 2024 12:45
Copy link
Contributor

coderabbitai bot commented Dec 2, 2024

Walkthrough

The pull request introduces several modifications across multiple components, primarily focusing on enhancing the user interface and accessibility. The DateInputV2 component now includes a title attribute for improved accessibility. The AutocompleteMultiselect component has undergone layout adjustments, particularly to the dropdown icon and button alignment. The DateFormField component has improved styling and clarified logic for max and min properties. Lastly, the ModelCrudEditor component has minor rendering adjustments, particularly in the delete button's appearance.

Changes

File Path Change Summary
src/components/Common/DateInputV2.tsx Added a title attribute to the input element in PopoverButton for accessibility.
src/components/Form/FormFields/AutocompleteMultiselect.tsx Updated ComboboxButton class for alignment, modified dropdown icon positioning, and adjusted loading state rendering.
src/components/Form/FormFields/DateFormField.tsx Enhanced styling with additional CSS class and clarified max and min prop logic using nullish coalescing.
src/components/Form/ModelCrudEditor.tsx Minor adjustments to rendering logic of the delete button and conditional rendering of "remove" text.

Assessment against linked issues

Objective Addressed Explanation
Fix overlap in date input (8998)
Fix the dropdown icon (8998)
Port over the <EncounterSymptomsBuilder> component (8998) No changes related to porting the component.

Possibly related PRs

Suggested labels

needs review, tested, urgent, P1

Suggested reviewers

  • rithviknishad
  • shivankacker
  • Jacobjeevan

🐇 In the meadow, changes bloom,
A title here, to lift the gloom.
Dropdowns dance, aligned just right,
With styles anew, they shine so bright.
In our code, we hop with glee,
Enhancements made, for all to see! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between be7cefa and 46da85f.

📒 Files selected for processing (2)
  • src/components/Form/FormFields/DateFormField.tsx (1 hunks)
  • src/components/Form/ModelCrudEditor.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/components/Form/ModelCrudEditor.tsx
  • src/components/Form/FormFields/DateFormField.tsx

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. (Experiment)
  • @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 Dec 2, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit e8bd966
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/675d0d7f18483f0008b8449d
😎 Deploy Preview https://deploy-preview-9270--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (4)
src/components/Form/FormFields/DateFormField.tsx (2)

40-43: LGTM! The styling changes address the UI alignment issues.

The addition of margin and text ellipsis classes aligns with the PR objectives to fix the UI bugs in the date input field.

Consider these improvements:

  1. Use a CSS variable for the margin to make it configurable:
-"mr-9 text-ellipsis"
+"mr-[var(--date-input-margin,2.25rem)] text-ellipsis"
  1. Add a comment explaining the purpose of these specific classes for future maintainability:
 className={classNames(
   field.error && "border-red-500",
-  "mr-9 text-ellipsis",
+  // Right margin for dropdown icon alignment, ellipsis for overflow handling
+  "mr-[var(--date-input-margin,2.25rem)] text-ellipsis",
 )}

Line range hint 39-58: Consider forwarding the title prop for accessibility.

The AI summary mentions that DateInputV2 now supports a title property for accessibility, but it's not being passed through from DateFormField. Consider adding this capability to improve accessibility.

Add the title prop to the Props type and forward it:

type Props = FormFieldBaseProps<Date> & {
  containerClassName?: string;
  placeholder?: string;
  max?: Date;
  min?: Date;
  disableFuture?: boolean;
  disablePast?: boolean;
  allowTime?: boolean;
  popOverClassName?: string;
+ title?: string;  // For accessibility tooltip
};

// In the component render
<DateInputV2
  // ... other props
+ title={props.title}
/>
src/components/Symptoms/SymptomsBuilder.tsx (2)

201-208: Remove redundant block statements to simplify the code

The block statements around the conditional expression in lines 201-208 are unnecessary and can be safely removed to simplify the code, as indicated by static analysis tools.

Apply this diff to remove the redundant block:

- {
    "id" in item
      ? setItem({
          onset_date: dateQueryString(value),
          id: item.id,
        })
      : setItem({ ...item, onset_date: dateQueryString(value) });
- }
+ "id" in item
+   ? setItem({
+       onset_date: dateQueryString(value),
+       id: item.id,
+     })
+   : setItem({ ...item, onset_date: dateQueryString(value) });
🧰 Tools
🪛 Biome (1.9.4)

[error] 201-208: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)


225-235: Remove redundant block statements to simplify the code

Similarly, the block statements in lines 225-235 are unnecessary and can be removed to clean up the code.

Apply this diff:

- {
    "id" in item
      ? setItem({
          cure_date: dateQueryString(value),
          id: item.id,
        })
      : setItem({
          ...(item as EncounterSymptom),
          cure_date: dateQueryString(value),
        });
- }
+ "id" in item
+   ? setItem({
+       cure_date: dateQueryString(value),
+       id: item.id,
+     })
+   : setItem({
+       ...(item as EncounterSymptom),
+       cure_date: dateQueryString(value),
+     });
🧰 Tools
🪛 Biome (1.9.4)

[error] 225-235: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2d9669e and ed94362.

📒 Files selected for processing (6)
  • src/components/Common/DateInputV2.tsx (1 hunks)
  • src/components/Form/FormFields/AutocompleteMultiselect.tsx (1 hunks)
  • src/components/Form/FormFields/DateFormField.tsx (1 hunks)
  • src/components/Form/ModelCrudEditor.tsx (2 hunks)
  • src/components/Symptoms/SymptomsBuilder.tsx (4 hunks)
  • src/components/Symptoms/types.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/components/Common/DateInputV2.tsx
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/Symptoms/SymptomsBuilder.tsx

[error] 201-208: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)


[error] 225-235: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

🔇 Additional comments (2)
src/components/Form/ModelCrudEditor.tsx (1)

Line range hint 103-124: LGTM

The adjustments to the layout enhance the component's responsiveness without affecting functionality.

src/components/Form/FormFields/AutocompleteMultiselect.tsx (1)

174-185: Improve alignment and positioning of the dropdown icon

The modifications to the ComboboxButton and associated classes enhance the visual alignment of the dropdown icon, providing a better user experience.

src/components/Symptoms/SymptomsBuilder.tsx Outdated Show resolved Hide resolved
src/components/Symptoms/types.ts Outdated Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (3)
src/components/Symptoms/SymptomsBuilder.tsx (3)

101-138: Enhance error handling in createSymptom function

The function should handle API errors more gracefully and provide more specific success messages.

Consider applying these improvements:

 const createSymptom = async (body: EncounterSymptomRequest) => {
   if (Array.isArray(body.symptom)) {
     const { symptom, onset_date, other_symptom } = body;
     const objects = symptom.map((symptom: EncounterSymptom["symptom"]) => ({
       symptom,
       onset_date: dateQueryString(onset_date),
       other_symptom:
         symptom === OTHER_SYMPTOM_CHOICE.id ? other_symptom : undefined,
     }));

     if (consultationId) {
       try {
         const responses = await Promise.all(
           objects.map((body) =>
             request(SymptomsApi.add, {
               body,
               pathParams: { consultationId: consultationId! },
             }),
           ),
         );

         if (responses.every(({ res }) => !!res?.ok)) {
-          Success({ msg: "Symptoms records updated successfully" });
+          Success({ msg: `Successfully added ${objects.length} symptom(s)` });
         } else {
+          throw new Error("Failed to add some symptoms");
         }
       } catch (error) {
+        console.error("Failed to create symptoms:", error);
+        throw error;
       }
     }
   } else {
     try {
       const { res } = await request(SymptomsApi.add, {
         pathParams: { consultationId },
         body,
       });

       if (res?.ok) {
-        Success({ msg: "Symptom added successfully" });
+        Success({ msg: `Successfully added ${SYMPTOM_CHOICES.find(s => s.id === body.symptom)?.text || 'symptom'}` });
       } else {
+        throw new Error("Failed to add symptom");
       }
     } catch (error) {
+      console.error("Failed to create symptom:", error);
+      throw error;
     }
   }
   refetch();
 };

183-185: Review the debounce delay duration

The current debounce delay of 5000ms (5 seconds) seems excessive and might affect user experience.

Consider reducing the delay:

 const debouncedSetItem = debounce((value: string) => {
   setItem({ other_symptom: value, symptom: item.symptom });
-}, 5000);
+}, 1000);

199-209: Remove redundant block statement

The block statement is unnecessary and can be simplified.

Apply this change:

 if (!dayjs(onsetDate).isSame(dayjs(value), "second")) {
   setOnsetDate(value);
-  {
-    "id" in item
-      ? setItem({
-          onset_date: dateQueryString(value),
-          id: item.id,
-        })
-      : setItem({ ...item, onset_date: dateQueryString(value) });
-  }
+  "id" in item
+    ? setItem({
+        onset_date: dateQueryString(value),
+        id: item.id,
+      })
+    : setItem({ ...item, onset_date: dateQueryString(value) });
 }
🧰 Tools
🪛 Biome (1.9.4)

[error] 201-208: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ed94362 and ef59197.

📒 Files selected for processing (2)
  • src/components/Symptoms/SymptomsBuilder.tsx (4 hunks)
  • src/components/Symptoms/types.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Symptoms/types.ts
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/Symptoms/SymptomsBuilder.tsx

[error] 201-208: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)


[error] 225-235: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

🔇 Additional comments (1)
src/components/Symptoms/SymptomsBuilder.tsx (1)

354-358: ⚠️ Potential issue

Fix the allowCreate condition logic

The current condition incorrectly disables the create button even when symptoms are selected.

Apply this fix:

-allowCreate={(item) =>
-  !item.onset_date && Array.isArray(item.symptom)
-    ? !item.symptom.length
-    : !item.symptom
-}
+allowCreate={(item) =>
+  !(Array.isArray(item.symptom) && item.symptom.length > 0)
+}

@JavidSumra
Copy link
Contributor Author

Hey @shivankacker, it seems that when we update fields like onsetDate or symptom, the component gets re-rendered. This is expected behavior, so I believe the test suit should be updated to account for this. Would it be okay to adjust the test suit accordingly?

@github-actions github-actions bot added needs-triage question Further information is requested labels Dec 4, 2024
@shivankacker
Copy link
Member

I don't think the tests are failing because of that. Go through test screenshots and see if you can find what is causing the failure

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

🧹 Outside diff range and nitpick comments (3)
src/components/Symptoms/SymptomsBuilder.tsx (3)

1-1: Consider adding timezone handling for medical records

When dealing with medical records, it's crucial to handle timezones correctly. Consider using dayjs with timezone plugin to ensure consistent date handling across different regions.

+import timezone from "dayjs/plugin/timezone";
+import utc from "dayjs/plugin/utc";
+
+dayjs.extend(utc);
+dayjs.extend(timezone);

201-208: Remove redundant block statements

The code contains unnecessary block statements that can be simplified.

-              {
                "id" in item
                  ? setItem({
                      onset_date: dateQueryString(value),
                      id: item.id,
                    })
                  : setItem({ ...item, onset_date: dateQueryString(value) });
-              }

-              {
                "id" in item
                  ? setItem({
                      cure_date: dateQueryString(value),
                      id: item.id,
                    })
                  : setItem({
                      ...(item as EncounterSymptom),
                      cure_date: dateQueryString(value),
                    });
-              }

Also applies to: 225-235

🧰 Tools
🪛 Biome (1.9.4)

[error] 201-208: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)


169-181: Consider using useReducer for complex state management

The component uses multiple useState hooks for related state variables. Consider using useReducer to simplify state management and ensure consistent updates.

type SymptomState = {
  selected: EncounterSymptom["symptom"] | EncounterSymptom["symptom"][];
  otherSymptom: string;
  onsetDate?: Date;
  onCureDate?: Date;
};

type SymptomAction =
  | { type: 'SET_SELECTED'; payload: EncounterSymptom["symptom"] | EncounterSymptom["symptom"][] }
  | { type: 'SET_OTHER_SYMPTOM'; payload: string }
  | { type: 'SET_ONSET_DATE'; payload?: Date }
  | { type: 'SET_CURE_DATE'; payload?: Date };

const symptomReducer = (state: SymptomState, action: SymptomAction): SymptomState => {
  switch (action.type) {
    case 'SET_SELECTED':
      return { ...state, selected: action.payload };
    case 'SET_OTHER_SYMPTOM':
      return { ...state, otherSymptom: action.payload };
    case 'SET_ONSET_DATE':
      return { ...state, onsetDate: action.payload };
    case 'SET_CURE_DATE':
      return { ...state, onCureDate: action.payload };
    default:
      return state;
  }
};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ef59197 and 5692925.

📒 Files selected for processing (2)
  • src/components/Common/DateInputV2.tsx (1 hunks)
  • src/components/Symptoms/SymptomsBuilder.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Common/DateInputV2.tsx
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/Symptoms/SymptomsBuilder.tsx

[error] 201-208: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)


[error] 225-235: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

🔇 Additional comments (1)
src/components/Symptoms/SymptomsBuilder.tsx (1)

354-358: Correct the condition in allowCreate prop to enable symptom creation

The current condition in the allowCreate prop incorrectly disables the create button even when symptoms are selected. It should be updated to properly reflect when creation is allowed.

src/components/Symptoms/SymptomsBuilder.tsx Outdated Show resolved Hide resolved
@nihal467 nihal467 removed question Further information is requested needs-triage labels Dec 9, 2024
@nihal467
Copy link
Member

nihal467 commented Dec 9, 2024

@JavidSumra Can you please share the current status of the PR? Otherwise, the PR will be closed in the next 48 hours, and you will be unassigned from the issue due to inactivity.

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

🧹 Outside diff range and nitpick comments (1)
src/components/Common/DateTextInput.tsx (1)

Line range hint 1-200: Enhance accessibility and documentation

The component has good keyboard navigation but could benefit from improved accessibility and documentation:

  1. Add ARIA roles and states for better screen reader support
  2. Document keyboard navigation in the component's JSDoc
  3. Add error announcements for screen readers

Consider these improvements:

 /**
  * DateTextInput component.
  *
+ * Keyboard Navigation:
+ * - Left/Right arrows: Navigate between fields
+ * - Backspace: Move to previous field when empty
+ * - Delete: Move to next field when empty
+ * 
  * @param {Object} props - Component properties.
  */

Add ARIA attributes to the container:

 <div
   className={classNames(...)}
+  role="group"
+  aria-label="Date and time input"
+  aria-invalid={!!error}
 >

Add live region for error announcements:

- {error && <span className="text-xs text-red-500">{error}</span>}
+ {error && (
+   <span 
+     className="text-xs text-red-500"
+     role="alert"
+     aria-live="polite"
+   >
+     {error}
+   </span>
+ )}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5692925 and e43492e.

📒 Files selected for processing (2)
  • cypress/support/commands.ts (1 hunks)
  • src/components/Common/DateTextInput.tsx (1 hunks)
🔇 Additional comments (1)
cypress/support/commands.ts (1)

194-197: Verify test coverage with updated selector

The selector change from data-test-id="date-input" to id="date-input" aligns with the component changes in DateTextInput.tsx. However, this change might affect other tests that rely on the old selector.

Let's verify if other tests might be affected:

✅ Verification successful

Selector change is safe to proceed

The search results show that commands.ts is the only file using either the old (data-test-id="date-input") or new (id="date-input") selector. This confirms that the selector change is isolated to the clickAndTypeDate command in commands.ts and doesn't affect any other test files in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usage of the old selector
rg -l 'data-test-id="date-input"' 'cypress/integration/**/*.{js,ts,jsx,tsx}'

Length of output: 159


Script:

#!/bin/bash
# Let's first find the correct test directory structure
fd -t d "cypress"

# Then search for any remaining usage of the old selector in all cypress files
rg -l 'data-test-id="date-input"' 'cypress/**/*.{js,ts,jsx,tsx}'

# Also search for current usage of the new selector for completeness
rg -l 'id="date-input"' 'cypress/**/*.{js,ts,jsx,tsx}'

Length of output: 288


Script:

#!/bin/bash
# Let's try searching in the cypress directory without the glob pattern
cd cypress
rg -l 'data-test-id="date-input"'
rg -l 'id="date-input"'

# Also list all files in cypress directory to understand the structure
find . -type f -name "*.ts" -o -name "*.js" -o -name "*.tsx" -o -name "*.jsx"

Length of output: 3132

src/components/Common/DateTextInput.tsx Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (2)
cypress/e2e/patient_spec/PatientLogUpdate.cy.ts (1)

Line range hint 332-365: Enhance MEWS Score test coverage and documentation

While the test covers basic functionality, it could be more comprehensive and maintainable:

  1. Document why "9" is the expected score based on the input values
  2. Add test cases for edge cases and boundary values
  3. Verify intermediate score changes when updating individual vital signs

Consider expanding the test with additional scenarios:

// Add test cases for different MEWS score ranges
it("Verifies MEWS Score calculation for different ranges", () => {
  // Low risk (0-2)
  patientLogupdate.typeSystolic("120");
  patientLogupdate.typePulse("70");
  // ... set other vitals for low risk
  cy.verifyContentPresence("#consultation-buttons", ["1"]);

  // Medium risk (3-4)
  patientLogupdate.typeSystolic("90");
  patientLogupdate.typePulse("130");
  // ... set other vitals for medium risk
  cy.verifyContentPresence("#consultation-buttons", ["4"]);

  // High risk (≥5)
  patientLogupdate.typeSystolic("85");
  patientLogupdate.typePulse("140");
  // ... set other vitals for high risk
  cy.verifyContentPresence("#consultation-buttons", ["9"]);
});
src/components/Symptoms/SymptomsBuilder.tsx (1)

202-209: Simplify redundant block statements

The code contains unnecessary block statements that can be simplified.

Apply this diff to simplify the code:

- {
-   "id" in item
-     ? setItem({
-         onset_date: dateQueryString(value),
-         id: item.id,
-       })
-     : setItem({ ...item, onset_date: dateQueryString(value) });
- }
+ "id" in item
+   ? setItem({
+       onset_date: dateQueryString(value),
+       id: item.id,
+     })
+   : setItem({ ...item, onset_date: dateQueryString(value) });

Apply similar simplification to the block at lines 226-236.

Also applies to: 226-236

🧰 Tools
🪛 Biome (1.9.4)

[error] 202-209: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e43492e and be7cefa.

📒 Files selected for processing (2)
  • cypress/e2e/patient_spec/PatientLogUpdate.cy.ts (1 hunks)
  • src/components/Symptoms/SymptomsBuilder.tsx (4 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/components/Symptoms/SymptomsBuilder.tsx

[error] 202-209: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)


[error] 226-236: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

🔇 Additional comments (2)
src/components/Symptoms/SymptomsBuilder.tsx (2)

355-359: ⚠️ Potential issue

Fix the condition in allowCreate prop

The current condition in the allowCreate prop incorrectly prevents symptom creation when symptoms are selected.

Apply this diff to fix the condition:

-        allowCreate={(item) =>
-          !item.onset_date && Array.isArray(item.symptom)
-            ? !item.symptom.length
-            : !item.symptom
-        }
+        allowCreate={(item) =>
+          item.onset_date && Array.isArray(item.symptom) && item.symptom.length > 0
+        }

Likely invalid or redundant comment.


101-138: ⚠️ Potential issue

Enhance error handling in createSymptom function

The error handling in the createSymptom function needs improvement to handle API failures gracefully.

Apply this diff to improve error handling:

 const createSymptom = async (body: EncounterSymptomRequest) => {
+  try {
     if (Array.isArray(body.symptom)) {
       const { symptom, onset_date, other_symptom } = body;
       const objects = symptom.map((symptom: EncounterSymptom["symptom"]) => ({
         symptom,
         onset_date: dateQueryString(onset_date),
         other_symptom:
           symptom === OTHER_SYMPTOM_CHOICE.id ? other_symptom : undefined,
       }));

       if (consultationId) {
         const responses = await Promise.all(
           objects.map((body) =>
             request(SymptomsApi.add, {
               body,
               pathParams: { consultationId: consultationId! },
             }),
           ),
         );

-        if (responses.every(({ res }) => !!res?.ok)) {
+        const failedResponses = responses.filter(({ res }) => !res?.ok);
+        if (failedResponses.length > 0) {
+          throw new Error(`Failed to create ${failedResponses.length} symptoms`);
+        }
         Success({ msg: "Symptoms records updated successfully" });
       }
     } else {
       const { res } = await request(SymptomsApi.add, {
         pathParams: { consultationId },
         body,
       });

       if (res?.ok) {
         Success({ msg: "Symptom added successfully" });
+      } else {
+        throw new Error("Failed to create symptom");
       }
     }
     refetch();
+  } catch (error) {
+    console.error("Error creating symptom:", error);
+    Error({ msg: error instanceof Error ? error.message : "Failed to create symptom" });
+  }
 };

Likely invalid or redundant comment.

cypress/e2e/patient_spec/PatientLogUpdate.cy.ts Outdated Show resolved Hide resolved
src/components/Symptoms/SymptomsBuilder.tsx Outdated Show resolved Hide resolved
@JavidSumra
Copy link
Contributor Author

Hey @nihal467, the PatientLogUpdate test case was failing due to some issues. I added a cy.wait before the date selection, and now it's passing. I also tried using the cy.intercept method, but it didn't work. Could you please guide me on the next steps?

@nihal467
Copy link
Member

nihal467 commented Dec 10, 2024

https://www.loom.com/share/b0d219030c524e4c8ca6a35660191ff4?sid=44912730-a263-4af0-a768-0af799822c5e

@JavidSumra when we initially open the log update page, the component is auto closed without interaction

@JavidSumra
Copy link
Contributor Author

@nihal467 need your review.

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.

Fix UI bugs with Symptoms editor and move to ModelCrudEditor component
3 participants