File size: 3,634 Bytes
de8b914
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using SCM.Application.Common;
using SCM.Application.Controle.Dtos;
using SCM.Domain.Controle;
using SCM.Shared.Exceptions;

namespace SCM.Application.Controle;

public sealed class ExecutorService : IExecutorService
{
    private readonly IExecutorRepository _repository;
    private readonly IProducaoControleRepository _producaoRepository;
    private readonly IUnitOfWork _unitOfWork;

    public ExecutorService(IExecutorRepository repository, IProducaoControleRepository producaoRepository, IUnitOfWork unitOfWork)
    {
        _repository = repository;
        _producaoRepository = producaoRepository;
        _unitOfWork = unitOfWork;
    }

    public async Task<IReadOnlyList<ExecutorResponse>> GetByObraAsync(Guid obraId, CancellationToken ct = default)
    {
        var itens = await _repository.GetByObraAsync(obraId, ct);
        return itens.Select(ToResponse).ToList();
    }

    public async Task<ExecutorResponse> GetByIdAsync(Guid id, CancellationToken ct = default)
    {
        var executor = await _repository.GetByIdAsync(id, ct)
            ?? throw new NotFoundException($"Executor {id} não encontrado.");
        return ToResponse(executor);
    }

    public async Task<ExecutorResponse> CreateAsync(CreateExecutorRequest request, CancellationToken ct = default)
    {
        if (!await _repository.ObraExistsAsync(request.ObraId, ct))
            throw new NotFoundException($"Obra {request.ObraId} não encontrada.");

        var executor = Executor.Create(request.ObraId, request.Codigo, request.Descricao);
        await GarantirCodigoUnicoAsync(executor.Codigo, executor.ObraId, null, ct);

        await ExecuteInTransactionAsync(() => _repository.AddAsync(executor, ct));
        return ToResponse(executor);
    }

    public async Task<ExecutorResponse> UpdateAsync(Guid id, UpdateExecutorRequest request, CancellationToken ct = default)
    {
        var executor = await _repository.GetByIdAsync(id, ct)
            ?? throw new NotFoundException($"Executor {id} não encontrado.");

        executor.Atualizar(request.Codigo, request.Descricao);
        await GarantirCodigoUnicoAsync(executor.Codigo, executor.ObraId, id, ct);

        await ExecuteInTransactionAsync(() => _repository.UpdateAsync(executor, ct));
        return ToResponse(executor);
    }

    public async Task DeleteAsync(Guid id, CancellationToken ct = default)
    {
        var executor = await _repository.GetByIdAsync(id, ct)
            ?? throw new NotFoundException($"Executor {id} não encontrado.");

        // Trava ativada na fatia 18: executor com produções lançadas não pode ser excluído.
        if (await _producaoRepository.ContarPorExecutorAsync(id, ct) > 0)
            throw new ConflictException("Não é possível excluir: o executor possui produções lançadas.");

        await ExecuteInTransactionAsync(() => _repository.DeleteAsync(executor.Id, ct));
    }

    private async Task GarantirCodigoUnicoAsync(string codigo, Guid obraId, Guid? excludeId, CancellationToken ct)
    {
        if (await _repository.CodigoExistsAsync(codigo, obraId, excludeId, ct))
            throw new ConflictException($"Já existe um executor com o código '{codigo}' nesta obra.");
    }

    private static ExecutorResponse ToResponse(Executor e) => new(e.Id, e.ObraId, e.Codigo, e.Descricao);

    private async Task ExecuteInTransactionAsync(Func<Task> action)
    {
        _unitOfWork.BeginTransaction();
        try
        {
            await action();
            _unitOfWork.Commit();
        }
        catch
        {
            _unitOfWork.Rollback();
            throw;
        }
    }
}