-
Notifications
You must be signed in to change notification settings - Fork 2
MOSU-147 refactor: 신청 response 및 로직 수정, 엔티티 필드 추가 #154
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
Conversation
|
Caution Review failedThe pull request is closed. WalkthroughThis update introduces user-level access control, soft deletion, and enhanced validation across application, exam application, and payment domains. It adds user IDs to key entities, refines repository queries for ownership and deletion status, and adjusts controller/service signatures to enforce user context. Database initialization, error codes, and entity inheritance are also refactored for improved consistency and maintainability. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Controller
participant Service
participant Repository
participant Entity
User->>Controller: Request (e.g., updateSubjects, getExamTicket)
Controller->>Service: Pass userId, examApplicationId, etc.
Service->>Repository: Validate user ownership (userId, examApplicationId)
alt Valid User
Service->>Repository: Perform operation (update, delete, fetch)
Repository->>Entity: Soft delete or fetch entity with userId filter
Entity-->>Repository: Entity instance(s)
Repository-->>Service: Result
Service-->>Controller: Success/response
Controller-->>User: API Response
else Invalid User
Service-->>Controller: Throw USER_NOT_ACCESS_FORBIDDEN
Controller-->>User: Error Response
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Poem
Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (40)
✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Summary of Changes
Hello @chominju02, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request introduces significant refactoring to the application and exam application modules, focusing on implementing soft deletion for core entities, enhancing data relationships between applications and payments, and strengthening access control and validation. It also refines several business logic aspects, such as discount calculations and subject updates, while cleaning up the codebase for better maintainability.
Highlights
- Soft Deletion Implementation: Introduced a comprehensive soft deletion mechanism across key entities.
ApplicationJpaEntity,ExamApplicationJpaEntity, andExamSubjectJpaEntitynow include adeletedflag, inheriting from newBaseDeleteEntityor an updatedBaseTimeEntity. This changes how records are 'deleted' in the database, marking them as inactive rather than physically removing them. Corresponding repository methods have been updated to perform soft deletes (e.g.,updateDeleteById,deleteWithExamTicketById). - Enhanced Application and Payment Logic: Refactored the application and payment flow to better link payments with the overall application. The
PaymentJpaEntitynow includes anapplicationIdfield, and theuserIdis consistently passed through the application registration and retrieval processes. This ensures more accurate tracking and user-specific data access. - Improved Access Control and Validation: Implemented stricter access control for retrieving application details and exam tickets. New validation checks ensure that users can only access their own application resources and that exam tickets are only viewable within a specific timeframe (3 days before the exam date). New error codes (
USER_NOT_ACCESS_FORBIDDEN,EXAM_TICKET_NOT_OPEN,EXAM_RESOURCE_ACCESS_DENIED) have been added to support these validations. - Refinement of Business Rules: Adjusted the logic for calculating discounts to correctly account for lunch prices. The process for updating exam subjects has also been modified: existing subjects are now hard-deleted before new ones are saved if the payment status is 'DONE'. This reflects a specific business decision for subject modification.
- Codebase Refactoring and Cleanup: Performed general code cleanup, including renaming validator methods to follow camelCase conventions, removing unused DTOs (
ExamWithSubjects.java,LunchInfo.java), and updating the database initializer to align with the new entity fields and pricing logic. Logging has also been enhanced in critical service methods.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request introduces a significant and valuable refactoring of the application logic, entity design, and test data initialization. The changes, such as adding userId for better tracking and implementing soft deletes, are positive steps forward.
I've identified a few issues that should be addressed. The most critical is an inconsistent implementation of soft deletes across different base entities, which could compromise data integrity. I've also pointed out an unused userId parameter in a repository query, which is a security concern. Other comments focus on improving maintainability by removing magic numbers, avoiding duplicated logic, and cleaning up the code. Addressing these points will further enhance the quality of the codebase.
| @Column(name = "is_deleted", nullable = false) | ||
| private Boolean deleted = false; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There's an inconsistent implementation of soft deletion. This BaseTimeEntity defines a deleted field mapped to the is_deleted column. Concurrently, a new BaseDeleteEntity is introduced with a deleted field mapped to a deleted column. This discrepancy in column names and having two base classes for soft deletion can lead to confusion and bugs.
To ensure consistency, I recommend consolidating the soft-delete logic into a single base class (e.g., BaseDeleteEntity) with a standardized column name. Other base entities, like BaseTimeEntity, can then extend it if they require both timestamping and soft-delete capabilities.
| Optional<ExamApplicationInfoProjection> findExamApplicationInfoById(Long userId, | ||
| Long examApplicationId); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The userId parameter in this method signature is not utilized within the associated JPQL query. While the service layer might be handling authorization, it's a security best practice to filter by user at the database level. This prevents potential data leaks and improves query performance by fetching only necessary data. Please add AND ea.userId = :userId to the WHERE clause.
| lunchCount > 0 ? totalAmount - (9000 * lunchCount) | ||
| : totalAmount); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Using the magic number 9000 for the lunch price makes the code harder to maintain and prone to inconsistencies. This value should be externalized to a constant, perhaps in a configuration file or a shared constants class, to be used across the application. The DatabaseInitializer already defines a LUNCH_PRICE constant, and a similar approach should be adopted here.
lunchCount > 0 ? totalAmount - (LUNCH_PRICE * lunchCount)
: totalAmount;|
|
||
| private void validateExamTicketOpenDate(LocalDate examDate, String examNumber) { | ||
|
|
||
| LocalDateTime openDateTime = examDate.minusDays(3).atTime(8, 0); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The values 3, 8, and 0 are used to define the exam ticket open date logic. These magic numbers make the code less readable. It would be better to extract them into named constants to clarify their purpose (e.g., EXAM_TICKET_OPEN_DAYS_BEFORE, EXAM_TICKET_OPEN_HOUR).
LocalDateTime openDateTime = examDate.minusDays(EXAM_TICKET_OPEN_DAYS_BEFORE).atTime(EXAM_TICKET_OPEN_HOUR, 0);| private void validateExamTicketOpenDate(LocalDate examDate, String examNumber) { | ||
|
|
||
| LocalDateTime openDateTime = examDate.minusDays(3).atTime(8, 0); | ||
| LocalDateTime now = LocalDateTime.now(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Using LocalDateTime.now() directly makes this method dependent on the system clock, which makes it difficult to test reliably. To improve testability, consider injecting a java.time.Clock instance and using LocalDateTime.now(clock). This allows you to control time within your tests.
LocalDateTime now = LocalDateTime.now(clock); // Assuming a Clock instance is injected| @Modifying | ||
| @Query(value = """ | ||
| DELETE es | ||
| FROM exam_subject es | ||
| JOIN payment p ON es.exam_application_id = p.exam_application_id | ||
| WHERE p.status = 'DONE' | ||
| AND p.exam_application_id = :examApplicationId | ||
| """, nativeQuery = true) | ||
| void deleteExamSubjectsWithDonePayment(@Param("examApplicationId") Long examApplicationId); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This repository employs inconsistent deletion strategies. The deleteByExamApplicationId method performs a soft delete (UPDATE), whereas deleteExamSubjectsWithDonePayment performs a hard delete (DELETE). This can be confusing and may lead to unexpected behavior.
If the hard delete is intentional (e.g., for a "delete and re-insert" pattern when updating subjects), please add a comment to clarify the reasoning. Otherwise, I recommend using a consistent soft-delete approach for all deletion operations on this entity.
| int baseTotal = switch (applyCount) { | ||
| case 1 -> 49_000; | ||
| case 2 -> 89_000; | ||
| case 3 -> 129_000; | ||
| default -> applyCount * BASE_EXAM_FEE; | ||
| }; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The switch statement for calculating baseTotal duplicates the pricing logic already present in FixedQuantityDiscountCalculator. To avoid code duplication and ensure that the test data generation stays in sync with the application logic, please use FixedQuantityDiscountCalculator to determine the price here.
| log.info( | ||
| "Saving ExamApplication - applicationId: {}, userId: {}, examId: {}, isLunchChecked: {}, examNumber: {}", | ||
| e.getApplicationId(), | ||
| e.getUserId(), | ||
| e.getExamId(), | ||
| e.getIsLunchChecked(), | ||
| e.getExamNumber() | ||
| ); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This log.info statement is inside a loop that performs a bulk operation. This can generate a large volume of logs, potentially impacting performance and making logs difficult to read. For such detailed, high-frequency logging, it's better to use the DEBUG level.
| log.info( | |
| "Saving ExamApplication - applicationId: {}, userId: {}, examId: {}, isLunchChecked: {}, examNumber: {}", | |
| e.getApplicationId(), | |
| e.getUserId(), | |
| e.getExamId(), | |
| e.getIsLunchChecked(), | |
| e.getExamNumber() | |
| ); | |
| log.debug( | |
| "Saving ExamApplication - applicationId: {}, userId: {}, examId: {}, isLunchChecked: {}, examNumber: {}", | |
| e.getApplicationId(), | |
| e.getUserId(), | |
| e.getExamId(), | |
| e.getIsLunchChecked(), | |
| e.getExamNumber() | |
| ); |
| // | ||
| // public static List<ExamResponse> fromList(List<ExamJpaEntity> foundExams) { | ||
| // return foundExams.stream() | ||
| // .map(ExamResponse::from) | ||
| // .toList(); | ||
| // } | ||
|
|
||
| // public static ExamResponse from(ExamWithLunchProjection exam) { | ||
| // AddressResponse address = AddressResponse.from(exam.address()); | ||
| // List<LunchInfo> lunchInfos = lunches.stream().map( | ||
| // lunch -> LunchInfo.of(lunch.getName(), lunch.getPrice()) | ||
| // ).toList(); | ||
| // return new ExamResponse( | ||
| // exam.examId(), | ||
| // exam.schoolName(), | ||
| // address, | ||
| // exam.area(), | ||
| // exam.capacity(), | ||
| // exam.deadLineTime(), | ||
| // exam.examDate() | ||
| // e | ||
| // ); | ||
| // } | ||
|
|
||
| // public static List<ExamResponse> fromList(List<ExamJpaEntity> foundExams) { | ||
| // return foundExams.stream() | ||
| // .map(ExamResponse::from) | ||
| // .toList(); | ||
| // } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| if (applicationId == null) { | ||
| throw new CustomRuntimeException(ErrorCode.WRONG_APPLICATION_ID_TYPE); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
✨ 구현한 기능
📢 논의하고 싶은 내용
🎸 기타
Summary by CodeRabbit
New Features
Improvements
Bug Fixes
Other Changes