Skip to content

ENG-500 Support for creating multiple diagnostic reports in a service request#16455

Open
NikhilA8606 wants to merge 9 commits into
developfrom
ENG-500-support-for-creating-multiple-diagnostic-reports-in-a-service-request
Open

ENG-500 Support for creating multiple diagnostic reports in a service request#16455
NikhilA8606 wants to merge 9 commits into
developfrom
ENG-500-support-for-creating-multiple-diagnostic-reports-in-a-service-request

Conversation

@NikhilA8606

@NikhilA8606 NikhilA8606 commented Jun 16, 2026

Copy link
Copy Markdown
Member

Proposed Changes

ENG-500
Figma link: https://www.figma.com/design/Z93EYKSa1MdBmXndsMBJSQ/Care---Master?node-id=40865-19149&t=94gI7vbM9r8kx6hY-1

Screen record:

Screen.Recording.2026-06-16.at.11.31.07.AM.mov

Merge Checklist

  • Add specs that demonstrate the bug or test the new feature.
  • Update product documentation.
  • Ensure that UI text is placed in I18n files.
  • Prepare a screenshot or demo video for the changelog entry and attach it to the issue.
  • Request peer reviews.
  • Complete QA on mobile devices.
  • Complete QA on desktop devices.
  • Add or update Playwright tests for related changes

Summary by CodeRabbit

Release Notes

  • New Features
    • Create and review multiple diagnostic reports in the same workflow, with per-report editing and approval.
  • Improvements
    • Report creation now checks specimen readiness and provides guidance when required items are missing.
    • Updated save/approve behavior for preliminary vs final reports, including clearer enabled/disabled states, improved loading behavior, and more precise file/result handling.
  • Localization
    • Updated English text with new prompts for report type selection and clearer error/success messages (including {{error}} details).

@NikhilA8606 NikhilA8606 requested review from a team and Copilot June 16, 2026 06:02
@netlify

netlify Bot commented Jun 16, 2026

Copy link
Copy Markdown

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 41bb2fa
🔍 Latest deploy log https://app.netlify.com/projects/care-ohc/deploys/6a3d0e1094150e00088b6d20
😎 Deploy Preview https://deploy-preview-16455.preview.ohc.network
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

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

@coderabbitai

coderabbitai Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Updates diagnostic report creation and review to operate per report entry, with status-gated editing, per-report queries and mutations, upload input IDs, and new locale strings for report creation, approval, and review states.

Changes

Diagnostic Report Multi-Report Refactor

Layer / File(s) Summary
i18n strings
public/locale/en.json
Adds another_diagnostic_report, failed_to_approve_diagnostic_report, failed_to_save_test_results, review_test_results, select_report_type_to_create, and test_results_saved_successfully; updates failed_to_create_diagnostic_report and result_review.
Service request report filtering
src/pages/Facility/services/serviceRequests/ServiceRequestShow.tsx
Filters out final diagnostic reports for the form and always renders DiagnosticReportForm when observation requirements exist.
File upload input id
src/hooks/useFileUpload.tsx
Adds optional inputId to the hook options and uses it for the file input element when provided.
Diagnostic report form container
src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx
Reworks the form around collected-specimen and multi-code state, renders existing reports directly, gates creation, and rewrites the collapsed create form for multi-report selection.
Diagnostic report item save flow
src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx
Binds conclusion and file mutations to report.id, updates submit behavior, clears upload state on close, and narrows submission state to mutation activity.
Diagnostic report item UI
src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx
Updates item headers and status badges from the current report, and gates editing, upload controls, and saved-results actions by report status.
Diagnostic report review items
src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx
Renders a review item per diagnostic report, fetches full report/files per item, and uses report-detail state for approval, conclusion editing, and review visibility.

Suggested labels

Type Changes

Suggested reviewers

  • Jacobjeevan
  • nihal467
  • amjithtitus09
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the main feature: multiple diagnostic reports in a service request.
Description check ✅ Passed The description includes the issue reference, design/screen-record links, and the merge checklist required by the template.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ENG-500-support-for-creating-multiple-diagnostic-reports-in-a-service-request

Comment @coderabbitai help to get the list of available commands.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR extends the Service Request diagnostic report workflow to support multiple diagnostic reports per request, updating both the entry form and the review UI to render and operate on each report independently.

Changes:

  • Render diagnostic report entry/review UI as a list of per-report components instead of only using the latest report.
  • Add UI for creating additional diagnostic reports (with optional report-type selection based on activityDefinition.diagnostic_report_codes).
  • Update/enhance i18n strings to support the new UI text.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 8 comments.

File Description
src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx Refactors review UI to render one collapsible review panel per diagnostic report and adjusts queries/actions per report.
src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx Refactors entry UI to render one collapsible form per report and adds UI to create additional reports (with report-type selection).
public/locale/en.json Adds/updates translation strings for the multi-report workflow UI.
Comments suppressed due to low confidence (1)

src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx:1240

  • With multiple diagnostic reports rendered, reusing id="conclusion" / htmlFor="conclusion" creates duplicate IDs and breaks label association for assistive tech. Make the conclusion field IDs unique per report.
                      <Label
                        htmlFor="conclusion"
                        className="text-base font-semibold text-gray-950"
                      >
                        {t("conclusion")}

Comment thread src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx Outdated
Comment thread src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx Outdated
Comment thread public/locale/en.json Outdated
@greptile-apps

greptile-apps Bot commented Jun 16, 2026

Copy link
Copy Markdown

