PipefyProspUpdate/Services/PipefyApiService.cs

320 lines
12 KiB
C#

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using PipefyProspUpdate.Models;
using System.Windows.Controls;
using System.Web;
namespace PipefyProspUpdate.Services;
public class PipefyApiService
{
private readonly HttpClient _httpClient;
private readonly string GraphQLUrl = App.config["Pipefy_URL"]!;
private readonly string BearerToken = App.config["Pipefy_API_Key"]!;
public PipefyApiService(HttpClient httpClient)
{
_httpClient = httpClient;
_httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", BearerToken);
}
public async Task<List<Models.Users>> GetUsersAsync()
{
var allUsers = new List<Models.Users>();
var query = new
{
query = @"query GetProspectantes{
pipe(id: 303017662){
users{
id
name
email
}
}
}"
};
var requestContent = new StringContent(JsonConvert.SerializeObject(query), Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(GraphQLUrl, requestContent);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
var graphQLResponse = JsonConvert.DeserializeObject<GraphQLResponse>(responseString);
if (graphQLResponse?.data!.pipe?.users != null)
{
allUsers.AddRange(graphQLResponse.data.pipe.users);
}
return allUsers;
}
public async Task<List<Node>> GetCardsAsync(string pipeId, string fieldId, Models.Suggestion sug, IProgress<int>? progress = null, int totalCities = 1)
{
var allCards = new List<Node>();
bool hasNextPage = true;
string? endCursor = null;
while (hasNextPage)
{
var query = new
{
query = @"query GetCards_ProspUpdate($pipeId: ID!, $fieldId: String!, $fieldValue: String!, $cursor: String){
findCards(
pipeId: $pipeId,
first: 50,
search: {
fieldId: $fieldId,
fieldValue: $fieldValue
},
after: $cursor
)
{
pageInfo{
hasNextPage
endCursor
}
totalCount
nodes{
id
title
assignees
{
id
name
email
}
pipe{
name
}
current_phase{
id
name
}
fields{
field{
id
}
value
array_value
}
}
}
}",
variables = new
{
pipeId,
fieldId,
fieldValue = sug.City,
cursor = endCursor,
}
};
var requestContent = new StringContent(JsonConvert.SerializeObject(query), Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(GraphQLUrl, requestContent);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
var graphQLResponse = JsonConvert.DeserializeObject<GraphQLResponse>(responseString);
if (graphQLResponse?.data!.findCards?.nodes != null)
{
allCards.AddRange(graphQLResponse.data.findCards.nodes);
}
endCursor = graphQLResponse!.data!.findCards!.pageinfo!.endCursor ?? (string?)null;
hasNextPage = (bool)(graphQLResponse!.data!.findCards?.pageinfo.hasNextPage)!;
}
string UF = sug.UF!;
allCards = allCards
.Where(x =>
x.fields!.Where(x => x.field!.id == "estado_importa_o" | x.field.id == "sele_o_de_lista").Select(x => x.value).First()!.ToString() == UF
).ToList();
if (AppState.Instance.currentItems < totalCities) { AppState.Instance.currentItems++; }
var progressPercentage = (int)((double)AppState.Instance.currentItems / totalCities * 100);
progress?.Report(progressPercentage);
return allCards;
}
public async Task<List<Models.Node>> MutateCardsAsync(List<Models.Node> cards, List<Models.Users> prosp, List<Models.Users> others, bool KeepProsp, bool KeepOthers, IProgress<int>? progress = null, int totalCards = 1)
{
List<Models.Node> allCards = new();
List<Models.Node> clearCards = new();
List<string> id_match = Enumerable.Range(0, cards.Count).Select(x => "").ToList();
List<string?> newListOfProsp = prosp.Select(x => x.id).ToList();
List<string?> newListOfOthers = others.Select(x => x.id).ToList();
string mutationQuery = "mutation{";
string clearQuery = "mutation{";
int i = 1;
foreach (Models.Node card in cards)
{
if (AppState.Instance.currentItems < totalCards) { AppState.Instance.currentItems++; }
int progressPercentage = (int)((double)AppState.Instance.currentItems / totalCards * 100);
progress?.Report(progressPercentage);
List<string?> assignees = (card.assignees ?? new List<Models.Users> {}).Select(x => x.id).ToList();
List<string?> both = card.others.Intersect(card.prosp).Distinct().ToList();
List<string?> all = card.others.Concat(card.prosp).ToList();
List<string?> neither = all.Except(assignees).Distinct().ToList();
bool valProsp = (!KeepProsp && newListOfProsp.Any()) || (KeepProsp && card.prosp.Any() && !newListOfProsp.Any());
if (!valProsp) { continue; }
List<string?> ProspOfCard = new();
List<string?> OthersOfCard = new();
if (KeepProsp && card.prosp.Any()) { ProspOfCard.Add(card.prosp.First()); }
if (KeepOthers && card.others.Any()) { OthersOfCard.AddRange(card.others); }
if (card.prosp.Count > 1) {
OthersOfCard.AddRange(card.prosp);
}
if (newListOfProsp.Any() && !KeepProsp) { ProspOfCard.AddRange(newListOfProsp); }
if (newListOfOthers.Any()) { OthersOfCard.AddRange(newListOfOthers); }
ProspOfCard = new List<string?> { ProspOfCard.Distinct().ToList().First() };
OthersOfCard = OthersOfCard.Distinct().ToList().Except(ProspOfCard).ToList();
if ((ProspOfCard.SequenceEqual(card.prosp)) && (OthersOfCard.SequenceEqual(card.others) && !neither.Any())) { continue; }
string sProspOfCard = "";
string sOthersOfCard = "";
if (ProspOfCard.Any())
{
sProspOfCard = $@"{{
fieldId:""respons_vel""
value: [{string.Join(", ", ProspOfCard)}]
}}";
}
sOthersOfCard = $@",
{{
fieldId:""demais_envolvidos""
value: [{string.Join(", ", OthersOfCard)}]
}}";
id_match[i-1] = card.id ?? "";
mutationQuery += $@"
N{i-1}: updateFieldsValues(
input: {{
nodeId: {card.id}
values: [
{sProspOfCard}{sOthersOfCard}
]
}}
)
{{
success
}}";
clearCards.Add(card);
string sAssignees = "";
if (ProspOfCard.Concat(OthersOfCard).Any())
{
sAssignees = $@"{string.Join(", ", ProspOfCard.Concat(OthersOfCard).Distinct())}";
}
if (card.pipe?.name != "Funil de Vendas")
{
clearQuery += $@"
N{i-1}: updateCard(
input: {{
id: {card.id}
assignee_ids: [
{sAssignees}
]
}}
)
{{
card{{
assignees{{
name
}}
}}
}}";
}
i++;
}
mutationQuery += "\n}";
clearQuery += "\n}";
if (mutationQuery.Contains("updateFieldsValues"))
{
var query = new
{
query = mutationQuery,
};
var requestContent = new StringContent(JsonConvert.SerializeObject(query), Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(GraphQLUrl, requestContent);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
allCards.AddRange(ProcessJson(responseString, id_match));
}
if (clearQuery.Contains("updateCard"))
{
var clearQueryVar = new
{
query = clearQuery,
};
var requestClearContent = new StringContent(JsonConvert.SerializeObject(clearQueryVar), Encoding.UTF8, "application/json");
var responseClear = await _httpClient.PostAsync(GraphQLUrl, requestClearContent);
responseClear.EnsureSuccessStatusCode();
var responseStringClear = await responseClear.Content.ReadAsStringAsync();
}
return allCards;
}
public static List<Models.Node> ProcessJson(string jsonString, List<string> id_match)
{
var jsonObject = JObject.Parse(jsonString);
var data = jsonObject["data"] as JObject;
var nodes = new List<Models.Node>();
foreach (var property in data!.Properties())
{
if (property.Value is JObject innerObject)
{
foreach (var innerProperty in innerObject.Properties())
{
bool isSuccess = bool.Parse(innerProperty.Value.ToString().ToLower());
string index = id_match[Int32.Parse(property.Name.Replace("N",""))];
AppState.Instance.ProspeccaoFilteredCards.Where(x => x.id == index).First().success = isSuccess;
nodes.Add(AppState.Instance.ProspeccaoFilteredCards.Where(x => x.id == index).First());
}
}
}
return nodes;
}
}