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

namespace SCM.Infrastructure.Persistence.Repositories;

public sealed class FaturamentoRepository : IFaturamentoRepository
{
    private readonly IUnitOfWork _uow;

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

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

    public async Task<(Guid ObraId, decimal ValorContrato)?> GetContratoAsync(Guid contratoId, CancellationToken ct = default)
    {
        const string sql = "SELECT obra_id, valor_contrato FROM contratos WHERE id = @Id";
        var row = await Conn.QueryFirstOrDefaultAsync<(Guid ObraId, decimal ValorContrato)?>(
            new CommandDefinition(sql, new { Id = contratoId }, Tx, cancellationToken: ct));
        return row;
    }

    public async Task<IReadOnlyList<LinhaFaturamento>> GetLinhasAsync(Guid obraId, CancellationToken ct = default)
    {
        // Uma linha por planejamento da EAP: percentual do item do critério + base física por
        // tipo ('F' = qt_feed, 'J' = qt_projeto_executivo, 'P' usa o acumulado como %).
        const string sql = """
            SELECT e.id AS eap_id, e.codigo AS eap_codigo,
                   COALESCE(e.criterio_tipo_calculo, 'F') AS tipo_calculo,
                   ci.percentual AS percentual_item,
                   CASE COALESCE(e.criterio_tipo_calculo, 'F')
                        WHEN 'J' THEN p.qt_projeto_executivo
                        ELSE p.qt_feed
                   END AS qt_base,
                   e.acumulado
            FROM eaps e
            JOIN eap_criterio_planejamentos p ON p.eap_id = e.id
            JOIN criterio_eap_itens ci ON ci.id = p.criterio_eap_item_id
            WHERE e.obra_id = @Id AND e.criterio_eap_id IS NOT NULL
            ORDER BY e.codigo, ci.percentual DESC
            """;
        var rows = await Conn.QueryAsync<LinhaFaturamento>(
            new CommandDefinition(sql, new { Id = obraId }, Tx, cancellationToken: ct));
        return rows.ToList();
    }
}