View Javadoc
1   package fr.tiogars.chat.domains.task.services;
2   
3   import java.util.List;
4   import fr.tiogars.chat.domains.task.entities.TaskEntity;
5   import fr.tiogars.chat.domains.tag.repositories.TagRepository;
6   import fr.tiogars.chat.domains.nomenclature.repositories.NomenclatureRepository;
7   import org.springframework.http.HttpStatus;
8   import org.springframework.stereotype.Component;
9   import org.springframework.web.server.ResponseStatusException;
10  
11  @Component
12  public class TaskReferences {
13      private final TagRepository tags;
14      private final NomenclatureRepository nomenclatures;
15  
16      public TaskReferences(TagRepository tags, NomenclatureRepository nomenclatures) {
17          this.tags = tags;
18          this.nomenclatures = nomenclatures;
19      }
20  
21      public void apply(TaskEntity entity, List<Long> tagIds, Long nomenclatureId) {
22          // Lock in a consistent order with taxonomy mutations to prevent reference/deletion races.
23          nomenclatures.lockForest();
24          var category = nomenclatureId == null ? null : nomenclatures.findById(nomenclatureId)
25                  .orElseThrow(() -> invalid("Nomenclature does not exist."));
26          var selectedTags = tagIds.stream().distinct().sorted()
27                  .map(id -> tags.lockById(id).orElseThrow(() -> invalid("Tag does not exist: " + id))).toList();
28          entity.references(selectedTags, category);
29      }
30  
31      private static ResponseStatusException invalid(String message) {
32          return new ResponseStatusException(HttpStatus.BAD_REQUEST, message);
33      }
34  }