Greptile Summary

This PR refactors the diagnostic report workflow to support creating and managing multiple reports within a single service request. The core change extracts per-report state into DiagnosticReportItem and DiagnosticReportReviewItem sub-components so each report has independent observation, conclusion, and file-upload state.

  • useFileUpload gains an inputId override to prevent duplicate HTML id attributes when multiple report cards are rendered simultaneously.
  • ServiceRequestShow now filters out finalized reports before passing them to DiagnosticReportForm, leaving the review section (DiagnosticReportReview) to display the full list.
  • Locale strings are updated with {{error}} interpolation in failure messages and new keys for the multi-report selection flow.

Confidence Score: 3/5

Two defects in DiagnosticReportForm should be fixed before merging: one shows a success toast on save-conclusion failure, and the other creates duplicate HTML ids when multiple reports are open at once.

The refactor correctly isolates per-report state and fixes the file-input ID collision, but the new DiagnosticReportItem component still calls toast.success inside its onError handler and uses a hardcoded id=conclusion that will be duplicated in the DOM whenever more than one preliminary report is rendered.

src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx — the onError toast variant and the conclusion textarea ID need to be corrected before this ships.

Important Files Changed

Filename Overview
src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx Large refactor extracting per-report state into DiagnosticReportItem; fixes file-input ID duplication but introduces a duplicate conclusion textarea ID and retains the toast.success-on-error bug in the new component.
src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx Correctly refactored into a DiagnosticReportReviewItem sub-component per report; conclusion textarea ID is properly scoped to report.id; disableEdit propagation fixed.
src/pages/Facility/services/serviceRequests/ServiceRequestShow.tsx Adds activeDiagnosticReports filter (non-final only) passed to DiagnosticReportForm; DiagnosticReportReview still receives all reports — looks intentional and correct.
src/hooks/useFileUpload.tsx Adds optional inputId override to prevent duplicate file input IDs when the hook is used in multiple concurrent components.
public/locale/en.json Adds i18n keys for new multi-report UI strings and error messages with {{error}} interpolation.
tests/facility/patient/encounter/serviceRequests/ServiceRequestCreate.spec.ts Test updated to handle the now-collapsed Test Results Entry card before interacting with the report-type dropdown.
tests/setup/patientAccount.setup.ts Uses .first() to handle multiple Go to account buttons in the DOM.

Reviews (7): Last reviewed commit: "cleanups" | Re-trigger Greptile

Comment thread public/locale/en.json Outdated
Comment thread src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx Outdated
Comment thread public/locale/en.json Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 9

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx (1)

369-371: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Bug: toast.success used in error handler should be toast.error.

The onError callback incorrectly uses toast.success to display the failure message, which will show a success toast for an error condition.

      onError: () => {
-       toast.success(t("failed_to_update_conclusion"));
+       toast.error(t("failed_to_update_conclusion"));
      },
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`
around lines 369 - 371, In the onError callback within DiagnosticReportForm
component, replace the toast.success call with toast.error to properly display
an error notification when the conclusion update fails. This ensures that error
conditions show error toasts rather than success toasts to users.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@public/locale/en.json`:
- Line 5071: Fix the spelling error in the review_test_results string value
where "Reult" is misspelled. Change it to "Result" so the user-facing string
reads "Review Test Result" instead of "Review Test Reult".
- Line 5537: The select_report_type_to_create string in the locale file is
grammatically awkward and confusing due to the repetition and unclear phrasing.
Rewrite this user-facing instruction to be clear and grammatically correct. The
new text should clearly tell users to select a diagnostic report type and then
create a report, without awkward quotation marks or repeated words, using simple
and direct language that guides the user action.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`:
- Around line 158-162: Replace all hardcoded English toast message strings with
translation keys using the t() function in DiagnosticReportForm.tsx. At lines
158-162 in the onError handler within the mutation, replace the hardcoded
failure message string with a call to t() using the key
"failed_to_create_diagnostic_report" and pass the error message as a parameter.
At lines 338-351, replace the hardcoded success message "Test results saved
successfully" with t("test_results_saved_successfully") and replace the
hardcoded failure message string in the error handler with a call to t() using
the key "failed_to_save_test_results" and pass the error message as a parameter.
For both locations, use t("unknown_error") as a fallback when the error message
is unavailable, consistent with i18n requirements.
- Around line 733-747: The upsertObservations and updateDiagnosticReport
mutations are executed sequentially without coordination, causing them to run in
parallel. If upsertObservations fails, updateDiagnosticReport will still
execute, leaving the diagnostic report in an inconsistent state. Fix this by
ensuring updateDiagnosticReport only executes after upsertObservations succeeds.
Either use mutateAsync with await to chain the mutations, or move the
updateDiagnosticReport call into the onSuccess callback of the
upsertObservations mutation. This ensures data consistency by preventing
updateDiagnosticReport from executing if the observations upsert operation
fails.
- Around line 1306-1312: The variables hasCollectedSpecimens and
isMultipleDiagnosticReport are being computed identically in both the parent
component and the DiagnosticReportForm child component. To follow DRY principles
and ensure consistency, remove the duplicate computations from
DiagnosticReportForm (the const declarations for hasCollectedSpecimens based on
activityDefinition.specimen_requirements and specimens, and
isMultipleDiagnosticReport based on activityDefinition.diagnostic_report_codes).
Instead, compute these values once in the parent component and pass them as
props to DiagnosticReportForm. Update the DiagnosticReportForm component
signature to accept these two values as props and use the passed-in values
instead of computing them locally.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx`:
- Around line 206-208: The Badge component and status-driven actions (render
gates for "view report" and approve actions) in DiagnosticReportReview.tsx are
using report.status from the stale list data instead of the fresher reportDetail
object. Replace report.status with the status from reportDetail at lines 206-208
and also at lines 294-331 where similar status checks are used for conditional
rendering and actions, ensuring all UI elements reflect the fetched detail data
consistently rather than potentially stale source data.
- Around line 163-167: The empty-state check for observations in the condition
block does not filter out ENTERED_IN_ERROR observations, while the table that
renders those observations applies this filter. This causes reports containing
only entered-in-error observations to display as non-empty with blank results.
Update the observation length check in the condition to filter out any
observations with ENTERED_IN_ERROR status before evaluating the length, matching
the filtering logic applied to the table rendering below. Apply the same
filtering logic at all affected locations where the raw observation length is
evaluated to determine visibility.
- Around line 102-106: The conclusion input field at line 267 (and related area
at lines 266-268) uses a fallback value logic that re-injects the server value
when the user clears the field, preventing empty edits from being representable
in UI state. Remove the fallback to reportDetail.conclusion in the value prop of
the input field—change the value binding from value={conclusion ||
reportDetail.conclusion || ""} to value={conclusion || ""} so that when users
clear the conclusion field, the empty state persists without being overwritten
by the server value.
- Around line 144-147: The toast.error call in the onError handler of
DiagnosticReportReview.tsx is using hardcoded English strings instead of i18next
translation keys. Add two new translation keys to public/locale/en.json: one for
the main error message template that accepts an error parameter (like
"diagnostic_report_approve_failed"), and one for the fallback unknown error text
(like "unknown_error"). Then update the toast.error call in the onError handler
to use i18next.t() to retrieve the localized message, passing the error text as
a parameter to the translation template.

