396 lines
18 KiB
C#
396 lines
18 KiB
C#
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).status;
|
|
sw.WriteLine(fatura_ID + "," + fatura_status + "," + fatura_arquivo);
|
|
using () ;
|
|
}
|
|
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).status;
|
|
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 status, string fatura_arquivo) 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<Rootobject>(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<string> 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<HttpResponseMessage> 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;
|
|
|
|
}
|
|
}
|
|
}
|
|
|