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

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,11 @@ public ResponseEntity<PageResponse<TaskResponseDTO>> getMyTasks(
schema = @Schema(implementation = ErrorResponse.class))),
@ApiResponse(responseCode = "404", description = "Task not found",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = ErrorResponse.class)))
schema = @Schema(implementation = ErrorResponse.class))),
@ApiResponse(responseCode = "409",
description = "Conflict — the entity was modified by another request since it was last read "
+ "(stale version)",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class)))
})
@PutMapping("/{taskId}")
@PreAuthorize("hasAnyRole('ADMIN', 'ORG')")
Expand All @@ -152,7 +156,11 @@ public ResponseEntity<TaskResponseDTO> updateTask(@PathVariable Long taskId,
schema = @Schema(implementation = ErrorResponse.class))),
@ApiResponse(responseCode = "404", description = "Task or user not found",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = ErrorResponse.class)))
schema = @Schema(implementation = ErrorResponse.class))),
@ApiResponse(responseCode = "409",
description = "Conflict — the entity was modified by another request since it was last read "
+ "(stale version)",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class)))
})
@PatchMapping("/{taskId}/add-owner")
@PreAuthorize("hasRole('ADMIN')")
Expand All @@ -177,7 +185,11 @@ public ResponseEntity<TaskResponseDTO> addOwner(@PathVariable Long taskId,
schema = @Schema(implementation = ErrorResponse.class))),
@ApiResponse(responseCode = "404", description = "Task or user not found",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = ErrorResponse.class)))
schema = @Schema(implementation = ErrorResponse.class))),
@ApiResponse(responseCode = "409",
description = "Conflict — the entity was modified by another request since it was last read "
+ "(stale version)",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class)))
})
@PatchMapping("/{taskId}/remove-owner")
@PreAuthorize("hasRole('ADMIN')")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ public class TaskBody {
@Column(name = "updated_at")
private Instant updatedAt;

@Version
@Column(name = "version", nullable = false)
private Long version;

@OneToMany(
mappedBy = "task",
cascade = CascadeType.ALL,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;

@Schema(description = "DTO for adding task owner")
public record AddOwnerRequestDTO(
@Schema(
description = "Email address of the new task owner. The user must have ADMIN or ORG role",
example = "example@mail.com",
requiredMode = Schema.RequiredMode.REQUIRED) @NotBlank @Email String newOwnerEmail) {
requiredMode = Schema.RequiredMode.REQUIRED) @NotBlank @Email String newOwnerEmail,

@Schema(description = "Optimistic locking version; must be echoed back on updates",
requiredMode = Schema.RequiredMode.REQUIRED) @NotNull Long version) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;

@Schema(description = "DTO for removing task owner")
public record RemoveOwnerRequestDTO(
@Schema(
description = "Email address of the task owner.",
example = "example@mail.com",
requiredMode = Schema.RequiredMode.REQUIRED) @NotBlank @Email String ownerEmail) {
requiredMode = Schema.RequiredMode.REQUIRED) @NotBlank @Email String ownerEmail,

@Schema(description = "Optimistic locking version; must be echoed back on updates",
requiredMode = Schema.RequiredMode.REQUIRED) @NotNull Long version) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.List;

@Schema(description = "DTO for updating an already existing task")
Expand All @@ -21,5 +22,7 @@ public record UpdateTaskRequestDTO(
@Schema(
description = "File ids to be detached from task",
example = "[52]",
requiredMode = Schema.RequiredMode.NOT_REQUIRED) List<Long> removedFileIds) {
requiredMode = Schema.RequiredMode.NOT_REQUIRED) List<Long> removedFileIds,
@Schema(description = "Optimistic locking version; must be echoed back on updates",
requiredMode = Schema.RequiredMode.REQUIRED) @NotNull Long version) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,7 @@ public record TaskResponseDTO(

@Schema(
description = "Ids of task's current owners",
example = "[1,2,3]") Set<Long> ownerIds) {
example = "[1,2,3]") Set<Long> ownerIds,

@Schema(description = "Optimistic locking version; must be echoed back on updates") Long version) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.itasocialacademy.oitassist.task.exceptions;

import com.itasocialacademy.oitassist.core.enums.ErrorCode;
import com.itasocialacademy.oitassist.core.exceptions.BusinessException;

public class StaleTaskVersionException extends BusinessException {
public StaleTaskVersionException(Long taskId) {
super("Task with id %d has been modified by another user. ".formatted(taskId),
ErrorCode.ENTITY_VERSION_CONFLICT);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import com.itasocialacademy.oitassist.task.dto.request.RemoveOwnerRequestDTO;
import com.itasocialacademy.oitassist.task.dto.request.UpdateTaskRequestDTO;
import com.itasocialacademy.oitassist.task.dto.response.TaskResponseDTO;
import com.itasocialacademy.oitassist.task.exceptions.StaleTaskVersionException;
import com.itasocialacademy.oitassist.task.exceptions.TaskAccessRestrictedException;
import com.itasocialacademy.oitassist.task.exceptions.TaskNotFoundException;
import com.itasocialacademy.oitassist.task.mapper.TaskBodyMapper;
Expand All @@ -30,6 +31,7 @@
import com.itasocialacademy.oitassist.user.api.interfaces.UserFacade;
import com.itasocialacademy.oitassist.user.dao.enums.Role;
import com.itasocialacademy.oitassist.user.exceptions.UserNotFoundException;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -128,10 +130,12 @@ public TaskResponseDTO updateTask(Long taskId, UpdateTaskRequestDTO requestDTO)
.map(o -> o.getId().getOwnerId()).collect(Collectors.toSet()),
existingTask.getId());

checkTaskVersion(existingTask.getVersion(), requestDTO.version(), existingTask.getId());

Comment thread
solenuk marked this conversation as resolved.
existingTask.setTitle(requestDTO.title());
existingTask.setDescription(requestDTO.description());

TaskBody updatedTask = taskBodyRepository.save(existingTask);
TaskBody updatedTask = taskBodyRepository.saveAndFlush(existingTask);
log.debug("Updated Task: Id {}, Title - {}", updatedTask.getId(), updatedTask.getTitle());

Long currentUserId = securityFacade.getCurrentUserId()
Expand Down Expand Up @@ -161,6 +165,8 @@ public TaskResponseDTO addTaskOwner(Long taskId, AddOwnerRequestDTO addOwnerRequ
throw new ValidationException("Provided user is not ADMIN nor ORG", ErrorCode.COMMON_VALIDATION_FAILED);
}

checkTaskVersion(task.getVersion(), addOwnerRequest.version(), task.getId());

if (task.getOwners().stream()
.anyMatch(owner -> owner.getId().getOwnerId().equals(userDetails.id()))) {
return getResponse(task);
Expand All @@ -171,6 +177,7 @@ public TaskResponseDTO addTaskOwner(Long taskId, AddOwnerRequestDTO addOwnerRequ
.build();

task.addOwner(owner);
auditOwnersUpdate(task);

log.debug("User {} added to task`s {} owners", userDetails.id(), task.getId());

Expand All @@ -190,20 +197,24 @@ public TaskResponseDTO removeTaskOwner(Long taskId, RemoveOwnerRequestDTO remove
UserAuthDetails userDetails = userFacade.findByEmail(removeOwnerRequest.ownerEmail())
.orElseThrow(UserNotFoundException::new);

checkTaskVersion(task.getVersion(), removeOwnerRequest.version(), task.getId());

Optional<TaskOwner> toRemove = task.getOwners().stream()
.filter(o -> o.getId().getOwnerId().equals(userDetails.id())).findFirst();

if (toRemove.isPresent()) {
if (task.getOwners().size() == 1) {
throw new ValidationException(
"Cannot remove the last owner of a task",
ErrorCode.COMMON_VALIDATION_FAILED);
}
task.removeOwner(toRemove.get());
} else {
if (toRemove.isEmpty()) {
return getResponse(task);
}

if (task.getOwners().size() == 1) {
throw new ValidationException(
"Cannot remove the last owner of a task",
ErrorCode.COMMON_VALIDATION_FAILED);
}

task.removeOwner(toRemove.get());
auditOwnersUpdate(task);

log.debug("User {} removed from task`s {} owners", userDetails.id(), task.getId());

return getResponse(task);
Expand Down Expand Up @@ -333,4 +344,16 @@ private String getNormalizedSearch(String search) {
.replace("%", "\\%")
.replace("_", "\\_");
}

private void checkTaskVersion(Long actualVersion, Long providedVersion, Long taskId) {
if (!Objects.equals(actualVersion, providedVersion)) {
throw new StaleTaskVersionException(taskId);
}
}

private void auditOwnersUpdate(TaskBody taskBody) {
taskBody.setUpdatedAt(Instant.now());
taskBody.setUpdatedBy(securityFacade.getCurrentUserId().orElseThrow(UserNotFoundException::new));
taskBodyRepository.saveAndFlush(taskBody);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,11 @@ public ResponseEntity<List<LinkedToursResponseDTO>> getLinkedTours(@PathVariable
schema = @Schema(implementation = ErrorResponse.class))),
@ApiResponse(responseCode = "404", description = "Task assignment not found",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = ErrorResponse.class)))
schema = @Schema(implementation = ErrorResponse.class))),
@ApiResponse(responseCode = "409",
description = "Conflict — the entity was modified by another request since it was last read "
+ "(stale version)",
content = @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class)))
})
@PatchMapping("/task-assignments/{assignmentId}")
@PreAuthorize("hasAnyRole('ADMIN', 'ORG')")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,8 @@ public class TaskAssignment {
@LastModifiedDate
@Column(name = "updated_at")
private Instant updatedAt;

@Version
@Column(name = "version", nullable = false)
private Long version;
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;

@Schema(description = "DTO for updating an existing task assignment")
public record UpdateTaskAssignmentRequestDTO(
Expand All @@ -20,5 +21,8 @@ public record UpdateTaskAssignmentRequestDTO(

@Schema(
description = "Requirements and constraints for submitted files",
requiredMode = Schema.RequiredMode.NOT_REQUIRED) @Valid TaskRequirementsRequestDTO requirements) {
requiredMode = Schema.RequiredMode.NOT_REQUIRED) @Valid TaskRequirementsRequestDTO requirements,

@Schema(description = "Optimistic locking version; must be echoed back on updates",
requiredMode = Schema.RequiredMode.REQUIRED) @NotNull Long version) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,7 @@ public record DetailedTaskAssignmentResponseDTO(

@Schema(
description = "Id of the user who created this assignment",
example = "3") Long createdBy) {
example = "3") Long createdBy,

@Schema(description = "Optimistic locking version; must be echoed back on updates") Long version) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,7 @@ public record TaskAssignmentResponseDTO(

@Schema(
description = "Id of the user who created this assignment",
example = "3") Long createdBy) {
example = "3") Long createdBy,

