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

namespace SCM.Infrastructure.Persistence.Repositories;

public sealed class LinhaBaseRepository : ILinhaBaseRepository
{
    private readonly IUnitOfWork _uow;

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

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

    public async Task<IReadOnlyList<LinhaBasePonto>> GetByEapAsync(Guid eapId, CancellationToken ct = default)
    {
        const string sql = """
            SELECT id, eap_id, semana, data, percentual, origem
            FROM eap_linha_base_pontos WHERE eap_id = @Id ORDER BY semana
            """;
        var rows = await Conn.QueryAsync<LinhaBasePonto>(
            new CommandDefinition(sql, new { Id = eapId }, Tx, cancellationToken: ct));
        return rows.ToList();
    }

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

    public async Task ReplaceAsync(Guid eapId, IReadOnlyList<LinhaBasePonto> pontos, CancellationToken ct = default)
    {
        await Conn.ExecuteAsync(new CommandDefinition(
            "DELETE FROM eap_linha_base_pontos WHERE eap_id = @Id",
            new { Id = eapId }, Tx, cancellationToken: ct));

        const string sql = """
            INSERT INTO eap_linha_base_pontos (id, eap_id, semana, data, percentual, origem)
            VALUES (@Id, @EapId, @Semana, @Data, @Percentual, @Origem)
            """;
        foreach (var p in pontos)
            await Conn.ExecuteAsync(new CommandDefinition(sql, new
            {
                p.Id, p.EapId, p.Semana, p.Data, p.Percentual, p.Origem
            }, Tx, cancellationToken: ct));
    }

    public async Task<bool> DeletePontoAsync(Guid eapId, int semana, CancellationToken ct = default)
    {
        const string sql = "DELETE FROM eap_linha_base_pontos WHERE eap_id = @EapId AND semana = @Semana";
        var affected = await Conn.ExecuteAsync(new CommandDefinition(
            sql, new { EapId = eapId, Semana = semana }, Tx, cancellationToken: ct));
        return affected > 0;
    }
}