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

πŸ”¨ Refactor/#34: User의 온기 총 횟수 계산 λ‘œμ§μ—μ„œ κ°€κ²Œλ³„ 쀑볡 제거 #35

Merged
merged 1 commit into from
Nov 18, 2024

Conversation

dongkyeomjang
Copy link
Collaborator

@dongkyeomjang dongkyeomjang commented Nov 18, 2024

Related issue πŸ› 

closed #34

μ–΄λ–€ 변경사항이 μžˆμ—ˆλ‚˜μš”?

  • 🐞 BugFix Something isn't working
  • πŸ’» CrossBrowsing Browser compatibility
  • 🌏 Deploy Deploy
  • 🎨 Design Markup & styling
  • πŸ“ƒ Docs Documentation writing and editing (README.md, etc.)
  • ✨ Feature Feature
  • πŸ”¨ Refactor Code refactoring
  • βš™οΈ Setting Development environment setup
  • βœ… Test Test related (storybook, jest, etc.)

CheckPoint βœ…

PR이 λ‹€μŒ μš”κ΅¬ 사항을 μΆ©μ‘±ν•˜λŠ”μ§€ ν™•μΈν•˜μ„Έμš”.

  • PR μ»¨λ²€μ…˜μ— 맞게 μž‘μ„±ν–ˆμŠ΅λ‹ˆλ‹€. (ν•„μˆ˜)
  • Docker Container ν™˜κ²½μœΌλ‘œ λ³€κ²½ 사항에 λŒ€ν•œ ν…ŒμŠ€νŠΈλ₯Ό ν–ˆμŠ΅λ‹ˆλ‹€.(버그 μˆ˜μ •/κΈ°λŠ₯에 λŒ€ν•œ ν…ŒμŠ€νŠΈ). (ν•„μˆ˜)
  • Feature의 경우, API λ¬Έμ„œ μ—…λ°μ΄νŠΈλ₯Ό μ™„λ£Œν–ˆμŠ΅λ‹ˆλ‹€. (선택)
  • BugFix의 경우, λ²„κ·Έμ˜ 원인을 νŒŒμ•…ν•˜μ˜€μŠ΅λ‹ˆλ‹€. (선택)

Work Description ✏️

  • User의 온기 총 횟수 계산 λ‘œμ§μ—μ„œ κ°€κ²Œλ³„ 쀑볡 제거

Uncompleted Tasks πŸ˜…

N/A

To Reviewers πŸ“’

Summary by CodeRabbit

  • New Features

    • Enhanced counting methods for "Onjung" instances, focusing on unique contributions from stores and users.
    • Introduced a method for creating "Onjung" instances using donations, receipts, and shares.
  • Bug Fixes

    • Updated logic in existing methods to ensure accurate counting of unique "Onjung" instances.
  • Documentation

    • Improved clarity on how counts are derived, emphasizing unique contributions rather than totals.

@dongkyeomjang dongkyeomjang added πŸ”¨ Refactor μ½”λ“œ λ¦¬νŒ©ν† λ§ dongkyeomjang assigned to dongkyeomjang labels Nov 18, 2024
@dongkyeomjang dongkyeomjang self-assigned this Nov 18, 2024
Copy link

coderabbitai bot commented Nov 18, 2024

Walkthrough

The changes involve modifications to the ReadOnjungBriefService and ReadOnjungCountService classes, specifically in their execute methods. The logic for counting "μ˜¨μ •" instances has been updated to focus on unique stores instead of total counts. Additionally, new methods have been introduced in the OnjungService class to facilitate the creation of Onjung instances and to calculate various counts, including total and unique counts of donations, receipts, and users associated with Onjung.

Changes

File Path Change Summary
src/main/java/com/daon/onjung/onjung/application/service/ReadOnjungBriefService.java Updated execute method to use calculateTotalUniqueOnjungStoreCount(onjung) instead of calculateTotalOnjungCount(onjung).
src/main/java/com/daon/onjung/onjung/application/service/ReadOnjungCountService.java Updated execute method to use calculateTotalUniqueOnjungStoreCount(onjung) instead of calculateTotalOnjungCount(onjung).
src/main/java/com/daon/onjung/onjung/domain/service/OnjungService.java Added methods: createOnjung, calculateTotalOnjungCount, calculateTotalUniqueOnjungStoreCount, calculateTotalUniqueOnjungUserCount.

Assessment against linked issues

