-
Notifications
You must be signed in to change notification settings - Fork 68
RELEASE XCPD w/ custodian + CCD fixes #4015
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Ref eng-454 Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.com>
Ref eng-441 Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.com>
Ref eng-441 Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.com>
Ref eng-441 Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.com>
Ref eng-441 Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.com>
…ty-ccd ENG-441 Additional fixes for invalid chars in CCDs
ENG-454 Inbound XCPD includes custodian
WalkthroughThe changes primarily introduce HTML encoding for dynamic string insertions in CDA and FHIR-to-CDA XML generation, update logging in several API routes, refine type annotations for organization data, and adjust handler wrapping and middleware configuration. No significant changes to control flow or exported function signatures are present. Changes
Sequence Diagram(s)sequenceDiagram
participant API_Route as API Route Handler
participant Logger as Logger
participant CDA_Generator as CDA XML Generator
participant HTML_Encoder as encodeToHtml Utility
API_Route->>Logger: Log request details (e.g., conversionType, search query)
API_Route->>CDA_Generator: Generate CDA/FHIR-to-CDA XML
CDA_Generator->>HTML_Encoder: Encode dynamic strings for XML
CDA_Generator-->>API_Route: Return encoded XML
Possibly related PRs
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 ESLint
npm error code ERR_SSL_WRONG_VERSION_NUMBER 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms (25)
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
🔭 Outside diff range comments (1)
packages/lambdas/src/ihe-gateway-v2-inbound-patient-discovery.ts (1)
27-71
: 🛠️ Refactor suggestionAvoid surfacing analytics/network failures as client (400) errors
analyticsAsync
/getSecretValue
are nice-to-have side effects.
If either of them throws, the execution jumps to the innercatch
, which returns 400 Bad Request – misleading for callers and potentially masking genuine server issues.Guard the analytics block with its own
try / catch
and downgrade failures to a log entry so that a transient PostHog or SecretsManager outage does not break the business flow nor misreport the status code.- if (result.patientMatch && postHogSecretName) { - const postHogApiKey = await getSecretValue(postHogSecretName, region); - - if (postHogApiKey && engineeringCxId) { - await analyticsAsync( - { - distinctId: engineeringCxId, - event: EventTypes.inboundPatientDiscovery, - properties: { - patientId: result.patientId, - patientMatch: result.patientMatch, - homeCommunityId: pdRequest.samlAttributes.homeCommunityId, - }, - }, - postHogApiKey - ); - } - } + if (result.patientMatch && postHogSecretName && engineeringCxId) { + try { + const postHogApiKey = await getSecretValue(postHogSecretName, region); + if (postHogApiKey) { + await analyticsAsync( + { + distinctId: engineeringCxId, + event: EventTypes.inboundPatientDiscovery, + properties: { + patientId: result.patientId, + patientMatch: result.patientMatch, + homeCommunityId: pdRequest.samlAttributes.homeCommunityId, + }, + }, + postHogApiKey + ); + } + } catch (analyticsError) { + log( + `Non-blocking analytics failure on ${lambdaName}: ${errorToString(analyticsError)}` + ); + } + }This keeps the happy path untouched while preventing false “Bad Request” responses.
(A separate improvement would be to distinguish between client vs. server errors explicitly, e.g., by throwing domain-specific errors.)
🧹 Nitpick comments (3)
packages/api/src/routes/internal/medical/patient.ts (1)
938-940
: Minor string-formatting nitThe log context string ends with an unmatched right parenthesis:
out(`cx ${cxId}, pt ${id}, requestId ${requestId})`); // -------------------^-out(`cx ${cxId}, pt ${id}, requestId ${requestId})`); +out(`cx ${cxId}, pt ${id}, requestId ${requestId}`);Purely cosmetic but keeps logs tidy.
packages/core/src/fhir-to-cda/cda-templates/components/allergies.ts (1)
170-189
: Encode all user-supplied strings for consistency & safety.Great to see
encodeToHtml
applied to substance and comments. The same sanitisation should be extended to the remaining free-text columns (category
,manifestation
,onset
,onsetDate
) to guarantee uniform escaping.- { - "#text": category?.join(", ") ?? NOT_SPECIFIED, + { + "#text": encodeToHtml(category?.join(", ") ?? NOT_SPECIFIED), }, { _ID: `${referenceId}-manifestation`, - "#text": manifestation, + "#text": encodeToHtml(manifestation ?? NOT_SPECIFIED), }, { - "#text": formatDateToHumanReadableFormat(reaction?.onset) ?? NOT_SPECIFIED, + "#text": encodeToHtml( + formatDateToHumanReadableFormat(reaction?.onset) ?? NOT_SPECIFIED + ), },packages/core/src/fhir-to-cda/cda-templates/components/problems.ts (1)
113-133
: A couple more fields should be HTML-encoded.
icdCode
and the human-readable clinical-status string can theoretically contain characters that break XML. ApplyencodeToHtml
for completeness and to match the other newly-encoded columns.- "#text": getIcdCode(condition.resource.code), + "#text": encodeToHtml(getIcdCode(condition.resource.code)), … - "#text": clinicalStatus?._displayName ?? NOT_SPECIFIED, + "#text": encodeToHtml(clinicalStatus?._displayName ?? NOT_SPECIFIED),
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (16)
packages/api/src/external/cda/generate-empty-ccd.ts
(8 hunks)packages/api/src/routes/internal/medical/patient.ts
(1 hunks)packages/api/src/routes/medical/patient.ts
(2 hunks)packages/core/src/external/carequality/ihe-gateway-v2/inbound/xcpd/create/xcpd-response.ts
(1 hunks)packages/core/src/external/fhir/export/string/shared/identifier.ts
(1 hunks)packages/core/src/fhir-to-cda/cda-templates/components/allergies.ts
(4 hunks)packages/core/src/fhir-to-cda/cda-templates/components/encounters.ts
(3 hunks)packages/core/src/fhir-to-cda/cda-templates/components/family-history.ts
(3 hunks)packages/core/src/fhir-to-cda/cda-templates/components/immunizations.ts
(3 hunks)packages/core/src/fhir-to-cda/cda-templates/components/medications.ts
(3 hunks)packages/core/src/fhir-to-cda/cda-templates/components/problems.ts
(3 hunks)packages/core/src/fhir-to-cda/cda-templates/components/procedures.ts
(3 hunks)packages/lambdas/src/ihe-gateway-v2-inbound-patient-discovery.ts
(3 hunks)packages/shared/src/common/metriport-organization.ts
(1 hunks)packages/utils/package.json
(1 hunks)packages/utils/src/saml/mock-ihe-gateway.ts
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.ts`: - Use the Onion Pattern to organize a package's code in layers - Try to use immutable code and avoid sharing state across different functions, objects, and systems - Try...
**/*.ts
: - Use the Onion Pattern to organize a package's code in layers
- Try to use immutable code and avoid sharing state across different functions, objects, and systems
- Try to build code that's idempotent whenever possible
- Prefer functional programming style functions: small, deterministic, 1 input, 1 output
- Minimize coupling / dependencies
- Avoid modifying objects received as parameter
- Only add comments to code to explain why something was done, not how it works
- Naming
- classes, enums:
PascalCase
- constants, variables, functions:
camelCase
- file names:
kebab-case
- table and column names:
snake_case
- Use meaningful names, so whoever is reading the code understands what it means
- Don’t use negative names, like
notEnabled
, preferisDisabled
- For numeric values, if the type doesn’t convey the unit, add the unit to the name
- Typescript
- Use types
- Prefer
const
instead oflet
- Avoid
any
and casting fromany
to other types- Type predicates: only applicable to narrow down the type, not to force a complete type conversion
- Prefer deconstructing parameters for functions instead of multiple parameters that might be of
the same type- Don’t use
null
inside the app, only on code interacting with external interfaces/services,
like DB and HTTP; convert toundefined
before sending inwards into the code- Use
async/await
instead of.then()
- Use the strict equality operator
===
, don’t use abstract equality operator==
- When calling a Promise-returning function asynchronously (i.e., not awaiting), use
.catch()
to
handle errors (seeprocessAsyncError
andemptyFunction
depending on the case)- Date and Time
- Always use
buildDayjs()
to createdayjs
instances- Prefer
dayjs.duration(...)
to create duration consts and keep them asduration
- Prefer Nullish Coalesce (??) than the OR operator (||) to provide a default value
- Avoid creating arrow functions
- Use truthy syntax instead of
in
- i.e.,if (data.link)
notif ('link' in data)
- Error handling
- Pass the original error as the new one’s
cause
so the stack trace is persisted- Error messages should have a static message - add dynamic data to MetriportError's
additionalInfo
prop- Avoid sending multiple events to Sentry for a single error
- Global constants and variables
- Move literals to constants declared after imports when possible (avoid magic numbers)
- Avoid shared, global objects
- Avoid using
console.log
andconsole.error
in packages other than utils, infra and shared,
and try to useout().log
instead- Avoid multi-line logs
- don't send objects as a second parameter to
console.log()
orout().log()
- don't create multi-line strings when using
JSON.stringify()
- Use
eslint
to enforce code style- Use
prettier
to format code- max column length is 100 chars
- multi-line comments use
/** */
- scripts: top-level comments go after the import
packages/core/src/fhir-to-cda/cda-templates/components/encounters.ts
packages/api/src/routes/medical/patient.ts
packages/core/src/fhir-to-cda/cda-templates/components/immunizations.ts
packages/core/src/fhir-to-cda/cda-templates/components/medications.ts
packages/core/src/fhir-to-cda/cda-templates/components/allergies.ts
packages/core/src/fhir-to-cda/cda-templates/components/family-history.ts
packages/utils/src/saml/mock-ihe-gateway.ts
packages/core/src/fhir-to-cda/cda-templates/components/procedures.ts
packages/core/src/fhir-to-cda/cda-templates/components/problems.ts
packages/core/src/external/carequality/ihe-gateway-v2/inbound/xcpd/create/xcpd-response.ts
packages/shared/src/common/metriport-organization.ts
packages/core/src/external/fhir/export/string/shared/identifier.ts
packages/lambdas/src/ihe-gateway-v2-inbound-patient-discovery.ts
packages/api/src/routes/internal/medical/patient.ts
packages/api/src/external/cda/generate-empty-ccd.ts
🧠 Learnings (2)
packages/api/src/routes/medical/patient.ts (2)
Learnt from: leite08
PR: metriport/metriport#3814
File: packages/api/src/routes/internal/medical/patient-consolidated.ts:141-174
Timestamp: 2025-05-20T21:26:26.804Z
Learning: The functionality introduced in packages/api/src/routes/internal/medical/patient-consolidated.ts is planned to be refactored in downstream PR #3857, including improvements to error handling and validation.
Learnt from: leite08
PR: metriport/metriport#3942
File: packages/core/src/command/consolidated/search/fhir-resource/search-consolidated.ts:48-55
Timestamp: 2025-06-01T13:42:46.270Z
Learning: In the consolidated search architecture, SearchConsolidatedParams interface allows optional query to support different implementation strategies. The searchPatientConsolidated function requires a defined query parameter because it's only called when query is guaranteed to be present. When query is undefined, SearchConsolidatedDirect branches to use getConsolidatedPatientData instead. This design pattern allows interface flexibility while maintaining implementation specificity.
packages/api/src/routes/internal/medical/patient.ts (1)
Learnt from: leite08
PR: metriport/metriport#3814
File: packages/api/src/routes/internal/medical/patient-consolidated.ts:141-174
Timestamp: 2025-05-20T21:26:26.804Z
Learning: The functionality introduced in packages/api/src/routes/internal/medical/patient-consolidated.ts is planned to be refactored in downstream PR #3857, including improvements to error handling and validation.
🧬 Code Graph Analysis (8)
packages/core/src/fhir-to-cda/cda-templates/components/encounters.ts (1)
packages/shared/src/common/html.ts (1)
encodeToHtml
(1-8)
packages/core/src/fhir-to-cda/cda-templates/components/immunizations.ts (1)
packages/shared/src/common/html.ts (1)
encodeToHtml
(1-8)
packages/core/src/fhir-to-cda/cda-templates/components/medications.ts (1)
packages/shared/src/common/html.ts (1)
encodeToHtml
(1-8)
packages/core/src/fhir-to-cda/cda-templates/components/allergies.ts (1)
packages/shared/src/common/html.ts (1)
encodeToHtml
(1-8)
packages/core/src/fhir-to-cda/cda-templates/components/procedures.ts (2)
packages/shared/src/common/html.ts (1)
encodeToHtml
(1-8)packages/utils/src/fhir/fhir-deduplication/report/resource-props.ts (1)
getNotes
(314-328)
packages/core/src/fhir-to-cda/cda-templates/components/problems.ts (1)
packages/shared/src/common/html.ts (1)
encodeToHtml
(1-8)
packages/shared/src/common/metriport-organization.ts (1)
packages/core/src/domain/organization.ts (1)
Organization
(52-55)
packages/api/src/external/cda/generate-empty-ccd.ts (2)
packages/shared/src/common/html.ts (1)
encodeToHtml
(1-8)packages/shared/src/common/metriport-organization.ts (1)
metriportOrganization
(4-24)
⏰ Context from checks skipped due to timeout of 90000ms (6)
- GitHub Check: check-pr / lint-build-test
- GitHub Check: check-pr / lint-build-test
- GitHub Check: check-pr / lint-build-test
- GitHub Check: check-pr / lint-build-test
- GitHub Check: check-pr / lint-build-test
- GitHub Check: Analyze (javascript)
🔇 Additional comments (12)
packages/core/src/external/fhir/export/string/shared/identifier.ts (1)
37-39
: Good defensive conversion, but double-check edge casesConverting
identifier.value
withString()
is a nice way to accept numbers, but note that:
0
orfalse
are filtered out because of theif (!identifier?.value)
guard – that’s fine for FHIR (wherevalue
should be a non-empty string) but worth keeping in mind if the upstream type ever loosens.String(null)
/String(undefined)
will never be reached because of the same guard – 👍.Looks good overall.
packages/utils/package.json (1)
27-29
:✅ Verification successful
Verify that the new script target actually exists
The script now references
src/saml/mock-ihe-gateway
. Ensure:
packages/utils/src/saml/mock-ihe-gateway.ts
is committed.- The file’s default export is still executable via
ts-node
(no breaking import path changes).
🏁 Script executed:
#!/bin/bash # List the expected file to confirm it’s present fd mock-ihe-gateway.ts -ILength of output: 71
🏁 Script executed:
#!/bin/bash # Display the first few lines to check for a shebang and inspect default export echo "=== Shebang Check ===" head -n 5 packages/utils/src/saml/mock-ihe-gateway.ts echo -e "\n=== Default Export Check ===" grep -R "export default" packages/utils/src/saml/mock-ihe-gateway.ts || echo "No default export found"Length of output: 579
Script target verified and ready to run
- Confirmed packages/utils/src/saml/mock-ihe-gateway.ts is present.
- This is a standalone ts-node script (top-level code), so no default export is required for execution.
packages/api/src/routes/medical/patient.ts (2)
8-9
:out()
usage: make sure typings still alignYou added
import { out } from "@metriport/core/util/log";
.
Double-check thatout(string)
returns an object with.log()
– older versions exportedout()
(no params) returning a logger. If the signature changed you’ll get a TS error at compile time.No change requested if it already compiles.
202-203
: Patient & customer identifiers now hit the logs
cx ${patient.cxId} pt ${patient.id}
is useful for debugging, but these are PHI/PII. Confirm that:
- The logger is configured to route these fields to a secure destination (or to be redacted in lower-envs).
- We’re not violating any internal policy that forbids patient identifiers in plain logs.
If that’s already covered by the logging infra, 👍.
packages/core/src/fhir-to-cda/cda-templates/components/medications.ts (2)
3-3
: HTML-encoding import is a solid additionImporting
encodeToHtml
brings the medications component in line with the other CDA templates and mitigates injection issues.
116-117
: Text is now safely escaped – verify callers aren’t double-encoding
encodeToHtml(medicationName ?? NOT_SPECIFIED)
correctly escapes unsafe characters.
Just confirm upstream data hasn’t already been encoded, otherwise you’ll end up with&lt;
.packages/core/src/fhir-to-cda/cda-templates/components/encounters.ts (2)
3-3
: Consistent HTML escaping introducedGood to see
encodeToHtml
imported – aligns with other sections.
153-159
: Escaping provider & location fields looks goodBoth practitioner info and location description are now HTML-safe. No further issues spotted.
packages/core/src/fhir-to-cda/cda-templates/components/family-history.ts (2)
8-8
: Import ofencodeToHtml
aligns with security best practices👍 Brings the family-history template in line with the new encoding standard.
136-143
: Relationship, name & comments now escapedThe new encoding prevents broken markup when commas/apostrophes appear in free-text. Looks correct.
packages/shared/src/common/metriport-organization.ts (1)
4-5
: Type-safety refinement looks solid.
Narrowing the type withRequired<…>
guarantees callers always have the critical organisation fields available. No additional concerns.packages/api/src/external/cda/generate-empty-ccd.ts (1)
30-48
: Encoding additions LGTM.Dynamic patient and organisation strings are now safely escaped, eliminating injection risks in generated CCDs.
No further issues spotted.
packages/core/src/external/carequality/ihe-gateway-v2/inbound/xcpd/create/xcpd-response.ts
Outdated
Show resolved
Hide resolved
Ref eng-454 Signed-off-by: Rafael Leite <2132564+leite08@users.noreply.github.com>
ENG-454 Custodian on XCPD doesn't have assignedCustodian
Issues:
Dependencies
none
Description
Testing
Check each PR.
Release Plan
master
Summary by CodeRabbit
Summary by CodeRabbit