File size: 14,882 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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
using System.Data;
using Dapper;
using SCM.Application.Common;
using SCM.Domain.Controle;

namespace SCM.Infrastructure.Persistence.Repositories;

public sealed class FatorProdutividadeRepository : IFatorProdutividadeRepository
{
    private readonly IUnitOfWork _uow;

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

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

    private const string Columns = """
        id, obra_id, subatividade_padrao_id, codigo, descricao,
        meta, planejado, prod_aferido, unidade_medida_id
        """;

    public async Task<FtApuracao?> GetFtApuracaoAsync(Guid folhaTarefaId, CancellationToken ct = default)
    {
        const string sql = """
            SELECT id, equipe_id, data_inicial, periodo, status
            FROM folhas_tarefa WHERE id = @Id
            """;
        return await Conn.QueryFirstOrDefaultAsync<FtApuracao>(
            new CommandDefinition(sql, new { Id = folhaTarefaId }, Tx, cancellationToken: ct));
    }

    public async Task<IReadOnlyList<FatorProdutividade>> GetByObraAsync(Guid obraId, CancellationToken ct = default)
    {
        const string sql = $"SELECT {Columns} FROM fatores_produtividade WHERE obra_id = @Id ORDER BY codigo";
        var rows = await Conn.QueryAsync<FatorProdutividade>(
            new CommandDefinition(sql, new { Id = obraId }, Tx, cancellationToken: ct));
        return rows.ToList();
    }

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

    public async Task<FatorProdutividade?> GetBySubAtividadeAsync(Guid subAtividadePadraoId, CancellationToken ct = default)
    {
        // Legado escolhe o de mais detalhes casados (detalhes adiados) — aqui o mais recente da subativ.
        const string sql = $"""
            SELECT {Columns} FROM fatores_produtividade
            WHERE subatividade_padrao_id = @Id
            ORDER BY codigo LIMIT 1
            """;
        return await Conn.QueryFirstOrDefaultAsync<FatorProdutividade>(
            new CommandDefinition(sql, new { Id = subAtividadePadraoId }, Tx, cancellationToken: ct));
    }

    public async Task<IReadOnlyList<FatorProdutividade>> GetTodosBySubAtividadeAsync(Guid subAtividadePadraoId, CancellationToken ct = default)
    {
        const string sql = $"SELECT {Columns} FROM fatores_produtividade WHERE subatividade_padrao_id = @Id ORDER BY codigo";
        var rows = await Conn.QueryAsync<FatorProdutividade>(
            new CommandDefinition(sql, new { Id = subAtividadePadraoId }, Tx, cancellationToken: ct));
        return rows.ToList();
    }

    public async Task<IReadOnlyList<FatorDetalhe>> GetDetalhesAsync(Guid fatorId, CancellationToken ct = default)
    {
        const string sql = """
            SELECT id, fator_produtividade_id, caracteristica_id, operador, valor
            FROM fator_detalhes WHERE fator_produtividade_id = @Id
            """;
        var rows = await Conn.QueryAsync<FatorDetalhe>(
            new CommandDefinition(sql, new { Id = fatorId }, Tx, cancellationToken: ct));
        return rows.ToList();
    }

    public async Task ReplaceDetalhesAsync(Guid fatorId, IReadOnlyList<FatorDetalhe> detalhes, CancellationToken ct = default)
    {
        await Conn.ExecuteAsync(new CommandDefinition(
            "DELETE FROM fator_detalhes WHERE fator_produtividade_id = @Id",
            new { Id = fatorId }, Tx, cancellationToken: ct));

        const string sql = """
            INSERT INTO fator_detalhes (id, fator_produtividade_id, caracteristica_id, operador, valor)
            VALUES (@Id, @FatorProdutividadeId, @CaracteristicaId, @Operador, @Valor)
            """;
        foreach (var d in detalhes)
            await Conn.ExecuteAsync(new CommandDefinition(sql, new
            {
                d.Id, d.FatorProdutividadeId, d.CaracteristicaId, d.Operador, d.Valor
            }, Tx, cancellationToken: ct));
    }

    public async Task<IReadOnlyDictionary<Guid, string>> GetValoresCaracteristicasDoItemAsync(Guid itemProgramadoId, CancellationToken ct = default)
    {
        const string sql = """
            SELECT v.caracteristica_id, v.valor
            FROM caracteristica_valores_ic v
            JOIN itens_programados i ON i.item_controle_id = v.item_controle_id
            WHERE i.id = @Id
            """;
        var rows = await Conn.QueryAsync<(Guid CaracteristicaId, string Valor)>(
            new CommandDefinition(sql, new { Id = itemProgramadoId }, Tx, cancellationToken: ct));
        return rows.ToDictionary(r => r.CaracteristicaId, r => r.Valor);
    }