@Schema(description = "Optimistic locking version; must be echoed back on updates") Long version) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.itasocialacademy.oitassist.taskassignment.exceptions;

import com.itasocialacademy.oitassist.core.enums.ErrorCode;
import com.itasocialacademy.oitassist.core.exceptions.BusinessException;

public class StaleAssignmentVersionException extends BusinessException {
public StaleAssignmentVersionException(Long assignmentId) {
super("Assignment with id %d has been modified by another user.".formatted(assignmentId),
ErrorCode.ENTITY_VERSION_CONFLICT);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import com.itasocialacademy.oitassist.taskassignment.dto.response.DetailedTaskAssignmentResponseDTO;
import com.itasocialacademy.oitassist.taskassignment.dto.response.LinkedToursResponseDTO;
import com.itasocialacademy.oitassist.taskassignment.dto.response.TaskAssignmentResponseDTO;
import com.itasocialacademy.oitassist.taskassignment.exceptions.StaleAssignmentVersionException;
import com.itasocialacademy.oitassist.taskassignment.exceptions.TaskAlreadyAssignedException;
import com.itasocialacademy.oitassist.taskassignment.exceptions.TaskAssignmentNotFoundException;
import com.itasocialacademy.oitassist.taskassignment.mapper.TaskAssignmentMapper;
Expand All @@ -35,10 +36,7 @@
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.*;

@Service
@Slf4j
Expand Down Expand Up @@ -137,6 +135,7 @@ public DetailedTaskAssignmentResponseDTO updateTaskAssignment(Long taskAssignmen
TourDetail tour = competitionFacade.findTourById(assignment.getTourId()).orElseThrow(
() -> new TourNotFoundException(assignment.getTourId()));

checkAssignmentVersion(assignment.getVersion(), request.version(), assignment.getId());
validateTourStatus(tour, "Cannot update task assignment.");

if (request.visibility() != null) {
Expand Down Expand Up @@ -278,4 +277,10 @@ private void checkAdminOrOrg() {
throw new AuthorizationException("You do not have permission to this operation", ErrorCode.ACCESS_DENIED);
}
}

public void checkAssignmentVersion(Long actualVersion, Long expectedVersion, Long assignmentId) {
if (!Objects.equals(actualVersion, expectedVersion)) {
throw new StaleAssignmentVersionException(assignmentId);
}
}
}
1 change: 1 addition & 0 deletions src/main/resources/db/changelog/db.changelog-master.xml
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,5 @@
<include file="/db/changelog/logs/2026-08-04-ch-create-task-owners-table-Murashko.xml"/>
<include file="/db/changelog/logs/2026-08-13-ch-add-news-updated-at-Rakuta.xml"/>
<include file="/db/changelog/logs/2026-08-11-ch-add-version-to-competitions-Pampukha.xml"/>
<include file="/db/changelog/logs/2026-08-26-ch-add-version-to-task-bodies-and-task-assignments-Selianyk.xml"/>
</databaseChangeLog>
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
https://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd">

<changeSet id="add-version-to-task-bodies" author="Ihor Selianyk">
<addColumn tableName="task_bodies">
<column name="version" type="BIGINT" defaultValueNumeric="0">
<constraints nullable="false"/>
</column>
</addColumn>
</changeSet>

<changeSet id="add-version-to-task-assignments" author="Ihor Selianyk">
<addColumn tableName="task_assignments">
<column name="version" type="BIGINT" defaultValueNumeric="0">
<constraints nullable="false"/>
</column>
</addColumn>
</changeSet>
</databaseChangeLog>
Loading
Loading