File size: 12,220 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
using System.Data;
using Dapper;
using SCM.Application.Common;
using SCM.Domain.Controle;

namespace SCM.Infrastructure.Persistence.Repositories;

public sealed class ProducaoControleRepository : IProducaoControleRepository
{
    private readonly IUnitOfWork _uow;

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

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

    private const string Columns = """
        id, item_programado_id, data, data_cadastro, classificacao,
        qt_prevista, qt_executada, qt_executada_parcial, avanco,
        executor_id, motivo_reapresentacao, tipo_lib_cq, data_lib_cq, fiscal_cq_id
        """;

    public async Task<IReadOnlyList<ProducaoControle>> GetByItemProgramadoAsync(Guid itemProgramadoId, CancellationToken ct = default)
    {
        const string sql = $"SELECT {Columns} FROM producoes_controle WHERE item_programado_id = @Id ORDER BY data, classificacao";
        var rows = await Conn.QueryAsync<ProducaoControle>(
            new CommandDefinition(sql, new { Id = itemProgramadoId }, Tx, cancellationToken: ct));
        return rows.ToList();
    }

    public async Task<ProducaoControle?> GetByIdAsync(Guid id, CancellationToken ct = default)
    {
        const string sql = $"SELECT {Columns} FROM producoes_controle WHERE id = @Id";
        return await Conn.QueryFirstOrDefaultAsync<ProducaoControle>(
            new CommandDefinition(sql, new { Id = id }, Tx, cancellationToken: ct));
    }

    public async Task<ProducaoControle?> GetPorChaveAsync(
        Guid itemProgramadoId, DateOnly data, ClassificacaoProducao classificacao, CancellationToken ct = default)
    {
        const string sql = $"""
            SELECT {Columns} FROM producoes_controle
            WHERE item_programado_id = @Id AND data = @Data AND classificacao = @Classificacao
            """;
        return await Conn.QueryFirstOrDefaultAsync<ProducaoControle>(new CommandDefinition(
            sql, new { Id = itemProgramadoId, Data = data, Classificacao = (int)classificacao }, Tx, cancellationToken: ct));
    }

    public async Task<ProducaoControle?> GetMaisRecenteNormalAsync(Guid itemProgramadoId, CancellationToken ct = default)
    {
        const string sql = $"""
            SELECT {Columns} FROM producoes_controle
            WHERE item_programado_id = @Id AND classificacao = 0
            ORDER BY data DESC LIMIT 1
            """;
        return await Conn.QueryFirstOrDefaultAsync<ProducaoControle>(
            new CommandDefinition(sql, new { Id = itemProgramadoId }, Tx, cancellationToken: ct));
    }

    public Task<bool> ItemProgramadoExistsAsync(Guid itemProgramadoId, CancellationToken ct = default)
        => ExisteAsync("itens_programados", itemProgramadoId, ct);

    public Task<bool> ExecutorExistsAsync(Guid executorId, CancellationToken ct = default)
        => ExisteAsync("executores", executorId, ct);

    public Task<bool> EquipeExistsAsync(Guid equipeId, CancellationToken ct = default)
        => ExisteAsync("equipes", equipeId, ct);

    public async Task AddAsync(ProducaoControle p, IReadOnlyList<ProducaoControleEquipe> equipes, CancellationToken ct = default)
    {
        const string sql = """
            INSERT INTO producoes_controle
                (id, item_programado_id, data, data_cadastro, classificacao,
                 qt_prevista, qt_executada, qt_executada_parcial, avanco,
                 executor_id, motivo_reapresentacao, tipo_lib_cq, data_lib_cq, fiscal_cq_id)
            VALUES
                (@Id, @ItemProgramadoId, @Data, @DataCadastro, @Classificacao,
                 @QtPrevista, @QtExecutada, @QtExecutadaParcial, @Avanco,
                 @ExecutorId, @MotivoReapresentacao, @TipoLibCq, @DataLibCq, @FiscalCqId)
            """;
        await Conn.ExecuteAsync(new CommandDefinition(sql, ToParameters(p), Tx, cancellationToken: ct));
        await InserirEquipesAsync(p.Id, equipes, ct);
    }

