Correção do json de envio para indicar corretamente o local da fatura aleém de "escapar" corretamente.
184 lines
7.0 KiB
C#
184 lines
7.0 KiB
C#
// <copyright file="Program.cs" company="PlaceholderCompany">
|
|
// Copyright (c) PlaceholderCompany. All rights reserved.
|
|
// </copyright>
|
|
|
|
namespace Download_Faturas
|
|
{
|
|
using System.Net;
|
|
using System.Net.Http.Headers;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
|
|
/// <summary>
|
|
/// Main program class.
|
|
/// </summary>
|
|
public class Program
|
|
{
|
|
#if DEBUG
|
|
/// <summary>
|
|
/// Path to the log file for invoices.
|
|
/// </summary>
|
|
public const string LogFaturas = @"X:\Back\Carteira x.x\4Docs\import.txt";
|
|
#else
|
|
public const string LogFaturas = "import.txt";
|
|
#endif
|
|
|
|
private static readonly HttpClient HttpClient = new ();
|
|
|
|
/// <summary>
|
|
/// Main entry point of the program.
|
|
/// </summary>
|
|
public static void Main()
|
|
{
|
|
for (int i = 1; i < 3; i++)
|
|
{
|
|
for (int j = 1; j < 7; j++)
|
|
{
|
|
DirectoryInfo pasta = new (@"X:\Middle\Carteira " + i + @"\Carteira " + i + "." + j + @"\Faturas fourdocs\1 - INDIVIDUAIS");
|
|
DirectoryInfo pasta_agrupadas = new (@"X:\Middle\Carteira " + i + @"\Carteira " + i + "." + j + @"\Faturas fourdocs\2 - AGRUPADAS");
|
|
|
|
if (LerPasta(pasta, agrupada: false))
|
|
{
|
|
LerPasta(pasta_agrupadas, agrupada: true);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Reads the specified folder and processes the invoices.
|
|
/// </summary>
|
|
/// <param name="pasta">The directory to read invoices from.</param>
|
|
/// <param name="agrupada">Indicates whether the invoices are grouped.</param>
|
|
/// <returns>True if the folder was read successfully; otherwise, false.</returns>
|
|
public static bool LerPasta(DirectoryInfo pasta, bool agrupada)
|
|
{
|
|
if (pasta.Exists)
|
|
{
|
|
string token = "UFY4VWzqcHYcGNd0gkBOMFL9G5ZThV6gXBQIJ79F5HSqITzavz4Fe7iXvAbJLvZJ";
|
|
|
|
// token = await req_token();
|
|
FileInfo[] faturas = pasta.GetFiles("*.pdf");
|
|
StreamWriter sw = new (LogFaturas, true);
|
|
|
|
foreach (FileInfo fatura in faturas)
|
|
{
|
|
if (!IsFileLocked(fatura))
|
|
{
|
|
HttpResponseMessage response = SendFatura(token, fatura.FullName, agrupada);
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
var iD = JsonDocument.Parse(response.Content.ReadAsStringAsync().Result).RootElement.GetProperty("requestId");
|
|
fatura.MoveTo(fatura.Directory?.Parent?.FullName + $@"\3 - PROCESSANDO\ID {iD} - " + fatura.Name.Replace(",", string.Empty));
|
|
sw.Write(iD);
|
|
sw.Write(",");
|
|
sw.Write(",");
|
|
sw.WriteLine(fatura.FullName);
|
|
}
|
|
}
|
|
}
|
|
|
|
sw.Close();
|
|
return true;
|
|
}
|
|
else
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Requests an authentication token.
|
|
/// </summary>
|
|
/// <returns>The authentication token as a string.</returns>
|
|
public static string? ReqToken()
|
|
{
|
|
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 = HttpClient.Send(request);
|
|
|
|
return JsonDocument.Parse(response.Content.ReadAsStringAsync().Result).RootElement.GetProperty("access_token").GetString();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sends an invoice to the API for processing.
|
|
/// </summary>
|
|
/// <param name="token">The authentication token.</param>
|
|
/// <param name="fatura">The path to the invoice file.</param>
|
|
/// <param name="agrupada">Indicates whether the invoices are grouped.</param>
|
|
/// <returns>The HTTP response from the API.</returns>
|
|
public static HttpResponseMessage SendFatura(string token, string fatura, bool agrupada)
|
|
{
|
|
var handler = new HttpClientHandler
|
|
{
|
|
// Proxy = new WebProxy("http://127.0.0.1:8888"),
|
|
// UseProxy = true,
|
|
// ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
|
|
};
|
|
|
|
using (var httpClient = new HttpClient(handler))
|
|
{
|
|
var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.4docs.cloud/v2/parse");
|
|
|
|
request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {token}");
|
|
|
|
var multipartContent = new MultipartFormDataContent
|
|
{
|
|
{ new ByteArrayContent(File.ReadAllBytes(fatura)), @"""file""", @$"""{Path.GetFileName(fatura)}""" },
|
|
};
|
|
multipartContent.ElementAt(0).Headers.Add("Content-Type", "application/pdf");
|
|
|
|
var payload = new
|
|
{
|
|
callbackUrl = "https://4docs.webhook.smartenergia.com.br/api",
|
|
pipelineName = "energy",
|
|
multiple = agrupada,
|
|
clientData = new
|
|
{
|
|
fatura_PATH = fatura.Replace(",", string.Empty).Replace("1 - INDIVIDUAIS", "3 - PROCESSANDO"),
|
|
},
|
|
};
|
|
|
|
var json = JsonSerializer.Serialize(payload);
|
|
multipartContent.Add(new StringContent(json, Encoding.UTF8, "application/json"), "json");
|
|
|
|
request.Content = multipartContent;
|
|
|
|
return httpClient.Send(request);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Checks if a file is locked.
|
|
/// </summary>
|
|
/// <param name="file">The file to check.</param>
|
|
/// <returns>True if the file is locked; otherwise, false.</returns>
|
|
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;
|
|
}
|
|
}
|
|
} |