From a6143a239a01fbe47c753168e7319659dab6055e Mon Sep 17 00:00:00 2001 From: Adriano Serighelli Date: Wed, 17 Apr 2024 17:19:35 -0300 Subject: [PATCH] =?UTF-8?q?Verifica=C3=A7=C3=A3o=20da=20"sa=C3=BAde"=20do?= =?UTF-8?q?=20login=20e=20senha=20dos=20usu=C3=A1rios?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .editorconfig | 4 + .filenesting.json | 3 + Download Faturas/Download Faturas.csproj | 7 +- Download Faturas/Fatura.cs | 53 +++-- Download Faturas/Program.cs | 3 +- Faturas 4docs.sln | 7 +- Webhook 4docs/.config/dotnet-tools.json | 5 + .../20240321221626_InitialCreate.Designer.cs | 51 ++++ .../20240321221626_InitialCreate.cs | 38 +++ .../WebhookDbContextModelSnapshot.cs | 48 ++++ Webhook 4docs/Pages/Index.cshtml | 4 +- Webhook 4docs/ProcessedInvoices.cs | 12 + Webhook 4docs/Program.cs | 223 +++++++++++++++++- Webhook 4docs/ValuesController.cs | 50 ++++ Webhook 4docs/Webhook 4docs.csproj | 20 +- Webhook 4docs/WebhookDbContext.cs | 10 + Webhook 4docs/appsettings.json | 31 ++- Webhook 4docs/libman.json | 5 + 18 files changed, 542 insertions(+), 32 deletions(-) create mode 100644 .editorconfig create mode 100644 .filenesting.json create mode 100644 Webhook 4docs/.config/dotnet-tools.json create mode 100644 Webhook 4docs/Migrations/20240321221626_InitialCreate.Designer.cs create mode 100644 Webhook 4docs/Migrations/20240321221626_InitialCreate.cs create mode 100644 Webhook 4docs/Migrations/WebhookDbContextModelSnapshot.cs create mode 100644 Webhook 4docs/ProcessedInvoices.cs create mode 100644 Webhook 4docs/ValuesController.cs create mode 100644 Webhook 4docs/WebhookDbContext.cs create mode 100644 Webhook 4docs/libman.json diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..d96f02c --- /dev/null +++ b/.editorconfig @@ -0,0 +1,4 @@ +[*.cs] + +# ASP0014: Suggest using top level route registrations +dotnet_diagnostic.ASP0014.severity = none diff --git a/.filenesting.json b/.filenesting.json new file mode 100644 index 0000000..0b71966 --- /dev/null +++ b/.filenesting.json @@ -0,0 +1,3 @@ +{ + "help":"https://go.microsoft.com/fwlink/?linkid=866610" +} \ No newline at end of file diff --git a/Download Faturas/Download Faturas.csproj b/Download Faturas/Download Faturas.csproj index 2e6f1e1..e669b62 100644 --- a/Download Faturas/Download Faturas.csproj +++ b/Download Faturas/Download Faturas.csproj @@ -2,12 +2,17 @@ Exe - net6.0-windows + net7.0-windows Download_Faturas enable enable + AnyCPU + + + + diff --git a/Download Faturas/Fatura.cs b/Download Faturas/Fatura.cs index 9057a12..ffe9e22 100644 --- a/Download Faturas/Fatura.cs +++ b/Download Faturas/Fatura.cs @@ -4,6 +4,7 @@ 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; @@ -17,11 +18,8 @@ private const string Token = "UFY4VWzqcHYcGNd0gkBOMFL9G5ZThV6gXBQIJ79F5HSqITzavz4Fe7iXvAbJLvZJ"; private JsonElement faturaParsed; private string? id; - private string? empresa; - private string? unidade; private string? pastaMiddle; private string? uc; - private int mes; private int? pagina; public Fatura(string id, string fatura_path, HttpClient httpClient) @@ -49,6 +47,23 @@ } } + public Fatura(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; } @@ -63,8 +78,13 @@ RecordSet dadosTusd = new (); // Resultado da fatura processada - Rootobject parsedResult = JsonSerializer.Deserialize(this.faturaParsed.GetProperty("result")) !; - + JsonElement a; + if (!this.faturaParsed.TryGetProperty("result", out a)) + { + this.faturaParsed.TryGetProperty("json", out a); + } + + Rootobject parsedResult = JsonSerializer.Deserialize(a) !; 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); @@ -80,11 +100,11 @@ if (unidades == 1) { - sqlQuery = $"SELECT Cod_Smart_unidade, 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"; + 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"; } else { - sqlQuery = $"SELECT Cod_Smart_unidade, 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) OR (Razao_Social LIKE @razao_social AND Codigo_Instalacao = @uc)"; + 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) OR (Razao_Social LIKE @razao_social AND Codigo_Instalacao = @uc)"; } } @@ -126,8 +146,9 @@ dadosTusd.Dem_Cont_FP = float.Parse(reader["Demanda_FP"].ToString() !); dadosTusd.Perfil = reader["Perfil"].ToString(); this.pastaMiddle = reader["Caminho_NFs"].ToString(); - this.empresa = reader["Cliente"].ToString(); - this.unidade = reader["Unidade"].ToString(); + this.Gestao = reader["Gestao"].ToString(); + this.Empresa = reader["Cliente"].ToString(); + this.Unidade = reader["Unidade"].ToString(); } } } @@ -151,13 +172,13 @@ { this.Status = "UNIDADE CONSUMIDORA NÃO LOCALIZADA NO BD"; this.uc = uc; - this.mes = dadosTusd.Mes; + this.Mes = dadosTusd.Mes; } else if (tusdLanc) { this.Status = "FATURA DUPLICADA NO BD"; this.uc = uc; - this.mes = dadosTusd.Mes; + this.Mes = dadosTusd.Mes; } else { @@ -473,7 +494,7 @@ sqlQuery = "INSERT INTO Dados_TUSD ("; PropertyInfo[] propriedades = typeof(RecordSet).GetProperties(); - int i = 0; + /*int i = 0;*/ foreach (PropertyInfo propriedade in propriedades) { string nomeColuna = propriedade.Name; @@ -526,7 +547,7 @@ this.Status = "FATURA INCLUIDA NO BD"; this.uc = uc; - this.mes = dadosTusd.Mes; + this.Mes = dadosTusd.Mes; } } @@ -538,7 +559,7 @@ { 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"; + destino = this.Arquivo?.Directory?.Parent?.FullName + $@"\5 - {this.Status}\ID {this.id!} - Mês {this.Mes} - UC {this.uc}.pdf"; if (separar) { @@ -560,7 +581,7 @@ 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"; + 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) { @@ -582,7 +603,7 @@ case ("FATURA INCLUIDA NO BD", _): - destino = this.Arquivo?.Directory?.Parent?.FullName + $@"\6 - {this.Status}\ID {this.id!} - Mês {this.mes} - Empresa {this.empresa} - Unidade {this.unidade}.pdf"; + 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) { diff --git a/Download Faturas/Program.cs b/Download Faturas/Program.cs index ff5aca7..23ac122 100644 --- a/Download Faturas/Program.cs +++ b/Download Faturas/Program.cs @@ -35,7 +35,7 @@ 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 == "MULTACTIONABLE" | fatura_status == "ACTIONABLE" | fatura_status == string.Empty | fatura_status == "UNIDADE CONSUMIDORA NÃO LOCALIZADA NO BD" | fatura_status == "PREPROCESS") { @@ -127,7 +127,6 @@ sw.WriteLine(fatura); Console.WriteLine(fatura); } - } sr.Close(); diff --git a/Faturas 4docs.sln b/Faturas 4docs.sln index beb4d5e..14e2495 100644 --- a/Faturas 4docs.sln +++ b/Faturas 4docs.sln @@ -7,7 +7,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Upload Faturas", "Upload Fa EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Download Faturas", "Download Faturas\Download Faturas.csproj", "{580DACAB-DBAB-402D-AE0F-BA42A205F812}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Webhook 4docs", "Webhook 4docs\Webhook 4docs.csproj", "{75EFF4FA-14FE-4540-B872-F84224CDECAF}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Webhook 4docs", "Webhook 4docs\Webhook 4docs.csproj", "{75EFF4FA-14FE-4540-B872-F84224CDECAF}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{A8B5D0A5-BD74-42CF-ABB4-7CFCB0C18492}" + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/Webhook 4docs/.config/dotnet-tools.json b/Webhook 4docs/.config/dotnet-tools.json new file mode 100644 index 0000000..b0e38ab --- /dev/null +++ b/Webhook 4docs/.config/dotnet-tools.json @@ -0,0 +1,5 @@ +{ + "version": 1, + "isRoot": true, + "tools": {} +} \ No newline at end of file diff --git a/Webhook 4docs/Migrations/20240321221626_InitialCreate.Designer.cs b/Webhook 4docs/Migrations/20240321221626_InitialCreate.Designer.cs new file mode 100644 index 0000000..53a97ab --- /dev/null +++ b/Webhook 4docs/Migrations/20240321221626_InitialCreate.Designer.cs @@ -0,0 +1,51 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Webhook_4docs.Migrations +{ + [DbContext(typeof(WebhookDbContext))] + [Migration("20240321221626_InitialCreate")] + partial class InitialCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.17") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("ProcessedInvoices", b => + { + b.Property("InvoiceId") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("InvoiceId")); + + b.Property("DateTimeProcessed") + .HasColumnType("timestamp with time zone"); + + b.Property("InvoicePath") + .HasColumnType("text"); + + b.Property("Status") + .HasColumnType("text"); + + b.HasKey("InvoiceId"); + + b.ToTable("ProcessedInvoices"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Webhook 4docs/Migrations/20240321221626_InitialCreate.cs b/Webhook 4docs/Migrations/20240321221626_InitialCreate.cs new file mode 100644 index 0000000..3ca9b35 --- /dev/null +++ b/Webhook 4docs/Migrations/20240321221626_InitialCreate.cs @@ -0,0 +1,38 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Webhook_4docs.Migrations +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ProcessedInvoices", + columns: table => new + { + InvoiceId = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + DateTimeProcessed = table.Column(type: "timestamp with time zone", nullable: false), + Status = table.Column(type: "text", nullable: true), + InvoicePath = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_ProcessedInvoices", x => x.InvoiceId); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ProcessedInvoices"); + } + } +} diff --git a/Webhook 4docs/Migrations/WebhookDbContextModelSnapshot.cs b/Webhook 4docs/Migrations/WebhookDbContextModelSnapshot.cs new file mode 100644 index 0000000..803e749 --- /dev/null +++ b/Webhook 4docs/Migrations/WebhookDbContextModelSnapshot.cs @@ -0,0 +1,48 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Webhook_4docs.Migrations +{ + [DbContext(typeof(WebhookDbContext))] + partial class WebhookDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.17") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("ProcessedInvoices", b => + { + b.Property("InvoiceId") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("InvoiceId")); + + b.Property("DateTimeProcessed") + .HasColumnType("timestamp with time zone"); + + b.Property("InvoicePath") + .HasColumnType("text"); + + b.Property("Status") + .HasColumnType("text"); + + b.HasKey("InvoiceId"); + + b.ToTable("ProcessedInvoices"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Webhook 4docs/Pages/Index.cshtml b/Webhook 4docs/Pages/Index.cshtml index b5f0c15..7380f74 100644 --- a/Webhook 4docs/Pages/Index.cshtml +++ b/Webhook 4docs/Pages/Index.cshtml @@ -1,10 +1,10 @@ -@page +@page @model IndexModel @{ ViewData["Title"] = "Home page"; }
-

