diff --git a/Download Faturas/Class1.cs b/Download Faturas/Class1.cs new file mode 100644 index 0000000..220941f --- /dev/null +++ b/Download Faturas/Class1.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Download_Faturas +{ + public class Rootobject + { + public string version { get; set; } + public string md5 { get; set; } + public string provider { get; set; } + public Providerdata providerData { get; set; } + public string locationNumber { get; set; } + public string subclass { get; set; } + public string subgroup { get; set; } + public Customer customer { get; set; } + public float losses { get; set; } + public float totalCharges { get; set; } + public string tariffModality { get; set; } + public Dates dates { get; set; } + public Measureditem[] measuredItems { get; set; } + public Item[] items { get; set; } + } + + public class Providerdata + { + public Name name { get; set; } + public Cnpj cnpj { get; set; } + } + + public class Name + { + public string value { get; set; } + public string confidence { get; set; } + } + + public class Cnpj + { + public string value { get; set; } + public string confidence { get; set; } + } + + public class Customer + { + public string cnpj { get; set; } + public string name { get; set; } + public Address address { get; set; } + } + + public class Address + { + public string streetAndNumber { get; set; } + public string city { get; set; } + public string state { get; set; } + public string zipCode { get; set; } + public string district { get; set; } + } + + public class Dates + { + public DateTime due { get; set; } + public DateTime month { get; set; } + public Reading reading { get; set; } + } + + public class Reading + { + public DateTime periodFrom { get; set; } + public DateTime periodUntil { get; set; } + } + + public class Measureditem + { + public string type { get; set; } + public string kind { get; set; } + public string period { get; set; } + public string[] texts { get; set; } + public float measured { get; set; } + } + + public class Item + { + public string type { get; set; } + public string kind { get; set; } + public string period { get; set; } + public float billed { get; set; } + public float rate { get; set; } + public float charge { get; set; } + public float tusdRate { get; set; } + public float teRate { get; set; } + public string[] texts { get; set; } + public float contract { get; set; } + public string name { get; set; } + public float taxable { get; set; } + public bool summable { get; set; } + } +} + diff --git a/Download Faturas/Class2.cs b/Download Faturas/Class2.cs new file mode 100644 index 0000000..548c7b3 --- /dev/null +++ b/Download Faturas/Class2.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Download_Faturas +{ + public class recordSet + { + public long Cod_TUSD { get; set; } + public long Cod_Smart_unidade { get; set; } + public int Mes { get; set; } + public float Revisao { get; set; } + public bool Rev_atual { get; set; } + public DateTime Hora_TUSD { get; set; } + public float Tempo_TUSD { get; set; } + public string Perfil_CliqCCEE { get; set; } + public string Submercado { get; set; } + public string Ambiente { get; set; } + public string Distribuidora { get; set; } + public string Grupo { get; set; } + public string Perfil { get; set; } + public DateTime Inicio_Leitura { get; set; } + public DateTime Fim_leitura { get; set; } + public float Valor { get; set; } + public float Consumo_P { get; set; } + public float Consumo_FP { get; set; } + public float Dem_Reg_P { get; set; } + public float Dem_Reg_FP { get; set; } + public float Dem_Cont_P { get; set; } + public float Dem_Cont_FP { get; set; } + public float PIS { get; set; } + public float COFINS { get; set; } + public float ICMS { get; set; } + public float Ilum_Publica { get; set; } + public float Multa { get; set; } + public float Credito { get; set; } + public float Outros { get; set; } + public float En_Reativa_Mvarh { get; set; } + public float Dem_Reativa_kvar { get; set; } + public float Bandeira_RS_MWh { get; set; } + public float Liminar_ICMS { get; set; } + public float Enc_conexao { get; set; } + public float FIC_DIC { get; set; } + //public string Hora_compliance { get; set; } + public float Dem_Fat_P { get; set; } + public float Dem_Fat_FP { get; set; } + public float Reativos_reais { get; set; } + public float Ultrapassagem_reais { get; set; } + public float Bandeira_reais { get; set; } + public float Compliance_calc { get; set; } + public bool Compliance_Correto { get; set; } + public bool Decl_DEVEC { get; set; } + public float Cred_livre { get; set; } + public string Coment_int { get; set; } + public string Coment_cli { get; set; } + public bool Lanc_aut { get; set; } + + } +} + diff --git a/Download Faturas/Download Faturas.csproj b/Download Faturas/Download Faturas.csproj new file mode 100644 index 0000000..83121ac --- /dev/null +++ b/Download Faturas/Download Faturas.csproj @@ -0,0 +1,16 @@ + + + + Exe + net6.0-windows + Download_Faturas + enable + enable + + + + + + + + diff --git a/Download Faturas/Program.cs b/Download Faturas/Program.cs new file mode 100644 index 0000000..cc30b3c --- /dev/null +++ b/Download Faturas/Program.cs @@ -0,0 +1,394 @@ +using System.Text; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Web; +using System.Text.RegularExpressions; +using System.IO; +using System.Data.OleDb; +using System.Globalization; + +namespace Download_Faturas +{ + public class Program + { +#if DEBUG + public const String log_faturas = @"X:\Back\Carteira x.x\4Docs\import.txt"; + public const String log_faturas2 = @"X:\Back\Carteira x.x\4Docs\import2.txt"; +#else + public const String log_faturas = "import.txt"; + public const String log_faturas2 = "import2.txt"; +#endif + public const string caminho_DB = "X:/Middle/Informativo Setorial/Modelo Word/BD1_dados cadastrais e faturas.accdb"; + private static HttpClient httpClient = new HttpClient(); + private static OleDbConnection conn = new(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + caminho_DB + ";Jet OLEDB:Database Password=gds21"); + private static OleDbCommand cmd = new(); + private static StreamReader sr = new StreamReader(log_faturas); + private static StreamWriter sw = new StreamWriter(log_faturas2); + private static string? fatura; + + public static async Task Main() + { + //Abre a conexao com o banco de dados + conn.Open(); + cmd.Connection = conn; + + //Loop entre as faturas pendentes + while ((fatura = sr.ReadLine()) != null) + { + string fatura_ID = fatura.Split(",")[0]; + string fatura_status = fatura.Split(",")[1]; + string fatura_arquivo = fatura.Split(",")[2]; + + //Verifica se a fatura foi processada e atualiza os valores para banco de dados + if (fatura_status == "DELAYED" | fatura_status == "ACTIONABLE" | fatura_status == "" | fatura_status == "UNIDADE CONSUMIDORA NÃO LOCALIZADA NO BD") + { + string token = "UFY4VWzqcHYcGNd0gkBOMFL9G5ZThV6gXBQIJ79F5HSqITzavz4Fe7iXvAbJLvZJ"; + //token = await req_token(); + HttpResponseMessage response = await status(token, fatura_ID); + JsonElement result = JsonDocument.Parse(response.Content.ReadAsStringAsync().Result).RootElement; + + //Verifica se a fatura foi processada e atualiza os valores para o banco de dados + bool multiple = result.TryGetProperty("multiple", out var _); + if (result.GetProperty("status").GetString() == "SUCCESS" & !multiple) + { + fatura_status = processar_fatura(result, fatura_ID, fatura_arquivo); + sw.WriteLine(fatura_ID + "," + fatura_status + "," + fatura_arquivo); + + } + else if (result.GetProperty("status").GetString() == "SUCCESS" & multiple) + { + var agrupadas_ID = result.GetProperty("children"); + + foreach (JsonElement individual_ID in agrupadas_ID.EnumerateArray()) + { + HttpResponseMessage response_individual = await status(token, individual_ID.ToString()); + JsonElement result_individual = JsonDocument.Parse(response_individual.Content.ReadAsStringAsync().Result).RootElement; + + if (result_individual.GetProperty("status").GetString() == "SUCCESS") + { + fatura_status = processar_fatura(result_individual, fatura_ID, fatura_arquivo); + sw.WriteLine(individual_ID.ToString() + "," + fatura_status + "," + fatura_arquivo); + } + else + { + sw.WriteLine(individual_ID.ToString() + "," + result_individual.GetProperty("status").GetString() + "," + fatura_arquivo); + } + } + } + else + { + sw.WriteLine(fatura_ID + "," + result.GetProperty("status").GetString() + "," + fatura_arquivo); + } + } + else + { + sw.WriteLine(fatura); + } + } + conn.Close(); + sr.Close(); + sw.Close(); + File.Move(log_faturas2, log_faturas, true); + } + public static string processar_fatura(JsonElement result, string fatura_ID, string fatura_arquivo) + { + //Variavel para armazenar os dados a serem lancados para a TUSD no BD + recordSet dadosTusd = new(); + + //Resultado da fatura processada + Rootobject parsedResult = JsonSerializer.Deserialize(result.GetProperty("result")); + + dadosTusd.Mes = int.Parse(parsedResult.dates.reading.periodUntil.AddDays(-15).ToString("yMM")); + + string uc = new Regex("^0+").Replace(parsedResult.locationNumber, ""); + + //Vinculo da fatura com os dados cadastrais + + string selectSQL = $"SELECT COUNT (Cod_Smart_unidade) FROM Dados_cadastrais WHERE Codigo_Instalacao = '{uc}'"; + + cmd.CommandText = selectSQL; + + var unidades = (int)cmd.ExecuteScalar(); + + if (unidades == 1) + { + selectSQL = $"SELECT Cod_Smart_unidade, PerfilCCEE, Submercado, Status_unidade, Grupo, Distribuidora, ICMS_TUSD, Demanda_P, Demanda_FP FROM Dados_cadastrais WHERE Codigo_Instalacao = '{uc}'"; + } + else + { + selectSQL = $"SELECT Cod_Smart_unidade, PerfilCCEE, Submercado, Status_unidade, Grupo, Distribuidora, ICMS_TUSD, Demanda_P, Demanda_FP FROM Dados_cadastrais WHERE (CNPJ_CPF LIKE '{parsedResult.customer.cnpj?.Substring(0, 8) ?? "NAN"}%' AND Codigo_Instalacao = '{uc}') OR (Razao_Social LIKE '{parsedResult.customer.name}' AND Codigo_Instalacao = '{uc}')"; + } + + cmd.CommandText = selectSQL; + + OleDbDataReader reader = cmd.ExecuteReader(); + + while (reader.Read()) + { + //Dados cadastrais + dadosTusd.Cod_Smart_unidade = long.Parse(reader["Cod_Smart_unidade"].ToString()); + dadosTusd.Perfil_CliqCCEE = reader["PerfilCCEE"].ToString(); + dadosTusd.Submercado = reader["Submercado"].ToString(); + dadosTusd.Ambiente = reader["Status_unidade"].ToString(); + dadosTusd.Grupo = reader["Grupo"].ToString(); + dadosTusd.Distribuidora = reader["Distribuidora"].ToString(); + dadosTusd.ICMS = float.Parse(reader["ICMS_TUSD"].ToString()); + dadosTusd.Dem_Cont_P = float.Parse(reader["Demanda_P"].ToString()); + dadosTusd.Dem_Cont_FP = float.Parse(reader["Demanda_FP"].ToString()); + } + reader.Close(); + + //Verifica se a fatura ja foi lançada + selectSQL = $"SELECT Cod_TUSD FROM Dados_TUSD WHERE Cod_TUSD = {long.Parse(dadosTusd.Cod_Smart_unidade.ToString() + dadosTusd.Mes.ToString())}"; + cmd.CommandText = selectSQL; + reader = cmd.ExecuteReader(); + bool tusdLanc = reader.HasRows; + reader.Close(); + if (dadosTusd.Cod_Smart_unidade == 0) + { + return "UNIDADE CONSUMIDORA NÃO LOCALIZADA NO BD"; + } + else if (tusdLanc) + { + return "FATURA DUPLICADA NO BD"; + } + else + { + //PIS e Cofins + string pisSQL = $"SELECT Distribuidoras_PIS.PIS, Distribuidoras_PIS.COFINS FROM Distribuidoras_geral INNER JOIN Distribuidoras_PIS ON Distribuidoras_geral.ID_dist = Distribuidoras_PIS.ID_dist WHERE Distribuidoras_PIS.Mes='{dadosTusd.Mes}' AND Distribuidoras_geral.Distribuidora='{dadosTusd.Distribuidora}'"; + + cmd.CommandText = pisSQL; + + reader = cmd.ExecuteReader(); + + while (reader.Read()) + { + //PIS e Cofins + dadosTusd.PIS = float.Parse(reader["PIS"].ToString()); + dadosTusd.COFINS = float.Parse(reader["COFINS"].ToString()); + } + reader.Close(); + + //Dados da fatura processada + dadosTusd.Cod_TUSD = long.Parse(dadosTusd.Cod_Smart_unidade.ToString() + dadosTusd.Mes.ToString()); + dadosTusd.Perfil = parsedResult.tariffModality == "blue" ? "AZUL" : "VERDE"; + dadosTusd.Valor = parsedResult.totalCharges; + dadosTusd.Inicio_Leitura = parsedResult.dates.reading.periodFrom; + dadosTusd.Fim_leitura = parsedResult.dates.reading.periodUntil; + dadosTusd.Hora_TUSD = DateTime.Now; + dadosTusd.Dem_Reativa_kvar = 0; + dadosTusd.Multa = 0; + dadosTusd.Credito = 0; + dadosTusd.Bandeira_RS_MWh = 0; + dadosTusd.FIC_DIC = 0; + dadosTusd.Enc_conexao = 0; + dadosTusd.Liminar_ICMS = 0; + dadosTusd.Outros = 0; + dadosTusd.Cred_livre = 0; + dadosTusd.Tempo_TUSD = 0; + dadosTusd.Lanc_aut = true; + dadosTusd.Rev_atual = true; + dadosTusd.Revisao = 0; + + //Loop entre os dados faturados na fatura + int j = 0; + foreach (Item item in parsedResult.items) + { + switch (item.type, item.period) + { + //Energia Ponta + case ("energy", "peak"): + dadosTusd.Consumo_P = item.billed / 1000; + break; + + //Energia Fora de Ponta + case ("energy", "off-peak"): + dadosTusd.Consumo_FP = item.billed / 1000; + break; + + //Demanda Ponta + case ("demand", "peak"): + dadosTusd.Dem_Cont_P = item.contract == 0 ? dadosTusd.Dem_Cont_P : item.contract; + break; + + //Demanda Fora de Ponta + case ("demand", "off-peak"): + dadosTusd.Dem_Cont_FP = item.contract == 0 ? dadosTusd.Dem_Cont_FP : item.contract; + break; + + //Ilum. publica + case ("publicLighting", _): + dadosTusd.Ilum_Publica = item.charge; + break; + + //Energia Reativa + case ("excessReactiveEnergy", _): + dadosTusd.En_Reativa_Mvarh = item.billed / 1000 + dadosTusd.En_Reativa_Mvarh; + break; + + //Demanda Reativa + case ("excessReactiveDemand", _): + dadosTusd.Dem_Reativa_kvar = item.billed; + break; + + //Bandeira Tarifaria + case ("flagSurcharge", _): + dadosTusd.Bandeira_RS_MWh = item.charge; + break; + + //Items não classificados + case ("other", _): + j++; + + //Exclui os items lançados anteriormente para a fatura + if (j == 1) + { + string deleteOthers = $"DELETE FROM Dados_TUSD_aux WHERE Cod_TUSD = {dadosTusd.Cod_TUSD}"; + cmd.CommandText = deleteOthers; + cmd.ExecuteNonQuery(); + } + //Insere os novos items + string insertOthers = "INSERT INTO Dados_TUSD_aux (Cod_TUSD,Id,Nome,Valor,Cod_lanc) VALUES (" + dadosTusd.Cod_TUSD + "," + j + ",'" + item.name + "'," + item.charge.ToString(new CultureInfo("en-US")) + "," + 0 + ")"; + cmd.CommandText = insertOthers; + cmd.ExecuteNonQuery(); + break; + } + } + + //Busca a demanda registrada nos itens medidos + foreach (Measureditem measuredItem in parsedResult.measuredItems) + { + switch (measuredItem.type, measuredItem.period) + { + case ("demand", "peak"): + dadosTusd.Dem_Reg_P = measuredItem.measured; + break; + case ("demand", "off-peak"): + dadosTusd.Dem_Reg_FP = measuredItem.measured; + break; + } + } + + var dados = dadosTusd.GetType().GetProperties(); + StringBuilder fields = new StringBuilder(); + StringBuilder values = new StringBuilder(); + + //Verifica se já existe a fatura lançada | atualizar fatura ou nova fatura + string selectTUSD = $"SELECT Cod_TUSD FROM Dados_TUSD WHERE Cod_TUSD = {dadosTusd.Cod_TUSD}"; + + cmd.CommandText = selectTUSD.ToString(); + + reader = cmd.ExecuteReader(); + + if (reader.Read()) + { + //Cria o comando para atualização da fatura + reader.Close(); + StringBuilder updateSQL = new StringBuilder("UPDATE Dados_TUSD SET "); + + //Loop por todos os dados ja obtidos + for (var i = 0; i < dados.Count(); i++) + { + //Adiciona o nome do campo + string field = dados[i].Name + "="; + + //Valor para o campo selecionado + var value = dados[i].GetValue(dadosTusd) ?? ""; + + //Adiciona '(aspas) para textos e datas + if (dados[i].PropertyType.Name == "String" ^ dados[i].PropertyType.Name == "DateTime") + { + value = "'" + (dados[i].GetValue(dadosTusd)?.ToString() ?? "") + "'"; + } + //Substitui ,(virgula) por .(ponto) + else if (dados[i].PropertyType.Name == "Single") + { + float valueFloat = (float)value; + value = valueFloat.ToString(new CultureInfo("en-US")); + } + + if (i > 0) + { + updateSQL.Append(","); + } + updateSQL.Append(field + value); + } + updateSQL.Append($" WHERE Cod_TUSD = {dadosTusd.Cod_TUSD}"); + cmd.CommandText = updateSQL.ToString(); + cmd.ExecuteNonQuery(); + } + else + { + //Cria o comando para lançar da fatura + reader.Close(); + StringBuilder insertSQL = new StringBuilder("INSERT INTO Dados_TUSD ("); + + //Loop pelo nome dos campos + for (var i = 0; i < dados.Count(); i++) + { + //Adiciona o nome do campo + string field = dados[i].Name; + + //Valor para o campo selecionado + var value = dados[i].GetValue(dadosTusd) ?? ""; + + //Adiciona '(aspas) para textos e datas + if (dados[i].PropertyType.Name == "String" ^ dados[i].PropertyType.Name == "DateTime") + { + value = "'" + (dados[i].GetValue(dadosTusd)?.ToString() ?? "") + "'"; + } + //Substitui ,(virgula) por .(ponto) + else if (dados[i].PropertyType.Name == "Single") + { + float valueFloat = (float)value; + value = valueFloat.ToString(new CultureInfo("en-US")); + } + + if (i > 0) + { + fields.Append(","); + values.Append(","); + } + fields.Append(field); + values.Append(value); + } + insertSQL.Append(fields) + .Append(") VALUES (") + .Append(values) + .Append(")"); + + cmd.CommandText = insertSQL.ToString(); + cmd.ExecuteNonQuery(); + } + return "FATURA INCLUIDA NO BD"; + } + } + public static async Task req_token() + { + var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.4docs.cloud/v2/oauth2/token"); + + var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("smart:vnqtvmesikjzyipc")); + request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}"); + + request.Content = new StringContent("grant_type=client_credentials"); + request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded"); + + var response = await httpClient.SendAsync(request); + + return JsonDocument.Parse(response.Content.ReadAsStringAsync().Result).RootElement.GetProperty("access_token").GetString(); + } + public static async Task status(string token, string id) + { + + var request = new HttpRequestMessage(new HttpMethod("GET"), $"https://api.4docs.cloud/v2/request/status?id={id}"); + + request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {token}"); + + var response = await httpClient.SendAsync(request); + + return response; + + } + } +} + diff --git a/Faturas 4docs.sln b/Faturas 4docs.sln new file mode 100644 index 0000000..6d85753 --- /dev/null +++ b/Faturas 4docs.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32616.157 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Upload Faturas", "Upload Faturas\Upload Faturas.csproj", "{38C7EBAA-5FEE-40DA-BFEE-12BEB4A1EA46}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Download Faturas", "Download Faturas\Download Faturas.csproj", "{580DACAB-DBAB-402D-AE0F-BA42A205F812}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {38C7EBAA-5FEE-40DA-BFEE-12BEB4A1EA46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {38C7EBAA-5FEE-40DA-BFEE-12BEB4A1EA46}.Debug|Any CPU.Build.0 = Debug|Any CPU + {38C7EBAA-5FEE-40DA-BFEE-12BEB4A1EA46}.Release|Any CPU.ActiveCfg = Release|Any CPU + {38C7EBAA-5FEE-40DA-BFEE-12BEB4A1EA46}.Release|Any CPU.Build.0 = Release|Any CPU + {580DACAB-DBAB-402D-AE0F-BA42A205F812}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {580DACAB-DBAB-402D-AE0F-BA42A205F812}.Debug|Any CPU.Build.0 = Debug|Any CPU + {580DACAB-DBAB-402D-AE0F-BA42A205F812}.Release|Any CPU.ActiveCfg = Release|Any CPU + {580DACAB-DBAB-402D-AE0F-BA42A205F812}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {B30416C0-8831-4849-A76F-187E364F13C1} + EndGlobalSection +EndGlobal diff --git a/Upload Faturas/Program.cs b/Upload Faturas/Program.cs new file mode 100644 index 0000000..c64773d --- /dev/null +++ b/Upload Faturas/Program.cs @@ -0,0 +1,187 @@ +using System.Text; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Web; +using System.Text.RegularExpressions; +using System.IO; + +public class program +{ +#if DEBUG + public const String log_faturas = @"X:\Back\Carteira x.x\4Docs\import.txt"; +#else + public const String log_faturas = "import.txt"; +#endif + + private static HttpClient httpClient = new HttpClient(); + public static async Task Main() + { + for (int i = 1; i < 3; i++) + { + for (int j = 1; j < 7; j++) + { + DirectoryInfo pasta = new DirectoryInfo(@"X:\Middle\Carteira " + i + @"\Carteira " + i + "." + j + @"\Faturas fourdocs\1 - INDIVIDUAIS"); + DirectoryInfo pasta_agrupadas = new DirectoryInfo(@"X:\Middle\Carteira " + i + @"\Carteira " + i + "." + j + @"\Faturas fourdocs\2 - AGRUPADAS"); + + if (ler_pasta(pasta, agrupada: false).Result) + { + await ler_pasta(pasta_agrupadas, agrupada: true); + } + } + } + + + //string? fim = "n"; + + //while (fim != "s") + //{ + // Console.WriteLine("Escolha a carteira: (todas - 1.1 - 1.2 - 1.3 - ...)\n"); + // string? carteira = Console.ReadLine(); + + // if (carteira != null & carteira!.Length == 3) + // { + // DirectoryInfo pasta = new DirectoryInfo(@"X:\Middle\Carteira " + carteira[0] + @"\Carteira " + carteira + @"\Faturas fourdocs"); + // DirectoryInfo pasta_agrupadas = new DirectoryInfo(@"X:\Middle\Carteira " + carteira[0] + @"\Carteira " + carteira + @"\Faturas fourdocs\Agrupadas"); + + // if (ler_pasta(pasta, agrupada: false).Result) + // { + // if (ler_pasta(pasta_agrupadas, agrupada: true).Result) + // { + // Console.WriteLine("\nDeseja finalizar? (s/n)\n"); + // fim = Console.ReadLine(); + // Console.WriteLine("\n"); + // } + // else + // { + // Console.WriteLine("\nAgrupadas não localizadas\n"); + // } + // } + // else + // { + // Console.WriteLine("\nCarteira não encontrada\n"); + // } + // } + // else if (carteira == "todas") + // { + // for (int i = 1; i < 3; i++) + // { + // for (int j = 1; j < 7; j++) + // { + // DirectoryInfo pasta = new DirectoryInfo(@"X:\Middle\Carteira " + i + @"\Carteira " + i + "." + j + @"\Faturas fourdocs"); + // DirectoryInfo pasta_agrupadas = new DirectoryInfo(@"X:\Middle\Carteira " + i + @"\Carteira " + i + "." + j + @"\Faturas fourdocs\Agrupadas"); + + // if (ler_pasta(pasta, agrupada: false).Result) + // { + // if (!ler_pasta(pasta_agrupadas, agrupada: true).Result) + // { + // Console.WriteLine($"\nCarteira {i}.{j} Agrupada - Erro"); + // } + // } + // else + // { + // Console.WriteLine($"\nCarteira {i}.{j} - Erro"); + // } + // } + // } + // Console.WriteLine("\nDeseja finalizar? (s/n)\n"); + // fim = Console.ReadLine(); + // Console.WriteLine("\n"); + // } + // else + // { + // Console.WriteLine("\nCarteira não encontrada\n"); + // } + //} + //await Task.Delay(1); + } + + public static async Task ler_pasta(DirectoryInfo pasta, bool agrupada) + { + if (pasta.Exists) + { + string token = "UFY4VWzqcHYcGNd0gkBOMFL9G5ZThV6gXBQIJ79F5HSqITzavz4Fe7iXvAbJLvZJ"; + //token = await req_token(); + FileInfo[] faturas = pasta.GetFiles("*.pdf"); + + StreamWriter sw = new StreamWriter(log_faturas, true); + + foreach (FileInfo fatura in faturas) + { + if (!IsFileLocked(fatura)) + { + HttpResponseMessage response = await send_fatura(token, fatura.FullName, agrupada); + if ((int)response.StatusCode == 202) + { + var ID = JsonDocument.Parse(response.Content.ReadAsStringAsync().Result).RootElement.GetProperty("requestId"); + fatura.MoveTo(fatura.Directory?.Parent?.FullName + $@"\3 - PROCESSANDO\{ID} - " + fatura.Name); + sw.Write(ID); + sw.Write(","); + sw.Write(","); + sw.WriteLine(fatura.FullName); + } + } + } + sw.Close(); + return true; + } + else + { + return false; + } + } + + public static async Task req_token() + { + var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.4docs.cloud/v2/oauth2/token"); + + var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("smart:vnqtvmesikjzyipc")); + request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}"); + + request.Content = new StringContent("grant_type=client_credentials"); + request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded"); + + var response = await httpClient.SendAsync(request); + + return JsonDocument.Parse(response.Content.ReadAsStringAsync().Result).RootElement.GetProperty("access_token").GetString(); + } + + public static async Task send_fatura(string token, string fatura, bool agrupada) + { + var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.4docs.cloud/v2/parse"); + + request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {token}"); + + var multipartContent = new MultipartFormDataContent(); + multipartContent.Add(new ByteArrayContent(File.ReadAllBytes(fatura)), @"""file""", @$"""{Path.GetFileName(fatura)}"""); + multipartContent.ElementAt(0).Headers.Add("Content-Type", "application/pdf"); + + string newPath = fatura.Substring(0, fatura.Length - 4) + " Finalizado.pdf"; + + multipartContent.Add(new StringContent($"{{\"callbackUrl\":\"https://api.4docs.cloud/v2/null\",\"pipelineName\":\"energy\",\"multiple\":{agrupada.ToString().ToLower()},\"clientData\":{{\"fatura_PATH\":\"{newPath}\"}}}}"), "json"); + + request.Content = multipartContent; + + return await httpClient.SendAsync(request); + } + public static bool IsFileLocked(FileInfo file) + { + try + { + using (FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None)) + { + stream.Close(); + } + } + catch (IOException) + { + //the file is unavailable because it is: + //still being written to + //or being processed by another thread + //or does not exist (has already been processed) + return true; + } + + //file is not locked + return false; + } +} diff --git a/Upload Faturas/Upload Faturas.csproj b/Upload Faturas/Upload Faturas.csproj new file mode 100644 index 0000000..0895b30 --- /dev/null +++ b/Upload Faturas/Upload Faturas.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + Download_Faturas + enable + enable + + + + + + +