Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import java.util.Collections;
import java.util.List;

import io.jsonwebtoken.JwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
Expand Down Expand Up @@ -46,7 +47,12 @@ protected void doFilterInternal(
}

jwt = authHeader.substring(7);
userEmail = jwtService.extractUsername(jwt);
try {
userEmail = jwtService.extractUsername(jwt);
} catch (JwtException e) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token expired or invalid");
return;
}

if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@ public class AllowanceController {
public ResponseEntity<Allowance> createAllowance(
@RequestHeader("Authorization") String authHeader, @Valid @RequestBody CreateAllowance req) {
String token = authHeader.substring(7);
return ResponseEntity.status(HttpStatus.ACCEPTED)
.body(allowanceService.createAllowance(req, token));
return ResponseEntity.status(HttpStatus.OK).body(allowanceService.createAllowance(req, token));
}

@GetMapping("")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import moneybuddy.fr.moneybuddy.dtos.Receipt.Receipt;
import moneybuddy.fr.moneybuddy.dtos.Receipt.SendReceipt;
import moneybuddy.fr.moneybuddy.service.ReceiptOcrService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
Expand All @@ -31,8 +30,8 @@ public ResponseEntity<Receipt> scanReceipt(
throws IOException {

String token = authHeader.substring(7);
boolean res = receiptOcrService.updateMoneyAndInsertReceipt(body.getFile(), token);
Receipt receipt = receiptOcrService.updateMoneyAndInsertReceipt(body.getFile(), token);

return ResponseEntity.status(res ? HttpStatus.OK : HttpStatus.BAD_REQUEST).body(null);
return ResponseEntity.ok(receipt);
}
}
16 changes: 10 additions & 6 deletions src/main/java/moneybuddy/fr/moneybuddy/dtos/TaskUpdate.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,21 +33,23 @@ public class TaskUpdate {

@PositiveOrZero(message = "coinReward doit etre positif ou égale a 0")
@Max(message = "Doit pas exceder 50", value = 50)
private int coinReward;
private Integer coinReward;

@PositiveOrZero(message = "moneyReward doit etre positif ou égale a 0")
private BigDecimal moneyReward;

private LocalDateTime dateLimit;
private List<DayOfWeek> weeklyDays;
private int monthlyDay;
private boolean preValidate;
private boolean disable;
private Integer monthlyDay;
private Boolean preValidate;
private Boolean disable;

@AssertTrue(message = "Au moins une récompense (coinReward ou moneyReward) doit être fournie")
@Schema(hidden = true)
public boolean isRewardValid() {
return (coinReward == 0 && moneyReward == null) || coinReward != 0 || moneyReward != null;
return (coinReward == null || coinReward == 0) && moneyReward == null
|| (coinReward != null && coinReward != 0)
|| moneyReward != null;
}

@AssertTrue(
Expand All @@ -61,6 +63,8 @@ public boolean isWeeklyDays() {

@AssertTrue(message = "Si c'est mensuel alors monthlyDay doit avoir une valeur")
public boolean isMonthlyDay() {
return type == null || !TaskType.MONTHLY.equals(type) || monthlyDay != 0;
return type == null
|| !TaskType.MONTHLY.equals(type)
|| (monthlyDay != null && monthlyDay != 0);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import jakarta.validation.UnexpectedTypeException;
import moneybuddy.fr.moneybuddy.dtos.ErrorResponse;
import moneybuddy.fr.moneybuddy.service.DiscordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
Expand All @@ -18,10 +20,13 @@
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartException;

@RestControllerAdvice
public class GlobalExceptionHandler {

private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

@Autowired private DiscordService discordService;

@ExceptionHandler(MoneyBuddyException.class)
Expand Down Expand Up @@ -120,8 +125,27 @@ public ResponseEntity<ErrorResponse> handleIndexOutOfBoundsException(
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
}

@ExceptionHandler(MultipartException.class)
public ResponseEntity<ErrorResponse> handleMultipartException(
MultipartException ex, WebRequest request) {
ErrorResponse errorResponse =
ErrorResponse.builder()
.timestamp(LocalDateTime.now())
.status(HttpStatus.BAD_REQUEST.value())
.error("Fichier invalide")
.message(
"Le fichier envoyé est invalide ou dépasse la taille maximale autorisée (10MB)")
.errorCode("MULTIPART_ERROR")
.path(request.getDescription(false).replace("uri=", ""))
.build();

return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
}

@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGenericException(Exception ex, WebRequest request) {
logger.error("Unhandled exception on {}", request.getDescription(false), ex);

ErrorResponse errorResponse =
ErrorResponse.builder()
.timestamp(LocalDateTime.now())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,13 @@ public class DiscordService {
@EventListener(ApplicationReadyEvent.class)
@Async
public void init() {
this.jda = JDABuilder.createDefault(token).build();
try {
this.jda = JDABuilder.createDefault(token).build();
} catch (Exception e) {
System.err.println(
"[DiscordService] Failed to initialize Discord bot (monitoring disabled): "
+ e.getMessage());
}
}

public void SendMessage(String text) {
Expand Down Expand Up @@ -75,6 +81,7 @@ public void sendNewAccountMessage(String email, SubAccount subAccount, Boolean i
}

public void sendErroMessage(MoneyBuddyException ex, WebRequest req) {
if (jda == null) return;
TextChannel channel = jda.getTextChannelById(monitoring_errors_channel);

Boolean error = Integer.toString(ex.getStatus().value()).startsWith("4");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,14 @@ public class IncomeService {
private final JwtService jwtService;

public void createTransactionForIncome(Income income) {
if (!income.getStatus().equals(IncomeStatus.ACCEPTED)) return;

Transaction transaction =
Transaction.builder()
.accountId(income.getAccountId())
.childId(income.getSubAccountIdChild())
.parentId(income.getSubAccountId())
.type(
income.getStatus().equals(IncomeStatus.ACCEPTED)
? TransactionType.CREDIT
: TransactionType.DEBIT)
.type(TransactionType.CREDIT)
.category(TransactionCategory.MONEY)
.amount(income.getAmount().toString())
.description(income.getTask().getDescription())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public Quiz updateQuiz(String quizId, UpdateQuizRequest req)
throws FileUploadException, JsonMappingException, JsonProcessingException {
Quiz quiz = getById(quizId);

quiz.setCorrectAnswerIndex(req.getCorrectAnswerIndex());
quiz.setCorrectAnswerIndex(req.getCorrectAnswerIndex());

quiz.setQuestion(Optional.ofNullable(req.getQuestion()).orElse(quiz.getQuestion()));
quiz.setResponse(Optional.ofNullable(req.getResponse()).orElse(quiz.getResponse()));
Expand Down
Loading
Loading