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

Fix optimizing db calls (#24) #63

Merged
merged 3 commits into from
Oct 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion api-docs/borrowings-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ The Borrowings API provides a set of endpoints to manage the borrowing and retur

### 3. **Pay Fine**

**Endpoint:** `/borrowings/{id}/pay-fine`
**Endpoint:** `/borrowings/{id}/pay`
**Method:** `PUT`
**Description:** Pays the fine associated with a borrowing.

Expand Down
24 changes: 15 additions & 9 deletions src/main/java/com/libraryman_api/borrowing/BorrowingService.java
Original file line number Diff line number Diff line change
Expand Up @@ -107,13 +107,13 @@ public Optional<BorrowingsDto> getBorrowingById(int borrowingId) {
@Transactional
public synchronized BorrowingsDto borrowBook(BorrowingsDto borrowing) {
Optional<BookDto> bookDto = bookService.getBookById(borrowing.getBook().getBookId());
Optional<MembersDto> member = memberService.getMemberById(borrowing.getMember().getMemberId());
if (bookDto.isPresent() && member.isPresent()) {
Optional<MembersDto> memberDto = memberService.getMemberById(borrowing.getMember().getMemberId());
if (bookDto.isPresent() && memberDto.isPresent()) {
Book bookEntity = bookService.DtoToEntity(bookDto.get());
Members memberEntity = memberService.DtoEntity(member.get());
Members memberEntity = memberService.DtoEntity(memberDto.get());

if (bookEntity.getCopiesAvailable() > 0) {
updateBookCopies(borrowing.getBook().getBookId(), "REMOVE", 1);
updateBookCopies(bookDto, "REMOVE", 1);
borrowing.setBorrowDate(new Date());
borrowing.setBook(bookService.EntityToDto(bookEntity));
borrowing.setMember(memberService.EntityToDto(memberEntity));
Expand Down Expand Up @@ -149,7 +149,10 @@ public synchronized BorrowingsDto borrowBook(BorrowingsDto borrowing) {
public synchronized BorrowingsDto returnBook(int borrowingId) {
BorrowingsDto borrowingsDto = getBorrowingById(borrowingId)
.orElseThrow(() -> new ResourceNotFoundException("Borrowing not found"));

Optional<MembersDto> memberDto = memberService.getMemberById(borrowingsDto.getMember().getMemberId());
if(!memberDto.isPresent()){
throw new ResourceNotFoundException("Member not found");
}
if (borrowingsDto.getReturnDate() != null) {
throw new ResourceNotFoundException("Book has already been returned");
}
Expand All @@ -166,7 +169,8 @@ public synchronized BorrowingsDto returnBook(int borrowingId) {
}

borrowingsDto.setReturnDate(new Date());
updateBookCopies(borrowingsDto.getBook().getBookId(), "ADD", 1);
Optional<BookDto> bookDto = bookService.getBookById(borrowingsDto.getBook().getBookId());
updateBookCopies(bookDto, "ADD", 1);
notificationService.bookReturnedNotification(DtoToEntity(borrowingsDto));
borrowingRepository.save(DtoToEntity(borrowingsDto));
return borrowingsDto;
Expand Down Expand Up @@ -197,6 +201,10 @@ private Fines imposeFine(Borrowings borrowing) {
public String payFine(int borrowingId) {
BorrowingsDto borrowingsDto = getBorrowingById(borrowingId)
.orElseThrow(() -> new ResourceNotFoundException("Borrowing not found"));
Optional<MembersDto> memberDto = memberService.getMemberById(borrowingsDto.getMember().getMemberId());
if(!memberDto.isPresent()){
throw new ResourceNotFoundException("Member not found");
}
Fines fine = borrowingsDto.getFine();

if (fine != null && !fine.isPaid()) {
Expand All @@ -222,9 +230,7 @@ public String payFine(int borrowingId) {
* @param numberOfCopies the number of copies to add or remove
* @throws ResourceNotFoundException if the book is not found or if there are not enough copies to remove
*/
public void updateBookCopies(int bookId, String operation, int numberOfCopies) {
Optional<BookDto> bookDto = bookService.getBookById(bookId);

public void updateBookCopies(Optional<BookDto> bookDto, String operation, int numberOfCopies) {
if (bookDto.isPresent()) {
Book bookEntity = bookService.DtoToEntity(bookDto.get());
if (operation.equals("ADD")) {
Expand Down
6 changes: 4 additions & 2 deletions src/main/java/com/libraryman_api/member/MemberService.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ public Optional<MembersDto> getMemberById(int memberId) {
public MembersDto addMember(MembersDto membersDto) {
Members member = DtoEntity(membersDto);
Members currentMember = memberRepository.save(member);
notificationService.accountCreatedNotification(currentMember);
if(currentMember!=null)
notificationService.accountCreatedNotification(currentMember);

return EntityToDto(currentMember);
}
Expand All @@ -111,7 +112,8 @@ public MembersDto updateMember(int memberId, MembersDto membersDtoDetails) {
member.setRole(membersDtoDetails.getRole());
member.setMembershipDate(membersDtoDetails.getMembershipDate());
member = memberRepository.save(member);
notificationService.accountDetailsUpdateNotification(member);
if(member!=null)
notificationService.accountDetailsUpdateNotification(member);
return EntityToDto(member);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
Expand All @@ -29,6 +32,7 @@ public class NotificationService {
private final EmailSender emailSender;
private final NotificationRepository notificationRepository;
private final MemberRepository memberRepository;
private static final Logger LOGGER = LoggerFactory.getLogger(NotificationService.class);

/**
* Constructs a new {@code NotificationService} with the specified {@link EmailSender},
Expand Down Expand Up @@ -201,14 +205,11 @@ public void bookReturnedNotification(Borrowings borrowing) {
* @param notification the notification instance containing information about the notification.
*/
private void sendNotification(Notifications notification) {
Members member = memberRepository.findByMemberId(notification.getMember().getMemberId())
.orElseThrow(() -> new ResourceNotFoundException("Member not found"));

emailSender.send(
member.getEmail(),
notification.getMember().getEmail(),
buildEmail(
subject(notification.getNotificationType()),
member.getName(),
notification.getMember().getName(),
notification.getMessage()
),
subject(notification.getNotificationType()),
Expand All @@ -234,7 +235,13 @@ public void sendDueDateReminders(){

// Send reminders for each borrowing
for (Borrowings borrowing : borrowingsDueSoon) {
reminderNotification(borrowing);
try {
Optional<Members> member = memberRepository.findByMemberId(borrowing.getMember().getMemberId());
if(member.isPresent())
reminderNotification(borrowing);
} catch (ResourceNotFoundException e) {
LOGGER.error("Member not found for memberId: " + borrowing.getMember().getMemberId(), e);
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
spring.application.name=libraryman-api
spring.profiles.active=${ENV:development}
spring.profiles.active=${ENV:development}