746 lines
33 KiB
C#
746 lines
33 KiB
C#
namespace Download_Faturas
|
|
{
|
|
using System.Data.OleDb;
|
|
using System.Globalization;
|
|
using System.Net.Http.Headers;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.RegularExpressions;
|
|
|
|
public class Program
|
|
{
|
|
#if DEBUG
|
|
public const string LogFaturas = @"X:\Back\Carteira x.x\4Docs\import.txt";
|
|
public const string LogFaturas2 = @"X:\Back\Carteira x.x\4Docs\import2.txt";
|
|
#else
|
|
public const String LogFaturas = "import.txt";
|
|
public const String LogFaturas2 = "import2.txt";
|
|
#endif
|
|
public const string CaminhoDB = "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=" + CaminhoDB + ";Jet OLEDB:Database Password=gds21");
|
|
private static OleDbCommand cmd = new ();
|
|
private static StreamReader sr = new StreamReader(LogFaturas);
|
|
private static StreamWriter sw = new StreamWriter(LogFaturas2);
|
|
private static string? fatura;
|
|
|
|
public static void 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 == string.Empty | fatura_status == "UNIDADE CONSUMIDORA NÃO LOCALIZADA NO BD")
|
|
{
|
|
// Verifica se a fatura foi processada e atualiza os valores para o banco de dados
|
|
Fatura fatura = new Fatura(fatura_ID, fatura_arquivo, httpClient);
|
|
|
|
// bool agrupada = fatura.Agrupada;
|
|
// string status = fatura.Status;
|
|
if (fatura.Status == "SUCCESS" & !fatura.Agrupada)
|
|
{
|
|
// (string? status, string? pasta_middle, string? uc, int mes) fatura_processamento = processar_fatura(result, fatura_ID, fatura_arquivo);
|
|
// fatura_status = fatura_processamento.status;
|
|
fatura.Processar(cmd);
|
|
sw.WriteLine(fatura_ID + "," + fatura_status + "," + fatura_arquivo);
|
|
|
|
// mover_fatura(fatura_processamento, fatura_arquivo);
|
|
}
|
|
else if (fatura.Status == "SUCCESS" & fatura.Agrupada)
|
|
{
|
|
foreach (JsonElement individual_ID in fatura.Agrupada_children)
|
|
{
|
|
Fatura faturaIndividual = new Fatura(individual_ID.ToString(), fatura_arquivo, httpClient);
|
|
|
|
if (faturaIndividual.Status == "SUCCESS")
|
|
{
|
|
faturaIndividual.Processar(cmd);
|
|
sw.WriteLine(individual_ID.ToString() + "," + fatura_status + "," + fatura_arquivo);
|
|
|
|
// mover fatura
|
|
}
|
|
else
|
|
{
|
|
sw.WriteLine(individual_ID.ToString() + "," + result_individual.GetProperty("status").GetString() + "," + fatura_arquivo);
|
|
|
|
// mover fatura
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
sw.WriteLine(fatura_ID + "," + result.GetProperty("status").GetString() + "," + fatura_arquivo);
|
|
|
|
// mover fatura
|
|
}
|
|
}
|
|
else
|
|
{
|
|
sw.WriteLine(fatura);
|
|
}
|
|
}
|
|
|
|
conn.Close();
|
|
sr.Close();
|
|
sw.Close();
|
|
File.Move(LogFaturas2, LogFaturas, true);
|
|
}
|
|
|
|
/*public static (string? status, string? pasta_middle, string? uc, int mes) 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, string.Empty);
|
|
|
|
// 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, Caminho_NFs 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, Caminho_NFs 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();
|
|
|
|
string pasta_faturas = "";
|
|
|
|
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());
|
|
pasta_faturas = reader["Caminho_NFs"].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", pasta_faturas, uc, dadosTusd.Mes);
|
|
}
|
|
else if (tusdLanc)
|
|
{
|
|
return ("FATURA DUPLICADA NO BD", pasta_faturas, uc, dadosTusd.Mes);
|
|
}
|
|
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", pasta_faturas, uc, dadosTusd.Mes);
|
|
}
|
|
}*/
|
|
/*public static void mover_fatura((string? status, string? pasta_middle, string? uc, int mes) fatura, string fatura_arquivo, bool multiple = false)
|
|
{
|
|
switch (fatura.status)
|
|
{
|
|
case "":
|
|
|
|
break;
|
|
case "a":
|
|
|
|
break;
|
|
case "b":
|
|
|
|
break;
|
|
}
|
|
}
|
|
*/
|
|
}
|
|
|
|
class Fatura
|
|
{
|
|
/* A fatura deve ter alguma propriedades públicas: Local de origem, local de destino, Status do processamento
|
|
* Outras propriedas privadas: ID, Mes, agrupada, token, UC
|
|
*
|
|
*
|
|
*
|
|
*/
|
|
|
|
private string token = "UFY4VWzqcHYcGNd0gkBOMFL9G5ZThV6gXBQIJ79F5HSqITzavz4Fe7iXvAbJLvZJ";
|
|
|
|
private JsonElement faturaParsed;
|
|
|
|
public Fatura(string id, string fatura_path, HttpClient httpClient)
|
|
{
|
|
// Utilizado para gerar novo token
|
|
// this.token = Req_token(httpClient).ToString();
|
|
HttpResponseMessage fatura_response = this.GetStatus(httpClient, this.token, id);
|
|
if (fatura_response.IsSuccessStatusCode)
|
|
{
|
|
this.faturaParsed = JsonDocument.Parse(fatura_response.Content.ReadAsStringAsync().Result).RootElement;
|
|
this.Agrupada = this.faturaParsed.TryGetProperty("multiple", out var _);
|
|
this.Status = this.faturaParsed.GetProperty("status").GetString() !;
|
|
if (this.Agrupada)
|
|
{
|
|
this.Agrupada_children = this.faturaParsed.GetProperty("children").EnumerateArray();
|
|
}
|
|
}
|
|
}
|
|
|
|
public string? Status { get; private set; }
|
|
|
|
public string? Pasta_middle { get; private set; }
|
|
|
|
public string? UC { get; private set; }
|
|
|
|
public int Mes { get; private set; }
|
|
|
|
public bool Agrupada { get; private set; }
|
|
|
|
public JsonElement.ArrayEnumerator Agrupada_children { get; private set; }
|
|
|
|
public void Processar(OleDbCommand cmd)
|
|
{
|
|
// 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>(this.faturaParsed.GetProperty("result")) !;
|
|
|
|
dadosTusd.Mes = int.Parse(parsedResult.dates.reading.periodUntil.AddDays(-15).ToString("yMM"));
|
|
|
|
string uc = new Regex("^0+").Replace(parsedResult.locationNumber, string.Empty);
|
|
|
|
// 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, Caminho_NFs 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, Caminho_NFs 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());
|
|
this.Pasta_middle = reader["Caminho_NFs"].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)
|
|
{
|
|
this.Status = "UNIDADE CONSUMIDORA NÃO LOCALIZADA NO BD";
|
|
this.UC = uc;
|
|
this.Mes = dadosTusd.Mes;
|
|
}
|
|
else if (tusdLanc)
|
|
{
|
|
this.Status = "FATURA DUPLICADA NO BD";
|
|
this.UC = uc;
|
|
this.Mes = dadosTusd.Mes;
|
|
}
|
|
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) ?? string.Empty;
|
|
|
|
// Adiciona '(aspas) para textos e datas
|
|
if (dados[i].PropertyType.Name == "String" ^ dados[i].PropertyType.Name == "DateTime")
|
|
{
|
|
value = "'" + (dados[i].GetValue(dadosTusd)?.ToString() ?? string.Empty) + "'";
|
|
}
|
|
|
|
// 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) ?? string.Empty;
|
|
|
|
// Adiciona '(aspas) para textos e datas
|
|
if (dados[i].PropertyType.Name == "String" ^ dados[i].PropertyType.Name == "DateTime")
|
|
{
|
|
value = "'" + (dados[i].GetValue(dadosTusd)?.ToString() ?? string.Empty) + "'";
|
|
}
|
|
|
|
// 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();
|
|
}
|
|
|
|
this.Status = "FATURA INCLUIDA NO BD";
|
|
this.UC = uc;
|
|
this.Mes = dadosTusd.Mes;
|
|
}
|
|
}
|
|
|
|
public void Mover()
|
|
{
|
|
}
|
|
|
|
private HttpResponseMessage GetStatus(HttpClient httpClient, 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 = httpClient.Send(request);
|
|
return response;
|
|
}
|
|
|
|
private string Req_token(HttpClient httpClient)
|
|
{
|
|
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() !;
|
|
}
|
|
}
|
|
} |