Merge branch 'chore/no-ref/new-tusd-logic-validation'

This commit is contained in:
Giuliano Paschoalino 2025-11-25 17:34:26 -03:00
commit 9c4a59b47b
11 changed files with 2051 additions and 133 deletions

3
.gitignore vendored
View File

@ -362,4 +362,5 @@ MigrationBackup/
# Fody - auto-generated XML schema
FodyWeavers.xsd
.aider*
.history/
.history
.vscode

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0-windows10.0.17763.0</TargetFramework>
<RootNamespace>Download_Faturas.Tests</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="xunit" Version="2.9.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Download Faturas\Download Faturas.csproj" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,145 @@
using System.Data.OleDb;
using System.Numerics;
using System.Text.Json;
using Download_Faturas;
namespace Download_Faturas1.Tests
{
public class FaturaIntegrationTests
{
private const string Token = "UFY4VWzqcHYcGNd0gkBOMFL9G5ZThV6gXBQIJ79F5HSqITzavz4Fe7iXvAbJLvZJ";
private static readonly HttpClient httpClient = new HttpClient();
[Fact]
public async Task CompareFaturaWithFaturaOld_ShouldReportDifferences()
{
// Sample fatura IDs to test (replace with real IDs or fetch dynamically)
var faturaIds = LoadCsvColumn("../../../../Download Faturas.Tests/4Docs_2025_07.csv", 0);
var differences = new List<string>();
differences.Add($"FaturaId\tDistribuidora\toldConsumo_P\tnewConsumo_P\toldConsumo_FP\tnewConsumo_FP\toldDem_Reg_P\tnewDem_Reg_P\toldDem_Reg_FP\tnewDem_Reg_FP\toldEn_Reativa_Mvarh\tnewEn_Reativa_Mvarh");
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=X:/Middle/Informativo Setorial/Modelo Word/BD1_Testes.accdb;Jet OLEDB:Database Password=gds21"))
{
// Open the connection to the test database
conn.Open();
foreach (var faturaId in faturaIds)
{
// Retrieve fatura JSON from 4Docs API
var request = new HttpRequestMessage(HttpMethod.Get, $"https://api.4docs.cloud/v2/request/status?id={faturaId}");
request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {Token}");
var response = await httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode) continue;
var json = await response.Content.ReadAsStringAsync();
var faturaParsed = JsonDocument.Parse(json).RootElement;
int? pagina;
// Process with old logic (FaturaOld)
var faturaOld = new FaturaOld(faturaId, faturaParsed);
// Process with new logic (Fatura)
var fatura = new Fatura(faturaId, faturaParsed);
faturaOld.Processar(conn); // This will write to DB, but we want to compare without writing
var oldVal = GetDadosTusd(conn, faturaOld.cod_tusd);
DeleteTusdRecords(conn, faturaOld.cod_tusd); // Delete old TUSD records before processing
fatura.Processar(conn); // This will also write to DB, but we want to compare without writing
var newVal = GetDadosTusd(conn, fatura.cod_tusd);
DeleteTusdRecords(conn, fatura.cod_tusd); // Delete old TUSD records before processing
if (!string.Equals(newVal, oldVal))
{
differences.Add($"{faturaId}\t{oldVal.Distribuidora}\t{oldVal.Consumo_P}\t{newVal.Consumo_P}\t{oldVal.Consumo_FP}\t{newVal.Consumo_FP}\t{oldVal.Dem_Reg_P}\t{newVal.Dem_Reg_P}\t{oldVal.Dem_Reg_FP}\t{newVal.Dem_Reg_FP}\t{oldVal.En_Reativa_Mvarh}\t{newVal.En_Reativa_Mvarh}");
}
}
}
if (differences.Count > 1)
{
WriteCsv("../../../../Download Faturas.Tests/divergencias.csv", differences);
}
Assert.True(differences.Count == 0, $"Differences found between Fatura and FaturaOld:\n{string.Join("\n", differences)}");
}
void DeleteTusdRecords(OleDbConnection conn, double codTusd)
{
// Deletes TUSD records based on cod_tusd
string sqlQuery = "DELETE FROM Dados_TUSD WHERE Cod_TUSD = ?";
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
cmd.Parameters.AddWithValue("?", codTusd);
cmd.ExecuteNonQuery();
}
}
RecordSet GetDadosTusd(OleDbConnection conn, double codTusd)
{
RecordSet dadosTusd = new RecordSet();
// Retrieves TUSD records based on cod_tusd
string sqlQuery = "SELECT * FROM Dados_TUSD WHERE Cod_TUSD = ?";
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
cmd.Parameters.AddWithValue("?", codTusd);
using (OleDbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// Dados Tusd
;
dadosTusd.Cod_TUSD = double.Parse(reader["Cod_TUSD"].ToString());
dadosTusd.Mes = int.Parse(reader["Mes"].ToString());
dadosTusd.Distribuidora = reader["Distribuidora"].ToString();
dadosTusd.Grupo = reader["Grupo"].ToString();
dadosTusd.Perfil = reader["Perfil"].ToString();
dadosTusd.Inicio_Leitura = DateTime.Parse(reader["Inicio_Leitura"].ToString());
dadosTusd.Fim_leitura = DateTime.Parse(reader["Fim_leitura"].ToString());
dadosTusd.Valor = float.Parse(reader["Valor"].ToString());
dadosTusd.Consumo_P = float.Parse(reader["Consumo_P"].ToString());
dadosTusd.Consumo_FP = float.Parse(reader["Consumo_FP"].ToString());
dadosTusd.Dem_Reg_P = float.Parse(reader["Dem_Reg_P"].ToString());
dadosTusd.Dem_Reg_FP = float.Parse(reader["Dem_Reg_FP"].ToString());
dadosTusd.Dem_Cont_P = float.Parse(reader["Dem_Cont_P"].ToString());
dadosTusd.Dem_Cont_FP = float.Parse(reader["Dem_Cont_FP"].ToString());
dadosTusd.En_Reativa_Mvarh = float.Parse(reader["En_Reativa_Mvarh"].ToString());
dadosTusd.Dem_Reativa_kvar = float.Parse(reader["Dem_Reativa_kvar"].ToString());
}
}
}
return dadosTusd;
}
//load csv column
List<string> LoadCsvColumn(string filePath, int columnIndex)
{
var columnData = new List<string>();
using (var reader = new StreamReader(filePath))
{
while (!reader.EndOfStream)
{
// skip first line (header)
reader.ReadLine();
var line = reader.ReadLine();
if (line != null)
{
var values = line.Split('\t');
if (values.Length > columnIndex && values[3] == "\"API\"")
{
columnData.Add(values[columnIndex].Replace("\"", "").Trim());
}
}
}
}
return columnData;
}
//write data to csv
void WriteCsv(string filePath, List<string> data)
{
using (var writer = new StreamWriter(filePath))
{
foreach (var item in data)
{
writer.WriteLine(item);
}
}
}
}
}

View File