    public async Task<bool> CodigoExistsAsync(string codigo, Guid obraId, Guid? excludeId = null, CancellationToken ct = default)
    {
        const string sql = """
            SELECT COUNT(*) FROM fatores_produtividade
            WHERE codigo = @Codigo AND obra_id = @ObraId AND (@ExcludeId::uuid IS NULL OR id <> @ExcludeId)
            """;
        var count = await Conn.ExecuteScalarAsync<long>(new CommandDefinition(
            sql, new { Codigo = codigo, ObraId = obraId, ExcludeId = excludeId }, Tx, cancellationToken: ct));
        return count > 0;
    }

    public Task<bool> ObraExistsAsync(Guid obraId, CancellationToken ct = default)
        => ExisteAsync("obras", obraId, ct);

    public Task<bool> SubAtividadeExistsAsync(Guid subAtividadePadraoId, CancellationToken ct = default)
        => ExisteAsync("subativs_padrao", subAtividadePadraoId, ct);

    public async Task AddAsync(FatorProdutividade f, CancellationToken ct = default)
    {
        const string sql = """
            INSERT INTO fatores_produtividade
                (id, obra_id, subatividade_padrao_id, codigo, descricao, meta, planejado, prod_aferido, unidade_medida_id)
            VALUES
                (@Id, @ObraId, @SubAtividadePadraoId, @Codigo, @Descricao, @Meta, @Planejado, @ProdAferido, @UnidadeMedidaId)
            """;
        await Conn.ExecuteAsync(new CommandDefinition(sql, ToParameters(f), Tx, cancellationToken: ct));
    }

    public async Task UpdateAsync(FatorProdutividade f, CancellationToken ct = default)
    {
        const string sql = """
            UPDATE fatores_produtividade
               SET codigo = @Codigo, descricao = @Descricao, meta = @Meta,
                   planejado = @Planejado, prod_aferido = @ProdAferido
             WHERE id = @Id
            """;
        await Conn.ExecuteAsync(new CommandDefinition(sql, ToParameters(f), Tx, cancellationToken: ct));
    }

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

    public async Task<decimal?> GetFatorConversaoAsync(Guid unidadeDeId, Guid unidadeParaId, CancellationToken ct = default)
    {
        const string sql = """
            SELECT fator FROM conversoes_unidade_medida
            WHERE unidade_de_id = @De AND unidade_para_id = @Para
            """;
        return await Conn.ExecuteScalarAsync<decimal?>(new CommandDefinition(
            sql, new { De = unidadeDeId, Para = unidadeParaId }, Tx, cancellationToken: ct));
    }

    public async Task<ItemAssociacaoFator?> GetItemAssociacaoAsync(Guid itemProgramadoId, CancellationToken ct = default)
    {
        const string sql = """
            SELECT id, quantidade, subatividade_padrao_id AS sub_atividade_padrao_id
            FROM itens_programados WHERE id = @Id
            """;
        return await Conn.QueryFirstOrDefaultAsync<ItemAssociacaoFator>(
            new CommandDefinition(sql, new { Id = itemProgramadoId }, Tx, cancellationToken: ct));
    }

    public async Task AssociarItemAsync(Guid itemProgramadoId, Guid? fatorId, decimal hhPrev, CancellationToken ct = default)
    {
        const string sql = """
            UPDATE itens_programados
               SET fator_produtividade_id = @FatorId, hh_prev = @HhPrev
             WHERE id = @Id
            """;
        await Conn.ExecuteAsync(new CommandDefinition(
            sql, new { Id = itemProgramadoId, FatorId = fatorId, HhPrev = hhPrev }, Tx, cancellationToken: ct));
    }

    public async Task<int> ContarItensAssociadosAsync(Guid fatorId, CancellationToken ct = default)
    {
        return await Conn.ExecuteScalarAsync<int>(new CommandDefinition(
            "SELECT COUNT(*) FROM itens_programados WHERE fator_produtividade_id = @Id",
            new { Id = fatorId }, Tx, cancellationToken: ct));
    }

    public async Task<IReadOnlyList<ItemFtApuracao>> GetItensFtAsync(Guid folhaTarefaId, CancellationToken ct = default)
    {
        const string sql = """
            SELECT i.id AS item_programado_id, i.hh_prev, i.fator_produtividade_id
            FROM folha_tarefa_itens fti
            JOIN itens_programados i ON i.id = fti.item_programado_id
            WHERE fti.folha_tarefa_id = @Id
            """;
        var rows = await Conn.QueryAsync<ItemFtApuracao>(
            new CommandDefinition(sql, new { Id = folhaTarefaId }, Tx, cancellationToken: ct));
        return rows.ToList();
    }

    public async Task<IReadOnlyList<ProducaoDiaApuracao>> GetProducoesPeriodoAsync(
        Guid folhaTarefaId, DateOnly inicio, DateOnly fim, CancellationToken ct = default)
    {
        const string sql = """
            SELECT p.item_programado_id, p.data, p.qt_prevista, p.qt_executada, p.qt_executada_parcial
            FROM producoes_controle p
            JOIN folha_tarefa_itens fti ON fti.item_programado_id = p.item_programado_id
            WHERE fti.folha_tarefa_id = @Id AND p.data BETWEEN @Inicio AND @Fim
            ORDER BY p.data
            """;
        var rows = await Conn.QueryAsync<ProducaoDiaApuracao>(new CommandDefinition(
            sql, new { Id = folhaTarefaId, Inicio = inicio, Fim = fim }, Tx, cancellationToken: ct));
        return rows.ToList();
    }

    public async Task<HorasDiaApuracao> GetHorasDiaAsync(Guid folhaTarefaId, DateOnly data, CancellationToken ct = default)
    {
        // Produtivo = normais+extras das atividades; improdutivo = paradas (+extras paradas) dos motivos.
        const string sql = """
            SELECT
              COALESCE((SELECT SUM(afa.horas_normais + afa.horas_extras)
                 FROM apropriacoes_horas ah
                 JOIN apropriacao_funcionarios af ON af.apropriacao_horas_id = ah.id
                 JOIN apropriacao_funcionario_atividades afa ON afa.apropriacao_funcionario_id = af.id
                 WHERE ah.folha_tarefa_id = @Id AND ah.data = @Data), 0) AS hh_produtivo,
              COALESCE((SELECT SUM(afm.horas_paradas + afm.horas_extras_paradas)
                 FROM apropriacoes_horas ah
                 JOIN apropriacao_funcionarios af ON af.apropriacao_horas_id = ah.id
                 JOIN apropriacao_funcionario_motivos afm ON afm.apropriacao_funcionario_id = af.id
                 WHERE ah.folha_tarefa_id = @Id AND ah.data = @Data), 0) AS hh_improdutivo
            """;
        return await Conn.QueryFirstAsync<HorasDiaApuracao>(new CommandDefinition(
            sql, new { Id = folhaTarefaId, Data = data }, Tx, cancellationToken: ct));
    }

    public async Task<IReadOnlyList<DiaEquipeFp>> GetDiaEquipeFpAsync(Guid folhaTarefaId, CancellationToken ct = default)
    {
        const string sql = """
            SELECT id, folha_tarefa_id, equipe_id, item_programado_id, data,
                   hh_produtivo, hh_improdutivo, qt_executada, valor_indice
            FROM dia_equipe_fp WHERE folha_tarefa_id = @Id ORDER BY data, item_programado_id
            """;
        var rows = await Conn.QueryAsync<DiaEquipeFp>(
            new CommandDefinition(sql, new { Id = folhaTarefaId }, Tx, cancellationToken: ct));
        return rows.ToList();
    }

    public async Task AddDiaEquipeFpAsync(DiaEquipeFp d, CancellationToken ct = default)
    {
        const string sql = """
            INSERT INTO dia_equipe_fp
                (id, folha_tarefa_id, equipe_id, item_programado_id, data,
                 hh_produtivo, hh_improdutivo, qt_executada, valor_indice)
            VALUES
                (@Id, @FolhaTarefaId, @EquipeId, @ItemProgramadoId, @Data,
                 @HhProdutivo, @HhImprodutivo, @QtExecutada, @ValorIndice)
            """;
        await Conn.ExecuteAsync(new CommandDefinition(sql, new
        {
            d.Id, d.FolhaTarefaId, d.EquipeId, d.ItemProgramadoId, d.Data,
            d.HhProdutivo, d.HhImprodutivo, d.QtExecutada, d.ValorIndice
        }, Tx, cancellationToken: ct));
    }

    public async Task DeleteDiaEquipeFpByFtAsync(Guid folhaTarefaId, CancellationToken ct = default)
    {
        await Conn.ExecuteAsync(new CommandDefinition(
            "DELETE FROM dia_equipe_fp WHERE folha_tarefa_id = @Id",
            new { Id = folhaTarefaId }, Tx, cancellationToken: ct));
    }

    public async Task RecalcularProdAferidoAsync(Guid fatorId, CancellationToken ct = default)
    {
        // prod_aferido = Σ hh_produtivo / Σ qt_executada do histórico (hh_produtivo > 0) de FTs
        // finalizadas (status = 2) cujos itens usam o fator; qtExec total 0 → divisor 1.
        const string sql = """
            UPDATE fatores_produtividade f
               SET prod_aferido = COALESCE((
                   SELECT ROUND(SUM(d.hh_produtivo) /
                          CASE WHEN COALESCE(SUM(d.qt_executada), 0) = 0 THEN 1 ELSE SUM(d.qt_executada) END, 4)
                   FROM dia_equipe_fp d
                   JOIN itens_programados i ON i.id = d.item_programado_id
                   JOIN folhas_tarefa ft ON ft.id = d.folha_tarefa_id
                   WHERE i.fator_produtividade_id = f.id AND d.hh_produtivo > 0 AND ft.status = 2
               ), 0)
             WHERE f.id = @Id
            """;
        await Conn.ExecuteAsync(new CommandDefinition(sql, new { Id = fatorId }, 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(FatorProdutividade f) => new
    {
        f.Id, f.ObraId, f.SubAtividadePadraoId, f.Codigo, f.Descricao,
        f.Meta, f.Planejado, f.ProdAferido, f.UnidadeMedidaId
    };
}