Skip to content

Conversation

@helenKaryamsetty
Copy link
Member

@helenKaryamsetty helenKaryamsetty commented Jun 18, 2025

πŸ“‹ Description

JIRA ID: AMM-1610

Added check to verify if that healthId number has any beneficiaries linked and adding only if not present

βœ… Type of Change

  • 🐞 Bug fix (non-breaking change which resolves an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • πŸ”₯ Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • πŸ›  Refactor (change that is neither a fix nor a new feature)
  • βš™οΈ Config change (configuration file or build script updates)
  • πŸ“š Documentation (updates to docs or readme)
  • πŸ§ͺ Tests (adding new or updating existing tests)
  • 🎨 UI/UX (changes that affect the user interface)
  • πŸš€ Performance (improves performance)
  • 🧹 Chore (miscellaneous changes that don't modify src or test files)

ℹ️ Additional Information

Please describe how the changes were tested, and include any relevant screenshots, logs, or other information that provides additional context.

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced validation to prevent linking a health ID to multiple beneficiary IDs, with user notification if a health ID is already associated.
  • Other

    • Improved data consistency by ensuring detailed profile information is saved when mapping new health IDs.

KA40094929 and others added 30 commits May 21, 2025 01:09
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 18, 2025

Walkthrough

The mapHealthIDToBeneficiary method in HealthIDServiceImpl was updated to prevent a health ID from being linked to multiple beneficiary IDs. The method now checks for existing links before saving new mappings and ensures health ID profile details are saved if missing.

Changes

File(s) Change Summary
src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java Updated mapHealthIDToBeneficiary to check existing health ID links before saving, save profile details if absent, and added @Override annotation.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant HealthIDServiceImpl
    participant Repository

    Client->>HealthIDServiceImpl: mapHealthIDToBeneficiary(request)
    HealthIDServiceImpl->>Repository: find beneficiary IDs linked to health ID
    alt Health ID already linked
        HealthIDServiceImpl-->>Client: Return "already linked" message
    else No existing link
        HealthIDServiceImpl->>Repository: Save BenHealthIDMapping
        HealthIDServiceImpl->>Repository: Check if health ID exists
        alt Health ID missing
            HealthIDServiceImpl->>Repository: Save HealthIDResponse profile
        end
        HealthIDServiceImpl-->>Client: Return saved mapping as JSON
    end
Loading

Possibly related PRs

Suggested reviewers

  • ravishanigarapu

Poem

In a meadow of IDs, a rabbit hops with glee,
Ensuring each health link is singular as can be.
No more tangled mappings, the logic’s crystal clear,
Each beneficiary’s bound, with no duplicate near.
With a twitch of my nose and a hop in my code,
The mappings are tidy, down the health data road! πŸ‡


πŸ“œ Recent review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 3fd09d8 and d807595.

πŸ“’ Files selected for processing (1)
  • src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: style-check / checkstyle
  • GitHub Check: Analyze (java)
  • GitHub Check: Build
  • GitHub Check: Package-test
✨ 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
Contributor

@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

🧹 Nitpick comments (2)
src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java (2)

76-78: Hard-coded string response & potential information leak.

Returning the literal message "HealthId is already linked to other beneficiary ID":

  1. Couples business logic with presentation – use an enum / constant or a proper response DTO.
  2. Discloses existence of the healthId to unauthorised callers (privacy concern). Consider returning a generic conflict/error code (HTTP 409) instead.

108-111: Possible NPE when middle name is absent.

abhaProfileJson.get("middleName").getAsString() will throw if middleName is missing or null.
Use safe extraction:

String middle = abhaProfileJson.has("middleName") && !abhaProfileJson.get("middleName").isJsonNull()
        ? abhaProfileJson.get("middleName").getAsString() : "";
healthID.setName(
        abhaProfileJson.get("firstName").getAsString() + " " + middle + " " +
        abhaProfileJson.get("lastName").getAsString());
πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 6a05670 and 3fd09d8.

πŸ“’ Files selected for processing (1)
  • src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
πŸ““ Common learnings
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#68
File: src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java:0-0
Timestamp: 2025-04-08T10:35:30.482Z
Learning: When no beneficiary IDs are found in the getMappedBenIdForHealthId method, returning "No Beneficiary Found" as a string response is the expected behavior rather than treating it as an error condition.
src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java (1)
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#68
File: src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java:0-0
Timestamp: 2025-04-08T10:35:30.482Z
Learning: When no beneficiary IDs are found in the getMappedBenIdForHealthId method, returning "No Beneficiary Found" as a string response is the expected behavior rather than treating it as an error condition.
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: style-check / checkstyle
  • GitHub Check: Analyze (java)
  • GitHub Check: Build
  • GitHub Check: Package-test

Comment on lines +73 to +78
if (health.getHealthIdNumber() != null) {
beneficiaryIdsList = benHealthIDMappingRepo.getBenIdForHealthId(health.getHealthIdNumber());

for (int i = 0; i < phrAddressArray.size(); i++) {
abhaAddressBuilder.append(phrAddressArray.get(i).getAsString());
if (i < phrAddressArray.size() - 1) {
abhaAddressBuilder.append(", ");
}
}
healthID.setHealthId(abhaAddressBuilder.toString());
healthID.setName(
abhaProfileJson.get("firstName").getAsString() + " " + abhaProfileJson.get("middleName").getAsString() + " " + abhaProfileJson.get("lastName").getAsString());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = simpleDateFormat.parse(abhaProfileJson.get("dob").getAsString());
SimpleDateFormat year = new SimpleDateFormat("yyyy");
SimpleDateFormat month = new SimpleDateFormat("MM");
SimpleDateFormat day = new SimpleDateFormat("dd");
healthID.setYearOfBirth(year.format(date));
healthID.setMonthOfBirth(month.format(date));
healthID.setDayOfBirth(day.format(date));
healthID.setCreatedBy(jsonRequest.get("createdBy").getAsString());
healthID.setProviderServiceMapID(jsonRequest.get("providerServiceMapId").getAsInt());
healthID.setIsNewAbha(jsonRequest.get("isNew").getAsBoolean());
healthIDRepo.save(healthID);
if (beneficiaryIdsList != null && beneficiaryIdsList.length > 0) {
return "HealthId is already linked to other beneficiary ID";
} else {
Copy link
Contributor

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Race condition: β€œcheck-then-save” is not atomic.

Between fetching the existing beneficiary IDs (line 74) and persisting the new mapping (later), another thread could insert a row, bypassing this safeguard and again linking the same healthId to a different beneficiary.
Use a database-level unique constraint on health_id_number (preferred) or wrap the block in a @Transactional method with ISOLATION.SERIALIZABLE / PESSIMISTIC_WRITE locking to guarantee consistency.

πŸ€– Prompt for AI Agents
In src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java around
lines 73 to 78, the current check-then-save logic for verifying if a
healthIdNumber is already linked is not atomic, causing a race condition. To fix
this, add a unique constraint on the health_id_number column at the database
level to prevent duplicates. Alternatively, annotate the method with
@Transactional and use an isolation level of SERIALIZABLE or apply
PESSIMISTIC_WRITE locking to ensure the check and save operations are atomic and
consistent.

Comment on lines 82 to 87
if (health.getBeneficiaryID() != null) {
Long check1 = benHealthIDMappingRepo.getBenRegID(health.getBeneficiaryID());
health.setBeneficiaryRegID(check1);
health = benHealthIDMappingRepo.save(health);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Null-safety & naming.

check1 may be null if getBenRegID finds no record, leading to NULL being persisted in beneficiaryRegID.
Also, the variable name check1 is non-descriptive.

-Long check1 = benHealthIDMappingRepo.getBenRegID(health.getBeneficiaryID());
-health.setBeneficiaryRegID(check1);
+Long beneficiaryRegId = benHealthIDMappingRepo.getBenRegID(health.getBeneficiaryID());
+if (beneficiaryRegId == null) {
+    throw new FHIRException("Invalid beneficiaryID – no matching registration ID found");
+}
+health.setBeneficiaryRegID(beneficiaryRegId);
πŸ“ 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
if (health.getBeneficiaryID() != null) {
Long check1 = benHealthIDMappingRepo.getBenRegID(health.getBeneficiaryID());
health.setBeneficiaryRegID(check1);
health = benHealthIDMappingRepo.save(health);
}
}
if (health.getBeneficiaryID() != null) {
- Long check1 = benHealthIDMappingRepo.getBenRegID(health.getBeneficiaryID());
- health.setBeneficiaryRegID(check1);
+ Long beneficiaryRegId = benHealthIDMappingRepo.getBenRegID(health.getBeneficiaryID());
+ if (beneficiaryRegId == null) {
+ throw new FHIRException("Invalid beneficiaryID – no matching registration ID found");
+ }
+ health.setBeneficiaryRegID(beneficiaryRegId);
health = benHealthIDMappingRepo.save(health);
}
πŸ€– Prompt for AI Agents
In src/main/java/com/wipro/fhir/service/healthID/HealthIDServiceImpl.java around
lines 82 to 87, the variable 'check1' is non-descriptive and may be null if
getBenRegID returns no record, causing null to be saved in beneficiaryRegID.
Rename 'check1' to a meaningful name like 'beneficiaryRegID' and add a null
check before setting beneficiaryRegID and saving the entity to avoid persisting
null values.

@sonarqubecloud
Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
14.3% Duplication on New Code (required ≀ 3%)

See analysis details on SonarQube Cloud

@helenKaryamsetty helenKaryamsetty changed the title Restricting same one ben with one healthId Restricting one ben with one healthId Jun 18, 2025
@ravishanigarapu ravishanigarapu merged commit 737c197 into PSMRI:develop Jun 18, 2025
6 of 8 checks passed
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