@ -0,0 +1,103 @@
FaturaId Distribuidora oldConsumo_P newConsumo_P oldConsumo_FP newConsumo_FP oldDem_Reg_P newDem_Reg_P oldDem_Reg_FP newDem_Reg_FP oldEn_Reativa_Mvarh newEn_Reativa_Mvarh
2661629 ESCELSA 4,488885 4,488885 42,093967 42,093967 102,5328 102,5328 110,7984 110,7984 0,023591401 0,023591401
2661627 0 0 0 0 0 0 0 0 0 0
2661625 0 0 0 0 0 0 0 0 0 0
2661623 0 0 0 0 0 0 0 0 0 0
2661621 0 0 0 0 0 0 0 0 0 0
2661619 0 0 0 0 0 0 0 0 0 0
2661617 0 0 0 0 0 0 0 0 0 0
2661615 0 0 0 0 0 0 0 0 0 0
2661613 COELBA 0,41380998 0,41380998 27,502321 27,502321 8,29 8,29 364,9 364,9 0 0
2661610 ESCELSA 0,095844 0,095844 4,78716 4,78716 4,536 4,536 140,616 140,616 1,9076821 1,9076821
2660716 COPEL 19,12 19,12 204,665 204,665 0 0 477,79 477,79 0,001 0,001
2659047 ELETROPAULO 0 0 0,88 0,88 0 0 0 0 0 0
2659045 ELETROPAULO 0 0 14,909 14,909 0 0 0 0 0 0
2657257 LIGHT 0 4,619 44,937 44,937 0 0 114 114 0 0
2657255 0 0 0 0 0 0 0 0 0 0
2657253 ELETROPAULO 0 0 0,735 0,735 0 0 0 0 0 0
2657251 ELETROPAULO 0 0 1,926 1,926 0 0 0 0 0 0
2657249 ELETROPAULO 0 0 2,427 2,427 0 0 0 0 0 0
2657247 ESCELSA 12,808945 12,808945 112,56336 112,56336 308,16 308,16 371,52 371,52 1,2908161 1,2908161
2657245 CEMIG 2,045 2,045 0 42,366 74 74 116 116 3,7159998 3,7159998
2657243 AMPLA 0,17639999 0,17639999 1,722 1,722 6,38 6,38 8,73 8,73 0,120288 0,120288
2657241 LIGHT 0 12,957 118,419 118,419 0 0 406 406 0,632 0,632
2651045 CEPISA 2,14103 2,14103 26,00794 26,00794 57,81 57,81 64,01125 64,01125 0,01244 0,01244
2651043 CEPISA 2,9558 2,9558 40,134693 40,134693 76,26 76,26 88,9085 88,9085 0,00168 0,00168
2651041 CEPISA 2,56523 2,56523 27,377981 27,377981 49,4665 49,4665 60,5775 60,5775 0,27462 0,27462
2651039 CEPISA 3,291 3,291 29,207449 29,207449 68,265 68,265 70,18175 70,18175 0,00016 0,00016
2651037 CEPISA 3,45336 3,45336 30,65442 30,65442 69,618 69,618 73,60525 73,60525 0 0
2651035 CEPISA 3,84917 3,84917 35,64043 35,64043 78,1255 78,1255 83,2505 83,2505 0,13628 0,13628
2651033 CEPISA 6,91395 6,91395 58,289288 58,289288 142,8235 142,8235 146,96451 146,96451 0 0
2651031 CEPISA 6,8126497 6,8126497 60,74608 60,74608 128,3095 128,3095 129,49849 129,49849 0,14518 0,14518
2651029 CEPISA 6,52224 6,52224 61,94176 61,94176 139,6255 139,6255 144,35075 144,35075 1,37341 1,37341
2651027 0 0 0 0 0 0 0 0 0 0
2651025 LIGHT 0 2,916 155,358 155,358 0 0 1156 1156 5,676 5,676
2651023 CEAL 2,33626 0 19,12764 0 52,808 51,52 65,6 64 0 0
2651021 0 0 0 0 0 0 0 0 0 0
2651019 LIGHT 0 9,416 101,152 101,152 0 0 226 226 0,148 0,148
2651017 ESCELSA 0 0 0 0 0 0 0 0 0 0
2648795 CEMAR 4,1178102 4,1178102 21,61643 21,61643 227,81 227,81 219,24 219,24 0,01172 0,01172
2648793 ESCELSA 0,495684 0,495684 9,642744 9,642744 45,072 45,072 72,288 72,288 1,79064 1,79064
2648791 ESCELSA 7,4809437 7,4809437 65,1681 65,1681 178,128 178,128 212,256 212,256 0,68979603 0,68979603
2648789 ESCELSA 1,5292467 1,5292467 17,503773 17,503773 54,7104 54,7104 62,0904 62,0904 0,2139093 0,2139093
2648787 ESCELSA 1,639713 1,639713 15,435602 15,435602 35,3748 35,3748 39,310802 39,310802 0 0
2648785 ESCELSA 1,7095032 1,7095032 10,781343 10,781343 76,26 76,26 92,299194 92,299194 0,0020418 0,0020418
2648783 ESCELSA 1,9161924 1,9161924 14,906247 14,906247 107,5512 107,5512 113,5536 113,5536 2,1044316 2,1044316
2648781 ESCELSA 2,171304 2,171304 19,354248 19,354248 81,216 81,216 91,584 91,584 0,535536 0,535536
2648779 ESCELSA 1,3130127 1,3130127 13,437049 13,437049 27,1092 27,1092 28,339201 28,339201 0,9636189 0,9636189
2648777 ESCELSA 1,2243912 1,2243912 8,927733 8,927733 85,7064 85,7064 108,141594 108,141594 1,7908062 1,7908062
2648775 ESCELSA 0 0 0 0 0 0 0 0 0 0
2648773 EPB 3,2951698 3,2951698 31,32226 31,32226 98,4 98,4 121,16 121,16 2,2639399 2,2639399
2648771 CEMIG 0,049 0,049 0 23,074 11 11 255 255 0,015 0,015
2648769 ESCELSA 0,295176 0,295176 100,56077 100,56077 5,376 5,376 696,864 696,864 4,44696 4,44696
2648767 CEMIG 2,68 2,68 0 28,158 147 147 175 175 0,187 0,187
2648765 CEMIG 3,52 3,52 0 91,388 144 144 336 336 2,21 2,21
2648763 AMPLA 2,365083 2,365083 19,2213 19,2213 106,59 106,59 128,77 128,77 0,9909899 0,9909899
2647742 LIGHT 0 3,252 37,896 37,896 0 0 95 95 0 0
2647740 LIGHT 0 17,267 201,999 201,999 0 0 444 444 0 0
2647738 LIGHT 0 8,743 91,044 91,044 0 0 217 217 0 0
2647736 ESCELSA 7,8000326 7,8000326 45,98316 45,98316 204,1308 204,1308 225,23761 225,23761 1,1846375 1,1846375
2647649 EPB 3,1483898 3,1483898 32,90557 32,90557 122,18 122,18 125,26 125,26 2,19673 2,19673
2647647 EPB 2,8223999 2,8223999 35,42784 35,42784 114,24 114,24 235,2 235,2 6,55123 6,55123
2642379 0 0 0 0 0 0 0 0 0 0
2642377 0 0 0 0 0 0 0 0 0 0
2642375 0 0 0 0 0 0 0 0 0 0
2642373 LIGHT 0 0 31,2 0 0 0 0 0 0 0
2642371 LIGHT 0 0 28,2 0 0 0 0 0 0 0
2642369 0 0 0 0 0 0 0 0 0 0
2642367 LIGHT 0 0 28,4 0 0 0 0 0 0 0
2642365 0 0 0 0 0 0 0 0 0 0
2642363 0 0 0 0 0 0 0 0 0 0
2642361 0 0 0 0 0 0 0 0 0 0
2642359 CEMIG 21,919 21,919 203,795 203,795 406 406 454 454 0 0
2641859 ESCELSA 0,364392 0,364392 42,21798 42,21798 15,792 15,792 326,928 326,928 3,543792 3,543792
2641857 CEAL 2,65737 0 21,834301 0 61,664 60,16 80,688 78,72 0 0
2641855 ESCELSA 1,2725999 1,2725999 81,32006 81,32006 67,2 67,2 491,904 491,904 0,027384 0,027384
2640192 ENERGISA-MS 1,8795 0 31,0065 0 169,79 169,79 227,64 227,64 9,7923 9,7923
2640189 CPFL PIRATININGA 91,2192 91,2192 638,16235 638,16235 1814,4 1814,4 2169,6 2169,6 0,014784001 0,014784001
2640187 CPFL PIRATININGA 52,9044 52,9044 584,6424 584,6424 1670,4 1670,4 2400 2400 2,301805 2,301805
2640185 CPFL PIRATININGA 50,46 50,46 518,0424 518,0424 1699,2 1699,2 2347,2 2347,2 2,160003 2,160003
2640183 CPFL PIRATININGA 54,162 54,162 597,40436 597,40436 1612,8 1612,8 2592 2592 0,65190303 0,65190303
2640181 0 0 0 0 0 0 0 0 0 0
2640179 0 0 0 0 0 0 0 0 0 0
2640177 0 0 0 0 0 0 0 0 0 0
2640175 CPFL PIRATININGA 57,3888 57,3888 619,0224 619,0224 1612,8 1612,8 2457,6 2457,6 2,689884 2,689884
2640172 0 0 0 0 0 0 0 0 0 0
2640170 0 0 0 0 0 0 0 0 0 0
2640168 0 0 0 0 0 0 0 0 0 0
2640166 CPFL PIRATININGA 110,8908 110,8908 875,56934 875,56934 2036,16 2036,16 2178,72 2178,72 2,8984199 2,8984199
2640164 CPFL PIRATININGA 100,03608 100,03608 853,90955 853,90955 1959,84 1959,84 2076,48 2076,48 1,774451 1,774451
2640162 CPFL PIRATININGA 102,10248 102,10248 766,9512 766,9512 1929,6 1929,6 1967,04 1967,04 0 0
2640160 CPFL PIRATININGA 100,03416 100,03416 802,90424 802,90424 1856,16 1856,16 2083,68 2083,68 0 0
2640158 CPFL PIRATININGA 111,19321 111,19321 797,52747 797,52747 1886,4 1886,4 2010,24 2010,24 0 0
2640155 CPFL PIRATININGA 109,6452 109,6452 777,58563 777,58563 1978,56 1978,56 2134,08 2134,08 0 0
2640153 CPFL PIRATININGA 113,21424 113,21424 883,6243 883,6243 2125,44 2125,44 2119,68 2119,68 2,571903 2,571903
2640151 CPFL PIRATININGA 77,0004 77,0004 607,032 607,032 1584 1584 2164,8 2164,8 0,008324999 0,008324999
2639657 0 0 0 0 0 0 0 0 0 0
2637389 CELPE 16,03854 16,03854 179,23457 179,23457 300,72 300,72 413,28 413,28 0 0
2637387 ESCELSA 0,90115196 0,90115196 82,13083 82,13083 171,36 171,36 479,808 479,808 5,9404798 5,9404798
2635764 0 0 0 0 0 0 0 0 0 0
2635762 0 0 0 0 0 0 0 0 0 0
2635759 0 0 0 0 0 0 0 0 0 0
2635757 0 0 0 0 0 0 0 0 0 0
2635755 COPEL 1,67 1,67 13,75 13,75 0 0 135,89 135,89 0 0
1 FaturaId Distribuidora oldConsumo_P newConsumo_P oldConsumo_FP newConsumo_FP oldDem_Reg_P newDem_Reg_P oldDem_Reg_FP newDem_Reg_FP oldEn_Reativa_Mvarh newEn_Reativa_Mvarh
2 2661629 ESCELSA 4,488885 4,488885 42,093967 42,093967 102,5328 102,5328 110,7984 110,7984 0,023591401 0,023591401
3 2661627 0 0 0 0 0 0 0 0 0 0
4 2661625 0 0 0 0 0 0 0 0 0 0
5 2661623 0 0 0 0 0 0 0 0 0 0
6 2661621 0 0 0 0 0 0 0 0 0 0
7 2661619 0 0 0 0 0 0 0 0 0 0
8 2661617 0 0 0 0 0 0 0 0 0 0
9 2661615 0 0 0 0 0 0 0 0 0 0
10 2661613 COELBA 0,41380998 0,41380998 27,502321 27,502321 8,29 8,29 364,9 364,9 0 0
11 2661610 ESCELSA 0,095844 0,095844 4,78716 4,78716 4,536 4,536 140,616 140,616 1,9076821 1,9076821
12 2660716 COPEL 19,12 19,12 204,665 204,665 0 0 477,79 477,79 0,001 0,001
13 2659047 ELETROPAULO 0 0 0,88 0,88 0 0 0 0 0 0
14 2659045 ELETROPAULO 0 0 14,909 14,909 0 0 0 0 0 0
15 2657257 LIGHT 0 4,619 44,937 44,937 0 0 114 114 0 0
16 2657255 0 0 0 0 0 0 0 0 0 0
17 2657253 ELETROPAULO 0 0 0,735 0,735 0 0 0 0 0 0
18 2657251 ELETROPAULO 0 0 1,926 1,926 0 0 0 0 0 0
19 2657249 ELETROPAULO 0 0 2,427 2,427 0 0 0 0 0 0
20 2657247 ESCELSA 12,808945 12,808945 112,56336 112,56336 308,16 308,16 371,52 371,52 1,2908161 1,2908161
21 2657245 CEMIG 2,045 2,045 0 42,366 74 74 116 116 3,7159998 3,7159998
22 2657243 AMPLA 0,17639999 0,17639999 1,722 1,722 6,38 6,38 8,73 8,73 0,120288 0,120288
23 2657241 LIGHT 0 12,957 118,419 118,419 0 0 406 406 0,632 0,632
24 2651045 CEPISA 2,14103 2,14103 26,00794 26,00794 57,81 57,81 64,01125 64,01125 0,01244 0,01244
25 2651043 CEPISA 2,9558 2,9558 40,134693 40,134693 76,26 76,26 88,9085 88,9085 0,00168 0,00168
26 2651041 CEPISA 2,56523 2,56523 27,377981 27,377981 49,4665 49,4665 60,5775 60,5775 0,27462 0,27462
27 2651039 CEPISA 3,291 3,291 29,207449 29,207449 68,265 68,265 70,18175 70,18175 0,00016 0,00016
28 2651037 CEPISA 3,45336 3,45336 30,65442 30,65442 69,618 69,618 73,60525 73,60525 0 0
29 2651035 CEPISA 3,84917 3,84917 35,64043 35,64043 78,1255 78,1255 83,2505 83,2505 0,13628 0,13628
30 2651033 CEPISA 6,91395 6,91395 58,289288 58,289288 142,8235 142,8235 146,96451 146,96451 0 0
31 2651031 CEPISA 6,8126497 6,8126497 60,74608 60,74608 128,3095 128,3095 129,49849 129,49849 0,14518 0,14518
32 2651029 CEPISA 6,52224 6,52224 61,94176 61,94176 139,6255 139,6255 144,35075 144,35075 1,37341 1,37341
33 2651027 0 0 0 0 0 0 0 0 0 0
34 2651025 LIGHT 0 2,916 155,358 155,358 0 0 1156 1156 5,676 5,676
35 2651023 CEAL 2,33626 0 19,12764 0 52,808 51,52 65,6 64 0 0
36 2651021 0 0 0 0 0 0 0 0 0 0
37 2651019 LIGHT 0 9,416 101,152 101,152 0 0 226 226 0,148 0,148
38 2651017 ESCELSA 0 0 0 0 0 0 0 0 0 0
39 2648795 CEMAR 4,1178102 4,1178102 21,61643 21,61643 227,81 227,81 219,24 219,24 0,01172 0,01172
40 2648793 ESCELSA 0,495684 0,495684 9,642744 9,642744 45,072 45,072 72,288 72,288 1,79064 1,79064
41 2648791 ESCELSA 7,4809437 7,4809437 65,1681 65,1681 178,128 178,128 212,256 212,256 0,68979603 0,68979603
42 2648789 ESCELSA 1,5292467 1,5292467 17,503773 17,503773 54,7104 54,7104 62,0904 62,0904 0,2139093 0,2139093
43 2648787 ESCELSA 1,639713 1,639713 15,435602 15,435602 35,3748 35,3748 39,310802 39,310802 0 0
44 2648785 ESCELSA 1,7095032 1,7095032 10,781343 10,781343 76,26 76,26 92,299194 92,299194 0,0020418 0,0020418
45 2648783 ESCELSA 1,9161924 1,9161924 14,906247 14,906247 107,5512 107,5512 113,5536 113,5536 2,1044316 2,1044316
46 2648781 ESCELSA 2,171304 2,171304 19,354248 19,354248 81,216 81,216 91,584 91,584 0,535536 0,535536
47 2648779 ESCELSA 1,3130127 1,3130127 13,437049 13,437049 27,1092 27,1092 28,339201 28,339201 0,9636189 0,9636189
48 2648777 ESCELSA 1,2243912 1,2243912 8,927733 8,927733 85,7064 85,7064 108,141594 108,141594 1,7908062 1,7908062
49 2648775 ESCELSA 0 0 0 0 0 0 0 0 0 0
50 2648773 EPB 3,2951698 3,2951698 31,32226 31,32226 98,4 98,4 121,16 121,16 2,2639399 2,2639399
51 2648771 CEMIG 0,049 0,049 0 23,074 11 11 255 255 0,015 0,015
52 2648769 ESCELSA 0,295176 0,295176 100,56077 100,56077 5,376 5,376 696,864 696,864 4,44696 4,44696
53 2648767 CEMIG 2,68 2,68 0 28,158 147 147 175 175 0,187 0,187
54 2648765 CEMIG 3,52 3,52 0 91,388 144 144 336 336 2,21 2,21
55 2648763 AMPLA 2,365083 2,365083 19,2213 19,2213 106,59 106,59 128,77 128,77 0,9909899 0,9909899
56 2647742 LIGHT 0 3,252 37,896 37,896 0 0 95 95 0 0
57 2647740 LIGHT 0 17,267 201,999 201,999 0 0 444 444 0 0
58 2647738 LIGHT 0 8,743 91,044 91,044 0 0 217 217 0 0
59 2647736 ESCELSA 7,8000326 7,8000326 45,98316 45,98316 204,1308 204,1308 225,23761 225,23761 1,1846375 1,1846375
60 2647649 EPB 3,1483898 3,1483898 32,90557 32,90557 122,18 122,18 125,26 125,26 2,19673 2,19673
61 2647647 EPB 2,8223999 2,8223999 35,42784 35,42784 114,24 114,24 235,2 235,2 6,55123 6,55123
62 2642379 0 0 0 0 0 0 0 0 0 0
63 2642377 0 0 0 0 0 0 0 0 0 0
64 2642375 0 0 0 0 0 0 0 0 0 0
65 2642373 LIGHT 0 0 31,2 0 0 0 0 0 0 0
66 2642371 LIGHT 0 0 28,2 0 0 0 0 0 0 0
67 2642369 0 0 0 0 0 0 0 0 0 0
68 2642367 LIGHT 0 0 28,4 0 0 0 0 0 0 0
69 2642365 0 0 0 0 0 0 0 0 0 0
70 2642363 0 0 0 0 0 0 0 0 0 0
71 2642361 0 0 0 0 0 0 0 0 0 0
72 2642359 CEMIG 21,919 21,919 203,795 203,795 406 406 454 454 0 0
73 2641859 ESCELSA 0,364392 0,364392 42,21798 42,21798 15,792 15,792 326,928 326,928 3,543792 3,543792
74 2641857 CEAL 2,65737 0 21,834301 0 61,664 60,16 80,688 78,72 0 0
75 2641855 ESCELSA 1,2725999 1,2725999 81,32006 81,32006 67,2 67,2 491,904 491,904 0,027384 0,027384
76 2640192 ENERGISA-MS 1,8795 0 31,0065 0 169,79 169,79 227,64 227,64 9,7923 9,7923
77 2640189 CPFL PIRATININGA 91,2192 91,2192 638,16235 638,16235 1814,4 1814,4 2169,6 2169,6 0,014784001 0,014784001
78 2640187 CPFL PIRATININGA 52,9044 52,9044 584,6424 584,6424 1670,4 1670,4 2400 2400 2,301805 2,301805
79 2640185 CPFL PIRATININGA 50,46 50,46 518,0424 518,0424 1699,2 1699,2 2347,2 2347,2 2,160003 2,160003
80 2640183 CPFL PIRATININGA 54,162 54,162 597,40436 597,40436 1612,8 1612,8 2592 2592 0,65190303 0,65190303
81 2640181 0 0 0 0 0 0 0 0 0 0
82 2640179 0 0 0 0 0 0 0 0 0 0
83 2640177 0 0 0 0 0 0 0 0 0 0
84 2640175 CPFL PIRATININGA 57,3888 57,3888 619,0224 619,0224 1612,8 1612,8 2457,6 2457,6 2,689884 2,689884
85 2640172 0 0 0 0 0 0 0 0 0 0
86 2640170 0 0 0 0 0 0 0 0 0 0
87 2640168 0 0 0 0 0 0 0 0 0 0
88 2640166 CPFL PIRATININGA 110,8908 110,8908 875,56934 875,56934 2036,16 2036,16 2178,72 2178,72 2,8984199 2,8984199
89 2640164 CPFL PIRATININGA 100,03608 100,03608 853,90955 853,90955 1959,84 1959,84 2076,48 2076,48 1,774451 1,774451
90 2640162 CPFL PIRATININGA 102,10248 102,10248 766,9512 766,9512 1929,6 1929,6 1967,04 1967,04 0 0
91 2640160 CPFL PIRATININGA 100,03416 100,03416 802,90424 802,90424 1856,16 1856,16 2083,68 2083,68 0 0
92 2640158 CPFL PIRATININGA 111,19321 111,19321 797,52747 797,52747 1886,4 1886,4 2010,24 2010,24 0 0
93 2640155 CPFL PIRATININGA 109,6452 109,6452 777,58563 777,58563 1978,56 1978,56 2134,08 2134,08 0 0
94 2640153 CPFL PIRATININGA 113,21424 113,21424 883,6243 883,6243 2125,44 2125,44 2119,68 2119,68 2,571903 2,571903
95 2640151 CPFL PIRATININGA 77,0004 77,0004 607,032 607,032 1584 1584 2164,8 2164,8 0,008324999 0,008324999
96 2639657 0 0 0 0 0 0 0 0 0 0
97 2637389 CELPE 16,03854 16,03854 179,23457 179,23457 300,72 300,72 413,28 413,28 0 0
98 2637387 ESCELSA 0,90115196 0,90115196 82,13083 82,13083 171,36 171,36 479,808 479,808 5,9404798 5,9404798
99 2635764 0 0 0 0 0 0 0 0 0 0
100 2635762 0 0 0 0 0 0 0 0 0 0
101 2635759 0 0 0 0 0 0 0 0 0 0
102 2635757 0 0 0 0 0 0 0 0 0 0
103 2635755 COPEL 1,67 1,67 13,75 13,75 0 0 135,89 135,89 0 0

View File

@ -1,12 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Download_Faturas
{
internal class Class1
{
}
}

View File

@ -26,6 +26,11 @@
</PackageReference>
<PackageReference Include="System.Data.OleDb" Version="9.0.0" />
<PackageReference Include="System.Text.Json" Version="9.0.0" />
<PackageReference Include="XUnit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>

View File

@ -72,11 +72,13 @@
public JsonElement.ArrayEnumerator Agrupada_children { get; private set; }
// Variavel para armazenar os dados a serem lancados para a TUSD no BD
public RecordSet dadosTusd = new ();
public double cod_tusd;
public void Processar(OleDbConnection conn)
{
// Variavel para armazenar os dados a serem lancados para a TUSD no BD
RecordSet dadosTusd = new ();
// Resultado da fatura processada
JsonElement a;
if (!this.faturaParsed.TryGetProperty("result", out a))
@ -85,8 +87,7 @@
}
Rootobject parsedResult = JsonSerializer.Deserialize<Rootobject>(a)!;
if (parsedResult.dates.reading.periodUntil == DateTime.MinValue)
if (parsedResult == null || parsedResult.dates == null || parsedResult.dates.reading == null || parsedResult.locationNumber == null || parsedResult.customer == null || parsedResult.items == null || parsedResult.dates.reading.periodUntil == DateTime.MinValue)
{
return;
}
@ -132,10 +133,10 @@
while (reader.Read())
{
// Dados cadastrais
dadosTusd.Cod_Smart_unidade = long.Parse(reader["Cod_Smart_unidade"].ToString() !);
dadosTusd.Cod_Smart_unidade = long.Parse(reader["Cod_Smart_unidade"].ToString()!);
dadosTusd.Perfil_CliqCCEE = reader["PerfilCCEE"].ToString();
dadosTusd.Submercado = reader["Submercado"].ToString();
DateTime dataMigração = DateTime.Parse(reader["Data_de_Migracao"].ToString() !);
DateTime dataMigração = DateTime.Parse(reader["Data_de_Migracao"].ToString()!);
if (int.Parse(dataMigração.ToString("yMM")) <= dadosTusd.Mes)
{
dadosTusd.Ambiente = reader["Status_unidade"].ToString();
@ -147,11 +148,11 @@
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() !);
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()!);
dadosTusd.Perfil = reader["Perfil"].ToString();
this.PastaTUSD = new DirectoryInfo(reader["Caminho_NFs"].ToString() !.Replace("\\NFe", string.Empty, StringComparison.OrdinalIgnoreCase) + "\\TUSD");
this.PastaTUSD = new DirectoryInfo(reader["Caminho_NFs"].ToString()!.Replace("\\NFe", string.Empty, StringComparison.OrdinalIgnoreCase) + "\\TUSD");
this.Gestao = reader["Gestao"].ToString();
this.Empresa = reader["Cliente"].ToString();
this.Unidade = reader["Unidade"].ToString();
@ -165,7 +166,7 @@
sqlQuery = $"SELECT Cod_TUSD FROM Dados_TUSD WHERE Cod_TUSD = ?";
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
double cod_tusd = double.Parse(dadosTusd.Cod_Smart_unidade.ToString() + dadosTusd.Mes.ToString());
cod_tusd = double.Parse(dadosTusd.Cod_Smart_unidade.ToString() + dadosTusd.Mes.ToString());
cmd.Parameters.AddWithValue("?", cod_tusd);
using (OleDbDataReader reader = cmd.ExecuteReader())
@ -202,8 +203,8 @@
while (reader.Read())
{
// PIS e Cofins
dadosTusd.PIS = float.Parse(reader["PIS"].ToString() !);
dadosTusd.COFINS = float.Parse(reader["COFINS"].ToString() !);
dadosTusd.PIS = float.Parse(reader["PIS"].ToString()!);
dadosTusd.COFINS = float.Parse(reader["COFINS"].ToString()!);
}
}
}
@ -408,7 +409,7 @@
}
}
if (dem_Reg_P != null && (Math.Round((decimal)dadosTusd.Consumo_FP, 2) == Math.Round((decimal)(consumo_Reg_FP * 1.025 / 1000) !, 2)))
if (dem_Reg_P != null && (Math.Round((decimal)dadosTusd.Consumo_FP, 2) == Math.Round((decimal)(consumo_Reg_FP * 1.025 / 1000)!, 2)))
{
dadosTusd.Dem_Reg_P = (float)(dem_Reg_P * 1.025);
}
@ -417,7 +418,7 @@
dadosTusd.Dem_Reg_P = (float)dem_Reg_P;
}
if (dem_Reg_FP != null && (Math.Round((decimal)dadosTusd.Consumo_FP, 2) == Math.Round((decimal)(consumo_Reg_FP * 1.025 / 1000) !, 2)))
if (dem_Reg_FP != null && (Math.Round((decimal)dadosTusd.Consumo_FP, 2) == Math.Round((decimal)(consumo_Reg_FP * 1.025 / 1000)!, 2)))
{
dadosTusd.Dem_Reg_FP = (float)(dem_Reg_FP * 1.025);
}

View File

@ -0,0 +1,698 @@
namespace Download_Faturas
{
using System.Data.OleDb;
using System.Globalization;
using System.Net.Http.Headers;
using System.Reflection;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.Intrinsics.X86;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using iText.Kernel.Pdf;
using iText.Kernel.Utils;
public class FaturaOld
{
private const string Token = "UFY4VWzqcHYcGNd0gkBOMFL9G5ZThV6gXBQIJ79F5HSqITzavz4Fe7iXvAbJLvZJ";
private JsonElement faturaParsed;
private string? id;
private string? uc;
private int? pagina;
public FaturaOld(string id, string fatura_path, HttpClient httpClient)
{
// Utilizado para gerar novo token
// this.token = Req_token(httpClient).ToString();
HttpResponseMessage fatura_response = this.GetStatus(httpClient, 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();
this.Arquivo = new FileInfo(fatura_path);
this.id = id;
if (this.faturaParsed.GetProperty("external").GetString() is not null)
{
this.pagina = JsonDocument.Parse(this.faturaParsed.GetProperty("external").GetString() !).RootElement.GetProperty("origin")[0].GetProperty("page").GetInt32();
}
if (this.Agrupada)
{
this.Agrupada_children = this.faturaParsed.GetProperty("children").EnumerateArray();
}
}
}
public FaturaOld(string id, JsonElement fatura_Parsed)
{
// Utilizado para gerar novo token
// this.token = Req_token(httpClient).ToString();
this.faturaParsed = fatura_Parsed;
this.Agrupada = false;
this.id = id;
}
public string? Gestao { get; private set; }
public string? Empresa { get; private set; }
public string? Unidade { get; private set; }
public int? Mes { get; private set; }
public string? Status { get; private set; }
public FileInfo? Arquivo { get; private set; }
public DirectoryInfo? PastaTUSD { get; private set; }
public bool Agrupada { get; private set; }
public JsonElement.ArrayEnumerator Agrupada_children { get; private set; }
// Variavel para armazenar os dados a serem lancados para a TUSD no BD
public RecordSet dadosTusd = new ();
public double cod_tusd;
public void Processar(OleDbConnection conn)
{
// Resultado da fatura processada
JsonElement a;
if (!this.faturaParsed.TryGetProperty("result", out a))
{
this.faturaParsed.TryGetProperty("json", out a);
}
Rootobject parsedResult = JsonSerializer.Deserialize<Rootobject>(a)!;
if (parsedResult == null || parsedResult.dates == null || parsedResult.dates.reading == null || parsedResult.locationNumber == null || parsedResult.customer == null || parsedResult.items == null || parsedResult.dates.reading.periodUntil == DateTime.MinValue)
{
return;
}
dadosTusd.Mes = int.Parse(parsedResult.dates.reading.periodUntil.AddDays(-15).ToString("yMM"));
string uc = new Regex("^0+").Replace(parsedResult.locationNumber, string.Empty).Replace("/", string.Empty).Replace("-", string.Empty).Replace(".", string.Empty);
// Vinculo da fatura com os dados cadastrais
int? unidades;
string sqlQuery = $"SELECT COUNT (Cod_Smart_unidade) FROM Dados_cadastrais WHERE Codigo_Instalacao = @uc AND unidade_gerenciada";
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
cmd.Parameters.AddWithValue("@uc", uc);
unidades = (int?)cmd.ExecuteScalar();
if (unidades == 1)
{
sqlQuery = $"SELECT Cod_Smart_unidade, Gestao, Cliente, Unidade, PerfilCCEE, Submercado, Status_unidade, Grupo, Perfil, Distribuidora, ICMS_TUSD, Demanda_P, Demanda_FP, Caminho_NFs, Data_de_Migracao FROM Dados_cadastrais WHERE Codigo_Instalacao = @uc AND unidade_gerenciada";
}
else
{
sqlQuery = $"SELECT Cod_Smart_unidade, Gestao, Cliente, Unidade, PerfilCCEE, Submercado, Status_unidade, Grupo, Perfil, Distribuidora, ICMS_TUSD, Demanda_P, Demanda_FP, Caminho_NFs, Data_de_Migracao FROM Dados_cadastrais WHERE (CNPJ_CPF LIKE @cnpj AND Codigo_Instalacao = @uc AND unidade_gerenciada) OR (Razao_Social LIKE @razao_social AND Codigo_Instalacao = @uc AND unidade_gerenciada)";
}
}
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
if (unidades == 1)
{
cmd.Parameters.AddWithValue("@uc", uc);
}
else
{
cmd.Parameters.AddWithValue("@cnpj", parsedResult.customer.cnpj?[..8] != null ? parsedResult.customer.cnpj?[..8] + "%" : "NAN");
cmd.Parameters.AddWithValue("@uc", uc);
cmd.Parameters.AddWithValue("@razao_social", parsedResult.customer.name);
}
using (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();
DateTime dataMigração = DateTime.Parse(reader["Data_de_Migracao"].ToString()!);
if (int.Parse(dataMigração.ToString("yMM")) <= dadosTusd.Mes)
{
dadosTusd.Ambiente = reader["Status_unidade"].ToString();
}
else
{
dadosTusd.Ambiente = "Cativo";
}
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()!);
dadosTusd.Perfil = reader["Perfil"].ToString();
this.PastaTUSD = new DirectoryInfo(reader["Caminho_NFs"].ToString()!.Replace("\\NFe", string.Empty, StringComparison.OrdinalIgnoreCase) + "\\TUSD");
this.Gestao = reader["Gestao"].ToString();
this.Empresa = reader["Cliente"].ToString();
this.Unidade = reader["Unidade"].ToString();
}
}
}
// Verifica se a fatura ja foi lançada
bool tusdLanc;
sqlQuery = $"SELECT Cod_TUSD FROM Dados_TUSD WHERE Cod_TUSD = ?";
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
cod_tusd = double.Parse(dadosTusd.Cod_Smart_unidade.ToString() + dadosTusd.Mes.ToString());
cmd.Parameters.AddWithValue("?", cod_tusd);
using (OleDbDataReader reader = cmd.ExecuteReader())
{
tusdLanc = reader.HasRows;
}
}
if (dadosTusd.Cod_Smart_unidade == 0)
{
this.Status = "UNIDADE CONSUMIDORA NÃO LOCALIZADA NO BD";
this.uc = uc;
this.Mes = dadosTusd.Mes;
return;
}
else if (tusdLanc)
{
this.Status = "FATURA DUPLICADA NO BD";
this.uc = uc;
this.Mes = dadosTusd.Mes;
return;
}
// PIS e Cofins
sqlQuery = $"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 = ? AND Distribuidoras_geral.Distribuidora = ?";
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
cmd.Parameters.AddWithValue("?", dadosTusd.Mes.ToString());
cmd.Parameters.AddWithValue("?", dadosTusd.Distribuidora);
using (OleDbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// PIS e Cofins
dadosTusd.PIS = float.Parse(reader["PIS"].ToString()!);
dadosTusd.COFINS = float.Parse(reader["COFINS"].ToString()!);
}
}
}
// Dados da fatura processada
dadosTusd.Cod_TUSD = long.Parse(dadosTusd.Cod_Smart_unidade.ToString() + dadosTusd.Mes.ToString());
switch (parsedResult.tariffModality, parsedResult.subgroup)
{
case ("blue", _):
dadosTusd.Perfil = "AZUL";
break;
case ("green", _):
dadosTusd.Perfil = "VERDE";
break;
case ("standart", _):
dadosTusd.Perfil = "CONVENCIONAL";
break;
case (_, "B3"):
dadosTusd.Perfil = "CONVENCIONAL";
break;
default:
break;
}
dadosTusd.Valor = parsedResult.totalCharges;
dadosTusd.Inicio_Leitura = parsedResult.dates.reading.periodFrom;
dadosTusd.Fim_leitura = parsedResult.dates.reading.periodUntil;
DateTime d = DateTime.Now;
dadosTusd.Hora_TUSD = new DateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second);
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;
float? dem_Reg_P = null;
float? dem_Reg_FP = null;
float? consumo_Reg_FP = 0;
string? kind_P = string.Empty;
string? kind_FP = string.Empty;
if (this.id == "2356193")
{
int i = 0;
i++;
}
List<(string, float)> insertOthers = new List<(string, float)>();
foreach (Item item in parsedResult.items)
{
switch (item.type, item.period)
{
// Energia Ponta
case ("energy", "peak"):
if (kind_P == string.Empty)
{
kind_P = item.kind;
}
if (item.kind == kind_P)
{
dadosTusd.Consumo_P += item.billed / 1000;
}
break;
// Energia Fora de Ponta
case ("energy", _):
if (item.period == "off-peak" || item.period == "off-peak inductive" || item.period == "off-peak capacitive" || item.period == "reserved")
{
if (kind_FP == string.Empty)
{
kind_FP = item.kind;
}
if (item.kind == kind_FP)
{
dadosTusd.Consumo_FP += item.billed / 1000;
}
}
else
{
insertOthers.Add((item.texts[0], item.charge));
}
break;
// Demanda
case ("demand", _):
if (item.contract != 0)
{
if (item.period == "peak")
{
dadosTusd.Dem_Reg_P = item.billed;
dadosTusd.Dem_Cont_P = item.contract;
}
else if (item.period == "off-peak")
{
dadosTusd.Dem_Reg_FP = item.billed;
dadosTusd.Dem_Cont_FP = item.contract;
}
if (dadosTusd.Perfil == "AZUL")
{
if (item.period == "peak")
{
sqlQuery = $"UPDATE Dados_cadastrais SET Demanda_P = @demanda WHERE Cod_Smart_unidade = @cod_smart_unidade";
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
cmd.Parameters.AddWithValue("@demanda", item.contract);
cmd.Parameters.AddWithValue("@cod_smart_unidade", dadosTusd.Cod_Smart_unidade);
cmd.ExecuteNonQuery();
}
}
else if (item.period == "off-peak")
{
sqlQuery = $"UPDATE Dados_cadastrais SET Demanda_FP = @demanda WHERE Cod_Smart_unidade = @cod_smart_unidade";
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
cmd.Parameters.AddWithValue("@demanda", item.contract);
cmd.Parameters.AddWithValue("@cod_smart_unidade", dadosTusd.Cod_Smart_unidade);
cmd.ExecuteNonQuery();
}
}
}
else if (dadosTusd.Perfil == "VERDE")
{
sqlQuery = $"UPDATE Dados_cadastrais SET Demanda_P = @demanda, Demanda_FP = @demanda WHERE Cod_Smart_unidade = @cod_smart_unidade";
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
cmd.Parameters.AddWithValue("@demanda", item.contract);
cmd.Parameters.AddWithValue("@cod_smart_unidade", dadosTusd.Cod_Smart_unidade);
cmd.ExecuteNonQuery();
}
}
}
break;
// Ilum. publica
case ("publicLighting", _):
dadosTusd.Ilum_Publica = item.charge;
break;
// Energia Reativa
case ("excessReactiveEnergy", _):
dadosTusd.En_Reativa_Mvarh += item.billed / 1000;
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 e cria a instrução SQL para inserir os novos items
if (j == 1)
{
sqlQuery = $"DELETE FROM Dados_TUSD_aux WHERE Cod_TUSD = @cod_tusd";
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
cmd.Parameters.AddWithValue("@cod_tusd", dadosTusd.Cod_TUSD);
cmd.ExecuteNonQuery();
}
}
insertOthers.Add((item.name, item.charge));
break;
}
}
// Busca a demanda registrada nos itens medidos
foreach (Measureditem measuredItem in parsedResult.measuredItems)
{
switch (measuredItem.type, measuredItem.period)
{
case ("demand", "peak"):
dem_Reg_P = measuredItem.measured.Max();
break;
case ("demand", "off-peak"):
dem_Reg_FP = measuredItem.measured.Max();
break;
case ("energy", "off-peak"):
consumo_Reg_FP = consumo_Reg_FP.GetValueOrDefault() + measuredItem.measured.Sum();
break;
case ("energy", "off-peak inductive"):
consumo_Reg_FP = consumo_Reg_FP.GetValueOrDefault() + measuredItem.measured.Sum();
break;
case ("energy", "off-peak capacitive"):
consumo_Reg_FP = consumo_Reg_FP.GetValueOrDefault() + measuredItem.measured.Sum();
break;
case ("energy", "off-peak capacitive green flag"):
consumo_Reg_FP = consumo_Reg_FP.GetValueOrDefault() + measuredItem.measured.Sum();
break;
case ("energy", "off-peak inductive green flag"):
consumo_Reg_FP = consumo_Reg_FP.GetValueOrDefault() + measuredItem.measured.Sum();
break;
case ("energy", "reserved"):
consumo_Reg_FP = consumo_Reg_FP.GetValueOrDefault() + measuredItem.measured.Sum();
break;
}
}
if (dem_Reg_P != null && (Math.Round((decimal)dadosTusd.Consumo_FP, 2) == Math.Round((decimal)(consumo_Reg_FP * 1.025 / 1000)!, 2)))
{
dadosTusd.Dem_Reg_P = (float)(dem_Reg_P * 1.025);
}
else if (dem_Reg_P != null)
{
dadosTusd.Dem_Reg_P = (float)dem_Reg_P;
}
if (dem_Reg_FP != null && (Math.Round((decimal)dadosTusd.Consumo_FP, 2) == Math.Round((decimal)(consumo_Reg_FP * 1.025 / 1000)!, 2)))
{
dadosTusd.Dem_Reg_FP = (float)(dem_Reg_FP * 1.025);
}
else if (dem_Reg_FP != null)
{
dadosTusd.Dem_Reg_FP = dem_Reg_FP ?? 0;
}
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
if (tusdLanc)
{
// Cria o comando para atualização da fatura
sqlQuery = "UPDATE Dados_TUSD SET ";
// Loop por todos os dados ja obtidos
PropertyInfo[] propriedades = typeof(RecordSet).GetProperties();
foreach (PropertyInfo propriedade in propriedades)
{
string nomeColuna = propriedade.Name;
// Adicione a coluna à instrução SQL
sqlQuery += $"{nomeColuna} = @{nomeColuna}, ";
}
// Remova a última vírgula e adicione a cláusula WHERE
sqlQuery = sqlQuery.TrimEnd(',', ' ') + $" WHERE Cod_TUSD = @cod_tusd";
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
foreach (PropertyInfo propriedade in propriedades)
{
string nomeColuna = propriedade.Name;
object valorColuna = propriedade.GetValue(dadosTusd) ?? string.Empty;
cmd.Parameters.AddWithValue($"@{nomeColuna}", valorColuna);
}
// Valor do código TUSD na cláusula WHERE
cmd.Parameters.AddWithValue("@cod_tusd", dadosTusd.Cod_TUSD);
cmd.ExecuteNonQuery();
}
// Inseri os itens classificados como "othes" após criar o registro da TUSD devido as relação entre as tabelas
foreach ((string name, float valor) in insertOthers)
{
j++;
sqlQuery = "INSERT INTO Dados_TUSD_aux (Cod_TUSD,Id,Nome,Valor,Cod_lanc) VALUES (@cod_tusd, @j, @name, @valor,0)";
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
cmd.Parameters.AddWithValue("@cod_tusd", dadosTusd.Cod_TUSD);
cmd.Parameters.AddWithValue("@j", j);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@valor", valor);
cmd.ExecuteNonQuery();
}
}
}
else
{
// Cria o comando para lançar da fatura
sqlQuery = "INSERT INTO Dados_TUSD (";
PropertyInfo[] propriedades = typeof(RecordSet).GetProperties();
/*int i = 0;*/
foreach (PropertyInfo propriedade in propriedades)
{
string nomeColuna = propriedade.Name;
// Adicione a coluna à instrução SQL
sqlQuery += $"{nomeColuna}, ";
}
// Remova a última vírgula e adicione a cláusula VALUES
sqlQuery = sqlQuery.TrimEnd(',', ' ') + ") VALUES (";
foreach (PropertyInfo propriedade in propriedades)
{
// Adicione os parâmetros à instrução SQL
string nomeColuna = propriedade.Name;
sqlQuery += $"@{nomeColuna}, ";
}
// Remova a última vírgula e feche a instrução SQL
sqlQuery = sqlQuery.TrimEnd(',', ' ') + ")";
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
foreach (PropertyInfo propriedade in propriedades)
{
string nomeColuna = propriedade.Name;
object valorColuna = propriedade.GetValue(dadosTusd) ?? string.Empty;
cmd.Parameters.AddWithValue($"@{nomeColuna}", valorColuna);
}
cmd.ExecuteNonQuery();
}
// Inseri os itens classificados como "othes" após criar o registro da TUSD devido as relação entre as tabelas
j = 0;
foreach ((string name, float valor) in insertOthers)
{
j++;
sqlQuery = "INSERT INTO Dados_TUSD_aux (Cod_TUSD,Id,Nome,Valor,Cod_lanc) VALUES (@cod_tusd, @j, @name, @valor, 0)";
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
cmd.Parameters.AddWithValue("@cod_tusd", dadosTusd.Cod_TUSD);
cmd.Parameters.AddWithValue("@j", j);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@valor", valor);
cmd.ExecuteNonQuery();
}
}
}
this.Status = "FATURA INCLUIDA NO BD";
this.uc = uc;
this.Mes = dadosTusd.Mes;
}
public void Mover(bool separar)
{
string destino = string.Empty;
switch (this.Status, separar)
{
case ("UNIDADE CONSUMIDORA NÃO LOCALIZADA NO BD", _):
destino = this.Arquivo?.Directory?.Parent?.FullName + $@"\5 - {this.Status}\ID {this.id!} - Mês {this.Mes} - UC {this.uc}.pdf";
if (separar)
{
new PDFSplitter(this.pagina, this.Arquivo!.ToString(), destino);
this.Arquivo = new FileInfo(destino);
}
else
{
try
{
this.Arquivo!.MoveTo(destino);
}
catch
{
}
}
break;
case ("FATURA DUPLICADA NO BD", _):
destino = this.Arquivo?.Directory?.Parent?.FullName + $@"\4 - {this.Status}\ID {this.id!} - Mês {this.Mes} - Empresa {this.Empresa} - Unidade {this.Unidade}.pdf";
if (separar)
{
new PDFSplitter(this.pagina, this.Arquivo!.ToString(), destino);
this.Arquivo = new FileInfo(destino);
}
else
{
try
{
this.Arquivo!.MoveTo(destino);
}
catch
{
}
}
break;
case ("FATURA INCLUIDA NO BD", _):
if (this.PastaTUSD!.Exists)
{
destino = this.PastaTUSD!.FullName + $@"\ID {this.id!} - Mês {this.Mes} - Empresa {this.Empresa} - Unidade {this.Unidade}.pdf";
}
else
{
destino = this.Arquivo?.Directory?.Parent?.FullName + $@"\6 - {this.Status}\ID {this.id!} - Mês {this.Mes} - Empresa {this.Empresa} - Unidade {this.Unidade}.pdf";
}
if (separar)
{
new PDFSplitter(this.pagina, this.Arquivo!.ToString(), destino);
this.Arquivo = new FileInfo(destino);
}
else
{
try
{
this.Arquivo!.MoveTo(destino);
}
catch
{
}
}
break;
case ("INVALID", _):
destino = this.Arquivo?.Directory?.Parent?.FullName + $@"\7 - ERRO\ID {this.id!} - {this.Arquivo?.Name}";
if (separar)
{
new PDFSplitter(this.pagina, this.Arquivo!.ToString(), destino);
this.Arquivo = new FileInfo(destino);
}
else
{
try
{
this.Arquivo!.MoveTo(destino);
}
catch
{
throw;
}
}
break;
case (_, true):
destino = this.Arquivo?.Directory?.Parent?.FullName + $@"\3 - PROCESSANDO\ID {this.id!} - {this.Arquivo?.Name}";
new PDFSplitter(this.pagina, this.Arquivo!.ToString(), destino);
this.Arquivo = new FileInfo(destino);
break;
}
}
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() !;
}
}
}