Welcome

+

Welcome Webserver

Learn about building Web apps with ASP.NET Core.

diff --git a/Webhook 4docs/ProcessedInvoices.cs b/Webhook 4docs/ProcessedInvoices.cs new file mode 100644 index 0000000..21f8575 --- /dev/null +++ b/Webhook 4docs/ProcessedInvoices.cs @@ -0,0 +1,12 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Text.Json.Serialization; + +public class ProcessedInvoices +{ + [Key] + public int InvoiceId { get; set; } + public DateTime DateTimeProcessed { get; set; } + public string? Status { get; set; } + public string? InvoicePath { get; set; } +} \ No newline at end of file diff --git a/Webhook 4docs/Program.cs b/Webhook 4docs/Program.cs index fc904d7..b0d9ae8 100644 --- a/Webhook 4docs/Program.cs +++ b/Webhook 4docs/Program.cs @@ -1,16 +1,69 @@ +using System.Data.OleDb; +using System.Text; +using System.Text.Json; +using Download_Faturas; +using Microsoft.AspNetCore.Http.Extensions; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Metadata.Internal; + namespace Webhook_4docs { public class Program { public static void Main(string[] args) { + string IndexedFilename(string stub, string extension) + { + int ix = 0; + string? filename = null; + + if (File.Exists(String.Format("{0}.{1}", stub, extension))) + { + do + { + ix++; + filename = String.Format("{0} ({1}).{2}", stub, ix, extension); + } while (File.Exists(filename)); + } + else + { + filename = String.Format("{0}.{1}", stub, extension); + } + return filename; + } + var builder = WebApplication.CreateBuilder(args); + builder.Configuration.AddJsonFile("appsettings.json"); + + var connectionString = builder.Configuration.GetConnectionString("WebhookDbContext"); + string? appFolder = builder.Configuration["PathBase"]; + + builder.Services.AddDbContext(options => + options.UseNpgsql(connectionString) + ); + + builder.Services.AddLogging(loggingBuilder => + { + loggingBuilder.ClearProviders(); + loggingBuilder.AddConsole(); + }); // Add services to the container. builder.Services.AddRazorPages(); var app = builder.Build(); + var logger = app.Services.GetRequiredService>(); + + using (var scope = app.Services.CreateScope()) + { + var dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Database.EnsureCreated(); + dbContext.Database.Migrate(); + } + + string fatura_arquivo; // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { @@ -18,17 +71,183 @@ namespace Webhook_4docs // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } + + - app.UseHttpsRedirection(); - app.UseStaticFiles(); + app.UsePathBase(appFolder); app.UseRouting(); + app.UseStaticFiles(); + app.UseAuthorization(); app.MapRazorPages(); + app.Use((context, next) => + { + context.Request.PathBase = new PathString(appFolder); + return next(context); + }); + + // Endpoint para \api + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + endpoints.MapPatch("/api", async context => + { + + string requestBody; + using (var reader = new StreamReader(context.Request.Body, Encoding.UTF8, true, 1024, true)) + { + requestBody = await reader.ReadToEndAsync(); + } + + var JsonBody = JsonDocument.Parse(requestBody).RootElement; + string CaminhoDB = "X:/Middle/Informativo Setorial/Modelo Word/BD1_dados cadastrais e faturas.accdb"; + + if (JsonBody.TryGetProperty("requestID", out _)) + { + string fatura_ID = JsonBody.GetProperty("requestID").ToString(); + + JsonElement DadosJson = JsonDocument.Parse(JsonBody.GetProperty("json").ToString()).RootElement; + + Fatura fatura = new Fatura(fatura_ID, JsonBody); + + using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + CaminhoDB + ";Jet OLEDB:Database Password=gds21")) + { + conn.Open(); + + fatura.Processar(conn); + } + + bool t = false; + + string? status = fatura.Status; + + int status_id = 0; + + switch (status) + { + case ("FATURA DUPLICADA NO BD"): + status_id = 4; + break; + case ("UNIDADE CONSUMIDORA NÃO LOCALIZADA NO BD"): + status_id = 5; + break; + case ("FATURA INCLUIDA NO BD"): + status_id = 6; + break; + case (_): + status = "ERRO"; + status_id = 7; + break; + } + + try + { + string path = $@"X:\Middle\Carteira {fatura.Gestao![0]}\Carteira {fatura.Gestao}\Faturas fourdocs\{status_id} - {status}"; + System.IO.Directory.CreateDirectory(path); + fatura_arquivo = IndexedFilename($@"{path}\ID {fatura_ID!} - Mês {fatura.Mes} - Empresa {fatura.Empresa} - Unidade {fatura.Unidade}", "pdf"); + t = CriarArquivo(fatura_arquivo, JsonBody.GetProperty("pdfFile").ToString()); + + var DatabaseModel = new ProcessedInvoices + { + InvoiceId = Int32.Parse(fatura_ID), + DateTimeProcessed = DateTime.UtcNow, + Status = status, + InvoicePath = fatura_arquivo + }; + + logger.LogInformation("Fatura incluída no BD"); + + using (var scope = app.Services.CreateScope()) + { + var dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.ProcessedInvoices.Add(DatabaseModel); + await dbContext.SaveChangesAsync(); + } + + logger.LogInformation("Fatura salva na pasta " + fatura_arquivo); + } + catch + { + t = false; + logger.LogError("Erro no processamento da fatura"); + } + + } + else if (JsonBody.TryGetProperty("healthy", out _) && JsonBody.TryGetProperty("blame", out _) && JsonBody.TryGetProperty("locationID", out _)) + { + double errorID = 0; + + switch (JsonBody.GetProperty("healthy").GetBoolean(), JsonBody.GetProperty("blame").ToString()) + { + case (false, "user"): + logger.LogError("Loc ID: " + JsonBody.GetProperty("locationID").ToString() + " Sem acesso"); + errorID = 1; + break; + case (false, "system"): + logger.LogError("Loc ID: " + JsonBody.GetProperty("locationID").ToString() + " Com erro de sistema"); + errorID = 2; + break; + case (false, _): + logger.LogError("Loc ID: " + JsonBody.GetProperty("locationID").ToString() + " Com erro " + JsonBody.GetProperty("blame").ToString()); + errorID = 3; + break; + case (true, _): + logger.LogInformation("Loc ID: " + JsonBody.GetProperty("locationID").ToString() + " está saudável"); + break; + } + + UpdateErrorIdStatus(CaminhoDB, JsonBody.GetProperty("locationID").GetInt64(), errorID); + + } + }); + }); app.Run(); } + public static void UpdateErrorIdStatus(string CaminhoDB, double location_id, double errorID) + { + using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + CaminhoDB + ";Jet OLEDB:Database Password=gds21")) + { + conn.Open(); + + using (OleDbCommand cmd = new OleDbCommand($"UPDATE AgVirtual4Docs SET AgVirtual4Docs.errorID = {errorID}\r\nWHERE (((AgVirtual4Docs.location_id)={location_id}));\r\n", conn)) + { + //cmd.Parameters.AddWithValue("@location_id", location_id); + //cmd.Parameters.AddWithValue("@errorID", errorID); + int test = cmd.ExecuteNonQuery(); + } + using (OleDbCommand cmd = new OleDbCommand($"SELECT location_id, errorID FROM AgVirtual4Docs WHERE location_id = @location_id", conn)) + { + cmd.Parameters.AddWithValue("@location_id", location_id); + using (OleDbDataReader reader = cmd.ExecuteReader()) + { + while(reader.Read()) + { + string? test = reader["errorID"].ToString(); + } + } + } + } + } + public static bool CriarArquivo(string fatura_arquivo, string pdfFile64) + { + //string fatura_arquivo = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\test.pdf"; + bool t = false; + if (!File.Exists(fatura_arquivo)) + { + byte[] bytes = Convert.FromBase64String(pdfFile64); + + System.IO.FileStream stream = new FileStream(fatura_arquivo, FileMode.CreateNew); + System.IO.BinaryWriter writer = + new BinaryWriter(stream); + writer.Write(bytes, 0, bytes.Length); + writer.Close(); + t = true; + } + return t; + } } } \ No newline at end of file diff --git a/Webhook 4docs/ValuesController.cs b/Webhook 4docs/ValuesController.cs new file mode 100644 index 0000000..8f281af --- /dev/null +++ b/Webhook 4docs/ValuesController.cs @@ -0,0 +1,50 @@ +//using Microsoft.AspNetCore.Mvc; + +//// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 + +//namespace Webhook_4docs +//{ +// [Route("api/[controller]")] +// [ApiController] +// public class ValuesController : ControllerBase +// { +// // GET: api/ +// [HttpGet] +// public IEnumerable Get() +// { +// return new string[] { "value1", "value2" }; +// } + +// // GET api//5 +// [HttpGet("{id}")] +// public string Get(int id) +// { +// return "value"; +// } + +// // POST api/ +// [HttpPost] +// public IEnumerable Post([FromBody] string value) +// { +// return new string[] { "value1", "value2" }; +// } + +// // PUT api//5 +// [HttpPut("{id}")] +// public void Put(int id, [FromBody] string value) +// { +// } + +// // DELETE api//5 +// [HttpDelete("{id}")] +// public void Delete(int id) +// { +// } + +// // PATCH api/ +// [HttpPatch] +// public void Patch() +// { +// } +// } +//} diff --git a/Webhook 4docs/Webhook 4docs.csproj b/Webhook 4docs/Webhook 4docs.csproj index 0131827..c947e5a 100644 --- a/Webhook 4docs/Webhook 4docs.csproj +++ b/Webhook 4docs/Webhook 4docs.csproj @@ -1,10 +1,28 @@ - net7.0 + net7.0-windows enable enable Webhook_4docs + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + diff --git a/Webhook 4docs/WebhookDbContext.cs b/Webhook 4docs/WebhookDbContext.cs new file mode 100644 index 0000000..c8b5453 --- /dev/null +++ b/Webhook 4docs/WebhookDbContext.cs @@ -0,0 +1,10 @@ +using Microsoft.EntityFrameworkCore; + +public class WebhookDbContext : DbContext +{ + public WebhookDbContext(DbContextOptions options) : base(options) + { + } + + public DbSet ProcessedInvoices { get; set; } +} diff --git a/Webhook 4docs/appsettings.json b/Webhook 4docs/appsettings.json index 10f68b8..a710ae7 100644 --- a/Webhook 4docs/appsettings.json +++ b/Webhook 4docs/appsettings.json @@ -1,9 +1,26 @@ { - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*" + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Microsoft.EntityFrameworkCore": "Warning" + }, + "Console": { + "TimestampFormat": "[dd/MM/yy HH:mm] " + } + }, + "AllowedHosts": "*", + "ConnectionStrings": { + "WebhookDbContext": "Server=192.168.10.248;Port=5432;Database=4docs;User Id=postgres;Password=gds21;" + + }, + "Kestrel": { + "Endpoints": { + "HttpLocalhost": { + "Url": "http://localhost:8664/" + } + } + }, + "PathBase": "/4docs" + } diff --git a/Webhook 4docs/libman.json b/Webhook 4docs/libman.json new file mode 100644 index 0000000..ceee271 --- /dev/null +++ b/Webhook 4docs/libman.json @@ -0,0 +1,5 @@ +{ + "version": "1.0", + "defaultProvider": "cdnjs", + "libraries": [] +} \ No newline at end of file