Atualizar ExcelController para suportar novo modelo de dados e ajustar caminhos de arquivo; alterar target framework para net8.0; adicionar suporte para template.xlsx; implementar processamento de argumentos de linha de comando.

This commit is contained in:
Giuliano Paschoalino 2025-07-15 13:43:06 -03:00
parent a87e84d165
commit b6f9cad6a6
5 changed files with 161 additions and 81 deletions

13
.config/dotnet-tools.json Normal file
View File

@ -0,0 +1,13 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "9.0.0",
"commands": [
"dotnet-ef"
],
"rollForward": false
}
}
}

View File

@ -28,12 +28,16 @@ namespace ImpressãoFaturamento.Controllers
return StatusCode(500, "An error occurred while processing the file.");
}
private string WriteDataToExcel(FaturamentoModel data)
internal string WriteDataToExcel(FaturamentoModel data)
{
#if DEBUG
string templatePath = Path.Combine(Directory.GetCurrentDirectory(), "template.xlsx");
string pdfOutputPath = Path.Combine(Directory.GetCurrentDirectory(), data.DadosCadastrais.NomeUnidade + ".pdf");
Application excelApp = new Application();
#else
string templatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "template.xlsx");
string pdfOutputPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, data.DadosCadastrais.NomeUnidade + ".pdf");
#endif
Application excelApp = new();
Workbooks workbooks = excelApp.Workbooks;
Workbook workbook = workbooks.Open(templatePath);
Worksheet worksheet = (Worksheet)workbook.Worksheets[1];
@ -49,6 +53,7 @@ namespace ImpressãoFaturamento.Controllers
worksheet.Cells[6, "G"].Value = data.DadosCadastrais.DescontoTUSD;
worksheet.Cells[5, "L"].Value = data.DadosCadastrais.PercentualUnidade;
worksheet.Cells[4, "R"].Value = data.DadosCadastrais.CustoTotalCCEE;
worksheet.Cells[9, "M"].Value = data.DadosCadastrais.TipoFaturamento;
//dados de faturamento - Cativo
int linha = 11;
@ -78,7 +83,7 @@ namespace ImpressãoFaturamento.Controllers
linha++;
}
faturamento(workbook, worksheet);
//faturamento(workbook, worksheet);
workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, pdfOutputPath);
workbook.Close(false);
@ -91,92 +96,92 @@ namespace ImpressãoFaturamento.Controllers
return pdfOutputPath;
}
public void faturamento(Workbook workbook, Worksheet worksheet)
{
float idUnidade = worksheet.Cells[70, "A"].Value;
float mesRef = worksheet.Cells[70, "D"].Value;
float tipoFaturamento = worksheet.Cells[70, "I"].Value;
float cod_fatura = idUnidade + mesRef + tipoFaturamento;
string empresa = worksheet.Cells[70, "B"].Value;
string unidade = worksheet.Cells[70, "C"].Value;
decimal custoCativo = worksheet.Cells[70, "E"].Value;
decimal custoLivre = worksheet.Cells[70, "F"].Value;
decimal economia = worksheet.Cells[70, "G"].Value;
decimal remuneracao = worksheet.Cells[70, "H"].Value;
decimal remuneracaoFixo = worksheet.Cells[70, "J"].Value;
decimal remuneracaoPiso = worksheet.Cells[70, "K"].Value;
decimal remuneracaoTeto = worksheet.Cells[70, "L"].Value;
decimal remuneracaoPercentual = worksheet.Cells[70, "M"].Value;
//public void faturamento(Workbook workbook, Worksheet worksheet)
//{
// float idUnidade = worksheet.Cells[70, "A"].Value;
// float mesRef = worksheet.Cells[70, "D"].Value;
// float tipoFaturamento = worksheet.Cells[70, "I"].Value;
// float cod_fatura = idUnidade + mesRef + tipoFaturamento;
// string empresa = worksheet.Cells[70, "B"].Value;
// string unidade = worksheet.Cells[70, "C"].Value;
// decimal custoCativo = worksheet.Cells[70, "E"].Value;
// decimal custoLivre = worksheet.Cells[70, "F"].Value;
// decimal economia = worksheet.Cells[70, "G"].Value;
// decimal remuneracao = worksheet.Cells[70, "H"].Value;
// decimal remuneracaoFixo = worksheet.Cells[70, "J"].Value;
// decimal remuneracaoPiso = worksheet.Cells[70, "K"].Value;
// decimal remuneracaoTeto = worksheet.Cells[70, "L"].Value;
// decimal remuneracaoPercentual = worksheet.Cells[70, "M"].Value;
int numeroUnidades = Convert.ToInt32(unidade);
// int numeroUnidades = Convert.ToInt32(unidade);
var pdfOutputPath = Path.Combine(Directory.GetCurrentDirectory(), idUnidade + ".pdf");
// var pdfOutputPath = Path.Combine(Directory.GetCurrentDirectory(), idUnidade + ".pdf");
if (remuneracaoFixo != 0 || numeroUnidades == 1)
{
//imprimir remuneracao fixa
workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, pdfOutputPath);
// if (remuneracaoFixo != 0 || numeroUnidades == 1)
// {
// //imprimir remuneracao fixa
// workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, pdfOutputPath);
}
// }
if (remuneracaoFixo == 0 || numeroUnidades != 1)
{
//imprimir remuneracao piso/teto/percentual
worksheet.Cells[61, "F"].Value = remuneracaoPiso;
//TODO: imprimir
worksheet.Cells[61, "F"].Value = remuneracaoTeto;
//TODO: imprimir
worksheet.Cells[61, "F"].Value = remuneracaoPercentual;
//TODO: imprimir
// if (remuneracaoFixo == 0 || numeroUnidades != 1)
// {
// //imprimir remuneracao piso/teto/percentual
// worksheet.Cells[61, "F"].Value = remuneracaoPiso;
// //TODO: imprimir
// worksheet.Cells[61, "F"].Value = remuneracaoTeto;
// //TODO: imprimir
// worksheet.Cells[61, "F"].Value = remuneracaoPercentual;
// //TODO: imprimir
workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, pdfOutputPath);
}
// workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, pdfOutputPath);
// }
//Conexão com o banco de dados Access
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=CaminhoParaSeuBancoDeDados.accdb;Jet OLEDB:Database Password=SuaSenha;";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
// //Conexão com o banco de dados Access
// string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=CaminhoParaSeuBancoDeDados.accdb;Jet OLEDB:Database Password=SuaSenha;";
// using (OleDbConnection connection = new OleDbConnection(connectionString))
// {
// connection.Open();
// Atualizar o registro se ele já existir
string updateQuery = "UPDATE TabelaResumoFaturamento SET ValorTotal = @ValorTotal WHERE IdUnidade = @IdUnidade";
using (OleDbCommand updateCommand = new OleDbCommand(updateQuery, connection))
{
updateCommand.Parameters.AddWithValue("@ValorTotal", remuneracao);
updateCommand.Parameters.AddWithValue("@IdUnidade", idUnidade);
int rowsUpdated = updateCommand.ExecuteNonQuery();
// // Atualizar o registro se ele já existir
// string updateQuery = "UPDATE TabelaResumoFaturamento SET ValorTotal = @ValorTotal WHERE IdUnidade = @IdUnidade";
// using (OleDbCommand updateCommand = new OleDbCommand(updateQuery, connection))
// {
// updateCommand.Parameters.AddWithValue("@ValorTotal", remuneracao);
// updateCommand.Parameters.AddWithValue("@IdUnidade", idUnidade);
// int rowsUpdated = updateCommand.ExecuteNonQuery();
// Se nenhum registro foi atualizado, inserir um novo registro
if (rowsUpdated == 0)
{
string insertQuery = "INSERT INTO TabelaResumoFaturamento (IdUnidade, MesRef, TipoFaturamento, ValorTotal) VALUES (@IdUnidade, @MesRef, @TipoFaturamento, @ValorTotal)";
using (OleDbCommand insertCommand = new OleDbCommand(insertQuery, connection))
{
insertCommand.Parameters.AddWithValue("@IdUnidade", idUnidade);
insertCommand.Parameters.AddWithValue("@MesRef", mesRef);
insertCommand.Parameters.AddWithValue("@TipoFaturamento", tipoFaturamento);
insertCommand.Parameters.AddWithValue("@ValorTotal", remuneracao);
insertCommand.ExecuteNonQuery();
}
}
}
// // Se nenhum registro foi atualizado, inserir um novo registro
// if (rowsUpdated == 0)
// {
// string insertQuery = "INSERT INTO TabelaResumoFaturamento (IdUnidade, MesRef, TipoFaturamento, ValorTotal) VALUES (@IdUnidade, @MesRef, @TipoFaturamento, @ValorTotal)";
// using (OleDbCommand insertCommand = new OleDbCommand(insertQuery, connection))
// {
// insertCommand.Parameters.AddWithValue("@IdUnidade", idUnidade);
// insertCommand.Parameters.AddWithValue("@MesRef", mesRef);
// insertCommand.Parameters.AddWithValue("@TipoFaturamento", tipoFaturamento);
// insertCommand.Parameters.AddWithValue("@ValorTotal", remuneracao);
// insertCommand.ExecuteNonQuery();
// }
// }
// }
// Verificar se é a última unidade faturada
if (unidadesFaturadas == numeroUnidades)
{
//TODO: comparar faturamento global e atualizar faturamento final
//TODO: manter somente o faturamento correto
// Atualizar o resumo de faturamento
string updateQuery = "UPDATE TabelaResumoFaturamento SET ValorTotal = @ValorTotal WHERE IdUnidade = @IdUnidade";
using (OleDbCommand updateCommand = new OleDbCommand(updateQuery, connection))
{
updateCommand.Parameters.AddWithValue("@ValorTotal", remuneracao);
updateCommand.Parameters.AddWithValue("@IdUnidade", idUnidade);
updateCommand.ExecuteNonQuery();
}
}
}
}
// // Verificar se é a última unidade faturada
// if (unidadesFaturadas == numeroUnidades)
// {
// //TODO: comparar faturamento global e atualizar faturamento final
// //TODO: manter somente o faturamento correto
// // Atualizar o resumo de faturamento
// string updateQuery = "UPDATE TabelaResumoFaturamento SET ValorTotal = @ValorTotal WHERE IdUnidade = @IdUnidade";
// using (OleDbCommand updateCommand = new OleDbCommand(updateQuery, connection))
// {
// updateCommand.Parameters.AddWithValue("@ValorTotal", remuneracao);
// updateCommand.Parameters.AddWithValue("@IdUnidade", idUnidade);
// updateCommand.ExecuteNonQuery();
// }
// }
// }
//}
}
}

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0-windows8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
@ -24,4 +24,10 @@
<PackageReference Include="System.Data.OleDb" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<None Update="template.xlsx">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -33,6 +33,9 @@ namespace ImpressãoFaturamento.Models
[JsonPropertyName("custo_total_CCEE")]
public decimal CustoTotalCCEE { get; set; }
[JsonPropertyName("tipo_faturamento")]
public string TipoFaturamento { get; set; }
}
public class ItemFaturamento

