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 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( new CommandDefinition(sql, new { Id = folhaTarefaId }, Tx, cancellationToken: ct)); } public async Task> 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( new CommandDefinition(sql, new { Id = obraId }, Tx, cancellationToken: ct)); return rows.ToList(); } public async Task GetByIdAsync(Guid id, CancellationToken ct = default) { const string sql = $"SELECT {Columns} FROM fatores_produtividade WHERE id = @Id"; return await Conn.QueryFirstOrDefaultAsync( new CommandDefinition(sql, new { Id = id }, Tx, cancellationToken: ct)); } public async Task 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( new CommandDefinition(sql, new { Id = subAtividadePadraoId }, Tx, cancellationToken: ct)); } public async Task> 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( new CommandDefinition(sql, new { Id = subAtividadePadraoId }, Tx, cancellationToken: ct)); return rows.ToList(); } public async Task> 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( new CommandDefinition(sql, new { Id = fatorId }, Tx, cancellationToken: ct)); return rows.ToList(); } public async Task ReplaceDetalhesAsync(Guid fatorId, IReadOnlyList 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> 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 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(new CommandDefinition( sql, new { Codigo = codigo, ObraId = obraId, ExcludeId = excludeId }, Tx, cancellationToken: ct)); return count > 0; } public Task ObraExistsAsync(Guid obraId, CancellationToken ct = default) => ExisteAsync("obras", obraId, ct); public Task 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 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 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(new CommandDefinition( sql, new { De = unidadeDeId, Para = unidadeParaId }, Tx, cancellationToken: ct)); } public async Task 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( 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 ContarItensAssociadosAsync(Guid fatorId, CancellationToken ct = default) { return await Conn.ExecuteScalarAsync(new CommandDefinition( "SELECT COUNT(*) FROM itens_programados WHERE fator_produtividade_id = @Id", new { Id = fatorId }, Tx, cancellationToken: ct)); } public async Task> 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( new CommandDefinition(sql, new { Id = folhaTarefaId }, Tx, cancellationToken: ct)); return rows.ToList(); } public async Task> 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(new CommandDefinition( sql, new { Id = folhaTarefaId, Inicio = inicio, Fim = fim }, Tx, cancellationToken: ct)); return rows.ToList(); } public async Task 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(new CommandDefinition( sql, new { Id = folhaTarefaId, Data = data }, Tx, cancellationToken: ct)); } public async Task> 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( 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 ExisteAsync(string tabela, Guid id, CancellationToken ct) { var sql = $"SELECT COUNT(*) FROM {tabela} WHERE id = @Id"; var count = await Conn.ExecuteScalarAsync( 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 }; }