diff --git a/Program.cs b/Program.cs index 0a89c39..628a66a 100644 --- a/Program.cs +++ b/Program.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Data.Common; using System.Numerics; using System.Threading.Tasks; using Npgsql; @@ -11,9 +12,42 @@ class Program static bool _stop = false; static bool _isAuthenticated = false; static readonly string _connectionString = "Server=192.168.10.248;Port=5432;Database=pipefy_move_cards;User Id=postgres;Password=gds21;"; - static readonly string _windowsID = Environment.UserName; + static readonly string _windowsID = "gestao1.3"; // Environment.UserName; + static readonly List<(string actionId, string actionName)> _actionIds = // Tuplas de IDs e nomes das fases que queremos monitorar + [ + new ("318642783-318906957", "Agendou reunião 1"), + new ("322784034-332649256", "Agendou reunião 2"), + new ("332659066-332653733", "Agendou reunião 3"), + new ("332659083-339300210", "Agendou reunião 4"), + new ("339300218-339300231", "Agendou reunião 5"), + new ("318906957-322784034", "Realizou reunião 1"), + new ("332649256-332659066", "Realizou reunião 2"), + new ("332653733-332659083", "Realizou reunião 3"), + new ("339300210-339300218", "Realizou reunião 4"), + new ("339300231-339300232", "Realizou reunião 5"), + new ("318906957-318642783", "Reunião cancelada"), + new ("332649256-322784034", "Reunião cancelada"), + new ("332653733-332659066", "Reunião cancelada"), + new ("339300210-332659083", "Reunião cancelada"), + new ("339300231-339300218", "Reunião cancelada"), + new ("325103205-325103208", "Agendou reunião 1"), + new ("325103212-332710299", "Agendou reunião 2"), + new ("332710321-332710322", "Agendou reunião 3"), + new ("332710362-339304168", "Agendou reunião 4"), + new ("339304193-339304215", "Agendou reunião 5"), + new ("325103208-325103212", "Realizou reunião 1"), + new ("332710299-332710321", "Realizou reunião 2"), + new ("332710322-332710362", "Realizou reunião 3"), + new ("339304168-339304193", "Realizou reunião 4"), + new ("339304215-339304218", "Realizou reunião 5"), + new ("325103208-325103205", "Reunião cancelada"), + new ("332710299-325103212", "Reunião cancelada"), + new ("332710322-332710321", "Reunião cancelada"), + new ("339304168-332710362", "Reunião cancelada"), + new ("339304215-339304193", "Reunião cancelada") + ]; // Agora guardamos uma lista de tuplas (UserID, Nome) - static readonly List<(BigInteger UserId, string Nome)> _pipeUsers = new(); + static readonly List<(BigInteger UserId, string Nome)> _pipeUsers = []; static void Main() { @@ -39,65 +73,40 @@ class Program AnsiConsole.MarkupLine("[bold yellow]Aplicação encerrada.[/]"); } - static void Autenticacao() + public class Record { - AnsiConsole.Status() - .Spinner(Spinner.Known.Dots) - .Start("[green]Autenticando usuário...[/]", ctx => - { - const string query = @" - SELECT ""UserID"", ""Nome"" - FROM public.""usuarios"" - WHERE ""windowsID"" = @WindowsID"; - - try - { - using var conn = new NpgsqlConnection(_connectionString); - conn.Open(); - using var cmd = new NpgsqlCommand(query, conn); - cmd.Parameters.AddWithValue("@WindowsID", _windowsID); - - using var reader = cmd.ExecuteReader(); - while (reader.Read()) - { - var userId = BigInteger.Parse(reader["UserID"].ToString()!); - var nome = reader["Nome"].ToString()!; - _pipeUsers.Add((userId, nome)); - } - - if (_pipeUsers.Count > 0) - { - _isAuthenticated = true; - } - else - { - AnsiConsole.MarkupLine("[bold red]Nenhum usuário encontrado para este WindowsID.[/]"); - _isAuthenticated = false; - } - } - catch (Exception ex) - { - AnsiConsole.MarkupLine($"\n[red]Erro na autenticação:[/] {ex.Message}"); - _isAuthenticated = false; - } - }); + public int? Id { get; set; } + public string? Action { get; set; } + public string? User { get; set; } + public string? FieldID { get; set; } + public int? From { get; set; } + public int? To { get; set; } + public int? CardID { get; set; } + public string? PipeSUID { get; set; } + public DateTime MovedAt { get; set; } + public required string Title { get; set; } + public string? AcaoID { get; set; } + public string? Acao { get; set; } } - static void AtualizarDados() { + var records = new List(); AnsiConsole.Clear(); // Painel de cabeçalho que mostra quantos usuários foram carregados - var header = new Panel($"[bold]WindowsID[/]: {_windowsID} • [bold]Usuários encontrados[/]: {_pipeUsers.Count}") - .Header("[yellow]Resumo Diário por Usuário[/]") + + var status = new Align(new Panel($"[bold]WindowsID[/]: {_windowsID} | [bold]Usuários encontrados[/]: {_pipeUsers.Count}"), HorizontalAlignment.Center, VerticalAlignment.Top); + var header = new Panel(status) + .Header("[yellow]Resumo Diário por Usuário[/]",Justify.Center) .Expand(); - AnsiConsole.Write(header); + AnsiConsole.Write(new Align(header, HorizontalAlignment.Center, VerticalAlignment.Top)); // Montamos uma tabela com: Nome do usuário | UserID | Registros Hoje - var table = new Table().Border(TableBorder.Rounded); - table.AddColumn("[green]Nome[/]"); - table.AddColumn("[green]UserID[/]"); - table.AddColumn("[green]Registros Hoje[/]"); + var tableContLigacoes = new Table().Border(TableBorder.Rounded).Alignment(Justify.Center); + tableContLigacoes.Border(TableBorder.Rounded); + tableContLigacoes.AddColumn(new TableColumn("[green]Nome[/]").Centered()); + tableContLigacoes.AddColumn(new TableColumn("[green]UserID[/]").Centered()); + tableContLigacoes.AddColumn(new TableColumn("[green]Registros Hoje[/]").Centered()); // Para cada usuário, rodar uma query COUNT(*) e adicionar linha na tabela foreach (var (userId, nome) in _pipeUsers) @@ -108,31 +117,86 @@ class Program .Start($"[blue]Obtendo registros de [yellow]{nome}[/]...[/]", ctx => { const string query = @" - SELECT COUNT(*) - FROM public.""ActionsHistory"" - WHERE ""UserID"" = @pipeUser - AND ""MovedAt"" > CURRENT_DATE - AND ""FieldID"" IS NOT NULL"; - try + SELECT * FROM public.""ActionsHistory"" + WHERE ""UserID"" = @pipeUser AND + ""MovedAt"" >= date_trunc('month', CURRENT_DATE)"; + //try + //{ + using var conn = new NpgsqlConnection(_connectionString); + conn.Open(); + using var cmd = new NpgsqlCommand(query, conn); + cmd.Parameters.AddWithValue("@pipeUser", userId); + var reader = cmd.ExecuteReader(); + using (reader) { - using var conn = new NpgsqlConnection(_connectionString); - conn.Open(); - using var cmd = new NpgsqlCommand(query, conn); - cmd.Parameters.AddWithValue("@pipeUser", userId); - count = Convert.ToInt32(cmd.ExecuteScalar()); - } - catch (Exception ex) - { - // Em caso de erro, exibimos zero e continuamos - count = 0; - AnsiConsole.MarkupLine($"\n[red]Erro ao consultar {nome}:[/] {ex.Message}"); + while (reader.Read()) + { + var temp = new Record + { + Id = ToIntOrNull(reader, "Id"), + Action = ToStringOrNull(reader, "Action"), + User = _pipeUsers.Find(u => u.UserId == ToIntOrNull(reader, "UserID")).Nome, + FieldID = ToStringOrNull(reader, "FieldID"), + From = ToIntOrNull(reader, "From"), + To = ToIntOrNull(reader, "To"), + CardID = ToIntOrNull(reader, "CardID"), + PipeSUID = ToStringOrNull(reader, "PipeSUID"), + MovedAt = (DateTime)(reader["MovedAt"] ?? DateTime.MinValue), + Title = ToStringOrNull(reader, "Title") ?? "-", + }; + temp.AcaoID = temp.From + "-" + temp.To; + temp.Acao = _actionIds.Find(p => p.actionId == temp.AcaoID).actionName; + + records.Add(temp); + } } + //} + //catch (Exception ex) + //{ + // // Em caso de erro, exibimos zero e continuamos + // count = 0; + // AnsiConsole.MarkupLine($"\n[red]Erro ao consultar {nome}:[/] {ex.Message}"); + //} }); - - table.AddRow(nome, userId.ToString(), $"[bold yellow]{count}[/]"); + count = records.Where(x => x.MovedAt >= DateTime.Today).ToList().Count; + tableContLigacoes.AddRow(nome, userId.ToString(), $"[bold yellow]{count}[/]"); } - AnsiConsole.Write(table); + var panel = new Panel(new Align(tableContLigacoes, HorizontalAlignment.Center, VerticalAlignment.Top)) + .Header("[blue bold] Ligações [/]", Justify.Center) + .Border(BoxBorder.Double) + .Expand(); + AnsiConsole.Write(new Align(panel, HorizontalAlignment.Center, VerticalAlignment.Top)); + + // Montamos uma tabela com: Nome do usuário | UserID | Registros Hoje + var tableReunioes = new Table().Border(TableBorder.Rounded).Alignment(Justify.Center); + tableReunioes.AddColumn(new TableColumn("[green]Data[/]").Centered()); + tableReunioes.AddColumn(new TableColumn("[green]Status[/]").Centered()); + tableReunioes.AddColumn(new TableColumn("[green]Empresa[/]").Centered()); + tableReunioes.AddColumn(new TableColumn("[green]Card ID\n(Ctrl + click)[/]").Centered()); + tableReunioes.AddColumn(new TableColumn("[green]Prospectante[/]").Centered()); + + records = [.. records.OrderBy(x => x.MovedAt).OrderBy(y => y.User)]; + + // Para cada usuário, rodar uma query COUNT(*) e adicionar linha na tabela + foreach (var record in records) + { + if (record.Acao is not null) + { + tableReunioes.AddRow( + record.MovedAt.ToString("d"), + record.Acao ?? "Ação desconhecida", + record.Title ?? "", + $"[link=https://app.pipefy.com/open-cards/{record.CardID}]{record.CardID}[/]", + record.User ?? "" + ); + } + } + panel = new Panel(new Align(tableReunioes, HorizontalAlignment.Center, VerticalAlignment.Top)) + .Header("[blue bold] Reuniões no Mês [/]", Justify.Center) + .Border(BoxBorder.Double) + .Expand(); + AnsiConsole.Write(new Align(panel, HorizontalAlignment.Center, VerticalAlignment.Top)); AnsiConsole.MarkupLine("\n[gray]Pressione [green]ENTER[/] para atualizar agora ou qualquer outra tecla para sair.[/]"); } @@ -181,4 +245,63 @@ class Program Console.WriteLine(""); } + static void Autenticacao() + { + AnsiConsole.Status() + .Spinner(Spinner.Known.Dots) + .Start("[green]Autenticando usuário...[/]", ctx => + { + const string query = @" + SELECT ""UserID"", ""Nome"" + FROM public.""usuarios"" + WHERE ""windowsID"" = @WindowsID"; + + try + { + using var conn = new NpgsqlConnection(_connectionString); + conn.Open(); + using var cmd = new NpgsqlCommand(query, conn); + cmd.Parameters.AddWithValue("@WindowsID", _windowsID); + + using var reader = cmd.ExecuteReader(); + while (reader.Read()) + { + var userId = BigInteger.Parse(reader["UserID"].ToString()!); + var nome = reader["Nome"].ToString()!; + _pipeUsers.Add((userId, nome)); + } + + if (_pipeUsers.Count > 0) + { + _isAuthenticated = true; + } + else + { + AnsiConsole.MarkupLine("[bold red]Nenhum usuário encontrado para este WindowsID.[/]"); + _isAuthenticated = false; + } + } + catch (Exception ex) + { + AnsiConsole.MarkupLine($"\n[red]Erro na autenticação:[/] {ex.Message}"); + _isAuthenticated = false; + } + }); + } + #region Helpers + + static int? ToIntOrNull(DbDataReader r, string col) + { + return r.IsDBNull(r.GetOrdinal(col)) + ? null + : Convert.ToInt32(r[col]); ; + } + + static string? ToStringOrNull(DbDataReader r, string col) + { + return r.IsDBNull(r.GetOrdinal(col)) + ? null + : r.GetString(r.GetOrdinal(col)); + } + #endregion }