Skip to content
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

Micro birth plan #14

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

Conversation

SauravBizbRolly
Copy link
Collaborator

@SauravBizbRolly SauravBizbRolly commented Feb 26, 2025

πŸ“‹ Description

JIRA ID:

Micro birth plan


βœ… 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

  • New Features
    • Introduced comprehensive micro birth plan management capabilities, allowing users to create, view, update, and delete records via new endpoints.
    • Enhanced eligible couple data with additional details, including the last menstrual period date for improved record accuracy.
    • Added a new data transfer object for encapsulating user ID and associated birth plan entries.
    • Implemented a new repository for managing micro birth plan data.
    • Added a service layer for handling business logic related to micro birth plans.

Copy link

coderabbitai bot commented Feb 26, 2025

Warning

Rate limit exceeded

@SauravBizbRolly has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 22 minutes and 56 seconds before requesting another review.

βŒ› How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between e961c0b and 53f31f2.

πŸ“’ Files selected for processing (1)
  • src/main/java/com/iemr/flw/service/impl/MicroBirthPlanServiceImpl.java (1 hunks)

Walkthrough

This pull request introduces functionalities for managing micro birth plans. A new REST controller provides endpoints to create, retrieve all, and fetch specific micro birth plans by ID. Additionally, a domain entity with JPA mapping, a corresponding DTO, a Spring Data repository, and a service layer (interface and implementation) are added to encapsulate CRUD operations. An existing DTO is also updated with a new Timestamp field (lmp_Date). The changes leverage Spring Boot annotations and CORS support for seamless integration.

Changes

File(s) Change Summary
src/main/java/com/iemr/flw/{controller/MicroBirthPlanController.java, domain/iemr/MicroBirthPlan.java, dto/MicroBirthPlanDTO.java, repo/MicroBirthPlanRepository.java, service/(MicroBirthPlanService.java, impl/MicroBirthPlanServiceImpl.java)} Introduced new classes and interfaces for micro birth plan management, including a REST controller with endpoints to create, list, and retrieve plans; a JPA-mapped domain entity; a DTO for encapsulating user data; a repository for CRUD operations; and a service layer for business logic.
src/main/java/com/iemr/flw/dto/.../EligibleCoupleDTO.java Added a new Timestamp field lmp_Date to capture the last menstrual period date.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant MC as MicroBirthPlanController
    participant S as MicroBirthPlanService
    participant R as MicroBirthPlanRepository
    C->>MC: POST /saveAll (MicroBirthPlanDTO)
    MC->>S: createMicroBirthPlan(MicroBirthPlanDTO)
    S->>R: Save/Update each MicroBirthPlan entry
    R-->>S: Persisted entry
    S-->>MC: MicroBirthPlan
    MC-->>C: ResponseEntity with created MicroBirthPlan
Loading
sequenceDiagram
    participant C as Client
    participant MC as MicroBirthPlanController
    participant S as MicroBirthPlanService
    participant R as MicroBirthPlanRepository
    C->>MC: GET /getAll?userId={userId}
    MC->>S: getAllMicroBirthPlans(userId)
    S->>R: Query micro birth plans by userId
    R-->>S: List of MicroBirthPlan
    S-->>MC: Map with entries
    MC-->>C: ResponseEntity with plan list
Loading

Suggested reviewers

  • helenKaryamsetty

Poem

In the garden of code, I happily roam,
New endpoints and services make this project my home.
Micro plans spring to life with each line I write,
A digital meadow bathed in pure delight.
With hops and skips, I celebrate the change anew,
Coding tales of magic for me and you! 🐰✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❀️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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: 9

🧹 Nitpick comments (9)
src/main/java/com/iemr/flw/dto/iemr/EligibleCoupleDTO.java (1)

108-109: Use consistent naming convention for the new field.

The new field lmp_Date uses snake_case with a capital 'D', which is inconsistent with the camelCase naming convention used for all other fields in this class.

-    private Timestamp lmp_Date;
+    private Timestamp lmpDate;
src/main/java/com/iemr/flw/repo/iemr/MicroBirthPlanRepository.java (2)

7-8: Remove unused import.

The java.util.List import is not used in this interface and should be removed.

-import java.util.List;

9-11: Consider using Long as ID type and add finder method.

Two recommendations:

  1. Use Long instead of Integer for consistency with other entity IDs in the system
  2. Add a dedicated method to find birth plans by userId to improve code readability
