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> 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( new CommandDefinition(sql, new { Id = itemProgramadoId }, Tx, cancellationToken: ct)); return rows.ToList(); } public async Task GetByIdAsync(Guid id, CancellationToken ct = default) { const string sql = $"SELECT {Columns} FROM producoes_controle WHERE id = @Id"; return await Conn.QueryFirstOrDefaultAsync( new CommandDefinition(sql, new { Id = id }, Tx, cancellationToken: ct)); } public async Task 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(new CommandDefinition( sql, new { Id = itemProgramadoId, Data = data, Classificacao = (int)classificacao }, Tx, cancellationToken: ct)); } public async Task 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( new CommandDefinition(sql, new { Id = itemProgramadoId }, Tx, cancellationToken: ct)); } public Task ItemProgramadoExistsAsync(Guid itemProgramadoId, CancellationToken ct = default) => ExisteAsync("itens_programados", itemProgramadoId, ct); public Task ExecutorExistsAsync(Guid executorId, CancellationToken ct = default) => ExisteAsync("executores", executorId, ct); public Task EquipeExistsAsync(Guid equipeId, CancellationToken ct = default) => ExisteAsync("equipes", equipeId, ct); public async Task AddAsync(ProducaoControle p, IReadOnlyList 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 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> 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( new CommandDefinition(sql, new { Id = producaoId }, Tx, cancellationToken: ct)); return rows.ToList(); } public async Task 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 ContarPorExecutorAsync(Guid executorId, CancellationToken ct = default) { const string sql = "SELECT COUNT(*) FROM producoes_controle WHERE executor_id = @Id"; return await Conn.ExecuteScalarAsync( new CommandDefinition(sql, new { Id = executorId }, Tx, cancellationToken: ct)); } public Task FiscalExistsAsync(Guid fiscalId, CancellationToken ct = default) => ExisteAsync("agentes", fiscalId, ct); public async Task GetItemControleIdAsync(Guid itemProgramadoId, CancellationToken ct = default) { const string sql = "SELECT item_controle_id FROM itens_programados WHERE id = @Id"; return await Conn.ExecuteScalarAsync( new CommandDefinition(sql, new { Id = itemProgramadoId }, Tx, cancellationToken: ct)); } public async Task> 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(new CommandDefinition( sql, new { Id = itemProgramadoId, DataLimite = dataLimite }, Tx, cancellationToken: ct)); return rows.ToList(); } public async Task 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(new CommandDefinition( sql, new { Id = itemProgramadoId, Data = data }, Tx, cancellationToken: ct)); return count > 0; } public async Task> 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(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> 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(new CommandDefinition( sql, new { Id = producaoId }, Tx, cancellationToken: ct)); return rows.ToList(); } private async Task InserirEquipesAsync(Guid producaoId, IReadOnlyList 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 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(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 }; }