    public async Task UpdateComEquipesAsync(ProducaoControle p, IReadOnlyList<ProducaoControleEquipe> equipes, CancellationToken ct = default)
    {
        const string sql = """
            UPDATE producoes_controle
               SET qt_prevista = @QtPrevista, qt_executada = @QtExecutada,
                   qt_executada_parcial = @QtExecutadaParcial, avanco = @Avanco,
                   executor_id = @ExecutorId, tipo_lib_cq = @TipoLibCq,
                   data_lib_cq = @DataLibCq, fiscal_cq_id = @FiscalCqId
             WHERE id = @Id
            """;
        await Conn.ExecuteAsync(new CommandDefinition(sql, ToParameters(p), Tx, cancellationToken: ct));

        await Conn.ExecuteAsync(new CommandDefinition(
            "DELETE FROM producao_controle_equipes WHERE producao_controle_id = @Id",
            new { p.Id }, Tx, cancellationToken: ct));
        await InserirEquipesAsync(p.Id, equipes, ct);
    }

    public async Task<IReadOnlyList<ProducaoControleEquipe>> GetEquipesAsync(Guid producaoId, CancellationToken ct = default)
    {
        const string sql = """
            SELECT id, producao_controle_id, equipe_id, quantidade_exec, porcentagem_exec
            FROM producao_controle_equipes WHERE producao_controle_id = @Id
            """;
        var rows = await Conn.QueryAsync<ProducaoControleEquipe>(
            new CommandDefinition(sql, new { Id = producaoId }, Tx, cancellationToken: ct));
        return rows.ToList();
    }

    public async Task<bool> DeleteAsync(Guid id, CancellationToken ct = default)
    {
        await Conn.ExecuteAsync(new CommandDefinition(
            "DELETE FROM producao_controle_equipes WHERE producao_controle_id = @Id",
            new { Id = id }, Tx, cancellationToken: ct));
        var affected = await Conn.ExecuteAsync(new CommandDefinition(
            "DELETE FROM producoes_controle WHERE id = @Id", new { Id = id }, Tx, cancellationToken: ct));
        return affected > 0;
    }

    public async Task<int> ContarPorExecutorAsync(Guid executorId, CancellationToken ct = default)
    {
        const string sql = "SELECT COUNT(*) FROM producoes_controle WHERE executor_id = @Id";
        return await Conn.ExecuteScalarAsync<int>(
            new CommandDefinition(sql, new { Id = executorId }, Tx, cancellationToken: ct));
    }

    public Task<bool> FiscalExistsAsync(Guid fiscalId, CancellationToken ct = default)
        => ExisteAsync("agentes", fiscalId, ct);

    public async Task<Guid?> GetItemControleIdAsync(Guid itemProgramadoId, CancellationToken ct = default)
    {
        const string sql = "SELECT item_controle_id FROM itens_programados WHERE id = @Id";
        return await Conn.ExecuteScalarAsync<Guid?>(
            new CommandDefinition(sql, new { Id = itemProgramadoId }, Tx, cancellationToken: ct));
    }

    public async Task<IReadOnlyList<ProducaoControle>> GetAnterioresPendentesAsync(
        Guid itemProgramadoId, DateOnly dataLimite, CancellationToken ct = default)
    {
        const string sql = $"""
            SELECT {Columns} FROM producoes_controle
            WHERE item_programado_id = @Id AND data < @DataLimite AND tipo_lib_cq IS NULL
            ORDER BY data
            """;
        var rows = await Conn.QueryAsync<ProducaoControle>(new CommandDefinition(
            sql, new { Id = itemProgramadoId, DataLimite = dataLimite }, Tx, cancellationToken: ct));
        return rows.ToList();
    }

    public async Task<bool> ExistePosteriorLiberadaAsync(Guid itemProgramadoId, DateOnly data, CancellationToken ct = default)
    {
        const string sql = """
            SELECT COUNT(*) FROM producoes_controle
            WHERE item_programado_id = @Id AND data > @Data AND tipo_lib_cq IN ('I','A','NA','CP')
            """;
        var count = await Conn.ExecuteScalarAsync<long>(new CommandDefinition(
            sql, new { Id = itemProgramadoId, Data = data }, Tx, cancellationToken: ct));
        return count > 0;
    }

