Skip to content

Fixes/userdeletionerrorfix#14

Merged
DennSel merged 2 commits into
mainfrom
fixes/userdeletionerrorfix
Jan 14, 2026
Merged

Fixes/userdeletionerrorfix#14
DennSel merged 2 commits into
mainfrom
fixes/userdeletionerrorfix

Conversation

@DennSel

@DennSel DennSel commented Jan 13, 2026

Copy link
Copy Markdown

Fixed an error where the app crashed when delting user while there were active loans.
Made it so you can't delete if you've got active loans.

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced input handling: user input now trimmed and blank entries treated as abort signal
    • User names are properly capitalized in profiles and menus
    • User deletion improved with automatic detection of active loans; prevents deletion and provides explanatory message
  • Chores

    • Updated menu visual separator styling

✏️ Tip: You can customize this high-level summary in your review settings.

- Added validation to prevent user deletion with active loans.
- Automatically capitalized users name during creation and updates.
- Improved trim handling for user input.
@coderabbitai

coderabbitai Bot commented Jan 13, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

These changes implement safer user deletion by blocking deletions when active loans exist, normalize user input formatting by capitalizing first letters and lowercasing the rest, and improve input handling by trimming and treating blank input as abort signals.

Changes

Cohort / File(s) Summary
User Interface Input & Deletion Flow
src/main/java/org/example/user/UserCLI.java
Replaced short ASCII banners with longer separators; added automatic name capitalization in create and update menus; improved prompt() method to trim input and treat blank input as abort; modified deleteUser() to remove pre-login check and conditionally delete based on deleteUserById() return value; adjusted menu flows accordingly.
Repository Layer Loan Validation
src/main/java/org/example/user/repository/JpaUserRepository.java
Added LoanServices dependency; modified deleteUserById() to check for active loans before deletion; returns false if active loans exist (blocking deletion), otherwise proceeds with transaction and returns true.

Sequence Diagram

sequenceDiagram
    participant User
    participant UserCLI
    participant JpaUserRepository
    participant LoanServices

    User->>UserCLI: Request delete user
    UserCLI->>JpaUserRepository: deleteUserById(userId)
    JpaUserRepository->>LoanServices: Check for active loans
    alt Active loans exist
        LoanServices-->>JpaUserRepository: Active loans found
        JpaUserRepository-->>UserCLI: Return false
        UserCLI-->>User: Display loan error message
    else No active loans
        LoanServices-->>JpaUserRepository: No active loans
        JpaUserRepository->>JpaUserRepository: Begin transaction
        JpaUserRepository->>JpaUserRepository: Remove user
        JpaUserRepository->>JpaUserRepository: Commit transaction
        JpaUserRepository-->>UserCLI: Return true
        UserCLI-->>User: Confirm deletion
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • PR #13: Modifies LoanServices API/constructor to require EntityManager per call, directly impacting the LoanServices instantiation and usage now added in JpaUserRepository.deleteUserById().
  • PR #12: Introduces or modifies loan-related APIs in LoanServices (such as activeLoans() method) that are now consumed by the new loan-checking logic in the repository layer.
  • PR #8: Contains initial implementations of UserCLI and JpaUserRepository behaviors that this PR now refines with safer deletion flow and enhanced input handling.

Poem

🐰 Names now stand so tall and bright,
Capitalized just right!
But loans must vanish first, you see,
Before a user can be free.

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Fixes/userdeletionerrorfix' is vague and overly broad. It lacks specificity about what error was fixed or what the actual changes accomplish, making it difficult for team members scanning history to understand the primary change. Revise the title to be more descriptive and specific, such as 'Prevent user deletion when active loans exist' or 'Add validation to block deletion of users with active loans'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/main/java/org/example/user/repository/JpaUserRepository.java (1)

34-51: Critical: Calling rollback() without an active transaction will throw an exception.

