Merge pull request #33 from lumijiez/dimas_restupdate

Update Rest API
This commit was merged in pull request #33.
This commit is contained in:
Dima
2023-11-13 10:55:06 +02:00
committed by GitHub
17 changed files with 235 additions and 37 deletions

View File

@@ -1,6 +1,6 @@
package com.faf223.expensetrackerfaf.config; package com.faf223.expensetrackerfaf.config;
import com.faf223.expensetrackerfaf.controller.auth.ErrorResponse; import com.faf223.expensetrackerfaf.util.errors.ErrorResponse;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.FilterChain; import jakarta.servlet.FilterChain;
@@ -61,7 +61,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json"); response.setContentType("application/json");
ErrorResponse errorResponse = new ErrorResponse("TokenExpired", "Your session has expired. Please log in again."); ErrorResponse errorResponse = new ErrorResponse("Your session has expired. Refresh your token.");
ObjectMapper objectMapper = new ObjectMapper(); // You may need to import ObjectMapper ObjectMapper objectMapper = new ObjectMapper(); // You may need to import ObjectMapper
response.getWriter().write(objectMapper.writeValueAsString(errorResponse)); response.getWriter().write(objectMapper.writeValueAsString(errorResponse));

View File

@@ -9,6 +9,10 @@ import com.faf223.expensetrackerfaf.model.User;
import com.faf223.expensetrackerfaf.service.ExpenseCategoryService; import com.faf223.expensetrackerfaf.service.ExpenseCategoryService;
import com.faf223.expensetrackerfaf.service.ExpenseService; import com.faf223.expensetrackerfaf.service.ExpenseService;
import com.faf223.expensetrackerfaf.service.UserService; import com.faf223.expensetrackerfaf.service.UserService;
import com.faf223.expensetrackerfaf.util.errors.ErrorResponse;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionNotCreatedException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionNotUpdatedException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionsNotFoundException;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@@ -19,8 +23,11 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.time.Month;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@RestController @RestController
@@ -38,7 +45,7 @@ public class ExpenseController {
public ResponseEntity<List<ExpenseDTO>> getAllExpenses() { public ResponseEntity<List<ExpenseDTO>> getAllExpenses() {
List<ExpenseDTO> expenses = expenseService.getTransactions().stream().map(expenseMapper::toDto).collect(Collectors.toList()); List<ExpenseDTO> expenses = expenseService.getTransactions().stream().map(expenseMapper::toDto).collect(Collectors.toList());
if (!expenses.isEmpty()) return ResponseEntity.ok(expenses); if (!expenses.isEmpty()) return ResponseEntity.ok(expenses);
else return ResponseEntity.notFound().build(); else throw new TransactionsNotFoundException("Transactions not found");
} }
@PostMapping() @PostMapping()
@@ -46,6 +53,9 @@ public class ExpenseController {
BindingResult bindingResult) { BindingResult bindingResult) {
Expense expense = expenseMapper.toExpense(expenseDTO); Expense expense = expenseMapper.toExpense(expenseDTO);
if(bindingResult.hasErrors())
throw new TransactionNotCreatedException(ErrorResponse.from(bindingResult).getMessage());
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof UserDetails userDetails) { if (authentication != null && authentication.getPrincipal() instanceof UserDetails userDetails) {
@@ -58,7 +68,7 @@ public class ExpenseController {
return ResponseEntity.status(HttpStatus.CREATED).build(); return ResponseEntity.status(HttpStatus.CREATED).build();
} }
return ResponseEntity.notFound().build(); throw new TransactionNotCreatedException("Could not create new expense");
} }
@@ -67,6 +77,9 @@ public class ExpenseController {
public ResponseEntity<Void> updateExpense(@PathVariable long id, @RequestBody ExpenseCreationDTO expenseDTO, public ResponseEntity<Void> updateExpense(@PathVariable long id, @RequestBody ExpenseCreationDTO expenseDTO,
BindingResult bindingResult) { BindingResult bindingResult) {
Expense expense = expenseService.getTransactionById(id); Expense expense = expenseService.getTransactionById(id);
if(expense == null) throw new TransactionsNotFoundException("The expense has not been found");
ExpenseCategory category = expenseCategoryService.getCategoryById(expenseDTO.getExpenseCategory()); ExpenseCategory category = expenseCategoryService.getCategoryById(expenseDTO.getExpenseCategory());
expense.setCategory(category); expense.setCategory(category);
expense.setAmount(expenseDTO.getAmount()); expense.setAmount(expenseDTO.getAmount());
@@ -75,19 +88,24 @@ public class ExpenseController {
expenseService.createOrUpdate(expense); expenseService.createOrUpdate(expense);
return ResponseEntity.status(HttpStatus.CREATED).build(); return ResponseEntity.status(HttpStatus.CREATED).build();
} else { } else {
return ResponseEntity.notFound().build(); throw new TransactionNotUpdatedException(ErrorResponse.from(bindingResult).getMessage());
} }
} }
@GetMapping("/personal-expenses") @GetMapping("/personal-expenses")
public ResponseEntity<List<ExpenseDTO>> getExpensesByUser() { public ResponseEntity<List<ExpenseDTO>> getExpensesByUser(@RequestParam Optional<LocalDate> date,
@RequestParam Optional<Month> month) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof UserDetails userDetails) { if (authentication != null && authentication.getPrincipal() instanceof UserDetails userDetails) {
String email = userDetails.getUsername(); String email = userDetails.getUsername();
List<ExpenseDTO> expenses = expenseService.getTransactionsByEmail(email).stream().map(expenseMapper::toDto).collect(Collectors.toList()); List<ExpenseDTO> expenses;
expenses = date.map(localDate -> expenseService.getTransactionsByDate(localDate).stream().map(expenseMapper::toDto).toList())
.orElseGet(() -> month.map(value -> expenseService.getTransactionsByMonth(value).stream().map(expenseMapper::toDto).toList())
.orElseGet(() -> expenseService.getTransactionsByEmail(email).stream().map(expenseMapper::toDto).toList()));
if (!expenses.isEmpty()) { if (!expenses.isEmpty()) {
return ResponseEntity.ok(expenses); return ResponseEntity.ok(expenses);
@@ -96,14 +114,14 @@ public class ExpenseController {
} }
} }
return ResponseEntity.notFound().build(); throw new TransactionsNotFoundException("The expenses have not been found");
} }
@GetMapping("/categories") @GetMapping("/categories")
public ResponseEntity<List<ExpenseCategory>> getAllCategories() { public ResponseEntity<List<ExpenseCategory>> getAllCategories() {
List<ExpenseCategory> categories = expenseCategoryService.getAllCategories(); List<ExpenseCategory> categories = expenseCategoryService.getAllCategories();
if (!categories.isEmpty()) return ResponseEntity.ok(categories); if (!categories.isEmpty()) return ResponseEntity.ok(categories);
else return ResponseEntity.notFound().build(); else throw new TransactionsNotFoundException("The expenses have not been found");
} }
@DeleteMapping("/delete/{id}") @DeleteMapping("/delete/{id}")

