Skip to content

Conversation

@SauravBizbRolly
Copy link

@SauravBizbRolly SauravBizbRolly commented Jun 19, 2025

πŸ“‹ Description

JIRA ID:

version 3.3.0 .

βœ… 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 bulk user registration functionality, allowing multiple users to be registered via a single request.
    • Added the ability to download an Excel file containing error logs from bulk registration attempts.
  • Enhancements
    • Improved employee data validation during registration, including checks for unique identifiers and field formats.
  • Bug Fixes
    • Included necessary dependencies and improved internal data handling for bulk operations.
  • Documentation
    • Updated and clarified code formatting for better readability.

@coderabbitai
Copy link

coderabbitai bot commented Jun 19, 2025

Walkthrough

This update introduces a bulk user registration feature using XML data, including new REST endpoints, data models, service interfaces, and implementations. It adds XML and compression dependencies, new repository queries, and utility methods for validation and error reporting. Minor formatting and import adjustments are also included.

Changes

File(s) Change Summary
pom.xml Added jackson-dataformat-xml and commons-compress dependencies; removed exclusion; added commented property value.
.../controller/bulkRegistration/BulkRegistrationController.java New REST controller for bulk registration and error sheet download.
.../data/bulkuser/BulkRegistrationError.java
.../Employee.java
.../EmployeeList.java
New data classes for error logging and XML employee data mapping.
.../data/employeemaster/M_Religion.java Brace style formatting adjustment.
.../repo/employeemaster/EmployeeMasterRepoo.java Added queries for employee lookup by Aadhaar and contact number.
.../service/bulkRegistration/BulkRegistrationService.java New interface for bulk registration service.
.../service/bulkRegistration/BulkRegistrationServiceImpl.java New implementation for bulk registration, validation, and error log Excel generation.
.../service/bulkRegistration/EmployeeXmlService.java New service for XML-to-EmployeeList parsing using Jackson.
.../service/employeemaster/EmployeeMasterInter.java Added methods for employee lookup and saving bulk user.
.../service/employeemaster/EmployeeMasterServiceImpl.java Implemented new lookup and save methods for bulk registration.
.../service/rolemaster/Role_MasterInter.java Added method to retrieve all states; import cleanup.
.../service/rolemaster/Role_Master_ServiceImpl.java Implemented getAllState(); formatting improvements.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant BulkRegistrationController
    participant BulkRegistrationServiceImpl
    participant EmployeeXmlService
    participant EmployeeMasterRepoo
    participant OtherServices

    Client->>BulkRegistrationController: POST /bulkRegistration (XML, Auth)
    BulkRegistrationController->>BulkRegistrationServiceImpl: registerBulkUser(xml, auth)
    BulkRegistrationServiceImpl->>EmployeeXmlService: parseXml(xml)
    EmployeeXmlService-->>BulkRegistrationServiceImpl: EmployeeList
    loop For each Employee
        BulkRegistrationServiceImpl->>EmployeeMasterRepoo: Check username/Aadhaar/contact
        BulkRegistrationServiceImpl->>OtherServices: Validate & lookup IDs
        alt Valid Employee
            BulkRegistrationServiceImpl->>EmployeeMasterRepoo: Save Employee
        else Invalid Employee
            BulkRegistrationServiceImpl->>BulkRegistrationServiceImpl: Log error
        end
    end
    BulkRegistrationServiceImpl-->>BulkRegistrationController: Status, error log
    BulkRegistrationController-->>Client: Response

    Client->>BulkRegistrationController: GET /download-error-sheet
    BulkRegistrationController->>BulkRegistrationServiceImpl: insertErrorLog()
    BulkRegistrationServiceImpl-->>BulkRegistrationController: Excel file (byte[])
    BulkRegistrationController-->>Client: Excel file download
Loading

Possibly related PRs

  • Bulk registrationΒ #69: Introduces the same bulk registration functionality, including controller, service, data classes, and dependencies, indicating direct overlap.

Poem

πŸ‡
Bulk bunnies hop into the fold,
XML tales of employees told.
With logs and checks and hashed delight,
They register friends through day and night.
Errors tracked, Excel sheets spunβ€”
This rabbit’s work is never done!

✨ 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.

@sonarqubecloud
Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
3 Security Hotspots
6.4% Duplication on New Code (required ≀ 3%)

See analysis details on SonarQube Cloud

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

🧹 Nitpick comments (9)
src/main/java/com/iemr/admin/repo/employeemaster/EmployeeMasterRepoo.java (1)

50-51: Consider performance optimization for contact number queries.

The contact number field should be indexed in the database for optimal query performance, especially if this method will be used frequently during bulk operations.

src/main/java/com/iemr/admin/data/bulkuser/BulkRegistrationError.java (1)

8-12: Improve encapsulation and add documentation.

Consider the following improvements for better code quality:

+/**
+ * Data class to hold bulk user registration error information
+ */
 @Data
 public class BulkRegistrationError {
-    String userName;
-    Integer rowNumber;
-    List<String> error;
+    private String userName;
+    private Integer rowNumber;
+    private List<String> error;
 }

Adding private access modifiers and documentation would improve encapsulation and code maintainability.

src/main/java/com/iemr/admin/service/rolemaster/Role_MasterInter.java (1)

27-27: Consider the trade-offs of wildcard imports.

While wildcard imports can reduce line count, they can make it harder to track which specific classes are being used and may cause naming conflicts. Consider if the specific imports were more readable.

src/main/java/com/iemr/admin/service/bulkRegistration/BulkRegistrationService.java (1)

3-5: Consider improving method signature clarity and return type.

The interface looks clean, but consider these improvements:

  • The user parameter name is vague - consider userData or xmlData for clarity
  • Returning void prevents callers from knowing the operation status - consider returning a result object or success indicator
  • Consider using more specific parameter types if possible
 public interface BulkRegistrationService {
-    void registerBulkUser(String user, String authorization);
+    BulkRegistrationResult registerBulkUser(String userData, String authorization);
 }
src/main/java/com/iemr/admin/service/rolemaster/Role_Master_ServiceImpl.java (1)

367-367: Fix inconsistent spacing.

There are extra blank lines that make the code formatting inconsistent.

 		RoleMaster buff=mRoleRepo.findByRoleID(role.getRoleID());