When user is null, the code falls through to line 49 and calls em.getTransaction().rollback(). However, em.getTransaction().begin() is only called on line 44 inside the if (user != null) block. This will throw an IllegalStateException because there's no active transaction to rollback.

🐛 Proposed fix
     @Override
     public boolean deleteUserById(Long id) {
         try (EntityManager em = EMFactory.getEntityManager()) {
             LoanServices loanServices = new LoanServices();
             User user = em.find(User.class, id);

             if (user != null) {
                 // Check for active loans
                 if (!loanServices.activeLoans(user, em).isEmpty()) {
                     return false;
                 }
                 em.getTransaction().begin();
                 em.remove(user);
                 em.getTransaction().commit();
                 return true;
             }
-            em.getTransaction().rollback();
             return false;
         }
     }
src/main/java/org/example/user/UserCLI.java (1)

214-223: Critical: Blank input abort breaks the update user flow.

The prompt() method now throws on blank input (line 219), but updateUserMenu() (lines 171-176) expects blank input to mean "keep current value." Users can no longer leave fields unchanged during updates because pressing Enter without input will abort the entire operation instead of preserving existing values.

🐛 Proposed fix: Create separate prompt methods or accept blank in update context

Option 1: Create a promptOptional() method for update scenarios:

private String promptOptional(String message) {
    System.out.print(message);
    String input = scanner.nextLine().trim();
    if (input.equalsIgnoreCase("avbryt")) {
        throw new RuntimeException("AVBRUTET");
    }
    return input; // Allow blank
}

Option 2: Pass a flag to allow blank:

-private String prompt(String message) {
+private String prompt(String message, boolean allowBlank) {
     System.out.print(message);
     String input = scanner.nextLine().trim();
-    if (input.equalsIgnoreCase("avbryt") || input.isBlank()) {
+    if (input.equalsIgnoreCase("avbryt") || (!allowBlank && input.isBlank())) {
         throw new RuntimeException("AVBRUTET");
     }
     return input;
 }
+
+private String prompt(String message) {
+    return prompt(message, false);
+}

Then use prompt("Nytt förnamn: ", true) in updateUserMenu().

🧹 Nitpick comments (1)
src/main/java/org/example/user/repository/JpaUserRepository.java (1)

36-36: Consider injecting LoanServices for better testability.

Instantiating LoanServices directly inside the method creates tight coupling. Consider injecting it via constructor or method parameter to improve testability and follow dependency inversion principles.

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d1e75e3 and f8a722d.

📒 Files selected for processing (2)
  • src/main/java/org/example/user/UserCLI.java
  • src/main/java/org/example/user/repository/JpaUserRepository.java
🧰 Additional context used
🧬 Code graph analysis (2)
src/main/java/org/example/user/UserCLI.java (1)
src/main/java/org/example/user/SessionManager.java (1)
  • SessionManager (5-33)
src/main/java/org/example/user/repository/JpaUserRepository.java (1)
src/main/java/org/example/LoanServices.java (1)
  • LoanServices (7-99)
🔇 Additional comments (4)
src/main/java/org/example/user/repository/JpaUserRepository.java (1)

40-43: LGTM!

The active loans check correctly prevents deletion of users with outstanding loans, addressing the PR objective.

src/main/java/org/example/user/UserCLI.java (3)

124-127: Name capitalization logic looks good.

The capitalization safely handles single-character names since substring(1) on a single char returns an empty string. The prompt() method's blank check on line 219 ensures this code won't receive empty strings.


196-211: LGTM!

The deletion flow is improved with proper result checking and informative error messaging. The integration with the repository-level active loans check is correct.


170-176: This blank-input handling is unreachable.

As noted above, the prompt() method will throw before these blank checks can execute. Once prompt() is fixed to allow blank input in update scenarios, this logic will work as intended.

@DennSel
DennSel merged commit af0273f into main Jan 14, 2026
2 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Jan 15, 2026
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