---

Outside diff comments:
In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`:
- Around line 369-371: In the onError callback within DiagnosticReportForm
component, replace the toast.success call with toast.error to properly display
an error notification when the conclusion update fails. This ensures that error
conditions show error toasts rather than success toasts to users.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: bf6bbacd-e990-42e4-a76b-8cf598ade0b9

📥 Commits

Reviewing files that changed from the base of the PR and between 5466816 and 5fcab8e.

📒 Files selected for processing (3)
  • public/locale/en.json
  • src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx
  • src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx

Comment thread public/locale/en.json Outdated
Comment thread public/locale/en.json Outdated
Comment thread src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx Outdated
Comment thread src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx Outdated
Comment thread src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx Outdated
@github-actions

github-actions Bot commented Jun 16, 2026

Copy link
Copy Markdown

🎭 Playwright Test Results

Status: ✅ Passed
Test Shards: 3

Metric Count
Total Tests 328
✅ Passed 328
❌ Failed 0
⏭️ Skipped 0

📊 Detailed results are available in the playwright-final-report artifact.

Run: #9784

@greptile-apps

greptile-apps Bot commented Jun 19, 2026

Copy link
Copy Markdown

Want your agent to iterate on Greptile's feedback? Try greploops.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jun 19, 2026

Copy link
Copy Markdown

Deploying care-preview with  Cloudflare Pages  Cloudflare Pages

Latest commit: 41bb2fa
Status: ✅  Deploy successful!
Preview URL: https://3e5ca66a.care-preview-a7w.pages.dev
Branch Preview URL: https://eng-500-support-for-creating.care-preview-a7w.pages.dev

View logs

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 6 comments.

Comments suppressed due to low confidence (1)

src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx:376

  • Error handling currently shows a success toast on failure. This makes it hard for users to understand that the save failed.
      },
      onError: () => {
        toast.success(t("failed_to_update_conclusion"));
      },
    });

Comment thread src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx (2)

373-375: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Bug: toast.success used in error handler will mislead users on failure.

The onError callback incorrectly uses toast.success instead of toast.error. When the conclusion update fails, users will see a success-styled notification with a failure message, which is confusing and incorrect.

Proposed fix
      onError: () => {
-        toast.success(t("failed_to_update_conclusion"));
+        toast.error(t("failed_to_update_conclusion"));
      },
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`
around lines 373 - 375, In the onError callback for the conclusion update
operation in DiagnosticReportForm, replace the toast.success method call with
toast.error. Keep the same translation key "failed_to_update_conclusion" but
ensure the notification displays as an error-styled toast instead of a
success-styled one, so users receive the correct visual feedback when the
conclusion update fails.

1288-1309: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Type declares specimens prop but it's neither destructured nor used.

The type at line 1302 declares specimens: SpecimenRead[] as required, yet the component doesn't destructure or use it (lines 1288-1295). The parent still passes specimens at line 271. Since hasCollectedSpecimens is now computed by the parent and passed as a prop, the specimens prop is no longer needed.

Proposed fix