-
 		if(buff==null) {
 		buff.setModifiedBy(role.getModifiedBy());
-
 		return mRoleRepo.save(buff);

Also applies to: 377-377

src/main/java/com/iemr/admin/data/bulkuser/Employee.java (1)

11-99: Consider using null instead of empty string defaults.

Initializing all fields to empty strings may cause validation issues. Consider using null defaults and implementing proper null checks in validation logic.

src/main/java/com/iemr/admin/controller/bulkRegistration/BulkRegistrationController.java (3)

13-19: Remove unused imports.

Several imports are not used in the code.

Remove these unused imports:

-import org.springframework.core.io.ClassPathResource;
-import java.lang.reflect.Method;

37-40: Add proper spacing between field declarations.

Field declarations should be separated by blank lines for better readability.

Apply this formatting:

 private EmployeeMasterRepoo employeeMasterRepoo;
+
 private Map<String, Object> errorResponse = new HashMap<>();
+
 @Autowired
 private LocationMasterServiceInter locationMasterServiceInter;
+
 private Map<String, Object> response = new HashMap<>();

78-80: Add braces for if construct.

All if constructs should use braces for consistency and maintainability.

Apply this fix:

-if(!bulkRegistrationServiceimpl.bulkRegistrationErrors.isEmpty()){
+if (!bulkRegistrationServiceimpl.bulkRegistrationErrors.isEmpty()) {
     bulkRegistrationServiceimpl.bulkRegistrationErrors.clear();
+}
πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 73ea731 and 3fd079a.

πŸ“’ Files selected for processing (14)
  • pom.xml (4 hunks)
  • src/main/java/com/iemr/admin/controller/bulkRegistration/BulkRegistrationController.java (1 hunks)
  • src/main/java/com/iemr/admin/data/bulkuser/BulkRegistrationError.java (1 hunks)
  • src/main/java/com/iemr/admin/data/bulkuser/Employee.java (1 hunks)
  • src/main/java/com/iemr/admin/data/bulkuser/EmployeeList.java (1 hunks)
  • src/main/java/com/iemr/admin/data/employeemaster/M_Religion.java (1 hunks)
  • src/main/java/com/iemr/admin/repo/employeemaster/EmployeeMasterRepoo.java (1 hunks)
  • src/main/java/com/iemr/admin/service/bulkRegistration/BulkRegistrationService.java (1 hunks)
  • src/main/java/com/iemr/admin/service/bulkRegistration/BulkRegistrationServiceImpl.java (1 hunks)
  • src/main/java/com/iemr/admin/service/bulkRegistration/EmployeeXmlService.java (1 hunks)
  • src/main/java/com/iemr/admin/service/employeemaster/EmployeeMasterInter.java (2 hunks)
  • src/main/java/com/iemr/admin/service/employeemaster/EmployeeMasterServiceImpl.java (2 hunks)
  • src/main/java/com/iemr/admin/service/rolemaster/Role_MasterInter.java (3 hunks)
  • src/main/java/com/iemr/admin/service/rolemaster/Role_Master_ServiceImpl.java (5 hunks)
🧰 Additional context used
πŸͺ› GitHub Actions: Build On Pull Request
src/main/java/com/iemr/admin/controller/bulkRegistration/BulkRegistrationController.java

[warning] 8-78: Checkstyle warnings: Unused imports, 'VARIABLE_DEF' should be separated from previous line, 'if' and 'else' constructs must use braces, line length exceeds 120 characters.

src/main/java/com/iemr/admin/service/bulkRegistration/BulkRegistrationServiceImpl.java

[error] 354-354: Compilation failure: cannot find symbol method setIsSanjeevani(boolean) in variable m_userServiceRoleMapping of type com.iemr.admin.data.employeemaster.M_UserServiceRoleMapping2


[warning] 97-477: Method saveUserUser length is 381 lines (max allowed is 50), multiple Checkstyle warnings including variable naming, line length, and 'if' construct braces.

πŸͺ› GitHub Actions: Call Checkstyle
src/main/java/com/iemr/admin/service/bulkRegistration/BulkRegistrationServiceImpl.java

[error] 354-354: Compilation failure: cannot find symbol method setIsSanjeevani(boolean) in variable m_userServiceRoleMapping of type com.iemr.admin.data.employeemaster.M_UserServiceRoleMapping2

πŸͺ› GitHub Actions: Package
src/main/java/com/iemr/admin/service/bulkRegistration/BulkRegistrationServiceImpl.java

[error] 354-354: Compilation failure: cannot find symbol method setIsSanjeevani(boolean) in variable m_userServiceRoleMapping of type com.iemr.admin.data.employeemaster.M_UserServiceRoleMapping2


[warning] Checkstyle warnings: multiple style issues including 'VARIABLE_DEF' should be separated from previous line, 'package' should be separated from previous line, 'Line is longer than 120 characters', 'Name must match pattern', 'Unused import', 'Method length exceeds max allowed', 'if/else construct must use braces', 'EmptyBlock', 'EmptyStatement', 'WhitespaceAround', 'WhitespaceAfter', 'WhitespaceBefore', 'RedundantModifier', 'SimplifyBooleanExpression', 'NeedBraces', 'MissingSwitchDefault', 'ModifierOrder', 'AvoidStarImport', 'NoWhitespaceBefore', 'NoWhitespaceAfter', 'ParenPad', 'TypeName', 'MemberName', 'LocalVariableName', 'ParameterName', 'MethodName', 'FileLength' warnings found.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (java)
πŸ”‡ Additional comments (9)
pom.xml (2)

81-85: Verify the security status of commons-compress version 1.21.

The fixed version 1.21 of commons-compress was released in 2021 and may have known security vulnerabilities. Please ensure this version is secure and consider upgrading to the latest version.

#!/bin/bash
# Description: Check for security advisories and latest version of commons-compress library

# Check for latest version
curl -s https://search.maven.org/solrsearch/select?q=g:"org.apache.commons"+AND+a:"commons-compress"&core=gav&rows=1&wt=json | jq -r '.response.docs[0].v'

# Check for security advisories
gh api graphql -f query='
{
  securityVulnerabilities(first: 10, ecosystem: MAVEN, package: "org.apache.commons:commons-compress") {
    nodes {
      advisory {
        summary
        severity
        publishedAt
      }
      vulnerableVersionRange
      firstPatchedVersion {
        identifier
      }
    }
  }
}'

194-194: ```shell
#!/bin/bash

Show context around the direct commons-compress dependency in pom.xml

grep -n -C3 'commons-compress' pom.xml


</details>
<details>
<summary>src/main/java/com/iemr/admin/data/employeemaster/M_Religion.java (1)</summary>

`39-39`: **LGTM: Improved code formatting.**

The brace placement now follows standard Java formatting conventions.

</details>
<details>
<summary>src/main/java/com/iemr/admin/service/rolemaster/Role_MasterInter.java (1)</summary>

`74-74`: **LGTM: New method follows consistent naming conventions.**

The new `getAllState()` method signature is consistent with other methods in the interface and follows the established naming pattern.

</details>
<details>
<summary>src/main/java/com/iemr/admin/service/rolemaster/Role_Master_ServiceImpl.java (3)</summary>

`49-49`: **LGTM! Formatting improvement.**

The brace placement follows consistent Java coding standards.

---

`282-282`: **LGTM! Method signature formatting.**

Consolidating the method signature to a single line improves readability.

---

`381-384`: **LGTM! Simple delegation method.**

The new `getAllState()` method correctly delegates to the repository and maintains consistency with the interface.

</details>
<details>
<summary>src/main/java/com/iemr/admin/service/employeemaster/EmployeeMasterInter.java (1)</summary>

`116-118`: **LGTM! Well-designed method declarations for bulk registration support.**

The new method declarations are well-named, follow existing conventions, and have appropriate parameter and return types:
- `FindEmployeeContact` and `FindEmployeeAadhaar` for validation checks
- `saveBulkUserEmployee` for persisting bulk user data

These methods properly support the bulk registration feature while maintaining interface consistency.



Also applies to: 194-194

</details>
<details>
<summary>src/main/java/com/iemr/admin/data/bulkuser/EmployeeList.java (1)</summary>

`10-17`: **LGTM! Well-designed data class with proper XML annotations.**

The class demonstrates good practices:
- Appropriate use of Lombok's `@Data` for boilerplate reduction
- Correct Jackson XML annotations for serialization/deserialization
- `@JacksonXmlRootElement` properly defines the root element
- `@JacksonXmlElementWrapper(useWrapping = false)` prevents unnecessary nesting
- Clean, focused structure for the intended XML format

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Comment on lines +43 to +44
@Query("SELECT u FROM M_User1 u WHERE u.aadhaarNo=:aadhaar AND deleted=false ")
M_User1 findEmployeeAadhaarNo(@Param("aadhaar") String userName);
Copy link

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Ensure proper handling of sensitive Aadhaar data.

The method handles Aadhaar numbers which are sensitive personal information. Ensure that:

  1. Input validation is performed at the service layer
  2. Audit logging is implemented for Aadhaar number queries
  3. Database column for aadhaarNo is properly indexed for performance
πŸ€– Prompt for AI Agents
In src/main/java/com/iemr/admin/repo/employeemaster/EmployeeMasterRepoo.java
around lines 43 to 44, the method querying Aadhaar numbers needs enhanced
handling for sensitive data. Ensure input validation for the Aadhaar number is
done in the service layer before calling this repository method. Implement audit
logging in the service layer to record queries involving Aadhaar numbers for
traceability. Verify that the database column for aadhaarNo is indexed to
optimize query performance.

Comment on lines +14 to +18
public EmployeeList parseXml(String xmlData) throws Exception {
System.out.println("user_xml_date"+xmlData.toString());

return xmlMapper.readValue(xmlData, EmployeeList.class);
}
Copy link

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Improve exception handling and input validation.

Consider using more specific exceptions and adding input validation for better error handling.

-    public EmployeeList parseXml(String xmlData) throws Exception {
+    public EmployeeList parseXml(String xmlData) throws IllegalArgumentException, JsonProcessingException {
+        if (xmlData == null || xmlData.trim().isEmpty()) {
+            throw new IllegalArgumentException("XML data cannot be null or empty");
+        }
         logger.debug("Parsing XML data: {}", xmlData);
-
-        return xmlMapper.readValue(xmlData, EmployeeList.class);
+        
+        try {
+            return xmlMapper.readValue(xmlData, EmployeeList.class);
+        } catch (JsonProcessingException e) {
+            logger.error("Failed to parse XML data", e);
+            throw e;
+        }
     }

Add the import:

+import com.fasterxml.jackson.core.JsonProcessingException;

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

πŸ€– Prompt for AI Agents
In src/main/java/com/iemr/admin/service/bulkRegistration/EmployeeXmlService.java
around lines 14 to 18, the parseXml method currently throws a generic Exception
and lacks input validation. Refine the method by validating that xmlData is not
null or empty before processing, and replace the generic Exception with more
specific exceptions such as IOException and JsonProcessingException to handle
parsing errors more precisely. Also, remove or replace the System.out.println
with proper logging. Add necessary imports for the specific exceptions used.


// Convert XML to EmployeeList (Java Object)
public EmployeeList parseXml(String xmlData) throws Exception {
System.out.println("user_xml_date"+xmlData.toString());
Copy link

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Replace System.out.println with proper logging and fix typo.

Debug output should use the logging framework instead of console output, and there's a typo in the message.

+    private static final Logger logger = LoggerFactory.getLogger(EmployeeXmlService.class);
+
     public EmployeeList parseXml(String xmlData) throws Exception {
-        System.out.println("user_xml_date"+xmlData.toString());
+        logger.debug("Parsing XML data: {}", xmlData);

Also add the import:

+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
πŸ€– Prompt for AI Agents
In src/main/java/com/iemr/admin/service/bulkRegistration/EmployeeXmlService.java
at line 15, replace the System.out.println statement with a proper logging call
using the project's logging framework, such as logger.info or logger.debug.
Correct the typo in the message from "user_xml_date" to "user_xml_data". Also,
add the necessary import statement for the logging class used.

Comment on lines +95 to +99
@JacksonXmlProperty(localName = "UserName")
private String UserName="";

@JacksonXmlProperty(localName = "Password")
private String Password="";
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix field naming convention violations.

Fields UserName and Password should follow Java camelCase convention.

Apply this diff to fix the naming:

-    @JacksonXmlProperty(localName = "UserName")
-    private String UserName="";
+    @JacksonXmlProperty(localName = "UserName")
+    private String userName="";

-    @JacksonXmlProperty(localName = "Password")
-    private String Password="";
+    @JacksonXmlProperty(localName = "Password")
+    private String password="";
πŸ“ 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
@JacksonXmlProperty(localName = "UserName")
private String UserName="";
@JacksonXmlProperty(localName = "Password")
private String Password="";
@JacksonXmlProperty(localName = "UserName")
private String userName="";
@JacksonXmlProperty(localName = "Password")
private String password="";
πŸ€– Prompt for AI Agents
In src/main/java/com/iemr/admin/data/bulkuser/Employee.java around lines 95 to
99, the field names UserName and Password violate Java camelCase naming
conventions. Rename these fields to userName and password respectively, updating
all references accordingly to maintain consistency and adhere to standard Java
naming practices.

Comment on lines +47 to +51
@JacksonXmlProperty(localName = "AadhaarNo")
private String aadhaarNo="";

@JacksonXmlProperty(localName = "PAN")
private String pan="";
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 validation for sensitive data fields.

The Aadhaar and PAN fields should include validation annotations to ensure data integrity and security.

Consider adding validation annotations:

 @JacksonXmlProperty(localName = "AadhaarNo")
+@Pattern(regexp = "\\d{12}", message = "Aadhaar number must be 12 digits")
 private String aadhaarNo="";

 @JacksonXmlProperty(localName = "PAN")
+@Pattern(regexp = "^[A-Z]{5}[0-9]{4}[A-Z]{1}$", message = "Invalid PAN format")
 private String pan="";
πŸ“ 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
@JacksonXmlProperty(localName = "AadhaarNo")
private String aadhaarNo="";
@JacksonXmlProperty(localName = "PAN")
private String pan="";
@JacksonXmlProperty(localName = "AadhaarNo")
@Pattern(regexp = "\\d{12}", message = "Aadhaar number must be 12 digits")
private String aadhaarNo="";
@JacksonXmlProperty(localName = "PAN")
@Pattern(regexp = "^[A-Z]{5}[0-9]{4}[A-Z]{1}$", message = "Invalid PAN format")
private String pan="";
πŸ€– Prompt for AI Agents
In src/main/java/com/iemr/admin/data/bulkuser/Employee.java around lines 47 to
51, the AadhaarNo and PAN fields lack validation annotations. Add appropriate
validation annotations such as @NotBlank and pattern-based constraints (e.g.,
@Pattern) to enforce correct formats and ensure data integrity and security for
these sensitive fields.

Comment on lines +97 to +477
private void saveUserUser(Employee employee, Integer row, String authorization) throws Exception {
List<String> validationErrors = new ArrayList<>();
BulkRegistrationError bulkRegistrationErrors_ = new BulkRegistrationError();
M_User1 mUser = new M_User1();
M_UserDemographics mUserDemographics = new M_UserDemographics();
M_UserServiceRoleMapping2 m_userServiceRoleMapping = new M_UserServiceRoleMapping2();

logger.info("employee_list after for loop" + employee.toString());
if (!employee.getUserName().isEmpty()) {
String checkUserIsExist = employeeMasterInter.FindEmployeeName(employee.getUserName());
String checkContactIsExist = employeeMasterInter.FindEmployeeContact(employee.getContactNo());
logger.info("checkAAdharIsExist" + checkUserIsExist);
if (checkUserIsExist.equalsIgnoreCase("usernotexist")) {
if (checkContactIsExist.equalsIgnoreCase("contactnotexist")) {
if (employee.getTitle() == null || employee.getTitle().isEmpty()) {
validationErrors.add("Title is missing.");
}
if (!employee.getTitle().isEmpty()) {
if (getTitleId(employee.getTitle()) == 0) {
validationErrors.add("Title is invalid.");

}

}

if (employee.getFirstName() == null || employee.getFirstName().isEmpty()) {
validationErrors.add("First Name is missing.");
}
if(!employee.getFirstName().isEmpty()){
if(employee.getFirstName().length()>50){
validationErrors.add("First name is invalid.");

}
if(isNumeric(employee.getFirstName())){
validationErrors.add("First name is invalid.");

}
}

if(!employee.getMiddleName().isEmpty()){
if(employee.getMiddleName().length()>50){
validationErrors.add("Middle name is invalid.");

}
if(isNumeric(employee.getMiddleName())){
validationErrors.add("Middle name is invalid.");

}
}
if (employee.getLastName() == null || employee.getLastName().isEmpty()) {
validationErrors.add("Last Name is missing.");
}
if(!employee.getLastName().isEmpty()){
if(employee.getLastName().length()>50){
validationErrors.add("Last name is invalid.");

}
if(isNumeric(employee.getLastName())){
validationErrors.add("Last name is invalid.");

}
}
if (employee.getGender().isEmpty()) {
validationErrors.add("Gender is missing");

}
if (employee.getContactNo().isEmpty()) {
validationErrors.add("Contact number missing");

}
if (!employee.getContactNo().isEmpty()) {
if (!isValidPhoneNumber(String.valueOf(employee.getContactNo()))) {
validationErrors.add("Contact Number is invalid");
}
}

if (employee.getDesignation().isEmpty()) {
validationErrors.add("Designation is missing");

}
if (employee.getEmergencyContactNo().isEmpty()) {
validationErrors.add("Emergency contact number is missing");

}
if (!employee.getEmergencyContactNo().isEmpty()) {
if (!isValidPhoneNumber(String.valueOf(employee.getEmergencyContactNo()))) {
validationErrors.add("Emergency Contact Number is invalid.");
}
}

if (employee.getDob().isEmpty()) {
validationErrors.add("Date of Birth is missing.");

}
if(!employee.getDob().isEmpty()){
if(!isValidDate(convertStringIntoDate(employee.getDob()).toString())){
validationErrors.add("Date of Birth is invalid.");

}
}

if(employee.getEmail().isEmpty()){
validationErrors.add("Email is missing.");

}
if(!employee.getEmail().isEmpty()){
if (!employee.getEmail().matches(EMAIL_REGEX)) {
validationErrors.add("Invalid Email format.");
}
}

if (employee.getPassword().isEmpty()) {
validationErrors.add("Please Enter valid password.");

}

if (!employee.getAadhaarNo().isEmpty()) {
if (!employeeMasterInter.FindEmployeeAadhaar(employee.getAadhaarNo()).equalsIgnoreCase("aadhaarnotexist")) {
validationErrors.add("Duplicate aadhaar number found");

}
if(isValidAadhar(employee.getAadhaarNo())){
validationErrors.add("Aadhaar number is invalid");

}
}


if (employee.getQualification().isEmpty()) {
validationErrors.add("Qualification is missing");

}

if (employee.getState().isEmpty()) {
validationErrors.add("Current State is missing.");
}
if (!employee.getState().isEmpty()) {
if (getStateId(employee.getState()) == 0) {
validationErrors.add("Current State is invalid.");

}
}
if (employee.getDistrict().isEmpty()) {
validationErrors.add("Current District is missing.");
}
if (!employee.getDistrict().isEmpty()) {
if (getDistrictId(employee.getDistrict()) == 0) {
validationErrors.add("Current District is invalid.");

}
}

if (employee.getPermanentState().isEmpty()) {
validationErrors.add("Permanent State is missing.");
}
if (!employee.getPermanentState().isEmpty()) {
if (getStateId(employee.getPermanentState()) == 0) {
validationErrors.add("Permanent State is invalid.");

}
}
if (employee.getPermanentDistrict().isEmpty()) {
validationErrors.add("Permanent District is missing.");
}

if (!employee.getPermanentDistrict().isEmpty()) {
if (getDistrictId(employee.getPermanentDistrict()) == 0) {
validationErrors.add("Permanent District is invalid.");

}
}

if(employee.getDateOfJoining().isEmpty()){
validationErrors.add("Date of Joining is missing.");

}
if(!employee.getDateOfJoining().isEmpty()){
if(!isValidDate(convertStringIntoDate(employee.getDateOfJoining()).toString())){
validationErrors.add("Date of Joining is invalid.");

}
}



if (!validationErrors.isEmpty()) {
errorLogs.add("Row " + (row + 1) + ": " + String.join(", ", validationErrors));
bulkRegistrationErrors_.setRowNumber((row + 1));
bulkRegistrationErrors_.setUserName(employee.getUserName());
bulkRegistrationErrors_.setError(validationErrors);
bulkRegistrationErrors.add(bulkRegistrationErrors_);



}


// showLogger(employee);

if (!employee.getTitle().isEmpty() && !employee.getFirstName().isEmpty() && !employee.getLastName().isEmpty() && !employee.getContactNo().isEmpty() && !employee.getEmergencyContactNo().isEmpty() && !employee.getDob().isEmpty() && !employee.getUserName().isEmpty() && !employee.getPassword().isEmpty() && !employee.getState().isEmpty() && !employee.getDistrict().isEmpty() && !employee.getPermanentState().isEmpty() && !employee.getPermanentDistrict().isEmpty() && !employee.getGender().isEmpty() && !employee.getQualification().isEmpty() && isValidDate(convertStringIntoDate(employee.getDob()).toString()) && isValidDate(convertStringIntoDate(employee.getDateOfJoining()).toString())) {
try {

mUser.setTitleID(getTitleId(employee.getTitle()));
mUser.setFirstName(employee.getFirstName());
mUser.setLastName(employee.getLastName());
mUser.setUserName(employee.getUserName());
mUser.setdOB(convertStringIntoDate(employee.getDob()));
mUser.setEmployeeID(employee.getContactNo());
mUser.setEmergencyContactNo(String.valueOf(employee.getEmergencyContactNo()));
mUser.setContactNo(String.valueOf(employee.getContactNo()));
if (!employee.getMiddleName().isEmpty()) {
mUser.setMiddleName(employee.getMiddleName());

}
if (!employee.getDesignation().isEmpty()) {
mUser.setDesignationID(getDesignationId(employee.getDesignation()));

}
if (!employee.getDesignation().isEmpty()) {
mUser.setDesignationName(employee.getDesignation());

}
if (!isValidAadhar(employee.getAadhaarNo()) && employeeMasterInter.FindEmployeeAadhaar(employee.getAadhaarNo()).equalsIgnoreCase("aadhaarnotexist")) {
mUser.setAadhaarNo(String.valueOf(employee.getAadhaarNo()));

}

if (!employee.getPan().isEmpty()) {
mUser.setpAN(employee.getPan());

}
mUser.setMaritalStatusID(1);
mUser.setEmailID(employee.getEmail());
mUser.setGenderID(Short.parseShort(String.valueOf(getGenderId(employee.getGender()))));
mUser.setQualificationID(4);
if (!employee.getQualification().isEmpty()) {
mUser.setQualificationID(getQualificationId(employee.getQualification()));

}
mUser.setdOJ(convertStringIntoDate(employee.getDateOfJoining()));
//mUser.setCreatedBy(jwtUtil.extractUsername(authorization));
mUser.setCreatedBy("Psmril2");
//mUser.setModifiedBy(jwtUtil.extractUsername(authorization));
mUser.setModifiedBy("Psmril2");
mUser.setStatusID(1);
mUser.setIsSupervisor(false);
mUser.setServiceProviderID(15);
mUser.setPassword(generateStrongPassword(employee.getPassword()));
logger.info("Register_user:" + mUser);
M_User1 bulkUserID = employeeMasterInter.saveBulkUserEmployee(mUser);
logger.info("BulkUser:" + bulkUserID);
m_userServiceRoleMapping.setUserID(bulkUserID.getUserID());
m_userServiceRoleMapping.setServiceProviderID(bulkUserID.getServiceProviderID());
m_userServiceRoleMapping.setCreatedBy("Psmril2");
m_userServiceRoleMapping.setRoleID(133);
m_userServiceRoleMapping.setProviderServiceMapID(1);
//m_userServiceRoleMapping.setWorkingLocationID(117);
m_userServiceRoleMapping.setIsSanjeevani(false);
m_userServiceRoleMapping.setBlockName("Biswanath");
String[] villageName = {"Bagijuli"};
m_userServiceRoleMapping.setVillageName(villageName);
String[] villageID = {"25460"};
m_userServiceRoleMapping.setVillageID(villageID);
m_userServiceRoleMapping.setBlockID(920);

mUserDemographics.setUserID(bulkUserID.getUserID());
mUserDemographics.setCountryID(91);
if (!employee.getCommunity().isEmpty()) {
mUserDemographics.setCommunityID(getCommunityId(employee.getCommunity()));

}
if (!employee.getReligion().isEmpty()) {
mUserDemographics.setReligionID(getReligionStringId(employee.getReligion()));

}
// mUserDemographics.setReligionID(1);
// mUserDemographics.setCreatedBy(jwtUtil.extractUsername(authorization));
mUserDemographics.setCreatedBy("Psmril2");
// Permanent Address
if (!employee.getPermanentAddressLine1().isEmpty()) {
mUserDemographics.setPermAddressLine1(employee.getPermanentAddressLine1());

}
if (!employee.getPermanentState().isEmpty()) {
mUserDemographics.setPermStateID(getStateId(employee.getPermanentState()));

}
if (!employee.getPermanentDistrict().isEmpty()) {
mUserDemographics.setPermDistrictID(getDistrictId(employee.getPermanentDistrict()));

}
mUserDemographics.setIsPermanent(false);
if (!employee.getPermanentPincode().isEmpty()) {
mUserDemographics.setPermPinCode(Integer.valueOf(employee.getPermanentPincode()));

}
if (!employee.getMotherName().isEmpty()) {
mUserDemographics.setMothersName(employee.getMotherName());

}
if (!employee.getFatherName().isEmpty()) {
mUserDemographics.setFathersName(employee.getFatherName());

}
// correspondence address
if (!employee.getAddressLine1().isEmpty()) {
mUserDemographics.setAddressLine1(employee.getAddressLine1());

}
if (!employee.getState().isEmpty()) {
mUserDemographics.setStateID(getStateId(employee.getState()));

}
mUserDemographics.setIsPresent(false);
if (!employee.getDistrict().isEmpty()) {
mUserDemographics.setDistrictID(getDistrictId(employee.getDistrict()));

}
if (!employee.getPincode().isEmpty()) {
mUserDemographics.setPinCode(employee.getPincode().toString());

}
employeeMasterInter.saveDemography(mUserDemographics);
m_bulkUser.add(mUser);
m_UserDemographics.add(mUserDemographics);
employeeMasterInter.saveRoleMappingeditedData(m_userServiceRoleMapping, authorization);

} catch (Exception e) {
errorLogs.add("Row :" + (row + 1) + e.getMessage());
bulkRegistrationErrors_.setRowNumber((row + 1));
bulkRegistrationErrors_.setUserName(employee.getUserName());
bulkRegistrationErrors_.setError(validationErrors);
bulkRegistrationErrors.add(bulkRegistrationErrors_);


}
}

} else {
validationErrors.add("Contact No Already exist");
if (!validationErrors.isEmpty()) {

errorLogs.add("Row " + (row + 1) + ": " + String.join(", ", validationErrors));
bulkRegistrationErrors_.setRowNumber((row + 1));
bulkRegistrationErrors_.setUserName(employee.getUserName());
bulkRegistrationErrors_.setError(validationErrors);
bulkRegistrationErrors.add(bulkRegistrationErrors_);


}
}

} else {
validationErrors.add("User Already exist");
if (!validationErrors.isEmpty()) {

errorLogs.add("Row " + (row + 1) + ": " + String.join(", ", validationErrors));
bulkRegistrationErrors_.setRowNumber((row + 1));
bulkRegistrationErrors_.setUserName(employee.getUserName());
bulkRegistrationErrors_.setError(validationErrors);
bulkRegistrationErrors.add(bulkRegistrationErrors_);


}

}
} else {
validationErrors.add("Please Enter UserName");
if (!validationErrors.isEmpty()) {
errorLogs.add("Row " + (row + 1) + ": " + String.join(", ", validationErrors));
bulkRegistrationErrors_.setRowNumber((row + 1));
bulkRegistrationErrors_.setUserName(employee.getUserName());
bulkRegistrationErrors_.setError(validationErrors);
bulkRegistrationErrors.add(bulkRegistrationErrors_);


}
}


}
Copy link

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Break down the extremely long saveUserUser method.

The method is 381 lines long, exceeding the 50-line limit by 7x. This violates the single responsibility principle and makes the code unmaintainable.

Refactor into smaller methods:

private void saveUserUser(Employee employee, Integer row, String authorization) throws Exception {
    List<String> validationErrors = validateEmployee(employee);
    
    if (!validationErrors.isEmpty()) {
        logValidationErrors(employee, row, validationErrors);
        return;
    }
    
    if (isEmployeeAlreadyExists(employee)) {
        logDuplicateEmployee(employee, row);
        return;
    }
    
    try {
        M_User1 savedUser = createAndSaveUser(employee, authorization);
        createAndSaveDemographics(savedUser, employee);
        createAndSaveRoleMapping(savedUser, authorization);
    } catch (Exception e) {
        logSaveError(employee, row, e);
    }
}

private List<String> validateEmployee(Employee employee) { /* validation logic */ }
private boolean isEmployeeAlreadyExists(Employee employee) { /* existence check */ }
private M_User1 createAndSaveUser(Employee employee, String authorization) { /* user creation */ }
// ... other extracted methods

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

🧰 Tools
πŸͺ› GitHub Actions: Call Checkstyle

[error] 354-354: Compilation failure: cannot find symbol method setIsSanjeevani(boolean) in variable m_userServiceRoleMapping of type com.iemr.admin.data.employeemaster.M_UserServiceRoleMapping2

πŸͺ› GitHub Actions: Build On Pull Request

[error] 354-354: Compilation failure: cannot find symbol method setIsSanjeevani(boolean) in variable m_userServiceRoleMapping of type com.iemr.admin.data.employeemaster.M_UserServiceRoleMapping2


[warning] 97-477: Method saveUserUser length is 381 lines (max allowed is 50), multiple Checkstyle warnings including variable naming, line length, and 'if' construct braces.

πŸͺ› GitHub Actions: Package

[error] 354-354: Compilation failure: cannot find symbol method setIsSanjeevani(boolean) in variable m_userServiceRoleMapping of type com.iemr.admin.data.employeemaster.M_UserServiceRoleMapping2


[warning] Checkstyle warnings: multiple style issues including 'VARIABLE_DEF' should be separated from previous line, 'package' should be separated from previous line, 'Line is longer than 120 characters', 'Name must match pattern', 'Unused import', 'Method length exceeds max allowed', 'if/else construct must use braces', 'EmptyBlock', 'EmptyStatement', 'WhitespaceAround', 'WhitespaceAfter', 'WhitespaceBefore', 'RedundantModifier', 'SimplifyBooleanExpression', 'NeedBraces', 'MissingSwitchDefault', 'ModifierOrder', 'AvoidStarImport', 'NoWhitespaceBefore', 'NoWhitespaceAfter', 'ParenPad', 'TypeName', 'MemberName', 'LocalVariableName', 'ParameterName', 'MethodName', 'FileLength' warnings found.

πŸ€– Prompt for AI Agents
In
src/main/java/com/iemr/admin/service/bulkRegistration/BulkRegistrationServiceImpl.java
around lines 97 to 477, the saveUserUser method is excessively long and violates
the single responsibility principle. Refactor this method by extracting logical
blocks into smaller private methods, such as separate methods for validating
employee fields, setting user details, setting demographics, and saving role
mappings. Each extracted method should handle a distinct part of the process to
improve readability and maintainability while keeping the main method concise.

m_userServiceRoleMapping.setRoleID(133);
m_userServiceRoleMapping.setProviderServiceMapID(1);
//m_userServiceRoleMapping.setWorkingLocationID(117);
m_userServiceRoleMapping.setIsSanjeevani(false);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix compilation error: missing setIsSanjeevani method.

The method setIsSanjeevani(boolean) does not exist in M_UserServiceRoleMapping2.

Remove or replace this line based on the actual available methods:

-m_userServiceRoleMapping.setIsSanjeevani(false);

Verify the correct method name in the M_UserServiceRoleMapping2 class or remove if not needed.

πŸ“ 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
m_userServiceRoleMapping.setIsSanjeevani(false);
🧰 Tools
πŸͺ› GitHub Actions: Call Checkstyle

[error] 354-354: Compilation failure: cannot find symbol method setIsSanjeevani(boolean) in variable m_userServiceRoleMapping of type com.iemr.admin.data.employeemaster.M_UserServiceRoleMapping2

πŸͺ› GitHub Actions: Build On Pull Request

[error] 354-354: Compilation failure: cannot find symbol method setIsSanjeevani(boolean) in variable m_userServiceRoleMapping of type com.iemr.admin.data.employeemaster.M_UserServiceRoleMapping2

πŸͺ› GitHub Actions: Package

[error] 354-354: Compilation failure: cannot find symbol method setIsSanjeevani(boolean) in variable m_userServiceRoleMapping of type com.iemr.admin.data.employeemaster.M_UserServiceRoleMapping2


[warning] Checkstyle warnings: multiple style issues including 'VARIABLE_DEF' should be separated from previous line, 'package' should be separated from previous line, 'Line is longer than 120 characters', 'Name must match pattern', 'Unused import', 'Method length exceeds max allowed', 'if/else construct must use braces', 'EmptyBlock', 'EmptyStatement', 'WhitespaceAround', 'WhitespaceAfter', 'WhitespaceBefore', 'RedundantModifier', 'SimplifyBooleanExpression', 'NeedBraces', 'MissingSwitchDefault', 'ModifierOrder', 'AvoidStarImport', 'NoWhitespaceBefore', 'NoWhitespaceAfter', 'ParenPad', 'TypeName', 'MemberName', 'LocalVariableName', 'ParameterName', 'MethodName', 'FileLength' warnings found.

πŸ€– Prompt for AI Agents
In
src/main/java/com/iemr/admin/service/bulkRegistration/BulkRegistrationServiceImpl.java
at line 354, the method setIsSanjeevani(boolean) does not exist in the
M_UserServiceRoleMapping2 class, causing a compilation error. Check the
M_UserServiceRoleMapping2 class for the correct method name to set this property
or remove this line if the functionality is not required. Update the code
accordingly to use the correct setter method or omit the call.

Comment on lines +337 to +343
//mUser.setCreatedBy(jwtUtil.extractUsername(authorization));
mUser.setCreatedBy("Psmril2");
//mUser.setModifiedBy(jwtUtil.extractUsername(authorization));
mUser.setModifiedBy("Psmril2");
mUser.setStatusID(1);
mUser.setIsSupervisor(false);
mUser.setServiceProviderID(15);
Copy link

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Remove hardcoded values and improve configuration.

The code contains multiple hardcoded values that should be configurable.

Extract hardcoded values to configuration:

-mUser.setCreatedBy("Psmril2");
-mUser.setModifiedBy("Psmril2");
-mUser.setServiceProviderID(15);
+mUser.setCreatedBy(jwtUtil.extractUsername(authorization));
+mUser.setModifiedBy(jwtUtil.extractUsername(authorization));
+mUser.setServiceProviderID(configProperties.getDefaultServiceProviderId());

Also configure role IDs, provider service map IDs, and other constants.

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

🧰 Tools
πŸͺ› GitHub Actions: Package

[warning] Checkstyle warnings: multiple style issues including 'VARIABLE_DEF' should be separated from previous line, 'package' should be separated from previous line, 'Line is longer than 120 characters', 'Name must match pattern', 'Unused import', 'Method length exceeds max allowed', 'if/else construct must use braces', 'EmptyBlock', 'EmptyStatement', 'WhitespaceAround', 'WhitespaceAfter', 'WhitespaceBefore', 'RedundantModifier', 'SimplifyBooleanExpression', 'NeedBraces', 'MissingSwitchDefault', 'ModifierOrder', 'AvoidStarImport', 'NoWhitespaceBefore', 'NoWhitespaceAfter', 'ParenPad', 'TypeName', 'MemberName', 'LocalVariableName', 'ParameterName', 'MethodName', 'FileLength' warnings found.

πŸ€– Prompt for AI Agents
In
src/main/java/com/iemr/admin/service/bulkRegistration/BulkRegistrationServiceImpl.java
around lines 337 to 343, replace all hardcoded values such as "Psmril2",
statusID, isSupervisor flag, and serviceProviderID with configurable properties.
Extract these values into configuration files or environment variables and
inject them into the service, ensuring role IDs, provider service map IDs, and
other constants are also configurable rather than hardcoded.

Comment on lines +721 to +748
public String generateStrongPassword(String password) throws NoSuchAlgorithmException, InvalidKeySpecException {
int iterations = 1001;
char[] chars = password.toCharArray();
byte[] salt = getSalt();

PBEKeySpec spec = new PBEKeySpec(chars, salt, iterations, 512);
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
byte[] hash = skf.generateSecret(spec).getEncoded();
return iterations + ":" + toHex(salt) + ":" + toHex(hash);
}

private byte[] getSalt() throws NoSuchAlgorithmException {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[16];
sr.nextBytes(salt);
return salt;
}

private String toHex(byte[] array) throws NoSuchAlgorithmException {
BigInteger bi = new BigInteger(1, array);
String hex = bi.toString(16);
int paddingLength = array.length * 2 - hex.length();
if (paddingLength > 0) {
return String.format(new StringBuilder().append("%0").append(paddingLength).append("d").toString(),
new Object[]{Integer.valueOf(0)}) + hex;
}
return hex;
}
Copy link

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Security concern: Password hashing implementation.

The password hashing implementation is duplicated from another class and should be centralized for consistency and security.

Use the existing password encryption service:

-mUser.setPassword(generateStrongPassword(employee.getPassword()));
+// Use existing service
+mUser.setPassword(employee.getPassword());
+// Let the encryption service handle it asynchronously
+encryptUserPassword.encryptUserCredentials(mUser);

Remove the duplicated password hashing methods and use the existing EncryptUserPassword service.

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

🧰 Tools
πŸͺ› GitHub Actions: Package

[warning] Checkstyle warnings: multiple style issues including 'VARIABLE_DEF' should be separated from previous line, 'package' should be separated from previous line, 'Line is longer than 120 characters', 'Name must match pattern', 'Unused import', 'Method length exceeds max allowed', 'if/else construct must use braces', 'EmptyBlock', 'EmptyStatement', 'WhitespaceAround', 'WhitespaceAfter', 'WhitespaceBefore', 'RedundantModifier', 'SimplifyBooleanExpression', 'NeedBraces', 'MissingSwitchDefault', 'ModifierOrder', 'AvoidStarImport', 'NoWhitespaceBefore', 'NoWhitespaceAfter', 'ParenPad', 'TypeName', 'MemberName', 'LocalVariableName', 'ParameterName', 'MethodName', 'FileLength' warnings found.

πŸ€– Prompt for AI Agents
In
src/main/java/com/iemr/admin/service/bulkRegistration/BulkRegistrationServiceImpl.java
around lines 721 to 748, the password hashing methods are duplicated and should
be removed. Instead, refactor the code to use the existing EncryptUserPassword
service for password encryption to ensure consistency and security. Remove the
generateStrongPassword, getSalt, and toHex methods and replace their usage with
calls to the centralized EncryptUserPassword service.

Comment on lines +69 to +94
@Override
public void registerBulkUser(String xml, String authorization) {
try {
EmployeeList employeeList = employeeXmlService.parseXml(xml);
if (!employeeList.getEmployees().isEmpty()) {
logger.info("employee_list" + employeeList.getEmployees().toString());
totalEmployeeListSize = employeeList.getEmployees().size();
for (int i = 0; i < employeeList.getEmployees().size(); i++) {
saveUserUser(employeeList.getEmployees().get(i), i, authorization);


}
} else {
errorLogs.add("Data is invalid or empty");

}


} catch (Exception e) {
logger.error("Exception:" + e.getMessage());
errorLogs.add("Data is invalid or empty");

}


}
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 proper transaction management.

The bulk registration process should be wrapped in a transaction to ensure data consistency.

Add transaction annotation:

@Override
+@Transactional(rollbackFor = Exception.class)
public void registerBulkUser(String xml, String authorization) {
    // existing implementation
}

Also consider implementing batch processing for better performance with large datasets.

🧰 Tools
πŸͺ› GitHub Actions: Package

[warning] Checkstyle warnings: multiple style issues including 'VARIABLE_DEF' should be separated from previous line, 'package' should be separated from previous line, 'Line is longer than 120 characters', 'Name must match pattern', 'Unused import', 'Method length exceeds max allowed', 'if/else construct must use braces', 'EmptyBlock', 'EmptyStatement', 'WhitespaceAround', 'WhitespaceAfter', 'WhitespaceBefore', 'RedundantModifier', 'SimplifyBooleanExpression', 'NeedBraces', 'MissingSwitchDefault', 'ModifierOrder', 'AvoidStarImport', 'NoWhitespaceBefore', 'NoWhitespaceAfter', 'ParenPad', 'TypeName', 'MemberName', 'LocalVariableName', 'ParameterName', 'MethodName', 'FileLength' warnings found.

πŸ€– Prompt for AI Agents
In
src/main/java/com/iemr/admin/service/bulkRegistration/BulkRegistrationServiceImpl.java
around lines 69 to 94, the registerBulkUser method lacks transaction management,
risking data inconsistency during bulk operations. Add the @Transactional
annotation to this method to ensure all database operations within it are
atomic. Additionally, consider refactoring the loop to use batch processing
techniques to improve performance when handling large employee lists.

@drtechie drtechie changed the base branch from develop to 3.3.0 June 19, 2025 12:34
<org.mapstruct.version>1.2.0.Final</org.mapstruct.version>
<org.projectlombok.version>1.16.18</org.projectlombok.version>
<environment>${ENV_VAR}</environment>
<!-- <environment>test</environment>-->
Copy link
Member

Choose a reason for hiding this comment

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

remove comments

@drtechie drtechie merged commit fcbc3da into PSMRI:3.3.0 Jun 19, 2025
2 of 7 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Sep 2, 2025
10 tasks
@coderabbitai coderabbitai bot mentioned this pull request Sep 9, 2025
10 tasks
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.

3 participants