Pipefy/Program.cs
2023-11-16 17:21:06 -03:00

274 lines
12 KiB
C#

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;
using System.Reflection.Metadata;
using Pipefy;
class Program
{
static async Task Main(string[] args)
{
Console.Clear();
// URL da API que você deseja chamar
string ConnSourcePath = @"C:\Users\contratos\Documents\Giuliano\Pipefy.accdb";
string apiUrl = "https://api.pipefy.com/graphql";
string PipefyToken = "eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJQaXBlZnkiLCJpYXQiOjE2OTg4NTYyMjcsImp0aSI6IjM2N2Y4M2NhLWZjODYtNGRhOC04ODEyLTkzODRkZGZkODc0MiIsInN1YiI6MzAyNTM0MzY2LCJ1c2VyIjp7ImlkIjozMDI1MzQzNjYsImVtYWlsIjoiYmFjazVAZW5lcmdpYXNtYXJ0LmNvbS5iciIsImFwcGxpY2F0aW9uIjozMDAyODkyNDgsInNjb3BlcyI6W119LCJpbnRlcmZhY2VfdXVpZCI6bnVsbH0.o13j9c_y3G3HX35qhX4PmkkibGsmlHsk5dL_Bxsr1CKV5Jlgj218kJdEmriS7aHiw0-P7sfs-bu4YcElfuyiqg";
string PipefyTokenTableID = "wzirXS8w";
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 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}}}}}";
bool hasNextPage = true;
bool hasSucceeded = true;
while (hasNextPage)
{
var httpClient = new HttpClient();
// Defina os headers da requisição (opcional)
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + PipefyToken);
var request = new HttpRequestMessage(HttpMethod.Post, apiUrl);
request.Headers.Add("Accept", "application/json");
var content = new StringContent(query, null, "application/json");
request.Content = content;
var response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
var responseData = JObject.Parse(responseContent);
Console.Clear();
var records = responseData["data"]["table_records"]["edges"];
foreach (var record in records)
{
//Console.WriteLine(record);
allRecords.Add(record);
}
hasNextPage = responseData["data"]["table_records"]["pageInfo"]["hasNextPage"].Value<bool>();
cursor = responseData["data"]["table_records"]["pageInfo"]["endCursor"].Value<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}\"}}}}";
}
else
{
Console.WriteLine($"Erro na solicitação GraphQL: {response.StatusCode}");
allRecords.Clear();
return allRecords;
}
}
return allRecords;
}
static List<Pipefy.ClasseEmpresas> GetDataFromDatabase(string ConnSourcePath)
{
string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ConnSourcePath;
List<Pipefy.ClasseEmpresas> data = new List<Pipefy.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())
{
Pipefy.ClasseEmpresas record = new Pipefy.ClasseEmpresas
{
c_digo_smart = (string)reader["Código Smart"].ToString(),
nome_da_empresa = (string)reader["Nome da empresa"],
modalidade = (string)reader["modalidade"],
gestores = (string)reader["gestores"],
// Adicione outras propriedades conforme necessário
};
data.Add(record);
}
}
}
}
return data;
}
static List<Pipefy.ClasseEmpresas> convertEmpresasJson(List<Pipefy.RootObject> jsonData)
{
List<Pipefy.ClasseEmpresas> data = new List<Pipefy.ClasseEmpresas>();
for (int i = 0;i<jsonData.Count;i++)
{
Pipefy.ClasseEmpresas record = new Pipefy.ClasseEmpresas();
for (int j = 0;j < jsonData[i].node.record_fields.Length;j++)
{
switch (jsonData[i].node.record_fields[j].field.id)
{
case "nome_da_empresa":
record.nome_da_empresa = jsonData[i].node.record_fields[j].value;
break;
case "c_digo_smart":
record.c_digo_smart = jsonData[i].node.record_fields[j].value.Replace(".0","");
break;
case "modalidade":
record.modalidade = jsonData[i].node.record_fields[j].value;
break;
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;
break;
}
}
// Adicione outras propriedades conforme necessário
data.Add(record);
}
return data;
}
static List<Pipefy.ClasseEmpresas> CompareData(List<Pipefy.ClasseEmpresas> databaseData, List<Pipefy.ClasseEmpresas> jsonList, List<Pipefy.ClasseGestores> jsonListGestores)
{
if (jsonList == null)
{
return databaseData;
}
List<Pipefy.ClasseEmpresas> recordsMissingInJson = new List<Pipefy.ClasseEmpresas>();
var exists = false;
foreach (var record in databaseData)
{
exists = false;
for (var j = 0; j < jsonList.Count; j++) {
//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())
{
exists = true;
break;
}
}
Console.Clear();
if (exists == false) {
record.gestores = findGestores(record.gestores,jsonListGestores);
if (record.gestores != "0")
{
recordsMissingInJson.Add(record);
}
else
{
int test = 10;
}
}
}
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";
}
}