2 Commits

Author SHA1 Message Date
mirrerror
b48f954cdd update families 2023-12-22 20:02:01 +02:00
mirrerror
2f56a5b76d add families 2023-12-12 22:41:14 +02:00
21 changed files with 396 additions and 58 deletions

View File

@@ -98,7 +98,7 @@ public class ExpenseController {
@GetMapping("/personal-expenses")
@Transactional(readOnly = true)
public ResponseEntity<List<ExpenseDTO>> getExpensesByUser(@RequestParam Optional<LocalDate> date,
public ResponseEntity<List<ExpenseDTO>> getExpensesByTimeUnits(@RequestParam Optional<LocalDate> date,
@RequestParam Optional<Integer> month,
@RequestParam Optional<Integer> startYear,
@RequestParam Optional<Integer> endYear,

View File

@@ -0,0 +1,130 @@
package com.faf223.expensetrackerfaf.controller;
import com.faf223.expensetrackerfaf.dto.FamilyCreationDTO;
import com.faf223.expensetrackerfaf.dto.FamilyDTO;
import com.faf223.expensetrackerfaf.dto.mappers.FamilyMapper;
import com.faf223.expensetrackerfaf.model.Family;
import com.faf223.expensetrackerfaf.model.User;
import com.faf223.expensetrackerfaf.service.FamilyService;
import com.faf223.expensetrackerfaf.service.UserService;
import com.faf223.expensetrackerfaf.util.errors.ErrorResponse;
import com.faf223.expensetrackerfaf.util.exceptions.*;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/families")
@RequiredArgsConstructor
public class FamilyController {
private final FamilyService familyService;
private final FamilyMapper familyMapper;
private final UserService userService;
@GetMapping()
@PreAuthorize("hasRole('ADMIN')")
public ResponseEntity<List<FamilyDTO>> getAllFamilies() {
List<FamilyDTO> families = familyService.getFamilies().stream().map(familyMapper::toDto).collect(Collectors.toList());
if (!families.isEmpty()) return ResponseEntity.ok(families);
else throw new FamiliesNotFoundException("Families not found");
}
@PostMapping()
public ResponseEntity<Map<String, Long>> createNewFamily(@RequestBody @Valid FamilyCreationDTO familyCreationDTO,
BindingResult bindingResult) {
if(bindingResult.hasErrors())
throw new FamilyNotCreatedException("Could not create new family");
Family family = familyMapper.toFamily(familyCreationDTO);
familyService.createOrUpdate(family);
Map<String, Long> response = new HashMap<>();
response.put("familyId", family.getId());
return ResponseEntity.status(HttpStatus.CREATED).body(response);
}
@PatchMapping("/update/{id}")
public ResponseEntity<Void> updateFamily(@PathVariable long id, @RequestBody @Valid FamilyCreationDTO familyDTO,
BindingResult bindingResult) {
if(bindingResult.hasErrors())
throw new FamilyNotUpdatedException(ErrorResponse.from(bindingResult).getMessage());
Family family = familyService.getFamilyById(id);
if(family == null)
throw new FamiliesNotFoundException("The family has not been found");
if(!familyService.containsMember(family))
throw new NotAMemberOfTheFamily("You are not a member of this family");
family.setName(familyDTO.getName());
familyService.createOrUpdate(family);
return ResponseEntity.status(HttpStatus.CREATED).build();
}
@DeleteMapping("/delete/{id}")
public void deleteFamily(@PathVariable long id) {
familyService.deleteFamilyById(id);
}
@PatchMapping("/add-member/{id}")
public ResponseEntity<Void> addFamilyMember(@PathVariable long id, @RequestParam Optional<String> email) {
if(email.isEmpty())
throw new UserNotFoundException("You have not specified the user email");
Family family = familyService.getFamilyById(id);
if(family == null)
throw new FamiliesNotFoundException("The family has not been found");
if(!familyService.containsMember(family))
throw new NotAMemberOfTheFamily("You are not a member of this family");
User user = userService.getUserByEmail(email.get());
if(user == null)
throw new UserNotFoundException("User with the specified email has not been found");
family.getMembers().add(user);
familyService.createOrUpdate(family);
return ResponseEntity.status(HttpStatus.CREATED).build();
}
@PatchMapping("/remove-member/{id}")
public ResponseEntity<Void> removeFamilyMember(@PathVariable long id, @RequestParam Optional<String> email) {
if(email.isEmpty())
throw new UserNotFoundException("You have not specified the user email");
Family family = familyService.getFamilyById(id);
if(family == null)
throw new FamiliesNotFoundException("The family has not been found");
if(!familyService.containsMember(family))
throw new NotAMemberOfTheFamily("You are not a member of this family");
User user = userService.getUserByEmail(email.get());
if(user == null)
throw new UserNotFoundException("User with the specified email has not been found");
family.getMembers().remove(user);
familyService.createOrUpdate(family);
return ResponseEntity.status(HttpStatus.CREATED).build();
}
}

View File

@@ -98,7 +98,7 @@ public class IncomeController {
@GetMapping("/personal-incomes")
@Transactional(readOnly = true)
public ResponseEntity<List<IncomeDTO>> getIncomesByUser(@RequestParam Optional<LocalDate> date,
public ResponseEntity<List<IncomeDTO>> getIncomesByTimeUnits(@RequestParam Optional<LocalDate> date,
@RequestParam Optional<Integer> month,
@RequestParam Optional<Integer> startYear,
@RequestParam Optional<Integer> endYear,

View File

@@ -23,10 +23,7 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.*;
@RestController
@RequestMapping("/users")
@@ -86,7 +83,7 @@ public class UserController {
@GetMapping()
@PreAuthorize("hasRole('ADMIN')")
public ResponseEntity<ArrayList<UserDTO>> getAllUsers() {
public ResponseEntity<List<UserDTO>> getAllUsers() {
ArrayList<User> users = new ArrayList<>(userService.getUsers());
return ResponseEntity.ok(userMapper.toDto(users));

View File

@@ -0,0 +1,14 @@
package com.faf223.expensetrackerfaf.dto;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class FamilyCreationDTO {
@NotNull(message = "Name must not be null")
@NotEmpty(message = "Name must not be empty")
private String name;
}

View File

@@ -0,0 +1,14 @@
package com.faf223.expensetrackerfaf.dto;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class FamilyDTO {
@NotNull(message = "Name must not be null")
@NotEmpty(message = "Name must not be empty")
private String name;
}

View File

@@ -0,0 +1,25 @@
package com.faf223.expensetrackerfaf.dto.mappers;
import com.faf223.expensetrackerfaf.dto.FamilyCreationDTO;
import com.faf223.expensetrackerfaf.dto.FamilyDTO;
import com.faf223.expensetrackerfaf.model.Family;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class FamilyMapper {
private final UserMapper userMapper;
public FamilyDTO toDto(Family family) {
return new FamilyDTO(family.getId(), family.getName(), userMapper.toDto(family.getMembers()));
}
public Family toFamily(FamilyCreationDTO familyCreationDTO) {
Family family = new Family();
family.setName(familyCreationDTO.getName());
return family;
}
}

View File

@@ -2,12 +2,9 @@ package com.faf223.expensetrackerfaf.dto.mappers;
import com.faf223.expensetrackerfaf.dto.IncomeCreationDTO;
import com.faf223.expensetrackerfaf.dto.IncomeDTO;
import com.faf223.expensetrackerfaf.model.Expense;
import com.faf223.expensetrackerfaf.model.Income;
import com.faf223.expensetrackerfaf.service.IncomeCategoryService;
import com.faf223.expensetrackerfaf.service.IncomeService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDate;

View File

@@ -6,6 +6,7 @@ import com.faf223.expensetrackerfaf.model.User;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class UserMapper {
@@ -14,11 +15,9 @@ public class UserMapper {
return new UserDTO(user.getFirstName(), user.getLastName(), user.getUsername());
}
public ArrayList<UserDTO> toDto(ArrayList<User> user) {
ArrayList<UserDTO> list = new ArrayList<>();
for (User u: user)
public List<UserDTO> toDto(List<User> user) {
List<UserDTO> list = new ArrayList<>();
for (User u : user)
list.add(toDto(u));
return list;

View File

@@ -38,9 +38,6 @@ public class Expense implements IMoneyTransaction {
@DecimalMin(value = "0.0", inclusive = false)
private BigDecimal amount;
public Expense(LocalDate date, BigDecimal amount) {
}
public Expense(ExpenseCategory expenseCategory, LocalDate date, BigDecimal amount) {
this.category = expenseCategory;
this.date = date;

View File

@@ -0,0 +1,42 @@
package com.faf223.expensetrackerfaf.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotEmpty;
import lombok.*;
import java.util.List;
import java.util.Objects;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity(name = "family")
@Builder
public class Family {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "family_id")
private Long id;
@NotEmpty
@Column(name = "family_name")
private String name;
@OneToMany(mappedBy = "family", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@ToString.Exclude
private List<User> members;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Family family = (Family) o;
return Objects.equals(id, family.id) && Objects.equals(name, family.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}

View File

@@ -1,48 +1,55 @@
package com.faf223.expensetrackerfaf.model;
package com.faf223.expensetrackerfaf.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.*;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.*;
import java.util.List;
import java.util.List;
@Entity(name = "users")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id
@Column(name = "user_uuid")
@GeneratedValue(strategy = GenerationType.UUID)
private String userUuid;
@Entity(name = "users")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id
@Column(name = "user_uuid")
@GeneratedValue(strategy = GenerationType.UUID)
private String userUuid;
@Column(name = "name")
@NotNull(message = "First name must not be null")
@NotEmpty(message = "First name must not be empty")
private String firstName;
@Column(name = "name")
@NotNull(message = "First name must not be null")
@NotEmpty(message = "First name must not be empty")
private String firstName;
@Column(name = "surname")
@NotNull(message = "Last name must not be null")
@NotEmpty(message = "Last name must not be empty")
private String lastName;
@Column(name = "surname")
@NotNull(message = "Last name must not be null")
@NotEmpty(message = "Last name must not be empty")
private String lastName;
@Column(name = "username")
@NotNull(message = "Username must not be null")
@NotEmpty(message = "Username must not be empty")
private String username;
@Column(name = "username")
@NotNull(message = "Username must not be null")
@NotEmpty(message = "Username must not be empty")
private String username;
@Transient
// @NotNull(message = "Password must not be null")
// @NotEmpty(message = "Password must not be empty")
private String password;
@Transient
// @NotNull(message = "Password must not be null")
// @NotEmpty(message = "Password must not be empty")
private String password;
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@ToString.Exclude
private List<Expense> expenses;
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@ToString.Exclude
private List<Expense> expenses;
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@ToString.Exclude
private List<Income> incomes;
}
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@ToString.Exclude
private List<Income> incomes;
@ManyToOne
@JoinColumn(name = "family_id")
@ToString.Exclude
@JsonIgnore
private Family family;
}

View File

@@ -0,0 +1,9 @@
package com.faf223.expensetrackerfaf.repository;
import com.faf223.expensetrackerfaf.model.Family;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface FamilyRepository extends JpaRepository<Family, Long> {
}

View File

@@ -6,4 +6,4 @@ import org.springframework.stereotype.Repository;
@Repository
public interface IncomeCategoryRepository extends JpaRepository<IncomeCategory, Long> {
}
}

View File

@@ -130,6 +130,8 @@ public class ExpenseService implements ITransactionService {
}
return true;
}
throw new UserNotAuthenticatedException("You are not authenticated");

View File

@@ -0,0 +1,67 @@
package com.faf223.expensetrackerfaf.service;
import com.faf223.expensetrackerfaf.model.Credential;
import com.faf223.expensetrackerfaf.model.Family;
import com.faf223.expensetrackerfaf.model.User;
import com.faf223.expensetrackerfaf.repository.CredentialRepository;
import com.faf223.expensetrackerfaf.repository.FamilyRepository;
import com.faf223.expensetrackerfaf.repository.UserRepository;
import com.faf223.expensetrackerfaf.util.exceptions.UserNotAuthenticatedException;
import com.faf223.expensetrackerfaf.util.exceptions.UserNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class FamilyService {
private final FamilyRepository familyRepository;
private final CredentialRepository credentialRepository;
private final UserRepository userRepository;
public List<Family> getFamilies() {
return familyRepository.findAll();
}
public void createOrUpdate(Family family) {
familyRepository.save(family);
}
public Family getFamilyById(long id) {
return familyRepository.findById(id).orElse(null);
}
public boolean containsMember(Family family) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof UserDetails userDetails) {
if(authentication.getAuthorities().stream().noneMatch(authority -> authority.getAuthority().equals("ADMIN"))) {
Optional<Credential> credential = credentialRepository.findByEmail(userDetails.getUsername());
if(credential.isEmpty()) throw new UserNotFoundException("The user has not been found");
Optional<User> user = userRepository.findById(credential.get().getUser().getUserUuid());
if(user.isEmpty()) throw new UserNotFoundException("The user has not been found");
return user.get().getFamily().equals(family);
}
return true;
}
throw new UserNotAuthenticatedException("You are not authenticated");
}
public void deleteFamilyById(long id) {
familyRepository.deleteById(id);
}
}

View File

@@ -129,6 +129,8 @@ public class IncomeService implements ITransactionService {
}
return true;
}
throw new UserNotAuthenticatedException("You are not authenticated");

View File

@@ -0,0 +1,9 @@
package com.faf223.expensetrackerfaf.util.exceptions;
public class FamiliesNotFoundException extends RuntimeException {
public FamiliesNotFoundException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,9 @@
package com.faf223.expensetrackerfaf.util.exceptions;
public class FamilyNotCreatedException extends RuntimeException {
public FamilyNotCreatedException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,9 @@
package com.faf223.expensetrackerfaf.util.exceptions;
public class FamilyNotUpdatedException extends RuntimeException {
public FamilyNotUpdatedException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,9 @@
package com.faf223.expensetrackerfaf.util.exceptions;
public class NotAMemberOfTheFamily extends RuntimeException {
public NotAMemberOfTheFamily(String message) {
super(message);
}
}