10000 feat(ihe): fix dob by thomasyopes · Pull Request #4050 · metriport/metriport · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat(ihe): fix dob #4050

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

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

feat(ihe): fix dob #4050

wants to merge 2 commits into from

Conversation

thomasyopes
Copy link
Contributor
@thomasyopes thomasyopes commented Jun 18, 2025

Ref: ENG-482

Issues:

Description

  • edit soap response birthdates to remove dashes

Testing

  • Local
    • N/A
  • Staging
    • inbound returns correct DOB format
  • Sandbox
    • N/A
  • Production
    • inbound returns correct DOB format

Release Plan

  • Merge this

Summary by CodeRabbit

  • Bug Fixes
    • Improved formatting of birth dates and timestamps in XML and SOAP responses to comply with HL7v3 standards for better interoperability.

Ref: ENG-482

Ref: #1040
Signed-off-by: Thomas Yopes <thomasyopes@Thomass-MBP.attlocal.net>
Copy link
linear bot commented Jun 18, 2025

Copy link
coderabbitai bot commented Jun 18, 2025

Walkthrough

The changes update date and timestamp formatting in both inbound and outbound Carequality IHE Gateway v2 modules by replacing manual string manipulations with conversions to HL7v3-compliant date formats using new utility functions. This affects patient birth dates and response/creation timestamps in XML and SOAP envelope constructions without altering control flow or error handling.

Changes

File(s) Change Summary
packages/core/src/external/carequality/ihe-gateway-v2/inbound/xcpd/create/xcpd-response.ts Replaced raw birth date strings with dateToHl7v3Date conversion; replaced timestamp formatting with timestampToHl7v3DateTime
packages/core/src/external/carequality/ihe-gateway-v2/outbound/xcpd/create/iti55-envelope.ts Replaced manual birth date string manipulation with dateToHl7v3Date; replaced timestamp formatting with timestampToHl7v3DateTime; removed unused regex
packages/core/src/external/carequality/ihe-gateway-v2/utils.ts Renamed timestampToSoapBody to timestampToHl7v3DateTime with updated HL7v3 date-time formatting; added new dateToHl7v3Date function

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 10000 's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error code ERR_SSL_WRONG_VERSION_NUMBER
npm error errno ERR_SSL_WRONG_VERSION_NUMBER
npm error request to https://10.0.0.28:4873/punycode/-/punycode-2.3.1.tgz failed, reason: C0DC0FCC177F0000:error:0A00010B:SSL routines:ssl3_get_record:wrong version number:../deps/openssl/openssl/ssl/record/ssl3_record.c:354:
npm error
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-19T16_48_15_389Z-debug-0.log

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need 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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/core/src/external/carequality/ihe-gateway-v2/inbound/xcpd/create/xcpd-response.ts (1)

142-142: Extract repeated DOB formatting into a helper
The same replace(/-/g, "") logic is duplicated. Consider introducing a small formatSoapDate/stripHyphensFromDate utility and reusing it in both builders to adhere to DRY principles.

+// near top of file
+function stripHyphensFromDate(date: string): string {
+  return date.replace(/-/g, "");
+}

--- a/packages/core/src/external/carequality/ihe-gateway-v2/inbound/xcpd/create/xcpd-response.ts
@@ createQueryByParameter(request: InboundPatientDiscoveryReq)
-              "@_value": patientResource.birthDate.replace(/-/g, ""),
+              "@_value": stripHyphensFromDate(patientResource.birthDate),

@@ createSubjectAndRegistrationEvent(response: InboundPatientDiscoveryResp)
-              "@_value": patientResource.birthDate.replace(/-/g, ""),
+              "@_value": stripHyphensFromDate(patientResource.birthDate),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d35b6d7 and cf9995b.