View File

@@ -0,0 +1,56 @@
package com.faf223.expensetrackerfaf.controller;
import com.faf223.expensetrackerfaf.util.errors.ErrorResponse;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionDoesNotBelongToTheUserException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionNotCreatedException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionsNotFoundException;
import com.faf223.expensetrackerfaf.util.exceptions.UserNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler
private ResponseEntity<ErrorResponse> handleDoesNotBelongException(TransactionDoesNotBelongToTheUserException e) {
ErrorResponse response = new ErrorResponse(
e.getMessage(),
System.currentTimeMillis()
);
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
@ExceptionHandler
private ResponseEntity<ErrorResponse> handleTransactionNotCreatedException(TransactionNotCreatedException e) {
ErrorResponse response = new ErrorResponse(
e.getMessage(),
System.currentTimeMillis()
);
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
@ExceptionHandler
private ResponseEntity<ErrorResponse> handleTransactionsNotFoundException(TransactionsNotFoundException e) {
ErrorResponse response = new ErrorResponse(
e.getMessage(),
System.currentTimeMillis()
);
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
@ExceptionHandler
private ResponseEntity<ErrorResponse> handleUserNotFoundException(UserNotFoundException e) {
ErrorResponse response = new ErrorResponse(
e.getMessage(),
System.currentTimeMillis()
);
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
}

View File

@@ -3,10 +3,16 @@ package com.faf223.expensetrackerfaf.controller;
import com.faf223.expensetrackerfaf.dto.IncomeCreationDTO; import com.faf223.expensetrackerfaf.dto.IncomeCreationDTO;
import com.faf223.expensetrackerfaf.dto.IncomeDTO; import com.faf223.expensetrackerfaf.dto.IncomeDTO;
import com.faf223.expensetrackerfaf.dto.mappers.IncomeMapper; import com.faf223.expensetrackerfaf.dto.mappers.IncomeMapper;
import com.faf223.expensetrackerfaf.model.*; import com.faf223.expensetrackerfaf.model.Income;
import com.faf223.expensetrackerfaf.model.IncomeCategory;
import com.faf223.expensetrackerfaf.model.User;
import com.faf223.expensetrackerfaf.service.IncomeCategoryService; import com.faf223.expensetrackerfaf.service.IncomeCategoryService;
import com.faf223.expensetrackerfaf.service.IncomeService; import com.faf223.expensetrackerfaf.service.IncomeService;
import com.faf223.expensetrackerfaf.service.UserService; import com.faf223.expensetrackerfaf.service.UserService;
import com.faf223.expensetrackerfaf.util.errors.ErrorResponse;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionNotCreatedException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionNotUpdatedException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionsNotFoundException;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@@ -17,8 +23,11 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.time.Month;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@RestController @RestController
@@ -36,13 +45,17 @@ public class IncomeController {
public ResponseEntity<List<IncomeDTO>> getAllIncomes() { public ResponseEntity<List<IncomeDTO>> getAllIncomes() {
List<IncomeDTO> incomes = incomeService.getTransactions().stream().map(incomeMapper::toDto).collect(Collectors.toList()); List<IncomeDTO> incomes = incomeService.getTransactions().stream().map(incomeMapper::toDto).collect(Collectors.toList());
if (!incomes.isEmpty()) return ResponseEntity.ok(incomes); if (!incomes.isEmpty()) return ResponseEntity.ok(incomes);
else return ResponseEntity.notFound().build(); else throw new TransactionsNotFoundException("Transactions not found");
} }
@PostMapping() @PostMapping()
public ResponseEntity<Void> createNewIncome(@RequestBody IncomeCreationDTO incomeDTO, public ResponseEntity<Void> createNewIncome(@RequestBody IncomeCreationDTO incomeDTO,
BindingResult bindingResult) { BindingResult bindingResult) {
Income income = incomeMapper.toIncome(incomeDTO); Income income = incomeMapper.toIncome(incomeDTO);
if(bindingResult.hasErrors())
throw new TransactionNotCreatedException(ErrorResponse.from(bindingResult).getMessage());
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof UserDetails userDetails) { if (authentication != null && authentication.getPrincipal() instanceof UserDetails userDetails) {
@@ -51,12 +64,11 @@ public class IncomeController {
User user = userService.getUserByEmail(email); User user = userService.getUserByEmail(email);
income.setUser(user); income.setUser(user);
System.out.println(income);
incomeService.createOrUpdate(income); incomeService.createOrUpdate(income);
return ResponseEntity.status(HttpStatus.CREATED).build(); return ResponseEntity.status(HttpStatus.CREATED).build();
} }
return ResponseEntity.notFound().build(); throw new TransactionNotCreatedException("Could not create new expense");
} }
// TODO: check if the income belongs to the user, extract logic into service // TODO: check if the income belongs to the user, extract logic into service
@@ -64,6 +76,9 @@ public class IncomeController {
public ResponseEntity<Void> updateIncome(@PathVariable long id, @RequestBody IncomeCreationDTO incomeDTO, public ResponseEntity<Void> updateIncome(@PathVariable long id, @RequestBody IncomeCreationDTO incomeDTO,
BindingResult bindingResult) { BindingResult bindingResult) {
Income income = incomeService.getTransactionById(id); Income income = incomeService.getTransactionById(id);
if(income == null) throw new TransactionsNotFoundException("The income has not been found");
IncomeCategory category = incomeCategoryService.getCategoryById(incomeDTO.getIncomeCategory()); IncomeCategory category = incomeCategoryService.getCategoryById(incomeDTO.getIncomeCategory());
income.setCategory(category); income.setCategory(category);
income.setAmount(incomeDTO.getAmount()); income.setAmount(incomeDTO.getAmount());
@@ -72,19 +87,24 @@ public class IncomeController {
incomeService.createOrUpdate(income); incomeService.createOrUpdate(income);
return ResponseEntity.status(HttpStatus.CREATED).build(); return ResponseEntity.status(HttpStatus.CREATED).build();
} else { } else {
return ResponseEntity.notFound().build(); throw new TransactionNotUpdatedException(ErrorResponse.from(bindingResult).getMessage());
} }
} }
@GetMapping("/personal-incomes") @GetMapping("/personal-incomes")
public ResponseEntity<List<IncomeDTO>> getIncomesByUser() { public ResponseEntity<List<IncomeDTO>> getExpensesByUser(@RequestParam Optional<LocalDate> date,
@RequestParam Optional<Month> month) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof UserDetails userDetails) { if (authentication != null && authentication.getPrincipal() instanceof UserDetails userDetails) {
String email = userDetails.getUsername(); String email = userDetails.getUsername();
List<IncomeDTO> incomes = incomeService.getTransactionsByEmail(email).stream().map(incomeMapper::toDto).collect(Collectors.toList()); List<IncomeDTO> incomes;
incomes = date.map(localDate -> incomeService.getTransactionsByDate(localDate).stream().map(incomeMapper::toDto).toList())
.orElseGet(() -> month.map(value -> incomeService.getTransactionsByMonth(value).stream().map(incomeMapper::toDto).toList())
.orElseGet(() -> incomeService.getTransactionsByEmail(email).stream().map(incomeMapper::toDto).toList()));
if (!incomes.isEmpty()) { if (!incomes.isEmpty()) {
return ResponseEntity.ok(incomes); return ResponseEntity.ok(incomes);
@@ -93,14 +113,14 @@ public class IncomeController {
} }
} }
return ResponseEntity.notFound().build(); throw new TransactionsNotFoundException("The expenses have not been found");
} }
@GetMapping("/categories") @GetMapping("/categories")
public ResponseEntity<List<IncomeCategory>> getAllCategories() { public ResponseEntity<List<IncomeCategory>> getAllCategories() {
List<IncomeCategory> categories = incomeCategoryService.getAllCategories(); List<IncomeCategory> categories = incomeCategoryService.getAllCategories();
if (!categories.isEmpty()) return ResponseEntity.ok(categories); if (!categories.isEmpty()) return ResponseEntity.ok(categories);
else return ResponseEntity.notFound().build(); else throw new TransactionsNotFoundException("The expenses have not been found");
} }
@DeleteMapping("/delete/{id}") @DeleteMapping("/delete/{id}")

View File

@@ -5,6 +5,7 @@ import com.faf223.expensetrackerfaf.dto.UserDTO;
import com.faf223.expensetrackerfaf.dto.mappers.UserMapper; import com.faf223.expensetrackerfaf.dto.mappers.UserMapper;
import com.faf223.expensetrackerfaf.model.User; import com.faf223.expensetrackerfaf.model.User;
import com.faf223.expensetrackerfaf.service.UserService; import com.faf223.expensetrackerfaf.service.UserService;
import com.faf223.expensetrackerfaf.util.exceptions.UserNotFoundException;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
@@ -32,7 +33,7 @@ public class UserController {
userService.updateUser(user); userService.updateUser(user);
return ResponseEntity.ok(userMapper.toDto(user)); return ResponseEntity.ok(userMapper.toDto(user));
} else { } else {
return ResponseEntity.notFound().build(); throw new UserNotFoundException("The user has not been found");
} }
} }
@@ -43,9 +44,8 @@ public class UserController {
if (authentication != null && authentication.getPrincipal() instanceof UserDetails userDetails) { if (authentication != null && authentication.getPrincipal() instanceof UserDetails userDetails) {
User user = userService.getUserByEmail(userDetails.getUsername()); User user = userService.getUserByEmail(userDetails.getUsername());
if (user != null) return ResponseEntity.ok(userMapper.toDto(user)); if (user != null) return ResponseEntity.ok(userMapper.toDto(user));
else return ResponseEntity.notFound().build();
} }
return ResponseEntity.notFound().build(); throw new UserNotFoundException("The user has not been found");
} }
@GetMapping() @GetMapping()

View File

@@ -1,16 +0,0 @@
package com.faf223.expensetrackerfaf.controller.auth;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ErrorResponse {
private String error;
private String message;
public ErrorResponse(String error, String message) {
this.error = error;
this.message = message;
}
}

View File

@@ -5,9 +5,13 @@ import com.faf223.expensetrackerfaf.model.User;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.time.LocalDate;
import java.util.List; import java.util.List;
@Repository @Repository
public interface ExpenseRepository extends JpaRepository<Expense, Long> { public interface ExpenseRepository extends JpaRepository<Expense, Long> {
List<Expense> findByUser(User user); List<Expense> findByUser(User user);
List<Expense> findByDate(LocalDate date);
List<Expense> findByDateBetween(LocalDate start, LocalDate end);
} }

View File

@@ -5,9 +5,13 @@ import com.faf223.expensetrackerfaf.model.User;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.time.LocalDate;
import java.util.List; import java.util.List;
@Repository @Repository
public interface IncomeRepository extends JpaRepository<Income, Long> { public interface IncomeRepository extends JpaRepository<Income, Long> {
List<Income> findByUser(User user); List<Income> findByUser(User user);
List<Income> findByDate(LocalDate date);
List<Income> findByDateBetween(LocalDate start, LocalDate end);
} }

View File

@@ -8,6 +8,8 @@ import com.faf223.expensetrackerfaf.repository.ExpenseRepository;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@@ -33,6 +35,20 @@ public class ExpenseService implements ITransactionService {
return new ArrayList<>(); return new ArrayList<>();
} }
@Override
public List<Expense> getTransactionsByDate(LocalDate date) {
return expenseRepository.findByDate(date);
}
// TODO: store transaction month in a separate field in the DB and change this logic
@Override
public List<Expense> getTransactionsByMonth(Month month) {
LocalDate startOfMonth = LocalDate.of(LocalDate.now().getYear(), month, 1);
LocalDate endOfMonth = startOfMonth.plusMonths(1).minusDays(1);
return expenseRepository.findByDateBetween(startOfMonth, endOfMonth);
}
public List<Expense> getTransactions() { public List<Expense> getTransactions() {
return expenseRepository.findAll(); return expenseRepository.findAll();
} }

View File

@@ -2,6 +2,8 @@ package com.faf223.expensetrackerfaf.service;
import com.faf223.expensetrackerfaf.model.IMoneyTransaction; import com.faf223.expensetrackerfaf.model.IMoneyTransaction;
import java.time.LocalDate;
import java.time.Month;
import java.util.List; import java.util.List;
public interface ITransactionService { public interface ITransactionService {
@@ -9,6 +11,8 @@ public interface ITransactionService {
void createOrUpdate(IMoneyTransaction transaction); void createOrUpdate(IMoneyTransaction transaction);
List<? extends IMoneyTransaction> getTransactions(); List<? extends IMoneyTransaction> getTransactions();
List<? extends IMoneyTransaction> getTransactionsByEmail(String email); List<? extends IMoneyTransaction> getTransactionsByEmail(String email);
List<? extends IMoneyTransaction> getTransactionsByDate(LocalDate date);
List<? extends IMoneyTransaction> getTransactionsByMonth(Month month);
IMoneyTransaction getTransactionById(long id); IMoneyTransaction getTransactionById(long id);
void deleteTransactionById(long it); void deleteTransactionById(long it);

View File

@@ -1,6 +1,7 @@
package com.faf223.expensetrackerfaf.service; package com.faf223.expensetrackerfaf.service;
import com.faf223.expensetrackerfaf.model.Credential; import com.faf223.expensetrackerfaf.model.Credential;
import com.faf223.expensetrackerfaf.model.Expense;
import com.faf223.expensetrackerfaf.model.IMoneyTransaction; import com.faf223.expensetrackerfaf.model.IMoneyTransaction;
import com.faf223.expensetrackerfaf.model.Income; import com.faf223.expensetrackerfaf.model.Income;
import com.faf223.expensetrackerfaf.repository.CredentialRepository; import com.faf223.expensetrackerfaf.repository.CredentialRepository;
@@ -8,6 +9,8 @@ import com.faf223.expensetrackerfaf.repository.IncomeRepository;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@@ -37,6 +40,20 @@ public class IncomeService implements ITransactionService {
return new ArrayList<>(); return new ArrayList<>();
} }
@Override
public List<Income> getTransactionsByDate(LocalDate date) {
return incomeRepository.findByDate(date);
}
// TODO: store transaction month in a separate field in the DB and change this logic
@Override
public List<Income> getTransactionsByMonth(Month month) {
LocalDate startOfMonth = LocalDate.of(LocalDate.now().getYear(), month, 1);
LocalDate endOfMonth = startOfMonth.plusMonths(1).minusDays(1);
return incomeRepository.findByDateBetween(startOfMonth, endOfMonth);
}
public Income getTransactionById(long id) { public Income getTransactionById(long id) {
return incomeRepository.findById(id).orElse(null); return incomeRepository.findById(id).orElse(null);
} }

View File

@@ -0,0 +1,40 @@
package com.faf223.expensetrackerfaf.util.errors;
import lombok.Data;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import java.util.List;
@Data
public class ErrorResponse {
private String message;
private long timestamp;
public ErrorResponse(String message, long timestamp) {
this.message = message;
this.timestamp = timestamp;
}
public ErrorResponse(String message) {
this.message = message;
this.timestamp = System.currentTimeMillis();
}
public static ErrorResponse from(BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
StringBuilder errorMessage = new StringBuilder();
List<FieldError> errors = bindingResult.getFieldErrors();
for(FieldError fieldError : errors)
errorMessage.append(fieldError.getField())
.append(" - ")
.append(fieldError.getDefaultMessage())
.append(";");
return new ErrorResponse(errorMessage.toString(), System.currentTimeMillis());
}
return new ErrorResponse("No error message was provided", System.currentTimeMillis());
}
}

View File

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

View File

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

View File

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

View File

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

View File

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