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

Scribe for Questionnaire #9584

Closed
wants to merge 21 commits into from
Closed

Scribe for Questionnaire #9584

wants to merge 21 commits into from

Conversation

shivankacker
Copy link
Member

@shivankacker shivankacker commented Dec 26, 2024

Requires ohcnetwork/care_scribe_fe#6

Proposed Changes

  • Added scribe support for the new questionnaire module

@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 concise release notes:

  • Localization

    • Updated localization file with key modifications
    • Removed and added various translation keys
  • New Features

    • Introduced ScribeStructuredInput component for structured data entry
    • Enhanced input handling for various questionnaire types (allergies, diagnoses, medications, symptoms)
    • Added new Select component with improved option management
  • UI Improvements

    • Updated appointment details page to show patient details button for all appointment statuses
    • Modified route handlers to include subjectType for better context
  • Technical Enhancements

    • Added useValueInjection hook for dynamic value synchronization
    • Refactored select and input components for more flexible data handling

@shivankacker shivankacker requested a review from a team as a code owner December 26, 2024 23:59
Copy link
Contributor

coderabbitai bot commented Dec 26, 2024

Walkthrough

This pull request introduces a comprehensive refactoring of various components across the application, focusing on structured input handling and user interface improvements. The changes primarily involve introducing a new ScribeStructuredInput component, modifying localization files, and updating select and form components to use more streamlined input mechanisms. The modifications span multiple files, including questionnaire question types, utility functions, and routing configurations, with an emphasis on improving data entry and user interaction.

Changes