@Repository
-public interface MicroBirthPlanRepository extends JpaRepository<MicroBirthPlan, Integer> {
+public interface MicroBirthPlanRepository extends JpaRepository<MicroBirthPlan, Long> {
+    List<MicroBirthPlan> findByUserId(Long userId);
}
src/main/java/com/iemr/flw/service/MicroBirthPlanService.java (2)

5-8: Remove unused imports.

The following imports are not used in this interface and should be removed:

  • com.iemr.flw.repo.iemr.MicroBirthPlanRepository
  • lombok.RequiredArgsConstructor
  • org.springframework.beans.factory.annotation.Autowired
import com.iemr.flw.domain.iemr.MicroBirthPlan;
import com.iemr.flw.dto.iemr.MicroBirthPlanDTO;
-import com.iemr.flw.repo.iemr.MicroBirthPlanRepository;
-import lombok.RequiredArgsConstructor;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

19-22: Remove unnecessary empty lines.

There are several empty lines at the end of the file that should be removed.

    Optional<MicroBirthPlan> getMicroBirthPlanById(Integer id) ;

-
-
-
-
}
src/main/java/com/iemr/flw/domain/iemr/MicroBirthPlan.java (3)

27-32: Missing validation for contact numbers

The comments indicate specific validation rules for contact numbers (must be 10 digits, start with 6-9), but there's no validation logic implemented. Consider adding Bean Validation annotations.

@Column(name = "contact_no_1", length = 10)
+@Pattern(regexp = "^[6-9]\\d{9}$", message = "Contact number must be 10 digits and start with 6-9")
private String contactNo1; // Auto-filled, must be 10 digits, starts with 6-9

@Column(name = "contact_no_2", length = 10)
+@Pattern(regexp = "^[6-9]\\d{9}$", message = "Contact number must be 10 digits and start with 6-9")
private String contactNo2; // Optional, 10 digits, starts with 6-9

33-68: Consider adding validation for formatting requirements

Several fields have comments indicating specific formatting requirements (e.g., "all caps", "alphabets only"), but there's no validation logic implemented to enforce these requirements.


72-77: Add created/updated timestamps and remove extra blank lines

Consider adding created and updated timestamp fields for auditing purposes. Also, remove the extra blank lines at the end of the class.

@Column(name = "is_synced")
private Boolean isSynced;

+@Column(name = "created_at")
+private Timestamp createdAt;
+
+@Column(name = "updated_at")
+private Timestamp updatedAt;
-


}
src/main/java/com/iemr/flw/service/impl/MicroBirthPlanServiceImpl.java (1)

82-84: Missing @OverRide annotation for deleteMicroBirthPlan

The deleteMicroBirthPlan method is missing the @Override annotation if it's part of the interface. If it's not part of the interface, consider adding it.

+@Override
public void deleteMicroBirthPlan(Integer id) {
    microBirthPlanRepository.deleteById(id);
}
πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between ec60b74 and ddf10b8.

πŸ“’ Files selected for processing (7)
  • src/main/java/com/iemr/flw/controller/MicroBirthPlanController.java (1 hunks)
  • src/main/java/com/iemr/flw/domain/iemr/MicroBirthPlan.java (1 hunks)
  • src/main/java/com/iemr/flw/dto/iemr/EligibleCoupleDTO.java (1 hunks)
  • src/main/java/com/iemr/flw/dto/iemr/MicroBirthPlanDTO.java (1 hunks)
  • src/main/java/com/iemr/flw/repo/iemr/MicroBirthPlanRepository.java (1 hunks)
  • src/main/java/com/iemr/flw/service/MicroBirthPlanService.java (1 hunks)
  • src/main/java/com/iemr/flw/service/impl/MicroBirthPlanServiceImpl.java (1 hunks)

Comment on lines +1 to +11
package com.iemr.flw.dto.iemr;

import com.iemr.flw.domain.iemr.MicroBirthPlan;
import lombok.Data;

import java.util.List;
@Data
public class MicroBirthPlanDTO {
Integer userId;
List<MicroBirthPlan> entries;
}
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 access modifiers and implement Serializable.

The DTO has several issues that should be addressed:

  1. Fields are missing access modifiers (should be private)
  2. The class doesn't implement Serializable (unlike other DTOs in the codebase)
  3. The DTO directly references a domain entity which breaks layer separation
package com.iemr.flw.dto.iemr;

import com.iemr.flw.domain.iemr.MicroBirthPlan;
import lombok.Data;

import java.util.List;
+import java.io.Serializable;

@Data
-public class MicroBirthPlanDTO {
-    Integer  userId;
-    List<MicroBirthPlan> entries;
+public class MicroBirthPlanDTO implements Serializable {
+    private Long userId;
+    private List<MicroBirthPlanDTO.Entry> entries;
+    
+    @Data
+    public static class Entry implements Serializable {
+        // Add all necessary fields from MicroBirthPlan entity
+        private Integer id;
+        // Other fields from MicroBirthPlan
+    }
}
πŸ“ 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
package com.iemr.flw.dto.iemr;
import com.iemr.flw.domain.iemr.MicroBirthPlan;
import lombok.Data;
import java.util.List;
@Data
public class MicroBirthPlanDTO {
Integer userId;
List<MicroBirthPlan> entries;
}
package com.iemr.flw.dto.iemr;
import com.iemr.flw.domain.iemr.MicroBirthPlan;
import lombok.Data;
import java.util.List;
import java.io.Serializable;
@Data
public class MicroBirthPlanDTO implements Serializable {
private Long userId;
private List<MicroBirthPlanDTO.Entry> entries;
@Data
public static class Entry implements Serializable {
// Add all necessary fields from MicroBirthPlan entity
private Integer id;
// Other fields from MicroBirthPlan
}
}

Comment on lines +13 to +18
@Service
public interface MicroBirthPlanService {
public MicroBirthPlan createMicroBirthPlan(MicroBirthPlanDTO birthPlan);
public List<MicroBirthPlan> getAllMicroBirthPlans(Integer userId);
public Optional<MicroBirthPlan> getMicroBirthPlanById(Integer id) ;

Copy link

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Service annotation should be on implementation, not interface.

Several issues need addressing:

  1. The @Service annotation should be on implementation classes, not interfaces
  2. Interface methods are implicitly public, so the public modifier is redundant
  3. For consistency with other entities, consider using Long instead of Integer for IDs
-@Service
public interface MicroBirthPlanService {
-    public MicroBirthPlan createMicroBirthPlan(MicroBirthPlanDTO birthPlan);
-    public List<MicroBirthPlan> getAllMicroBirthPlans(Integer userId);
-    public Optional<MicroBirthPlan> getMicroBirthPlanById(Integer id) ;
+    MicroBirthPlan createMicroBirthPlan(MicroBirthPlanDTO birthPlan);
+    List<MicroBirthPlan> getAllMicroBirthPlans(Long userId);
+    Optional<MicroBirthPlan> getMicroBirthPlanById(Long id);
πŸ“ 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
@Service
public interface MicroBirthPlanService {
public MicroBirthPlan createMicroBirthPlan(MicroBirthPlanDTO birthPlan);
public List<MicroBirthPlan> getAllMicroBirthPlans(Integer userId);
public Optional<MicroBirthPlan> getMicroBirthPlanById(Integer id) ;
public interface MicroBirthPlanService {
MicroBirthPlan createMicroBirthPlan(MicroBirthPlanDTO birthPlan);
List<MicroBirthPlan> getAllMicroBirthPlans(Long userId);
Optional<MicroBirthPlan> getMicroBirthPlanById(Long id);
}

Comment on lines +15 to +16
@Column(name = "user_id")
private Integer UserId;
Copy link

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Inconsistent naming convention for 'UserId'

The field UserId is using Pascal case while all other fields in the class use camel case. This is inconsistent with Java naming conventions.

@Column(name = "user_id")
-private Integer UserId;
+private Integer userId;
πŸ“ 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
@Column(name = "user_id")
private Integer UserId;
@Column(name = "user_id")
private Integer userId;

Comment on lines +29 to +36

@RequestMapping(value = "getAll",method = RequestMethod.GET)
public ResponseEntity<Map<String, Object>> getAllMicroBirthPlans(@Param("userId")Integer userId) {
Map<String, Object> response = new HashMap<>();
response.put("entries",service.getMicroBirthPlanById(userId));

return ResponseEntity.ok(response);
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Method name inconsistent with implementation

The method getAllMicroBirthPlans actually calls getMicroBirthPlanById(userId) which is incorrect. It should call getAllMicroBirthPlans(userId) to match the method name and expected behavior.

@RequestMapping(value = "getAll",method = RequestMethod.GET)
public ResponseEntity<Map<String, Object>> getAllMicroBirthPlans(@Param("userId")Integer userId) {
     Map<String, Object> response  = new HashMap<>();
-     response.put("entries",service.getMicroBirthPlanById(userId));
+     response.put("entries",service.getAllMicroBirthPlans(userId));

    return ResponseEntity.ok(response);
}
πŸ“ 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
@RequestMapping(value = "getAll",method = RequestMethod.GET)
public ResponseEntity<Map<String, Object>> getAllMicroBirthPlans(@Param("userId")Integer userId) {
Map<String, Object> response = new HashMap<>();
response.put("entries",service.getMicroBirthPlanById(userId));
return ResponseEntity.ok(response);
}
@RequestMapping(value = "getAll",method = RequestMethod.GET)
public ResponseEntity<Map<String, Object>> getAllMicroBirthPlans(@Param("userId")Integer userId) {
Map<String, Object> response = new HashMap<>();
response.put("entries",service.getAllMicroBirthPlans(userId));
return ResponseEntity.ok(response);
}

Comment on lines +38 to +43
@RequestMapping(value = "getAllMicroBirthPlansBy{id}",method = RequestMethod.GET)
public ResponseEntity<MicroBirthPlan> getMicroBirthPlanById(@PathVariable Integer id) {
return service.getMicroBirthPlanById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
Copy link

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Endpoint naming inconsistency

The endpoint path getAllMicroBirthPlansBy{id} doesn't follow standard REST conventions. It would be clearer as /{id} since it's getting a single resource by ID.

-@RequestMapping(value = "getAllMicroBirthPlansBy{id}",method = RequestMethod.GET)
+@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public ResponseEntity<MicroBirthPlan> getMicroBirthPlanById(@PathVariable Integer id) {
    return service.getMicroBirthPlanById(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
}
πŸ“ 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
@RequestMapping(value = "getAllMicroBirthPlansBy{id}",method = RequestMethod.GET)
public ResponseEntity<MicroBirthPlan> getMicroBirthPlanById(@PathVariable Integer id) {
return service.getMicroBirthPlanById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public ResponseEntity<MicroBirthPlan> getMicroBirthPlanById(@PathVariable Integer id) {
return service.getMicroBirthPlanById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}

Comment on lines +16 to +23
@RestController
@RequestMapping(value = "/micro-birthPlan",headers = "Authorization", produces = "application/json")
public class MicroBirthPlanController {
@Autowired
private MicroBirthPlanService service;
@CrossOrigin()
@Operation(summary = "Micro BirthPlan")

Copy link

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Incomplete Operation annotation and security considerations

The @Operation annotation is missing a description. Also, the @CrossOrigin() annotation without parameters allows requests from any origin, which might pose security risks.

@RestController
@RequestMapping(value = "/micro-birthPlan",headers = "Authorization", produces = "application/json")
public class MicroBirthPlanController {
    @Autowired
    private  MicroBirthPlanService service;
-    @CrossOrigin()
-    @Operation(summary = "Micro BirthPlan")
+    @CrossOrigin(origins = "${allowed.origins}")
+    @Operation(summary = "Micro BirthPlan", description = "API endpoints for creating and managing micro birth plans")
πŸ“ 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
@RestController
@RequestMapping(value = "/micro-birthPlan",headers = "Authorization", produces = "application/json")
public class MicroBirthPlanController {
@Autowired
private MicroBirthPlanService service;
@CrossOrigin()
@Operation(summary = "Micro BirthPlan")
@RestController
@RequestMapping(value = "/micro-birthPlan", headers = "Authorization", produces = "application/json")
public class MicroBirthPlanController {
@Autowired
private MicroBirthPlanService service;
@CrossOrigin(origins = "${allowed.origins}")
@Operation(summary = "Micro BirthPlan", description = "API endpoints for creating and managing micro birth plans")

Comment on lines +45 to +47
public List<MicroBirthPlan> getAllMicroBirthPlans(Integer userId) {
return microBirthPlanRepository.findAll().stream().filter(microBirthPlan -> Objects.equals(microBirthPlan.getUserId(), userId)).collect(Collectors.toList());
}
Copy link

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Inefficient implementation of getAllMicroBirthPlans

The current implementation fetches all records from the database and then filters them in memory. This is inefficient and will not scale well. Use a repository method that directly queries for records with the specified userId.

@Override
public List<MicroBirthPlan> getAllMicroBirthPlans(Integer userId) {
-    return microBirthPlanRepository.findAll().stream().filter(microBirthPlan -> Objects.equals(microBirthPlan.getUserId(), userId)).collect(Collectors.toList());
+    return microBirthPlanRepository.findByUserId(userId);
}

You'll need to add this method to the repository:

List<MicroBirthPlan> findByUserId(Integer userId);

Comment on lines +49 to +52
@Override
public Optional<MicroBirthPlan> getMicroBirthPlanById(Integer id) {
return Optional.empty();
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Unimplemented getMicroBirthPlanById method

The getMicroBirthPlanById method returns an empty Optional instead of fetching the actual data from the repository.

@Override
public Optional<MicroBirthPlan> getMicroBirthPlanById(Integer id) {
-    return Optional.empty();
+    return microBirthPlanRepository.findById(id);
}
πŸ“ 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
@Override
public Optional<MicroBirthPlan> getMicroBirthPlanById(Integer id) {
return Optional.empty();
}
@Override
public Optional<MicroBirthPlan> getMicroBirthPlanById(Integer id) {
return microBirthPlanRepository.findById(id);
}

Comment on lines +23 to +41
public MicroBirthPlan createMicroBirthPlan(MicroBirthPlanDTO birthPlan) {
MicroBirthPlan microBirthPlan = null;

for (MicroBirthPlan entry : birthPlan.getEntries()) {
// Check if the entry already exists in the database
Optional<MicroBirthPlan> existingEntry = microBirthPlanRepository.findById(entry.getId());

if (existingEntry.isPresent()) {
updateMicroBirthPlan(entry.getId(),microBirthPlan);
continue;
}

// Set user ID and prepare for saving
entry.setUserId(birthPlan.getUserId());
microBirthPlan = microBirthPlanRepository.save(entry);
}

return microBirthPlan;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical issue in createMicroBirthPlan method

There are several issues with this method:

  1. The microBirthPlan variable is initialized as null but then passed to updateMicroBirthPlan().
  2. The method only returns the last processed entry, not all entries that were processed.
  3. No transaction management is being used for batch operations.
@Override
public MicroBirthPlan createMicroBirthPlan(MicroBirthPlanDTO birthPlan) {
-    MicroBirthPlan microBirthPlan = null;
+    MicroBirthPlan lastProcessedPlan = null;

    for (MicroBirthPlan entry : birthPlan.getEntries()) {
        // Check if the entry already exists in the database
        Optional<MicroBirthPlan> existingEntry = microBirthPlanRepository.findById(entry.getId());

        if (existingEntry.isPresent()) {
-            updateMicroBirthPlan(entry.getId(),microBirthPlan);
+            lastProcessedPlan = updateMicroBirthPlan(entry.getId(), entry);
            continue;
        }

        // Set user ID and prepare for saving
        entry.setUserId(birthPlan.getUserId());
-        microBirthPlan = microBirthPlanRepository.save(entry);
+        lastProcessedPlan = microBirthPlanRepository.save(entry);
    }

-    return microBirthPlan;
+    return lastProcessedPlan;
}

Committable suggestion skipped: line range outside the PR's diff.

@SauravBizbRolly SauravBizbRolly self-assigned this Feb 26, 2025
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)
src/main/java/com/iemr/flw/controller/MicroBirthPlanController.java (1)

24-25: Consider aligning the endpoint name with the returned resource type.

Currently, the endpoint path is "saveAll" while the controller method and service call return a single MicroBirthPlan object, which can be misleading. Consider renaming the endpoint to something like "/create" or "/save" to accurately reflect that it handles a single resource instead of a collection.

Apply this diff to rename the endpoint:

-@RequestMapping(value = "saveAll",method = RequestMethod.POST)
+@RequestMapping(value = "/create", method = RequestMethod.POST)
πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 5b2464a and e961c0b.

πŸ“’ Files selected for processing (1)
  • src/main/java/com/iemr/flw/controller/MicroBirthPlanController.java (1 hunks)
πŸ”‡ Additional comments (3)
src/main/java/com/iemr/flw/controller/MicroBirthPlanController.java (3)

31-34: Method name inconsistent with implementation.
You are retrieving a single micro birth plan by user ID (service.getMicroBirthPlanById(userId)) rather than all micro birth plans. This was raised in a previous review.

Consider updating the code and/or method names to match the functionality:

response.put("entries",
-         service.getMicroBirthPlanById(userId));
+         service.getAllMicroBirthPlans(userId));

39-44: Endpoint naming inconsistency.
The endpoint getAllMicroBirthPlansBy{id} suggests multiple resources but actually returns a single plan by ID. A REST convention for fetching one item by ID would be "/{id}". This was mentioned in a previous review.

Here is the suggested fix:

-@RequestMapping(value = "getAllMicroBirthPlansBy{id}",method = RequestMethod.GET)
+@RequestMapping(value = "/{id}",method = RequestMethod.GET)

21-22: Refactor security and documentation annotations.
You still have a broad @CrossOrigin() without restrictions and lack a detailed description in the @Operation annotation. This was highlighted in an earlier review.

Consider refining your CORS policy and enhancing the OpenAPI documentation, for instance:

-@CrossOrigin()
-@Operation(summary = "Micro BirthPlan")
+@CrossOrigin(origins = "${allowed.origins}")
+@Operation(summary = "Micro BirthPlan", description = "API endpoints for creating and managing micro birth plans")

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.

1 participant