AccountService.java
package cz.vsb.crm.service;
import cz.vsb.crm.dto.AccountRequest;
import cz.vsb.crm.dto.AccountResponse;
import cz.vsb.crm.exception.ResourceNotFoundException;
import cz.vsb.crm.model.Account;
import cz.vsb.crm.repository.AccountRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.util.List;
@Service
@RequiredArgsConstructor
@Transactional
public class AccountService {
private final AccountRepository accountRepository;
@Transactional(readOnly = true)
public List<AccountResponse> findAll(boolean activeOnly) {
List<Account> accounts = activeOnly
? accountRepository.findByDeactivatedAtIsNull()
: accountRepository.findAll();
return accounts.stream().map(AccountResponse::from).toList();
}
@Transactional(readOnly = true)
public AccountResponse findById(Long id) {
return AccountResponse.from(get(id));
}
public AccountResponse create(AccountRequest request) {
return AccountResponse.from(accountRepository.save(request.toEntity()));
}
public AccountResponse update(Long id, AccountRequest request) {
Account account = get(id);
request.applyTo(account);
return AccountResponse.from(accountRepository.save(account));
}
public void delete(Long id) {
Account account = get(id);
account.setDeactivatedAt(LocalDate.now());
accountRepository.save(account);
}
private Account get(Long id) {
return accountRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Account", id));
}
}