Skip to content

Conversation

keshavsaharia
Copy link
Contributor

@keshavsaharia keshavsaharia commented Jun 18, 2025

metriport/metriport-internal#1040

Issues:

Dependencies

Description

This uses UTC time via buildDayjs for the MedicationDispense and MedicationRequest resources (on the dateWritten and whenHandedOver dates). It also adds an "outpatient" category to the MedicationRequest since all Surescripts data is retrieve from PBMs (pharmacy benefits managers) who are collecting data from pharmacies.

Testing

  • Local
    • Generated test bundles with npm run surescripts -- convert-customer-response ... (see other PRs)
  • Staging
    • Run on test bundles for staging patients
  • Production
    • Run test with production system and Lambdas

Release Plan

  • Merge this

Summary by CodeRabbit

  • New Features

    • Added support for including a standardized "outpatient" category in medication requests when applicable.
    • Introduced an optional output file parameter for Surescripts analysis exports.
  • Bug Fixes

    • Improved date handling for medication dispense and medication request records to ensure consistent formatting.
    • Enhanced network reliability with automatic retries for term server requests.
  • Chores

    • Refined SFTP write action to return content length for better result tracking.
    • Streamlined Surescripts response conversion handlers for improved code reuse.
    • Updated coverage resources to include patient references and placeholders for payor information.
    • Removed Provenance resource generation related to Surescripts data.
    • Adjusted deduplication logic to improve resource handling consistency.

Copy link

linear bot commented Jun 18, 2025

Copy link

coderabbitai bot commented Jun 18, 2025

Walkthrough

The updates standardize date handling in medication-related modules by replacing direct toISOString() calls with the buildDayjs utility. Additionally, a new function is introduced to provide a fixed category for outpatient medication requests, which is conditionally included in the resulting FHIR MedicationRequest object.

Changes

File(s) Change Summary
packages/core/src/external/surescripts/fhir/medication-dispense.ts Replaced direct toISOString() usage with buildDayjs(...).toISOString() for date processing.
packages/core/src/external/surescripts/fhir/medication-request.ts Added getDispenseCategory function; updated date handling to use buildDayjs; updated imports.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant MedicationRequestModule

    Caller->>MedicationRequestModule: getMedicationRequest(detail)
    MedicationRequestModule->>MedicationRequestModule: getAuthoredOn(detail)
    MedicationRequestModule->>MedicationRequestModule: buildDayjs(detail.dateWritten).toISOString()
    MedicationRequestModule->>MedicationRequestModule: getDispenseCategory()
    MedicationRequestModule-->>Caller: MedicationRequest object (with category and authoredOn)
Loading
sequenceDiagram
    participant Caller
    participant MedicationDispenseModule

    Caller->>MedicationDispenseModule: getWhenHandedOver(detail)
    MedicationDispenseModule->>MedicationDispenseModule: buildDayjs(detail.dateWritten).toISOString()
    MedicationDispenseModule-->>Caller: ISO date string
Loading

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

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: C0ACAFE8787F0000: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-18T19_54_13_590Z-debug-0.log

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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

⚠️ This PR is titled PATCH or RELEASE but its not targeting the master branch. Please update the base branch to master or update the PR title.

@keshavsaharia keshavsaharia marked this pull request as ready for review June 18, 2025 18:01
Copy link

⚠️ This PR is titled PATCH or RELEASE but its not targeting the master branch. Please update the base branch to master or update the PR title.

Copy link

⚠️ This PR is titled PATCH or RELEASE but its not targeting the master branch. Please update the base branch to master or update the PR title.

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 (2)
packages/core/src/external/surescripts/fhir/medication-request.ts (2)

19-19: Optimize unnecessary conditional check.

Since getDispenseCategory() always returns a non-empty array, the conditional check is unnecessary and adds complexity.

- const category = getDispenseCategory();
+ const category = getDispenseCategory();
- ...(category ? { category } : undefined),
+ category,

Also applies to: 26-26


44-55: Consider more descriptive function naming.

The function name getDispenseCategory might be misleading since it returns a medication request category, not a dispense-specific category. The implementation correctly provides the outpatient category as specified in the PR objectives.

Consider renaming to be more descriptive:

-function getDispenseCategory(): MedicationRequest["category"] {
+function getMedicationRequestCategory(): MedicationRequest["category"] {

And update the usage accordingly:

- const category = getDispenseCategory();
+ const category = getMedicationRequestCategory();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d5c7cc7 and 21edb57.

📒 Files selected for processing (2)
  • packages/core/src/external/surescripts/fhir/medication-dispense.ts (2 hunks)
  • packages/core/src/external/surescripts/fhir/medication-request.ts (3 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/surescripts/fhir/medication-dispense.ts
  • packages/core/src/external/surescripts/fhir/medication-request.ts
🧠 Learnings (3)
📓 Common learnings
Learnt from: keshavsaharia
PR: metriport/metriport#3885
File: packages/core/src/external/surescripts/client.ts:0-0
Timestamp: 2025-05-30T01:09:55.013Z
Learning: In packages/core/src/external/surescripts/client.ts, the Surescripts date formatting should use local time according to their documentation ("message-date-must-be-local"), which means buildDayjs() cannot be used since it defaults to UTC. The specific use case for transmission date formatting requires dayjs to be used directly to preserve local time behavior.
packages/core/src/external/surescripts/fhir/medication-dispense.ts (1)
Learnt from: keshavsaharia
PR: metriport/metriport#3885
File: packages/core/src/external/surescripts/client.ts:0-0
Timestamp: 2025-05-30T01:09:55.013Z
Learning: In packages/core/src/external/surescripts/client.ts, the Surescripts date formatting should use local time according to their documentation ("message-date-must-be-local"), which means buildDayjs() cannot be used since it defaults to UTC. The specific use case for transmission date formatting requires dayjs to be used directly to preserve local time behavior.
packages/core/src/external/surescripts/fhir/medication-request.ts (2)
Learnt from: thomasyopes
PR: metriport/metriport#3970
File: packages/api/src/external/ehr/athenahealth/command/write-back/medication.ts:17-17
Timestamp: 2025-06-06T16:45:31.832Z
Learning: The writeMedicationToChart function in packages/api/src/external/ehr/athenahealth/command/write-back/medication.ts returns a response that is not currently used by any consumers, so changes to its return type are not breaking changes in practice.
Learnt from: keshavsaharia
PR: metriport/metriport#3885
File: packages/core/src/external/surescripts/client.ts:0-0
Timestamp: 2025-05-30T01:09:55.013Z
Learning: In packages/core/src/external/surescripts/client.ts, the Surescripts date formatting should use local time according to their documentation ("message-date-must-be-local"), which means buildDayjs() cannot be used since it defaults to UTC. The specific use case for transmission date formatting requires dayjs to be used directly to preserve local time behavior.
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (4)
packages/core/src/external/surescripts/fhir/medication-dispense.ts (2)

8-8: LGTM: Import follows coding guidelines.

Adding the buildDayjs import aligns with the coding guideline to "Always use buildDayjs() to create dayjs instances."


53-53: LGTM: Date handling standardization.

The change from direct toISOString() to buildDayjs().toISOString() correctly standardizes date handling for FHIR resources and ensures UTC formatting as intended by the PR objectives.

packages/core/src/external/surescripts/fhir/medication-request.ts (2)

2-2: LGTM: Import follows coding guidelines.

Adding the buildDayjs import aligns with the coding guideline to "Always use buildDayjs() to create dayjs instances."


59-59: LGTM: Date handling standardization.

The change from direct toISOString() to buildDayjs().toISOString() correctly standardizes date handling for FHIR resources and ensures UTC formatting as intended by the PR objectives.

@keshavsaharia keshavsaharia changed the title PATCH: fix(core): uses buildDayjs and UTC for medication resources, and adds "outpatient" category PATCH: fix(core): uses buildDayjs and UTC for medication resources, adds "outpatient" category, and minor fixes Jun 18, 2025
Copy link

⚠️ This PR is titled PATCH or RELEASE but its not targeting the master branch. Please update the base branch to master or update the PR title.

Copy link
Member

@leite08 leite08 left a comment

Choose a reason for hiding this comment

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

Let's leave "patch" for patches (PRs that write into master). This is a regular feature PR.

@keshavsaharia keshavsaharia changed the title PATCH: fix(core): uses buildDayjs and UTC for medication resources, adds "outpatient" category, and minor fixes fix(core): uses buildDayjs and UTC for medication resources, adds "outpatient" category, and minor fixes Jun 18, 2025
@keshavsaharia keshavsaharia enabled auto-merge June 18, 2025 19:05
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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 21edb57 and 5fdf048.

📒 Files selected for processing (12)
  • packages/core/src/external/sftp/command/sftp-action/sftp-action-cloud.ts (0 hunks)
  • packages/core/src/external/sftp/command/sftp-action/sftp-action-direct.ts (1 hunks)
  • packages/core/src/external/sftp/command/sftp-action/sftp-action.ts (1 hunks)
  • packages/core/src/external/surescripts/fhir/coverage.ts (1 hunks)
  • packages/core/src/external/surescripts/fhir/medication.ts (5 hunks)
  • packages/core/src/external/surescripts/fhir/provenance.ts (0 hunks)
  • packages/core/src/external/surescripts/fhir/shared.ts (4 hunks)
  • packages/core/src/external/term-server/index.ts (2 hunks)
  • packages/lambdas/src/surescripts/convert-batch-response.ts (1 hunks)
  • packages/lambdas/src/surescripts/convert-patient-response.ts (1 hunks)
  • packages/utils/src/surescripts/analysis.ts (2 hunks)
  • packages/utils/src/surescripts/convert-customer-response.ts (1 hunks)
💤 Files with no reviewable changes (2)
  • packages/core/src/external/sftp/command/sftp-action/sftp-action-cloud.ts
  • packages/core/src/external/surescripts/fhir/provenance.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/utils/src/surescripts/convert-customer-response.ts
  • packages/core/src/external/term-server/index.ts
  • packages/core/src/external/sftp/command/sftp-action/sftp-action-direct.ts
  • packages/core/src/external/surescripts/fhir/coverage.ts
  • packages/utils/src/surescripts/analysis.ts
  • packages/lambdas/src/surescripts/convert-batch-response.ts
  • packages/lambdas/src/surescripts/convert-patient-response.ts
  • packages/core/src/external/sftp/command/sftp-action/sftp-action.ts
  • packages/core/src/external/surescripts/fhir/medication.ts
  • packages/core/src/external/surescripts/fhir/shared.ts
🧠 Learnings (3)
📓 Common learnings
Learnt from: keshavsaharia
PR: metriport/metriport#3885
File: packages/core/src/external/surescripts/client.ts:0-0
Timestamp: 2025-05-30T01:09:55.013Z
Learning: In packages/core/src/external/surescripts/client.ts, the Surescripts date formatting should use local time according to their documentation ("message-date-must-be-local"), which means buildDayjs() cannot be used since it defaults to UTC. The specific use case for transmission date formatting requires dayjs to be used directly to preserve local time behavior.
packages/core/src/external/surescripts/fhir/medication.ts (1)
Learnt from: thomasyopes
PR: metriport/metriport#3970
File: packages/api/src/external/ehr/athenahealth/command/write-back/medication.ts:17-17
Timestamp: 2025-06-06T16:45:31.832Z
Learning: The writeMedicationToChart function in packages/api/src/external/ehr/athenahealth/command/write-back/medication.ts returns a response that is not currently used by any consumers, so changes to its return type are not breaking changes in practice.
packages/core/src/external/surescripts/fhir/shared.ts (1)
Learnt from: keshavsaharia
PR: metriport/metriport#4045
File: packages/core/src/external/surescripts/fhir/shared.ts:87-93
Timestamp: 2025-06-18T18:50:40.948Z
Learning: The `getResourceFromResourceMap` function in `packages/core/src/external/surescripts/fhir/shared.ts` works correctly as implemented. The comparison `resourceValue === resourceMap[key]` where `resourceValue = resource[key]` is intentional and functions as designed, despite appearing to compare different types.
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • 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 (21)
packages/utils/src/surescripts/analysis.ts (3)

40-40: LGTM: Clean addition of output file option.

The new --out-file option is properly added to the command configuration.


46-46: LGTM: Parameter handling is correct.

The parameter destructuring and type definition properly include the new optional outFile parameter.

Also applies to: 52-52


175-179: LGTM: Directory creation and file writing implementation is solid.

The approach properly creates the target directory recursively and writes the file to the correct location. The use of path.join() ensures proper path handling across platforms.

packages/core/src/external/sftp/command/sftp-action/sftp-action.ts (1)

26-26: LGTM: Improved type semantics for write action result.

The change from undefined to number for the write action result type provides more meaningful feedback by returning the length of written content. This aligns well with the coordinated changes in the SFTP action implementations.

packages/core/src/external/sftp/command/sftp-action/sftp-action-direct.ts (1)

33-34: LGTM: Consistent implementation of write action result.

The change to return action.content.length instead of the client write result provides a more predictable and useful return value. This implementation aligns perfectly with the updated type definition and ensures consistent behavior across different SFTP implementations.

packages/core/src/external/term-server/index.ts (1)

96-98: LGTM: Added network retry resilience.

Wrapping the term server HTTP request with executeWithNetworkRetries improves reliability when interacting with external services. This follows best practices for handling transient network issues without changing the function's interface or response processing logic.

packages/utils/src/surescripts/convert-customer-response.ts (1)

50-50: LGTM: Performance optimization by reusing handler instance.

Moving the handler instantiation outside the loop is a good optimization that reduces unnecessary object creation. Since the SurescriptsConvertPatientResponseHandlerDirect appears to be stateless, reusing the same instance across all transmissions is both safe and efficient.

packages/core/src/external/surescripts/fhir/coverage.ts (2)

15-18: LGTM: Enhanced Coverage resource with patient context.

The function signature enhancement to accept SurescriptsContext and the inclusion of beneficiary reference improve the FHIR Coverage resource construction. The TODO comment appropriately tracks the future enhancement for payor references under the same issue (ENG-377).

Also applies to: 21-21, 28-30


1-68: Inconsistency with PR objectives.

The PR objectives mention "uses buildDayjs and UTC for medication resources, adds 'outpatient' category" but the medication-related files (medication-request.ts and medication-dispense.ts) mentioned in the AI summaries are not included in this review. This creates a disconnect between the stated PR objectives and the files being reviewed.

#!/bin/bash
# Description: Verify if medication-related files exist and contain buildDayjs usage
# Expected: Find medication-request.ts and medication-dispense.ts files with buildDayjs usage

# Search for medication-related files in the surescripts FHIR directory
fd "medication.*\.ts$" packages/core/src/external/surescripts/fhir/

# Search for buildDayjs usage in any surescripts files
rg -A 3 -B 3 "buildDayjs" packages/core/src/external/surescripts/

Likely an incorrect or invalid review comment.

packages/lambdas/src/surescripts/convert-patient-response.ts (2)

2-2: LGTM: Type consolidation improves maintainability.

The consolidation from intersection types to a single SurescriptsJob type simplifies the type system and improves code maintainability.


8-13: LGTM: Handler logic remains intact.

The handler function logic is preserved while benefiting from the simplified type signature.

packages/lambdas/src/surescripts/convert-batch-response.ts (2)

2-2: LGTM: Consistent type consolidation.

The type consolidation matches the pattern used in the patient response handler, maintaining consistency across the codebase.


8-13: LGTM: Simplified handler maintains functionality.

The handler function is appropriately simplified while preserving the core conversion logic.

packages/core/src/external/surescripts/fhir/shared.ts (3)

11-11: LGTM: Import cleanup removes unused types.

The removal of unused Resource and ResourceMap type imports cleanses the import statement.


55-69: Verify the behavioral change in coding deduplication.

Similar to the system identifier deduplication, this function now returns the last found existing resource instead of the first. Please confirm this behavioral change is intentional.


33-47: Verify the behavioral change in deduplication logic.

The deduplication logic has changed from returning the first found existing resource to returning the last found existing resource. This is a significant behavioral change.

Previous behavior: Return immediately upon finding the first existing resource
New behavior: Continue iteration and return the last found existing resource

Please confirm this change is intentional and aligns with the expected deduplication semantics.

#!/bin/bash
# Description: Search for usages of deduplicateBySystemIdentifier to understand the expected behavior
# Expected: Find code that relies on this function to understand if the behavior change is breaking

rg -A 10 -B 5 "deduplicateBySystemIdentifier"
packages/core/src/external/surescripts/fhir/medication.ts (5)

75-76: LGTM: Conditional display field prevents undefined values.

The conditional inclusion of the display field using the ternary operator prevents undefined values from being included in the coding object.


84-85: LGTM: Consistent conditional display handling.

Consistent with the NDC code handling above, this properly handles optional display fields.


99-111: LGTM: Improved return type aligns with FHIR standards.

The change from returning a single Coding to a CodeableConcept with a coding array better aligns with FHIR standards and provides a more structured representation of medication form data.


146-150: LGTM: Refactored ingredient handling improves modularity.

The extraction of ingredient CodeableConcept creation to a dedicated helper function improves code modularity and readability.


170-183: LGTM: Well-structured helper function.

The new helper function properly encapsulates the creation of medication ingredient CodeableConcept with appropriate validation and conditional display field handling.

@@ -72,7 +72,7 @@ function getMedicationNdcCode(detail: ResponseDetail): Coding | undefined {
return {
system: NDC_URL,
code: detail.ndcNumber,
display: detail.drugDescription ?? "",
...(detail.drugDescription ? { display: detail.drugDescription } : undefined),
Copy link
Member

Choose a reason for hiding this comment

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

🤩

Copy link
Member

@leite08 leite08 left a comment

Choose a reason for hiding this comment

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

Approving so we can more forward, but I see some dedup code on packages/core/src/external/surescripts/fhir/shared.ts. Isn't this something we could rely on the global dedup logic?

@keshavsaharia keshavsaharia added this pull request to the merge queue Jun 18, 2025
Merged via the queue into develop with commit d1a944d Jun 18, 2025
17 checks passed
@keshavsaharia keshavsaharia deleted the eng-377-utc-for-medication-events branch June 18, 2025 20:36
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