File size: 8,623 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
using System.Data;
using Dapper;
using SCM.Application.Common;
using SCM.Domain.Planejamento;

namespace SCM.Infrastructure.Persistence.Repositories;

public sealed class FolhaTarefaRepository : IFolhaTarefaRepository
{
    private readonly IUnitOfWork _uow;

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

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

    private const string Columns = """
        id, contrato_id, equipe_id, supervisor_id, codigo, descricao, observacao,
        data_inicial, periodo, data_final_prox_periodo, numero_horas,
        semana_contrato_num, semana_anual, tipo, status, fechada,
        revisao, data_fechamento, codigo_equipe_congelado, data_criacao
        """;

    public async Task<IReadOnlyList<FolhaTarefa>> GetByContratoAsync(Guid contratoId, CancellationToken ct = default)
    {
        const string sql = $"SELECT {Columns} FROM folhas_tarefa WHERE contrato_id = @ContratoId ORDER BY codigo";
        var rows = await Conn.QueryAsync<FolhaTarefa>(
            new CommandDefinition(sql, new { ContratoId = contratoId }, Tx, cancellationToken: ct));
        return rows.ToList();
    }

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

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

    public async Task<(bool Existe, DateOnly? DataInicio)> GetContratoDataInicioAsync(Guid contratoId, CancellationToken ct = default)
    {
        const string sql = "SELECT data_inicio FROM contratos WHERE id = @Id";
        var rows = (await Conn.QueryAsync<DateOnly?>(
            new CommandDefinition(sql, new { Id = contratoId }, Tx, cancellationToken: ct))).ToList();
        return rows.Count == 0 ? (false, null) : (true, rows[0]);
    }

    public async Task<int?> ContarFuncionariosDaEquipeAsync(Guid equipeId, CancellationToken ct = default)
    {
        const string sqlEquipe = "SELECT COUNT(*) FROM equipes WHERE id = @Id";
        var existe = await Conn.ExecuteScalarAsync<long>(
            new CommandDefinition(sqlEquipe, new { Id = equipeId }, Tx, cancellationToken: ct));
        if (existe == 0) return null;

        const string sql = "SELECT COUNT(*) FROM equipe_membros WHERE equipe_id = @Id";
        return await Conn.ExecuteScalarAsync<int>(
            new CommandDefinition(sql, new { Id = equipeId }, Tx, cancellationToken: ct));
    }

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

    public async Task<bool?> EquipeEstaAtivaAsync(Guid equipeId, CancellationToken ct = default)
    {
        const string sql = "SELECT ativa FROM equipes WHERE id = @Id";
        var rows = (await Conn.QueryAsync<bool>(
            new CommandDefinition(sql, new { Id = equipeId }, Tx, cancellationToken: ct))).ToList();
        return rows.Count == 0 ? null : rows[0];
    }

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

    public async Task<IReadOnlyList<(string Nome, string Matricula, string? Funcao, int Tipo, bool Ativo)>> GetSnapshotFuncionariosAsync(Guid equipeId, CancellationToken ct = default)
    {
        const string sql = """
            SELECT f.nome, f.matricula, f.funcao, f.tipo, f.ativo
            FROM equipe_membros m
            JOIN funcionarios f ON f.id = m.funcionario_id
            WHERE m.equipe_id = @Id
            ORDER BY f.nome
            """;
        var rows = await Conn.QueryAsync<(string Nome, string Matricula, string? Funcao, int Tipo, bool Ativo)>(
            new CommandDefinition(sql, new { Id = equipeId }, Tx, cancellationToken: ct));
        return rows.ToList();
    }

    public async Task CongelarFuncionariosAsync(Guid folhaTarefaId, IReadOnlyList<(string Nome, string Matricula, string? Funcao, int Tipo, bool Ativo)> snapshot, CancellationToken ct = default)
    {
        const string sql = """
            INSERT INTO folha_tarefa_funcionarios_congelados (id, folha_tarefa_id, nome, matricula, funcao, tipo, ativo)
            VALUES (@Id, @FtId, @Nome, @Matricula, @Funcao, @Tipo, @Ativo)
            """;
        foreach (var s in snapshot)
            await Conn.ExecuteAsync(new CommandDefinition(sql, new
            {
                Id = Guid.NewGuid(), FtId = folhaTarefaId, s.Nome, s.Matricula, s.Funcao, s.Tipo, s.Ativo
            }, Tx, cancellationToken: ct));
    }

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

    public async Task AddAsync(FolhaTarefa f, CancellationToken ct = default)
    {
        const string sql = """
            INSERT INTO folhas_tarefa
                (id, contrato_id, equipe_id, supervisor_id, codigo, descricao, observacao,
                 data_inicial, periodo, data_final_prox_periodo, numero_horas,
                 semana_contrato_num, semana_anual, tipo, status, fechada,
                 revisao, data_fechamento, codigo_equipe_congelado, data_criacao)
            VALUES
                (@Id, @ContratoId, @EquipeId, @SupervisorId, @Codigo, @Descricao, @Observacao,
                 @DataInicial, @Periodo, @DataFinalProxPeriodo, @NumeroHoras,
                 @SemanaContratoNum, @SemanaAnual, @Tipo, @Status, @Fechada,
                 @Revisao, @DataFechamento, @CodigoEquipeCongelado, @DataCriacao)
            """;
        await Conn.ExecuteAsync(new CommandDefinition(sql, ToParameters(f), Tx, cancellationToken: ct));
    }

    public async Task UpdateAsync(FolhaTarefa f, CancellationToken ct = default)
    {
        const string sql = """
            UPDATE folhas_tarefa
               SET codigo = @Codigo, descricao = @Descricao, observacao = @Observacao,
                   data_inicial = @DataInicial, periodo = @Periodo,
                   data_final_prox_periodo = @DataFinalProxPeriodo, numero_horas = @NumeroHoras,
                   semana_contrato_num = @SemanaContratoNum, semana_anual = @SemanaAnual,
                   tipo = @Tipo, status = @Status, fechada = @Fechada,
                   revisao = @Revisao, data_fechamento = @DataFechamento,
                   codigo_equipe_congelado = @CodigoEquipeCongelado
             WHERE id = @Id
            """;
        await Conn.ExecuteAsync(new CommandDefinition(sql, ToParameters(f), Tx, cancellationToken: ct));
    }

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

    private static object ToParameters(FolhaTarefa f) => new
    {
        f.Id, f.ContratoId, f.EquipeId, f.SupervisorId, f.Codigo, f.Descricao, f.Observacao,
        f.DataInicial, f.Periodo, f.DataFinalProxPeriodo, f.NumeroHoras,
        f.SemanaContratoNum, f.SemanaAnual, f.Tipo, Status = (int)f.Status, f.Fechada,
        f.Revisao, f.DataFechamento, f.CodigoEquipeCongelado, f.DataCriacao
    };
}