Objective Addressed Explanation
User의 온기 총 횟수 계산 λ‘œμ§μ—μ„œ κ°€κ²Œλ³„ 쀑볡 제거 (#34) βœ…

Poem

🐰 In the fields where Onjungs play,
Unique counts brighten the day.
With stores so rare, we hop with cheer,
Each count a joy, each friend so dear!
Let's count the love, not just the score,
For every Onjung, there's always more! 🌼


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

🧹 Outside diff range and nitpick comments (4)
src/main/java/com/daon/onjung/onjung/application/service/ReadOnjungCountService.java (1)

Line range hint 33-64: Consider adding caching for performance optimization.

Since the warmth count calculation involves multiple database queries and processing, consider implementing caching to improve performance. The count doesn't change frequently and could be invalidated only when new donations, receipts, or shares are added for the user.

Example implementation approach:

  1. Add a cache key based on user ID and last activity timestamp
  2. Cache the count result
  3. Invalidate cache when new activities are added

This would be particularly beneficial for users with a large number of activities.

src/main/java/com/daon/onjung/onjung/domain/service/OnjungService.java (3)

Line range hint 19-31: Consider adding parameter validation

While the builder pattern implementation is clean, consider adding null checks and empty list validation to ensure robust object creation.

 public Onjung createOnjung(
         List<Donation> donations,
         List<Receipt> receipts,
         List<Share> shares
 ) {
+    if (donations == null || receipts == null || shares == null) {
+        throw new IllegalArgumentException("Lists cannot be null");
+    }
     return Onjung.builder()
             .donations(donations)
             .receipts(receipts)
             .shares(shares)
             .build();
 }

Line range hint 57-76: Apply the same stream optimization as suggested for store counting

This method has the same structure and opportunities for optimization as the store counting method.

 public Integer calculateTotalUniqueOnjungUserCount(Onjung onjung) {
-    Set<User> uniqueUsers = new HashSet<>();
-
-    // 각 λ¦¬μŠ€νŠΈμ—μ„œ User 객체λ₯Ό μˆ˜μ§‘ν•˜μ—¬ Set에 μΆ”κ°€
-    uniqueUsers.addAll(onjung.getDonations().stream()
-            .map(Donation::getUser)
-            .collect(Collectors.toSet()));
-
-    uniqueUsers.addAll(onjung.getReceipts().stream()
-            .map(Receipt::getUser)
-            .collect(Collectors.toSet()));
-
-    uniqueUsers.addAll(onjung.getShares().stream()
-            .map(Share::getUser)
-            .collect(Collectors.toSet()));
-
-    return uniqueUsers.size();
+    return Stream.of(
+            onjung.getDonations().stream().map(Donation::getUser),
+            onjung.getReceipts().stream().map(Receipt::getUser),
+            onjung.getShares().stream().map(Share::getUser)
+        )
+        .flatMap(Function.identity())
+        .collect(Collectors.toSet())
+        .size();
 }

Line range hint 78-89: Consider consistent stream usage pattern

The method mixes different styles of calculation. Consider using a consistent stream-based approach for all three calculations.

 public Integer calculateTotalOnjungAmount(Onjung onjung) {
-    return onjung.getDonations().stream()
-            .map(Donation::getDonationAmount)
-            .reduce(0, Integer::sum) +
-            onjung.getReceipts().stream()
-                    .map(Receipt::getPaymentAmount)
-                    .reduce(0, Integer::sum) +
-            onjung.getShares().size() * 100;
+    return Stream.of(
+            onjung.getDonations().stream().map(Donation::getDonationAmount).reduce(0, Integer::sum),
+            onjung.getReceipts().stream().map(Receipt::getPaymentAmount).reduce(0, Integer::sum),
+            onjung.getShares().stream().map(share -> 100).reduce(0, Integer::sum)
+        ).reduce(0, Integer::sum);
 }
πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 0436cfd and 4157484.

πŸ“’ Files selected for processing (3)
  • src/main/java/com/daon/onjung/onjung/application/service/ReadOnjungBriefService.java (1 hunks)
  • src/main/java/com/daon/onjung/onjung/application/service/ReadOnjungCountService.java (1 hunks)
  • src/main/java/com/daon/onjung/onjung/domain/service/OnjungService.java (3 hunks)
πŸ”‡ Additional comments (5)
src/main/java/com/daon/onjung/onjung/application/service/ReadOnjungCountService.java (1)

57-58: LGTM! The changes align well with the refactoring objective.

The modification correctly implements the new counting logic that excludes store duplicates, as intended by the PR objective. The updated comment clearly documents the behavior change.

Let's verify the implementation of the new counting method:

βœ… Verification successful

Implementation correctly handles store uniqueness using HashSet βœ…

The implementation in OnjungService properly uses a HashSet to eliminate store duplicates:

  • Creates a Set<Store> to maintain unique stores
  • Collects stores from both donations and receipts using Stream API
  • Automatically handles deduplication through HashSet's properties

The method is also being used consistently across the codebase:

  • ReadOnjungCountService: For total unique store count
  • ReadOnjungBriefService: As part of brief statistics
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of calculateTotalUniqueOnjungStoreCount
# Expected: Method should use Set to ensure store uniqueness

# Search for the implementation
ast-grep --pattern 'calculateTotalUniqueOnjungStoreCount($$$) {
  $$$
}'

# Verify test coverage
rg -A 5 "calculateTotalUniqueOnjungStoreCount.*test"

Length of output: 129


Script:

#!/bin/bash
# Let's try a different approach to find the implementation and tests

# Search for the method name in Java files
rg -t java "calculateTotalUniqueOnjungStoreCount" -B 2 -A 10

# Search for the class name to understand the context
rg -t java "class OnjungService" -B 2 -A 10

# Look for test files related to OnjungService
fd -e java -x grep -l "OnjungService.*Test"

Length of output: 5408

src/main/java/com/daon/onjung/onjung/application/service/ReadOnjungBriefService.java (2)

55-56: LGTM! The changes align well with the refactoring objectives.

The modification correctly implements the requirement to exclude store-based duplicates in the warmth calculation logic, as specified in issue #34.


55-56: Verify the unique store counting implementation.

Let's ensure the new counting logic is implemented consistently across the codebase.

βœ… Verification successful

Unique store counting implementation is correctly implemented

The new calculateTotalUniqueOnjungStoreCount method is properly implemented using a HashSet to collect unique stores from donations, receipts, and shares. The method is consistently used across the codebase in ReadOnjungBriefService and ReadOnjungCountService, replacing the old calculateTotalOnjungCount method where store uniqueness is required.

  • The implementation correctly uses Java Streams to map and collect Store objects from all three sources
  • Stores are properly deduplicated using HashSet's natural set properties
  • The old counting method still exists but serves a different purpose (total actions count)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of unique store counting logic

# Check for any other occurrences of the old counting method
rg "calculateTotalOnjungCount" -A 2

# Check the implementation of the new counting method
ast-grep --pattern 'calculateTotalUniqueOnjungStoreCount($$$)'

# Look for similar counting logic in test files
fd -e java -e kt --full-path ".*[Tt]est.*" --exec rg "calculateTotal.*Count"

Length of output: 938


Script:

#!/bin/bash
# Let's check the implementation of the new unique store counting method
rg "calculateTotalUniqueOnjungStoreCount" -A 5

# Check for any store-related counting logic
rg "store.*count|count.*store" -i

# Look for test coverage of the new counting method
fd -e java --full-path ".*test.*" --exec rg "calculateTotalUniqueOnjungStoreCount"

# Check the Onjung class to understand the data structure
ast-grep --pattern 'class Onjung {
  $$$
}'

Length of output: 4361


Script:

#!/bin/bash
# Let's check the complete implementation of OnjungService to see both old and new counting methods
rg -A 20 "class OnjungService" src/main/java/com/daon/onjung/onjung/domain/service/OnjungService.java

# Check the Onjung class's structure to understand donations, receipts, and shares
rg "getDonations|getReceipts|getShares" -A 2

# Look for any test files related to OnjungService
fd -e java --full-path ".*OnjungService.*Test.*"

Length of output: 4296

src/main/java/com/daon/onjung/onjung/domain/service/OnjungService.java (2)

Line range hint 3-14: LGTM! Clean import organization

The imports are well-organized and include all necessary dependencies for the service functionality.


32-35: Verify if this method is still needed

Given the PR's objective to focus on unique store counts and the introduction of calculateTotalUniqueOnjungStoreCount, verify if this total count method is still needed in the codebase.

βœ… Verification successful

Let me check the context of where this method is being used to better understand its purpose.


Let me check if there's a new unique count method being used in the same service to understand if both methods serve different purposes.


Let me check the complete implementation of ReadOnjungSummaryService to understand how both counts are being used.


The calculateTotalOnjungCount method is still needed and serves a different purpose

The method is actively used in ReadOnjungSummaryService to calculate the total number of donations (totalDonationCount) which is different from unique store counts. While calculateTotalOnjungCount counts all donations/receipts/shares, the unique count methods serve a different purpose by counting distinct entities. Both metrics are needed for different aspects of the summary response.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usages of calculateTotalOnjungCount
rg "calculateTotalOnjungCount" -A 2

Length of output: 794


Script:

#!/bin/bash
# Get more context around the usage in ReadOnjungSummaryService
rg "class ReadOnjungSummaryService" -A 20

