Metodos que creaban dialogos a clases

Se separaron estos metodos para mayor claridad en el codigo y mas facil
reutilizacion de los dialogos ya que ahora me vi en el caso de que me
encontraba utilizando estos metodos  en 2 vistas separadas y me vi
copiando los metodos de una a otra, pero eso no es bonito! asi que las
separe en clases con un solo metodo publico llamado execute el cual
devuelve el objeto que se espera recibir o un null en caso de que el
usuario cancele el dialogo o ocurra algun error.
This commit is contained in:
Daniel Cortes
2019-02-27 02:48:54 -03:00
parent f5b44f32fe
commit 57d6d62b10
12 changed files with 668 additions and 194 deletions

BIN
dist/Programa Caja.jar vendored

Binary file not shown.

View File

@@ -23,4 +23,4 @@ look_and_feel = javax.swing.plaf.metal.MetalLookAndFeel
nombre_caja = DEV nombre_caja = DEV
# directorio en el que sugerir donde guardar los informes. # directorio en el que sugerir donde guardar los informes.
base_save_directory =/home/ryuuji/src/caja/dist/local-release/informes/ base_save_directory =/home/ryuuji/src/caja/dist/informes/

View File

@@ -27,11 +27,14 @@ package danielcortes.xyz;
import danielcortes.xyz.controllers.BaseLayoutController; import danielcortes.xyz.controllers.BaseLayoutController;
import danielcortes.xyz.data.Configuration; import danielcortes.xyz.data.Configuration;
import danielcortes.xyz.data.DAOManager; import danielcortes.xyz.data.DAOManager;
import danielcortes.xyz.informes.InformeEstadoResultado;
import danielcortes.xyz.views.BaseLayout; import danielcortes.xyz.views.BaseLayout;
import javax.swing.*; import javax.swing.*;
import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.time.YearMonth;
import java.util.Locale; import java.util.Locale;
import java.util.logging.LogManager; import java.util.logging.LogManager;
@@ -47,6 +50,11 @@ public class Main {
run(); run();
} }
public static void generarInforme(){
File file = new File(Configuration.get("base_save_directory") + "test.xls");
new InformeEstadoResultado(YearMonth.of(2019,2), file.toPath()).generarInforme();
}
private static void run() { private static void run() {
BaseLayout view = new BaseLayout(); BaseLayout view = new BaseLayout();
BaseLayoutController controller = new BaseLayoutController(view); BaseLayoutController controller = new BaseLayoutController(view);

View File

@@ -1,15 +1,22 @@
package danielcortes.xyz.controllers; package danielcortes.xyz.controllers;
import danielcortes.xyz.data.Configuration;
import danielcortes.xyz.data.DAOManager; import danielcortes.xyz.data.DAOManager;
import danielcortes.xyz.informes.InformeEstadoResultado;
import danielcortes.xyz.models.estado_resultado.EstadoResultado; import danielcortes.xyz.models.estado_resultado.EstadoResultado;
import danielcortes.xyz.models.estado_resultado.EstadoResultadoDAO; import danielcortes.xyz.models.estado_resultado.EstadoResultadoDAO;
import danielcortes.xyz.models.tipo_egreso.TipoEgreso; import danielcortes.xyz.models.tipo_egreso.TipoEgreso;
import danielcortes.xyz.utils.StringUtils;
import danielcortes.xyz.views.EstadoResultadoView; import danielcortes.xyz.views.EstadoResultadoView;
import danielcortes.xyz.views.dialogs.InformeGeneratedConfirmation;
import danielcortes.xyz.views.dialogs.XLSFileChooser;
import danielcortes.xyz.views.listeners.FocusLostListener; import danielcortes.xyz.views.listeners.FocusLostListener;
import java.nio.file.Path;
import java.time.YearMonth; import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
public class EstadoResultadoController extends BaseController{ public class EstadoResultadoController extends BaseController {
private EstadoResultadoView view; private EstadoResultadoView view;
private EstadoResultado estadoResultado; private EstadoResultado estadoResultado;
private YearMonth mes; private YearMonth mes;
@@ -20,11 +27,7 @@ public class EstadoResultadoController extends BaseController{
this.updateMonth(); this.updateMonth();
} }
public EstadoResultadoView getView() { public void update() {
return view;
}
public void update(){
this.updateMonth(); this.updateMonth();
} }
@@ -36,9 +39,10 @@ public class EstadoResultadoController extends BaseController{
this.setupMovementViewEvents(); this.setupMovementViewEvents();
this.view.getGuardarButton().addActionListener(e -> EstadoResultadoController.this.guardarListener()); this.view.getGuardarButton().addActionListener(e -> EstadoResultadoController.this.guardarListener());
this.view.getExportarButton().addActionListener(e -> EstadoResultadoController.this.exportarListener());
} }
private void setupUpdateViewEvents(){ private void setupUpdateViewEvents() {
this.view.getGastosGeneralesCuentaCorrienteFactura().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateGastosGenerales()); this.view.getGastosGeneralesCuentaCorrienteFactura().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateGastosGenerales());
this.view.getGastosGeneralesCuentaCorrienteBoleta().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateGastosGenerales()); this.view.getGastosGeneralesCuentaCorrienteBoleta().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateGastosGenerales());
this.view.getGastosGeneralesCuentaCorrienteSinRespaldo().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateGastosGenerales()); this.view.getGastosGeneralesCuentaCorrienteSinRespaldo().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateGastosGenerales());
@@ -89,6 +93,22 @@ public class EstadoResultadoController extends BaseController{
dao.updateEstadoResultado(this.estadoResultado); dao.updateEstadoResultado(this.estadoResultado);
} }
private void exportarListener() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy");
String formatedName = mes.format(formatter);
String capitalized = StringUtils.capitalize(formatedName);
Path saveFile = new XLSFileChooser(Configuration.get("base_save_directory") + "Estado Resultado " + capitalized).execute();
if(saveFile == null){
return;
}
InformeEstadoResultado estadoResultado = new InformeEstadoResultado(this.mes, saveFile);
estadoResultado.generarInforme();
new InformeGeneratedConfirmation(saveFile).execute();
}
private void updateMonth() { private void updateMonth() {
this.mes = this.view.getMonth(); this.mes = this.view.getMonth();
this.estadoResultado = DAOManager.getEstadoResultadoDAO().findByMonth(this.mes); this.estadoResultado = DAOManager.getEstadoResultadoDAO().findByMonth(this.mes);
@@ -108,8 +128,8 @@ public class EstadoResultadoController extends BaseController{
private void fillVentas() { private void fillVentas() {
int ventaBruta = DAOManager.getIngresoDAO().getTotalIngresoMes(this.mes); int ventaBruta = DAOManager.getIngresoDAO().getTotalIngresoMes(this.mes);
int ventaExentas = DAOManager.getIngresoDAO().getTotalExentasMes(this.mes); int ventaExentas = DAOManager.getIngresoDAO().getTotalExentasMes(this.mes);
int ventaIVA = (int) Math.round((double) ventaBruta * .19d); int ventaNeta = (int) Math.round((double) ventaBruta / 1.19d);
int ventaNeta = ventaBruta - ventaIVA; int ventaIVA = ventaBruta - ventaNeta;
int ventaNetaYExentas = ventaExentas + ventaNeta; int ventaNetaYExentas = ventaExentas + ventaNeta;
this.view.getVentaBrutaField().setValue(ventaBruta); this.view.getVentaBrutaField().setValue(ventaBruta);
@@ -120,21 +140,17 @@ public class EstadoResultadoController extends BaseController{
} }
private void fillGastosGenerales() { private void fillGastosGenerales() {
TipoEgreso facturaMateriaPrima = DAOManager.getTipoEgresoDAO().findByNombre("Factura Materia Prima").get(0);
TipoEgreso facturaGastosGenerales = DAOManager.getTipoEgresoDAO().findByNombre("Factura Gastos Generales").get(0); TipoEgreso facturaGastosGenerales = DAOManager.getTipoEgresoDAO().findByNombre("Factura Gastos Generales").get(0);
TipoEgreso gastoGeneralConBoleta = DAOManager.getTipoEgresoDAO().findByNombre("Gasto General Con Boleta").get(0); TipoEgreso gastoGeneralConBoleta = DAOManager.getTipoEgresoDAO().findByNombre("Gasto General Con Boleta").get(0);
TipoEgreso gastoMenorMateriaPrima = DAOManager.getTipoEgresoDAO().findByNombre("Gasto Menor Materia Prima").get(0);
TipoEgreso gastoGeneralSinRespaldo = DAOManager.getTipoEgresoDAO().findByNombre("Gasto General Sin Respaldo").get(0); TipoEgreso gastoGeneralSinRespaldo = DAOManager.getTipoEgresoDAO().findByNombre("Gasto General Sin Respaldo").get(0);
int cuentaCorrienteFactura = this.estadoResultado.getCuentaCorrienteFactura(); int cuentaCorrienteFactura = this.estadoResultado.getCuentaCorrienteFactura();
int cuentaCorrienteBoleta = this.estadoResultado.getCuentaCorrienteBoleta(); int cuentaCorrienteBoleta = this.estadoResultado.getCuentaCorrienteBoleta();
int cuentaCorrienteSinRespaldo = this.estadoResultado.getCuentaCorrienteSinRespaldo(); int cuentaCorrienteSinRespaldo = this.estadoResultado.getCuentaCorrienteSinRespaldo();
int efectivoFacturaMateriaPrima = DAOManager.getEgresoDAO().getTotalEgresoMesPorTipo(this.mes, facturaMateriaPrima);
int efectivoFacturaGastosGenerales = DAOManager.getEgresoDAO().getTotalEgresoMesPorTipo(this.mes, facturaGastosGenerales); int efectivoFacturaGastosGenerales = DAOManager.getEgresoDAO().getTotalEgresoMesPorTipo(this.mes, facturaGastosGenerales);
int efectivoGastoGeneralConBoleta = DAOManager.getEgresoDAO().getTotalEgresoMesPorTipo(this.mes, gastoGeneralConBoleta); int efectivoGastoGeneralConBoleta = DAOManager.getEgresoDAO().getTotalEgresoMesPorTipo(this.mes, gastoGeneralConBoleta);
int efectivoGastoMenorMateriaPrima = DAOManager.getEgresoDAO().getTotalEgresoMesPorTipo(this.mes, gastoMenorMateriaPrima);
int efectivoGastoGeneralSinRespaldo = DAOManager.getEgresoDAO().getTotalEgresoMesPorTipo(this.mes, gastoGeneralSinRespaldo); int efectivoGastoGeneralSinRespaldo = DAOManager.getEgresoDAO().getTotalEgresoMesPorTipo(this.mes, gastoGeneralSinRespaldo);
int gastoTotal = efectivoFacturaMateriaPrima + efectivoFacturaGastosGenerales + efectivoGastoGeneralConBoleta + efectivoGastoMenorMateriaPrima + efectivoGastoGeneralSinRespaldo + cuentaCorrienteBoleta + cuentaCorrienteFactura + cuentaCorrienteSinRespaldo; int gastoTotal = efectivoFacturaGastosGenerales + efectivoGastoGeneralConBoleta + efectivoGastoGeneralSinRespaldo + cuentaCorrienteBoleta + cuentaCorrienteFactura + cuentaCorrienteSinRespaldo;
this.view.getGastosGeneralesEfectivoFacturaField().setValue(efectivoFacturaGastosGenerales); this.view.getGastosGeneralesEfectivoFacturaField().setValue(efectivoFacturaGastosGenerales);
this.view.getGastosGeneralesEfectivoBoletaField().setValue(efectivoGastoGeneralConBoleta); this.view.getGastosGeneralesEfectivoBoletaField().setValue(efectivoGastoGeneralConBoleta);
@@ -160,7 +176,7 @@ public class EstadoResultadoController extends BaseController{
int total = costoVenta + remuneraciones + finiquitos + aguinaldo + bonosPersonal int total = costoVenta + remuneraciones + finiquitos + aguinaldo + bonosPersonal
+ honorariosContador + arriendo + partime; + honorariosContador + arriendo + partime;
double porcentajeCostoVenta = (double) costoVenta / (double)ventaBruta * 100d; double porcentajeCostoVenta = (double) costoVenta / (double) ventaBruta * 100d;
this.view.getGastosOperacionalesCostoVenta().setValue(costoVenta); this.view.getGastosOperacionalesCostoVenta().setValue(costoVenta);
this.view.getGastosOperacionesPorcentajeCostoVenta().setValue(porcentajeCostoVenta); this.view.getGastosOperacionesPorcentajeCostoVenta().setValue(porcentajeCostoVenta);
@@ -285,7 +301,7 @@ public class EstadoResultadoController extends BaseController{
int total = oldTotal int total = oldTotal
- (oldCostoVenta + oldRemuneraciones + oldFiniquitos + oldAguinaldo + oldBonos + oldHonorarios + oldArriendo) - (oldCostoVenta + oldRemuneraciones + oldFiniquitos + oldAguinaldo + oldBonos + oldHonorarios + oldArriendo)
+ (costoVenta + remuneraciones + finiquitos + aguinaldo + bonos + honorarios + arriendo); + (costoVenta + remuneraciones + finiquitos + aguinaldo + bonos + honorarios + arriendo);
double porcentajeCostoVenta = (double) costoVenta / (double)ventaBruta * 100d; double porcentajeCostoVenta = (double) costoVenta / (double) ventaBruta * 100d;
this.view.getGastosOperacionalesTotal().setValue(total); this.view.getGastosOperacionalesTotal().setValue(total);
this.view.getGastosOperacionesPorcentajeCostoVenta().setValue(porcentajeCostoVenta); this.view.getGastosOperacionesPorcentajeCostoVenta().setValue(porcentajeCostoVenta);
@@ -294,31 +310,32 @@ public class EstadoResultadoController extends BaseController{
} }
private void updateResumen() { private void updateResumen() {
int bruto = this.view.getVentaBrutaField().getValue(); int bruto = this.view.getVentaBrutaField().getValue();
int totalGastosOperacionales = this.view.getGastosOperacionalesTotal().getValue(); int totalGastosOperacionales = this.view.getGastosOperacionalesTotal().getValue();
int totalGastosGenerales = this.view.getGastosGeneralesTotal().getValue(); int totalGastosGenerales = this.view.getGastosGeneralesTotal().getValue();
int totalServicios = this.view.getServiciosTotal().getValue(); int totalServicios = this.view.getServiciosTotal().getValue();
int netoExentas = this.view.getVentasNetaExentasField().getValue(); int netoExentas = this.view.getVentasNetaExentasField().getValue();
int iva = this.view.getVentaIVAField().getValue(); int iva = this.view.getVentaIVAField().getValue();
double ppm = this.view.getResumenPPM().getValue(); double ppm = this.view.getResumenPPM().getValue();
int ivaFavor = this.view.getResumenIVAFavor().getValue(); int ivaFavor = this.view.getResumenIVAFavor().getValue();
int utilidad = bruto - totalGastosGenerales - totalGastosOperacionales - totalServicios; int utilidad = bruto - totalGastosGenerales - totalGastosOperacionales - totalServicios;
int ppmMes = (int) Math.round(ppm * (double)netoExentas / 100d); int ppmMes = (int) Math.round(ppm * (double) netoExentas / 100d);
int IVAPPM = iva + ppmMes; int IVAPPM = iva + ppmMes;
int aPagar = IVAPPM - ivaFavor; int aPagar = IVAPPM - ivaFavor;
int resultado = utilidad - aPagar; int resultado = utilidad - aPagar;
this.view.getResumenUtilidad().setValue(utilidad); this.view.getResumenUtilidad().setValue(utilidad);
this.view.getResumenPPMMes().setValue(ppmMes); this.view.getResumenPPMMes().setValue(ppmMes);
this.view.getResumenIVAMes().setValue(iva); this.view.getResumenIVAMes().setValue(iva);
this.view.getResumenIVAPPM().setValue(IVAPPM); this.view.getResumenIVAPPM().setValue(IVAPPM);
this.view.getResumenAPagar().setValue(aPagar); this.view.getResumenAPagar().setValue(aPagar);
this.view.getResumenResultado().setValue(resultado); this.view.getResumenResultado().setValue(resultado);
this.estadoResultado.setPpm(ppm); this.estadoResultado.setPpm(ppm);
this.estadoResultado.setIvaFavor(ivaFavor); this.estadoResultado.setIvaFavor(ivaFavor);
} }
} }

View File

@@ -30,15 +30,12 @@ import danielcortes.xyz.informes.InformeLibroDeVentas;
import danielcortes.xyz.models.tipo_egreso.TipoEgreso; import danielcortes.xyz.models.tipo_egreso.TipoEgreso;
import danielcortes.xyz.utils.StringUtils; import danielcortes.xyz.utils.StringUtils;
import danielcortes.xyz.views.InformesSideBar; import danielcortes.xyz.views.InformesSideBar;
import danielcortes.xyz.views.dialogs.InformeGeneratedConfirmation;
import danielcortes.xyz.views.dialogs.MonthSelectDialog; import danielcortes.xyz.views.dialogs.MonthSelectDialog;
import danielcortes.xyz.views.dialogs.TipoEgresoSelectDialog; import danielcortes.xyz.views.dialogs.TipoEgresoSelectDialog;
import danielcortes.xyz.views.dialogs.XLSFileChooser;
import javax.swing.*; import java.nio.file.Path;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
@@ -60,7 +57,7 @@ public class InformesSideBarController {
} }
private void generarInformeLibroDeVentasListener() { private void generarInformeLibroDeVentasListener() {
LocalDate month = askForMonth(); LocalDate month = new MonthSelectDialog().execute();
if (month == null) { if (month == null) {
return; return;
} }
@@ -69,24 +66,25 @@ public class InformesSideBarController {
String formatedName = month.format(formatter); String formatedName = month.format(formatter);
String capitalized = StringUtils.capitalize(formatedName); String capitalized = StringUtils.capitalize(formatedName);
Path saveFile = askForFile(Configuration.get("base_save_directory") + "Libro " + capitalized); Path saveFile = new XLSFileChooser(Configuration.get("base_save_directory") + "Libro " + capitalized).execute();
if (saveFile == null) { if (saveFile == null) {
return; return;
} }
InformeLibroDeVentas informe = new InformeLibroDeVentas(month, saveFile); InformeLibroDeVentas informe = new InformeLibroDeVentas(month, saveFile);
Path generatedFile = informe.generarInforme(); informe.generarInforme();
this.showConfirmation(generatedFile); new InformeGeneratedConfirmation(saveFile).execute();
} }
private void generarInformeEgresosListener() { private void generarInformeEgresosListener() {
TipoEgreso tipoEgreso = askForTipoEgreso(); TipoEgreso tipoEgreso = new TipoEgresoSelectDialog().execute();
if (tipoEgreso == null) { if (tipoEgreso == null) {
return; return;
} }
LocalDate month = askForMonth(); LocalDate month = new MonthSelectDialog().execute();
if (month == null) { if (month == null) {
return; return;
} }
@@ -94,7 +92,7 @@ public class InformesSideBarController {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM YYYY"); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM YYYY");
String formatedMonth = month.format(formatter); String formatedMonth = month.format(formatter);
Path saveFile = askForFile("Informe Egresos - " + tipoEgreso.getNombre() + " - " + StringUtils.capitalize(formatedMonth)); Path saveFile = new XLSFileChooser("Informe Egresos - " + tipoEgreso.getNombre() + " - " + StringUtils.capitalize(formatedMonth)).execute();
if (saveFile == null) { if (saveFile == null) {
return; return;
} }
@@ -102,108 +100,6 @@ public class InformesSideBarController {
InformeEgresos informe = new InformeEgresos(tipoEgreso.getId(), month, saveFile); InformeEgresos informe = new InformeEgresos(tipoEgreso.getId(), month, saveFile);
Path generatedFile = informe.generarInforme(); Path generatedFile = informe.generarInforme();
this.showConfirmation(generatedFile); new InformeGeneratedConfirmation(saveFile).execute();
}
private LocalDate askForMonth() {
MonthSelectDialog monthSelectDialog = new MonthSelectDialog(null);
if (monthSelectDialog.isAcepted()) {
return monthSelectDialog.getMonth();
} else {
return null;
}
}
private TipoEgreso askForTipoEgreso() {
TipoEgresoSelectDialog tipoEgresoSelectDialog = new TipoEgresoSelectDialog(null);
if (tipoEgresoSelectDialog.isAcepted()) {
return tipoEgresoSelectDialog.getTipoEgreso();
} else {
return null;
}
}
private Path askForFile(String suggestedName) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
chooser.setSelectedFile(new File(suggestedName + ".xls"));
chooser.setFileFilter(new FileNameExtensionFilter("Excel 2007", "xls"));
if (chooser.showSaveDialog(this.view.getContentPanel()) == JFileChooser.APPROVE_OPTION) {
return processFilePath(chooser.getSelectedFile().getPath());
} else {
return null;
}
}
private void showConfirmation(Path path) {
int result = JOptionPane.showConfirmDialog(
null,
"El informes se a generado\n" +
"¿Desea abrirlo?",
"Confirmacion",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE
);
if (result == 0) {
try {
Desktop.getDesktop().open(path.toFile());
} catch (IOException e) {
e.printStackTrace();
}
}
}
private Path processFilePath(String pathString) {
Path path;
if (!pathString.endsWith(".xls")) {
pathString = pathString + ".xls";
}
try {
path = Paths.get(pathString);
} catch (InvalidPathException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(
this.view.getContentPanel(),
"El nombre de archivo entregado es invalido",
"Error!",
JOptionPane.ERROR_MESSAGE
);
return null;
}
try {
Files.createFile(path);
} catch (FileAlreadyExistsException e) {
int response = JOptionPane.showConfirmDialog(
this.view.getContentPanel(),
"El archivo ya existe\n¿Desea sobreescribirlo?",
"Confirmacion",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE
);
if (response != 0) {
return null;
}
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(
this.view.getContentPanel(),
"No a sido posible crear el archivo",
"Error!",
JOptionPane.ERROR_MESSAGE
);
return null;
}
return path;
} }
} }

View File

@@ -0,0 +1,412 @@
package danielcortes.xyz.informes;
import danielcortes.xyz.data.DAOManager;
import danielcortes.xyz.models.estado_resultado.EstadoResultado;
import danielcortes.xyz.models.tipo_egreso.TipoEgreso;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.PropertyTemplate;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.HashMap;
public class InformeEstadoResultado {
private ArrayList<Row> headers;
private ArrayList<Row> footers;
private ArrayList<Row> ventaRows;
private ArrayList<Row> gastosOperacionalesRows;
private ArrayList<Row> serviciosRows;
private ArrayList<Row> gastosGeneralesRows;
private ArrayList<Row> resumenGeneralRows;
private YearMonth mes;
private Path saveFile;
private EstadoResultado estadoResultado;
private Workbook wb;
private Sheet sheet;
private CreationHelper createHelper;
private HashMap<String, CellStyle> styles;
public InformeEstadoResultado(YearMonth mes, Path saveFile) {
this.mes = mes;
this.saveFile = saveFile;
this.estadoResultado = DAOManager.getEstadoResultadoDAO().findByMonth(this.mes);
this.wb = new HSSFWorkbook();
this.sheet = wb.createSheet();
this.createHelper = wb.getCreationHelper();
this.headers = new ArrayList<>();
this.footers = new ArrayList<>();
this.ventaRows = new ArrayList<>();
this.gastosOperacionalesRows = new ArrayList<>();
this.serviciosRows = new ArrayList<>();
this.gastosGeneralesRows = new ArrayList<>();
this.resumenGeneralRows = new ArrayList<>();
this.styles = this.generateStyles();
}
private void fillHeaders() {
Row venta = this.sheet.createRow(0);
Row gastosOperacionales = this.sheet.createRow(7);
Row servicios = this.sheet.createRow(18);
Row gastosGenerales = this.sheet.createRow(25);
Row resumenGeneral = this.sheet.createRow(34);
venta.createCell(0).setCellValue("Venta");
venta.createCell(1);
gastosOperacionales.createCell(0).setCellValue("Gastos Operacionales");
gastosOperacionales.createCell(1);
servicios.createCell(0).setCellValue("Servicios");
servicios.createCell(1);
gastosGenerales.createCell(0).setCellValue("Gastos Generales");
gastosGenerales.createCell(1);
resumenGeneral.createCell(0).setCellValue("Resumen General");
resumenGeneral.createCell(1);
resumenGeneral.createCell(2);
this.headers.add(venta);
this.headers.add(gastosOperacionales);
this.headers.add(servicios);
this.headers.add(gastosGenerales);
this.headers.add(resumenGeneral);
}
private void fillVentaData() {
Row bruto = sheet.createRow(1);
Row neto = sheet.createRow(2);
Row iva = sheet.createRow(3);
Row exentas = sheet.createRow(4);
this.ventaRows.add(bruto);
this.ventaRows.add(neto);
this.ventaRows.add(iva);
this.ventaRows.add(exentas);
bruto.createCell(0).setCellValue("Bruto");
bruto.createCell(1).setCellValue(DAOManager.getIngresoDAO().getTotalIngresoMes(this.mes));
neto.createCell(0).setCellValue("Neto");
neto.createCell(1).setCellFormula("B2/1.19");
iva.createCell(0).setCellValue("IVA");
iva.createCell(1).setCellFormula("B2-B3");
exentas.createCell(0).setCellValue("Exentas");
exentas.createCell(1).setCellValue(DAOManager.getIngresoDAO().getTotalExentasMes(this.mes));
}
private void fillGastosOperacionalesData() {
Row costoVenta = sheet.createRow(8);
Row remuneraciones = sheet.createRow(9);
Row finiquitos = sheet.createRow(10);
Row aguinaldo = sheet.createRow(11);
Row partime = sheet.createRow(12);
Row bonosPersonal = sheet.createRow(13);
Row honorariosContador = sheet.createRow(14);
Row arriendo = sheet.createRow(15);
this.gastosOperacionalesRows.add(costoVenta);
this.gastosOperacionalesRows.add(remuneraciones);
this.gastosOperacionalesRows.add(finiquitos);
this.gastosOperacionalesRows.add(aguinaldo);
this.gastosOperacionalesRows.add(partime);
this.gastosOperacionalesRows.add(bonosPersonal);
this.gastosOperacionalesRows.add(honorariosContador);
this.gastosOperacionalesRows.add(arriendo);
costoVenta.createCell(0).setCellValue("Costo de Venta");
costoVenta.createCell(1).setCellValue(this.estadoResultado.getCostoVenta());
remuneraciones.createCell(0).setCellValue("Remuneraciones");
remuneraciones.createCell(1).setCellValue(this.estadoResultado.getRemuneraciones());
finiquitos.createCell(0).setCellValue("Finiquitos");
finiquitos.createCell(1).setCellValue(this.estadoResultado.getFiniquitos());
aguinaldo.createCell(0).setCellValue("Aguinaldo");
aguinaldo.createCell(1).setCellValue(this.estadoResultado.getAguinaldo());
partime.createCell(0).setCellValue("Partime");
partime.createCell(1).setCellValue(DAOManager.getEgresoDAO().getTotalEgresoMesPorTipo(this.mes, DAOManager.getTipoEgresoDAO().findByNombre("Pago Partime").get(0)));
bonosPersonal.createCell(0).setCellValue("Bonos Personal");
bonosPersonal.createCell(1).setCellValue(this.estadoResultado.getBonosPersonal());
honorariosContador.createCell(0).setCellValue("Honorarios Contador");
honorariosContador.createCell(1).setCellValue(this.estadoResultado.getHonorariosContador());
arriendo.createCell(0).setCellValue("Arriendo");
arriendo.createCell(1).setCellValue(this.estadoResultado.getArriendo());
}
private void fillServiciosData() {
Row agua = sheet.createRow(19);
Row luz = sheet.createRow(20);
Row gas = sheet.createRow(21);
Row telefono = sheet.createRow(22);
this.serviciosRows.add(agua);
this.serviciosRows.add(luz);
this.serviciosRows.add(gas);
this.serviciosRows.add(telefono);
agua.createCell(0).setCellValue("Agua");
agua.createCell(1).setCellValue(this.estadoResultado.getAgua());
luz.createCell(0).setCellValue("Luz");
luz.createCell(1).setCellValue(this.estadoResultado.getLuz());
gas.createCell(0).setCellValue("Gas");
gas.createCell(1).setCellValue(this.estadoResultado.getGas());
telefono.createCell(0).setCellValue("Telefono");
telefono.createCell(1).setCellValue(this.estadoResultado.getTelefono());
}
private void fillGastosGeneralesData() {
TipoEgreso facturaGastosGenerales = DAOManager.getTipoEgresoDAO().findByNombre("Factura Gastos Generales").get(0);
TipoEgreso gastoGeneralConBoleta = DAOManager.getTipoEgresoDAO().findByNombre("Gasto General Con Boleta").get(0);
TipoEgreso gastoGeneralSinRespaldo = DAOManager.getTipoEgresoDAO().findByNombre("Gasto General Sin Respaldo").get(0);
Row cuentaCorrienteFactura = sheet.createRow(26);
Row cuentaCorrienteBoleta = sheet.createRow(27);
Row cuentaCorrienteSinRespaldo = sheet.createRow(28);
Row efectivoFactura = sheet.createRow(29);
Row efectivoBoleta = sheet.createRow(30);
Row efectivoSinRespaldo = sheet.createRow(31);
this.gastosGeneralesRows.add(cuentaCorrienteFactura);
this.gastosGeneralesRows.add(cuentaCorrienteBoleta);
this.gastosGeneralesRows.add(cuentaCorrienteSinRespaldo);
this.gastosGeneralesRows.add(efectivoFactura);
this.gastosGeneralesRows.add(efectivoBoleta);
this.gastosGeneralesRows.add(efectivoSinRespaldo);
cuentaCorrienteFactura.createCell(0).setCellValue("CTA CTE con Factura");
cuentaCorrienteFactura.createCell(1).setCellValue(this.estadoResultado.getCuentaCorrienteFactura());
cuentaCorrienteBoleta.createCell(0).setCellValue("CTA CTE con Boleta");
cuentaCorrienteBoleta.createCell(1).setCellValue(this.estadoResultado.getCuentaCorrienteBoleta());
cuentaCorrienteSinRespaldo.createCell(0).setCellValue("CTA CTE sin Respaldo");
cuentaCorrienteSinRespaldo.createCell(1).setCellValue(this.estadoResultado.getCuentaCorrienteSinRespaldo());
efectivoFactura.createCell(0).setCellValue("Efectivo con Factura");
efectivoFactura.createCell(1).setCellValue(DAOManager.getEgresoDAO().getTotalEgresoMesPorTipo(this.mes, facturaGastosGenerales));
efectivoBoleta.createCell(0).setCellValue("Efectivo con Boleta");
efectivoBoleta.createCell(1).setCellValue(DAOManager.getEgresoDAO().getTotalEgresoMesPorTipo(this.mes, gastoGeneralConBoleta));
efectivoSinRespaldo.createCell(0).setCellValue("Efectivo sin Respaldo");
efectivoSinRespaldo.createCell(1).setCellValue(DAOManager.getEgresoDAO().getTotalEgresoMesPorTipo(this.mes, gastoGeneralSinRespaldo));
}
private void fillResumenGeneralData() {
Row utilidad = sheet.createRow(35);
Row ppmMes = sheet.createRow(36);
Row ivaMes = sheet.createRow(37);
Row ivaMesPpm = sheet.createRow(38);
Row ivaFavor = sheet.createRow(39);
Row aPagar = sheet.createRow(40);
this.resumenGeneralRows.add(utilidad);
this.resumenGeneralRows.add(ppmMes);
this.resumenGeneralRows.add(ivaMes);
this.resumenGeneralRows.add(ivaMesPpm);
this.resumenGeneralRows.add(ivaFavor);
this.resumenGeneralRows.add(aPagar);
utilidad.createCell(0).setCellValue("Utilidad");
utilidad.createCell(1);
utilidad.createCell(2).setCellFormula("B2 - B17 - B24 - B33");
ppmMes.createCell(0).setCellValue("PPM Mes");
ppmMes.createCell(1).setCellValue(this.estadoResultado.getPpm() / 100);
ppmMes.createCell(2).setCellFormula("B6 * B37");
ivaMes.createCell(0).setCellValue("+ IVA Mes");
ivaMes.createCell(1);
ivaMes.createCell(2).setCellFormula("B4");
ivaMesPpm.createCell(0);
ivaMesPpm.createCell(1);
ivaMesPpm.createCell(2).setCellFormula("C37 + C38");
ivaFavor.createCell(0).setCellValue("- IVA a Favor");
ivaFavor.createCell(1);
ivaFavor.createCell(2).setCellValue(this.estadoResultado.getIvaFavor());
aPagar.createCell(0).setCellValue("A Pagar PPM + IVA");
aPagar.createCell(1);
aPagar.createCell(2).setCellFormula("C39 - C40");
}
private void fillFooters() {
Row venta = sheet.createRow(5);
Row gastosOperacionales = sheet.createRow(16);
Row servicios = sheet.createRow(23);
Row gastosGenerales = sheet.createRow(32);
Row resumenGeneral = sheet.createRow(41);
this.footers.add(venta);
this.footers.add(gastosOperacionales);
this.footers.add(servicios);
this.footers.add(gastosGenerales);
this.footers.add(resumenGeneral);
venta.createCell(0).setCellValue("Neto mas Exentas");
venta.createCell(1).setCellFormula("B5+B3");
gastosOperacionales.createCell(0).setCellValue("Total");
gastosOperacionales.createCell(1).setCellFormula("Sum(B9:B16)");
servicios.createCell(0).setCellValue("Total");
servicios.createCell(1).setCellFormula("Sum(B20:B23)");
gastosGenerales.createCell(0).setCellValue("Total");
gastosGenerales.createCell(1).setCellFormula("Sum(B27:B32)");
resumenGeneral.createCell(0).setCellValue("Resultado");
resumenGeneral.createCell(1);
resumenGeneral.createCell(2).setCellFormula("C36 - C41");
}
private void setStyles() {
for (Row header : this.headers) {
header.getCell(0).setCellStyle(this.styles.get("header"));
header.getCell(1).setCellStyle(this.styles.get("header"));
header.setHeightInPoints(20);
}
for (Row footer : this.footers) {
footer.getCell(0).setCellStyle(this.styles.get("footer"));
footer.getCell(1).setCellStyle(this.styles.get("footer_money"));
footer.setHeightInPoints(20);
}
//Adicionalmente, el footer y el header de resumen general tiene una columna mas de datos
headers.get(headers.size() - 1).getCell(2).setCellStyle(this.styles.get("header"));
footers.get(footers.size() - 1).getCell(1).setCellStyle(this.styles.get("footer"));
footers.get(footers.size() - 1).getCell(2).setCellStyle(this.styles.get("footer_money"));
for (Row row : this.ventaRows) {
row.getCell(0).setCellStyle(this.styles.get("regular"));
row.getCell(1).setCellStyle(this.styles.get("money"));
row.setHeightInPoints(15);
}
for (Row row : this.gastosOperacionalesRows) {
row.getCell(0).setCellStyle(this.styles.get("regular"));
row.getCell(1).setCellStyle(this.styles.get("money"));
row.setHeightInPoints(15);
}
for (Row row : this.serviciosRows) {
row.getCell(0).setCellStyle(this.styles.get("regular"));
row.getCell(1).setCellStyle(this.styles.get("money"));
row.setHeightInPoints(15);
}
for (Row row : this.gastosGeneralesRows) {
row.getCell(0).setCellStyle(this.styles.get("regular"));
row.getCell(1).setCellStyle(this.styles.get("money"));
row.setHeightInPoints(15);
}
for (Row row : this.resumenGeneralRows) {
row.getCell(0).setCellStyle(this.styles.get("regular"));
row.getCell(1).setCellStyle(this.styles.get("regular"));
row.getCell(2).setCellStyle(this.styles.get("money"));
row.setHeightInPoints(15);
}
//La fila de ppm mes en el resumen general tiene un campo distinto que contiene un porcentaje
resumenGeneralRows.get(1).getCell(1).setCellStyle(this.styles.get("percent"));
sheet.autoSizeColumn(0);
sheet.autoSizeColumn(1);
sheet.autoSizeColumn(2);
}
private void addBorders() {
PropertyTemplate pt = new PropertyTemplate();
pt.drawBorders(new CellRangeAddress(0, 0, 0, 1), BorderStyle.THIN, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(5, 5, 0, 1), BorderStyle.THIN, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(7, 7, 0, 1), BorderStyle.THIN, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(16, 16, 0, 1), BorderStyle.THIN, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(18, 18, 0, 1), BorderStyle.THIN, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(23, 23, 0, 1), BorderStyle.THIN, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(25, 25, 0, 1), BorderStyle.THIN, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(32, 32, 0, 1), BorderStyle.THIN, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(34, 34, 0, 2), BorderStyle.THIN, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(41, 41, 0, 2), BorderStyle.THIN, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(1, 4, 0, 1), BorderStyle.THIN, BorderExtent.VERTICAL);
pt.drawBorders(new CellRangeAddress(8, 15, 0, 1), BorderStyle.THIN, BorderExtent.VERTICAL);
pt.drawBorders(new CellRangeAddress(19, 23, 0, 1), BorderStyle.THIN, BorderExtent.VERTICAL);
pt.drawBorders(new CellRangeAddress(26, 31, 0, 1), BorderStyle.THIN, BorderExtent.VERTICAL);
pt.drawBorders(new CellRangeAddress(35, 40, 0, 2), BorderStyle.THIN, BorderExtent.VERTICAL);
pt.applyBorders(this.sheet);
}
public void generarInforme() {
fillHeaders();
fillVentaData();
fillGastosOperacionalesData();
fillServiciosData();
fillGastosGeneralesData();
fillResumenGeneralData();
fillFooters();
setStyles();
addBorders();
try (OutputStream fileOut = Files.newOutputStream(this.saveFile)) {
wb.write(fileOut);
} catch (IOException e) {
e.printStackTrace();
}
}
private HashMap<String, CellStyle> generateStyles() {
Font font = this.wb.createFont();
font.setBold(true);
font.setColor(IndexedColors.WHITE.getIndex());
CellStyle regularStyle = this.wb.createCellStyle();
CellStyle grayStyle = this.wb.createCellStyle();
grayStyle.setFont(font);
grayStyle.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
grayStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
CellStyle moneyStyle = this.wb.createCellStyle();
moneyStyle.setDataFormat(this.createHelper.createDataFormat().getFormat("\"$\"#,##0_);(\"$\"#,##0)"));
CellStyle percentStyle = this.wb.createCellStyle();
percentStyle.setDataFormat(this.createHelper.createDataFormat().getFormat("0.00%"));
CellStyle headerStyle = this.wb.createCellStyle();
headerStyle.cloneStyleFrom(grayStyle);
headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
CellStyle footerStyle = this.wb.createCellStyle();
footerStyle.cloneStyleFrom(grayStyle);
footerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
CellStyle footerMoneyStyle = this.wb.createCellStyle();
footerMoneyStyle.cloneStyleFrom(footerStyle);
footerMoneyStyle.setDataFormat(this.createHelper.createDataFormat().getFormat("\"$\"#,##0_);(\"$\"#,##0)"));
HashMap<String, CellStyle> styles = new HashMap<>();
styles.put("regular", regularStyle);
styles.put("money", moneyStyle);
styles.put("percent", percentStyle);
styles.put("header", headerStyle);
styles.put("footer", footerStyle);
styles.put("footer_money", footerMoneyStyle);
return styles;
}
}

View File

@@ -299,7 +299,7 @@ public class InformeLibroDeVentas {
} }
} }
public Path generarInforme() { public void generarInforme() {
sortInforme(); sortInforme();
fillData(); fillData();
fillHeaders(); fillHeaders();
@@ -311,11 +311,9 @@ public class InformeLibroDeVentas {
try (OutputStream fileOut = Files.newOutputStream(this.saveFile)) { try (OutputStream fileOut = Files.newOutputStream(this.saveFile)) {
wb.write(fileOut); wb.write(fileOut);
return this.saveFile;
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
return null;
} }
private HashMap<String, CellStyle> generateStyles() { private HashMap<String, CellStyle> generateStyles() {

View File

@@ -0,0 +1,33 @@
package danielcortes.xyz.views.dialogs;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.nio.file.Path;
public class InformeGeneratedConfirmation {
private Path path;
public InformeGeneratedConfirmation(Path path){
this.path = path;
}
public void execute(){
int result = JOptionPane.showConfirmDialog(
null,
"El informes se a generado" + "\n" + "¿Desea abrirlo?",
"Confirmacion",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE
);
if (result == 0) {
try {
Desktop.getDesktop().open(this.path.toFile());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

View File

@@ -28,12 +28,11 @@ import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer; import com.intellij.uiDesigner.core.Spacer;
import danielcortes.xyz.views.components.YearSpinnerModel; import danielcortes.xyz.views.components.YearSpinnerModel;
import danielcortes.xyz.views.listeners.WindowClosingListener;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.ArrayList; import java.util.ArrayList;
@@ -48,29 +47,35 @@ public class MonthSelectDialog extends JDialog {
private boolean acepted; private boolean acepted;
public MonthSelectDialog(JComponent parent) { public MonthSelectDialog() {
$$$setupUI$$$(); $$$setupUI$$$();
setContentPane(contentPane); setup();
setModalityType(ModalityType.APPLICATION_MODAL); }
getRootPane().setDefaultButton(buttonOK);
private void setup() {
this.setContentPane(contentPane);
this.setModalityType(ModalityType.APPLICATION_MODAL);
this.getRootPane().setDefaultButton(buttonOK);
buttonOK.addActionListener(e -> onOK()); this.buttonOK.addActionListener(e -> onOK());
buttonCancel.addActionListener(e -> onCancel()); this.buttonCancel.addActionListener(e -> onCancel());
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() { this.addWindowListener((WindowClosingListener) e -> onCancel());
public void windowClosing(WindowEvent e) { this.contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
onCancel();
}
});
contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
this.setLocationRelativeTo(null);
pack(); pack();
setLocationRelativeTo(parent); }
public LocalDate execute() {
setVisible(true); setVisible(true);
if (this.isAcepted()) {
return this.getMonth();
} else {
return null;
}
} }
private void onOK() { private void onOK() {
@@ -83,11 +88,11 @@ public class MonthSelectDialog extends JDialog {
dispose(); dispose();
} }
public boolean isAcepted() { private boolean isAcepted() {
return this.acepted; return this.acepted;
} }
public LocalDate getMonth() { private LocalDate getMonth() {
int year = Integer.valueOf((String) yearSpinner.getValue()); int year = Integer.valueOf((String) yearSpinner.getValue());
int month = this.months.indexOf(this.monthCombo.getSelectedItem()) + 1; int month = this.months.indexOf(this.monthCombo.getSelectedItem()) + 1;

View File

@@ -29,12 +29,11 @@ import com.intellij.uiDesigner.core.GridLayoutManager;
import danielcortes.xyz.data.DAOManager; import danielcortes.xyz.data.DAOManager;
import danielcortes.xyz.models.tipo_egreso.TipoEgreso; import danielcortes.xyz.models.tipo_egreso.TipoEgreso;
import danielcortes.xyz.models.tipo_egreso.TipoEgresoToStringWrapper; import danielcortes.xyz.models.tipo_egreso.TipoEgresoToStringWrapper;
import danielcortes.xyz.views.listeners.WindowClosingListener;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TipoEgresoSelectDialog extends JDialog { public class TipoEgresoSelectDialog extends JDialog {
private JPanel contentPane; private JPanel contentPane;
@@ -44,27 +43,35 @@ public class TipoEgresoSelectDialog extends JDialog {
private boolean acepted; private boolean acepted;
public TipoEgresoSelectDialog(JComponent parent) { public TipoEgresoSelectDialog() {
$$$setupUI$$$(); $$$setupUI$$$();
setContentPane(contentPane); this.setup();
setModalityType(ModalityType.APPLICATION_MODAL); }
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
getRootPane().setDefaultButton(buttonOK);
addWindowListener(new WindowAdapter() { private void setup() {
public void windowClosing(WindowEvent e) { this.setContentPane(contentPane);
buttonCancel.doClick(); this.setModalityType(ModalityType.APPLICATION_MODAL);
} this.getRootPane().setDefaultButton(buttonOK);
});
contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); this.buttonOK.addActionListener(e -> onOK());
this.buttonCancel.addActionListener(e -> onCancel());
buttonOK.addActionListener(e -> onOK()); this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
buttonCancel.addActionListener(e -> onCancel()); this.addWindowListener((WindowClosingListener) e -> onCancel());
this.contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
pack(); this.setLocationRelativeTo(null);
setLocationRelativeTo(parent); this.pack();
setVisible(true); }
public TipoEgreso execute() {
this.setVisible(true);
if (this.isAcepted()) {
return this.getTipoEgreso();
} else {
return null;
}
} }
private void onOK() { private void onOK() {
@@ -134,4 +141,5 @@ public class TipoEgresoSelectDialog extends JDialog {
public JComponent $$$getRootComponent$$$() { public JComponent $$$getRootComponent$$$() {
return contentPane; return contentPane;
} }
} }

View File

@@ -0,0 +1,79 @@
package danielcortes.xyz.views.dialogs;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
public class XLSFileChooser {
private JFileChooser chooser;
public XLSFileChooser(String suggestedName){
this.chooser = new JFileChooser();
this.chooser.setDialogType(JFileChooser.SAVE_DIALOG);
this.chooser.setSelectedFile(new File(suggestedName + ".xls"));
this.chooser.setFileFilter(new FileNameExtensionFilter("Excel 2007", "xls"));
}
public Path execute(){
boolean accepted = this.chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION;
if(accepted){
Path path = processFilePath(this.chooser.getSelectedFile().getPath());
return path;
}else{
return null;
}
}
private Path processFilePath(String pathString) {
Path path;
if (!pathString.endsWith(".xls")) {
pathString = pathString + ".xls";
}
try {
path = Paths.get(pathString);
} catch (InvalidPathException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(
null,
"El nombre de archivo entregado es invalido",
"Error!",
JOptionPane.ERROR_MESSAGE
);
return null;
}
try {
Files.createFile(path);
} catch (FileAlreadyExistsException e) {
int response = JOptionPane.showConfirmDialog(
null,
"El archivo ya existe" + "\n" + "¿Desea sobreescribirlo?",
"Confirmacion",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE
);
if (response != 0) {
return null;
}
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(
null,
"No a sido posible crear el archivo",
"Error!",
JOptionPane.ERROR_MESSAGE
);
return null;
}
return path;
}
}

View File

@@ -0,0 +1,18 @@
package danielcortes.xyz.views.listeners;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
/**
* Simple wraper for WindowListener to simple use the windowClosing method in a lambda function
*/
public interface WindowClosingListener extends WindowListener {
default void windowOpened(WindowEvent e){}
default void windowClosed(WindowEvent e){}
default void windowIconified(WindowEvent e){}
default void windowDeiconified(WindowEvent e){}
default void windowActivated(WindowEvent e){}
default void windowDeactivated(WindowEvent e){}
void windowClosing(WindowEvent e);
}