    public async Task<IReadOnlyList<ProducaoControle>> GetConformePosterioresACascatearAsync(
        Guid itemProgramadoId, DateOnly dataLimite, CancellationToken ct = default)
    {
        // 'CP' anteriores marcados por esta liberação: depois da liberação explícita (I/A/NA)
        // imediatamente anterior (se houver) e antes de @DataLimite.
        const string sql = $"""
            SELECT {Columns} FROM producoes_controle
            WHERE item_programado_id = @Id AND tipo_lib_cq = 'CP' AND data < @DataLimite
              AND data > COALESCE((
                    SELECT MAX(data) FROM producoes_controle
                    WHERE item_programado_id = @Id AND tipo_lib_cq IN ('I','A','NA') AND data < @DataLimite
                  ), DATE '0001-01-01')
            ORDER BY data
            """;
        var rows = await Conn.QueryAsync<ProducaoControle>(new CommandDefinition(
            sql, new { Id = itemProgramadoId, DataLimite = dataLimite }, Tx, cancellationToken: ct));
        return rows.ToList();
    }

    public async Task UpdateLiberacaoCqAsync(ProducaoControle p, CancellationToken ct = default)
    {
        const string sql = """
            UPDATE producoes_controle
               SET tipo_lib_cq = @TipoLibCq, data_lib_cq = @DataLibCq, fiscal_cq_id = @FiscalCqId
             WHERE id = @Id
            """;
        await Conn.ExecuteAsync(new CommandDefinition(
            sql, new { p.Id, p.TipoLibCq, p.DataLibCq, p.FiscalCqId }, Tx, cancellationToken: ct));
    }

    public async Task AddEstornoAsync(ProducaoEstorno e, CancellationToken ct = default)
    {
        const string sql = """
            INSERT INTO producao_estornos
                (id, producao_controle_id, item_programado_id, tipo_lib_cq_anterior,
                 data_lib_cq_anterior, fiscal_cq_id_anterior, data_estorno)
            VALUES
                (@Id, @ProducaoControleId, @ItemProgramadoId, @TipoLibCqAnterior,
                 @DataLibCqAnterior, @FiscalCqIdAnterior, @DataEstorno)
            """;
        await Conn.ExecuteAsync(new CommandDefinition(sql, new
        {
            e.Id, e.ProducaoControleId, e.ItemProgramadoId, e.TipoLibCqAnterior,
            e.DataLibCqAnterior, e.FiscalCqIdAnterior, e.DataEstorno
        }, Tx, cancellationToken: ct));
    }

    public async Task<IReadOnlyList<ProducaoEstorno>> GetEstornosAsync(Guid producaoId, CancellationToken ct = default)
    {
        const string sql = """
            SELECT id, producao_controle_id, item_programado_id, tipo_lib_cq_anterior,
                   data_lib_cq_anterior, fiscal_cq_id_anterior, data_estorno
            FROM producao_estornos WHERE producao_controle_id = @Id ORDER BY data_estorno
            """;
        var rows = await Conn.QueryAsync<ProducaoEstorno>(new CommandDefinition(
            sql, new { Id = producaoId }, Tx, cancellationToken: ct));
        return rows.ToList();
    }

    private async Task InserirEquipesAsync(Guid producaoId, IReadOnlyList<ProducaoControleEquipe> equipes, CancellationToken ct)
    {
        const string sql = """
            INSERT INTO producao_controle_equipes (id, producao_controle_id, equipe_id, quantidade_exec, porcentagem_exec)
            VALUES (@Id, @ProducaoControleId, @EquipeId, @QuantidadeExec, @PorcentagemExec)
            """;
        foreach (var e in equipes)
            await Conn.ExecuteAsync(new CommandDefinition(sql, new
            {
                e.Id, ProducaoControleId = producaoId, e.EquipeId, e.QuantidadeExec, e.PorcentagemExec
            }, Tx, cancellationToken: ct));
    }

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

    private static object ToParameters(ProducaoControle p) => new
    {
        p.Id, p.ItemProgramadoId, p.Data, p.DataCadastro, Classificacao = (int)p.Classificacao,
        p.QtPrevista, p.QtExecutada, p.QtExecutadaParcial, p.Avanco,
        p.ExecutorId, p.MotivoReapresentacao, p.TipoLibCq, p.DataLibCq, p.FiscalCqId
    };
}