📒 Files selected for processing (1)
  • packages/core/src/external/carequality/ihe-gateway-v2/inbound/xcpd/create/xcpd-response.ts (2 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, prefer isDisabled
    • For numeric values, if the type doesn’t convey the unit, add the unit to the name
  • Typescript
    • Use types
    • Prefer const instead of let
    • Avoid any and casting from any 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 to undefined 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 (see processAsyncError and emptyFunction depending on the case)
    • Date and Time
      • Always use buildDayjs() to create dayjs instances
      • Prefer dayjs.duration(...) to create duration consts and keep them as duration
  • 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) not if ('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 and console.error in packages other than utils, infra and shared,
    and try to use out().log instead
  • Avoid multi-line logs
    • don't send objects as a second parameter to console.log() or out().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/external/carequality/ihe-gateway-v2/inbound/xcpd/create/xcpd-response.ts
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (1)
packages/core/src/external/carequality/ihe-gateway-v2/inbound/xcpd/create/xcpd-response.ts (1)

43-43: Correct DOB formatting for livingSubjectBirthTime
Stripping hyphens via replace(/-/g, "") ensures the birthDate appears as YYYYMMDD in the livingSubjectBirthTime element.

Ref: ENG-482

Ref: #1040
Signed-off-by: Thomas Yopes <thomasyopes@Thomass-MBP.attlocal.net>
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.

Actionable comments posted: 3

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cf9995b and 560fbd5.

📒 Files selected for processing (3)
  • packages/core/src/external/carequality/ihe-gateway-v2/inbound/xcpd/create/xcpd-response.ts (4 hunks)
  • packages/core/src/external/carequality/ihe-gateway-v2/outbound/xcpd/create/iti55-envelope.ts (3 hunks)
  • packages/core/src/external/carequality/ihe-gateway-v2/utils.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/external/carequality/ihe-gateway-v2/inbound/xcpd/create/xcpd-response.ts
🧰 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, prefer isDisabled
    • For numeric values, if the type doesn’t convey the unit, add the unit to the name
  • Typescript
    • Use types
    • Prefer const instead of let
    • Avoid any and casting from any 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 to undefined 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 (see processAsyncError and emptyFunction depending on the case)
    • Date and Time
      • Always use buildDayjs() to create dayjs instances
      • Prefer dayjs.duration(...) to create duration consts and keep them as duration
  • 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) not if ('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 and console.error in packages other than utils, infra and shared,
    and try to use out().log instead
  • Avoid multi-line logs
    • don't send objects as a second parameter to console.log() or out().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/external/carequality/ihe-gateway-v2/outbound/xcpd/create/iti55-envelope.ts
  • packages/core/src/external/carequality/ihe-gateway-v2/utils.ts
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (2)
packages/core/src/external/carequality/ihe-gateway-v2/outbound/xcpd/create/iti55-envelope.ts (2)

14-14: LGTM on import statement.

The import correctly brings in the new HL7v3 formatting utility functions.


65-65: Correct usage of timestamp formatting.

The implementation properly uses the new timestampToHl7v3DateTime function to format creation time according to HL7v3 standards.

Comment on lines +6 to +8
export function timestampToHl7v3DateTime(createdTimestamp: string): string {
return dayjs(createdTimestamp).format("YYYYMMDDHHmmss");
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Good implementation but add input validation.

The function correctly formats timestamps to HL7v3 standard format. However, consider adding input validation to handle undefined/null values gracefully.

 export function timestampToHl7v3DateTime(createdTimestamp: string): string {
+  if (!createdTimestamp) {
+    throw new Error("createdTimestamp is required");
+  }
   return dayjs(createdTimestamp).format("YYYYMMDDHHmmss");
 }
📝 Committable suggestion

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

Suggested change
export function timestampToHl7v3DateTime(createdTimestamp: string): string {
return dayjs(createdTimestamp).format("YYYYMMDDHHmmss");
}
export function timestampToHl7v3DateTime(createdTimestamp: string): string {
if (!createdTimestamp) {
throw new Error("createdTimestamp is required");
}
return dayjs(createdTimestamp).format("YYYYMMDDHHmmss");
}
🤖 Prompt for AI Agents
In packages/core/src/external/carequality/ihe-gateway-v2/utils.ts around lines 6
to 8, the function timestampToHl7v3DateTime lacks input validation for undefined
or null values. Add a check at the start of the function to verify if
createdTimestamp is defined and not null; if it is invalid, return an empty
string or a default value. This will prevent runtime errors and handle invalid
inputs gracefully.

Comment on lines +10 to 12
export function dateToHl7v3Date(date: string): string {
return dayjs(date).format("YYYYMMDD");
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add input validation for robust error handling.

The function correctly formats dates to HL7v3 standard format without dashes. However, it should handle undefined/null inputs to prevent runtime errors when dayjs(undefined) creates an invalid date object.

 export function dateToHl7v3Date(date: string): string {
+  if (!date) {
+    throw new Error("date is required");
+  }
   return dayjs(date).format("YYYYMMDD");
 }

Alternatively, if undefined dates should be handled gracefully:

-export function dateToHl7v3Date(date: string): string {
+export function dateToHl7v3Date(date: string | undefined): string | undefined {
+  if (!date) {
+    return undefined;
+  }
   return dayjs(date).format("YYYYMMDD");
 }
📝 Committable suggestion

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

Suggested change
export function dateToHl7v3Date(date: string): string {
return dayjs(date).format("YYYYMMDD");
}
export function dateToHl7v3Date(date: string): string {
if (!date) {
throw new Error("date is required");
}
return dayjs(date).format("YYYYMMDD");
}
Suggested change
export function dateToHl7v3Date(date: string): string {
return dayjs(date).format("YYYYMMDD");
}
export function dateToHl7v3Date(date: string | undefined): string | undefined {
if (!date) {
return undefined;
}
return dayjs(date).format("YYYYMMDD");
}
🤖 Prompt for AI Agents
In packages/core/src/external/carequality/ihe-gateway-v2/utils.ts around lines
10 to 12, the dateToHl7v3Date function lacks input validation and can throw
runtime errors if the input date is undefined or null. Add a check at the start
of the function to verify the input is a valid non-null string; if not, handle
it gracefully by either returning an empty string or throwing a descriptive
error. This prevents dayjs from processing invalid inputs and ensures robust
error handling.

@@ -247,7 +246,7 @@ function createSoapBody({
const providerId = bodyData.principalCareProviderIds[0];
const homeCommunityId = getHomeCommunityId(gateway, bodyData.samlAttributes);
const patientGender = mapFhirToIheGender(bodyData.patientResource.gender);
const patientBirthtime = bodyData.patientResource.birthDate?.replace(DATE_DASHES_REGEX, "");
const patientBirthtime = dateToHl7v3Date(bodyData.patientResource.birthDate);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle optional birth date to prevent runtime errors.

The birthDate property might be undefined according to FHIR specification, but dateToHl7v3Date expects a string parameter. This could cause runtime errors if the utility function doesn't handle undefined values.

-  const patientBirthtime = dateToHl7v3Date(bodyData.patientResource.birthDate);
+  const patientBirthtime = bodyData.patientResource.birthDate 
+    ? dateToHl7v3Date(bodyData.patientResource.birthDate) 
+    : undefined;

This ensures that dateToHl7v3Date is only called when birthDate is defined, preventing potential runtime errors.

📝 Committable suggestion

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

Suggested change
const patientBirthtime = dateToHl7v3Date(bodyData.patientResource.birthDate);
const patientBirthtime = bodyData.patientResource.birthDate
? dateToHl7v3Date(bodyData.patientResource.birthDate)
: undefined;
🤖 Prompt for AI Agents
In
packages/core/src/external/carequality/ihe-gateway-v2/outbound/xcpd/create/iti55-envelope.ts
at line 249, the code calls dateToHl7v3Date with
bodyData.patientResource.birthDate which may be undefined. To fix this, add a
check to ensure birthDate is defined before calling dateToHl7v3Date, and only
call it if birthDate is a valid string. This prevents runtime errors from
passing undefined to the function.

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
0