Length of output: 2601


Script:

#!/bin/bash
# Search for unique count method usage in ReadOnjungSummaryService
rg "calculateTotalUniqueOnjungStoreCount|calculateUnique" src/main/java/com/daon/onjung/onjung/application/service/ReadOnjungSummaryService.java -A 2

Length of output: 151


Script:

#!/bin/bash
# Get the full implementation of ReadOnjungSummaryService
cat src/main/java/com/daon/onjung/onjung/application/service/ReadOnjungSummaryService.java

Length of output: 2287

Comment on lines +37 to +55
// μ˜¨μ • 객체λ₯Ό λ°›μ•„μ„œ 총 μ˜¨μ • 횟수λ₯Ό 계산(κ°€κ²Œ 쀑볡 μ œμ™Έ)
public Integer calculateTotalUniqueOnjungStoreCount(Onjung onjung) {
Set<Store> uniqueStores = new HashSet<>();

// 각 λ¦¬μŠ€νŠΈμ—μ„œ Store 객체λ₯Ό μˆ˜μ§‘ν•˜μ—¬ Set에 μΆ”κ°€
uniqueStores.addAll(onjung.getDonations().stream()
.map(Donation::getStore)
.collect(Collectors.toSet()));

uniqueStores.addAll(onjung.getReceipts().stream()
.map(Receipt::getStore)
.collect(Collectors.toSet()));

uniqueStores.addAll(onjung.getShares().stream()
.map(Share::getStore)
.collect(Collectors.toSet()));

return uniqueStores.size();
}
Copy link

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Optimize stream operations and reduce duplication

While the implementation correctly handles store uniqueness, it can be optimized by combining the streams and reducing code duplication.

 public Integer calculateTotalUniqueOnjungStoreCount(Onjung onjung) {
-    Set<Store> uniqueStores = new HashSet<>();
-
-    // 각 λ¦¬μŠ€νŠΈμ—μ„œ Store 객체λ₯Ό μˆ˜μ§‘ν•˜μ—¬ Set에 μΆ”κ°€
-    uniqueStores.addAll(onjung.getDonations().stream()
-            .map(Donation::getStore)
-            .collect(Collectors.toSet()));
-
-    uniqueStores.addAll(onjung.getReceipts().stream()
-            .map(Receipt::getStore)
-            .collect(Collectors.toSet()));
-
-    uniqueStores.addAll(onjung.getShares().stream()
-            .map(Share::getStore)
-            .collect(Collectors.toSet()));
-
-    return uniqueStores.size();
+    return Stream.of(
+            onjung.getDonations().stream().map(Donation::getStore),
+            onjung.getReceipts().stream().map(Receipt::getStore),
+            onjung.getShares().stream().map(Share::getStore)
+        )
+        .flatMap(Function.identity())
+        .collect(Collectors.toSet())
+        .size();
 }
πŸ“ 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
// μ˜¨μ • 객체λ₯Ό λ°›μ•„μ„œ 총 μ˜¨μ • 횟수λ₯Ό 계산(κ°€κ²Œ 쀑볡 μ œμ™Έ)
public Integer calculateTotalUniqueOnjungStoreCount(Onjung onjung) {
Set<Store> uniqueStores = new HashSet<>();
// 각 λ¦¬μŠ€νŠΈμ—μ„œ Store 객체λ₯Ό μˆ˜μ§‘ν•˜μ—¬ Set에 μΆ”κ°€
uniqueStores.addAll(onjung.getDonations().stream()
.map(Donation::getStore)
.collect(Collectors.toSet()));
uniqueStores.addAll(onjung.getReceipts().stream()
.map(Receipt::getStore)
.collect(Collectors.toSet()));
uniqueStores.addAll(onjung.getShares().stream()
.map(Share::getStore)
.collect(Collectors.toSet()));
return uniqueStores.size();
}
// μ˜¨μ • 객체λ₯Ό λ°›μ•„μ„œ 총 μ˜¨μ • 횟수λ₯Ό 계산(κ°€κ²Œ 쀑볡 μ œμ™Έ)
public Integer calculateTotalUniqueOnjungStoreCount(Onjung onjung) {
return Stream.of(
onjung.getDonations().stream().map(Donation::getStore),
onjung.getReceipts().stream().map(Receipt::getStore),
onjung.getShares().stream().map(Share::getStore)
)
.flatMap(Function.identity())
.collect(Collectors.toSet())
.size();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
dongkyeomjang assigned to dongkyeomjang πŸ”¨ Refactor μ½”λ“œ λ¦¬νŒ©ν† λ§
Projects
None yet
1 participant