View Javadoc
1   package fr.tiogars.inception.domains.domaintemplate.services;
2   
3   import java.io.IOException;
4   import java.util.List;
5   import java.util.Optional;
6   
7   import org.springframework.stereotype.Service;
8   import org.springframework.transaction.annotation.Transactional;
9   
10  import fr.tiogars.inception.domains.domaintemplate.models.DomainTemplate;
11  import fr.tiogars.inception.domains.domaintemplate.repositories.DomainTemplateRepository;
12  
13  /** Generates a printable PDF for selected active DomainTemplates. */
14  @Service
15  public class DomainTemplatesPrintSelectedService {
16  
17      private final DomainTemplateRepository repository;
18      private final DomainTemplatePdfRenderer renderer;
19  
20      public DomainTemplatesPrintSelectedService(DomainTemplateRepository repository, DomainTemplatePdfRenderer renderer) {
21          this.repository = repository;
22          this.renderer = renderer;
23      }
24  
25      /**
26       * Prints a selection ordered by code without duplicating records.
27       *
28       * @param ids selected persistent identifiers
29       * @return PDF bytes, or empty if any selected record was not found
30       * @throws IOException when the PDF cannot be generated
31       */
32      @Transactional(readOnly = true)
33      public Optional<byte[]> printSelected(List<Long> ids) throws IOException {
34          if (ids.isEmpty()) {
35              throw new IllegalArgumentException("Select at least one DomainTemplate to print.");
36          }
37          List<Long> uniqueIds = ids.stream().distinct().toList();
38          List<DomainTemplate> templates = repository.findAllByIdInOrderByCodeAsc(uniqueIds).stream()
39                  .map(DomainTemplateFindAllService::toRecord)
40                  .toList();
41          if (templates.size() != uniqueIds.size()) {
42              return Optional.empty();
43          }
44          return Optional.of(renderer.render("Selected DomainTemplates", templates));
45      }
46  }