Remove specimens from the type definition and stop passing it from the parent:

 const CreateDiagnosticReportForm = ({
   activityDefinition,
   isCreatingReport,
   disableEdit,
   serviceRequestId,
   handleCreateReport,
   hasCollectedSpecimens,
   isMultipleDiagnosticReport,
 }: {
   activityDefinition?: {
     diagnostic_report_codes?: Code[];
     classification?: string;
     specimen_requirements?: SpecimenDefinitionRead[];
   };
-  specimens: SpecimenRead[];
   isCreatingReport: boolean;
   disableEdit: boolean;
   serviceRequestId: string;
   handleCreateReport: (code?: Code) => void;
   hasCollectedSpecimens: boolean;
   isMultipleDiagnosticReport: boolean;
 }) => {

And in the parent (around line 271):

       <CreateDiagnosticReportForm
         hasCollectedSpecimens
         isMultipleDiagnosticReport
         activityDefinition={activityDefinition}
-        specimens={specimens}
         isCreatingReport={isCreatingReport}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`
around lines 1288 - 1309, The CreateDiagnosticReportForm component's type
definition declares a required specimens prop of type SpecimenRead[], but this
prop is neither destructured in the function parameters nor used anywhere in the
component. Since the parent component now computes and passes
hasCollectedSpecimens directly instead of relying on the specimens prop, you
should remove the specimens property from the type definition of
CreateDiagnosticReportForm and remove the specimens prop being passed from the
parent component where it calls CreateDiagnosticReportForm around line 271.
♻️ Duplicate comments (1)
src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx (1)

160-162: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Hardcoded "Unknown error" fallback violates i18n requirements.

The main error message correctly uses the translation key, but the fallback string is still hardcoded English. Per coding guidelines, all literal strings must use i18next.

Proposed fix
          t("failed_to_create_diagnostic_report", {
-            error: err.message || "Unknown error",
+            error: err.message || t("unknown_error"),
          }),
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`
around lines 160 - 162, The hardcoded "Unknown error" string in the error
translation call violates i18n requirements. In the DiagnosticReportForm.tsx
file where the failed_to_create_diagnostic_report translation is being used,
replace the hardcoded "Unknown error" fallback string with a proper translation
key using the t() function, such as t("unknown_error") or an appropriate
translation key that matches your translation file structure. This ensures all
user-facing strings are properly internationalized.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx`:
- Line 90: The conclusion state is initialized only once from the report prop at
line 90, but when detail data loads asynchronously with a non-empty conclusion
value, the local state remains empty while the UI displays the actual conclusion
via fallback. This causes a mismatch where approving at lines 151-156 submits
the empty conclusion state, overwriting the stored data. Add a useEffect hook
that depends on the report object and updates the conclusion state whenever
report.conclusion changes, ensuring the local state stays synchronized with the
actual loaded data before submission occurs.

---

Outside diff comments:
In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`:
- Around line 373-375: In the onError callback for the conclusion update
operation in DiagnosticReportForm, replace the toast.success method call with
toast.error. Keep the same translation key "failed_to_update_conclusion" but
ensure the notification displays as an error-styled toast instead of a
success-styled one, so users receive the correct visual feedback when the
conclusion update fails.
- Around line 1288-1309: The CreateDiagnosticReportForm component's type
definition declares a required specimens prop of type SpecimenRead[], but this
prop is neither destructured in the function parameters nor used anywhere in the
component. Since the parent component now computes and passes
hasCollectedSpecimens directly instead of relying on the specimens prop, you
should remove the specimens property from the type definition of
CreateDiagnosticReportForm and remove the specimens prop being passed from the
parent component where it calls CreateDiagnosticReportForm around line 271.

---

Duplicate comments:
In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`:
- Around line 160-162: The hardcoded "Unknown error" string in the error
translation call violates i18n requirements. In the DiagnosticReportForm.tsx
file where the failed_to_create_diagnostic_report translation is being used,
replace the hardcoded "Unknown error" fallback string with a proper translation
key using the t() function, such as t("unknown_error") or an appropriate
translation key that matches your translation file structure. This ensures all
user-facing strings are properly internationalized.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: cae703b9-61e9-4e8f-8203-ec4ad6200062

📥 Commits

Reviewing files that changed from the base of the PR and between a8f3809 and 0d1dc49.

📒 Files selected for processing (3)
  • public/locale/en.json
  • src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx
  • src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx

@nihal467 nihal467 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

  • go through all the AI comments, and resolve it before the QA review

Copilot AI review requested due to automatic review settings June 23, 2026 09:34
@NikhilA8606 NikhilA8606 marked this pull request as ready for review June 23, 2026 09:35
Comment thread src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx Outdated

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 4 out of 4 changed files in this pull request and generated 9 comments.

Comments suppressed due to low confidence (2)

src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx:1250

  • Like the review component, each report form uses htmlFor="conclusion" / id="conclusion". Rendering multiple reports will create duplicate ids and breaks label-to-control association. Use a unique id per report.
                      <Label
                        htmlFor="conclusion"
                        className="text-base font-semibold text-gray-950"
                      >
                        {t("conclusion")}
                      </Label>
                      <textarea
                        id="conclusion"
                        className="w-full field-sizing-content focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500 rounded-lg border border-gray-300 p-2"

src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx:343

  • This success toast is a hard-coded English string; UI text should go through i18n (especially since this PR adds several new i18n keys already).
      onSuccess: () => {
        toast.success("Test results saved successfully");

Comment thread src/pages/Facility/services/serviceRequests/ServiceRequestShow.tsx Outdated
Comment thread src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx Outdated
Comment thread public/locale/en.json
Comment thread public/locale/en.json
Comment thread public/locale/en.json

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (5)
src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx (5)

375-377: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Show an error toast when conclusion update fails.

onError currently calls toast.success, so failed conclusion updates are reported as successful.

🐛 Proposed fix
       onError: () => {
-        toast.success(t("failed_to_update_conclusion"));
+        toast.error(t("failed_to_update_conclusion"));
       },
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`
around lines 375 - 377, In the DiagnosticReportForm component, the onError
callback is incorrectly calling toast.success instead of toast.error when
conclusion update fails. Fix this by changing the toast.success method call to
toast.error in the onError handler to properly display an error notification
when the conclusion update fails, ensuring the message with the key
"failed_to_update_conclusion" is shown as an error toast rather than a success
toast.

386-389: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Invalidate the uploaded-files query after upload.

The file list is fetched with ["files", "diagnostic_report", report.id], but upload success only invalidates ["diagnosticReport", report.id], so the uploaded-files table can stay stale.

🐛 Proposed fix
     onUpload: () => {
       queryClient.invalidateQueries({
         queryKey: ["diagnosticReport", report.id],
       });
+      queryClient.invalidateQueries({
+        queryKey: ["files", "diagnostic_report", report.id],
+      });
     },
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`
around lines 386 - 389, The onUpload callback in DiagnosticReportForm is only
invalidating the ["diagnosticReport", report.id] query key, but the uploaded
files list is fetched with a different query key ["files", "diagnostic_report",
report.id]. After a successful file upload, add another
queryClient.invalidateQueries call to also invalidate the ["files",
"diagnostic_report", report.id] query key so the uploaded files table refreshes
with the newly uploaded file.

267-270: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Pass the computed booleans instead of literal true.

Bare JSX props set both values to true, so the empty-state form always behaves as if specimens are collected and multi-report mode is enabled.

🐛 Proposed fix
         <CreateDiagnosticReportForm
-          hasCollectedSpecimens
-          isMultipleDiagnosticReport
+          hasCollectedSpecimens={hasCollectedSpecimens}
+          isMultipleDiagnosticReport={isMultipleDiagnosticReport}
           activityDefinition={activityDefinition}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`
around lines 267 - 270, The CreateDiagnosticReportForm component has bare JSX
props for hasCollectedSpecimens and isMultipleDiagnosticReport, which implicitly
set them to true, causing incorrect behavior in the empty-state form. Replace
these bare props with explicit assignments that pass the actual computed boolean
values instead. Determine what values these booleans should derive from based on
the component's state or props, and assign them using the syntax
hasCollectedSpecimens={computedValue} and
isMultipleDiagnosticReport={computedValue}.

132-135: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Require every declared specimen requirement before creating a report.

Line 135 uses some(), so report creation is allowed as soon as any specimen is available, even when specimen_requirements contains multiple required specimens. Use the requirement-to-specimen relationship to ensure each required specimen has an available specimen, while keeping the no-requirements case allowed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`
around lines 132 - 135, The hasCollectedSpecimens check in DiagnosticReportForm
uses some() which allows report creation when any specimen is available, but it
should require that every specimen requirement has a corresponding available
specimen. Replace the some() logic with validation that iterates through each
specimen requirement in activityDefinition.specimen_requirements and verifies
that a matching available specimen exists for each one, using the
requirement-to-specimen relationship. Keep the first part of the OR condition
intact so reports are still allowed when there are no specimen requirements
(length === 0).

204-263: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Allow “another report” creation for non-multiple report flows.

This block only renders when isMultipleDiagnosticReport is true, making the else handleCreateReport() branch on Lines 250-252 unreachable and preventing service requests without diagnostic-report-code choices from creating a second report.

🐛 Proposed fix
-          {isMultipleDiagnosticReport && (
-            <div className="-mt-3 rounded-b-lg bg-gray-100 px-2 pb-2 pt-5">
+          <div className="-mt-3 rounded-b-lg bg-gray-100 px-2 pb-2 pt-5">
               {showReportTypeSelect ? (
                 <Select
                   value={selectedReportCode?.code ?? ""}
                   onValueChange={(value) => {
@@
                   {t("another_diagnostic_report")}
                 </Button>
               )}
-            </div>
-          )}
+          </div>
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`
around lines 204 - 263, The entire block containing the "another diagnostic
report" button is wrapped by the condition isMultipleDiagnosticReport being
true, which makes the else branch in the onClick handler of the Button component
(where handleCreateReport is called directly without selecting a report type)
unreachable for non-multiple report flows. Remove or restructure the outer
isMultipleDiagnosticReport condition so that the button appears regardless of
whether isMultipleDiagnosticReport is true or false, allowing service requests
without diagnostic-report-code choices to create a second report. The inner
conditional logic in the onClick handler should still determine whether to show
the report type select or call handleCreateReport directly based on
isMultipleDiagnosticReport.
♻️ Duplicate comments (3)
src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx (3)

146-149: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Approval error toast bypasses i18n translation system.

The error message at lines 147-148 is a hardcoded English literal instead of using t() with translation keys.

💬 Suggested i18n fix

Add to public/locale/en.json:

{
  "failed_to_approve_diagnostic_report": "Failed to approve diagnostic report: {{error}}",
  "unknown_error": "Unknown error"
}

Update the error handler:

       onError: (err: Error) => {
-        toast.error(
-          `Failed to approve diagnostic report: ${err.message || "Unknown error"}`,
-        );
+        toast.error(
+          t("failed_to_approve_diagnostic_report", {
+            error: err.message || t("unknown_error"),
+          }),
+        );
       },

As per coding guidelines, "All literal strings must use i18next for multi-language support in healthcare interfaces" and "English translations go in public/locale/en.json."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx`
around lines 146 - 149, The error message in the onError handler of the
DiagnosticReportReview.tsx file uses a hardcoded English string instead of
leveraging the i18n translation system. Replace the hardcoded string in the
toast.error call with the t() translation function using an appropriate
translation key, and add the corresponding translation entries to
public/locale/en.json. The translation key should represent the failed approval
message and include a placeholder for the dynamic error message portion so that
the error details can be interpolated into the translated string.

Source: Coding guidelines


168-171: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Empty-state logic counts ENTERED_IN_ERROR observations that are never displayed.

Lines 168-171 compute isReportNotReviewable using the raw observation count, but lines 257-260 filter out ENTERED_IN_ERROR observations before rendering. Reports containing only entered-in-error observations will be marked reviewable and display an expanded card with blank results.

🧹 Recommended fix
   const reportDetail = fullReport ?? report;
+  const visibleObservations = (reportDetail.observations ?? []).filter(
+    (obs) => obs.status !== ObservationStatus.ENTERED_IN_ERROR,
+  );

   const isReportNotReviewable =
-    (!reportDetail.observations || reportDetail.observations.length === 0) &&
+    visibleObservations.length === 0 &&
     (!files?.results || files.results.length === 0) &&
     !reportDetail.conclusion;
   
   ...
   
                 <CardContent className="p-4">
-                  {(reportDetail.observations?.length ?? 0) === 0 && (
+                  {visibleObservations.length === 0 && (
                     <p className="text-gray-800 whitespace-pre-wrap p-2 rounded-lg bg-white border cursor-default text-center">
                       {t("no_observations_entered")}
                     </p>
                   )}
                   <DiagnosticReportResultsTable
-                    observations={(reportDetail.observations ?? []).filter(
-                      (obs) =>
-                        obs.status !== ObservationStatus.ENTERED_IN_ERROR,
-                    )}
+                    observations={visibleObservations}
                   />

Also applies to: 251-260

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx`
around lines 168 - 171, The isReportNotReviewable logic at lines 168-171 is
counting all observations including ENTERED_IN_ERROR ones, but the rendering
logic at lines 257-260 filters out ENTERED_IN_ERROR observations before
displaying. Update the isReportNotReviewable check to filter
reportDetail.observations to exclude ENTERED_IN_ERROR status observations, using
the same filtering logic as the rendering section, so that reports containing
only entered-in-error observations are not marked as reviewable.

10-10: 🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win

Conclusion state never syncs with loaded report data, enabling data corruption on approve.

Lines 10 and 96 removed the useEffect that would sync local conclusion state when fullReport loads. Combined with the fallback at line 279 (value={conclusion || reportDetail.conclusion || ""}), this creates two critical bugs:

  1. User cannot clear conclusion: When user deletes text, the fallback re-injects reportDetail.conclusion, making empty edits impossible.
  2. Approve overwrites data: Line 164 sends conclusion || reportDetail.conclusion. If conclusion was initialized to "" from report.conclusion but fullReport.conclusion later loaded with a value, approving without editing will submit the stale empty string and clear the server's stored conclusion.
🔧 Required fix
-import { useState } from "react";
+import { useEffect, useState } from "react";

 function DiagnosticReportReviewItem({
   ...
 }) {
   ...
-  const [conclusion, setConclusion] = useState<string>(report.conclusion || "");
+  const [conclusion, setConclusion] = useState<string>(report.conclusion ?? "");
+
+  useEffect(() => {
+    setConclusion(fullReport?.conclusion ?? report.conclusion ?? "");
+  }, [fullReport?.conclusion, report.conclusion]);

   ...
   
   // In the textarea:
-                      value={conclusion || reportDetail.conclusion || ""}
+                      value={conclusion}

Also applies to: 96-96, 279-279

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx`
at line 10, The useEffect hook that synchronized the local conclusion state with
the loaded fullReport data was removed, causing the conclusion state to become
stale and potentially corrupted. Add back a useEffect hook that depends on
fullReport and sets the conclusion state to fullReport.conclusion when
fullReport data is loaded. This will ensure the conclusion state always reflects
the current report data, preventing users from being unable to clear conclusions
and preventing approvals from overwriting server data with stale empty strings.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`:
- Around line 458-461: The useEffect hook that sets conclusion based on
fullReport.conclusion has conclusion in its dependency array, causing the effect
to re-run on every local keystroke, which overwrites user edits with the server
value. Remove conclusion from the dependency array of this effect so it only
runs when fullReport changes, not when the local conclusion state is updated by
user input.

In `@src/pages/Facility/services/serviceRequests/ServiceRequestShow.tsx`:
- Around line 604-622: The DiagnosticReportForm and DiagnosticReportReview
components are currently rendering unconditionally, but they should only display
when diagnostic observation requirements exist. Wrap both the
DiagnosticReportForm component (starting around line 604) and the
DiagnosticReportReview component (starting around line 616) with a conditional
check that verifies observationRequirements.length is greater than zero before
rendering. This ensures the diagnostic report sections only appear when there
are actual observation requirements to fulfill.

---

Outside diff comments:
In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`:
- Around line 375-377: In the DiagnosticReportForm component, the onError
callback is incorrectly calling toast.success instead of toast.error when
conclusion update fails. Fix this by changing the toast.success method call to
toast.error in the onError handler to properly display an error notification
when the conclusion update fails, ensuring the message with the key
"failed_to_update_conclusion" is shown as an error toast rather than a success
toast.
- Around line 386-389: The onUpload callback in DiagnosticReportForm is only
invalidating the ["diagnosticReport", report.id] query key, but the uploaded
files list is fetched with a different query key ["files", "diagnostic_report",
report.id]. After a successful file upload, add another
queryClient.invalidateQueries call to also invalidate the ["files",
"diagnostic_report", report.id] query key so the uploaded files table refreshes
with the newly uploaded file.
- Around line 267-270: The CreateDiagnosticReportForm component has bare JSX
props for hasCollectedSpecimens and isMultipleDiagnosticReport, which implicitly
set them to true, causing incorrect behavior in the empty-state form. Replace
these bare props with explicit assignments that pass the actual computed boolean
values instead. Determine what values these booleans should derive from based on
the component's state or props, and assign them using the syntax
hasCollectedSpecimens={computedValue} and
isMultipleDiagnosticReport={computedValue}.
- Around line 132-135: The hasCollectedSpecimens check in DiagnosticReportForm
uses some() which allows report creation when any specimen is available, but it
should require that every specimen requirement has a corresponding available
specimen. Replace the some() logic with validation that iterates through each
specimen requirement in activityDefinition.specimen_requirements and verifies
that a matching available specimen exists for each one, using the
requirement-to-specimen relationship. Keep the first part of the OR condition
intact so reports are still allowed when there are no specimen requirements
(length === 0).
- Around line 204-263: The entire block containing the "another diagnostic
report" button is wrapped by the condition isMultipleDiagnosticReport being
true, which makes the else branch in the onClick handler of the Button component
(where handleCreateReport is called directly without selecting a report type)
unreachable for non-multiple report flows. Remove or restructure the outer
isMultipleDiagnosticReport condition so that the button appears regardless of
whether isMultipleDiagnosticReport is true or false, allowing service requests
without diagnostic-report-code choices to create a second report. The inner
conditional logic in the onClick handler should still determine whether to show
the report type select or call handleCreateReport directly based on
isMultipleDiagnosticReport.

---

Duplicate comments:
In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx`:
- Around line 146-149: The error message in the onError handler of the
DiagnosticReportReview.tsx file uses a hardcoded English string instead of
leveraging the i18n translation system. Replace the hardcoded string in the
toast.error call with the t() translation function using an appropriate
translation key, and add the corresponding translation entries to
public/locale/en.json. The translation key should represent the failed approval
message and include a placeholder for the dynamic error message portion so that
the error details can be interpolated into the translated string.
- Around line 168-171: The isReportNotReviewable logic at lines 168-171 is
counting all observations including ENTERED_IN_ERROR ones, but the rendering
logic at lines 257-260 filters out ENTERED_IN_ERROR observations before
displaying. Update the isReportNotReviewable check to filter
reportDetail.observations to exclude ENTERED_IN_ERROR status observations, using
the same filtering logic as the rendering section, so that reports containing
only entered-in-error observations are not marked as reviewable.
- Line 10: The useEffect hook that synchronized the local conclusion state with
the loaded fullReport data was removed, causing the conclusion state to become
stale and potentially corrupted. Add back a useEffect hook that depends on
fullReport and sets the conclusion state to fullReport.conclusion when
fullReport data is loaded. This will ensure the conclusion state always reflects
the current report data, preventing users from being unable to clear conclusions
and preventing approvals from overwriting server data with stale empty strings.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 0c79045b-5fd0-4de5-8fd5-2d7ed8c7cab4

📥 Commits

Reviewing files that changed from the base of the PR and between 0d1dc49 and 29314ad.

📒 Files selected for processing (4)
  • public/locale/en.json
  • src/pages/Facility/services/serviceRequests/ServiceRequestShow.tsx
  • src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx
  • src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx

Comment thread src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx Outdated
Comment thread src/pages/Facility/services/serviceRequests/ServiceRequestShow.tsx Outdated
@NikhilA8606 NikhilA8606 requested a review from nihal467 June 25, 2026 10:18

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (5)
src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx (4)

1183-1188: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Keep final report attachments read-only.

Final reports hide upload controls, but FileListTable still receives canEdit={!disableEdit}, allowing existing attachments on finalized reports to be modified or deleted.

🐛 Proposed fix
-                      canEdit={!disableEdit}
+                      canEdit={
+                        !disableEdit &&
+                        report.status !== DiagnosticReportStatus.final
+                      }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`
around lines 1183 - 1188, The final report attachments are still editable
because FileListTable is passed canEdit={!disableEdit} even when the report is
finalized. Update DiagnosticReportForm so the FileListTable usage for final
reports is forced read-only, using the existing disableEdit/final-report state
in this component to pass a false canEdit value and prevent modifying or
deleting attachments.

1250-1258: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use a per-report conclusion textarea id.

Multiple rendered reports all use id="conclusion", so labels can target the wrong textarea in the multi-report flow.

🐛 Proposed fix
+                {(() => {
+                  const conclusionId = `conclusion_${report.id}`;
+                  return (
                   <Card className="mb-4 shadow-none rounded-lg border-gray-200 bg-gray-50">
                     <CardContent className="p-4 space-y-2">
                       <Label
-                        htmlFor="conclusion"
+                        htmlFor={conclusionId}
                         className="text-base font-semibold text-gray-950"
                       >
                         {t("conclusion")}
                       </Label>
                       <textarea
-                        id="conclusion"
+                        id={conclusionId}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`
around lines 1250 - 1258, The conclusion field in DiagnosticReportForm currently
uses a shared textarea id, which can cause label targeting conflicts when
multiple reports are rendered. Update the Label/textarea pair in the conclusion
section to use a report-specific id derived from the current report identifier
or index, and make sure the Label htmlFor and textarea id stay in sync within
the same report rendering block.

381-383: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Show an error toast when conclusion update fails.

The error handler currently calls toast.success, so failed updates are presented as successful.

🐛 Proposed fix
-      onError: () => {
-        toast.success(t("failed_to_update_conclusion"));
+      onError: () => {
+        toast.error(t("failed_to_update_conclusion"));
       },
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`
around lines 381 - 383, The conclusion update failure handler in
DiagnosticReportForm is using toast.success inside the onError callback, so
failed updates are shown as successful. Update the onError callback to use the
error-toast path instead, keeping the existing failed_to_update_conclusion
translation key and the surrounding conclusion update flow in
DiagnosticReportForm consistent with the success/error handling used elsewhere
in this component.

136-138: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Allow report creation when no specimen requirements are defined.

activityDefinition?.specimen_requirements?.length === 0 is false when specimen_requirements is undefined, so requests with no declared specimen requirements can be blocked unless an unrelated specimen exists.

🐛 Proposed fix
-  const hasCollectedSpecimens =
-    activityDefinition?.specimen_requirements?.length === 0 ||
+  const specimenRequirements = activityDefinition?.specimen_requirements ?? [];
+  const hasCollectedSpecimens =
+    specimenRequirements.length === 0 ||
     specimens.some((specimen) => specimen.status === SpecimenStatus.available);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`
around lines 136 - 138, The specimen gating in DiagnosticReportForm is too
strict because hasCollectedSpecimens only treats an empty specimen_requirements
array as valid, not an undefined one. Update the hasCollectedSpecimens check in
DiagnosticReportForm to allow report creation whenever
activityDefinition.specimen_requirements is missing or empty, while still
requiring an available specimen when requirements are actually declared.
src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx (1)

290-304: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Gate file editing for finalized reports.

Line 302 passes canEdit={!disableEdit} for every status, so finalized diagnostic reports can still expose editable attachment controls while the rest of the UI treats final reports as read-only.

Suggested fix
-                      canEdit={!disableEdit}
+                      canEdit={
+                        !disableEdit &&
+                        report.status !== DiagnosticReportStatus.final
+                      }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx`
around lines 290 - 304, Gate the attachment editing controls in
DiagnosticReportReview by report status instead of only using disableEdit; the
FileListTable in the uploaded files section currently receives
canEdit={!disableEdit} for all cases. Update the logic around
DiagnosticReportReview and FileListTable props so finalized diagnostic reports
pass canEdit as false, keeping the file list read-only whenever the report is
finalized even if other edit conditions would allow changes.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx`:
- Around line 1183-1188: The final report attachments are still editable because
FileListTable is passed canEdit={!disableEdit} even when the report is
finalized. Update DiagnosticReportForm so the FileListTable usage for final
reports is forced read-only, using the existing disableEdit/final-report state
in this component to pass a false canEdit value and prevent modifying or
deleting attachments.
- Around line 1250-1258: The conclusion field in DiagnosticReportForm currently
uses a shared textarea id, which can cause label targeting conflicts when
multiple reports are rendered. Update the Label/textarea pair in the conclusion
section to use a report-specific id derived from the current report identifier
or index, and make sure the Label htmlFor and textarea id stay in sync within
the same report rendering block.
- Around line 381-383: The conclusion update failure handler in
DiagnosticReportForm is using toast.success inside the onError callback, so
failed updates are shown as successful. Update the onError callback to use the
error-toast path instead, keeping the existing failed_to_update_conclusion
translation key and the surrounding conclusion update flow in
DiagnosticReportForm consistent with the success/error handling used elsewhere
in this component.
- Around line 136-138: The specimen gating in DiagnosticReportForm is too strict
because hasCollectedSpecimens only treats an empty specimen_requirements array
as valid, not an undefined one. Update the hasCollectedSpecimens check in
DiagnosticReportForm to allow report creation whenever
activityDefinition.specimen_requirements is missing or empty, while still
requiring an available specimen when requirements are actually declared.

In
`@src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx`:
- Around line 290-304: Gate the attachment editing controls in
DiagnosticReportReview by report status instead of only using disableEdit; the
FileListTable in the uploaded files section currently receives
canEdit={!disableEdit} for all cases. Update the logic around
DiagnosticReportReview and FileListTable props so finalized diagnostic reports
pass canEdit as false, keeping the file list read-only whenever the report is
finalized even if other edit conditions would allow changes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3eb2de99-6e72-4837-9a0f-15720da989f6

📥 Commits

Reviewing files that changed from the base of the PR and between 29314ad and 13acde3.

📒 Files selected for processing (5)
  • public/locale/en.json
  • src/hooks/useFileUpload.tsx
  • src/pages/Facility/services/serviceRequests/ServiceRequestShow.tsx
  • src/pages/Facility/services/serviceRequests/components/DiagnosticReportForm.tsx
  • src/pages/Facility/services/serviceRequests/components/DiagnosticReportReview.tsx

Copilot AI review requested due to automatic review settings June 25, 2026 10:56

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.

Comment on lines 376 to 380
@@ -259,14 +380,16 @@ export function DiagnosticReportForm({
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Success toast shown on error

toast.success is called inside the updateDiagnosticReport onError handler. Every time saving the conclusion fails, users will see a green "success" notification saying the localized "Failed to update conclusion" message — the opposite of the intended behavior. Every other error handler in this file correctly uses toast.error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants