20231116 - Modularidade e retrieve Gestores

This commit is contained in:
giuliano 2023-11-16 17:21:06 -03:00
parent f8963096ef
commit 9f6a277f31
2 changed files with 137 additions and 204 deletions

View File

@ -15,18 +15,67 @@ class Program
{ {
Console.Clear(); Console.Clear();
// URL da API que você deseja chamar // URL da API que você deseja chamar
string ConnSourcePath = @"C:\Users\contratos\Documents\Giuliano\Pipefy.accdb";
string apiUrl = "https://api.pipefy.com/graphql"; string apiUrl = "https://api.pipefy.com/graphql";
string PipefyToken = "eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJQaXBlZnkiLCJpYXQiOjE2OTg4NTYyMjcsImp0aSI6IjM2N2Y4M2NhLWZjODYtNGRhOC04ODEyLTkzODRkZGZkODc0MiIsInN1YiI6MzAyNTM0MzY2LCJ1c2VyIjp7ImlkIjozMDI1MzQzNjYsImVtYWlsIjoiYmFjazVAZW5lcmdpYXNtYXJ0LmNvbS5iciIsImFwcGxpY2F0aW9uIjozMDAyODkyNDgsInNjb3BlcyI6W119LCJpbnRlcmZhY2VfdXVpZCI6bnVsbH0.o13j9c_y3G3HX35qhX4PmkkibGsmlHsk5dL_Bxsr1CKV5Jlgj218kJdEmriS7aHiw0-P7sfs-bu4YcElfuyiqg"; string PipefyToken = "eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJQaXBlZnkiLCJpYXQiOjE2OTg4NTYyMjcsImp0aSI6IjM2N2Y4M2NhLWZjODYtNGRhOC04ODEyLTkzODRkZGZkODc0MiIsInN1YiI6MzAyNTM0MzY2LCJ1c2VyIjp7ImlkIjozMDI1MzQzNjYsImVtYWlsIjoiYmFjazVAZW5lcmdpYXNtYXJ0LmNvbS5iciIsImFwcGxpY2F0aW9uIjozMDAyODkyNDgsInNjb3BlcyI6W119LCJpbnRlcmZhY2VfdXVpZCI6bnVsbH0.o13j9c_y3G3HX35qhX4PmkkibGsmlHsk5dL_Bxsr1CKV5Jlgj218kJdEmriS7aHiw0-P7sfs-bu4YcElfuyiqg";
string ConnSourcePath = @"C:\Users\contratos\Documents\Giuliano\Pipefy.accdb"; string PipefyTokenTableID = "wzirXS8w";
string PipefyTokenTableID = "b9t-7uD5"; JArray allRecords = await GetPipefyDataAsync(apiUrl,PipefyToken,PipefyTokenTableID);
JArray allGestores = await GetPipefyDataAsync(apiUrl, PipefyToken, "nuyW2tji");
Console.Clear();
if (allRecords is not null)
{
string strGestores = JsonConvert.SerializeObject(allGestores);
// Desserialize o JSON em objetos C#
var jsonGestores = JsonConvert.DeserializeObject<List<Pipefy.RootObject>>(strGestores);
List<Pipefy.ClasseGestores> jsonListGestores = convertGestoresJson(jsonGestores);
string strJson = JsonConvert.SerializeObject(allRecords);
// Desserialize o JSON em objetos C#
var jsonData = JsonConvert.DeserializeObject<List<Pipefy.RootObject>>(strJson);
List<Pipefy.ClasseEmpresas> jsonList = convertEmpresasJson(jsonData);
// Consulte os dados da tabela no banco de dados Access
List<Pipefy.ClasseEmpresas> databaseData = GetDataFromDatabase(ConnSourcePath);
// Compare os dados e encontre os registros ausentes no JSON
List<Pipefy.ClasseEmpresas> recordsMissingInJson = CompareData(databaseData, jsonList, jsonListGestores);
if (recordsMissingInJson.Count != 0)
{
// Faça algo com os registros ausentes
int maxCId = recordsMissingInJson.OrderByDescending(s => s.c_digo_smart.Length).First().c_digo_smart.Length;
int maxCNome = recordsMissingInJson.OrderByDescending(s => s.nome_da_empresa.Length).First().nome_da_empresa.Length;
int maxCMod = recordsMissingInJson.OrderByDescending(s => s.modalidade.Length).First().modalidade.Length;
int maxCGestao = recordsMissingInJson.OrderByDescending(s => s.gestores.Length).First().gestores.Length;
foreach (var record in recordsMissingInJson)
{
Console.WriteLine(String.Format($"| ID: {{0,{maxCId}}} | Nome: {{1,{maxCNome}}} | Modalidade: {{2,{maxCMod}}} | Gestão: {{3,{maxCGestao}}} |",record.c_digo_smart,record.nome_da_empresa,record.modalidade,record.gestores));
}
Console.WriteLine($"");
}
Console.WriteLine($"{recordsMissingInJson.Count} registros encontrados.");
}
}
private static async Task<JArray> GetPipefyDataAsync(string apiUrl, string PipefyToken, string PipefyTokenTableID)
{
JArray allRecords = new JArray();
string? cursor = "null"; string? cursor = "null";
string query = $"{{\"query\":\"query GetRecords($cursor: String){{ table_records(table_id: \\\"{PipefyTokenTableID}\\\",first:50,after:$cursor){{ pageInfo{{ hasNextPage endCursor }} edges{{ node{{ record_fields{{ field {{ id }} value array_value }} }} }} }}}}\",\"variables\":{{\"cursor\":{cursor}}}}}"; string query = $"{{\"query\":\"query GetRecords($cursor: String){{ table_records(table_id: \\\"{PipefyTokenTableID}\\\",first:50,after:$cursor){{ pageInfo{{ hasNextPage endCursor }} edges{{ node{{ id record_fields{{ field {{ id }} value array_value }} }} }} }}}}\",\"variables\":{{\"cursor\":{cursor}}}}}";
//Console.WriteLine(query);
bool hasNextPage = true; bool hasNextPage = true;
bool hasSucceeded = true; bool hasSucceeded = true;
JArray allRecords = new JArray();
while (hasNextPage) while (hasNextPage)
{ {
@ -63,40 +112,18 @@ class Program
else else
{ {
Console.WriteLine($"Erro na solicitação GraphQL: {response.StatusCode}"); Console.WriteLine($"Erro na solicitação GraphQL: {response.StatusCode}");
hasSucceeded = false; allRecords.Clear();
break; return allRecords;
} }
} }
Console.Clear(); return allRecords;
if (hasSucceeded)
{
string strJson = JsonConvert.SerializeObject(allRecords);
// Desserialize o JSON em objetos C#
var jsonData = JsonConvert.DeserializeObject<List<Pipefy.RootObject>>(strJson);
List<ClasseEmpresas> jsonList = convertJson(jsonData);
// Consulte os dados da tabela no banco de dados Access
List<ClasseEmpresas> databaseData = GetDataFromDatabase(ConnSourcePath);
// Compare os dados e encontre os registros ausentes no JSON
List<ClasseEmpresas> recordsMissingInJson = CompareData(databaseData, jsonList);
if (recordsMissingInJson.Count == 0) { Console.WriteLine("Sem registros");}
// Faça algo com os registros ausentes
foreach (var record in recordsMissingInJson)
{
Console.WriteLine($"Registro ausente no JSON - ID: {record.c_digo_smart}, Nome: {record.nome_da_empresa}");
} }
}
} static List<Pipefy.ClasseEmpresas> GetDataFromDatabase(string ConnSourcePath)
static List<ClasseEmpresas> GetDataFromDatabase(string ConnSourcePath)
{ {
string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ConnSourcePath; string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ConnSourcePath;
List<ClasseEmpresas> data = new List<ClasseEmpresas>(); List<Pipefy.ClasseEmpresas> data = new List<Pipefy.ClasseEmpresas>();
using (OleDbConnection connection = new OleDbConnection(connectionString)) using (OleDbConnection connection = new OleDbConnection(connectionString))
{ {
@ -110,7 +137,7 @@ class Program
{ {
while (reader.Read()) while (reader.Read())
{ {
ClasseEmpresas record = new ClasseEmpresas Pipefy.ClasseEmpresas record = new Pipefy.ClasseEmpresas
{ {
c_digo_smart = (string)reader["Código Smart"].ToString(), c_digo_smart = (string)reader["Código Smart"].ToString(),
nome_da_empresa = (string)reader["Nome da empresa"], nome_da_empresa = (string)reader["Nome da empresa"],
@ -127,13 +154,13 @@ class Program
return data; return data;
} }
static List<ClasseEmpresas> convertJson(List<Pipefy.RootObject> jsonData) static List<Pipefy.ClasseEmpresas> convertEmpresasJson(List<Pipefy.RootObject> jsonData)
{ {
List<ClasseEmpresas> data = new List<ClasseEmpresas>(); List<Pipefy.ClasseEmpresas> data = new List<Pipefy.ClasseEmpresas>();
for (int i = 0;i<jsonData.Count;i++) for (int i = 0;i<jsonData.Count;i++)
{ {
ClasseEmpresas record = new ClasseEmpresas(); Pipefy.ClasseEmpresas record = new Pipefy.ClasseEmpresas();
for (int j = 0;j < jsonData[i].node.record_fields.Length;j++) for (int j = 0;j < jsonData[i].node.record_fields.Length;j++)
{ {
switch (jsonData[i].node.record_fields[j].field.id) switch (jsonData[i].node.record_fields[j].field.id)
@ -148,6 +175,34 @@ class Program
record.modalidade = jsonData[i].node.record_fields[j].value; record.modalidade = jsonData[i].node.record_fields[j].value;
break; break;
case "gestores": case "gestores":
record.gestores = jsonData[i].node.record_fields[j].array_value.FirstOrDefault().ToString();
break;
}
}
// Adicione outras propriedades conforme necessário
data.Add(record);
}
return data;
}
static List<Pipefy.ClasseGestores> convertGestoresJson(List<Pipefy.RootObject> jsonData)
{
List<Pipefy.ClasseGestores> data = new List<Pipefy.ClasseGestores>();
for (int i = 0; i < jsonData.Count; i++)
{
Pipefy.ClasseGestores record = new Pipefy.ClasseGestores();
for (int j = 0; j < jsonData[i].node.record_fields.Length; j++)
{
switch (jsonData[i].node.record_fields[j].field.id)
{
case "gestor":
record.id = jsonData[i].node.record_fields.ToString();
break;
case "gest_o":
record.gestores = jsonData[i].node.record_fields[j].value; record.gestores = jsonData[i].node.record_fields[j].value;
break; break;
@ -161,14 +216,14 @@ class Program
return data; return data;
} }
static List<ClasseEmpresas> CompareData(List<ClasseEmpresas> databaseData, List<ClasseEmpresas> jsonList) static List<Pipefy.ClasseEmpresas> CompareData(List<Pipefy.ClasseEmpresas> databaseData, List<Pipefy.ClasseEmpresas> jsonList, List<Pipefy.ClasseGestores> jsonListGestores)
{ {
if (jsonList == null) if (jsonList == null)
{ {
return databaseData; return databaseData;
} }
List<ClasseEmpresas> recordsMissingInJson = new List<ClasseEmpresas>(); List<Pipefy.ClasseEmpresas> recordsMissingInJson = new List<Pipefy.ClasseEmpresas>();
var exists = false; var exists = false;
foreach (var record in databaseData) foreach (var record in databaseData)
@ -179,7 +234,7 @@ class Program
//Console.WriteLine(jsonList[j].c_digo_smart.ToString().Replace(".0", "") + " - " + record.c_digo_smart.ToString() + " - " + (jsonList[j].c_digo_smart.ToString().Replace(".0", "") == record.c_digo_smart.ToString())); //Console.WriteLine(jsonList[j].c_digo_smart.ToString().Replace(".0", "") + " - " + record.c_digo_smart.ToString() + " - " + (jsonList[j].c_digo_smart.ToString().Replace(".0", "") == record.c_digo_smart.ToString()));
if (jsonList[j].c_digo_smart.ToString().Replace(".0", "") == record.c_digo_smart.ToString()) if (jsonList[j].c_digo_smart?.ToString().Replace(".0", "") == record.c_digo_smart.ToString())
{ {
exists = true; exists = true;
break; break;
@ -189,169 +244,31 @@ class Program
Console.Clear(); Console.Clear();
if (exists == false) { recordsMissingInJson.Add(record); } if (exists == false) {
record.gestores = findGestores(record.gestores,jsonListGestores);
if (record.gestores != "0")
{
recordsMissingInJson.Add(record);
}
else
{
int test = 10;
}
}
} }
return recordsMissingInJson; return recordsMissingInJson;
} }
static string findGestores(string sCodigo, List<Pipefy.ClasseGestores> jsonListGestores)
{
for (var i = 0; i < jsonListGestores.Count; i++)
{
if (sCodigo == jsonListGestores[i].gestores?.ToString())
{
return jsonListGestores[i].id;
}
}
return "0";
}
} }
class ClasseEmpresas
{
public string c_digo_smart { get; set; }
public string nome_da_empresa { get; set; }
public string modalidade { get; set; }
public string gestores { get; set; }
// Adicione outras propriedades conforme necessário
}
//using System;
//using System.Data.OleDb;
//using System.Net.Http;
//using System.Net.Http.Headers;
//using System.Text.Json;
//using System.Threading.Tasks;
//using Newtonsoft.Json;
//using Newtonsoft.Json.Linq;
//using System.Collections.Generic;
//class Program
//{
// static async Task Main(string[] args)
// {
// // URL da API que você deseja chamar
// string apiUrl = "https://api.pipefy.com/graphql";
// string PipefyToken = "eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJQaXBlZnkiLCJpYXQiOjE2OTg4NTYyMjcsImp0aSI6IjM2N2Y4M2NhLWZjODYtNGRhOC04ODEyLTkzODRkZGZkODc0MiIsInN1YiI6MzAyNTM0MzY2LCJ1c2VyIjp7ImlkIjozMDI1MzQzNjYsImVtYWlsIjoiYmFjazVAZW5lcmdpYXNtYXJ0LmNvbS5iciIsImFwcGxpY2F0aW9uIjozMDAyODkyNDgsInNjb3BlcyI6W119LCJpbnRlcmZhY2VfdXVpZCI6bnVsbH0.o13j9c_y3G3HX35qhX4PmkkibGsmlHsk5dL_Bxsr1CKV5Jlgj218kJdEmriS7aHiw0-P7sfs-bu4YcElfuyiqg";
// string ConnSourcePath = @"C:\Users\contratos\Documents\Giuliano\Pipefy.accdb";
// string PipefyTokenTableID = "b9t-7uD5";
// // Crie uma instância HttpClient
// using (HttpClient httpClient = new HttpClient())
// {
// // Defina os headers da requisição (opcional)
// httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
// httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + PipefyToken);
// // Crie a consulta GraphQL
// //string rawGraphQuery = @"{""query"":""query{\r\n table_records(table_id: \""" + PipefyTokenTableID + @"\"") {\r\n edges {\r\n node {\r\n id\r\n record_fields{\r\n field{\r\n id\r\n }\r\n value\r\n }\r\n }\r\n }\r\n }\r\n}"",""variables"":{}}";
// string rawGraphQuery = "{\"query\":\"query { table_records(table_id: \\\"" + PipefyTokenTableID + "\\\") { edges { node { id record_fields { field { id } value } } } } }\",\"variables\":{}}";
// string query = /*lang=json,strict*/ rawGraphQuery;
// // Defina o conteúdo do corpo da requisição
// var content = new StringContent(query, System.Text.Encoding.UTF8, "application/json");
// // Envie a requisição POST com a consulta GraphQL
// var response = await httpClient.PostAsync(apiUrl, content);
// if (response.IsSuccessStatusCode)
// {
// string responseBody = await response.Content.ReadAsStringAsync();
// Console.WriteLine("Resposta bem-sucedida:");
// Console.WriteLine(responseBody);
// // Desserialize o JSON em objetos C#
// var jsonData = JsonConvert.DeserializeObject<Root>(responseBody);
// // Consulte os dados da tabela no banco de dados Access
// List<ClasseEmpresas> databaseData = GetDataFromDatabase(ConnSourcePath);
// // Compare os dados e encontre os registros ausentes no JSON
// List<ClasseEmpresas> recordsMissingInJson = CompareData(databaseData, jsonData);
// // Faça algo com os registros ausentes
// foreach (var record in recordsMissingInJson)
// {
// Console.WriteLine($"Registro ausente no JSON - ID: {record.Id}, Nome: {record.Nome}");
// }
// }
// else
// {
// Console.WriteLine($"Erro na requisição: {response.StatusCode}");
// }
// }
// }
// static List<ClasseEmpresas> GetDataFromDatabase(string ConnSourcePath)
// {
// string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ConnSourcePath;
// List<ClasseEmpresas> data = new List<ClasseEmpresas>();
// using (OleDbConnection connection = new OleDbConnection(connectionString))
// {
// connection.Open();
// // Execute uma consulta SQL para recuperar dados da tabela no banco de dados Access
// string sqlQuery = "SELECT * FROM tblEmpresas";
// using (OleDbCommand command = new OleDbCommand(sqlQuery, connection))
// {
// using (OleDbDataReader reader = command.ExecuteReader())
// {
// while (reader.Read())
// {
// ClasseEmpresas record = new ClasseEmpresas
// {
// Id = (int)reader["id"],
// Nome = (string)reader["nome"],
// // Adicione outras propriedades conforme necessário
// };
// data.Add(record);
// }
// }
// }
// }
// return data;
// }
// static List<ClasseEmpresas> CompareData(List<ClasseEmpresas> databaseData, Root? jsonData)
// {
// if(jsonData == null) { return databaseData; }
// List<ClasseEmpresas> recordsMissingInJson = new List<ClasseEmpresas>();
// foreach (var record in databaseData)
// {
// if (!jsonData.Any(item => item.id == record.id))
// {
// recordsMissingInJson.Add(record);
// }
// }
// return recordsMissingInJson;
// }
//}
//class Root
//{
// public required List<ClasseEmpresas> jsonData { get; set; }
// internal bool Any(Func<object, bool> value)
// {
// throw new NotImplementedException();
// }
//}
//class ClasseEmpresas
//{
// public int Id { get; set; }
// public required string Nome { get; set; }
// internal bool Any(Func<object, bool> value)
// {
// throw new NotImplementedException();
// }
// // Adicione outras propriedades conforme necessário
//}

18
data.cs
View File

@ -11,7 +11,7 @@ namespace Pipefy
public Node node { get; set; } public Node node { get; set; }
} }
public class data public class Data
{ {
public Node node { get; set; } public Node node { get; set; }
} }
@ -32,4 +32,20 @@ namespace Pipefy
{ {
public string id { get; set; } public string id { get; set; }
} }
public class ClasseEmpresas
{
public string c_digo_smart { get; set; }
public string nome_da_empresa { get; set; }
public string modalidade { get; set; }
public string gestores { get; set; }
}
public class ClasseGestores
{
public string id { get; set; }
public string gestores { get; set; }
}
} }