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

Structured Response View Cleanup #9797

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

Conversation

amjithtitus09
Copy link
Contributor

@amjithtitus09 amjithtitus09 commented Jan 6, 2025

Proposed Changes

  • Structured Response View Cleanup

@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

  • Refactor

    • Enhanced type safety for consultation details view by updating prop types to StructuredQuestionType
    • Improved query handling by restructuring into distinct hooks for symptoms, diagnoses, and allergies
    • Streamlined parameter construction and error handling logic for better clarity and robustness
  • Style

    • Removed an unnecessary blank line in a type definitions file

@amjithtitus09 amjithtitus09 requested a review from a team as a code owner January 6, 2025 14:15
Copy link
Contributor

coderabbitai bot commented Jan 6, 2025

Walkthrough

The pull request focuses on refactoring the StructuredResponseView component in the consultation details section. The changes primarily involve enhancing type safety by narrowing the type prop to a specific union type, introducing separate useQuery hooks for different data types (symptoms, diagnoses, and allergies), and streamlining the parameter construction logic. The implementation now provides more granular control over API calls and improves error handling by conditionally enabling queries based on the component's props.

Changes

File Change Summary
src/components/Facility/ConsultationDetails/StructuredResponseView.tsx - Narrowed type prop to union type `"symptom"
src/types/notes/messages.ts - Removed a blank line at the end of the file (no functional changes)
src/components/Facility/ConsultationDetails/QuestionnaireResponsesList.tsx - Imported StructuredQuestionType
- Updated type prop to cast to StructuredQuestionType

Sequence Diagram

sequenceDiagram
    participant Component as StructuredResponseView
    participant QueryHook as useQuery
    participant API as Backend API

    Component->>QueryHook: Trigger query based on type
    alt Symptoms
        QueryHook->>API: Fetch symptom data
    else Diagnoses
        QueryHook->>API: Fetch diagnosis data
    else Allergies
        QueryHook->>API: Fetch allergy data
    end
    API-->>QueryHook: Return query results
    QueryHook-->>Component: Provide data for rendering
Loading

Suggested labels

tested, changes required, needs review

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

🐰 Queries dance with type-safe grace,
Code refactored at lightning pace
Symptoms, diagnoses take their stand
Allergies mapped by a rabbit's hand
Cleaner, safer - our code's embrace! 🩺


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

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 47b6dac
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/677bf5193119dd00088833b0
😎 Deploy Preview https://deploy-preview-9797--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

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

Copy link

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

Deploying care-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 47b6dac
Status: ✅  Deploy successful!
Preview URL: https://b05d89c5.care-fe.pages.dev
Branch Preview URL: https://structured-response-view-cle.care-fe.pages.dev

View logs

@github-actions github-actions bot added the Deploy-Failed Deplyment is not showing preview label Jan 6, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (4)
src/components/Facility/ConsultationDetails/StructuredResponseView.tsx (4)

57-58: Consider providing additional user-facing error details.
While console.error helps in dev environments, consider augmenting the UI error message to guide end users on possible remediation steps (e.g., retry).


65-65: Handle loading or empty states more gracefully.
If symptomQuery.data is null or undefined, an empty table or spinner could be displayed instead of rendering nothing.


69-71: Avoid rendering nothing if no data is found.
Similarly, for diagnoses, consider returning a placeholder or “No data” message to improve user experience.


75-75: Provide feedback on empty allergy records.
Similarly, show a placeholder or fallback if allergyQuery.data is empty or undefined, instead of returning nothing.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b208351 and 08ae3d8.

📒 Files selected for processing (2)
  • src/components/Facility/ConsultationDetails/StructuredResponseView.tsx (2 hunks)
  • src/types/notes/messages.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • src/types/notes/messages.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: care-fe
🔇 Additional comments (4)
src/components/Facility/ConsultationDetails/StructuredResponseView.tsx (4)

13-13: Strengthened type safety is commendable.
Narrowing the type prop to "symptom" | "diagnosis" | "allergy_intolerance" helps prevent type-related bugs and provides clear intent.


25-26: Concise definition of common parameters.
Defining basePathParams and queryParams as separate objects keeps the setup clean and maintains clarity for shared fields.


28-31: Good consolidation of parameter construction.
Centralizing parameter logic in getParams avoids duplication and keeps the code DRY.


51-55: Good approach to unify queries.
Mapping type to the respective query object for a single entry point considerably reduces conditional complexity.

Comment on lines 39 to 43
const diagnosisQuery = useQuery({
queryKey: ["diagnosis"],
queryFn: query(diagnosisApi.retrieveDiagnosis, getParams("diagnosisId")),
enabled: type === "diagnosis" && !!id,
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure each diagnosis fetch is uniquely identified.
Similar to the symptom query, updating the query key to include the id would prevent stale or incorrectly cached diagnosis data.

- queryKey: ["diagnosis"],
+ queryKey: ["diagnosis", id],
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const diagnosisQuery = useQuery({
queryKey: ["diagnosis"],
queryFn: query(diagnosisApi.retrieveDiagnosis, getParams("diagnosisId")),
enabled: type === "diagnosis" && !!id,
});
const diagnosisQuery = useQuery({
queryKey: ["diagnosis", id],
queryFn: query(diagnosisApi.retrieveDiagnosis, getParams("diagnosisId")),
enabled: type === "diagnosis" && !!id,
});

Comment on lines 45 to 49
const allergyQuery = useQuery({
queryKey: ["allergy_intolerance"],
queryFn: query(allergyApi.retrieveAllergy, getParams("allergyId")),
enabled: type === "allergy_intolerance" && !!id,
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Distinguish allergy requests with the specific ID.
Including the id in the query key would help React Query accurately track and control fetches for different allergy records.

- queryKey: ["allergy_intolerance"],
+ queryKey: ["allergy_intolerance", id],
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const allergyQuery = useQuery({
queryKey: ["allergy_intolerance"],
queryFn: query(allergyApi.retrieveAllergy, getParams("allergyId")),
enabled: type === "allergy_intolerance" && !!id,
});
const allergyQuery = useQuery({
queryKey: ["allergy_intolerance", id],
queryFn: query(allergyApi.retrieveAllergy, getParams("allergyId")),
enabled: type === "allergy_intolerance" && !!id,
});

Comment on lines 33 to 36
const symptomQuery = useQuery({
queryKey: ["symptom"],
queryFn: query(symptomApi.retrieveSymptom, getParams("symptomId")),
enabled: type === "symptom" && !!id,
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve query key to differentiate requests with unique IDs.
When fetching data keyed only by "symptom", React Query may not refetch properly if id changes. Consider including the id in the query key for correct caching and refetching behavior.

- queryKey: ["symptom"],
+ queryKey: ["symptom", id],
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const symptomQuery = useQuery({
queryKey: ["symptom"],
queryFn: query(symptomApi.retrieveSymptom, getParams("symptomId")),
enabled: type === "symptom" && !!id,
const symptomQuery = useQuery({
queryKey: ["symptom", id],
queryFn: query(symptomApi.retrieveSymptom, getParams("symptomId")),
enabled: type === "symptom" && !!id,

Copy link

cypress bot commented Jan 6, 2025

CARE    Run #4173

Run Properties:  status check failed Failed #4173  •  git commit 47b6dacaec: Structured Response View Cleanup
Project CARE
Branch Review structured-response-view-cleanup
Run status status check failed Failed #4173
Run duration 01m 48s
Commit git commit 47b6dacaec: Structured Response View Cleanup
Committer Amjith Titus
View all properties for this run ↗︎

Test results
Tests that failed  Failures 1
Tests that were flaky  Flaky 0
Tests that did not run due to a developer annotating a test with .skip  Pending 0
Tests that did not run due to a failure in a mocha hook  Skipped 0
Tests that passed  Passing 3
View all changes introduced in this branch ↗︎

Tests for review

Failed  cypress/e2e/patient_spec/patient_search.cy.ts • 1 failed test

View Output

Test Artifacts
Patient Search > search patient with phone number and verifies details Test Replay Screenshots

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

github-actions bot commented Jan 7, 2025

👋 Hi, @amjithtitus09,
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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
src/components/Facility/ConsultationDetails/StructuredResponseView.tsx (3)

31-36: Consider memoizing the parameter construction.

While the parameter handling is well-organized, consider memoizing basePathParams and getParams to prevent unnecessary recreations on re-renders.

-  const basePathParams = { patientId };
-  const queryParams = { encounter: encounterId };
-
-  const getParams = (idKey: string) => ({
+  const basePathParams = useMemo(() => ({ patientId }), [patientId]);
+  const queryParams = useMemo(() => ({ encounter: encounterId }), [encounterId]);
+
+  const getParams = useCallback((idKey: string) => ({
     pathParams: { ...basePathParams, [idKey]: id },
     queryParams,
-  });
+  }), [basePathParams, queryParams, id]);

59-66: Enhance error handling implementation.

While the error handling provides user feedback, consider these improvements:

  1. Use a proper logging service instead of console.error in production
  2. Provide more user-friendly error messages
  3. Consider adding error boundaries
-  if (currentQuery.error) {
-    console.error(`Error loading ${type}:`, currentQuery.error);
-    return <div>Error loading {type}</div>;
+  if (currentQuery.error) {
+    // Use your logging service here
+    logger.error(`Error loading ${type}:`, currentQuery.error);
+    return (
+      <ErrorMessage
+        title={`Unable to load ${type} information`}
+        message="Please try again later or contact support if the problem persists."
+      />
+    );
   }

73-83: Consider making single-item array requirement more explicit.

The table components receive arrays containing single items. Consider making this requirement more explicit in the component's type definitions or documentation.

// Add to type definitions
type SingleItemArray<T> = [T];

// Document the requirement
/**
 * @param symptoms - Single-item array containing the symptom to display
 */
interface SymptomTableProps {
  symptoms: SingleItemArray<Symptom>;
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 08ae3d8 and 47b6dac.

📒 Files selected for processing (2)
  • src/components/Facility/ConsultationDetails/QuestionnaireResponsesList.tsx (2 hunks)
  • src/components/Facility/ConsultationDetails/StructuredResponseView.tsx (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Cloudflare Pages: care-fe
🔇 Additional comments (5)
src/components/Facility/ConsultationDetails/StructuredResponseView.tsx (3)

11-19: LGTM! Type definitions enhance type safety.

The introduction of SupportedType and the use of StructuredQuestionType in the Props interface improves type safety and makes the component's requirements more explicit.


27-28: LGTM! Well-implemented type guard.

The type guard effectively narrows the StructuredQuestionType to SupportedType, providing runtime type safety.


39-55: LGTM! Well-structured query implementations.

The query implementations follow React Query best practices:

  • Proper query keys including the id
  • Conditional enabling based on type and id
  • Isolated queries for different data types
src/components/Facility/ConsultationDetails/QuestionnaireResponsesList.tsx (2)

13-16: LGTM! Import organization improves readability.

The grouped imports from the questionnaire types module enhance code organization.


269-269: Verify type assertion safety.

While the type assertion improves type safety by ensuring the type prop matches StructuredQuestionType, consider using a type guard instead of type assertion to validate the type at runtime.

Let's verify the structure of StructuredQuestionType and its usage:

✅ Verification successful

Type assertion is appropriate and safe in this context

The type assertion is necessary and safe here because:

  • It's converting from an optional structured_type to a required type prop
  • The component rendering logic ensures the type exists
  • StructuredQuestionType is a well-defined union of string literals
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the definition and usage of StructuredQuestionType

# Check the type definition
ast-grep --pattern 'type StructuredQuestionType = $_'

# Check other usages of this type in the codebase
rg -t typescript "StructuredQuestionType" -A 3 -B 3

Length of output: 644


Script:

#!/bin/bash
# Find the component's props and type usage context
ast-grep --pattern 'interface $_ {
  $$$
  type: $_
  $$$
}'

# Get more context around the type assertion
rg -g "*.{ts,tsx}" "type={type as StructuredQuestionType}" -B 10 -A 5

# Look for any runtime validation
rg -g "*.{ts,tsx}" "type.*StructuredQuestionType" -B 3 -A 3

Length of output: 10963

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Deploy-Failed Deplyment is not showing preview merge conflict pull requests with merge conflict
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant