munera-vaadin/src/main/java/com/application/munera/services/PersonService.java

68 lines
2.3 KiB
Java
Raw Normal View History

2024-05-21 21:21:55 +00:00
package com.application.munera.services;
2024-06-04 12:12:34 +00:00
import com.application.munera.data.Expense;
2024-05-21 21:21:55 +00:00
import com.application.munera.data.Person;
import com.application.munera.repositories.PersonRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
2024-06-04 12:12:34 +00:00
import java.math.BigDecimal;
2024-05-21 21:21:55 +00:00
import java.util.List;
import java.util.Optional;
@Service
public class PersonService {
private final PersonRepository personRepository;
2024-06-04 12:12:34 +00:00
private final ExpenseService expenseService;
2024-05-21 21:21:55 +00:00
2024-06-04 12:12:34 +00:00
public PersonService(PersonRepository personRepository, ExpenseService expenseService) {
2024-05-21 21:21:55 +00:00
this.personRepository = personRepository;
2024-06-04 12:12:34 +00:00
this.expenseService = expenseService;
2024-05-21 21:21:55 +00:00
}
public Optional<Person> get(Long id) {
return personRepository.findById(id);
}
public List<Person> findAll() {
return this.personRepository.findAll();
}
2024-06-04 13:43:17 +00:00
public void update(Person person) {
this.personRepository.save(person);
2024-05-21 21:21:55 +00:00
}
public void delete(Long id) {
this.personRepository.deleteById(id);
}
2024-05-24 17:15:30 +00:00
public Page<Person> list(Pageable pageable){
return personRepository.findAll(pageable);
}
2024-05-21 21:21:55 +00:00
public Page<Person> list(Pageable pageable, Specification<Person> filter) {
return this.personRepository.findAll(filter, pageable);
}
public int count() {
return (int) this.personRepository.count();
}
2024-06-04 12:12:34 +00:00
public BigDecimal calculateDebt(final Person person){
return this.expenseService.findDebtByUser(person).stream().map(Expense::getCost).reduce(BigDecimal.ZERO, BigDecimal::add);
}
2024-06-04 12:35:16 +00:00
public BigDecimal calculateCredit(final Person person) {
return this.expenseService.findCreditByUser(person).stream().map(Expense::getCost).reduce(BigDecimal.ZERO, BigDecimal::add);
}
2024-06-22 11:29:53 +00:00
public BigDecimal calculateNetBalance(final Person person) {
final var credit = this.expenseService.findCreditByUser(person).stream().map(Expense::getCost).reduce(BigDecimal.ZERO, BigDecimal::add);
final var debit = this.expenseService.findDebtByUser(person).stream().map(Expense::getCost).reduce(BigDecimal.ZERO, BigDecimal::add);
2024-06-22 11:29:53 +00:00
return credit.subtract(debit);
}
2024-05-21 21:21:55 +00:00
}