View File

@ -1,3 +1,14 @@
using ImpressãoFaturamento.Controllers;
using ImpressãoFaturamento.Models;
//args = [@"C:\Users\contratos\AppData\Local\Temp\json_input.json"];
if (args.Length > 0)
{
ProcessCommandLineArguments(args);
return;
}
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
@ -23,3 +34,45 @@ app.UseAuthorization();
app.MapControllers();
app.Run();
static void ProcessCommandLineArguments(string[] arguments)
{
Console.WriteLine("Recebendo JSON via linha de comando...");
if (arguments.Length != 1)
{
Console.WriteLine("Erro: Um único argumento contendo o JSON é esperado.");
return;
}
string jsonInput = arguments[0];
if (!File.Exists(jsonInput))
{
Console.WriteLine($"Erro: O arquivo '{jsonInput}' não foi encontrado.");
return;
}
try
{
string jsonContent = File.ReadAllText(jsonInput);
var data = System.Text.Json.JsonSerializer.Deserialize<FaturamentoModel>(jsonContent);
if (data != null)
{
ExcelController controller = new();
string pdfPath = controller.WriteDataToExcel(data);
Console.WriteLine($"PDF gerado com sucesso: {pdfPath}");
}
else
{
throw new ArgumentNullException("Faturamento", "Dados inválidos.");
}
}
catch (Exception ex)
{
Console.WriteLine($"Erro ao processar o JSON: {ex.Message}");
}
}