Skip to content

Enhancement: Removed recently updated prototype usage in documentsInQueue.jsp for fetch, and jQuery to append data#2335

Open
LiamStanziani wants to merge 2 commits intohotfix/01232026from
enhancement/update-ajax-updater-document-use
Open

Enhancement: Removed recently updated prototype usage in documentsInQueue.jsp for fetch, and jQuery to append data#2335
LiamStanziani wants to merge 2 commits intohotfix/01232026from
enhancement/update-ajax-updater-document-use

Conversation

@LiamStanziani
Copy link
Collaborator

@LiamStanziani LiamStanziani commented Mar 13, 2026

Summary

Replace deprecated Prototype.js Ajax.Updater with modern fetch API in documentsInQueues.jsp showDocLab() function, switching from GET to POST and adding CSRF protection.

This PR was created to address this review comment: #2305 (review)

Problem

The showDocLab() function in documentsInQueues.jsp used Prototype.js's Ajax.Updater and Insertion.Bottom — deprecated libraries that should be phased out. It also used a GET request to load document/lab content, passing
patient-related parameters (segmentID, providerNo, demoName) in the query string.

Solution

  • Replaced Ajax.Updater with fetch API (vanilla JS) for the HTTP request
  • Changed GET to POST so parameters are sent in the request body instead of the query string
  • Added CSRF token via the OWASP CSRFGuard taglib (csrf:tokenname//csrf:tokenvalue/) in request headers
  • Replaced Prototype $() with document.getElementById() for DOM element lookup
  • Used jQuery .html() and .append() for DOM insertion to preserve script execution from the server-rendered JSP fragments (showDocument.jsp, labDisplayAjax.jsp), which contain inline scripts required for PDF rendering, autocomplete, and popup functions
  • Added error handling with response.ok check and .catch() for network failures

Summary by Sourcery

Modernize document/lab loading in documentsInQueues.jsp by replacing Prototype.js Ajax.Updater with a fetch-based POST request secured with CSRF headers and safer DOM handling.

Enhancements:

  • Switch document/lab loading from Prototype.js Ajax.Updater GET requests to a vanilla fetch-based POST that sends parameters in the request body.
  • Encode all request parameters and add a guard for missing target elements to make dynamic loading more robust.
  • Use jQuery-based DOM insertion to preserve script execution when rendering server-generated JSP fragments.
  • Integrate OWASP CSRFGuard taglib to add CSRF protection headers on the AJAX request.

Summary by cubic

Replaced Prototype.js Ajax.Updater in documentsInQueues.jsp with a fetch-based POST that includes CSRF headers. Uses jQuery for DOM insertion and adds param encoding and a target element check to make loading safer.

  • Refactors

    • Switched to fetch POST with application/x-www-form-urlencoded, same-origin credentials, and headers X-Requested-With and CSRF via the OWASP CSRFGuard taglib.
    • Moved params from the query string to the request body; replaced $() with document.getElementById.
    • Inserted HTML via jQuery .html()/.append() and added response.ok checks with error logging.
  • Bug Fixes

    • Encode all request params with encodeURIComponent to handle special characters.
    • Guard against a missing target element and bail with a clear console error.

Written for commit 2ad6bd2. Summary will update on new commits.

Summary by CodeRabbit

  • Security

    • Strengthened CSRF token validation and protection mechanisms in document queue operations
  • Refactor

    • Modernized request handling from legacy framework to current web standards for improved reliability and performance
    • Enhanced error handling with comprehensive logging to facilitate better troubleshooting and system stability

@LiamStanziani LiamStanziani self-assigned this Mar 13, 2026
@LiamStanziani LiamStanziani requested a review from Copilot March 13, 2026 18:32
@sourcery-ai
Copy link

sourcery-ai bot commented Mar 13, 2026

Reviewer's Guide

Modernizes the showDocLab() AJAX flow in documentsInQueues.jsp by replacing Prototype.js Ajax.Updater with a fetch-based POST request that includes CSRF protection, URL-encoded parameters, native DOM lookups plus jQuery-based HTML insertion, and basic error handling.

Sequence diagram for updated showDocLab fetch-based document loading

sequenceDiagram
    actor User
    participant Browser as Browser_showDocLab
    participant Server as Server_JSP

    User->>Browser: Click document/lab in queue
    Browser->>Browser: showDocLab(docNo, providerNo, searchProviderNo, status, demoName, inQueue, childId)
    Browser->>Browser: Determine type DOC/LAB/OTHER
    Browser->>Browser: Resolve placeholder or child element via getElementById
    alt Target element not found
        Browser->>Browser: console.error("showDocLab: target element not found")
        Browser-->>User: No content loaded
    else Target element found
        Browser->>Browser: Build URL based on type
        Browser->>Browser: Build URL-encoded body with encodeURIComponent
        Browser->>Server: fetch POST /showDocument.jsp or /labDisplayAjax.jsp
            Note right of Browser: Headers: Content-Type, X-Requested-With, CSRF token\nCredentials: same-origin
        Server-->>Browser: HTTP response with HTML fragment
        alt response.ok
            Browser->>Browser: response.text()
            alt Placeholder exists
                Browser->>Browser: jQuery(div).html(html)
            else No placeholder
                Browser->>Browser: jQuery(div).append(html)
            end
            Browser->>Browser: focusFirstDocLab()
            Browser-->>User: Updated document/lab content displayed
        else !response.ok
            Browser->>Browser: Throw Error("Failed to load document")
            Browser->>Browser: console.error("Error loading document/lab", err)
            Browser-->>User: Error state (no update)
        end
    end
Loading

Flow diagram for updated showDocLab control logic

flowchart TD
    A[start showDocLab] --> B[Normalize docNo and determine type]
    B --> C[Resolve placeholder element by id docPlaceholder_docNo]
    C --> D[Resolve target div as placeholder or childId element]
    D --> E{Is target div found?}
    E -- No --> F[Log console.error target element not found]
    F --> G[Return from showDocLab]
    E -- Yes --> H[Set URL based on type DOC or LAB]
    H --> I[Build form body with segmentID, providerNo, searchProviderNo, status, demoName, inQueue]
    I --> J[encodeURIComponent for all parameter values]
    J --> K[Call fetch with POST, URL, headers including CSRF, same-origin credentials]
    K --> L{response.ok?}
    L -- No --> M[Throw error Failed to load document]
    M --> N[Log console.error Error loading document or lab]
    N --> O[End]
    L -- Yes --> P[Read response.text as html]
    P --> Q{Placeholder exists?}
    Q -- Yes --> R["Use jQuery(div).html(html)"]
    Q -- No --> S["Use jQuery(div).append(html)"]
    R --> T[Call focusFirstDocLab]
    S --> T[Call focusFirstDocLab]
    T --> O[End]
Loading

File-Level Changes

Change Details Files
Replace Prototype.js Ajax.Updater GET call with a secure fetch-based POST using form-encoded body and CSRF headers.
  • Determine target URL based on doc type and send parameters in the request body instead of the query string.
  • Use encodeURIComponent on all request parameters before building the form-encoded payload string.
  • Configure fetch with method POST, content-type application/x-www-form-urlencoded, X-Requested-With header, CSRFGuard-derived header name/value, and same-origin credentials.
  • Check response.ok, convert the response to text, and log a clear error plus throw on HTTP failure or network error.
src/main/webapp/oscarMDS/documentsInQueues.jsp
Update DOM lookup and insertion to use native APIs and jQuery while preserving inline script execution and handling missing targets.
  • Replace Prototype $() calls with document.getElementById for both the placeholder and child container elements.
  • Guard against a missing target element, log an explicit console error including the docNo, and bail early.
  • Use jQuery(div).html(html) when inserting into an existing placeholder and jQuery(div).append(html) when appending into the child container, then call focusFirstDocLab() after successful insertion.
src/main/webapp/oscarMDS/documentsInQueues.jsp
Integrate OWASP CSRFGuard taglib to support CSRF-protected AJAX requests from this JSP.
  • Add the CSRFGuard taglib directive at the top of the JSP.
  • Insert CSRFGuard token name and value tags into the fetch request headers to send CSRF tokens with each request.
src/main/webapp/oscarMDS/documentsInQueues.jsp

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link

coderabbitai bot commented Mar 13, 2026

📝 Walkthrough

Walkthrough

This pull request modernizes the documentsInQueues.jsp file by migrating from Prototype's Ajax.Updater to the native Fetch API for handling AJAX requests, while adding CSRF protection headers and updating DOM manipulation to use native methods.

Changes

Cohort / File(s) Summary
AJAX & CSRF Modernization
src/main/webapp/oscarMDS/documentsInQueues.jsp
Replaced Prototype Ajax.Updater with Fetch API POST requests, added CSRF token support in request headers, switched to native getElementById for DOM selection, and implemented jQuery for DOM updates with error handling via console logging.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

Suggested reviewers

  • D3V41
  • yingbull

Poem

🐰 From Prototype's old dusty ways,
We hop to Fetch's brighter days,
With CSRF guards now standing tall,
And native methods heeding call—
JavaScript grows fresh and free! 🌟

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly and specifically identifies the main change: removing Prototype.js usage in favor of fetch and jQuery, which aligns with the changeset modifications in documentsInQueues.jsp.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch enhancement/update-ajax-updater-document-use
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@gemini-code-assist
Copy link

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly modernizes the showDocLab() function within documentsInQueues.jsp by replacing outdated Prototype.js AJAX and DOM manipulation techniques with contemporary JavaScript fetch API and jQuery. The changes enhance the application's security posture by transitioning to POST requests with CSRF protection and improve code readability and error handling, aligning the codebase with current web development best practices.

Highlights

  • Modernized AJAX Call: Replaced the deprecated Prototype.js Ajax.Updater with the native fetch API for making HTTP requests, improving maintainability and leveraging modern web standards.
  • Enhanced Security: Switched the request method from GET to POST for sending parameters in the request body instead of the query string, and incorporated CSRF protection by including CSRF tokens in the fetch request headers.
  • Updated DOM Manipulation: Migrated from Prototype.js $() for element selection to document.getElementById() and utilized jQuery's .html() and .append() for inserting content, ensuring proper script execution from server-rendered JSP fragments.
  • Improved Error Handling: Implemented robust error handling for network requests using response.ok checks and .catch() for fetch operations, providing better feedback for failures.
Changelog
  • src/main/webapp/oscarMDS/documentsInQueues.jsp
    • Added CSRF taglib import for security tokens.
    • Replaced Prototype.js $() function calls with document.getElementById() for DOM element selection.
    • Replaced the Ajax.Updater call with a modern fetch API implementation.
    • Changed the HTTP request method from GET to POST.
    • Included CSRF token headers in the fetch request.
    • Updated the logic for inserting HTML content into the DOM to use jQuery's .html() and .append() methods.
    • Added error handling for fetch requests using .then() and .catch() blocks.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@LiamStanziani
Copy link
Collaborator Author

@coderabbitai review

@LiamStanziani
Copy link
Collaborator Author

@SourceryAI review

@coderabbitai
Copy link

coderabbitai bot commented Mar 13, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • The data string sent in the POST body is built by simple concatenation; consider using encodeURIComponent or URLSearchParams to safely URL-encode each parameter value so special characters in docNo, demoName, etc. don’t break the request.
  • The error handling currently only logs to console.error; if this path is user-facing, consider surfacing a minimal inline error state or fallback in the UI so failures aren’t silent from the user’s perspective.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `data` string sent in the POST body is built by simple concatenation; consider using `encodeURIComponent` or `URLSearchParams` to safely URL-encode each parameter value so special characters in `docNo`, `demoName`, etc. don’t break the request.
- The error handling currently only logs to `console.error`; if this path is user-facing, consider surfacing a minimal inline error state or fallback in the UI so failures aren’t silent from the user’s perspective.

## Individual Comments

### Comment 1
<location path="src/main/webapp/oscarMDS/documentsInQueues.jsp" line_range="925-914" />
<code_context>
+                if (!response.ok) { throw new Error('Failed to load document'); }
+                return response.text();
+            })
+            .then(function (html) {
+                if (placeholder) {
+                    jQuery(div).html(html);
+                } else {
+                    jQuery(div).append(html);
+                }
+                focusFirstDocLab();
+            })
+            .catch(function (err) {
</code_context>
<issue_to_address>
**suggestion:** DOM update logic diverges slightly from previous `Insertion.Bottom` semantics when `div` is missing.

With the new logic, if `div` cannot be resolved (`document.getElementById(childId)` returns `null`), `jQuery(div)` becomes a no-op: the response is fetched but never inserted when both `placeholder` and `div` are null. If this state is possible, consider failing fast (e.g., explicit error/log or early return before the fetch) to make misconfigurations visible instead of silently dropping the content.

Suggested implementation:

```
            .then(function (html) {
                if (!div) {
                    console.error('Error loading document/lab: target container element not found', { childId: childId });
                    return;
                }

                if (placeholder) {
                    jQuery(div).html(html);
                } else {
                    jQuery(div).append(html);
                }
                focusFirstDocLab();
            })

```

1. Ensure that `childId` is in scope for this function. If the identifier for the target element is named differently (e.g., `docId` or similar), update the logged object key/value accordingly.
2. If you prefer failing earlier (before the `fetch` call) instead of here, add a corresponding `if (!div) { console.error(...); return; }` guard at the start of the function that triggers this request, keeping the same error message format for consistency.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request is a great enhancement, replacing the deprecated Prototype.js Ajax.Updater with the modern fetch API. The switch to POST requests and the addition of CSRF protection are excellent security improvements. I've found one high-severity issue regarding missing URL encoding for the POST data, which could lead to bugs with special characters in patient data. I've also suggested a medium-severity improvement to provide better error feedback to the user in the UI. Overall, this is a solid modernization effort.

Copy link

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

🧹 Nitpick comments (1)
src/main/webapp/oscarMDS/documentsInQueues.jsp (1)

912-935: Solid fetch implementation with CSRF protection.

The migration from Prototype's Ajax.Updater to native fetch is well-implemented:

  • CSRF headers using JSP tags will render correctly at server-time
  • POST method with credentials: 'same-origin' properly maintains session
  • jQuery DOM insertion preserves inline script execution for PDF rendering and autocomplete functionality

One minor observation: the error handling logs to console but doesn't provide user feedback. If a document fails to load, the placeholder div remains empty with no indication to the user.

💡 Optional: Add minimal user feedback for failed loads
 .catch(function (err) {
     console.error('Error loading document/lab:', err);
+    if (div) {
+        jQuery(div).html('<p class="text-danger">Failed to load document. Please refresh the page.</p>');
+    }
 });

,

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/webapp/oscarMDS/documentsInQueues.jsp` around lines 912 - 935, When
the fetch in the document loader fails, add minimal user-visible feedback in the
same target element instead of leaving it empty: inside the .catch handler
update the target element referenced by div/placeholder (use the existing
placeholder flag to decide whether to replace or append) with a brief,
accessible error message (e.g., "Unable to load document. Please try again.")
and preserve the console.error call; ensure the message is inserted via the same
jQuery(div) usage so styling/behavior remains consistent and consider keeping
focusFirstDocLab() behavior unaffected.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/main/webapp/oscarMDS/documentsInQueues.jsp`:
- Around line 912-935: When the fetch in the document loader fails, add minimal
user-visible feedback in the same target element instead of leaving it empty:
inside the .catch handler update the target element referenced by
div/placeholder (use the existing placeholder flag to decide whether to replace
or append) with a brief, accessible error message (e.g., "Unable to load
document. Please try again.") and preserve the console.error call; ensure the
message is inserted via the same jQuery(div) usage so styling/behavior remains
consistent and consider keeping focusFirstDocLab() behavior unaffected.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ad507cc5-eba3-4d39-b711-0d8ef16a771d

📥 Commits

Reviewing files that changed from the base of the PR and between b244f18 and 7faa754.

📒 Files selected for processing (1)
  • src/main/webapp/oscarMDS/documentsInQueues.jsp

Copy link

Copilot AI left a comment

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 updates the Documents In Queues JSP to modernize the client-side request used to load document/lab content and to integrate OWASP CSRFGuard token handling for those requests.

Changes:

  • Added the OWASP CSRFGuard JSP taglib to enable token rendering.
  • Replaced a Prototype Ajax.Updater call with a fetch-based request that injects the CSRF token via request headers.
  • Switched DOM lookups from Prototype’s $() to document.getElementById() in the updated block.

…URL params, and added request with header field
@LiamStanziani LiamStanziani marked this pull request as ready for review March 13, 2026 19:12
@qodo-code-review
Copy link

Review Summary by Qodo

Modernize document loading with fetch API and CSRF protection

✨ Enhancement 🐞 Bug fix

Grey Divider

Walkthroughs

Description
• Replace deprecated Prototype.js Ajax.Updater with modern fetch API
• Switch from GET to POST requests with CSRF protection headers
• Add parameter encoding and target element validation
• Use jQuery for DOM insertion to preserve inline scripts
Diagram
flowchart LR
  A["Prototype.js<br/>Ajax.Updater"] -->|"Replace with"| B["Fetch API<br/>POST Request"]
  B -->|"Add security"| C["CSRF Headers<br/>same-origin"]
  B -->|"Encode params"| D["encodeURIComponent<br/>all values"]
  B -->|"Insert HTML"| E["jQuery .html()/.append()<br/>preserve scripts"]
  F["Target element<br/>validation"] -->|"Guard against"| G["Missing div<br/>error handling"]
Loading

Grey Divider

File Changes

1. src/main/webapp/oscarMDS/documentsInQueues.jsp Enhancement, security, bug fix +41/-17

Replace Prototype Ajax with fetch and add CSRF protection

• Added OWASP CSRFGuard taglib import for CSRF token support
• Replaced Prototype $() with document.getElementById() for DOM lookups
• Added validation to check if target element exists before processing
• Converted GET request to POST with application/x-www-form-urlencoded body
• Added URL parameter encoding using encodeURIComponent() for all request parameters
• Implemented fetch API with CSRF headers and same-origin credentials
• Replaced DOM insertion with jQuery .html() and .append() to preserve inline scripts
• Added error handling with response validation and .catch() for network failures

src/main/webapp/oscarMDS/documentsInQueues.jsp


Grey Divider

Qodo Logo

@qodo-code-review
Copy link

qodo-code-review bot commented Mar 13, 2026

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (1) 📎 Requirement gaps (0)

Grey Divider


Action required

1. Scripts not executed 🐞 Bug ✓ Correctness
Description
showDocLab() inserts fetched JSP fragments via jQuery(div).html()/append() but does not execute
embedded <script> blocks, so initialization code in showDocument.jsp (e.g., calling showPDF on load)
may never run and document/lab views can break.
Code

src/main/webapp/oscarMDS/documentsInQueues.jsp[R934-941]

+            .then(function (html) {
+                if (placeholder) {
+                    jQuery(div).html(html);
+                } else {
+                    jQuery(div).append(html);
+                }
+                focusFirstDocLab();
+            })
Evidence
The codebase already documents that scripts inserted via HTML insertion won’t run unless explicitly
extracted/re-added, and it provides a helper for this. The new implementation inserts raw HTML
without using that helper, while showDocument.jsp includes on-load inline JS that triggers PDF
rendering.

src/main/webapp/oscarMDS/documentsInQueues.jsp[920-941]
src/main/webapp/share/javascript/oscarMDSIndex.js[106-131]
src/main/webapp/documentManager/showDocument.jsp[735-744]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`showDocLab()` switched from Prototype `Ajax.Updater` with `evalScripts: true` to `fetch()` + `jQuery(div).html()/append()`. The new path inserts HTML but does not explicitly execute embedded `&lt;script&gt;` blocks, and the fragment JSPs include initialization JS (e.g., `showPDF(...)`) that must run when the fragment loads.

### Issue Context
The repo already contains a helper (`appendHtmlWithScripts`) with an explicit comment that browsers don’t execute scripts inserted via HTML insertion, and it is used elsewhere for the same document/lab fragment use case.

### Fix Focus Areas
- src/main/webapp/oscarMDS/documentsInQueues.jsp[920-941]
- src/main/webapp/share/javascript/oscarMDSIndex.js[106-131]
- src/main/webapp/documentManager/showDocument.jsp[735-744]

### Implementation notes
- When `placeholder` exists: clear/replace the container, then insert HTML and execute inline scripts.
- When `placeholder` is absent: append HTML and execute inline scripts.
- Reuse `appendHtmlWithScripts(div, html)` (already loaded on this page) or implement an equivalent local helper that executes scripts from the fragment.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. console.error logs docNo 📘 Rule violation ⛨ Security
Description
The new client-side error log includes docNo (sent as segmentID), which may constitute a patient
identifier/PHI depending on how it maps to documents/labs. This risks leaking sensitive data into
browser logs or remote log collectors.
Code

src/main/webapp/oscarMDS/documentsInQueues.jsp[R895-897]

+            if (!div) {
+                console.error('showDocLab: target element not found for docNo=' + docNo);
+                return;
Evidence
PR Compliance ID 4 prohibits logging/exposing PHI; the added code logs an identifier (docNo)
directly to console.error, which can be captured and persisted outside intended secure channels.

CLAUDE.md
src/main/webapp/oscarMDS/documentsInQueues.jsp[895-897]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Client-side logging includes `docNo` (used as `segmentID`), which may be considered PHI/patient-identifying and should not be written to logs.

## Issue Context
Browser console logs are frequently collected by monitoring/telemetry tools and can be exposed to unintended audiences; avoid logging patient/document identifiers.

## Fix Focus Areas
- src/main/webapp/oscarMDS/documentsInQueues.jsp[895-897]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Unsafe external scripts injected 🐞 Bug ⛯ Reliability
Description
By inserting entire JSP responses into the DOM, the page can also inject external <script src=...>
tags from showDocument.jsp and labDisplayAjax.jsp; those include a relative showDocument.js and an
old jquery-1.4.2.js, which can 404, duplicate-load, or clobber the existing jQuery on
documentsInQueues.jsp if script execution is enabled.
Code

src/main/webapp/oscarMDS/documentsInQueues.jsp[R934-939]

+            .then(function (html) {
+                if (placeholder) {
+                    jQuery(div).html(html);
+                } else {
+                    jQuery(div).append(html);
+                }
Evidence
The fetched fragments contain external script tags (including a relative path and an older jQuery),
while documentsInQueues.jsp already loads newer jQuery and the correct showDocument.js. If scripts
from the fragment are executed (which the previous implementation did via evalScripts: true, and
which the current PR intends to preserve), these external includes become actively harmful.

src/main/webapp/oscarMDS/documentsInQueues.jsp[934-939]
src/main/webapp/documentManager/showDocument.jsp[735-738]
src/main/webapp/lab/CA/ALL/labDisplayAjax.jsp[171-173]
src/main/webapp/oscarMDS/documentsInQueues.jsp[83-87]
src/main/webapp/oscarMDS/documentsInQueues.jsp[2368-2371]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The fetched fragment JSPs include external `&lt;script src&gt;` tags:
- `showDocument.jsp` includes a **relative** `src=&quot;showDocument.js&quot;`.
- `labDisplayAjax.jsp` includes `jquery-1.4.2.js`.
If the new approach executes fragment scripts (as intended to preserve prior behavior), these external scripts can load with wrong base paths, duplicate-load assets, or override the already-loaded jQuery 1.12 on `documentsInQueues.jsp`.

### Issue Context
`documentsInQueues.jsp` already loads `${contextPath}/documentManager/showDocument.js` and jQuery 1.12.0, so fragment-level external includes are redundant at best and dangerous at worst.

### Fix Focus Areas
- src/main/webapp/oscarMDS/documentsInQueues.jsp[934-939]
- src/main/webapp/documentManager/showDocument.jsp[735-738]
- src/main/webapp/lab/CA/ALL/labDisplayAjax.jsp[171-173]
- src/main/webapp/oscarMDS/documentsInQueues.jsp[83-87]
- src/main/webapp/oscarMDS/documentsInQueues.jsp[2368-2371]

### Implementation notes
- If you add/keep script execution for fragments, restrict execution to **inline scripts only** (skip `script.src`).
- Alternatively, move those `&lt;script src&gt;` includes behind a condition (e.g., only include them when `inWindow=true`) so AJAX fragment responses don’t ship external dependencies.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Qodo Logo

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • Consider using URLSearchParams (e.g. new URLSearchParams({...}).toString()) instead of manually concatenating and encoding the data string to make the request body construction more readable and less error-prone when adding/removing parameters.
  • In the fetch error handling, you may want to include the HTTP status/response text in the thrown error (or log it) when !response.ok to make troubleshooting backend issues easier than a generic 'Failed to load document' message.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider using `URLSearchParams` (e.g. `new URLSearchParams({...}).toString()`) instead of manually concatenating and encoding the `data` string to make the request body construction more readable and less error-prone when adding/removing parameters.
- In the `fetch` error handling, you may want to include the HTTP status/response text in the thrown error (or log it) when `!response.ok` to make troubleshooting backend issues easier than a generic 'Failed to load document' message.

## Individual Comments

### Comment 1
<location path="src/main/webapp/oscarMDS/documentsInQueues.jsp" line_range="899" />
<code_context>
+                console.error('showDocLab: target element not found for docNo=' + docNo);
+                return;
+            }
             var url = '';
             if (type == 'DOC')
                 url = "<%= request.getContextPath() %>/documentManager/showDocument.jsp";
</code_context>
<issue_to_address>
**suggestion:** Consider guarding against empty or unknown URLs before issuing the fetch request.

Right now, if `checkType(docNo)` returns an unexpected value, `url` remains an empty string and `fetch` will target the current page. Even though this matches the old `Ajax.Updater` behavior, with the new explicit error handling it would be clearer and safer to log and `return` when `url` is falsy, so we don’t silently send requests to the wrong endpoint.

Suggested implementation:

```
            var url = '';
            if (type == 'DOC')
                url = "<%= request.getContextPath() %>/documentManager/showDocument.jsp";
            else
                url = "";

            if (!url) {
                console.error('showDocLab: unable to resolve URL for docNo=' + docNo + ', type=' + type);
                return;
            }

```

If the `fetch` (or equivalent AJAX) call is not immediately after this snippet, ensure that the `url` variable is not reassigned later and that all code paths that lead to a network request go through this guard. If there are other call sites or helper functions that construct URLs in a similar way, consider adding the same `!url` guard pattern there for consistency.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

1 issue found across 1 file

Confidence score: 3/5

  • There is a concrete user-impacting risk in src/main/webapp/oscarMDS/documentsInQueues.jsp: if checkType(docNo) returns an unrecognized type, url stays empty and fetch('') targets the current page URL.
  • This can silently POST form-encoded patient data to the wrong endpoint, which raises a meaningful regression/privacy concern, so this is not a low-risk merge despite being isolated to one file.
  • Pay close attention to src/main/webapp/oscarMDS/documentsInQueues.jsp - ensure unrecognized document types cannot fall through to an empty fetch URL.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="src/main/webapp/oscarMDS/documentsInQueues.jsp">

<violation number="1" location="src/main/webapp/oscarMDS/documentsInQueues.jsp:920">
P2: When `checkType(docNo)` returns an unrecognized type, `url` remains an empty string. Calling `fetch('')` resolves to the current page URL (per the Fetch spec), so this will silently POST form-encoded patient data to the current JSP page instead of failing visibly. Add a guard before the `fetch` call to bail out when `url` is falsy.

```js
if (!url) {
    console.error('showDocLab: unable to resolve URL for docNo=' + docNo + ', type=' + type);
    return;
}
```</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

@LiamStanziani LiamStanziani requested a review from D3V41 March 13, 2026 19:29
@LiamStanziani LiamStanziani changed the title Enhancement: Removed updated prototype usage for fetch, and jQuery to append data Enhancement: Removed recently updated prototype usage in documentsInQueue.jsp for fetch, and jQuery to append data Mar 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants