File size: 2,543 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
using System.Data;
using Dapper;
using SCM.Application.Common;
using SCM.Domain.Medicao;

namespace SCM.Infrastructure.Persistence.Repositories;

public sealed class CriterioEapItemRepository : ICriterioEapItemRepository
{
    private readonly IUnitOfWork _uow;

    public CriterioEapItemRepository(IUnitOfWork uow) => _uow = uow;

    private IDbConnection Conn => _uow.Connection;
    private IDbTransaction? Tx => _uow.CurrentTransaction;

    public async Task<IReadOnlyList<CriterioEapItem>> GetByCriterioAsync(Guid criterioEapId, CancellationToken ct = default)
    {
        const string sql = """
            SELECT id, criterio_eap_id, sub_atividade_padrao_id, percentual
            FROM criterio_eap_itens WHERE criterio_eap_id = @Id ORDER BY percentual DESC
            """;
        var rows = await Conn.QueryAsync<CriterioEapItem>(
            new CommandDefinition(sql, new { Id = criterioEapId }, Tx, cancellationToken: ct));
        return rows.ToList();
    }

    public async Task<bool> CriterioExistsAsync(Guid criterioEapId, CancellationToken ct = default)
    {
        const string sql = "SELECT COUNT(*) FROM criterios_eap WHERE id = @Id";
        var count = await Conn.ExecuteScalarAsync<long>(
            new CommandDefinition(sql, new { Id = criterioEapId }, Tx, cancellationToken: ct));
        return count > 0;
    }

    public async Task<bool> SubAtividadeExistsAsync(Guid subAtividadePadraoId, CancellationToken ct = default)
    {
        const string sql = "SELECT COUNT(*) FROM subativs_padrao WHERE id = @Id";
        var count = await Conn.ExecuteScalarAsync<long>(
            new CommandDefinition(sql, new { Id = subAtividadePadraoId }, Tx, cancellationToken: ct));
        return count > 0;
    }

    public async Task ReplaceAsync(Guid criterioEapId, IReadOnlyList<CriterioEapItem> itens, CancellationToken ct = default)
    {
        await Conn.ExecuteAsync(new CommandDefinition(
            "DELETE FROM criterio_eap_itens WHERE criterio_eap_id = @Id",
            new { Id = criterioEapId }, Tx, cancellationToken: ct));

        const string sql = """
            INSERT INTO criterio_eap_itens (id, criterio_eap_id, sub_atividade_padrao_id, percentual)
            VALUES (@Id, @CriterioEapId, @SubAtividadePadraoId, @Percentual)
            """;
        foreach (var i in itens)
            await Conn.ExecuteAsync(new CommandDefinition(sql, new
            {
                i.Id, i.CriterioEapId, i.SubAtividadePadraoId, i.Percentual
            }, Tx, cancellationToken: ct));
    }
}