File Change Summary
public/locale/en.json Localization key modifications, removing and adding keys related to various features
src/Utils/scribe.tsx New ScribeStructuredInput component introduced
src/Utils/useValueInjectionObserver.tsx Added useValueInjection hook
src/components/Questionnaire/QuestionTypes/* Multiple question type components refactored to use ScribeStructuredInput
src/components/ui/select-util.tsx New Select component implementation
src/components/ui/switch.tsx Added useValueInjection hook integration
src/Routers/routes/ConsultationRoutes.tsx Added subjectType to route handlers

Sequence Diagram

sequenceDiagram
    participant User
    participant ScribeStructuredInput
    participant QuestionnaireForm
    participant OnChangeHandler

    User->>ScribeStructuredInput: Enter structured data
    ScribeStructuredInput->>OnChangeHandler: Trigger onChange
    OnChangeHandler->>QuestionnaireForm: Update questionnaire response
    QuestionnaireForm-->>User: Reflect updated data
Loading

Possibly related PRs

Suggested Reviewers

  • rithviknishad
  • bodhish

Poem

🐰 A Rabbit's Ode to Structured Input 🌟

With ScribeStructuredInput so neat,
Our data flows smooth, clean, and sweet
Hooks dancing, components align
Questionnaires now truly shine!
Code rabbit hops with pure delight 🎉


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.

@shivankacker shivankacker marked this pull request as draft December 26, 2024 23:59
Copy link

cloudflare-workers-and-pages bot commented Dec 27, 2024

Deploying care-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: fef419a
Status: ✅  Deploy successful!
Preview URL: https://05248833.care-fe.pages.dev
Branch Preview URL: https://form-field-scribe.care-fe.pages.dev

View logs

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Dec 28, 2024
Copy link

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

@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Dec 29, 2024
Copy link

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

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Dec 30, 2024
Base automatically changed from form-field-v1 to develop December 31, 2024 06:36
Copy link

netlify bot commented Dec 31, 2024

Deploy Preview for care-ohc ready!

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

@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Dec 31, 2024
@shivankacker shivankacker marked this pull request as ready for review December 31, 2024 09:11
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

🧹 Nitpick comments (10)
src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (2)

121-197: Prompt definition is quite extensive.
Consider splitting out the type definitions or using a dedicated schema to reduce the length of this prop. Keeping them separate can improve maintainability and readability.


198-264: Verify large example object is necessary as inline data.
Having a sizable example inline is helpful for devs, but it can clutter the production code. Consider referencing a separate file or using shortened placeholders if the complete example is not essential here.

src/Utils/scribe.tsx (1)

5-40: Validate JSON serialization overhead.
Outputting example and value as JSON is a neat approach for interop, but ensure the strings remain within practical size limits. If value grows large, consider lazy encoding or chunking to avoid performance hits.

src/components/ui/select-util.tsx (2)

13-22: Consider adding a generic type for the options.
Currently, the options prop is hardcoded to accept { label: React.ReactNode; value: string }[]. In cases where you might want to keep track of more complex metadata in each option, consider adding a generic type parameter for the options array to extend the flexibility of this component.


42-49: Be mindful of large JSON data in attributes.
data-cui-listbox-options serializes all props.options into a JSON string, which could become large if the list is lengthy. For performance, consider a more lightweight approach when dealing with large option sets (e.g., dynamic loading).

src/components/Questionnaire/QuestionTypes/DateTimeQuestion.tsx (1)

96-136: Ensure synergy between dayjs and ISO string transformations.
The child component triggers onChange with an ISO string. You convert it via dayjs(value).toDate(). Confirm that time zone offsets and user locale differences are handled consistently, especially if the user’s local time zone differs from the server's.

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

105-148: Watch for large arrays & partial updates.
When dealing with large arrays, each change triggers a re-render of the entire AllergyQuestion list. Depending on performance constraints, consider optimizing the update logic. For partial updates, a more granular approach within ScribeStructuredInput may improve efficiency.

src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx (1)

119-190: Prevent frequent re-renders with large data sets and object equality checks.
If the user has many medication statements, each slight edit might cause large re-renders. Consider using memoization or targeted updates. This could significantly improve performance in data-heavy scenarios.

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

149-166: Mapped encounter status options are clear and well-labeled

Providing user-friendly labels (e.g., "Planned", "In Progress") helps maintain clarity. Consider adding translations if internationalization is required elsewhere in the codebase.


Line range hint 347-375: Comprehensive dietary preference list

Providing multiple diet preference options covers a wide spectrum of patient needs. If additional preferences are observed in practice, consider injecting them dynamically from a backend or config for scalability.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c2ce66e and b964266.

📒 Files selected for processing (15)
  • public/locale/en.json (3 hunks)
  • src/Utils/scribe.tsx (1 hunks)
  • src/Utils/useValueInjectionObserver.tsx (1 hunks)
  • src/components/Patient/EncounterQuestionnaire.tsx (2 hunks)
  • src/components/Questionnaire/QuestionTypes/AllergyQuestion.tsx (3 hunks)
  • src/components/Questionnaire/QuestionTypes/ChoiceQuestion.tsx (2 hunks)
  • src/components/Questionnaire/QuestionTypes/DateTimeQuestion.tsx (3 hunks)
  • src/components/Questionnaire/QuestionTypes/DiagnosisQuestion.tsx (3 hunks)
  • src/components/Questionnaire/QuestionTypes/EncounterQuestion.tsx (6 hunks)
  • src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (2 hunks)
  • src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx (2 hunks)
  • src/components/Questionnaire/QuestionTypes/SymptomQuestion.tsx (3 hunks)
  • src/components/Questionnaire/QuestionnaireForm.tsx (1 hunks)
  • src/components/ui/select-util.tsx (1 hunks)
  • src/components/ui/switch.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • src/components/Questionnaire/QuestionnaireForm.tsx
  • public/locale/en.json
🔇 Additional comments (32)
src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (4)

20-20: Import usage looks valid.
The import from @/Utils/scribe appears correct and consistent with the file’s content.


106-119: Ensure onChange usage is consistent with form lifecycle.
The callback updates the questionnaire response, which is correct. However, confirm that all dependent states or parent components are updated accordingly when value changes.


265-283: Rendering existing medications.
The structure is clean and well-labeled. Just ensure the logic is covered by unit tests, particularly for removing or updating items in the list.


284-290: Seamless medication adding flow.
The approach is intuitive. Keep an eye out for concurrency edge cases if multiple adds can occur in quick succession.

src/Utils/scribe.tsx (1)

1-4: Hook usage is appropriate.
The useValueInjection import and usage is consistent with the intended design of structured input.

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

8-9: New import for plugin component.
This appears consistent with the new plugin-based architecture.


26-27: Plugin placement.
Embedding <PLUGIN_Component __name="Scribe" /> at this level is a flexible approach for extension. Double-check plugin integration order to ensure the correct lifecycle events fire.


28-55: Overall flow remains intact.
Wrapping the standard Page component and the QuestionnaireForm is sound. The onSubmit callback is unchanged, so no immediate concerns. Verify that plugin scripts do not block or alter the navigate flow inadvertently.

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

4-4: Switch to select-util.
The transition to select-util is straightforward. Ensure that any advanced features from the old select are still supported or re-implemented.


8-8: Removed unused import.
The removal of AnswerOption clarifies the code.


54-60: Ensure new value-binding logic works.
Replacing the old pattern with the simpler onChange prop is more readable. Just confirm that disabled and dynamic updates work as intended during form validation.

src/components/ui/switch.tsx (3)

6-7: Smart injection.
Importing useValueInjection suggests a robust approach for sync events.


11-16: Check for potential conflicts in onCheckedChange.
The usage of props.onCheckedChange?.(value === "true") is correct, but confirm it won’t conflict with or bypass any external state management logic that might also be toggling the checked state.


21-27: Data attributes for debugging & integration.
Exposing data attributes (data-cui-checkbox, data-cui-checked) is a good approach for testing. Just ensure these attributes don’t accidentally leak any sensitive info.

src/components/ui/select-util.tsx (2)

29-33: Verify correct cleanup and attribute usage.
useValueInjection sets data-cui-listbox-value on the element. Ensure that if element gets reset to null, or if onChange is triggered when value is null, no unexpected errors occur. A mild verification step is recommended.


56-60: Use stable keys for dynamic lists.
Keys are taken correctly from each option’s value property, which helps React efficiently manage these elements. This is a good practice.

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

2-2: Validate dayjs usage.
dayjs is a popular choice for date operations. Verify in other parts of the code that moment-based or standard Date manipulations are consistently replaced or updated to avoid confusion or duplication.


18-18: ScribeStructuredInput import.
The import suggests a strategy for structured or AI-based input. Ensure that any dynamic or user-input-driven transformations are tested for edge cases (e.g., invalid or incomplete ISO strings).

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

26-26: Structured AI-based input.
ScribeStructuredInput centralizes your logic for adding, deleting, or updating allergy data. Validate that all necessary transforms (e.g., mapping to/from allergies) are consistent and tested, given the added complexity.

src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx (1)

26-26: Verify side effects from AI-based scribe logic.
ScribeStructuredInput is used for medication statements. Confirm that all server or downstream consumers can handle the newly structured data, for instance by checking mandatory fields or data shape.

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

37-37: Good import organization for structured input

Importing ScribeStructuredInput here is consistent with the file’s usage and improves readability by segregating structured input logic into a dedicated component.


122-164: Excellent use of self-documenting prompt and example

By providing a detailed prompt and example object, you effectively guide users on how to manipulate symptom data. This self-documenting approach clarifies the expected structure and enhances maintainability.


362-362: Encapsulate domain-specific input logic within the custom component

Wrapping the symptoms table within <ScribeStructuredInput> centralizes the domain-specific input processing (create, update, remove) and fosters reusability for advanced structured data in the future.

src/components/Questionnaire/QuestionTypes/EncounterQuestion.tsx (5)

6-6: Select utility import offers better customization

Switching to the new Select from @/components/ui/select-util can provide improved extensibility and customization. Ensure the library’s usage remains consistent across other question types for uniform UX.


173-187: Consistent usage of typed values for encounter_class

Mapping typed values (e.g., 'amb' as EncounterClass) fosters type safety. This helps avoid string literal typos when updating encounter class in the future.


194-218: Ensure all priority options align with supported system codes

The extended list of priority values is beneficial. Verify that they match any corresponding backend enumerations to avoid mismatches or runtime errors.


Line range hint 269-299: Structured approach to updating hospitalization data

Applying partial updates (e.g., handleUpdateEncounter({ hospitalization: {...} })) ensures consistent handling of nested objects while avoiding accidental overwrites.


Line range hint 307-340: Conditionally rendering discharge disposition is appropriate

Showing “Discharge Disposition” only when the status is "completed" matches real-world workflow logic. This guards against invalid states in the UI.

src/Utils/useValueInjectionObserver.tsx (1)

56-74: New custom hook elegantly extends attribute observation

The useValueInjection hook combines useValueInjectionObserver and an onChange callback, creating a clean pattern for synchronizing DOM changes with React state. Verify that callers handle cases where domValue is undefined to avoid runtime errors.

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

37-37: Importing ScribeStructuredInput streamlines structured data input

Centralizing structured data handling in ScribeStructuredInput encourages reusability and keeps UI code more organized.


121-161: Reflective prompts and examples empower correct usage

Including a descriptive prompt and a real-world example strongly guides users in the correct input format for diagnoses. This reduces guesswork and potential data-entry errors.


337-337: End of structured input block maintains consistency

Terminating <ScribeStructuredInput> here without additional processing fosters a predictable pattern for these question components.

Comment on lines +120 to +132
prompt={`An array of objects of the following type: {
code: {
code: string,
display: string,
system: "http://snomed.info/sct"
},
clinical_status?: "active" | "inactive" | "resolved",
category?: "food" | "medication" | "environment" | "biologic",
criticality?: "low" | "high" | "unable-to-assess",
verification?: "unconfirmed" | "presumed" | "confirmed" | "refuted" | "entered-in-error"
last_occurrence?: YYYY-MM-DD string,
note?: string
}. Update existing data, delete existing data or append to the existing list as per the will of the user. Current date is ${new Date().toLocaleDateString()}`}
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

Whitelist or sanitize user-driven updates.
prompt suggests user instructions for editing structured data. Make sure your application defends against malicious or malformed data (e.g., unexpected property injection). Proper server-side validations are essential.

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Dec 31, 2024
Copy link

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

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

Line range hint 495-543: Revise STAT timing representation.

The STAT (immediate) frequency option uses period_unit: "s" which may not be the most appropriate representation for immediate administration. STAT medications typically don't have a recurring schedule.

Consider this alternative implementation:

 STAT: {
   display: "Imediately",
-  timing: { repeat: { frequency: 1, period: 1, period_unit: "s" } },
+  timing: { 
+    event: [new Date().toISOString()],  // Single administration time
+    repeat: undefined  // No repetition for STAT doses
+  },
 },
🧹 Nitpick comments (8)
src/components/Questionnaire/QuestionTypes/DateTimeQuestion.tsx (2)

104-104: Remove debug console.log statement.

Debug logging should be removed before merging to production.

-            console.log(value, date);

99-112: Consider timezone handling in the prompt.

The prompt mentions "minus 5 hour 30 minutes" which seems to hardcode a specific timezone offset. Consider making this dynamic based on the user's timezone.

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

105-120: Add type validation in the onChange handler.

Consider adding runtime type validation for the incoming value to ensure it matches the expected structure before updating the state.

 onChange={(value) => {
   if (value) {
+    // Add runtime type validation
+    if (!Array.isArray(value) || !value.every(item => 
+      item.code && typeof item.code.code === 'string' &&
+      typeof item.code.display === 'string' &&
+      item.code.system === 'http://snomed.info/sct'
+    )) {
+      console.error('Invalid allergy data structure');
+      return;
+    }
     setAllergies(value);
     updateQuestionnaireResponseCB({
src/components/Questionnaire/QuestionTypes/DiagnosisQuestion.tsx (3)

138-146: Improve prompt readability and validation.

The prompt structure could be improved for better readability and validation:

  1. Consider using a JSON schema format
  2. Add validation rules for required fields
  3. Include min/max length constraints for strings

147-161: Enhance example coverage.

The example only shows one scenario. Consider adding more examples that cover:

  • Different clinical statuses
  • Various verification statuses
  • Edge cases (e.g., minimal valid diagnosis)

Line range hint 163-339: Consider performance optimization for large datasets.

For better performance with large datasets, consider:

  1. Implementing virtualization for the table rows
  2. Debouncing the diagnosis search
  3. Memoizing the row components
src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx (1)

175-193: Consider using semantic HTML for the medication list.

While the implementation is functionally correct, consider using <dl> (description list) instead of <ul> for better semantic meaning, as each medication item contains key-value pairs.

-<ul className="space-y-2 divide-y-2 divide-gray-200 divide-dashed">
+<dl className="space-y-2 divide-y-2 divide-gray-200 divide-dashed">
   {medications.map((medication, index) => (
-    <li key={index}>
+    <div key={index}>
       <MedicationStatementItem
         medication={medication}
         disabled={disabled}
         onUpdate={(medication) =>
           handleUpdateMedication(index, medication)
         }
         onRemove={() => handleRemoveMedication(index)}
         index={index}
       />
-    </li>
+    </div>
   ))}
-</ul>
+</dl>
src/components/Questionnaire/QuestionTypes/SymptomQuestion.tsx (1)

122-166: Enhance date format specification in the prompt.

The prompt mentions "YYYY-MM-DD string" for onset_datetime, but it would be more precise to specify the exact format requirements and validation rules.

-          onset?: {
-            onset_datetime: YYYY-MM-DD string
-          },
+          onset?: {
+            onset_datetime: string // ISO 8601 date format (YYYY-MM-DD), must be <= current date
+          },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b964266 and fd7c909.

📒 Files selected for processing (6)
  • src/components/Questionnaire/QuestionTypes/AllergyQuestion.tsx (3 hunks)
  • src/components/Questionnaire/QuestionTypes/DateTimeQuestion.tsx (4 hunks)
  • src/components/Questionnaire/QuestionTypes/DiagnosisQuestion.tsx (3 hunks)
  • src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (4 hunks)
  • src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx (4 hunks)
  • src/components/Questionnaire/QuestionTypes/SymptomQuestion.tsx (3 hunks)
🔇 Additional comments (4)
src/components/Questionnaire/QuestionTypes/DateTimeQuestion.tsx (1)

40-44: LGTM! Clean state initialization.

The state initialization correctly handles both the existing date values and undefined cases.

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

122-134: Whitelist or sanitize user-driven updates.

The prompt suggests user instructions for editing structured data. Make sure your application defends against malicious or malformed data.

src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx (1)

Line range hint 64-194: Well-structured implementation of ScribeStructuredInput!

The integration is clean with proper state management, comprehensive prompt structure, and a clear example that matches the schema.

src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (1)

Line range hint 489-494: Verify period_unit values in FREQUENCY_OPTIONS.

The TODO comment suggests uncertainty about period_unit correctness. This is critical for medication timing.

✅ Verification successful

Period unit values in FREQUENCY_OPTIONS are correctly defined and consistent

The verification shows that:

  • The period_unit type is consistently defined as "s" | "min" | "h" | "d" | "wk" | "mo" | "a" across the codebase
  • All period_unit values used in FREQUENCY_OPTIONS are valid according to this type:
    • "d" (day) for BD (twice daily), HS, OD
    • "h" (hour) for Q4H (every 4 hours), Q6H, Q8H
    • "wk" (week) for weekly dosing
    • "s" (stat) for stat dosing

The TODO comment can be safely removed as the period units are correctly implemented and match the medication timing requirements.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for period_unit usage across the codebase to verify consistency

# Search for period_unit definitions and usages
rg -A 5 'period_unit.*[\'"](?:s|min|h|d|wk|mo|a)[\'"]'

# Search for any existing test files related to frequency options
fd -g '*test*' | xargs rg 'FREQUENCY_OPTIONS'

Length of output: 116


Script:

#!/bin/bash
# Search for period_unit definitions and usages with proper quotes
rg "period_unit.*['\"](?:s|min|h|d|wk|mo|a)['\"]"

# Search for FREQUENCY_OPTIONS definitions and usages
rg "FREQUENCY_OPTIONS" -A 5

# Search specifically for files containing both period_unit and FREQUENCY_OPTIONS
rg "period_unit|FREQUENCY_OPTIONS"

Length of output: 10399

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

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

Line range hint 191-213: Add error handling for diagnosis search

The diagnosis search doesn't handle API errors gracefully.

Consider adding error handling:

 <CommandEmpty>
-  {diagnosisSearch.loading
-    ? "Loading..."
-    : "No diagnoses found"}
+  {diagnosisSearch.loading ? "Loading..." :
+   diagnosisSearch.error ? "Error loading diagnoses" :
+   "No diagnoses found"}
 </CommandEmpty>
🧹 Nitpick comments (4)
.env (1)

17-17: Add protocol and consider environment-specific configuration

The URL format could be improved for better reliability:

  1. Add the protocol (http/https) prefix
  2. Consider making the port configurable
  3. Add separate configurations for different environments
-REACT_ENABLED_APPS=localhost:4173/ohcnetwork/care_scribe_fe
+REACT_ENABLED_APPS=http://localhost:${SCRIBE_PORT:-4173}/ohcnetwork/care_scribe_fe
src/components/Questionnaire/QuestionTypes/DiagnosisQuestion.tsx (3)

138-146: Extract system URLs and data structure into constants

The prompt hardcodes implementation details that should be maintained as constants:

  1. SNOMED CT system URL
  2. Data structure specification

Consider extracting these into constants:

const SNOMED_SYSTEM_URL = "http://snomed.info/sct";
const DIAGNOSIS_STRUCTURE = `{
  code: {"code": string, "display": string, "system": "${SNOMED_SYSTEM_URL}"},
  clinical_status: ...
}`;

147-161: Update example with a more appropriate date

The example uses a future date (2024-12-03) which might confuse users or the AI.

Consider using a recent past date in the example to avoid confusion:

-              onset_datetime: "2024-12-03",
+              onset_datetime: "2023-12-03",

Line range hint 277-286: Enhance date input accessibility

The date input lacks proper labeling and aria attributes.

Consider adding accessibility attributes:

 <input
   type="date"
   className="w-full rounded-md border p-2"
+  aria-label="Onset date"
+  id={`diagnosis-onset-${index}`}
   value={diagnosis.onset?.onset_datetime || ""}
   onChange={(e) =>
     updateDiagnosis(index, {
       onset: { onset_datetime: e.target.value },
     })
   }
   disabled={disabled}
 />
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fd7c909 and a279cd2.

📒 Files selected for processing (3)
  • .env (1 hunks)
  • src/components/Questionnaire/QuestionTypes/DiagnosisQuestion.tsx (3 hunks)
  • src/components/Questionnaire/QuestionTypes/SymptomQuestion.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Questionnaire/QuestionTypes/SymptomQuestion.tsx
🔇 Additional comments (2)
.env (1)

17-17: Coordinate deployment with care_scribe_fe PR #6

This change depends on care_scribe_fe PR #6. Ensure both PRs are deployed together to maintain functionality.

Run this script to verify the dependency:

src/components/Questionnaire/QuestionTypes/DiagnosisQuestion.tsx (1)

37-37: Verify the ScribeStructuredInput dependency

Since this component depends on care_scribe_fe repository (PR #6), ensure that:

  1. The dependency is properly configured in the project
  2. The version containing this component is specified
  3. The companion PR (care_scribe_fe#6) is merged first

Comment on lines 123 to 136
onChange={(value) => {
if (value) {
setDiagnoses(value);
updateQuestionnaireResponseCB({
...questionnaireResponse,
values: [
{
type: "diagnosis",
value,
},
],
});
}
}}
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

Add validation for AI-modified data structure

The onChange handler directly updates the state without validating the structure of the AI-modified data.

Consider adding validation:

const validateDiagnosis = (diagnosis: unknown): diagnosis is Diagnosis => {
  // Add type validation logic
  return true; // Implement proper validation
};

const handleChange = (value: unknown) => {
  if (Array.isArray(value) && value.every(validateDiagnosis)) {
    setDiagnoses(value);
    updateQuestionnaireResponseCB({
      ...questionnaireResponse,
      values: [{ type: "diagnosis", value }],
    });
  } else {
    console.error('Invalid diagnosis data structure');
  }
};

@github-actions github-actions bot added merge conflict pull requests with merge conflict and removed merge conflict pull requests with merge conflict labels Jan 2, 2025
Copy link

github-actions bot commented Jan 2, 2025

👋 Hi, @shivankacker,
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: 1

♻️ Duplicate comments (1)
src/components/Questionnaire/QuestionTypes/DiagnosisQuestion.tsx (1)

101-113: ⚠️ Potential issue

Add validation for AI-modified data structure

The onChange handler needs validation similar to the SymptomQuestion component.

Apply the same validation pattern as suggested in SymptomQuestion, but adapted for the Diagnosis type.

🧹 Nitpick comments (2)
src/components/Questionnaire/QuestionTypes/SymptomQuestion.tsx (1)

116-125: Enhance prompt with validation rules

The prompt could be more helpful by including validation rules and required field indicators.

-prompt={`An array of objects of the following type, based on the SNOMED CT Code for the applicable symptoms: {
+prompt={`An array of objects of the following type, based on the SNOMED CT Code for the applicable symptoms: {
-  code: {"code" : string, "display" : string, "system" : "http://snomed.info/sct"},
+  code: {"code" : string, "display" : string, "system" : "http://snomed.info/sct"}, // Required
-  clinical_status: "active" | "recurrence" | "relapse" | "inactive" | "remission" | "resolved",
+  clinical_status: "active" | "recurrence" | "relapse" | "inactive" | "remission" | "resolved", // Required
   verification_status: "unconfirmed" | "provisional" | "differential" | "confirmed" | "refuted" | "entered-in-error",
   severity?: "severe" | "moderate" | "mild",
   onset?: {
     onset_datetime: YYYY-MM-DD string
   },
   note?: string
-}
+} // Note: code and clinical_status are required fields
src/components/Questionnaire/QuestionTypes/DiagnosisQuestion.tsx (1)

141-169: Extract common UI patterns into shared components

Both SymptomQuestion and DiagnosisQuestion share similar UI patterns for handling notes, dropdowns, and layout. Consider extracting these into reusable components.

Create shared components for:

  1. The grid layout header
  2. The dropdown menu for actions
  3. The notes input section

Example for the action dropdown:

// src/components/Questionnaire/QuestionTypes/shared/ActionDropdown.tsx
interface ActionDropdownProps {
  disabled?: boolean;
  showNotes: boolean;
  onToggleNotes: () => void;
  onRemove: () => void;
}

export const ActionDropdown: React.FC<ActionDropdownProps> = ({
  disabled,
  showNotes,
  onToggleNotes,
  onRemove,
}) => {
  // Implementation here
};

Also applies to: 99-172

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a279cd2 and 77e7e1b.

📒 Files selected for processing (5)
  • public/locale/en.json (0 hunks)
  • src/components/Patient/EncounterQuestionnaire.tsx (2 hunks)
  • src/components/Questionnaire/QuestionTypes/DiagnosisQuestion.tsx (2 hunks)
  • src/components/Questionnaire/QuestionTypes/SymptomQuestion.tsx (2 hunks)
  • src/components/Questionnaire/QuestionnaireForm.tsx (1 hunks)
💤 Files with no reviewable changes (1)
  • public/locale/en.json
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/components/Patient/EncounterQuestionnaire.tsx
  • src/components/Questionnaire/QuestionnaireForm.tsx
🔇 Additional comments (1)
src/components/Questionnaire/QuestionTypes/SymptomQuestion.tsx (1)

30-30: Verify the ScribeStructuredInput import path

The import path assumes the Utils directory is at the root level. Let's verify this path exists.

✅ Verification successful

Import path for ScribeStructuredInput is correctly configured

The import path @/Utils/scribe is valid as verified by the presence of the file at src/Utils/scribe.tsx. The @ alias in the import statement typically maps to the src directory in the project configuration.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the existence of the scribe.tsx file
fd --type f "scribe.tsx$"

Length of output: 48

Comment on lines +102 to +114
onChange={(value) => {
if (value) {
updateQuestionnaireResponseCB({
...questionnaireResponse,
values: [
{
type: "symptom",
value,
},
],
});
}
}}
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

Add validation for AI-modified data structure

The onChange handler directly updates the state without validating the structure of the AI-modified data.

Add type validation:

-onChange={(value) => {
-  if (value) {
-    updateQuestionnaireResponseCB({
-      ...questionnaireResponse,
-      values: [
-        {
-          type: "symptom",
-          value,
-        },
-      ],
-    });
-  }
-}}
+onChange={(value) => {
+  const validateSymptom = (symptom: unknown): symptom is Symptom => {
+    if (!symptom || typeof symptom !== 'object') return false;
+    const s = symptom as Partial<Symptom>;
+    return (
+      s.code?.code !== undefined &&
+      s.code?.display !== undefined &&
+      s.code?.system !== undefined &&
+      s.clinical_status !== undefined
+    );
+  };
+
+  if (Array.isArray(value) && value.every(validateSymptom)) {
+    updateQuestionnaireResponseCB({
+      ...questionnaireResponse,
+      values: [{ type: "symptom", value }],
+    });
+  } else {
+    console.error('Invalid symptom data structure');
+  }
+}}
📝 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
onChange={(value) => {
if (value) {
updateQuestionnaireResponseCB({
...questionnaireResponse,
values: [
{
type: "symptom",
value,
},
],
});
}
}}
onChange={(value) => {
const validateSymptom = (symptom: unknown): symptom is Symptom => {
if (!symptom || typeof symptom !== 'object') return false;
const s = symptom as Partial<Symptom>;
return (
s.code?.code !== undefined &&
s.code?.display !== undefined &&
s.code?.system !== undefined &&
s.clinical_status !== undefined
);
};
if (Array.isArray(value) && value.every(validateSymptom)) {
updateQuestionnaireResponseCB({
...questionnaireResponse,
values: [{ type: "symptom", value }],
});
} else {
console.error('Invalid symptom data structure');
}
}}

@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Jan 2, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/components/Questionnaire/QuestionTypes/AllergyQuestion.tsx (1)

128-172: ⚠️ Potential issue

Ensure proper validation of structured data input.

The ScribeStructuredInput component accepts and processes structured data that could potentially contain malicious or malformed content.

Consider implementing the following safeguards:

  1. Add input validation before processing the onChange event
  2. Implement a type guard to ensure the value matches the expected structure
  3. Sanitize the data before updating the state

Example type guard implementation:

interface AllergyInputValidation {
  isValid: (value: unknown): value is AllergyIntolerance[] => {
    if (!Array.isArray(value)) return false;
    return value.every(item => (
      item.code?.code &&
      item.code?.display &&
      item.code?.system === "http://snomed.info/sct"
    ));
  }
}
🧹 Nitpick comments (3)
src/components/Questionnaire/QuestionTypes/AllergyQuestion.tsx (2)

157-170: Update example data to use a past date.

The example data shows a future date ("2024-12-11") which might confuse users or cause validation issues.

-            last_occurrence: "2024-12-11",
+            last_occurrence: "2023-12-11",

173-214: Consider performance optimization for large datasets.

The table structure is deeply nested within the ScribeStructuredInput component, which could impact performance with large datasets.

Consider these optimizations:

  1. Implement virtualization for large lists using a library like react-window
  2. Memoize the table rows using React.memo
  3. Consider pagination for better performance with large datasets

Example row memoization:

const MemoizedAllergyTableRow = React.memo(AllergyTableRow, 
  (prev, next) => prev.allergy === next.allergy
);
src/pages/Landing/LandingPage.tsx (1)

34-34: Use of dynamic query key for caching
Including searchQuery in the query key will cause the data to be refreshed each time the search text changes, which is likely intended. However, be conscious of how frequently this may trigger re-fetching if the user types quickly. Consider adding client-side debouncing if unnecessary re-fetches might be costly.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 77e7e1b and 53e37a9.

📒 Files selected for processing (4)
  • .env (1 hunks)
  • src/components/Questionnaire/QuestionTypes/AllergyQuestion.tsx (2 hunks)
  • src/components/Questionnaire/QuestionnaireForm.tsx (1 hunks)
  • src/pages/Landing/LandingPage.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/components/Questionnaire/QuestionnaireForm.tsx
  • .env
🔇 Additional comments (2)
src/components/Questionnaire/QuestionTypes/AllergyQuestion.tsx (1)

44-44: LGTM!

The import statement is correctly placed and follows the project's import conventions.

src/pages/Landing/LandingPage.tsx (1)

36-39: Verify server compatibility with additional query parameter
You have introduced a name: searchQuery parameter to the API request. Ensure the back-end endpoint supports filtering by “name” and that no performance concerns arise with large data sets. If server-side filtering is expensive, consider a client-side approach or pagination for large results.

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 (5)
src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (5)

55-59: Enhance type safety of state initialization

The state initialization could be more explicit about the expected type.

-  const [medications, setMedications] = useState<MedicationRequest[]>(() => {
-    return (
-      (questionnaireResponse.values?.[0]?.value as MedicationRequest[]) || []
-    );
-  });
+  const [medications, setMedications] = useState<MedicationRequest[]>(() => 
+    questionnaireResponse.values?.[0]?.value 
+      ? (questionnaireResponse.values[0].value as MedicationRequest[]) 
+      : []
+  );

116-129: Simplify onChange handler logic

The onChange handler can be more concise by leveraging optional chaining.

-        onChange={(value) => {
-          if (value) {
-            setMedications(value);
-            updateQuestionnaireResponseCB({
-              ...questionnaireResponse,
-              values: [
-                {
-                  type: "medication_request",
-                  value,
-                },
-              ],
-            });
-          }
-        }}
+        onChange={(value) => {
+          setMedications(value ?? []);
+          updateQuestionnaireResponseCB({
+            ...questionnaireResponse,
+            values: value ? [{ type: "medication_request", value }] : [],
+          });
+        }}

207-207: Use dynamic date formatting

The current date string in the prompt should use a consistent date format.

-        Update existing data, delete existing data or append to the existing list as per the will of the user. Current date is ${new Date().toLocaleDateString()}`}
+        Update existing data, delete existing data or append to the existing list as per the will of the user. Current date is ${new Date().toISOString().split('T')[0]}`}

280-289: Add error boundary for medication item rendering

The MedicationRequestItem component handles complex data structures and could benefit from error boundaries to prevent the entire form from crashing if individual items fail to render.

Consider wrapping the MedicationRequestItem with an error boundary:

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

// Inside the map function
<ErrorBoundary fallback={<div>Error loading medication {index + 1}</div>}>
  <MedicationRequestItem
    medication={medication}
    disabled={disabled}
    onUpdate={(medication) => handleUpdateMedication(index, medication)}
    onRemove={() => handleRemoveMedication(index)}
    index={index}
  />
</ErrorBoundary>

Line range hint 476-534: Consider internationalizing frequency options

The frequency display strings should be internationalized for better maintainability and localization support.

Consider moving the display strings to i18n files:

const FREQUENCY_OPTIONS = {
  BD: {
    display: t('medication.frequency.twice_daily'),
    timing: { repeat: { frequency: 2, period: 1, period_unit: "d" } },
  },
  // ... other options
} as const satisfies Record<
  string,
  {
    display: string;
    timing: MedicationRequest["dosage_instruction"][0]["timing"];
  }
>;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 53e37a9 and 3908e18.

📒 Files selected for processing (3)
  • public/locale/en.json (0 hunks)
  • src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (4 hunks)
  • src/components/Questionnaire/QuestionnaireForm.tsx (1 hunks)
💤 Files with no reviewable changes (1)
  • public/locale/en.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Questionnaire/QuestionnaireForm.tsx
🔇 Additional comments (2)
src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (2)

209-272: Review and sanitize example data

The example data contains specific medical information that might be sensitive. Consider using more generic examples.

✅ Verification successful

Replace sensitive medical data with generic examples

The verification confirms that the sensitive medical data appears only in this example and is not used elsewhere in the codebase (except for "dialysis" which appears in legitimate application features). To maintain data privacy and avoid potential sensitivity issues, consider replacing the current example with more generic medication and condition examples:

  • Replace "Ciprofloxacin and fluocinolone" with a generic medication name like "Medication A" or "Example Medication"
  • Replace specific anatomical terms ("Subretinal", "right deltoid muscle") with generic terms like "Oral route" and "Left arm"
  • Replace the specific condition "Acquired arteriovenous malformation..." with a generic condition like "Pain" or "Fever"
  • Consider using placeholder SNOMED CT codes or removing them if they're not essential for the example

The example should demonstrate the structure without exposing specific medical information.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if similar sensitive data exists elsewhere in the codebase
rg -i "ciprofloxacin|fluocinolone|arteriovenous" --type ts --type tsx

Length of output: 99


Script:

#!/bin/bash
# Check if similar sensitive medical data exists elsewhere in the codebase, fixing the file type issue
rg -i "ciprofloxacin|fluocinolone|arteriovenous"

# Also check for other potential medical terms from the example
rg -i "subretinal|deltoid|dialysis" 

# Look for similar medication request patterns
ast-grep --pattern 'medication: {
  code: $_,
  display: $_,
  system: "http://snomed.info/sct"
}'

Length of output: 1522


Line range hint 475-475: Address TODO comment regarding period_unit verification

The comment indicates uncertainty about the correctness of period_unit values.

Would you like me to help implement the verification logic for period_unit values?

✅ Verification successful

The period_unit values are correctly implemented and validated

After analyzing the codebase, I can confirm that the period_unit implementation is correct and properly constrained:

  1. The type definition in src/types/emr/medicationRequest.ts strictly defines allowed values: "s" | "min" | "h" | "d" | "wk" | "mo" | "a"
  2. The FREQUENCY_OPTIONS constant in MedicationRequestQuestion.tsx uses these values consistently:
    • Daily doses use "d" (BD, HS, OD, QOD)
    • Hourly doses use "h" (Q4H, QID, TID)
    • Weekly doses use "wk" (QWK)
    • Immediate/STAT uses "s"

The TODO comment can be safely removed as the period_unit values are properly implemented and match standard medical timing conventions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for period_unit usage and validation across the codebase
ast-grep --pattern 'period_unit: $_' 

Length of output: 38


Script:

#!/bin/bash
# Let's try different approaches to find period_unit related code
# Search for period_unit string in the codebase
rg -i "period_unit" -A 3 -B 3

# Also search for TODO comments related to period validation
rg -i "TODO.*period" -A 3 -B 3

Length of output: 10424

@shivankacker shivankacker self-assigned this Jan 3, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
src/Routers/routes/ConsultationRoutes.tsx (1)

42-42: Consider strongly typing the 'subjectType' prop.

Defining a union type such as 'encounter' | 'patient' or introducing a dedicated enum would improve readability and refactoring safety when passing subjectType to EncounterQuestionnaire.

src/components/Schedule/Appointments/AppointmentDetailsPage.tsx (1)

366-373: Great addition to maintain patient accessibility when the appointment is no longer active.

Providing a "view patient" button ensures staff can quickly access patient data even for canceled or completed appointments. As an optional enhancement, consider showing a small note to clarify that the appointment cannot be further acted upon (e.g., rebook, check-in, etc.) in its current state, to avoid confusion.

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

101-101: Remove debug console.log statement.

The console.log statement should be removed before merging to production.

-            console.log(value, date);

106-106: Improve the prompt clarity for better AI understanding.

The current prompt string could be improved for better clarity and AI comprehension:

-        prompt={`A date in ISO format, minus 5 hour 30 minutes in the following format : {date: datestring}. Current time for your reference is ${new Date().toISOString()}`}
+        prompt={`A date in ISO format (e.g., "2024-01-25T14:30:00.000Z"). The date should be provided in the following structure: { date: "ISO_DATE_STRING" }. Note: The system time zone is UTC-5:30. Current time for reference: ${new Date().toISOString()}`}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3908e18 and 7cc5e59.

📒 Files selected for processing (5)
  • src/Routers/routes/ConsultationRoutes.tsx (1 hunks)
  • src/components/Questionnaire/QuestionTypes/DateTimeQuestion.tsx (3 hunks)
  • src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (2 hunks)
  • src/components/Questionnaire/QuestionnaireForm.tsx (2 hunks)
  • src/components/Schedule/Appointments/AppointmentDetailsPage.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Questionnaire/QuestionnaireForm.tsx
🔇 Additional comments (4)
src/components/Questionnaire/QuestionTypes/DateTimeQuestion.tsx (1)

96-142: LGTM! ScribeStructuredInput integration looks good.

The integration of ScribeStructuredInput maintains the existing functionality while adding AI-powered input capabilities. The component properly handles:

  • Value synchronization with the questionnaire response
  • Preservation of the existing UI elements
  • Proper date formatting and conversion
src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (3)

115-257: Well-structured prompt and example for AI guidance.

The prompt and example are comprehensive and well-documented, including:

  • Clear type definitions with proper JSDoc comments
  • Detailed example with realistic values
  • Complete coverage of all possible fields

260-289: LGTM! ScribeStructuredInput integration maintains UI functionality.

The integration successfully:

  • Preserves the existing UI components and functionality
  • Maintains the medication list management
  • Properly handles the ValueSetSelect component

Line range hint 449-449: Verify period_unit values in FREQUENCY_OPTIONS.

There's a TODO comment indicating that period_unit values need verification. Let's verify the implementation across the codebase.

✅ Verification successful

All period_unit values in FREQUENCY_OPTIONS are valid and consistent

The verification shows that:

  1. The type definition in src/types/emr/medicationRequest.ts correctly defines valid period units as: "s" | "min" | "h" | "d" | "wk" | "mo" | "a"
  2. All period_unit values used in FREQUENCY_OPTIONS are within this set:
    • "d" for BD (twice daily), HS (night only), OD (once daily), QOD (alternate day)
    • "h" for Q4H (4th hourly), QID (6th hourly), TID (8th hourly)
    • "wk" for QWK (once a week)
    • "s" for STAT (immediately)

The implementation is consistent with the type definition and uses appropriate units for each frequency option.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for period_unit usage to verify consistency
echo "Searching for period_unit usage patterns..."
rg "period_unit.*[\"'](?:s|min|h|d|wk|mo|a)[\"']" -g "*.{ts,tsx,js,jsx}"

# Search for FREQUENCY_OPTIONS usage
echo "Searching for FREQUENCY_OPTIONS usage..."
ast-grep --pattern 'const FREQUENCY_OPTIONS = $_'

Length of output: 6535

Copy link

github-actions bot commented Jan 3, 2025

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

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

cypress bot commented Jan 7, 2025

CARE    Run #4175

Run Properties:  status check failed Failed #4175  •  git commit fef419a08c: Scribe for Questionnaire
Project CARE
Branch Review form-field-scribe
Run status status check failed Failed #4175
Run duration 01m 46s
Commit git commit fef419a08c: Scribe for Questionnaire
Committer Shivank Kacker
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

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/Questionnaire/QuestionTypes/DiagnosisQuestion.tsx (1)

99-169: LGTM! Consider enhancing the example with more diverse cases.

The integration of ScribeStructuredInput is well-implemented with clear prompts and examples. The table view effectively maintains the existing UI while adding AI capabilities.

Consider expanding the example to include:

  • A diagnosis with multiple notes
  • A diagnosis with different clinical and verification statuses
  • A diagnosis without an onset date
    This would help users understand the full range of valid inputs.
src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (2)

120-196: Simplify the prompt for better readability.

The prompt uses TypeScript-specific syntax which might be confusing for non-technical users. Consider using a more natural language format.

Example:

-          status?: "active" | "on-hold" | "ended" | "stopped" | "completed" | "cancelled" | "entered-in-error" | "draft" | "unknown",
+          status?: one of: "active", "on-hold", "ended", "stopped", "completed", "cancelled", "entered-in-error", "draft", "unknown",

198-261: Provide a simpler, more common example.

The current example uses a complex medication with uncommon route and method. Consider using a more typical use case.

Example:

-              display: "Ciprofloxacin and fluocinolone only product in otic dose form",
-              route: {
-                code: "58831000052108",
-                display: "Subretinal route",
+              display: "Paracetamol 500mg tablet",
+              route: {
+                code: "26643006",
+                display: "Oral route",
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7cc5e59 and fef419a.

📒 Files selected for processing (9)
  • public/locale/en.json (0 hunks)
  • src/components/Patient/EncounterQuestionnaire.tsx (2 hunks)
  • src/components/Questionnaire/QuestionTypes/AllergyQuestion.tsx (2 hunks)
  • src/components/Questionnaire/QuestionTypes/DiagnosisQuestion.tsx (2 hunks)
  • src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (3 hunks)
  • src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx (4 hunks)
  • src/components/Questionnaire/QuestionTypes/SymptomQuestion.tsx (2 hunks)
  • src/components/Questionnaire/QuestionnaireForm.tsx (2 hunks)
  • src/components/Schedule/Appointments/AppointmentDetailsPage.tsx (1 hunks)
💤 Files with no reviewable changes (1)
  • public/locale/en.json
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/components/Questionnaire/QuestionnaireForm.tsx
  • src/components/Patient/EncounterQuestionnaire.tsx
  • src/components/Questionnaire/QuestionTypes/MedicationStatementQuestion.tsx
  • src/components/Questionnaire/QuestionTypes/AllergyQuestion.tsx
  • src/components/Questionnaire/QuestionTypes/SymptomQuestion.tsx
🔇 Additional comments (2)
src/components/Schedule/Appointments/AppointmentDetailsPage.tsx (1)

375-382: LGTM! Improved user experience for completed appointments.

The addition of the "View Patient" button for completed appointments enhances accessibility while maintaining UI consistency.

src/components/Questionnaire/QuestionTypes/MedicationRequestQuestion.tsx (1)

Line range hint 104-281: LGTM! Well-structured integration of ScribeStructuredInput.

The implementation effectively combines AI-powered input with the existing UI for medication management.

@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, @shivankacker,
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.

@gigincg
Copy link
Member

gigincg commented Jan 8, 2025

Closing in Favour of #9636

@gigincg gigincg closed this Jan 8, 2025
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 needs review needs testing work-in-progress
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants