ImpressaoFaturamento/Controllers/ExcelController.cs

188 lines
8.7 KiB
C#

using Microsoft.AspNetCore.Mvc;
using ImpressãoFaturamento.Models;
using Microsoft.Office.Interop.Excel;
using System.Data.OleDb;
namespace ImpressãoFaturamento.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class ExcelController : ControllerBase
{
[HttpPost]
public IActionResult Post([FromBody] FaturamentoModel data)
{
if (data == null)
{
return BadRequest("Invalid data.");
}
var filePath = WriteDataToExcel(data);
if (!string.IsNullOrEmpty(filePath))
{
return Ok("File created and printed successfully.");
}
return StatusCode(500, "An error occurred while processing the file.");
}
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");
#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];
//dados cadastrais
worksheet.Cells[3, "C"].Value = data.DadosCadastrais.NomeCliente;
worksheet.Cells[4, "C"].Value = data.DadosCadastrais.NomeUnidade;
worksheet.Cells[5, "C"].Value = data.DadosCadastrais.MesConsumo;
worksheet.Cells[6, "C"].Value = data.DadosCadastrais.BandeiraCativo;
worksheet.Cells[3, "G"].Value = data.DadosCadastrais.ICMS;
worksheet.Cells[4, "G"].Value = data.DadosCadastrais.PIS_COFINS;
worksheet.Cells[5, "G"].Value = data.DadosCadastrais.FatorTributo;
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;
foreach (var item in data.Faturamento.Cativo)
{
worksheet.Cells[linha, "B"].Value = item.Nome;
worksheet.Cells[linha, "C"] = item.Quantidade;
worksheet.Cells[linha, "E"] = item.Tarifa;
worksheet.Cells[linha, "G"] = item.Subtotal;
worksheet.Cells[linha, "H"] = item.TipoImposto;
worksheet.Cells[linha, "I"].Value = item.ValorFinal;
linha++;
}
//dados de faturamento - Livre
linha = 33;
foreach (var item in data.Faturamento.Livre)
{
worksheet.Cells[linha, "B"].Value = item.Nome;
worksheet.Cells[linha, "C"] = item.Quantidade;
worksheet.Cells[linha, "E"] = item.Tarifa;
worksheet.Cells[linha, "G"] = item.Subtotal;
worksheet.Cells[linha, "H"] = item.TipoImposto;
worksheet.Cells[linha, "I"].Value = item.ValorFinal;
linha++;
}
//faturamento(workbook, worksheet);
workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, pdfOutputPath);
workbook.Close(false);
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
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;
// int numeroUnidades = Convert.ToInt32(unidade);
// 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 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);
// }
// //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();
// // 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();
// }
// }
// }
//}
}
}