View File

@ -14,6 +14,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
.editorconfig = .editorconfig
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Download Faturas.Tests", "Download Faturas.Tests\Download Faturas.Tests.csproj", "{67A025C1-B7A4-48D0-8157-C0BBA550469F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -32,6 +34,10 @@ Global
{75EFF4FA-14FE-4540-B872-F84224CDECAF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{75EFF4FA-14FE-4540-B872-F84224CDECAF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{75EFF4FA-14FE-4540-B872-F84224CDECAF}.Release|Any CPU.Build.0 = Release|Any CPU
{67A025C1-B7A4-48D0-8157-C0BBA550469F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{67A025C1-B7A4-48D0-8157-C0BBA550469F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{67A025C1-B7A4-48D0-8157-C0BBA550469F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{67A025C1-B7A4-48D0-8157-C0BBA550469F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -118,7 +118,7 @@ namespace Webhook_4docs
JsonElement DadosJson = JsonDocument.Parse(root.ToString()).RootElement;
string tipoDocumento = root.Get("documentType").ToString().ToLower();
string tipoDocumento = root.Get("documentType").ToString() ?? string.Empty.ToLower();
if (tipoDocumento != string.Empty && tipoDocumento != "nota_fiscal")
{
@ -169,7 +169,7 @@ namespace Webhook_4docs
case ("FATURA DUPLICADA NO BD"):
status_id = 4;
break;
case ("UNIDADE CONSUMIDORA NÃO LOCALIZADA NO BD"):
case ("UNIDADE CONSUMIDORA N<EFBFBD>O LOCALIZADA NO BD"):
status_id = 5;
break;
case ("FATURA INCLUIDA NO BD"):
@ -191,7 +191,7 @@ namespace Webhook_4docs
if (status_id != 4)
{
fatura_arquivo = IndexedFilename($@"{path}\ID {fatura_ID!} - Mês {fatura.Mes} - Empresa {fatura.Empresa} - Unidade {fatura.Unidade}", "pdf");
fatura_arquivo = IndexedFilename($@"{path}\ID {fatura_ID!} - M<EFBFBD>s {fatura.Mes} - Empresa {fatura.Empresa} - Unidade {fatura.Unidade}", "pdf");
CriarArquivo(fatura_arquivo, JsonBody.GetProperty("pdfFile").ToString());
var DatabaseModel = new ProcessedInvoices
@ -202,7 +202,7 @@ namespace Webhook_4docs
InvoicePath = fatura_arquivo
};
logger.LogInformation("Fatura incluída no BD");
logger.LogInformation("Fatura inclu<EFBFBD>da no BD");
logger.LogInformation("Fatura salva na pasta " + fatura_arquivo);
@ -244,18 +244,16 @@ namespace Webhook_4docs
errorID = 3;
break;
case (true, _):
//logger.LogInformation("Loc ID: " + JsonBody.GetProperty("locationID").ToString() + " está saudável");
//logger.LogInformation("Loc ID: " + JsonBody.GetProperty("locationID").ToString() + " est<EFBFBD> saud<75>vel");
break;
}
int test = await UpdateErrorIdStatusAsync(CaminhoDB, JsonBody.GetProperty("locationID").GetInt64(), errorID, (JsonBody.GetProperty("systemText").ToString() == "" ? JsonBody.GetProperty("websiteText").ToString() : JsonBody.GetProperty("systemText").ToString()), logger);
var errorText = GetErrorText(JsonBody);
await UpdateErrorIdStatusAsync(CaminhoDB, JsonBody.GetProperty("locationID").GetInt64(), errorID, errorText, logger);
if (test == 0)
{
await InsertErrorIdStatusAsync(CaminhoDB, errorID, requestBody, logger);
}
}
});
//implementa<74><61>o futura para receber as faturas enviadas via api de forma ass<73>ncrona - Upload4Docs (substituir parte do agendador de tarefas)
endpoints.MapPut("/api", async context =>
{
var a = 10;
@ -263,100 +261,29 @@ namespace Webhook_4docs
});
app.Run();
}
public static async Task InsertErrorIdStatusAsync(string CaminhoDB, double errorID, string requestBody, ILogger logger)
//tenta pegar o deactivationReport, se não conseguir ou for null, tenta pegar o websiteText, se não conseguir ou for null, tenta pegar o systemText. As propriedades podem não exisir
public static string GetErrorText(JsonElement root)
{
var JsonBody = JsonDocument.Parse(requestBody).RootElement;
string errorText = string.Empty;
// Extração dos valores do JSON
double locationID = JsonBody.GetProperty("locationID").GetInt64();
string accountID = JsonBody.GetProperty("accountID").ToString();
string deliveryTimeStamp = JsonBody.GetProperty("deliveryTimestamp").ToString();
string provider = JsonBody.GetProperty("provider").ToString();
string accessPoint = JsonBody.GetProperty("accessPoint").ToString();
string slaStatus = JsonBody.GetProperty("slaStatus").ToString();
string healthy = JsonBody.GetProperty("healthy").ToString();
string blame = JsonBody.GetProperty("blame").ToString();
string lastSuccess = JsonBody.GetProperty("lastSuccess").ToString();
string active = JsonBody.GetProperty("active").ToString();
string blacklistStatus = JsonBody.GetProperty("blacklistStatus").ToString();
string lastActivated = JsonBody.GetProperty("lastActivated").ToString();
string lastDeactivated = JsonBody.GetProperty("lastDeactivated").ToString();
string lastDeactivatedBy = JsonBody.GetProperty("lastDeactivatedBy").ToString();
int maxRetries = 3;
int attempt = 0;
while (attempt < maxRetries)
if (root.TryGetProperty("deactivationReport", out JsonElement deactivationReportElement) && deactivationReportElement.ValueKind != JsonValueKind.Null)
{
var connLease = await connRateLimiter.AcquireAsync();
if (connLease.IsAcquired)
{
try
{
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + CaminhoDB + ";Jet OLEDB:Database Password=gds21"))
{
await conn.OpenAsync();
using (OleDbCommand cmd = new OleDbCommand(
@"INSERT INTO AgVirtual4DocsErros (
locationID, accountID, errorID, deliveryTimeStamp, provider, accessPoint, slaStatus,
healthy, blame, lastSuccess, active, blacklistStatus, lastActivated, lastDeactivated, lastDeactivatedBy
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", conn))
{
// Adiciona parâmetros de forma segura
cmd.Parameters.AddWithValue("@locationID", locationID);
cmd.Parameters.AddWithValue("@accountID", accountID);
cmd.Parameters.AddWithValue("@errorID", errorID);
cmd.Parameters.AddWithValue("@deliveryTimeStamp", deliveryTimeStamp);
cmd.Parameters.AddWithValue("@provider", provider);
cmd.Parameters.AddWithValue("@accessPoint", accessPoint);
cmd.Parameters.AddWithValue("@slaStatus", slaStatus);
cmd.Parameters.AddWithValue("@healthy", healthy);
cmd.Parameters.AddWithValue("@blame", blame);
cmd.Parameters.AddWithValue("@lastSuccess", lastSuccess);
cmd.Parameters.AddWithValue("@active", active);
cmd.Parameters.AddWithValue("@blacklistStatus", blacklistStatus);
cmd.Parameters.AddWithValue("@lastActivated", lastActivated);
cmd.Parameters.AddWithValue("@lastDeactivated", lastDeactivated);
cmd.Parameters.AddWithValue("@lastDeactivatedBy", lastDeactivatedBy);
// Executa o comando
await cmd.ExecuteNonQueryAsync();
}
}
break; // Sai do loop em caso de sucesso
}
catch (OleDbException ex)
{
// Registra o erro
logger.LogInformation($"Erro no OleDb insert: {ex.Message} (Tentativa {attempt + 1} de {maxRetries})");
if (attempt < maxRetries - 1)
{
// Aguarda antes de tentar novamente
await Task.Delay(1000 * (int)Math.Pow(2, attempt)); // Retry com Backoff Exponencial
}
else
{
// Propaga a exceção na última tentativa
throw;
}
}
finally
{
connLease.Dispose();
}
attempt++; // Incrementa a tentativa após adquirir o lease, mesmo que falhe
}
else
{
// Aguarda um curto período antes de tentar novamente se não conseguiu adquirir o lease
await Task.Delay(200);
}
errorText = deactivationReportElement.ToString();
}
else if (root.TryGetProperty("websiteText", out JsonElement websiteTextElement) && websiteTextElement.ValueKind != JsonValueKind.Null)
{
errorText = websiteTextElement.ToString();
}
else if (root.TryGetProperty("systemText", out JsonElement systemTextElement) && systemTextElement.ValueKind != JsonValueKind.Null)
{
errorText = systemTextElement.ToString();
}
else
{
errorText = "Erro desconhecido";
}
return errorText;
}
public static async Task<int> UpdateErrorIdStatusAsync(string CaminhoDB, double location_id, double errorID, string systemText, ILogger logger)
{
@ -381,7 +308,7 @@ namespace Webhook_4docs
SET errorID = @errorID, status = @status
WHERE location_id = @location_id", conn))
{
// Adiciona parâmetros de forma segura
// Adiciona par<EFBFBD>metros de forma segura
cmd.Parameters.AddWithValue("@errorID", errorID);
cmd.Parameters.AddWithValue("@status", systemText);
cmd.Parameters.AddWithValue("@location_id", location_id);
@ -405,7 +332,7 @@ namespace Webhook_4docs
}
else
{
// Propaga a exceção na última tentativa
// Propaga a exce<EFBFBD><EFBFBD>o na <20>ltima tentativa
throw;
}
}
@ -414,11 +341,11 @@ namespace Webhook_4docs
connLease.Dispose();
}
attempt++; // Incrementa a tentativa após adquirir o lease, mesmo que falhe
attempt++; // Incrementa a tentativa ap<EFBFBD>s adquirir o lease, mesmo que falhe
}
else
{
// Aguarda um curto período antes de tentar novamente se não conseguiu adquirir o lease
// Aguarda um curto per<EFBFBD>odo antes de tentar novamente se n<>o conseguiu adquirir o lease
await Task.Delay(200);
}
}