Se aplico el estilo de codigo de google :3

https://github.com/google/styleguide
This commit is contained in:
Daniel Cortes
2019-03-01 23:28:43 -03:00
parent 412e128398
commit 95685b7f82
81 changed files with 8826 additions and 7757 deletions

View File

@@ -28,68 +28,72 @@ 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.views.BaseLayout; import danielcortes.xyz.views.BaseLayout;
import javax.swing.*;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Locale; import java.util.Locale;
import java.util.logging.LogManager; import java.util.logging.LogManager;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main { public class Main {
private static final int DATABASE_VERSION = 2;
static { private static final int DATABASE_VERSION = 2;
setUpLogger();
setUpSystemProperties(); static {
updateDatabase(); setUpLogger();
setUpSystemProperties();
updateDatabase();
}
public static void main(String[] args) {
run();
}
private static void run() {
BaseLayout view = new BaseLayout();
BaseLayoutController controller = new BaseLayoutController(view);
executeView(view.getContentPanel());
}
private static void updateDatabase() {
DAOManager.getVersionDAO().updateTo(DATABASE_VERSION);
}
private static void executeView(JComponent view) {
JFrame frame = new JFrame(Configuration.get("nombre_caja"));
frame.setContentPane(view);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void setUpSystemProperties() {
System.setProperty("awt.useSystemAAFontSettings", "on");
System.setProperty("swing.aatext", "true");
try {
UIManager.setLookAndFeel(Configuration.get("look_and_feel"));
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
} }
public static void main(String[] args) { Locale.setDefault(new Locale("es"));
run(); }
private static void setUpLogger() {
LogManager manager = LogManager.getLogManager();
try {
FileInputStream in = new FileInputStream("config/logging.properties");
manager.readConfiguration(in);
in.close();
} catch (IOException e) {
System.exit(1);
} }
private static void run() {
BaseLayout view = new BaseLayout();
BaseLayoutController controller = new BaseLayoutController(view);
executeView(view.getContentPanel());
}
private static void updateDatabase(){ }
DAOManager.getVersionDAO().updateTo(DATABASE_VERSION);
}
private static void executeView(JComponent view) {
JFrame frame = new JFrame(Configuration.get("nombre_caja"));
frame.setContentPane(view);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void setUpSystemProperties() {
System.setProperty("awt.useSystemAAFontSettings", "on");
System.setProperty("swing.aatext", "true");
try {
UIManager.setLookAndFeel(Configuration.get("look_and_feel"));
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
Locale.setDefault(new Locale("es"));
}
private static void setUpLogger() {
LogManager manager = LogManager.getLogManager();
try {
FileInputStream in = new FileInputStream("config/logging.properties");
manager.readConfiguration(in);
in.close();
} catch (IOException e) {
System.exit(1);
}
}
} }

View File

@@ -31,228 +31,233 @@ import danielcortes.xyz.models.efectivo.Efectivo;
import danielcortes.xyz.views.ArqueoView; import danielcortes.xyz.views.ArqueoView;
import danielcortes.xyz.views.CalcularFondoView; import danielcortes.xyz.views.CalcularFondoView;
import danielcortes.xyz.views.components.NumberFormatedTextField; import danielcortes.xyz.views.components.NumberFormatedTextField;
import java.awt.Color;
import javax.swing.*; import javax.swing.KeyStroke;
import java.awt.*;
/** /**
* Controlador destinado a la vista ArqueoView * Controlador destinado a la vista ArqueoView Maneja su contenido y las acciones que esta realiza.
* Maneja su contenido y las acciones que esta realiza.
*/ */
public class ArqueoController extends BaseController{ public class ArqueoController extends BaseController {
private ArqueoView view;
private Caja caja;
private Efectivo efectivo;
private Documentos documentos;
/** private ArqueoView view;
* Crea el controlador y ejecuta el metodo que genera los eventos para su vista. private Caja caja;
*/ private Efectivo efectivo;
public ArqueoController(ArqueoView view) { private Documentos documentos;
this.view = view;
this.setUpViewEvents(); /**
* Crea el controlador y ejecuta el metodo que genera los eventos para su vista.
*/
public ArqueoController(ArqueoView view) {
this.view = view;
this.setUpViewEvents();
}
/**
* Actualiza los campos de documentos, efectivo y resumen con los datos de la caja.
*
* @param caja Caja para la cual se seleccionaran los datos a mostrar
*/
public void updateCaja(Caja caja) {
this.caja = caja;
this.fillDocumentos();
this.fillEfectivo();
this.fillResumen();
}
/**
* Acceso publico para rellenar el resumen
*/
public void updateResumen() {
this.fillResumen();
}
/**
* Rellena los campos del efectivo con la instancia de efectivo que pertenece a la caja
*/
private void fillEfectivo() {
this.efectivo = DAOManager.getEfectivoDAO().findByCaja(this.caja);
this.view.getVeinteMilField().setValue(efectivo.getVeinteMil());
this.view.getDiezMilField().setValue(efectivo.getDiezMil());
this.view.getCincoMilField().setValue(efectivo.getCincoMil());
this.view.getDosMilField().setValue(efectivo.getDosMil());
this.view.getMilField().setValue(efectivo.getMil());
this.view.getQuinientosField().setValue(efectivo.getQuinientos());
this.view.getCienField().setValue(efectivo.getCien());
this.view.getCincuentaField().setValue(efectivo.getCincuenta());
this.view.getDiezField().setValue(efectivo.getDiez());
}
/**
* Rellea los campos de documentos con la instancia de documentos que pertenece a la caja
*/
private void fillDocumentos() {
this.documentos = DAOManager.getDocumentosDAO().findByCaja(caja);
this.view.getTarjetasField().setValue(documentos.getTarjetas());
this.view.getChequesField().setValue(documentos.getCheques());
this.view.getRetiroField().setValue(documentos.getRetiros());
}
/**
* Llama a todos los metodos que llenan y calculan los campos de resumen
*/
private void fillResumen() {
this.updateResumenEfectivo();
this.updateResumenDocumentos();
this.updateResumenEgresos();
this.updateResumenArqueo();
}
/**
* Calcula el total de efectivo y lo muestra en el efectivoField
*/
private void updateResumenEfectivo() {
NumberFormatedTextField efectivoField = this.view.getEfectivoField();
int total = DAOManager.getEfectivoDAO().getTotalEfectivo(this.caja);
efectivoField.setValue(total);
}
/**
* Calcula el total de documentos y lo muestra en el documentosField
*/
private void updateResumenDocumentos() {
NumberFormatedTextField documentosField = this.view.getDocumentosField();
int total = DAOManager.getDocumentosDAO().getTotalDocumentos(this.caja);
documentosField.setValue(total);
}
/**
* Obtiene el total de egresos y lo muestra en el campo de egresosField
*/
private void updateResumenEgresos() {
int total = DAOManager.getEgresoDAO().getTotalEgreso(this.caja);
this.view.getEgresosField().setValue(total);
}
/**
* Calcula los datos de arqueo, rendido y ajuste y los muestra en sus campos correspondientes
*/
private void updateResumenArqueo() {
int totalEfectivo = DAOManager.getEfectivoDAO().getTotalEfectivo(this.caja);
int totalDocumentos = DAOManager.getDocumentosDAO().getTotalDocumentos(this.caja);
int totalEgresos = DAOManager.getEgresoDAO().getTotalEgreso(this.caja);
int totalIngresos = DAOManager.getIngresoDAO().getTotalIngreso(this.caja);
int rendido = totalDocumentos + totalEfectivo + totalEgresos;
int diferencia = rendido - totalIngresos;
this.view.getRendidoField().setValue(rendido);
this.view.getDebeRendirField().setValue(totalIngresos);
this.view.getDiferenciaField().setValue(diferencia);
if (diferencia < 0) {
this.view.getDiferenciaField().setForeground(new Color(255, 0, 0));
} else {
this.view.getDiferenciaField().setForeground(new Color(0, 0, 0));
} }
/** }
* Actualiza los campos de documentos, efectivo y resumen con los datos de la caja.
*
* @param caja Caja para la cual se seleccionaran los datos a mostrar
*/
public void updateCaja(Caja caja) {
this.caja = caja;
this.fillDocumentos();
this.fillEfectivo();
this.fillResumen();
}
/** /**
* Acceso publico para rellenar el resumen * Setea los eventos de los fields de la vista
*/ */
public void updateResumen() { private void setUpViewEvents() {
this.fillResumen(); moveTo(this.view.getVeinteMilField(), this.view.getDiezMilField());
} moveTo(this.view.getDiezMilField(), this.view.getCincoMilField());
moveTo(this.view.getCincoMilField(), this.view.getDosMilField());
moveTo(this.view.getDosMilField(), this.view.getMilField());
moveTo(this.view.getMilField(), this.view.getQuinientosField());
moveTo(this.view.getQuinientosField(), this.view.getCienField());
moveTo(this.view.getCienField(), this.view.getCincuentaField());
moveTo(this.view.getCincuentaField(), this.view.getDiezField());
doAction(this.view.getDiezField(), "save", KeyStroke.getKeyStroke("ENTER"),
e -> this.guardarEfectivoActionListener());
moveTo(this.view.getChequesField(), this.view.getTarjetasField());
moveTo(this.view.getTarjetasField(), this.view.getRetiroField());
doAction(this.view.getRetiroField(), "save", KeyStroke.getKeyStroke("ENTER"),
e -> this.guardarDocumentosActionListener());
/** this.view.getGuardarEfectivoButton()
* Rellena los campos del efectivo con la instancia de efectivo que pertenece a la caja .addActionListener(e -> this.guardarEfectivoActionListener());
*/ this.view.getGuardarDocumentosButton()
private void fillEfectivo() { .addActionListener(e -> this.guardarEfectivoActionListener());
this.efectivo = DAOManager.getEfectivoDAO().findByCaja(this.caja); this.view.getCalcularFondoButton().addActionListener(e -> this.calcularFondoActionListener());
this.view.getVeinteMilField().setValue(efectivo.getVeinteMil()); }
this.view.getDiezMilField().setValue(efectivo.getDiezMil());
this.view.getCincoMilField().setValue(efectivo.getCincoMil());
this.view.getDosMilField().setValue(efectivo.getDosMil());
this.view.getMilField().setValue(efectivo.getMil());
this.view.getQuinientosField().setValue(efectivo.getQuinientos());
this.view.getCienField().setValue(efectivo.getCien());
this.view.getCincuentaField().setValue(efectivo.getCincuenta());
this.view.getDiezField().setValue(efectivo.getDiez());
}
/** /**
* Rellea los campos de documentos con la instancia de documentos que pertenece a la caja * Llama a los metodos necesarios para guardar los campos de efectivo Primero llama a normalizar
*/ * el input, luego a esconder los mensajes de error, para finalmente llamar a guardar el efectivo
private void fillDocumentos() { */
this.documentos = DAOManager.getDocumentosDAO().findByCaja(caja); private void guardarEfectivoActionListener() {
this.view.getTarjetasField().setValue(documentos.getTarjetas()); this.view.getGuardarEfectivoButton().requestFocus();
this.view.getChequesField().setValue(documentos.getCheques()); this.guardarEfectivo();
this.view.getRetiroField().setValue(documentos.getRetiros()); }
}
/** /**
* Llama a todos los metodos que llenan y calculan los campos de resumen * Llama a los metodos necesarios para guardar los documentos Primero llama a normalizar el input,
*/ * luego a esconder los mensajes de error y finalmente a guardar los documentos
private void fillResumen() { */
this.updateResumenEfectivo(); private void guardarDocumentosActionListener() {
this.updateResumenDocumentos(); this.view.getGuardarDocumentosButton().requestFocus();
this.updateResumenEgresos(); this.guardarDocumentos();
this.updateResumenArqueo(); }
}
/** /**
* Calcula el total de efectivo y lo muestra en el efectivoField * Lanza la ventana en la que se puede calcular el fondo de la caja.
*/ */
private void updateResumenEfectivo() { private void calcularFondoActionListener() {
NumberFormatedTextField efectivoField = this.view.getEfectivoField(); CalcularFondoView view = new CalcularFondoView();
int total = DAOManager.getEfectivoDAO().getTotalEfectivo(this.caja); CalcularFondoController controller = new CalcularFondoController(view, this.caja);
efectivoField.setValue(total); launchFrame(view.getContentPanel(), "Calcular Fondo");
} }
/** /**
* Calcula el total de documentos y lo muestra en el documentosField * Guarda los datos del detalle de efectivo solo despues de que los campos sean validados, luego
*/ * de guardar llama a updateResumenEfectivo y updateResumenArqueo para actualizar los datos en
private void updateResumenDocumentos() { * efectivoField y arqueoField
NumberFormatedTextField documentosField = this.view.getDocumentosField(); */
int total = DAOManager.getDocumentosDAO().getTotalDocumentos(this.caja); private void guardarEfectivo() {
documentosField.setValue(total); int diez = this.view.getDiezField().getValue();
} int cincuenta = this.view.getCincuentaField().getValue();
int cien = this.view.getCienField().getValue();
int quinientos = this.view.getQuinientosField().getValue();
int mil = this.view.getMilField().getValue();
int dosMil = this.view.getDosMilField().getValue();
int cincoMil = this.view.getCincoMilField().getValue();
int diezMil = this.view.getDiezMilField().getValue();
int veinteMil = this.view.getVeinteMilField().getValue();
/** this.efectivo.setDiez(diez);
* Obtiene el total de egresos y lo muestra en el campo de egresosField this.efectivo.setCincuenta(cincuenta);
*/ this.efectivo.setCien(cien);
private void updateResumenEgresos() { this.efectivo.setQuinientos(quinientos);
int total = DAOManager.getEgresoDAO().getTotalEgreso(this.caja); this.efectivo.setMil(mil);
this.view.getEgresosField().setValue(total); this.efectivo.setDosMil(dosMil);
} this.efectivo.setCincoMil(cincoMil);
this.efectivo.setDiezMil(diezMil);
this.efectivo.setVeinteMil(veinteMil);
DAOManager.getEfectivoDAO().updateEfectivo(efectivo);
/** this.updateResumenEfectivo();
* Calcula los datos de arqueo, rendido y ajuste y los muestra en sus campos correspondientes this.updateResumenArqueo();
*/ }
private void updateResumenArqueo() {
int totalEfectivo = DAOManager.getEfectivoDAO().getTotalEfectivo(this.caja);
int totalDocumentos = DAOManager.getDocumentosDAO().getTotalDocumentos(this.caja);
int totalEgresos = DAOManager.getEgresoDAO().getTotalEgreso(this.caja);
int totalIngresos = DAOManager.getIngresoDAO().getTotalIngreso(this.caja);
int rendido = totalDocumentos + totalEfectivo + totalEgresos; /**
int diferencia = rendido - totalIngresos; * Guarda los datos del detalle de documentos solo despues de que los campos sean validados, luego
* de guardar llama a updateResumenDocumentos y updateResumenArqueo para actualizar los datos de
* documentosField y arqueoField
*/
private void guardarDocumentos() {
int tarjetas = this.view.getTarjetasField().getValue();
int cheques = this.view.getChequesField().getValue();
int retiros = this.view.getRetiroField().getValue();
this.view.getRendidoField().setValue(rendido); this.documentos.setTarjetas(tarjetas);
this.view.getDebeRendirField().setValue(totalIngresos); this.documentos.setCheques(cheques);
this.view.getDiferenciaField().setValue(diferencia); this.documentos.setRetiros(retiros);
DAOManager.getDocumentosDAO().updateDocumentos(documentos);
if (diferencia < 0) { this.updateResumenDocumentos();
this.view.getDiferenciaField().setForeground(new Color(255, 0, 0)); this.updateResumenArqueo();
} else { }
this.view.getDiferenciaField().setForeground(new Color(0, 0, 0));
}
}
/**
* Setea los eventos de los fields de la vista
*/
private void setUpViewEvents() {
moveTo(this.view.getVeinteMilField(), this.view.getDiezMilField());
moveTo(this.view.getDiezMilField(), this.view.getCincoMilField());
moveTo(this.view.getCincoMilField(), this.view.getDosMilField());
moveTo(this.view.getDosMilField(), this.view.getMilField());
moveTo(this.view.getMilField(), this.view.getQuinientosField());
moveTo(this.view.getQuinientosField(), this.view.getCienField());
moveTo(this.view.getCienField(), this.view.getCincuentaField());
moveTo(this.view.getCincuentaField(), this.view.getDiezField());
doAction(this.view.getDiezField(), "save", KeyStroke.getKeyStroke("ENTER"), e -> this.guardarEfectivoActionListener());
moveTo(this.view.getChequesField(), this.view.getTarjetasField());
moveTo(this.view.getTarjetasField(), this.view.getRetiroField());
doAction(this.view.getRetiroField(), "save", KeyStroke.getKeyStroke("ENTER"), e -> this.guardarDocumentosActionListener());
this.view.getGuardarEfectivoButton().addActionListener(e -> this.guardarEfectivoActionListener());
this.view.getGuardarDocumentosButton().addActionListener(e -> this.guardarEfectivoActionListener());
this.view.getCalcularFondoButton().addActionListener(e -> this.calcularFondoActionListener());
}
/**
* Llama a los metodos necesarios para guardar los campos de efectivo
* Primero llama a normalizar el input, luego a esconder los mensajes de error, para finalmente llamar a guardar el efectivo
*/
private void guardarEfectivoActionListener() {
this.view.getGuardarEfectivoButton().requestFocus();
this.guardarEfectivo();
}
/**
* Llama a los metodos necesarios para guardar los documentos
* Primero llama a normalizar el input, luego a esconder los mensajes de error y finalmente a guardar los documentos
*/
private void guardarDocumentosActionListener() {
this.view.getGuardarDocumentosButton().requestFocus();
this.guardarDocumentos();
}
/**
* Lanza la ventana en la que se puede calcular el fondo de la caja.
*/
private void calcularFondoActionListener() {
CalcularFondoView view = new CalcularFondoView();
CalcularFondoController controller = new CalcularFondoController(view, this.caja);
launchFrame(view.getContentPanel(), "Calcular Fondo");
}
/**
* Guarda los datos del detalle de efectivo solo despues de que los campos sean validados, luego de guardar
* llama a updateResumenEfectivo y updateResumenArqueo para actualizar los datos en efectivoField y arqueoField
*/
private void guardarEfectivo() {
int diez = this.view.getDiezField().getValue();
int cincuenta = this.view.getCincuentaField().getValue();
int cien = this.view.getCienField().getValue();
int quinientos = this.view.getQuinientosField().getValue();
int mil = this.view.getMilField().getValue();
int dosMil = this.view.getDosMilField().getValue();
int cincoMil = this.view.getCincoMilField().getValue();
int diezMil = this.view.getDiezMilField().getValue();
int veinteMil = this.view.getVeinteMilField().getValue();
this.efectivo.setDiez(diez);
this.efectivo.setCincuenta(cincuenta);
this.efectivo.setCien(cien);
this.efectivo.setQuinientos(quinientos);
this.efectivo.setMil(mil);
this.efectivo.setDosMil(dosMil);
this.efectivo.setCincoMil(cincoMil);
this.efectivo.setDiezMil(diezMil);
this.efectivo.setVeinteMil(veinteMil);
DAOManager.getEfectivoDAO().updateEfectivo(efectivo);
this.updateResumenEfectivo();
this.updateResumenArqueo();
}
/**
* Guarda los datos del detalle de documentos solo despues de que los campos sean validados, luego de guardar
* llama a updateResumenDocumentos y updateResumenArqueo para actualizar los datos de documentosField y arqueoField
*/
private void guardarDocumentos() {
int tarjetas = this.view.getTarjetasField().getValue();
int cheques = this.view.getChequesField().getValue();
int retiros = this.view.getRetiroField().getValue();
this.documentos.setTarjetas(tarjetas);
this.documentos.setCheques(cheques);
this.documentos.setRetiros(retiros);
DAOManager.getDocumentosDAO().updateDocumentos(documentos);
this.updateResumenDocumentos();
this.updateResumenArqueo();
}
} }

View File

@@ -2,41 +2,44 @@ package danielcortes.xyz.controllers;
import danielcortes.xyz.controllers.actions.BasicAction; import danielcortes.xyz.controllers.actions.BasicAction;
import danielcortes.xyz.data.Configuration; import danielcortes.xyz.data.Configuration;
import java.awt.Dimension;
import javax.swing.*; import javax.swing.JComponent;
import java.awt.*; import javax.swing.JFrame;
import javax.swing.KeyStroke;
class BaseController { class BaseController {
static void moveTo(JComponent origin, JComponent destiny) {
KeyStroke next = KeyStroke.getKeyStroke("ENTER");
KeyStroke back = KeyStroke.getKeyStroke("ESCAPE");
origin.getInputMap(JComponent.WHEN_FOCUSED).put(next, "nextField");
destiny.getInputMap(JComponent.WHEN_FOCUSED).put(back, "previousField");
origin.getActionMap().put("nextField", (BasicAction) e -> destiny.requestFocus());
destiny.getActionMap().put("previousField", (BasicAction) e -> origin.requestFocus());
}
static void doAction(JComponent target, String name, KeyStroke keyStroke, BasicAction action){
target.getInputMap(JComponent.WHEN_FOCUSED).put(keyStroke, name);
target.getActionMap().put(name, action);
}
static void launchFrame(JComponent view, String title) { static void moveTo(JComponent origin, JComponent destiny) {
JFrame frame = new JFrame(title + ": " + Configuration.get("nombre_caja")); KeyStroke next = KeyStroke.getKeyStroke("ENTER");
frame.setContentPane(view); KeyStroke back = KeyStroke.getKeyStroke("ESCAPE");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); origin.getInputMap(JComponent.WHEN_FOCUSED).put(next, "nextField");
destiny.getInputMap(JComponent.WHEN_FOCUSED).put(back, "previousField");
origin.getActionMap().put("nextField", (BasicAction) e -> destiny.requestFocus());
destiny.getActionMap().put("previousField", (BasicAction) e -> origin.requestFocus());
}
frame.pack(); static void doAction(JComponent target, String name, KeyStroke keyStroke, BasicAction action) {
frame.setLocationRelativeTo(null); target.getInputMap(JComponent.WHEN_FOCUSED).put(keyStroke, name);
frame.setVisible(true); target.getActionMap().put(name, action);
} }
static void launchFrame(JComponent view, String title, Dimension d){ static void launchFrame(JComponent view, String title) {
JFrame frame = new JFrame(title + ": " + Configuration.get("nombre_caja")); JFrame frame = new JFrame(title + ": " + Configuration.get("nombre_caja"));
frame.setContentPane(view); frame.setContentPane(view);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(d); frame.pack();
frame.setLocationRelativeTo(null); frame.setLocationRelativeTo(null);
frame.setVisible(true); frame.setVisible(true);
} }
static void launchFrame(JComponent view, String title, Dimension d) {
JFrame frame = new JFrame(title + ": " + Configuration.get("nombre_caja"));
frame.setContentPane(view);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(d);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
} }

View File

@@ -1,84 +1,89 @@
package danielcortes.xyz.controllers; package danielcortes.xyz.controllers;
import danielcortes.xyz.views.*; import danielcortes.xyz.views.BaseLayout;
import danielcortes.xyz.views.CajasView;
import java.awt.*; import danielcortes.xyz.views.EstadoResultadoView;
import danielcortes.xyz.views.InformesSideBar;
import danielcortes.xyz.views.MainSideBar;
import java.awt.CardLayout;
public class BaseLayoutController extends BaseController { public class BaseLayoutController extends BaseController {
private final String MAIN_SIDEBAR = "MAIN";
private final String INFORMES_SIDEBAR = "INFORMES";
private final String CAJAS_MAIN = "CAJAS";
private final String ESTADO_RESULTADO_MAIN = "ESTADO_RESULTADO";
private BaseLayout baseLayoutView; private final String MAIN_SIDEBAR = "MAIN";
private final String INFORMES_SIDEBAR = "INFORMES";
private final String CAJAS_MAIN = "CAJAS";
private final String ESTADO_RESULTADO_MAIN = "ESTADO_RESULTADO";
private MainSideBarController mainSideBarController; private BaseLayout baseLayoutView;
private InformesSideBarController informesSideBarController;
private CajasController cajasController; private MainSideBarController mainSideBarController;
private EstadoResultadoController estadoResultadoController; private InformesSideBarController informesSideBarController;
public BaseLayoutController(BaseLayout baseLayoutView) { private CajasController cajasController;
this.baseLayoutView = baseLayoutView; private EstadoResultadoController estadoResultadoController;
this.loadSideBarContents();
this.loadMainPanelContents();
this.setupViewEvents();
}
private void setupViewEvents() { public BaseLayoutController(BaseLayout baseLayoutView) {
CardLayout sideLayout = (CardLayout) this.baseLayoutView.getSidePanel().getLayout(); this.baseLayoutView = baseLayoutView;
CardLayout mainLayout = (CardLayout) this.baseLayoutView.getMainPanel().getLayout(); this.loadSideBarContents();
this.loadMainPanelContents();
this.setupViewEvents();
}
this.mainSideBarController.getView().getInformesMensualesButton().addActionListener( private void setupViewEvents() {
e -> sideLayout.show(this.baseLayoutView.getSidePanel(), INFORMES_SIDEBAR) CardLayout sideLayout = (CardLayout) this.baseLayoutView.getSidePanel().getLayout();
); CardLayout mainLayout = (CardLayout) this.baseLayoutView.getMainPanel().getLayout();
this.mainSideBarController.getView().getCajasButton().addActionListener(
e -> mainLayout.show(this.baseLayoutView.getMainPanel(), CAJAS_MAIN)
);
this.informesSideBarController.getView().getVolverButton().addActionListener( this.mainSideBarController.getView().getInformesMensualesButton().addActionListener(
e -> sideLayout.show(this.baseLayoutView.getSidePanel(), MAIN_SIDEBAR) e -> sideLayout.show(this.baseLayoutView.getSidePanel(), INFORMES_SIDEBAR)
); );
this.mainSideBarController.getView().getCajasButton().addActionListener(
e -> mainLayout.show(this.baseLayoutView.getMainPanel(), CAJAS_MAIN)
);
this.informesSideBarController.getView().getEstadoResultadoButton().addActionListener(e -> { this.informesSideBarController.getView().getVolverButton().addActionListener(
this.estadoResultadoController.update(); e -> sideLayout.show(this.baseLayoutView.getSidePanel(), MAIN_SIDEBAR)
mainLayout.show(this.baseLayoutView.getMainPanel(), ESTADO_RESULTADO_MAIN); );
});
} this.informesSideBarController.getView().getEstadoResultadoButton().addActionListener(e -> {
this.estadoResultadoController.update();
mainLayout.show(this.baseLayoutView.getMainPanel(), ESTADO_RESULTADO_MAIN);
});
private void loadSideBarContents() { }
this.loadMainSideBar();
this.loadInformesSideBar();
}
private void loadMainSideBar() { private void loadSideBarContents() {
MainSideBar mainSideBar = new MainSideBar(); this.loadMainSideBar();
this.mainSideBarController = new MainSideBarController(mainSideBar); this.loadInformesSideBar();
this.baseLayoutView.getSidePanel().add(mainSideBar.getContentPanel(), MAIN_SIDEBAR); }
}
private void loadInformesSideBar() { private void loadMainSideBar() {
InformesSideBar informesSideBar = new InformesSideBar(); MainSideBar mainSideBar = new MainSideBar();
this.informesSideBarController = new InformesSideBarController(informesSideBar); this.mainSideBarController = new MainSideBarController(mainSideBar);
this.baseLayoutView.getSidePanel().add(informesSideBar.getContentPanel(), INFORMES_SIDEBAR); this.baseLayoutView.getSidePanel().add(mainSideBar.getContentPanel(), MAIN_SIDEBAR);
} }
private void loadMainPanelContents() { private void loadInformesSideBar() {
this.loadCajasMainContent(); InformesSideBar informesSideBar = new InformesSideBar();
this.loadEstadoResultadoMainContent(); this.informesSideBarController = new InformesSideBarController(informesSideBar);
} this.baseLayoutView.getSidePanel().add(informesSideBar.getContentPanel(), INFORMES_SIDEBAR);
}
private void loadCajasMainContent() { private void loadMainPanelContents() {
CajasView cajasView = new CajasView(); this.loadCajasMainContent();
this.cajasController= new CajasController(cajasView); this.loadEstadoResultadoMainContent();
this.baseLayoutView.getMainPanel().add(cajasView.getContentPanel(), CAJAS_MAIN); }
}
private void loadEstadoResultadoMainContent() { private void loadCajasMainContent() {
EstadoResultadoView estadoResultadoView = new EstadoResultadoView(); CajasView cajasView = new CajasView();
this.estadoResultadoController = new EstadoResultadoController(estadoResultadoView); this.cajasController = new CajasController(cajasView);
this.baseLayoutView.getMainPanel().add(estadoResultadoView.getContentPanel(), ESTADO_RESULTADO_MAIN); this.baseLayoutView.getMainPanel().add(cajasView.getContentPanel(), CAJAS_MAIN);
} }
private void loadEstadoResultadoMainContent() {
EstadoResultadoView estadoResultadoView = new EstadoResultadoView();
this.estadoResultadoController = new EstadoResultadoController(estadoResultadoView);
this.baseLayoutView.getMainPanel()
.add(estadoResultadoView.getContentPanel(), ESTADO_RESULTADO_MAIN);
}
} }

View File

@@ -28,147 +28,147 @@ import danielcortes.xyz.data.DAOManager;
import danielcortes.xyz.models.caja.Caja; import danielcortes.xyz.models.caja.Caja;
import danielcortes.xyz.models.documentos.Documentos; import danielcortes.xyz.models.documentos.Documentos;
import danielcortes.xyz.models.efectivo.Efectivo; import danielcortes.xyz.models.efectivo.Efectivo;
import danielcortes.xyz.views.*; import danielcortes.xyz.views.ArqueoView;
import danielcortes.xyz.views.CajasView;
import java.awt.*; import danielcortes.xyz.views.EgresosView;
import danielcortes.xyz.views.IngresosView;
import java.awt.CardLayout;
import java.time.LocalDate; import java.time.LocalDate;
/** /**
* Controlador destinado a controlar la vista de CajasView * Controlador destinado a controlar la vista de CajasView Ademas es la que crea las vistas internas
* Ademas es la que crea las vistas internas en un CardLayaut junto a sus controladores * en un CardLayaut junto a sus controladores
*/ */
public class CajasController { public class CajasController {
private CajasView view;
private IngresosController ingresosController; private CajasView view;
private EgresosController egresosController;
private ArqueoController arqueoController;
/** private IngresosController ingresosController;
* Crea el controlador private EgresosController egresosController;
* Necesita todos las interfaces DAO para poder asignarselos a sus vistas, private ArqueoController arqueoController;
* esto con el objetivo que sean facilmente intercambiables.
* <p>
* Llama a los metodos que:
* - Cargan el contenido del CardLayout
* - Selecciona una fecha inicial
* - Genera los eventos de la vista
* - Presiona el boton de la vista inicial
*/
public CajasController(CajasView view) {
this.view = view;
this.loadCardContents();
this.setUpDate();
this.setUpViewEvents();
this.pressInitialButton();
}
public CajasView getView() { /**
return view; * Crea el controlador Necesita todos las interfaces DAO para poder asignarselos a sus vistas,
} * esto con el objetivo que sean facilmente intercambiables.
* <p>
* Llama a los metodos que: - Cargan el contenido del CardLayout - Selecciona una fecha inicial -
* Genera los eventos de la vista - Presiona el boton de la vista inicial
*/
public CajasController(CajasView view) {
this.view = view;
this.loadCardContents();
this.setUpDate();
this.setUpViewEvents();
this.pressInitialButton();
}
/** public CajasView getView() {
* Coloca la fecha actual en el datepicker y luego llama a actualizar las cajas de las vistas return view;
*/ }
private void setUpDate() {
this.view.getDatePicker().setDateToToday();
this.updateCaja();
}
/** /**
* Setea los eventos de los botones y el datepicker * Coloca la fecha actual en el datepicker y luego llama a actualizar las cajas de las vistas
* - Cada vez que se cambia la fecha en el datepicker se llama a actualizar la caja */
* - Cuando se presiona uno de los botones muestra la vista correspondiente en el cardlayout private void setUpDate() {
*/ this.view.getDatePicker().setDateToToday();
private void setUpViewEvents() { this.updateCaja();
this.view.getEgresosButton().addActionListener(e -> { }
CardLayout layout = (CardLayout) this.view.getCardPanel().getLayout();
layout.show(this.view.getCardPanel(), "EGRESOS");
});
this.view.getIngresosButton().addActionListener(e -> {
CardLayout layout = (CardLayout) this.view.getCardPanel().getLayout();
layout.show(this.view.getCardPanel(), "INGRESOS");
});
this.view.getArqueoButton().addActionListener(e -> {
this.arqueoController.updateResumen();
CardLayout layout = (CardLayout) this.view.getCardPanel().getLayout(); /**
layout.show(this.view.getCardPanel(), "ARQUEO"); * Setea los eventos de los botones y el datepicker - Cada vez que se cambia la fecha en el
}); * datepicker se llama a actualizar la caja - Cuando se presiona uno de los botones muestra la
this.view.getDatePicker().addDateChangeListener(e -> updateCaja()); * vista correspondiente en el cardlayout
} */
private void setUpViewEvents() {
this.view.getEgresosButton().addActionListener(e -> {
CardLayout layout = (CardLayout) this.view.getCardPanel().getLayout();
layout.show(this.view.getCardPanel(), "EGRESOS");
});
this.view.getIngresosButton().addActionListener(e -> {
CardLayout layout = (CardLayout) this.view.getCardPanel().getLayout();
layout.show(this.view.getCardPanel(), "INGRESOS");
});
this.view.getArqueoButton().addActionListener(e -> {
this.arqueoController.updateResumen();
/** CardLayout layout = (CardLayout) this.view.getCardPanel().getLayout();
* Llama a update caja con la fecha seleccionada en el datepicker en los controladores del manager. layout.show(this.view.getCardPanel(), "ARQUEO");
*/ });
private void updateCaja() { this.view.getDatePicker().addDateChangeListener(e -> updateCaja());
LocalDate selectedDate = this.view.getDatePicker().getDate(); }
Caja caja = DAOManager.getCajaDAO().getByFecha(selectedDate).orElseGet(() -> {
Caja c = new Caja();
c.setFecha(selectedDate);
DAOManager.getCajaDAO().insert(c);
Efectivo efectivo = new Efectivo(); /**
efectivo.setCaja(c); * Llama a update caja con la fecha seleccionada en el datepicker en los controladores del
DAOManager.getEfectivoDAO().insertDefaultEfectivo(efectivo); * manager.
*/
private void updateCaja() {
LocalDate selectedDate = this.view.getDatePicker().getDate();
Caja caja = DAOManager.getCajaDAO().getByFecha(selectedDate).orElseGet(() -> {
Caja c = new Caja();
c.setFecha(selectedDate);
DAOManager.getCajaDAO().insert(c);
Documentos documentos = new Documentos(); Efectivo efectivo = new Efectivo();
documentos.setCaja(c); efectivo.setCaja(c);
DAOManager.getDocumentosDAO().insertDefaultDocumentos(documentos); DAOManager.getEfectivoDAO().insertDefaultEfectivo(efectivo);
return c;
});
this.ingresosController.updateCaja(caja); Documentos documentos = new Documentos();
this.egresosController.updateCaja(caja); documentos.setCaja(c);
this.arqueoController.updateCaja(caja); DAOManager.getDocumentosDAO().insertDefaultDocumentos(documentos);
} return c;
});
/** this.ingresosController.updateCaja(caja);
* Llama a los metodos que cargan las vistas que estaran dentro del cardlayout this.egresosController.updateCaja(caja);
*/ this.arqueoController.updateCaja(caja);
private void loadCardContents() { }
this.loadEgresosView();
this.loadIngresosView();
this.loadArqueoView();
}
/** /**
* Crea la vista de ingresos, la agrega a el cardlayout y se le es asignado a su controlador * Llama a los metodos que cargan las vistas que estaran dentro del cardlayout
*/ */
private void loadIngresosView() { private void loadCardContents() {
IngresosView ingresosView = new IngresosView(); this.loadEgresosView();
this.loadIngresosView();
this.loadArqueoView();
}
this.view.getCardPanel().add(ingresosView.getContentPanel(), "INGRESOS"); /**
* Crea la vista de ingresos, la agrega a el cardlayout y se le es asignado a su controlador
*/
private void loadIngresosView() {
IngresosView ingresosView = new IngresosView();
this.ingresosController = new IngresosController(ingresosView); this.view.getCardPanel().add(ingresosView.getContentPanel(), "INGRESOS");
}
/** this.ingresosController = new IngresosController(ingresosView);
* Crea la vista de egresos, la agrega a el cardlayout y se le es asignado a su controlador }
*/
private void loadEgresosView() {
EgresosView egresosView = new EgresosView();
this.view.getCardPanel().add(egresosView.getContentPanel(), "EGRESOS"); /**
* Crea la vista de egresos, la agrega a el cardlayout y se le es asignado a su controlador
*/
private void loadEgresosView() {
EgresosView egresosView = new EgresosView();
this.egresosController = new EgresosController(egresosView); this.view.getCardPanel().add(egresosView.getContentPanel(), "EGRESOS");
}
/** this.egresosController = new EgresosController(egresosView);
* Crea la vista de arqueo, la agrega a el cardlayout y se le es asignado a su controlador }
*/
private void loadArqueoView() {
ArqueoView arqueoView = new ArqueoView();
this.view.getCardPanel().add(arqueoView.getContentPanel(), "ARQUEO"); /**
* Crea la vista de arqueo, la agrega a el cardlayout y se le es asignado a su controlador
*/
private void loadArqueoView() {
ArqueoView arqueoView = new ArqueoView();
this.arqueoController = new ArqueoController(arqueoView); this.view.getCardPanel().add(arqueoView.getContentPanel(), "ARQUEO");
}
/** this.arqueoController = new ArqueoController(arqueoView);
* Activa el primer boton del manager }
*/
private void pressInitialButton() { /**
this.view.getIngresosButton().doClick(); * Activa el primer boton del manager
} */
private void pressInitialButton() {
this.view.getIngresosButton().doClick();
}
} }

View File

@@ -5,160 +5,162 @@ import danielcortes.xyz.models.caja.Caja;
import danielcortes.xyz.models.calculo_fondo.CalculoFondo; import danielcortes.xyz.models.calculo_fondo.CalculoFondo;
import danielcortes.xyz.views.CalcularFondoView; import danielcortes.xyz.views.CalcularFondoView;
import danielcortes.xyz.views.components.table_model.FondoTableModel; import danielcortes.xyz.views.components.table_model.FondoTableModel;
import javax.swing.*;
import java.awt.event.MouseAdapter; import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent; import java.awt.event.MouseEvent;
import javax.swing.JTable;
import javax.swing.KeyStroke;
public class CalcularFondoController extends BaseController{ public class CalcularFondoController extends BaseController {
private CalcularFondoView view;
private Caja caja;
private int editingId; private CalcularFondoView view;
private boolean editing; private Caja caja;
private CalculoFondo editingCalculoFondo;
public CalcularFondoController(CalcularFondoView view, Caja caja) { private int editingId;
this.view = view; private boolean editing;
this.caja = caja; private CalculoFondo editingCalculoFondo;
this.fillTable(); public CalcularFondoController(CalcularFondoView view, Caja caja) {
this.fillResumen(); this.view = view;
this.updateResumen(); this.caja = caja;
this.setupViewEvents();
this.updateButtonsEnabled(); this.fillTable();
this.fillResumen();
this.updateResumen();
this.setupViewEvents();
this.updateButtonsEnabled();
}
private void fillTable() {
FondoTableModel tableModel = this.view.getTableModel();
tableModel.removeRows();
for (CalculoFondo calculoFondo : DAOManager.getCalculoFondoDAO().findByCaja(this.caja)) {
tableModel.addRow(calculoFondo);
} }
}
private void fillTable() { private void fillResumen() {
FondoTableModel tableModel = this.view.getTableModel(); this.view.getFondoField().setValue(this.caja.getFondo());
tableModel.removeRows(); }
for (CalculoFondo calculoFondo : DAOManager.getCalculoFondoDAO().findByCaja(this.caja)) {
tableModel.addRow(calculoFondo); private void updateResumen() {
this.caja.setFondo(this.view.getFondoField().getValue());
int suma = DAOManager.getCalculoFondoDAO().getTotalCalculoFondo(this.caja);
this.view.getSumaField().setValue(suma);
this.view.getDepositoField().setValue(suma - this.caja.getFondo());
DAOManager.getCajaDAO().update(this.caja);
}
private void setupViewEvents() {
moveTo(this.view.getValorField(), this.view.getDescripcionField());
doAction(this.view.getDescripcionField(), "save", KeyStroke.getKeyStroke("ENTER"),
e -> this.guardarActionListener());
doAction(this.view.getFondoField(), "updateResumen", KeyStroke.getKeyStroke("ENTER"),
e -> this.updateResumen());
this.view.getTable().getSelectionModel().addListSelectionListener(e -> updateButtonsEnabled());
this.view.getGuardarButton().addActionListener(e -> guardarActionListener());
this.view.getEditarButton().addActionListener(e -> editarActionListener());
this.view.getEliminarButton().addActionListener(e -> eliminarActionListener());
this.view.getTable().addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent mouseEvent) {
JTable table = (JTable) mouseEvent.getSource();
if (mouseEvent.getClickCount() == 2 && table.getSelectedRow() != -1) {
CalcularFondoController.this.editarActionListener();
} }
}
});
}
private void guardarActionListener() {
this.normalizeInput();
int valor = this.view.getValorField().getValue();
String descripcion = this.view.getDescripcionField().getText();
if (editing) {
this.editarCalculoFondo(valor, descripcion);
this.editing = false;
} else {
this.guardarCalculoFondo(valor, descripcion);
} }
private void fillResumen() { this.updateResumen();
this.view.getFondoField().setValue(this.caja.getFondo()); this.cleanInput();
this.resetFocus();
}
private void editarActionListener() {
int selectedID = this.view.getTable().getSelectedRow();
if (selectedID >= 0) {
int selectedModelID = this.view.getTable().getRowSorter().convertRowIndexToModel(selectedID);
CalculoFondo calculoFondo = this.view.getTableModel().getCalculoFondo(selectedModelID);
this.editingId = selectedModelID;
this.editingCalculoFondo = calculoFondo;
this.editing = true;
this.view.getValorField().setValue(calculoFondo.getValor());
this.view.getDescripcionField().setText(calculoFondo.getDescripcion());
}
}
private void eliminarActionListener() {
int selectedID = this.view.getTable().getSelectedRow();
if (selectedID >= 0) {
CalculoFondo calculoFondo = this.view.getTableModel().getCalculoFondo(selectedID);
this.view.getTableModel().removeRow(selectedID);
DAOManager.getCalculoFondoDAO().deleteCalculoFondo(calculoFondo);
this.updateResumen();
this.updateButtonsEnabled();
this.resetFocus();
}
}
private void guardarCalculoFondo(int valor, String descripcion) {
CalculoFondo calculoFondo = new CalculoFondo();
calculoFondo.setValor(valor);
calculoFondo.setDescripcion(descripcion);
calculoFondo.setCaja(this.caja);
DAOManager.getCalculoFondoDAO().insertCalculoFondo(calculoFondo);
this.view.getTableModel().addRow(calculoFondo);
}
private void editarCalculoFondo(int valor, String descripcion) {
this.editingCalculoFondo.setValor(valor);
this.editingCalculoFondo.setDescripcion(descripcion);
this.editingCalculoFondo.setCaja(this.caja);
DAOManager.getCalculoFondoDAO().updateCalculoFondo(editingCalculoFondo);
this.view.getTableModel().setCalculoFondo(this.editingId, this.editingCalculoFondo);
}
private void updateButtonsEnabled() {
if (this.view.getTable().getSelectedRow() >= 0) {
this.view.getEliminarButton().setEnabled(true);
this.view.getEditarButton().setEnabled(true);
} else {
this.view.getEliminarButton().setEnabled(false);
this.view.getEditarButton().setEnabled(false);
}
}
private void cleanInput() {
this.view.getValorField().setValue(0);
this.view.getDescripcionField().setText("");
}
private void normalizeInput() {
if (this.view.getDescripcionField().getText() == null) {
this.view.getDescripcionField().setText("");
} }
private void updateResumen() { this.view.getDescripcionField().setText(this.view.getDescripcionField().getText().trim());
this.caja.setFondo(this.view.getFondoField().getValue()); }
int suma = DAOManager.getCalculoFondoDAO().getTotalCalculoFondo(this.caja);
this.view.getSumaField().setValue(suma); private void resetFocus() {
this.view.getDepositoField().setValue(suma - this.caja.getFondo()); this.view.getValorField().requestFocus();
}
DAOManager.getCajaDAO().update(this.caja);
}
private void setupViewEvents() {
moveTo(this.view.getValorField(), this.view.getDescripcionField());
doAction(this.view.getDescripcionField(), "save", KeyStroke.getKeyStroke("ENTER"), e -> this.guardarActionListener());
doAction(this.view.getFondoField(), "updateResumen", KeyStroke.getKeyStroke("ENTER"), e -> this.updateResumen());
this.view.getTable().getSelectionModel().addListSelectionListener(e -> updateButtonsEnabled());
this.view.getGuardarButton().addActionListener(e -> guardarActionListener());
this.view.getEditarButton().addActionListener(e -> editarActionListener());
this.view.getEliminarButton().addActionListener(e -> eliminarActionListener());
this.view.getTable().addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent mouseEvent) {
JTable table = (JTable) mouseEvent.getSource();
if (mouseEvent.getClickCount() == 2 && table.getSelectedRow() != -1) {
CalcularFondoController.this.editarActionListener();
}
}
});
}
private void guardarActionListener() {
this.normalizeInput();
int valor = this.view.getValorField().getValue();
String descripcion = this.view.getDescripcionField().getText();
if (editing) {
this.editarCalculoFondo(valor, descripcion);
this.editing = false;
} else {
this.guardarCalculoFondo(valor, descripcion);
}
this.updateResumen();
this.cleanInput();
this.resetFocus();
}
private void editarActionListener() {
int selectedID = this.view.getTable().getSelectedRow();
if (selectedID >= 0) {
int selectedModelID = this.view.getTable().getRowSorter().convertRowIndexToModel(selectedID);
CalculoFondo calculoFondo = this.view.getTableModel().getCalculoFondo(selectedModelID);
this.editingId = selectedModelID;
this.editingCalculoFondo = calculoFondo;
this.editing = true;
this.view.getValorField().setValue(calculoFondo.getValor());
this.view.getDescripcionField().setText(calculoFondo.getDescripcion());
}
}
private void eliminarActionListener() {
int selectedID = this.view.getTable().getSelectedRow();
if (selectedID >= 0) {
CalculoFondo calculoFondo = this.view.getTableModel().getCalculoFondo(selectedID);
this.view.getTableModel().removeRow(selectedID);
DAOManager.getCalculoFondoDAO().deleteCalculoFondo(calculoFondo);
this.updateResumen();
this.updateButtonsEnabled();
this.resetFocus();
}
}
private void guardarCalculoFondo(int valor, String descripcion) {
CalculoFondo calculoFondo = new CalculoFondo();
calculoFondo.setValor(valor);
calculoFondo.setDescripcion(descripcion);
calculoFondo.setCaja(this.caja);
DAOManager.getCalculoFondoDAO().insertCalculoFondo(calculoFondo);
this.view.getTableModel().addRow(calculoFondo);
}
private void editarCalculoFondo(int valor, String descripcion) {
this.editingCalculoFondo.setValor(valor);
this.editingCalculoFondo.setDescripcion(descripcion);
this.editingCalculoFondo.setCaja(this.caja);
DAOManager.getCalculoFondoDAO().updateCalculoFondo(editingCalculoFondo);
this.view.getTableModel().setCalculoFondo(this.editingId, this.editingCalculoFondo);
}
private void updateButtonsEnabled() {
if (this.view.getTable().getSelectedRow() >= 0) {
this.view.getEliminarButton().setEnabled(true);
this.view.getEditarButton().setEnabled(true);
} else {
this.view.getEliminarButton().setEnabled(false);
this.view.getEditarButton().setEnabled(false);
}
}
private void cleanInput() {
this.view.getValorField().setValue(0);
this.view.getDescripcionField().setText("");
}
private void normalizeInput() {
if (this.view.getDescripcionField().getText() == null) {
this.view.getDescripcionField().setText("");
}
this.view.getDescripcionField().setText(this.view.getDescripcionField().getText().trim());
}
private void resetFocus() {
this.view.getValorField().requestFocus();
}
} }

View File

@@ -31,357 +31,356 @@ 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.EgresosView; import danielcortes.xyz.views.EgresosView;
import danielcortes.xyz.views.components.table_model.EgresosTableModel; import danielcortes.xyz.views.components.table_model.EgresosTableModel;
import javax.swing.*;
import java.awt.event.ActionEvent; import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter; import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent; import java.awt.event.MouseEvent;
import javax.swing.AbstractAction;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.KeyStroke;
/** /**
* Controlador el cual esta orientado a manejar la vista de EgresosView * Controlador el cual esta orientado a manejar la vista de EgresosView Maneja su contenido y las
* Maneja su contenido y las acciones que esta realiza * acciones que esta realiza
*/ */
public class EgresosController extends BaseController{ public class EgresosController extends BaseController {
private EgresosView view;
private Caja caja;
private int editingId; private EgresosView view;
private boolean editing; private Caja caja;
private Egreso editingEgreso;
/** private int editingId;
* Crea el controlador private boolean editing;
* Al inicial ejecuta: private Egreso editingEgreso;
* - Metodo que genera los eventos para la vista.
* - Metodo que llena los tipos de egresos en la vista. /**
* - Actualiza el estado de los botones. * Crea el controlador Al inicial ejecuta: - Metodo que genera los eventos para la vista. - Metodo
*/ * que llena los tipos de egresos en la vista. - Actualiza el estado de los botones.
public EgresosController(EgresosView view) { */
this.view = view; public EgresosController(EgresosView view) {
this.setUpViewEvents(); this.view = view;
this.fillTipoEgresoCombo(); this.setUpViewEvents();
this.updateButtonsEnabled(); this.fillTipoEgresoCombo();
this.updateButtonsEnabled();
}
/**
* Guarda la caja entregada y actualiza los datos de la tabla de egresos y actualiza el field con
* el total de egresos.
*/
public void updateCaja(Caja caja) {
this.caja = caja;
this.fillEgresosTable();
this.updateTotalEgresos();
}
/**
* Rellena el ComboBox con los tipos de egresos disponibles
*/
private void fillTipoEgresoCombo() {
JComboBox<TipoEgresoToStringWrapper> tipoCombo = view.getTipoCombo();
for (TipoEgreso tipoEgreso : DAOManager.getTipoEgresoDAO().findAll()) {
tipoCombo.addItem(new TipoEgresoToStringWrapper(tipoEgreso));
} }
}
/** /**
* Guarda la caja entregada y actualiza los datos de la tabla de egresos y actualiza el field con el total de egresos. * Rellena la tabla de egresos con los egresos correspondientes a la caja seleccionada
*/ */
public void updateCaja(Caja caja) { private void fillEgresosTable() {
this.caja = caja; EgresosTableModel egresosTableModel = view.getEgresosTableModel();
this.fillEgresosTable(); egresosTableModel.removeRows();
this.updateTotalEgresos(); for (Egreso egreso : DAOManager.getEgresoDAO().findByCaja(this.caja)) {
egresosTableModel.addRow(egreso);
} }
}
/** /**
* Rellena el ComboBox con los tipos de egresos disponibles * Asigna todos los eventos para la vista de egresos. - Cuando se apreta el boton de guardar o se
*/ * apreta enter en los fields de descripcion, nro, valor y tipo Se llama al metodo
private void fillTipoEgresoCombo() { * guardarActionListener. - Cuando se apreta el boton de eliminar se llama al metodos
JComboBox<TipoEgresoToStringWrapper> tipoCombo = view.getTipoCombo(); * eliminarActionListener - Cuando se presiona editar o se realizan 2 clicks en la tabla de
for (TipoEgreso tipoEgreso : DAOManager.getTipoEgresoDAO().findAll()) { * egresos se llama a editarActionListener - Cuando se selecciona una fila en la tabla se llama a
tipoCombo.addItem(new TipoEgresoToStringWrapper(tipoEgreso)); * updateButtonsEnabled
*/
private void setUpViewEvents() {
moveTo(this.view.getNroField(), this.view.getDescripcionField());
moveTo(this.view.getDescripcionField(), this.view.getValorField());
moveTo(this.view.getValorField(), this.view.getTipoCombo());
doAction(this.view.getTipoCombo(), "save", KeyStroke.getKeyStroke("ENTER"),
e -> this.guardarActionListener());
this.view.getEgresosTable().getSelectionModel()
.addListSelectionListener(e -> updateButtonsEnabled());
this.view.getGuardarButton().addActionListener(e -> guardarActionListener());
this.view.getEliminarButton().addActionListener(e -> eliminarActionListener());
this.view.getEditarButton().addActionListener(e -> editarActionListener());
this.view.getEgresosTable().addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent mouseEvent) {
JTable table = (JTable) mouseEvent.getSource();
if (mouseEvent.getClickCount() == 2 && table.getSelectedRow() != -1) {
EgresosController.this.editarActionListener();
} }
}
});
}
/**
* Realiza las preparaciones previas a guardar un egreso Primero llama a normalizar los inputs y a
* ocultar los mensajes de error Luego si es que esta colocada la flag de editing se llama al
* metodo editarEgreso y si no, se llama a guardarEgreso Al terminar esto, se llama a resetear el
* focus en los inputs y a actualizar el total de egresos
*/
private void guardarActionListener() {
this.normalizeInputs();
this.hideErrorMessages();
String nro = this.view.getNroField().getText();
String descripcion = this.view.getDescripcionField().getText();
int valor = this.view.getValorField().getValue();
TipoEgreso tipo = (TipoEgreso) this.view.getTipoCombo().getSelectedItem();
if (editing) {
this.editarEgreso(nro, descripcion, valor, tipo, this.caja);
} else {
this.guardarEgreso(nro, descripcion, valor, tipo, this.caja);
}
this.resetFocus();
}
/**
* Realiza las acciones necesarias para eliminar un egreso Obtiene el egreso seleccionado y lo
* elimina, luego llama a actualizar el total de egresos y a actualizar el estado de los botones.
*/
private void eliminarActionListener() {
int selectedID = this.view.getEgresosTable().getSelectedRow();
if (selectedID >= 0) {
Egreso egreso = this.view.getEgresosTableModel().getEgreso(selectedID);
this.view.getEgresosTableModel().removeRow(selectedID);
DAOManager.getEgresoDAO().deleteEgreso(egreso);
this.updateTotalEgresos();
this.updateButtonsEnabled();
this.resetFocus();
}
}
/**
* Realiza lo necesario para comenzar a editar un egreso Llama a esconder los mensajes de error.
* Guarda globalmente en la clase el egreso que se esta editando, su id y una flag indicando que
* se esta en modo editar. Ademas rellena los campos de input con los valores del egreso que se
* esta editando.
*/
private void editarActionListener() {
this.hideErrorMessages();
int selectedID = this.view.getEgresosTable().getSelectedRow();
int selectedModelID = this.view.getEgresosTable().getRowSorter()
.convertRowIndexToModel(selectedID);
if (selectedModelID >= 0) {
Egreso egreso = this.view.getEgresosTableModel().getEgreso(selectedModelID);
this.editingId = selectedModelID;
this.editingEgreso = egreso;
this.editing = true;
this.view.getNroField().setText(egreso.getNro());
this.view.getDescripcionField().setText(egreso.getDescripcion());
this.view.getValorField().setValue(egreso.getValor());
this.view.getTipoCombo().setSelectedItem(egreso.getTipoEgreso());
}
}
/**
* Obtiene el total de egresos y los coloca en el campo de totalEgresosField.
*/
private void updateTotalEgresos() {
int total = DAOManager.getEgresoDAO().getTotalEgreso(this.caja);
this.view.getTotalEgresosField().setValue(total);
}
/**
* Cuando se tiene seleccionada una fila de la tabla activa los botones de eliminar y editar Si no
* esta seleccionada los desactiva
*/
private void updateButtonsEnabled() {
if (this.view.getEgresosTable().getSelectedRow() >= 0) {
this.view.getEliminarButton().setEnabled(true);
this.view.getEditarButton().setEnabled(true);
} else {
this.view.getEliminarButton().setEnabled(false);
this.view.getEditarButton().setEnabled(false);
}
}
/**
* Guarda un egreso tras llamar a validar su input Luego de guardar, agrega el egreso a la tabla,
* llama a actualizar el total de egresos y llama a limpiar a los inputs
*/
private void guardarEgreso(String nro, String descripcion, int valor, TipoEgreso tipo,
Caja caja) {
if (this.validateInput(nro, descripcion, tipo, caja)) {
Egreso egreso = new Egreso();
egreso.setValor(valor);
egreso.setDescripcion(descripcion);
egreso.setNro(nro);
egreso.setTipoEgreso(tipo);
egreso.setCaja(caja);
DAOManager.getEgresoDAO().insertEgreso(egreso);
this.view.getEgresosTableModel().addRow(egreso);
this.updateTotalEgresos();
this.clearInputs();
}
}
/**
* Actualiza un egreso tras llamar a validar su input Tras esto actualiza el egreso en la tabla,
* llama a actualizar el total de egresos y a limpiar los inputs Finalmente setea la flag editing
* a false
*/
private void editarEgreso(String nro, String descripcion, int valor, TipoEgreso tipo, Caja caja) {
if (this.validateInput(nro, descripcion, tipo, caja)) {
this.editingEgreso.setValor(valor);
this.editingEgreso.setDescripcion(descripcion);
this.editingEgreso.setNro(nro);
this.editingEgreso.setTipoEgreso(tipo);
DAOManager.getEgresoDAO().updateEgreso(this.editingEgreso);
this.view.getEgresosTableModel().setEgreso(this.editingId, this.editingEgreso);
this.updateTotalEgresos();
this.clearInputs();
this.editing = false;
}
}
/**
* llama a los metodos necesarios para validar los inputs entregados
*
* @return true cuando todas las validaciones retoran true, si no, false
*/
private boolean validateInput(String nro, String descripcion, TipoEgreso tipoEgreso, Caja caja) {
boolean nroValidation = this.validateNro(nro);
boolean descripcionValidation = this.validateDescripcion(descripcion);
boolean tipoEgresoValidation = this.validateTipoEgreso(tipoEgreso);
boolean cajaValidation = this.validateCaja(caja);
return nroValidation && descripcionValidation && tipoEgresoValidation;
}
/**
* Valida la variable nro contra los casos - Es null - Esta vacio Cuando el primer caso sea true,
* colocara un mensaje de error correspondiente en el jlabel correspondiente
*
* @return Si cualquiera de estos casos son true se retornara false, si no, se retorna true
*/
private boolean validateNro(String nro) {
if (nro == null) {
this.view.getErrorNumero().setText("Hubo un problema con los datos");
this.view.getErrorNumero().setVisible(true);
return false;
} }
/** nro = nro.trim();
* Rellena la tabla de egresos con los egresos correspondientes a la caja seleccionada if (nro.isEmpty()) {
*/ this.view.getErrorNumero().setText("El campo esta vacio");
private void fillEgresosTable() { this.view.getErrorNumero().setVisible(true);
EgresosTableModel egresosTableModel = view.getEgresosTableModel(); return false;
egresosTableModel.removeRows(); }
for (Egreso egreso : DAOManager.getEgresoDAO().findByCaja(this.caja)) { return true;
egresosTableModel.addRow(egreso);
} }
/**
* Valida la variable descripcion contra los casos - Es null - Esta vacio Cuando el primer caso
* sea true, colocara un mensaje de error correspondiente en el jlabel correspondiente
*
* @return Si cualquiera de estos casos son true se retornara false, si no, se retorna true
*/
private boolean validateDescripcion(String descripcion) {
if (descripcion == null) {
this.view.getErrorDescripcion().setText("Hubo un problema con los datos");
this.view.getErrorDescripcion().setVisible(true);
return false;
} }
/** if (descripcion.isEmpty()) {
* Asigna todos los eventos para la vista de egresos. this.view.getErrorDescripcion().setText("El campo esta vacio");
* - Cuando se apreta el boton de guardar o se apreta enter en los fields de descripcion, nro, valor y tipo this.view.getErrorDescripcion().setVisible(true);
* Se llama al metodo guardarActionListener. return false;
* - Cuando se apreta el boton de eliminar se llama al metodos eliminarActionListener }
* - Cuando se presiona editar o se realizan 2 clicks en la tabla de egresos se llama a editarActionListener return true;
* - Cuando se selecciona una fila en la tabla se llama a updateButtonsEnabled }
*/
private void setUpViewEvents() {
moveTo(this.view.getNroField(), this.view.getDescripcionField());
moveTo(this.view.getDescripcionField(), this.view.getValorField());
moveTo(this.view.getValorField(), this.view.getTipoCombo());
doAction(this.view.getTipoCombo(), "save", KeyStroke.getKeyStroke("ENTER"), e -> this.guardarActionListener());
this.view.getEgresosTable().getSelectionModel().addListSelectionListener(e -> updateButtonsEnabled()); /**
this.view.getGuardarButton().addActionListener(e -> guardarActionListener()); * Valida la variable tipoEgreso contra los casos - Es null Cuando este caso sea true, colocara un
this.view.getEliminarButton().addActionListener(e -> eliminarActionListener()); * mensaje de error correspondiente en el jlabel correspondiente
this.view.getEditarButton().addActionListener(e -> editarActionListener()); *
* @return Si este caso es true se retornara false, si no, se retorna true
*/
private boolean validateTipoEgreso(TipoEgreso tipoEgreso) {
if (tipoEgreso == null) {
this.view.getErrorTipoEgreso().setText("Hubo un problema con los datos");
this.view.getErrorTipoEgreso().setVisible(true);
return false;
}
return true;
}
this.view.getEgresosTable().addMouseListener(new MouseAdapter() { /**
public void mouseClicked(MouseEvent mouseEvent) { * Valida la variable caja contra los casos - Es null
JTable table = (JTable) mouseEvent.getSource(); *
if (mouseEvent.getClickCount() == 2 && table.getSelectedRow() != -1) { * @return Si este caso es true se retornara false, si no, se retorna true
EgresosController.this.editarActionListener(); */
} private boolean validateCaja(Caja caja) {
} return caja != null;
}); }
/**
* Esconde los mensajes de error en la ventana de egresos
*/
private void hideErrorMessages() {
this.view.getErrorTipoEgreso().setVisible(false);
this.view.getErrorDescripcion().setVisible(false);
this.view.getErrorNumero().setVisible(false);
}
/**
* Vacia los campos de texto y selecciona la primera opcion en el jcombobox
*/
private void clearInputs() {
this.view.getTipoCombo().setSelectedIndex(0);
this.view.getNroField().setText("");
this.view.getValorField().setValue(0);
this.view.getValorField().setText("");
this.view.getDescripcionField().setText("");
}
/**
* Ejecuta trim sobre todos los campos de texto
*/
private void normalizeInputs() {
this.view.getNroField().setText(this.view.getNroField().getText().trim());
this.view.getDescripcionField().setText(this.view.getDescripcionField().getText().trim());
}
/**
* Setea el focus en el campo nroField
*/
private void resetFocus() {
this.view.getNroField().requestFocus();
}
private class GuardarAction extends AbstractAction {
EgresosController controller;
GuardarAction(EgresosController controller) {
this.controller = controller;
} }
/** @Override
* Realiza las preparaciones previas a guardar un egreso public void actionPerformed(ActionEvent e) {
* Primero llama a normalizar los inputs y a ocultar los mensajes de error this.controller.guardarActionListener();
* Luego si es que esta colocada la flag de editing se llama al metodo editarEgreso y si no, se llama a guardarEgreso
* Al terminar esto, se llama a resetear el focus en los inputs y a actualizar el total de egresos
*/
private void guardarActionListener() {
this.normalizeInputs();
this.hideErrorMessages();
String nro = this.view.getNroField().getText();
String descripcion = this.view.getDescripcionField().getText();
int valor = this.view.getValorField().getValue();
TipoEgreso tipo = (TipoEgreso) this.view.getTipoCombo().getSelectedItem();
if (editing) {
this.editarEgreso(nro, descripcion, valor, tipo, this.caja);
} else {
this.guardarEgreso(nro, descripcion, valor, tipo, this.caja);
}
this.resetFocus();
}
/**
* Realiza las acciones necesarias para eliminar un egreso
* Obtiene el egreso seleccionado y lo elimina, luego llama a actualizar el total de egresos y a actualizar el estado de los botones.
*/
private void eliminarActionListener() {
int selectedID = this.view.getEgresosTable().getSelectedRow();
if (selectedID >= 0) {
Egreso egreso = this.view.getEgresosTableModel().getEgreso(selectedID);
this.view.getEgresosTableModel().removeRow(selectedID);
DAOManager.getEgresoDAO().deleteEgreso(egreso);
this.updateTotalEgresos();
this.updateButtonsEnabled();
this.resetFocus();
}
}
/**
* Realiza lo necesario para comenzar a editar un egreso
* Llama a esconder los mensajes de error.
* Guarda globalmente en la clase el egreso que se esta editando, su id y una flag indicando que se esta en modo editar.
* Ademas rellena los campos de input con los valores del egreso que se esta editando.
*/
private void editarActionListener() {
this.hideErrorMessages();
int selectedID = this.view.getEgresosTable().getSelectedRow();
int selectedModelID = this.view.getEgresosTable().getRowSorter().convertRowIndexToModel(selectedID);
if (selectedModelID >= 0) {
Egreso egreso = this.view.getEgresosTableModel().getEgreso(selectedModelID);
this.editingId = selectedModelID;
this.editingEgreso = egreso;
this.editing = true;
this.view.getNroField().setText(egreso.getNro());
this.view.getDescripcionField().setText(egreso.getDescripcion());
this.view.getValorField().setValue(egreso.getValor());
this.view.getTipoCombo().setSelectedItem(egreso.getTipoEgreso());
}
}
/**
* Obtiene el total de egresos y los coloca en el campo de totalEgresosField.
*/
private void updateTotalEgresos() {
int total = DAOManager.getEgresoDAO().getTotalEgreso(this.caja);
this.view.getTotalEgresosField().setValue(total);
}
/**
* Cuando se tiene seleccionada una fila de la tabla activa los botones de eliminar y editar
* Si no esta seleccionada los desactiva
*/
private void updateButtonsEnabled() {
if (this.view.getEgresosTable().getSelectedRow() >= 0) {
this.view.getEliminarButton().setEnabled(true);
this.view.getEditarButton().setEnabled(true);
} else {
this.view.getEliminarButton().setEnabled(false);
this.view.getEditarButton().setEnabled(false);
}
}
/**
* Guarda un egreso tras llamar a validar su input
* Luego de guardar, agrega el egreso a la tabla, llama a actualizar el total de egresos y llama a limpiar a los inputs
*/
private void guardarEgreso(String nro, String descripcion, int valor, TipoEgreso tipo, Caja caja) {
if (this.validateInput(nro, descripcion, tipo, caja)) {
Egreso egreso = new Egreso();
egreso.setValor(valor);
egreso.setDescripcion(descripcion);
egreso.setNro(nro);
egreso.setTipoEgreso(tipo);
egreso.setCaja(caja);
DAOManager.getEgresoDAO().insertEgreso(egreso);
this.view.getEgresosTableModel().addRow(egreso);
this.updateTotalEgresos();
this.clearInputs();
}
}
/**
* Actualiza un egreso tras llamar a validar su input
* Tras esto actualiza el egreso en la tabla, llama a actualizar el total de egresos y a limpiar los inputs
* Finalmente setea la flag editing a false
*/
private void editarEgreso(String nro, String descripcion, int valor, TipoEgreso tipo, Caja caja) {
if (this.validateInput(nro, descripcion, tipo, caja)) {
this.editingEgreso.setValor(valor);
this.editingEgreso.setDescripcion(descripcion);
this.editingEgreso.setNro(nro);
this.editingEgreso.setTipoEgreso(tipo);
DAOManager.getEgresoDAO().updateEgreso(this.editingEgreso);
this.view.getEgresosTableModel().setEgreso(this.editingId, this.editingEgreso);
this.updateTotalEgresos();
this.clearInputs();
this.editing = false;
}
}
/**
* llama a los metodos necesarios para validar los inputs entregados
*
* @return true cuando todas las validaciones retoran true, si no, false
*/
private boolean validateInput(String nro, String descripcion, TipoEgreso tipoEgreso, Caja caja) {
boolean nroValidation = this.validateNro(nro);
boolean descripcionValidation = this.validateDescripcion(descripcion);
boolean tipoEgresoValidation = this.validateTipoEgreso(tipoEgreso);
boolean cajaValidation = this.validateCaja(caja);
return nroValidation && descripcionValidation && tipoEgresoValidation;
}
/**
* Valida la variable nro contra los casos
* - Es null
* - Esta vacio
* Cuando el primer caso sea true, colocara un mensaje de error correspondiente en el jlabel correspondiente
*
* @return Si cualquiera de estos casos son true se retornara false, si no, se retorna true
*/
private boolean validateNro(String nro) {
if (nro == null) {
this.view.getErrorNumero().setText("Hubo un problema con los datos");
this.view.getErrorNumero().setVisible(true);
return false;
}
nro = nro.trim();
if (nro.isEmpty()) {
this.view.getErrorNumero().setText("El campo esta vacio");
this.view.getErrorNumero().setVisible(true);
return false;
}
return true;
}
/**
* Valida la variable descripcion contra los casos
* - Es null
* - Esta vacio
* Cuando el primer caso sea true, colocara un mensaje de error correspondiente en el jlabel correspondiente
*
* @return Si cualquiera de estos casos son true se retornara false, si no, se retorna true
*/
private boolean validateDescripcion(String descripcion) {
if (descripcion == null) {
this.view.getErrorDescripcion().setText("Hubo un problema con los datos");
this.view.getErrorDescripcion().setVisible(true);
return false;
}
if (descripcion.isEmpty()) {
this.view.getErrorDescripcion().setText("El campo esta vacio");
this.view.getErrorDescripcion().setVisible(true);
return false;
}
return true;
}
/**
* Valida la variable tipoEgreso contra los casos
* - Es null
* Cuando este caso sea true, colocara un mensaje de error correspondiente en el jlabel correspondiente
*
* @return Si este caso es true se retornara false, si no, se retorna true
*/
private boolean validateTipoEgreso(TipoEgreso tipoEgreso) {
if (tipoEgreso == null) {
this.view.getErrorTipoEgreso().setText("Hubo un problema con los datos");
this.view.getErrorTipoEgreso().setVisible(true);
return false;
}
return true;
}
/**
* Valida la variable caja contra los casos
* - Es null
*
* @return Si este caso es true se retornara false, si no, se retorna true
*/
private boolean validateCaja(Caja caja) {
return caja != null;
}
/**
* Esconde los mensajes de error en la ventana de egresos
*/
private void hideErrorMessages() {
this.view.getErrorTipoEgreso().setVisible(false);
this.view.getErrorDescripcion().setVisible(false);
this.view.getErrorNumero().setVisible(false);
}
/**
* Vacia los campos de texto y selecciona la primera opcion en el jcombobox
*/
private void clearInputs() {
this.view.getTipoCombo().setSelectedIndex(0);
this.view.getNroField().setText("");
this.view.getValorField().setValue(0);
this.view.getValorField().setText("");
this.view.getDescripcionField().setText("");
}
/**
* Ejecuta trim sobre todos los campos de texto
*/
private void normalizeInputs() {
this.view.getNroField().setText(this.view.getNroField().getText().trim());
this.view.getDescripcionField().setText(this.view.getDescripcionField().getText().trim());
}
/**
* Setea el focus en el campo nroField
*/
private void resetFocus() {
this.view.getNroField().requestFocus();
}
private class GuardarAction extends AbstractAction {
EgresosController controller;
GuardarAction(EgresosController controller) {
this.controller = controller;
}
@Override
public void actionPerformed(ActionEvent e) {
this.controller.guardarActionListener();
}
} }
}
} }

View File

@@ -11,331 +11,367 @@ import danielcortes.xyz.views.EstadoResultadoView;
import danielcortes.xyz.views.dialogs.InformeGeneratedConfirmation; import danielcortes.xyz.views.dialogs.InformeGeneratedConfirmation;
import danielcortes.xyz.views.dialogs.XLSFileChooser; 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.nio.file.Path;
import java.time.YearMonth; import java.time.YearMonth;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
public class EstadoResultadoController extends BaseController { public class EstadoResultadoController extends BaseController {
private EstadoResultadoView view;
private EstadoResultado estadoResultado;
private YearMonth mes;
public EstadoResultadoController(EstadoResultadoView view) { private EstadoResultadoView view;
this.view = view; private EstadoResultado estadoResultado;
this.setupViewEvents(); private YearMonth mes;
this.updateMonth();
public EstadoResultadoController(EstadoResultadoView view) {
this.view = view;
this.setupViewEvents();
this.updateMonth();
}
public void update() {
this.updateMonth();
}
private void setupViewEvents() {
this.view.getMonthCombo().addActionListener(e -> this.updateMonth());
this.view.getYearSpinner().addChangeListener(e -> this.updateMonth());
this.setupUpdateViewEvents();
this.setupMovementViewEvents();
this.view.getGuardarButton()
.addActionListener(e -> EstadoResultadoController.this.guardarListener());
this.view.getExportarButton()
.addActionListener(e -> EstadoResultadoController.this.exportarListener());
}
private void setupUpdateViewEvents() {
this.view.getGastosGeneralesCuentaCorrienteFactura().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.getServiciosAgua().addFocusListener(
(FocusLostListener) e -> EstadoResultadoController.this.updateServicios());
this.view.getServiciosLuz().addFocusListener(
(FocusLostListener) e -> EstadoResultadoController.this.updateServicios());
this.view.getServiciosGas().addFocusListener(
(FocusLostListener) e -> EstadoResultadoController.this.updateServicios());
this.view.getServiciosTelefono().addFocusListener(
(FocusLostListener) e -> EstadoResultadoController.this.updateServicios());
this.view.getServiciosOtro().addFocusListener(
(FocusLostListener) e -> EstadoResultadoController.this.updateServicios());
this.view.getGastosOperacionalesCostoVenta().addFocusListener(
(FocusLostListener) e -> EstadoResultadoController.this.updateGastosOperacionales());
this.view.getGastosOperacionalesRemuneraciones().addFocusListener(
(FocusLostListener) e -> EstadoResultadoController.this.updateGastosOperacionales());
this.view.getGastosOperacionalesFiniquitos().addFocusListener(
(FocusLostListener) e -> EstadoResultadoController.this.updateGastosOperacionales());
this.view.getGastosOperacionalesAguinaldo().addFocusListener(
(FocusLostListener) e -> EstadoResultadoController.this.updateGastosOperacionales());
this.view.getGastosOperacionalesBonos().addFocusListener(
(FocusLostListener) e -> EstadoResultadoController.this.updateGastosOperacionales());
this.view.getGastosOperacionalesHonorariosContador().addFocusListener(
(FocusLostListener) e -> EstadoResultadoController.this.updateGastosOperacionales());
this.view.getGastosOperacionalesArriendo().addFocusListener(
(FocusLostListener) e -> EstadoResultadoController.this.updateGastosOperacionales());
this.view.getResumenIVAFavor()
.addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateResumen());
this.view.getResumenPPM()
.addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateResumen());
}
private void setupMovementViewEvents() {
moveTo(this.view.getGastosOperacionalesCostoVenta(),
this.view.getGastosOperacionalesRemuneraciones());
moveTo(this.view.getGastosOperacionalesRemuneraciones(),
this.view.getGastosOperacionalesFiniquitos());
moveTo(this.view.getGastosOperacionalesFiniquitos(),
this.view.getGastosOperacionalesAguinaldo());
moveTo(this.view.getGastosOperacionalesAguinaldo(), this.view.getGastosOperacionalesBonos());
moveTo(this.view.getGastosOperacionalesBonos(),
this.view.getGastosOperacionalesHonorariosContador());
moveTo(this.view.getGastosOperacionalesHonorariosContador(),
this.view.getGastosOperacionalesArriendo());
moveTo(this.view.getGastosOperacionalesArriendo(), this.view.getServiciosAgua());
moveTo(this.view.getServiciosAgua(), this.view.getServiciosLuz());
moveTo(this.view.getServiciosLuz(), this.view.getServiciosGas());
moveTo(this.view.getServiciosGas(), this.view.getServiciosTelefono());
moveTo(this.view.getServiciosTelefono(), this.view.getServiciosOtro());
moveTo(this.view.getServiciosOtro(), this.view.getGastosGeneralesCuentaCorrienteFactura());
moveTo(this.view.getGastosGeneralesCuentaCorrienteFactura(),
this.view.getGastosGeneralesCuentaCorrienteBoleta());
moveTo(this.view.getGastosGeneralesCuentaCorrienteBoleta(),
this.view.getGastosGeneralesCuentaCorrienteSinRespaldo());
moveTo(this.view.getGastosGeneralesCuentaCorrienteSinRespaldo(), this.view.getResumenPPM());
moveTo(this.view.getResumenPPM(), this.view.getResumenIVAFavor());
}
private void guardarListener() {
EstadoResultadoDAO dao = DAOManager.getEstadoResultadoDAO();
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;
} }
public void update() { InformeEstadoResultado estadoResultado = new InformeEstadoResultado(this.mes, saveFile);
this.updateMonth(); estadoResultado.generarInforme();
new InformeGeneratedConfirmation(saveFile).execute();
}
private void updateMonth() {
this.mes = this.view.getMonth();
this.estadoResultado = DAOManager.getEstadoResultadoDAO().findByMonth(this.mes);
if (estadoResultado == null) {
this.estadoResultado = EstadoResultado.emptyEstadoResultado;
this.estadoResultado.setMes(this.mes);
DAOManager.getEstadoResultadoDAO().insertEstadoResultado(estadoResultado);
} }
private void setupViewEvents() { this.fillVentas();
this.view.getMonthCombo().addActionListener(e -> this.updateMonth()); this.fillGastosGenerales();
this.view.getYearSpinner().addChangeListener(e -> this.updateMonth()); this.fillServicios();
this.fillGastosOperacionales();
this.fillResumen();
}
this.setupUpdateViewEvents(); private void fillVentas() {
this.setupMovementViewEvents(); int ventaBruta = DAOManager.getIngresoDAO().getTotalIngresoMes(this.mes);
int ventaExentas = DAOManager.getIngresoDAO().getTotalExentasMes(this.mes);
int ventaNeta = (int) Math.round((double) ventaBruta / 1.19d);
int ventaIVA = ventaBruta - ventaNeta;
int ventaNetaYExentas = ventaExentas + ventaNeta;
this.view.getGuardarButton().addActionListener(e -> EstadoResultadoController.this.guardarListener()); this.view.getVentaBrutaField().setValue(ventaBruta);
this.view.getExportarButton().addActionListener(e -> EstadoResultadoController.this.exportarListener()); this.view.getVentaIVAField().setValue(ventaIVA);
} this.view.getVentaNetaField().setValue(ventaNeta);
this.view.getVentaExentasField().setValue(ventaExentas);
this.view.getVentasNetaExentasField().setValue(ventaNetaYExentas);
}
private void setupUpdateViewEvents() { private void fillGastosGenerales() {
this.view.getGastosGeneralesCuentaCorrienteFactura().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateGastosGenerales()); TipoEgreso facturaGastosGenerales = DAOManager.getTipoEgresoDAO()
this.view.getGastosGeneralesCuentaCorrienteBoleta().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateGastosGenerales()); .findByNombre("Factura Gastos Generales").get(0);
this.view.getGastosGeneralesCuentaCorrienteSinRespaldo().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateGastosGenerales()); TipoEgreso gastoGeneralConBoleta = DAOManager.getTipoEgresoDAO()
.findByNombre("Gasto General Con Boleta").get(0);
TipoEgreso gastoGeneralSinRespaldo = DAOManager.getTipoEgresoDAO()
.findByNombre("Gasto General Sin Respaldo").get(0);
this.view.getServiciosAgua().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateServicios()); int cuentaCorrienteFactura = this.estadoResultado.getCuentaCorrienteFactura();
this.view.getServiciosLuz().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateServicios()); int cuentaCorrienteBoleta = this.estadoResultado.getCuentaCorrienteBoleta();
this.view.getServiciosGas().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateServicios()); int cuentaCorrienteSinRespaldo = this.estadoResultado.getCuentaCorrienteSinRespaldo();
this.view.getServiciosTelefono().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateServicios()); int efectivoFacturaGastosGenerales = DAOManager.getEgresoDAO()
this.view.getServiciosOtro().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateServicios()); .getTotalEgresoMesPorTipo(this.mes, facturaGastosGenerales);
int efectivoGastoGeneralConBoleta = DAOManager.getEgresoDAO()
.getTotalEgresoMesPorTipo(this.mes, gastoGeneralConBoleta);
int efectivoGastoGeneralSinRespaldo = DAOManager.getEgresoDAO()
.getTotalEgresoMesPorTipo(this.mes, gastoGeneralSinRespaldo);
int gastoTotal = efectivoFacturaGastosGenerales + efectivoGastoGeneralConBoleta
+ efectivoGastoGeneralSinRespaldo + cuentaCorrienteBoleta + cuentaCorrienteFactura
+ cuentaCorrienteSinRespaldo;
this.view.getGastosOperacionalesCostoVenta().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateGastosOperacionales()); this.view.getGastosGeneralesEfectivoFacturaField().setValue(efectivoFacturaGastosGenerales);
this.view.getGastosOperacionalesRemuneraciones().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateGastosOperacionales()); this.view.getGastosGeneralesEfectivoBoletaField().setValue(efectivoGastoGeneralConBoleta);
this.view.getGastosOperacionalesFiniquitos().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateGastosOperacionales()); this.view.getGastosGeneralesEfectivoSinRespaldo().setValue(efectivoGastoGeneralSinRespaldo);
this.view.getGastosOperacionalesAguinaldo().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateGastosOperacionales()); this.view.getGastosGeneralesCuentaCorrienteFactura().setValue(cuentaCorrienteFactura);
this.view.getGastosOperacionalesBonos().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateGastosOperacionales()); this.view.getGastosGeneralesCuentaCorrienteBoleta().setValue(cuentaCorrienteBoleta);
this.view.getGastosOperacionalesHonorariosContador().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateGastosOperacionales()); this.view.getGastosGeneralesCuentaCorrienteSinRespaldo().setValue(cuentaCorrienteSinRespaldo);
this.view.getGastosOperacionalesArriendo().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateGastosOperacionales()); this.view.getGastosGeneralesTotal().setValue(gastoTotal);
}
this.view.getResumenIVAFavor().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateResumen()); private void fillGastosOperacionales() {
this.view.getResumenPPM().addFocusListener((FocusLostListener) e -> EstadoResultadoController.this.updateResumen()); TipoEgreso tipoPagoPartime = DAOManager.getTipoEgresoDAO().findByNombre("Pago Partime").get(0);
}
private void setupMovementViewEvents() { int costoVenta = this.estadoResultado.getCostoVenta();
int remuneraciones = this.estadoResultado.getRemuneraciones();
int finiquitos = this.estadoResultado.getFiniquitos();
int aguinaldo = this.estadoResultado.getAguinaldo();
int bonosPersonal = this.estadoResultado.getBonosPersonal();
int honorariosContador = this.estadoResultado.getHonorariosContador();
int arriendo = this.estadoResultado.getArriendo();
int partime = DAOManager.getEgresoDAO().getTotalEgresoMesPorTipo(this.mes, tipoPagoPartime);
int ventaBruta = DAOManager.getIngresoDAO().getTotalIngresoMes(this.mes);
moveTo(this.view.getGastosOperacionalesCostoVenta(), this.view.getGastosOperacionalesRemuneraciones()); int total = costoVenta + remuneraciones + finiquitos + aguinaldo + bonosPersonal
moveTo(this.view.getGastosOperacionalesRemuneraciones(), this.view.getGastosOperacionalesFiniquitos()); + honorariosContador + arriendo + partime;
moveTo(this.view.getGastosOperacionalesFiniquitos(), this.view.getGastosOperacionalesAguinaldo()); double porcentajeCostoVenta = (double) costoVenta / (double) ventaBruta * 100d;
moveTo(this.view.getGastosOperacionalesAguinaldo(), this.view.getGastosOperacionalesBonos());
moveTo(this.view.getGastosOperacionalesBonos(), this.view.getGastosOperacionalesHonorariosContador());
moveTo(this.view.getGastosOperacionalesHonorariosContador(), this.view.getGastosOperacionalesArriendo());
moveTo(this.view.getGastosOperacionalesArriendo(), this.view.getServiciosAgua());
moveTo(this.view.getServiciosAgua(), this.view.getServiciosLuz()); this.view.getGastosOperacionalesCostoVenta().setValue(costoVenta);
moveTo(this.view.getServiciosLuz(), this.view.getServiciosGas()); this.view.getGastosOperacionesPorcentajeCostoVenta().setValue(porcentajeCostoVenta);
moveTo(this.view.getServiciosGas(), this.view.getServiciosTelefono()); this.view.getGastosOperacionalesRemuneraciones().setValue(remuneraciones);
moveTo(this.view.getServiciosTelefono(), this.view.getServiciosOtro()); this.view.getGastosOperacionalesFiniquitos().setValue(finiquitos);
moveTo(this.view.getServiciosOtro(), this.view.getGastosGeneralesCuentaCorrienteFactura()); this.view.getGastosOperacionalesAguinaldo().setValue(aguinaldo);
this.view.getGastosOperacionalesBonos().setValue(bonosPersonal);
this.view.getGastosOperacionalesHonorariosContador().setValue(honorariosContador);
this.view.getGastosOperacionalesArriendo().setValue(arriendo);
this.view.getGastosOperacionalesPartime().setValue(partime);
moveTo(this.view.getGastosGeneralesCuentaCorrienteFactura(), this.view.getGastosGeneralesCuentaCorrienteBoleta()); this.view.getGastosOperacionalesTotal().setValue(total);
moveTo(this.view.getGastosGeneralesCuentaCorrienteBoleta(), this.view.getGastosGeneralesCuentaCorrienteSinRespaldo()); }
moveTo(this.view.getGastosGeneralesCuentaCorrienteSinRespaldo(), this.view.getResumenPPM());
moveTo(this.view.getResumenPPM(), this.view.getResumenIVAFavor()); private void fillServicios() {
} int agua = this.estadoResultado.getAgua();
int luz = this.estadoResultado.getLuz();
int gas = this.estadoResultado.getGas();
int telefono = this.estadoResultado.getTelefono();
int otro = this.estadoResultado.getOtroServicio();
private void guardarListener() { int total = agua + luz + gas + telefono + otro;
EstadoResultadoDAO dao = DAOManager.getEstadoResultadoDAO();
dao.updateEstadoResultado(this.estadoResultado);
}
private void exportarListener() { this.view.getServiciosAgua().setValue(agua);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy"); this.view.getServiciosLuz().setValue(luz);
String formatedName = mes.format(formatter); this.view.getServiciosGas().setValue(gas);
String capitalized = StringUtils.capitalize(formatedName); this.view.getServiciosTelefono().setValue(telefono);
this.view.getServiciosOtro().setValue(otro);
this.view.getServiciosTotal().setValue(total);
}
Path saveFile = new XLSFileChooser(Configuration.get("base_save_directory") + "Estado Resultado " + capitalized).execute(); private void fillResumen() {
double ppm = this.estadoResultado.getPpm();
int aFavor = this.estadoResultado.getIvaFavor();
if(saveFile == null){ this.view.getResumenPPM().setValue(ppm);
return; this.view.getResumenIVAFavor().setValue(aFavor);
}
InformeEstadoResultado estadoResultado = new InformeEstadoResultado(this.mes, saveFile); this.updateResumen();
estadoResultado.generarInforme(); }
new InformeGeneratedConfirmation(saveFile).execute();
}
private void updateMonth() { private void updateGastosGenerales() {
this.mes = this.view.getMonth(); int oldCuentaCorrienteFactura = this.estadoResultado.getCuentaCorrienteFactura();
this.estadoResultado = DAOManager.getEstadoResultadoDAO().findByMonth(this.mes); int oldCuentaCorrienteBoleta = this.estadoResultado.getCuentaCorrienteBoleta();
if (estadoResultado == null) { int oldCuentaCorrienteSinRespaldo = this.estadoResultado.getCuentaCorrienteSinRespaldo();
this.estadoResultado = EstadoResultado.emptyEstadoResultado; int oldTotal = this.view.getGastosGeneralesTotal().getValue();
this.estadoResultado.setMes(this.mes);
DAOManager.getEstadoResultadoDAO().insertEstadoResultado(estadoResultado);
}
this.fillVentas(); int cuentaCorrienteFactura = this.view.getGastosGeneralesCuentaCorrienteFactura().getValue();
this.fillGastosGenerales(); int cuentaCorrienteBoleta = this.view.getGastosGeneralesCuentaCorrienteBoleta().getValue();
this.fillServicios(); int cuentaCorrienteSinRespaldo = this.view.getGastosGeneralesCuentaCorrienteSinRespaldo()
this.fillGastosOperacionales(); .getValue();
this.fillResumen();
}
private void fillVentas() { this.estadoResultado.setCuentaCorrienteFactura(cuentaCorrienteFactura);
int ventaBruta = DAOManager.getIngresoDAO().getTotalIngresoMes(this.mes); this.estadoResultado.setCuentaCorrienteBoleta(cuentaCorrienteBoleta);
int ventaExentas = DAOManager.getIngresoDAO().getTotalExentasMes(this.mes); this.estadoResultado.setCuentaCorrienteSinRespaldo(cuentaCorrienteSinRespaldo);
int ventaNeta = (int) Math.round((double) ventaBruta / 1.19d);
int ventaIVA = ventaBruta - ventaNeta;
int ventaNetaYExentas = ventaExentas + ventaNeta;
this.view.getVentaBrutaField().setValue(ventaBruta); int total = oldTotal
this.view.getVentaIVAField().setValue(ventaIVA); - (oldCuentaCorrienteFactura + oldCuentaCorrienteBoleta + oldCuentaCorrienteSinRespaldo)
this.view.getVentaNetaField().setValue(ventaNeta); + (cuentaCorrienteFactura + cuentaCorrienteBoleta + cuentaCorrienteSinRespaldo);
this.view.getVentaExentasField().setValue(ventaExentas);
this.view.getVentasNetaExentasField().setValue(ventaNetaYExentas);
}
private void fillGastosGenerales() { this.view.getGastosGeneralesTotal().setValue(total);
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);
int cuentaCorrienteFactura = this.estadoResultado.getCuentaCorrienteFactura(); this.updateResumen();
int cuentaCorrienteBoleta = this.estadoResultado.getCuentaCorrienteBoleta(); }
int cuentaCorrienteSinRespaldo = this.estadoResultado.getCuentaCorrienteSinRespaldo();
int efectivoFacturaGastosGenerales = DAOManager.getEgresoDAO().getTotalEgresoMesPorTipo(this.mes, facturaGastosGenerales);
int efectivoGastoGeneralConBoleta = DAOManager.getEgresoDAO().getTotalEgresoMesPorTipo(this.mes, gastoGeneralConBoleta);
int efectivoGastoGeneralSinRespaldo = DAOManager.getEgresoDAO().getTotalEgresoMesPorTipo(this.mes, gastoGeneralSinRespaldo);
int gastoTotal = efectivoFacturaGastosGenerales + efectivoGastoGeneralConBoleta + efectivoGastoGeneralSinRespaldo + cuentaCorrienteBoleta + cuentaCorrienteFactura + cuentaCorrienteSinRespaldo;
this.view.getGastosGeneralesEfectivoFacturaField().setValue(efectivoFacturaGastosGenerales); private void updateServicios() {
this.view.getGastosGeneralesEfectivoBoletaField().setValue(efectivoGastoGeneralConBoleta); int oldAgua = this.estadoResultado.getAgua();
this.view.getGastosGeneralesEfectivoSinRespaldo().setValue(efectivoGastoGeneralSinRespaldo); int oldLuz = this.estadoResultado.getLuz();
this.view.getGastosGeneralesCuentaCorrienteFactura().setValue(cuentaCorrienteFactura); int oldGas = this.estadoResultado.getGas();
this.view.getGastosGeneralesCuentaCorrienteBoleta().setValue(cuentaCorrienteBoleta); int oldTelefono = this.estadoResultado.getTelefono();
this.view.getGastosGeneralesCuentaCorrienteSinRespaldo().setValue(cuentaCorrienteSinRespaldo); int oldOtro = this.estadoResultado.getOtroServicio();
this.view.getGastosGeneralesTotal().setValue(gastoTotal); int oldTotal = this.view.getServiciosTotal().getValue();
}
private void fillGastosOperacionales() { int agua = this.view.getServiciosAgua().getValue();
TipoEgreso tipoPagoPartime = DAOManager.getTipoEgresoDAO().findByNombre("Pago Partime").get(0); int luz = this.view.getServiciosLuz().getValue();
int gas = this.view.getServiciosGas().getValue();
int telefono = this.view.getServiciosTelefono().getValue();
int otro = this.view.getServiciosOtro().getValue();
int costoVenta = this.estadoResultado.getCostoVenta(); this.estadoResultado.setAgua(agua);
int remuneraciones = this.estadoResultado.getRemuneraciones(); this.estadoResultado.setLuz(luz);
int finiquitos = this.estadoResultado.getFiniquitos(); this.estadoResultado.setGas(gas);
int aguinaldo = this.estadoResultado.getAguinaldo(); this.estadoResultado.setTelefono(telefono);
int bonosPersonal = this.estadoResultado.getBonosPersonal(); this.estadoResultado.setOtroServicio(otro);
int honorariosContador = this.estadoResultado.getHonorariosContador();
int arriendo = this.estadoResultado.getArriendo();
int partime = DAOManager.getEgresoDAO().getTotalEgresoMesPorTipo(this.mes, tipoPagoPartime);
int ventaBruta = DAOManager.getIngresoDAO().getTotalIngresoMes(this.mes);
int total = costoVenta + remuneraciones + finiquitos + aguinaldo + bonosPersonal int total = oldTotal
+ honorariosContador + arriendo + partime; - (oldAgua + oldLuz + oldGas + oldTelefono + oldOtro)
double porcentajeCostoVenta = (double) costoVenta / (double) ventaBruta * 100d; + (agua + luz + gas + telefono + otro);
this.view.getGastosOperacionalesCostoVenta().setValue(costoVenta); this.view.getServiciosTotal().setValue(total);
this.view.getGastosOperacionesPorcentajeCostoVenta().setValue(porcentajeCostoVenta);
this.view.getGastosOperacionalesRemuneraciones().setValue(remuneraciones);
this.view.getGastosOperacionalesFiniquitos().setValue(finiquitos);
this.view.getGastosOperacionalesAguinaldo().setValue(aguinaldo);
this.view.getGastosOperacionalesBonos().setValue(bonosPersonal);
this.view.getGastosOperacionalesHonorariosContador().setValue(honorariosContador);
this.view.getGastosOperacionalesArriendo().setValue(arriendo);
this.view.getGastosOperacionalesPartime().setValue(partime);
this.view.getGastosOperacionalesTotal().setValue(total); this.updateResumen();
} }
private void fillServicios() { private void updateGastosOperacionales() {
int agua = this.estadoResultado.getAgua(); int oldCostoVenta = this.estadoResultado.getCostoVenta();
int luz = this.estadoResultado.getLuz(); int oldRemuneraciones = this.estadoResultado.getRemuneraciones();
int gas = this.estadoResultado.getGas(); int oldFiniquitos = this.estadoResultado.getFiniquitos();
int telefono = this.estadoResultado.getTelefono(); int oldAguinaldo = this.estadoResultado.getAguinaldo();
int otro = this.estadoResultado.getOtroServicio(); int oldBonos = this.estadoResultado.getBonosPersonal();
int oldHonorarios = this.estadoResultado.getHonorariosContador();
int oldArriendo = this.estadoResultado.getArriendo();
int oldTotal = this.view.getGastosOperacionalesTotal().getValue();
int total = agua + luz + gas + telefono + otro; int costoVenta = this.view.getGastosOperacionalesCostoVenta().getValue();
int remuneraciones = this.view.getGastosOperacionalesRemuneraciones().getValue();
int finiquitos = this.view.getGastosOperacionalesFiniquitos().getValue();
int aguinaldo = this.view.getGastosOperacionalesAguinaldo().getValue();
int bonos = this.view.getGastosOperacionalesBonos().getValue();
int honorarios = this.view.getGastosOperacionalesHonorariosContador().getValue();
int arriendo = this.view.getGastosOperacionalesArriendo().getValue();
this.view.getServiciosAgua().setValue(agua); int ventaBruta = DAOManager.getIngresoDAO().getTotalIngresoMes(this.mes);
this.view.getServiciosLuz().setValue(luz);
this.view.getServiciosGas().setValue(gas);
this.view.getServiciosTelefono().setValue(telefono);
this.view.getServiciosOtro().setValue(otro);
this.view.getServiciosTotal().setValue(total);
}
private void fillResumen() { this.estadoResultado.setCostoVenta(costoVenta);
double ppm = this.estadoResultado.getPpm(); this.estadoResultado.setRemuneraciones(remuneraciones);
int aFavor = this.estadoResultado.getIvaFavor(); this.estadoResultado.setFiniquitos(finiquitos);
this.estadoResultado.setAguinaldo(aguinaldo);
this.estadoResultado.setBonosPersonal(bonos);
this.estadoResultado.setHonorariosContador(honorarios);
this.estadoResultado.setArriendo(arriendo);
this.view.getResumenPPM().setValue(ppm); int total = oldTotal
this.view.getResumenIVAFavor().setValue(aFavor); - (oldCostoVenta + oldRemuneraciones + oldFiniquitos + oldAguinaldo + oldBonos
+ oldHonorarios + oldArriendo)
+ (costoVenta + remuneraciones + finiquitos + aguinaldo + bonos + honorarios + arriendo);
double porcentajeCostoVenta = (double) costoVenta / (double) ventaBruta * 100d;
this.updateResumen(); this.view.getGastosOperacionalesTotal().setValue(total);
} this.view.getGastosOperacionesPorcentajeCostoVenta().setValue(porcentajeCostoVenta);
private void updateGastosGenerales() { this.updateResumen();
int oldCuentaCorrienteFactura = this.estadoResultado.getCuentaCorrienteFactura(); }
int oldCuentaCorrienteBoleta = this.estadoResultado.getCuentaCorrienteBoleta();
int oldCuentaCorrienteSinRespaldo = this.estadoResultado.getCuentaCorrienteSinRespaldo();
int oldTotal = this.view.getGastosGeneralesTotal().getValue();
int cuentaCorrienteFactura = this.view.getGastosGeneralesCuentaCorrienteFactura().getValue(); private void updateResumen() {
int cuentaCorrienteBoleta = this.view.getGastosGeneralesCuentaCorrienteBoleta().getValue(); int bruto = this.view.getVentaBrutaField().getValue();
int cuentaCorrienteSinRespaldo = this.view.getGastosGeneralesCuentaCorrienteSinRespaldo().getValue(); int totalGastosOperacionales = this.view.getGastosOperacionalesTotal().getValue();
int totalGastosGenerales = this.view.getGastosGeneralesTotal().getValue();
int totalServicios = this.view.getServiciosTotal().getValue();
int netoExentas = this.view.getVentasNetaExentasField().getValue();
int iva = this.view.getVentaIVAField().getValue();
double ppm = this.view.getResumenPPM().getValue();
int ivaFavor = this.view.getResumenIVAFavor().getValue();
this.estadoResultado.setCuentaCorrienteFactura(cuentaCorrienteFactura); int utilidad = bruto - totalGastosGenerales - totalGastosOperacionales - totalServicios;
this.estadoResultado.setCuentaCorrienteBoleta(cuentaCorrienteBoleta); int ppmMes = (int) Math.round(ppm * (double) netoExentas / 100d);
this.estadoResultado.setCuentaCorrienteSinRespaldo(cuentaCorrienteSinRespaldo); int IVAPPM = iva + ppmMes;
int aPagar = IVAPPM - ivaFavor;
int resultado = utilidad - aPagar;
int total = oldTotal this.view.getResumenUtilidad().setValue(utilidad);
- (oldCuentaCorrienteFactura + oldCuentaCorrienteBoleta + oldCuentaCorrienteSinRespaldo) this.view.getResumenPPMMes().setValue(ppmMes);
+ (cuentaCorrienteFactura + cuentaCorrienteBoleta + cuentaCorrienteSinRespaldo); this.view.getResumenIVAMes().setValue(iva);
this.view.getResumenIVAPPM().setValue(IVAPPM);
this.view.getResumenAPagar().setValue(aPagar);
this.view.getResumenResultado().setValue(resultado);
this.view.getGastosGeneralesTotal().setValue(total); this.estadoResultado.setPpm(ppm);
this.estadoResultado.setIvaFavor(ivaFavor);
this.updateResumen(); }
}
private void updateServicios() {
int oldAgua = this.estadoResultado.getAgua();
int oldLuz = this.estadoResultado.getLuz();
int oldGas = this.estadoResultado.getGas();
int oldTelefono = this.estadoResultado.getTelefono();
int oldOtro = this.estadoResultado.getOtroServicio();
int oldTotal = this.view.getServiciosTotal().getValue();
int agua = this.view.getServiciosAgua().getValue();
int luz = this.view.getServiciosLuz().getValue();
int gas = this.view.getServiciosGas().getValue();
int telefono = this.view.getServiciosTelefono().getValue();
int otro = this.view.getServiciosOtro().getValue();
this.estadoResultado.setAgua(agua);
this.estadoResultado.setLuz(luz);
this.estadoResultado.setGas(gas);
this.estadoResultado.setTelefono(telefono);
this.estadoResultado.setOtroServicio(otro);
int total = oldTotal
- (oldAgua + oldLuz + oldGas + oldTelefono + oldOtro)
+ (agua + luz + gas + telefono + otro);
this.view.getServiciosTotal().setValue(total);
this.updateResumen();
}
private void updateGastosOperacionales() {
int oldCostoVenta = this.estadoResultado.getCostoVenta();
int oldRemuneraciones = this.estadoResultado.getRemuneraciones();
int oldFiniquitos = this.estadoResultado.getFiniquitos();
int oldAguinaldo = this.estadoResultado.getAguinaldo();
int oldBonos = this.estadoResultado.getBonosPersonal();
int oldHonorarios = this.estadoResultado.getHonorariosContador();
int oldArriendo = this.estadoResultado.getArriendo();
int oldTotal = this.view.getGastosOperacionalesTotal().getValue();
int costoVenta = this.view.getGastosOperacionalesCostoVenta().getValue();
int remuneraciones = this.view.getGastosOperacionalesRemuneraciones().getValue();
int finiquitos = this.view.getGastosOperacionalesFiniquitos().getValue();
int aguinaldo = this.view.getGastosOperacionalesAguinaldo().getValue();
int bonos = this.view.getGastosOperacionalesBonos().getValue();
int honorarios = this.view.getGastosOperacionalesHonorariosContador().getValue();
int arriendo = this.view.getGastosOperacionalesArriendo().getValue();
int ventaBruta = DAOManager.getIngresoDAO().getTotalIngresoMes(this.mes);
this.estadoResultado.setCostoVenta(costoVenta);
this.estadoResultado.setRemuneraciones(remuneraciones);
this.estadoResultado.setFiniquitos(finiquitos);
this.estadoResultado.setAguinaldo(aguinaldo);
this.estadoResultado.setBonosPersonal(bonos);
this.estadoResultado.setHonorariosContador(honorarios);
this.estadoResultado.setArriendo(arriendo);
int total = oldTotal
- (oldCostoVenta + oldRemuneraciones + oldFiniquitos + oldAguinaldo + oldBonos + oldHonorarios + oldArriendo)
+ (costoVenta + remuneraciones + finiquitos + aguinaldo + bonos + honorarios + arriendo);
double porcentajeCostoVenta = (double) costoVenta / (double) ventaBruta * 100d;
this.view.getGastosOperacionalesTotal().setValue(total);
this.view.getGastosOperacionesPorcentajeCostoVenta().setValue(porcentajeCostoVenta);
this.updateResumen();
}
private void updateResumen() {
int bruto = this.view.getVentaBrutaField().getValue();
int totalGastosOperacionales = this.view.getGastosOperacionalesTotal().getValue();
int totalGastosGenerales = this.view.getGastosGeneralesTotal().getValue();
int totalServicios = this.view.getServiciosTotal().getValue();
int netoExentas = this.view.getVentasNetaExentasField().getValue();
int iva = this.view.getVentaIVAField().getValue();
double ppm = this.view.getResumenPPM().getValue();
int ivaFavor = this.view.getResumenIVAFavor().getValue();
int utilidad = bruto - totalGastosGenerales - totalGastosOperacionales - totalServicios;
int ppmMes = (int) Math.round(ppm * (double) netoExentas / 100d);
int IVAPPM = iva + ppmMes;
int aPagar = IVAPPM - ivaFavor;
int resultado = utilidad - aPagar;
this.view.getResumenUtilidad().setValue(utilidad);
this.view.getResumenPPMMes().setValue(ppmMes);
this.view.getResumenIVAMes().setValue(iva);
this.view.getResumenIVAPPM().setValue(IVAPPM);
this.view.getResumenAPagar().setValue(aPagar);
this.view.getResumenResultado().setValue(resultado);
this.estadoResultado.setPpm(ppm);
this.estadoResultado.setIvaFavor(ivaFavor);
}
} }

View File

@@ -34,72 +34,77 @@ 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 danielcortes.xyz.views.dialogs.XLSFileChooser;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.YearMonth; import java.time.YearMonth;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
public class InformesSideBarController { public class InformesSideBarController {
private InformesSideBar view;
public InformesSideBarController(InformesSideBar view) { private InformesSideBar view;
this.view = view;
this.setupViewEvents(); public InformesSideBarController(InformesSideBar view) {
this.view = view;
this.setupViewEvents();
}
public InformesSideBar getView() {
return view;
}
private void setupViewEvents() {
this.view.getInformeLibroDeVentasButton()
.addActionListener(e -> generarInformeLibroDeVentasListener());
this.view.getGenerarEgresosFacturasMateriaPrimaButton()
.addActionListener(e -> generarInformeEgresosListener());
}
private void generarInformeLibroDeVentasListener() {
YearMonth month = new MonthSelectDialog().execute();
if (month == null) {
return;
} }
public InformesSideBar getView() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy");
return view; String formatedName = month.format(formatter);
String capitalized = StringUtils.capitalize(formatedName);
Path saveFile = new XLSFileChooser(
Configuration.get("base_save_directory") + "Libro " + capitalized).execute();
if (saveFile == null) {
return;
} }
private void setupViewEvents() { InformeLibroDeVentas informe = new InformeLibroDeVentas(month, saveFile);
this.view.getInformeLibroDeVentasButton().addActionListener(e -> generarInformeLibroDeVentasListener()); informe.generarInforme();
this.view.getGenerarEgresosFacturasMateriaPrimaButton().addActionListener(e -> generarInformeEgresosListener());
new InformeGeneratedConfirmation(saveFile).execute();
}
private void generarInformeEgresosListener() {
TipoEgreso tipoEgreso = new TipoEgresoSelectDialog().execute();
if (tipoEgreso == null) {
return;
} }
private void generarInformeLibroDeVentasListener() { YearMonth month = new MonthSelectDialog().execute();
YearMonth month = new MonthSelectDialog().execute(); if (month == null) {
if (month == null) { return;
return;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy");
String formatedName = month.format(formatter);
String capitalized = StringUtils.capitalize(formatedName);
Path saveFile = new XLSFileChooser(Configuration.get("base_save_directory") + "Libro " + capitalized).execute();
if (saveFile == null) {
return;
}
InformeLibroDeVentas informe = new InformeLibroDeVentas(month, saveFile);
informe.generarInforme();
new InformeGeneratedConfirmation(saveFile).execute();
} }
private void generarInformeEgresosListener() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM YYYY");
TipoEgreso tipoEgreso = new TipoEgresoSelectDialog().execute(); String formatedMonth = month.format(formatter);
if (tipoEgreso == null) {
return;
}
YearMonth month = new MonthSelectDialog().execute(); Path saveFile = new XLSFileChooser(
if (month == null) { "Informe Egresos - " + tipoEgreso.getNombre() + " - " + StringUtils
return; .capitalize(formatedMonth)).execute();
} if (saveFile == null) {
return;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM YYYY");
String formatedMonth = month.format(formatter);
Path saveFile = new XLSFileChooser("Informe Egresos - " + tipoEgreso.getNombre() + " - " + StringUtils.capitalize(formatedMonth)).execute();
if (saveFile == null) {
return;
}
InformeEgresos informe = new InformeEgresos(tipoEgreso.getId(), month, saveFile);
Path generatedFile = informe.generarInforme();
new InformeGeneratedConfirmation(saveFile).execute();
} }
InformeEgresos informe = new InformeEgresos(tipoEgreso.getId(), month, saveFile);
Path generatedFile = informe.generarInforme();
new InformeGeneratedConfirmation(saveFile).execute();
}
} }

View File

@@ -31,385 +31,392 @@ import danielcortes.xyz.models.tipo_ingreso.TipoIngreso;
import danielcortes.xyz.models.tipo_ingreso.TipoIngresoToStringWrapper; import danielcortes.xyz.models.tipo_ingreso.TipoIngresoToStringWrapper;
import danielcortes.xyz.views.IngresosView; import danielcortes.xyz.views.IngresosView;
import danielcortes.xyz.views.components.table_model.IngresosTableModel; import danielcortes.xyz.views.components.table_model.IngresosTableModel;
import javax.swing.*;
import java.awt.event.ActionEvent; import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter; import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent; import java.awt.event.MouseEvent;
import javax.swing.AbstractAction;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.KeyStroke;
/** /**
* Controlador el cual esta orientado a manejar la vista de IngresosView * Controlador el cual esta orientado a manejar la vista de IngresosView Maneja su contenido y las
* Maneja su contenido y las acciones que esta realiza * acciones que esta realiza
*/ */
public class IngresosController extends BaseController{ public class IngresosController extends BaseController {
private IngresosView view;
private Caja caja;
private int editingId; private IngresosView view;
private Ingreso editingIngreso; private Caja caja;
private boolean editing;
/** private int editingId;
* Crea el controlado de egresos, el cual esta acoplado con la vista de ingresos, controlando el estado y contenido de esta. private Ingreso editingIngreso;
* Al iniciarse ejecuta. private boolean editing;
* - Metodo que llena el combobox de tipos de ingreso
* - Metodo que genera los eventos para la vista /**
* - Metodo que actualiza el estado de los botones * Crea el controlado de egresos, el cual esta acoplado con la vista de ingresos, controlando el
*/ * estado y contenido de esta. Al iniciarse ejecuta. - Metodo que llena el combobox de tipos de
public IngresosController(IngresosView view) { * ingreso - Metodo que genera los eventos para la vista - Metodo que actualiza el estado de los
this.view = view; * botones
this.fillTipoIngresoCombo(); */
this.setupViewEvents(); public IngresosController(IngresosView view) {
this.updateButtonsEnabled(); this.view = view;
this.fillTipoIngresoCombo();
this.setupViewEvents();
this.updateButtonsEnabled();
}
/**
* Guarda la caja ingresada y actualiza el contenido de la tabla de ingresos y el campo de total
* de ingresos
*/
public void updateCaja(Caja caja) {
this.caja = caja;
this.fillIngresosTable();
this.updateTotalIngresos();
}
/**
* LLena el combobox de tipos de ingresos
*/
private void fillTipoIngresoCombo() {
JComboBox<TipoIngresoToStringWrapper> tipoCombo = this.view.getTipoCombo();
for (TipoIngreso tipo : DAOManager.getTipoIngresoDAO().findAll()) {
tipoCombo.addItem(new TipoIngresoToStringWrapper(tipo));
} }
}
/**
/** * Llena la tabla de ingresos con los ingresos pertenecientes a la caja guarda
* Guarda la caja ingresada y actualiza el contenido de la tabla de ingresos y el campo de total de ingresos */
*/ private void fillIngresosTable() {
public void updateCaja(Caja caja) { IngresosTableModel ingresosTableModel = this.view.getIngresosTableModel();
this.caja = caja; ingresosTableModel.removeRows();
this.fillIngresosTable(); for (Ingreso ingreso : DAOManager.getIngresoDAO().findByCaja(this.caja)) {
this.updateTotalIngresos(); ingresosTableModel.addRow(ingreso);
} }
}
/** /**
* LLena el combobox de tipos de ingresos * Genera los eventos para los distintos componentes de la vista - Cuando se presiona el boton de
*/ * guardar o se apreta enter en los fields de valor, nro inicial, nro final y tipo se llama a
private void fillTipoIngresoCombo() { * guardarActionListener - Cuando se presiona el boton de eliminar se llama al
JComboBox<TipoIngresoToStringWrapper> tipoCombo = this.view.getTipoCombo(); * eliminarActionListener - Cuando se selecciona una fila en la tabla se llama a
for (TipoIngreso tipo : DAOManager.getTipoIngresoDAO().findAll()) { * updateButtonsEnabled - Cuando se presiona el boton de editar o se hace doble click sobre una
tipoCombo.addItem(new TipoIngresoToStringWrapper(tipo)); * fila de la tabla se llama a editarActionListener
*/
private void setupViewEvents() {
moveTo(this.view.getValorField(), this.view.getNroZInicialField());
moveTo(this.view.getNroZInicialField(), this.view.getNroZFinalField());
moveTo(this.view.getNroZFinalField(), this.view.getNroInicialField());
moveTo(this.view.getNroInicialField(), this.view.getNroFinalField());
moveTo(this.view.getNroFinalField(), this.view.getTipoCombo());
doAction(this.view.getTipoCombo(), "save", KeyStroke.getKeyStroke("ENTER"),
e -> this.guardarActionListener());
this.view.getIngresosTable().getSelectionModel()
.addListSelectionListener(e -> updateButtonsEnabled());
this.view.getGuardarButton().addActionListener(e -> guardarActionListener());
this.view.getEliminarButton().addActionListener(e -> eliminarActionListener());
this.view.getEditarButton().addActionListener(e -> editarActionListener());
this.view.getIngresosTable().addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent mouseEvent) {
JTable table = (JTable) mouseEvent.getSource();
if (mouseEvent.getClickCount() == 2 && table.getSelectedRow() != -1) {
IngresosController.this.editarActionListener();
} }
}
});
}
/**
* Realiza las preparaciones previas a guardar un ingreso Primero llama a normalizar los inputs y
* a esconder los mensajes de error Luego dependiendo si se tiene la flag editing en true o false
* se llama a editar ingreso o a guardarlo Tras terminar esto se llama a resetear el focus.
*/
private void guardarActionListener() {
this.normalizeInputs();
this.hideErrorMessages();
int valor = this.view.getValorField().getValue();
String nroZInicial = this.view.getNroZInicialField().getText();
String nroZFinal = this.view.getNroZFinalField().getText();
String nroInicial = this.view.getNroInicialField().getText();
String nroFinal = this.view.getNroFinalField().getText();
TipoIngreso tipoIngreso = (TipoIngreso) this.view.getTipoCombo().getSelectedItem();
if (editing) {
this.editarIngreso(valor, nroZInicial, nroZFinal, nroInicial, nroFinal, tipoIngreso,
this.caja);
} else {
this.guardarIngreso(valor, nroZInicial, nroZFinal, nroInicial, nroFinal, tipoIngreso,
this.caja);
}
this.resetFocus();
}
/**
* Realiza las acciones necesarias para eliminar un ingreso Solo lo va a realizar si es que esta
* seleccionada una fila de la tabla, se eliminara el ingreso seleccionado Una vez eliminado se
* llama a actualizar el total de ingresos y el estado de los botones
*/
private void eliminarActionListener() {
int selectedId = this.view.getIngresosTable().getSelectedRow();
if (selectedId >= 0) {
Ingreso ingreso = this.view.getIngresosTableModel().getIngreso(selectedId);
this.view.getIngresosTableModel().removeRow(selectedId);
DAOManager.getIngresoDAO().deleteIngreso(ingreso);
this.updateTotalIngresos();
this.updateButtonsEnabled();
this.resetFocus();
}
}
/**
* Realiza las preparaciones previas a editar un ingreso Primero llama a esconder los mensajes de
* error. Guarda globlarmente el ingreso a ser editar, el id de este y una flag que indica que se
* esta en modo de editar. Finalmente llena los campos de inputs con los datos del ingreso a
* editar.
*/
private void editarActionListener() {
this.hideErrorMessages();
int selectedID = this.view.getIngresosTable().getSelectedRow();
int selectedModelID = this.view.getIngresosTable().getRowSorter()
.convertRowIndexToModel(selectedID);
if (selectedModelID >= 0) {
Ingreso ingreso = this.view.getIngresosTableModel().getIngreso(selectedModelID);
this.editingId = selectedModelID;
this.editingIngreso = ingreso;
this.editing = true;
this.view.getTipoCombo().setSelectedItem(ingreso.getTipoIngreso());
this.view.getValorField().setValue(ingreso.getValor());
this.view.getNroZInicialField().setText(String.valueOf(ingreso.getNroZInicial()));
this.view.getNroZFinalField().setText(String.valueOf(ingreso.getNroZFinal()));
this.view.getNroInicialField().setText(String.valueOf(ingreso.getNroInicial()));
this.view.getNroFinalField().setText(String.valueOf(ingreso.getNroFinal()));
}
}
/**
* Obtiene el total de ingresos de la caja y lo coloca en el el field totalingresos
*/
private void updateTotalIngresos() {
int total = DAOManager.getIngresoDAO().getTotalIngreso(this.caja);
this.view.getTotalIngresoField().setValue(total);
}
/**
* Actualiza si los botones estan habilitados Esto depende de si se encuentra al menos una fila en
* la tabla seleccionada Si es asi, son habilidatos, si no, de deshabilitan
*/
private void updateButtonsEnabled() {
if (this.view.getIngresosTable().getSelectedRow() >= 0) {
this.view.getEliminarButton().setEnabled(true);
this.view.getEditarButton().setEnabled(true);
} else {
this.view.getEliminarButton().setEnabled(false);
this.view.getEditarButton().setEnabled(false);
}
}
/**
* Guarda un ingreso tras llamar a validar el input Luego de guardar agrega a la tabla el ingreso,
* llama a limpiar los campos de input y a actualizar el total de ingresos
*/
private void guardarIngreso(int valor, String nroZInicial, String nroZFinal, String nroInicial,
String nroFinal, TipoIngreso tipoIngreso, Caja caja) {
if (this.validateInput(nroZInicial, nroZFinal, nroInicial, nroFinal, tipoIngreso, caja)) {
Ingreso ingreso = new Ingreso();
ingreso.setTipoIngreso(tipoIngreso);
ingreso.setCaja(caja);
ingreso.setValor(valor);
ingreso.setNroZInicial(nroZInicial);
ingreso.setNroZFinal(nroZFinal);
ingreso.setNroInicial(nroInicial);
ingreso.setNroFinal(nroFinal);
DAOManager.getIngresoDAO().insertIngreso(ingreso);
this.view.getIngresosTableModel().addRow(ingreso);
this.clearInputs();
this.updateTotalIngresos();
}
}
/**
* Edita el ingreso tras llamar a validar el input Tras esto actualiza el ingreso en la tabla,
* llama a actualizar el total de ingresos, a limpiar los campos de input y a desactivar la flag
* de editing.
*/
private void editarIngreso(int valor, String nroZInicial, String nroZFinal, String nroInicial,
String nroFinal, TipoIngreso tipoIngreso, Caja caja) {
if (this.validateInput(nroZInicial, nroZFinal, nroInicial, nroFinal, tipoIngreso, caja)) {
this.editingIngreso.setTipoIngreso(tipoIngreso);
this.editingIngreso.setValor(valor);
this.editingIngreso.setNroZInicial(nroZInicial);
this.editingIngreso.setNroZFinal(nroZFinal);
this.editingIngreso.setNroInicial(nroInicial);
this.editingIngreso.setNroFinal(nroFinal);
DAOManager.getIngresoDAO().updateIngreso(this.editingIngreso);
this.view.getIngresosTableModel().setIngreso(this.editingId, this.editingIngreso);
this.updateTotalIngresos();
this.clearInputs();
this.editing = false;
}
}
/**
* Llama a los metodos necesarios para validar el input
*
* @return true cuando todas las validaciones retoran true, si no, false
*/
private boolean validateInput(String nroZInicial, String nroZFinal, String nroInicial,
String nroFinal, TipoIngreso tipoIngreso, Caja caja) {
this.hideErrorMessages();
boolean nroInicialValidation = this.validateNroInicial(nroInicial);
boolean nroFinalValidation = this.validateNroFinal(nroFinal);
boolean tipoIngresoValidation = this.validateTipoIngreso(tipoIngreso);
boolean cajaValidation = this.validateCaja(caja);
return nroInicialValidation && nroFinalValidation && tipoIngresoValidation && cajaValidation;
}
/**
* Valida la variable caja este caso - Es null
*
* @return Si este caso es true se retornara false, si no, se retorna true
*/
private boolean validateCaja(Caja caja) {
return caja != null;
}
/**
* Valida la variable nroInicial contra los casos - Es null - Esta vacio Cuando el primer caso sea
* true, colocara un mensaje de error correspondiente en el jlabel correspondiente
*
* @return Si cualquiera de estos casos son true se retornara false, si no, se retorna true
*/
private boolean validateNroInicial(String nroInicial) {
if (nroInicial == null) {
this.view.getErrorNroInicial().setText("Hubo un problema con los datos");
this.view.getErrorNroInicial().setVisible(true);
return false;
} }
/** if (nroInicial.isEmpty()) {
* Llena la tabla de ingresos con los ingresos pertenecientes a la caja guarda this.view.getErrorNroInicial().setText("El campo esta vacio");
*/ this.view.getErrorNroInicial().setVisible(true);
private void fillIngresosTable() { return false;
IngresosTableModel ingresosTableModel = this.view.getIngresosTableModel(); }
ingresosTableModel.removeRows(); return true;
for (Ingreso ingreso : DAOManager.getIngresoDAO().findByCaja(this.caja)) { }
ingresosTableModel.addRow(ingreso);
} /**
* Valida la variable nroFinal contra los casos - Es null - Esta vacio Cuando el primer caso sea
* true, colocara un mensaje de error correspondiente en el jlabel correspondiente
*
* @return Si cualquiera de estos casos son true se retornara false, si no, se retorna true
*/
private boolean validateNroFinal(String nroFinal) {
if (nroFinal == null) {
this.view.getErrorNroFinal().setText("Hubo un problema con los datos");
this.view.getErrorNroFinal().setVisible(true);
return false;
} }
/** if (nroFinal.isEmpty()) {
* Genera los eventos para los distintos componentes de la vista this.view.getErrorNroFinal().setText("El campo esta vacio");
* - Cuando se presiona el boton de guardar o se apreta enter en los fields de valor, nro inicial, this.view.getErrorNroFinal().setVisible(true);
* nro final y tipo se llama a guardarActionListener return false;
* - Cuando se presiona el boton de eliminar se llama al eliminarActionListener }
* - Cuando se selecciona una fila en la tabla se llama a updateButtonsEnabled return true;
* - Cuando se presiona el boton de editar o se hace doble click sobre una fila de la tabla se llama a editarActionListener }
*/
private void setupViewEvents() {
moveTo(this.view.getValorField(), this.view.getNroZInicialField());
moveTo(this.view.getNroZInicialField(), this.view.getNroZFinalField());
moveTo(this.view.getNroZFinalField(), this.view.getNroInicialField());
moveTo(this.view.getNroInicialField(), this.view.getNroFinalField());
moveTo(this.view.getNroFinalField(), this.view.getTipoCombo());
doAction(this.view.getTipoCombo(), "save", KeyStroke.getKeyStroke("ENTER"), e ->this.guardarActionListener());
this.view.getIngresosTable().getSelectionModel().addListSelectionListener(e -> updateButtonsEnabled()); /**
this.view.getGuardarButton().addActionListener(e -> guardarActionListener()); * Valida la variable caja este caso - Es null Cuando sea true, colocara un mensaje de error en el
this.view.getEliminarButton().addActionListener(e -> eliminarActionListener()); * jlabel correspondiente
this.view.getEditarButton().addActionListener(e -> editarActionListener()); *
* @return Si este caso es true se retornara false, si no, se retorna true
*/
private boolean validateTipoIngreso(TipoIngreso tipoIngreso) {
if (tipoIngreso == null) {
this.view.getErrorTipoIngreso().setText("Hubo un problema con los datos");
this.view.getErrorTipoIngreso().setVisible(true);
return false;
}
return true;
}
this.view.getIngresosTable().addMouseListener(new MouseAdapter() { /**
public void mouseClicked(MouseEvent mouseEvent) { * Esconde los mensajes de error en la ventana de ingresos
JTable table = (JTable) mouseEvent.getSource(); */
if (mouseEvent.getClickCount() == 2 && table.getSelectedRow() != -1) { private void hideErrorMessages() {
IngresosController.this.editarActionListener(); this.view.getErrorTipoIngreso().setVisible(false);
} this.view.getErrorNroInicial().setVisible(false);
} this.view.getErrorNroFinal().setVisible(false);
}); }
/**
* Vacia los jtextfields y selecciona la primera opcion del jcombobox
*/
private void clearInputs() {
this.view.getTipoCombo().setSelectedIndex(0);
this.view.getValorField().setValue(0);
this.view.getValorField().setText("");
this.view.getNroZInicialField().setText("");
this.view.getNroZFinalField().setText("");
this.view.getNroInicialField().setText("");
this.view.getNroFinalField().setText("");
}
/**
* Ejecuta un trim sobre todos los jtextfield
*/
private void normalizeInputs() {
this.view.getNroZInicialField().setText(this.view.getNroZInicialField().getText().trim());
this.view.getNroZFinalField().setText(this.view.getNroZFinalField().getText().trim());
this.view.getNroInicialField().setText(this.view.getNroInicialField().getText().trim());
this.view.getNroFinalField().setText(this.view.getNroFinalField().getText().trim());
}
/**
* Le pide focus al tipo combo
*/
private void resetFocus() {
this.view.getValorField().requestFocus();
}
private class NextAction extends AbstractAction {
JComponent next;
NextAction(JComponent next) {
this.next = next;
} }
/** @Override
* Realiza las preparaciones previas a guardar un ingreso public void actionPerformed(ActionEvent e) {
* Primero llama a normalizar los inputs y a esconder los mensajes de error this.next.requestFocus();
* Luego dependiendo si se tiene la flag editing en true o false se llama a editar ingreso o a guardarlo }
* Tras terminar esto se llama a resetear el focus. }
*/
private void guardarActionListener() {
this.normalizeInputs();
this.hideErrorMessages();
int valor = this.view.getValorField().getValue(); private class GuardarAction extends AbstractAction {
String nroZInicial = this.view.getNroZInicialField().getText();
String nroZFinal = this.view.getNroZFinalField().getText();
String nroInicial = this.view.getNroInicialField().getText();
String nroFinal = this.view.getNroFinalField().getText();
TipoIngreso tipoIngreso = (TipoIngreso) this.view.getTipoCombo().getSelectedItem();
if (editing) { IngresosController controller;
this.editarIngreso(valor, nroZInicial, nroZFinal, nroInicial, nroFinal, tipoIngreso, this.caja);
} else { GuardarAction(IngresosController controller) {
this.guardarIngreso(valor, nroZInicial, nroZFinal, nroInicial, nroFinal, tipoIngreso, this.caja); this.controller = controller;
}
this.resetFocus();
} }
/** @Override
* Realiza las acciones necesarias para eliminar un ingreso public void actionPerformed(ActionEvent e) {
* Solo lo va a realizar si es que esta seleccionada una fila de la tabla, se eliminara el ingreso seleccionado this.controller.guardarActionListener();
* Una vez eliminado se llama a actualizar el total de ingresos y el estado de los botones
*/
private void eliminarActionListener() {
int selectedId = this.view.getIngresosTable().getSelectedRow();
if (selectedId >= 0) {
Ingreso ingreso = this.view.getIngresosTableModel().getIngreso(selectedId);
this.view.getIngresosTableModel().removeRow(selectedId);
DAOManager.getIngresoDAO().deleteIngreso(ingreso);
this.updateTotalIngresos();
this.updateButtonsEnabled();
this.resetFocus();
}
}
/**
* Realiza las preparaciones previas a editar un ingreso
* Primero llama a esconder los mensajes de error.
* Guarda globlarmente el ingreso a ser editar, el id de este y una flag que indica que se esta en modo de editar.
* Finalmente llena los campos de inputs con los datos del ingreso a editar.
*/
private void editarActionListener() {
this.hideErrorMessages();
int selectedID = this.view.getIngresosTable().getSelectedRow();
int selectedModelID = this.view.getIngresosTable().getRowSorter().convertRowIndexToModel(selectedID);
if (selectedModelID >= 0) {
Ingreso ingreso = this.view.getIngresosTableModel().getIngreso(selectedModelID);
this.editingId = selectedModelID;
this.editingIngreso = ingreso;
this.editing = true;
this.view.getTipoCombo().setSelectedItem(ingreso.getTipoIngreso());
this.view.getValorField().setValue(ingreso.getValor());
this.view.getNroZInicialField().setText(String.valueOf(ingreso.getNroZInicial()));
this.view.getNroZFinalField().setText(String.valueOf(ingreso.getNroZFinal()));
this.view.getNroInicialField().setText(String.valueOf(ingreso.getNroInicial()));
this.view.getNroFinalField().setText(String.valueOf(ingreso.getNroFinal()));
}
}
/**
* Obtiene el total de ingresos de la caja y lo coloca en el el field totalingresos
*/
private void updateTotalIngresos() {
int total = DAOManager.getIngresoDAO().getTotalIngreso(this.caja);
this.view.getTotalIngresoField().setValue(total);
}
/**
* Actualiza si los botones estan habilitados
* Esto depende de si se encuentra al menos una fila en la tabla seleccionada
* Si es asi, son habilidatos, si no, de deshabilitan
*/
private void updateButtonsEnabled() {
if (this.view.getIngresosTable().getSelectedRow() >= 0) {
this.view.getEliminarButton().setEnabled(true);
this.view.getEditarButton().setEnabled(true);
} else {
this.view.getEliminarButton().setEnabled(false);
this.view.getEditarButton().setEnabled(false);
}
}
/**
* Guarda un ingreso tras llamar a validar el input
* Luego de guardar agrega a la tabla el ingreso, llama a limpiar los campos de input y a actualizar el total de ingresos
*/
private void guardarIngreso(int valor, String nroZInicial, String nroZFinal, String nroInicial, String nroFinal, TipoIngreso tipoIngreso, Caja caja) {
if (this.validateInput(nroZInicial, nroZFinal, nroInicial, nroFinal, tipoIngreso, caja)) {
Ingreso ingreso = new Ingreso();
ingreso.setTipoIngreso(tipoIngreso);
ingreso.setCaja(caja);
ingreso.setValor(valor);
ingreso.setNroZInicial(nroZInicial);
ingreso.setNroZFinal(nroZFinal);
ingreso.setNroInicial(nroInicial);
ingreso.setNroFinal(nroFinal);
DAOManager.getIngresoDAO().insertIngreso(ingreso);
this.view.getIngresosTableModel().addRow(ingreso);
this.clearInputs();
this.updateTotalIngresos();
}
}
/**
* Edita el ingreso tras llamar a validar el input
* Tras esto actualiza el ingreso en la tabla, llama a actualizar el total de ingresos, a limpiar los campos de input y a desactivar la flag de editing.
*/
private void editarIngreso(int valor, String nroZInicial, String nroZFinal, String nroInicial, String nroFinal, TipoIngreso tipoIngreso, Caja caja) {
if (this.validateInput(nroZInicial, nroZFinal, nroInicial, nroFinal, tipoIngreso, caja)) {
this.editingIngreso.setTipoIngreso(tipoIngreso);
this.editingIngreso.setValor(valor);
this.editingIngreso.setNroZInicial(nroZInicial);
this.editingIngreso.setNroZFinal(nroZFinal);
this.editingIngreso.setNroInicial(nroInicial);
this.editingIngreso.setNroFinal(nroFinal);
DAOManager.getIngresoDAO().updateIngreso(this.editingIngreso);
this.view.getIngresosTableModel().setIngreso(this.editingId, this.editingIngreso);
this.updateTotalIngresos();
this.clearInputs();
this.editing = false;
}
}
/**
* Llama a los metodos necesarios para validar el input
*
* @return true cuando todas las validaciones retoran true, si no, false
*/
private boolean validateInput(String nroZInicial, String nroZFinal, String nroInicial, String nroFinal, TipoIngreso tipoIngreso, Caja caja) {
this.hideErrorMessages();
boolean nroInicialValidation = this.validateNroInicial(nroInicial);
boolean nroFinalValidation = this.validateNroFinal(nroFinal);
boolean tipoIngresoValidation = this.validateTipoIngreso(tipoIngreso);
boolean cajaValidation = this.validateCaja(caja);
return nroInicialValidation && nroFinalValidation && tipoIngresoValidation && cajaValidation;
}
/**
* Valida la variable caja este caso
* - Es null
*
* @return Si este caso es true se retornara false, si no, se retorna true
*/
private boolean validateCaja(Caja caja) {
return caja != null;
}
/**
* Valida la variable nroInicial contra los casos
* - Es null
* - Esta vacio
* Cuando el primer caso sea true, colocara un mensaje de error correspondiente en el jlabel correspondiente
*
* @return Si cualquiera de estos casos son true se retornara false, si no, se retorna true
*/
private boolean validateNroInicial(String nroInicial) {
if (nroInicial == null) {
this.view.getErrorNroInicial().setText("Hubo un problema con los datos");
this.view.getErrorNroInicial().setVisible(true);
return false;
}
if (nroInicial.isEmpty()) {
this.view.getErrorNroInicial().setText("El campo esta vacio");
this.view.getErrorNroInicial().setVisible(true);
return false;
}
return true;
}
/**
* Valida la variable nroFinal contra los casos
* - Es null
* - Esta vacio
* Cuando el primer caso sea true, colocara un mensaje de error correspondiente en el jlabel correspondiente
*
* @return Si cualquiera de estos casos son true se retornara false, si no, se retorna true
*/
private boolean validateNroFinal(String nroFinal) {
if (nroFinal == null) {
this.view.getErrorNroFinal().setText("Hubo un problema con los datos");
this.view.getErrorNroFinal().setVisible(true);
return false;
}
if (nroFinal.isEmpty()) {
this.view.getErrorNroFinal().setText("El campo esta vacio");
this.view.getErrorNroFinal().setVisible(true);
return false;
}
return true;
}
/**
* Valida la variable caja este caso
* - Es null
* Cuando sea true, colocara un mensaje de error en el jlabel correspondiente
*
* @return Si este caso es true se retornara false, si no, se retorna true
*/
private boolean validateTipoIngreso(TipoIngreso tipoIngreso) {
if (tipoIngreso == null) {
this.view.getErrorTipoIngreso().setText("Hubo un problema con los datos");
this.view.getErrorTipoIngreso().setVisible(true);
return false;
}
return true;
}
/**
* Esconde los mensajes de error en la ventana de ingresos
*/
private void hideErrorMessages() {
this.view.getErrorTipoIngreso().setVisible(false);
this.view.getErrorNroInicial().setVisible(false);
this.view.getErrorNroFinal().setVisible(false);
}
/**
* Vacia los jtextfields y selecciona la primera opcion del jcombobox
*/
private void clearInputs() {
this.view.getTipoCombo().setSelectedIndex(0);
this.view.getValorField().setValue(0);
this.view.getValorField().setText("");
this.view.getNroZInicialField().setText("");
this.view.getNroZFinalField().setText("");
this.view.getNroInicialField().setText("");
this.view.getNroFinalField().setText("");
}
/**
* Ejecuta un trim sobre todos los jtextfield
*/
private void normalizeInputs() {
this.view.getNroZInicialField().setText(this.view.getNroZInicialField().getText().trim());
this.view.getNroZFinalField().setText(this.view.getNroZFinalField().getText().trim());
this.view.getNroInicialField().setText(this.view.getNroInicialField().getText().trim());
this.view.getNroFinalField().setText(this.view.getNroFinalField().getText().trim());
}
/**
* Le pide focus al tipo combo
*/
private void resetFocus() {
this.view.getValorField().requestFocus();
}
private class NextAction extends AbstractAction {
JComponent next;
NextAction(JComponent next) {
this.next = next;
}
@Override
public void actionPerformed(ActionEvent e) {
this.next.requestFocus();
}
}
private class GuardarAction extends AbstractAction {
IngresosController controller;
GuardarAction(IngresosController controller) {
this.controller = controller;
}
@Override
public void actionPerformed(ActionEvent e) {
this.controller.guardarActionListener();
}
} }
}
} }

View File

@@ -2,23 +2,23 @@ package danielcortes.xyz.controllers;
import danielcortes.xyz.data.Configuration; import danielcortes.xyz.data.Configuration;
import danielcortes.xyz.views.MainSideBar; import danielcortes.xyz.views.MainSideBar;
import javax.swing.border.TitledBorder; import javax.swing.border.TitledBorder;
public class MainSideBarController { public class MainSideBarController {
private MainSideBar view;
public MainSideBarController(MainSideBar view){ private MainSideBar view;
this.view = view;
this.loadRestaurantName();
}
public MainSideBar getView() { public MainSideBarController(MainSideBar view) {
return view; this.view = view;
} this.loadRestaurantName();
}
private void loadRestaurantName(){ public MainSideBar getView() {
String nombre = Configuration.get("nombre_caja"); return view;
((TitledBorder)this.view.getButtonPanel().getBorder()).setTitle("Restaurant: " + nombre); }
}
private void loadRestaurantName() {
String nombre = Configuration.get("nombre_caja");
((TitledBorder) this.view.getButtonPanel().getBorder()).setTitle("Restaurant: " + nombre);
}
} }

View File

@@ -1,35 +1,36 @@
package danielcortes.xyz.controllers.actions; package danielcortes.xyz.controllers.actions;
import javax.swing.*;
import java.awt.event.ActionEvent; import java.awt.event.ActionEvent;
import java.beans.PropertyChangeListener; import java.beans.PropertyChangeListener;
import javax.swing.Action;
public interface BasicAction extends Action { public interface BasicAction extends Action {
@Override
default Object getValue(String key) {
return null;
}
@Override @Override
default void putValue(String key, Object value) { default Object getValue(String key) {
} return null;
}
@Override @Override
default void setEnabled(boolean b) { default void putValue(String key, Object value) {
} }
@Override @Override
default boolean isEnabled() { default boolean isEnabled() {
return true; return true;
} }
@Override @Override
default void addPropertyChangeListener(PropertyChangeListener listener) { default void setEnabled(boolean b) {
} }
@Override @Override
default void removePropertyChangeListener(PropertyChangeListener listener) { default void addPropertyChangeListener(PropertyChangeListener listener) {
} }
void actionPerformed(ActionEvent e); @Override
default void removePropertyChangeListener(PropertyChangeListener listener) {
}
void actionPerformed(ActionEvent e);
} }

View File

@@ -24,18 +24,20 @@
package danielcortes.xyz.controllers.actions; package danielcortes.xyz.controllers.actions;
import javax.swing.*;
import java.awt.event.ActionEvent; import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
public class MoveToAction extends AbstractAction { public class MoveToAction extends AbstractAction {
private JComponent next;
public MoveToAction(JComponent next) { private JComponent next;
this.next = next;
}
@Override public MoveToAction(JComponent next) {
public void actionPerformed(ActionEvent e) { this.next = next;
this.next.requestFocus(); }
}
@Override
public void actionPerformed(ActionEvent e) {
this.next.requestFocus();
}
} }

View File

@@ -31,29 +31,30 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public class Configuration { public class Configuration {
private static final Logger LOGGER = Logger.getLogger( Configuration.class.getName() );
private static final Properties config; private static final Logger LOGGER = Logger.getLogger(Configuration.class.getName());
static { private static final Properties config;
config = new Properties();
try { static {
LOGGER.log(Level.INFO, "Leyendo y llenando el objeto de properties"); config = new Properties();
FileInputStream in = new FileInputStream("config/app.properties"); try {
config.load(in); LOGGER.log(Level.INFO, "Leyendo y llenando el objeto de properties");
in.close();
LOGGER.log(Level.INFO, "El objeto de properties se a llenado correctamente"); FileInputStream in = new FileInputStream("config/app.properties");
config.load(in);
in.close();
} catch (IOException e) { LOGGER.log(Level.INFO, "El objeto de properties se a llenado correctamente");
LOGGER.log(Level.SEVERE, e.toString(), e);
System.exit(1); } catch (IOException e) {
} LOGGER.log(Level.SEVERE, e.toString(), e);
System.exit(1);
} }
}
public static String get(String key) { public static String get(String key) {
return config.getProperty(key); return config.getProperty(key);
} }
} }

View File

@@ -28,5 +28,6 @@ import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
public interface ConnectionHolder { public interface ConnectionHolder {
Connection getConnection() throws SQLException;
Connection getConnection() throws SQLException;
} }

View File

@@ -50,79 +50,80 @@ import danielcortes.xyz.models.version.SQLiteVersionDAO;
import danielcortes.xyz.models.version.VersionDAO; import danielcortes.xyz.models.version.VersionDAO;
public class DAOManager { public class DAOManager {
private static final CajaDAO cajaDAO;
private static final CalculoFondoDAO calculoFondoDAO;
private static final DocumentosDAO documentosDAO;
private static final EfectivoDAO efectivoDAO;
private static final EgresoDAO egresoDAO;
private static final InformeEgresosContentDAO egresosContentDAO;
private static final InformeLibroDeVentasContentDAO libroDeVentasContentDAO;
private static final IngresoDAO ingresoDAO;
private static final TipoEgresoDAO tipoEgresoDAO;
private static final TipoIngresoDAO tipoIngresoDAO;
private static final EstadoResultadoDAO estadoResultadoDAO;
private static final VersionDAO versionDAO;
static { private static final CajaDAO cajaDAO;
cajaDAO = new SQLiteCajaDAO(); private static final CalculoFondoDAO calculoFondoDAO;
calculoFondoDAO = new SQLiteCalculoFondoDAO(); private static final DocumentosDAO documentosDAO;
documentosDAO = new SQLiteDocumentosDAO(); private static final EfectivoDAO efectivoDAO;
efectivoDAO = new SQLiteEfectivoDAO(); private static final EgresoDAO egresoDAO;
egresoDAO = new SQLiteEgresoDAO(); private static final InformeEgresosContentDAO egresosContentDAO;
egresosContentDAO = new SQLiteInformeEgresosContentDAO(); private static final InformeLibroDeVentasContentDAO libroDeVentasContentDAO;
libroDeVentasContentDAO = new SQLiteInformeLibroDeVentasContentDAO(); private static final IngresoDAO ingresoDAO;
ingresoDAO = new SQLiteIngresoDAO(); private static final TipoEgresoDAO tipoEgresoDAO;
tipoEgresoDAO = new SQLiteTipoEgresoDAO(); private static final TipoIngresoDAO tipoIngresoDAO;
tipoIngresoDAO = new SQLiteTipoIngresoDAO(); private static final EstadoResultadoDAO estadoResultadoDAO;
estadoResultadoDAO = new SQLiteEstadoResultadoDAO(); private static final VersionDAO versionDAO;
versionDAO = new SQLiteVersionDAO();
}
public static CajaDAO getCajaDAO() { static {
return cajaDAO; cajaDAO = new SQLiteCajaDAO();
} calculoFondoDAO = new SQLiteCalculoFondoDAO();
documentosDAO = new SQLiteDocumentosDAO();
efectivoDAO = new SQLiteEfectivoDAO();
egresoDAO = new SQLiteEgresoDAO();
egresosContentDAO = new SQLiteInformeEgresosContentDAO();
libroDeVentasContentDAO = new SQLiteInformeLibroDeVentasContentDAO();
ingresoDAO = new SQLiteIngresoDAO();
tipoEgresoDAO = new SQLiteTipoEgresoDAO();
tipoIngresoDAO = new SQLiteTipoIngresoDAO();
estadoResultadoDAO = new SQLiteEstadoResultadoDAO();
versionDAO = new SQLiteVersionDAO();
}
public static CalculoFondoDAO getCalculoFondoDAO() { public static CajaDAO getCajaDAO() {
return calculoFondoDAO; return cajaDAO;
} }
public static DocumentosDAO getDocumentosDAO() { public static CalculoFondoDAO getCalculoFondoDAO() {
return documentosDAO; return calculoFondoDAO;
} }
public static EfectivoDAO getEfectivoDAO() { public static DocumentosDAO getDocumentosDAO() {
return efectivoDAO; return documentosDAO;
} }
public static EgresoDAO getEgresoDAO() { public static EfectivoDAO getEfectivoDAO() {
return egresoDAO; return efectivoDAO;
} }
public static InformeEgresosContentDAO getEgresosContentDAO() { public static EgresoDAO getEgresoDAO() {
return egresosContentDAO; return egresoDAO;
} }
public static InformeLibroDeVentasContentDAO getLibroDeVentasContentDAO() { public static InformeEgresosContentDAO getEgresosContentDAO() {
return libroDeVentasContentDAO; return egresosContentDAO;
} }
public static IngresoDAO getIngresoDAO() { public static InformeLibroDeVentasContentDAO getLibroDeVentasContentDAO() {
return ingresoDAO; return libroDeVentasContentDAO;
} }
public static TipoEgresoDAO getTipoEgresoDAO() { public static IngresoDAO getIngresoDAO() {
return tipoEgresoDAO; return ingresoDAO;
} }
public static TipoIngresoDAO getTipoIngresoDAO() { public static TipoEgresoDAO getTipoEgresoDAO() {
return tipoIngresoDAO; return tipoEgresoDAO;
} }
public static EstadoResultadoDAO getEstadoResultadoDAO() { public static TipoIngresoDAO getTipoIngresoDAO() {
return estadoResultadoDAO; return tipoIngresoDAO;
} }
public static VersionDAO getVersionDAO() { public static EstadoResultadoDAO getEstadoResultadoDAO() {
return versionDAO; return estadoResultadoDAO;
} }
public static VersionDAO getVersionDAO() {
return versionDAO;
}
} }

View File

@@ -31,28 +31,29 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public class SQLiteConnectionHolder implements ConnectionHolder { public class SQLiteConnectionHolder implements ConnectionHolder {
private static final Logger LOGGER = Logger.getLogger( Configuration.class.getName() );
private static final Logger LOGGER = Logger.getLogger(Configuration.class.getName());
private String databaseURI; private String databaseURI;
public SQLiteConnectionHolder() { public SQLiteConnectionHolder() {
this.databaseURI = Configuration.get("sqlite_database_uri"); this.databaseURI = Configuration.get("sqlite_database_uri");
}
@Override
public Connection getConnection() throws SQLException {
Connection con = null;
try {
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection(databaseURI);
LOGGER.log(Level.FINEST, "Creada conexion a base de datos SQLITE");
} catch (ClassNotFoundException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
System.exit(133);
} }
@Override return con;
public Connection getConnection() throws SQLException { }
Connection con = null;
try {
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection(databaseURI);
LOGGER.log(Level.FINEST, "Creada conexion a base de datos SQLITE");
} catch (ClassNotFoundException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
System.exit(133);
}
return con;
}
} }

View File

@@ -28,11 +28,6 @@ import danielcortes.xyz.models.caja.SQLiteCajaDAO;
import danielcortes.xyz.models.informes.egresos.InformeEgresosContent; import danielcortes.xyz.models.informes.egresos.InformeEgresosContent;
import danielcortes.xyz.models.informes.egresos.SQLiteInformeEgresosContentDAO; import danielcortes.xyz.models.informes.egresos.SQLiteInformeEgresosContentDAO;
import danielcortes.xyz.utils.Pair; import danielcortes.xyz.utils.Pair;
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.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.nio.file.Files; import java.nio.file.Files;
@@ -43,255 +38,287 @@ import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderExtent;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.PropertyTemplate;
public class InformeEgresos { public class InformeEgresos {
private final String[] titles = {
"FECHA",
"",
"DESCRIPCION",
"VALOR"
};
private List<InformeEgresosContent> informe; private final String[] titles = {
private Path saveFile; "FECHA",
"",
"DESCRIPCION",
"VALOR"
};
//Filas donde se almacenaran los totales private List<InformeEgresosContent> informe;
private ArrayList<Row> totalRows; private Path saveFile;
//Filas donde se almacenaran los egresos.
private ArrayList<Row> dataRows; //Filas donde se almacenaran los totales
//Fila que contiene el total final; private ArrayList<Row> totalRows;
private Row totalFinal; //Filas donde se almacenaran los egresos.
private ArrayList<Row> dataRows;
//Fila que contiene el total final;
private Row totalFinal;
//Rango que corresponde a un dia de egresos; //Rango que corresponde a un dia de egresos;
private ArrayList<Pair<Integer, Integer>> totalRange; private ArrayList<Pair<Integer, Integer>> totalRange;
private Workbook wb; private Workbook wb;
private Sheet sheet; private Sheet sheet;
private CreationHelper createHelper; private CreationHelper createHelper;
private HashMap<String, CellStyle> styles; private HashMap<String, CellStyle> styles;
public InformeEgresos(int tipoEgresoId, YearMonth mes, Path saveFile) { public InformeEgresos(int tipoEgresoId, YearMonth mes, Path saveFile) {
new SQLiteCajaDAO().createCajasForMonth(mes); new SQLiteCajaDAO().createCajasForMonth(mes);
this.informe = new SQLiteInformeEgresosContentDAO().getInformeEgresosFactuasMateriaPrima(mes, tipoEgresoId); this.informe = new SQLiteInformeEgresosContentDAO()
this.saveFile = saveFile; .getInformeEgresosFactuasMateriaPrima(mes, tipoEgresoId);
this.saveFile = saveFile;
this.wb = new HSSFWorkbook(); this.wb = new HSSFWorkbook();
this.sheet = wb.createSheet(); this.sheet = wb.createSheet();
this.createHelper = wb.getCreationHelper(); this.createHelper = wb.getCreationHelper();
this.totalRows = new ArrayList<>(); this.totalRows = new ArrayList<>();
this.totalRange = new ArrayList<>(); this.totalRange = new ArrayList<>();
this.dataRows = new ArrayList<>(); this.dataRows = new ArrayList<>();
this.styles = this.generateStyles(); this.styles = this.generateStyles();
}
private void fillHeaders() {
Row titles = sheet.createRow(0);
for (int x = 0; x < this.titles.length; x++) {
titles.createCell(x).setCellValue(this.titles[x]);
}
}
private void fillData() {
int rowCounter = 1;
int dayStart = rowCounter;
int dayEnd;
for (int informeID = 0; informeID < informe.size(); informeID++) {
InformeEgresosContent data = informe.get(informeID);
int cellCounter = 0;
Row dataRow = sheet.createRow(rowCounter);
dataRows.add(dataRow);
Date fecha = Date.from(data.getFecha().atStartOfDay(ZoneId.systemDefault()).toInstant());
dataRow.createCell(cellCounter++).setCellValue(fecha);
dataRow.createCell(cellCounter++).setCellValue(data.getNro());
dataRow.createCell(cellCounter++).setCellValue(data.getDescripcion());
dataRow.createCell(cellCounter).setCellValue(data.getValor());
// Comprueba si es que el siguiente elemento en la lista de informe es del siguiente dia, si es asi, agrega una linea con los totales diarios.
if (informeID + 1 >= informe.size() || !data.getFecha()
.equals(informe.get(informeID + 1).getFecha())) {
totalRows.add(sheet.createRow(rowCounter + 1));
dayEnd = rowCounter;
totalRange.add(new Pair<>(dayStart, dayEnd));
dayStart = rowCounter + 2;
rowCounter++;
}
rowCounter++;
}
}
private void fillTotales() {
StringBuilder sumTotalFinal = new StringBuilder();
//Se aprovechara la iteracion para agregar los totales individuales y para construir la suma del total final
for (int x = 0; x < totalRows.size(); x++) {
Row row = totalRows.get(x);
Pair<Integer, Integer> range = totalRange.get(x);
row.createCell(2).setCellValue("TOTAL DIARIO");
row.createCell(3)
.setCellFormula("SUM(D" + (range.getLeft() + 1) + ":D" + (range.getRight() + 1) + ")");
sumTotalFinal.append("D").append(row.getRowNum() + 1);
if (x + 1 != totalRows.size()) {
sumTotalFinal.append("+");
} else {
this.totalFinal = sheet.createRow(row.getRowNum() + 1);
this.totalFinal.createCell(2).setCellValue("TOTAL MENSUAL");
this.totalFinal.createCell(3).setCellFormula(sumTotalFinal.toString());
}
} }
private void fillHeaders() {
Row titles = sheet.createRow(0);
for (int x = 0; x < this.titles.length; x++) { }
titles.createCell(x).setCellValue(this.titles[x]);
} private void freezeCells() {
this.sheet.createFreezePane(0, 1);
}
private void addBorders() {
int rows = this.totalRows.size() + this.dataRows.size() + 1;
PropertyTemplate pt = new PropertyTemplate();
//Bordes Internos
pt.drawBorders(new CellRangeAddress(0, rows, 0, 3), BorderStyle.THIN, BorderExtent.ALL);
//Bordes de los Headers
pt.drawBorders(new CellRangeAddress(0, 0, 0, 3), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
//Bordes de los Totales
for (Row row : this.totalRows) {
int index = row.getRowNum();
pt.drawBorders(new CellRangeAddress(index, index, 0, 3), BorderStyle.NONE, BorderExtent.ALL);
pt.drawBorders(new CellRangeAddress(index, index, 0, 3), BorderStyle.MEDIUM,
BorderExtent.OUTSIDE);
} }
private void fillData() { //Borde del Total Final
int rowCounter = 1; pt.drawBorders(
int dayStart = rowCounter; new CellRangeAddress(this.totalFinal.getRowNum(), this.totalFinal.getRowNum(), 0, 3),
int dayEnd; BorderStyle.NONE, BorderExtent.ALL);
pt.drawBorders(
new CellRangeAddress(this.totalFinal.getRowNum(), this.totalFinal.getRowNum(), 0, 3),
BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
for (int informeID = 0; informeID < informe.size(); informeID++) { //Borde externo
InformeEgresosContent data = informe.get(informeID); pt.drawBorders(new CellRangeAddress(0, rows, 0, 3), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
int cellCounter = 0;
Row dataRow = sheet.createRow(rowCounter);
dataRows.add(dataRow);
Date fecha = Date.from(data.getFecha().atStartOfDay(ZoneId.systemDefault()).toInstant());
dataRow.createCell(cellCounter++).setCellValue(fecha); pt.applyBorders(this.sheet);
dataRow.createCell(cellCounter++).setCellValue(data.getNro()); }
dataRow.createCell(cellCounter++).setCellValue(data.getDescripcion());
dataRow.createCell(cellCounter).setCellValue(data.getValor());
// Comprueba si es que el siguiente elemento en la lista de informe es del siguiente dia, si es asi, agrega una linea con los totales diarios. private void setStyles() {
if (informeID + 1 >= informe.size() || !data.getFecha().equals(informe.get(informeID + 1).getFecha())) { //Estilo para el header
totalRows.add(sheet.createRow(rowCounter + 1)); this.sheet.getRow(0).getCell(0).setCellStyle(this.styles.get("header"));
this.sheet.getRow(0).getCell(1).setCellStyle(this.styles.get("header"));
this.sheet.getRow(0).getCell(2).setCellStyle(this.styles.get("header"));
this.sheet.getRow(0).getCell(3).setCellStyle(this.styles.get("header"));
dayEnd = rowCounter; //Estilo para el Total Final
totalRange.add(new Pair<>(dayStart, dayEnd)); this.totalFinal.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK)
dayStart = rowCounter + 2; .setCellStyle(this.styles.get("gray"));
rowCounter++; this.totalFinal.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK)
} .setCellStyle(this.styles.get("gray"));
this.totalFinal.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK)
.setCellStyle(this.styles.get("gray"));
this.totalFinal.getCell(3).setCellStyle(this.styles.get("total_final"));
rowCounter++; //Estilo para las filas de datos
} for (Row row : this.dataRows) {
row.getCell(0).setCellStyle(this.styles.get("date"));
row.getCell(1).setCellStyle(this.styles.get("regular"));
row.getCell(2).setCellStyle(this.styles.get("regular"));
row.getCell(3).setCellStyle(this.styles.get("money"));
} }
private void fillTotales() { //Estilo para las filas de totales
StringBuilder sumTotalFinal = new StringBuilder(); for (Row row : this.totalRows) {
row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK)
//Se aprovechara la iteracion para agregar los totales individuales y para construir la suma del total final .setCellStyle(this.styles.get("not_so_gray"));
for (int x = 0; x < totalRows.size(); x++) { row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK)
Row row = totalRows.get(x); .setCellStyle(this.styles.get("not_so_gray"));
Pair<Integer, Integer> range = totalRange.get(x); row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK)
.setCellStyle(this.styles.get("not_so_gray"));
row.createCell(2).setCellValue("TOTAL DIARIO"); row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK)
row.createCell(3).setCellFormula("SUM(D" + (range.getLeft() + 1) + ":D" + (range.getRight() + 1) + ")"); .setCellStyle(this.styles.get("total"));
sumTotalFinal.append("D").append(row.getRowNum() + 1);
if (x + 1 != totalRows.size()) {
sumTotalFinal.append("+");
} else {
this.totalFinal = sheet.createRow(row.getRowNum() + 1);
this.totalFinal.createCell(2).setCellValue("TOTAL MENSUAL");
this.totalFinal.createCell(3).setCellFormula(sumTotalFinal.toString());
}
}
} }
private void freezeCells() { //Setea el alto de las filas
this.sheet.createFreezePane(0, 1); this.sheet.getRow(0).setHeightInPoints(30);
this.totalFinal.setHeightInPoints(20);
for (Row row : this.dataRows) {
row.setHeightInPoints(15);
}
for (Row row : this.totalRows) {
row.setHeightInPoints(18);
} }
private void addBorders() { //Setea el ancho de las columnas
int rows = this.totalRows.size() + this.dataRows.size() + 1; sheet.autoSizeColumn(0);
PropertyTemplate pt = new PropertyTemplate(); sheet.autoSizeColumn(1);
sheet.autoSizeColumn(2);
sheet.autoSizeColumn(3);
}
//Bordes Internos private HashMap<String, CellStyle> generateStyles() {
pt.drawBorders(new CellRangeAddress(0, rows, 0, 3), BorderStyle.THIN, BorderExtent.ALL); Font font = this.wb.createFont();
font.setBold(true);
font.setColor(IndexedColors.WHITE.getIndex());
//Bordes de los Headers CellStyle regularStyle = this.wb.createCellStyle();
pt.drawBorders(new CellRangeAddress(0, 0, 0, 3), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
//Bordes de los Totales CellStyle grayStyle = this.wb.createCellStyle();
for (Row row : this.totalRows) { grayStyle.setFont(font);
int index = row.getRowNum(); grayStyle.setVerticalAlignment(VerticalAlignment.CENTER);
pt.drawBorders(new CellRangeAddress(index, index, 0, 3), BorderStyle.NONE, BorderExtent.ALL); grayStyle.setFillForegroundColor(IndexedColors.GREY_80_PERCENT.getIndex());
pt.drawBorders(new CellRangeAddress(index, index, 0, 3), BorderStyle.MEDIUM, BorderExtent.OUTSIDE); grayStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
}
//Borde del Total Final CellStyle notSoGrayStyle = this.wb.createCellStyle();
pt.drawBorders(new CellRangeAddress(this.totalFinal.getRowNum(), this.totalFinal.getRowNum(), 0, 3), BorderStyle.NONE, BorderExtent.ALL); notSoGrayStyle.setFont(font);
pt.drawBorders(new CellRangeAddress(this.totalFinal.getRowNum(), this.totalFinal.getRowNum(), 0, 3), BorderStyle.MEDIUM, BorderExtent.OUTSIDE); notSoGrayStyle.setVerticalAlignment(VerticalAlignment.CENTER);
notSoGrayStyle.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
notSoGrayStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//Borde externo CellStyle dateStyle = this.wb.createCellStyle();
pt.drawBorders(new CellRangeAddress(0, rows, 0, 3), BorderStyle.MEDIUM, BorderExtent.OUTSIDE); dateStyle.setDataFormat(this.createHelper.createDataFormat().getFormat("dd/mm/yyyy"));
pt.applyBorders(this.sheet); CellStyle moneyStyle = this.wb.createCellStyle();
} moneyStyle
.setDataFormat(this.createHelper.createDataFormat().getFormat("\"$\"#,##0_);(\"$\"#,##0)"));
private void setStyles() {
//Estilo para el header CellStyle headerStyle = this.wb.createCellStyle();
this.sheet.getRow(0).getCell(0).setCellStyle(this.styles.get("header")); headerStyle.cloneStyleFrom(grayStyle);
this.sheet.getRow(0).getCell(1).setCellStyle(this.styles.get("header")); headerStyle.setAlignment(HorizontalAlignment.CENTER);
this.sheet.getRow(0).getCell(2).setCellStyle(this.styles.get("header"));
this.sheet.getRow(0).getCell(3).setCellStyle(this.styles.get("header")); CellStyle totalStyle = this.wb.createCellStyle();
totalStyle.cloneStyleFrom(notSoGrayStyle);
//Estilo para el Total Final totalStyle
this.totalFinal.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellStyle(this.styles.get("gray")); .setDataFormat(this.createHelper.createDataFormat().getFormat("\"$\"#,##0_);(\"$\"#,##0)"));
this.totalFinal.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellStyle(this.styles.get("gray"));
this.totalFinal.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellStyle(this.styles.get("gray")); CellStyle totalFinalStyle = this.wb.createCellStyle();
this.totalFinal.getCell(3).setCellStyle(this.styles.get("total_final")); totalFinalStyle.cloneStyleFrom(grayStyle);
totalFinalStyle
//Estilo para las filas de datos .setDataFormat(this.createHelper.createDataFormat().getFormat("\"$\"#,##0_);(\"$\"#,##0)"));
for (Row row : this.dataRows) {
row.getCell(0).setCellStyle(this.styles.get("date")); HashMap<String, CellStyle> styles = new HashMap<>();
row.getCell(1).setCellStyle(this.styles.get("regular")); styles.put("regular", regularStyle);
row.getCell(2).setCellStyle(this.styles.get("regular")); styles.put("gray", grayStyle);
row.getCell(3).setCellStyle(this.styles.get("money")); styles.put("not_so_gray", notSoGrayStyle);
} styles.put("date", dateStyle);
styles.put("money", moneyStyle);
//Estilo para las filas de totales styles.put("header", headerStyle);
for (Row row : this.totalRows) { styles.put("total", totalStyle);
row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellStyle(this.styles.get("not_so_gray")); styles.put("total_final", totalFinalStyle);
row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellStyle(this.styles.get("not_so_gray"));
row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellStyle(this.styles.get("not_so_gray")); return styles;
row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellStyle(this.styles.get("total")); }
}
public Path generarInforme() {
fillHeaders();
//Setea el alto de las filas fillData();
this.sheet.getRow(0).setHeightInPoints(30); fillTotales();
this.totalFinal.setHeightInPoints(20); freezeCells();
for (Row row : this.dataRows) { setStyles();
row.setHeightInPoints(15); addBorders();
}
for (Row row : this.totalRows) { try (OutputStream fileOut = Files.newOutputStream(this.saveFile)) {
row.setHeightInPoints(18); wb.write(fileOut);
} return this.saveFile;
} catch (IOException e) {
e.printStackTrace();
//Setea el ancho de las columnas
sheet.autoSizeColumn(0);
sheet.autoSizeColumn(1);
sheet.autoSizeColumn(2);
sheet.autoSizeColumn(3);
}
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.setVerticalAlignment(VerticalAlignment.CENTER);
grayStyle.setFillForegroundColor(IndexedColors.GREY_80_PERCENT.getIndex());
grayStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
CellStyle notSoGrayStyle = this.wb.createCellStyle();
notSoGrayStyle.setFont(font);
notSoGrayStyle.setVerticalAlignment(VerticalAlignment.CENTER);
notSoGrayStyle.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
notSoGrayStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
CellStyle dateStyle = this.wb.createCellStyle();
dateStyle.setDataFormat(this.createHelper.createDataFormat().getFormat("dd/mm/yyyy"));
CellStyle moneyStyle = this.wb.createCellStyle();
moneyStyle.setDataFormat(this.createHelper.createDataFormat().getFormat("\"$\"#,##0_);(\"$\"#,##0)"));
CellStyle headerStyle = this.wb.createCellStyle();
headerStyle.cloneStyleFrom(grayStyle);
headerStyle.setAlignment(HorizontalAlignment.CENTER);
CellStyle totalStyle = this.wb.createCellStyle();
totalStyle.cloneStyleFrom(notSoGrayStyle);
totalStyle.setDataFormat(this.createHelper.createDataFormat().getFormat("\"$\"#,##0_);(\"$\"#,##0)"));
CellStyle totalFinalStyle = this.wb.createCellStyle();
totalFinalStyle.cloneStyleFrom(grayStyle);
totalFinalStyle.setDataFormat(this.createHelper.createDataFormat().getFormat("\"$\"#,##0_);(\"$\"#,##0)"));
HashMap<String, CellStyle> styles = new HashMap<>();
styles.put("regular", regularStyle);
styles.put("gray", grayStyle);
styles.put("not_so_gray", notSoGrayStyle);
styles.put("date", dateStyle);
styles.put("money", moneyStyle);
styles.put("header", headerStyle);
styles.put("total", totalStyle);
styles.put("total_final", totalFinalStyle);
return styles;
}
public Path generarInforme() {
fillHeaders();
fillData();
fillTotales();
freezeCells();
setStyles();
addBorders();
try (OutputStream fileOut = Files.newOutputStream(this.saveFile)) {
wb.write(fileOut);
return this.saveFile;
} catch (IOException e) {
e.printStackTrace();
}
return null;
} }
return null;
}
} }

View File

@@ -5,11 +5,6 @@ import danielcortes.xyz.data.DAOManager;
import danielcortes.xyz.models.estado_resultado.EstadoResultado; import danielcortes.xyz.models.estado_resultado.EstadoResultado;
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 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.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.nio.file.Files; import java.nio.file.Files;
@@ -18,448 +13,481 @@ import java.time.YearMonth;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderExtent;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.PropertyTemplate;
public class InformeEstadoResultado { public class InformeEstadoResultado {
private ArrayList<Row> titles;
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 ArrayList<Row> titles;
private Path saveFile; 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 EstadoResultado estadoResultado; private YearMonth mes;
private Path saveFile;
private Workbook wb; private EstadoResultado estadoResultado;
private Sheet sheet;
private CreationHelper createHelper;
private HashMap<String, CellStyle> styles;
public InformeEstadoResultado(YearMonth mes, Path saveFile) { private Workbook wb;
this.mes = mes; private Sheet sheet;
this.saveFile = saveFile; private CreationHelper createHelper;
private HashMap<String, CellStyle> styles;
this.estadoResultado = DAOManager.getEstadoResultadoDAO().findByMonth(this.mes); public InformeEstadoResultado(YearMonth mes, Path saveFile) {
this.mes = mes;
this.saveFile = saveFile;
this.wb = new HSSFWorkbook(); this.estadoResultado = DAOManager.getEstadoResultadoDAO().findByMonth(this.mes);
this.sheet = wb.createSheet();
this.createHelper = wb.getCreationHelper();
this.titles = new ArrayList<>(); this.wb = new HSSFWorkbook();
this.headers = new ArrayList<>(); this.sheet = wb.createSheet();
this.footers = new ArrayList<>(); this.createHelper = wb.getCreationHelper();
this.ventaRows = new ArrayList<>();
this.gastosOperacionalesRows = new ArrayList<>();
this.serviciosRows = new ArrayList<>();
this.gastosGeneralesRows = new ArrayList<>();
this.resumenGeneralRows = new ArrayList<>();
this.styles = this.generateStyles(); this.titles = new ArrayList<>();
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 fillTitle() {
int startRow = 0;
Row titleMes = this.sheet.createRow(startRow++);
Row titleLocal = this.sheet.createRow(startRow++);
this.titles.add(titleMes);
this.titles.add(titleLocal);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy");
String formatedMes = this.mes.format(formatter);
titleMes.createCell(0).setCellValue("Estado Resultado");
titleMes.createCell(1).setCellValue(StringUtils.capitalize(formatedMes));
titleLocal.createCell(0).setCellValue("Local");
titleLocal.createCell(1).setCellValue(StringUtils.capitalize(Configuration.get("nombre_caja")));
}
private void fillVentaData() {
int startId = 2;
Row header = this.sheet.createRow(startId++);
Row bruto = sheet.createRow(startId++);
Row neto = sheet.createRow(startId++);
Row iva = sheet.createRow(startId++);
Row exentas = sheet.createRow(startId++);
Row footer = sheet.createRow(startId++);
this.headers.add(header);
this.ventaRows.add(bruto);
this.ventaRows.add(neto);
this.ventaRows.add(iva);
this.ventaRows.add(exentas);
this.footers.add(footer);
header.createCell(0).setCellValue("Venta");
header.createCell(1);
bruto.createCell(0).setCellValue("Bruto");
bruto.createCell(1).setCellValue(DAOManager.getIngresoDAO().getTotalIngresoMes(this.mes));
neto.createCell(0).setCellValue("Neto");
neto.createCell(1).setCellFormula("B4/1.19");
iva.createCell(0).setCellValue("IVA");
iva.createCell(1).setCellFormula("B4-B5");
exentas.createCell(0).setCellValue("Exentas");
exentas.createCell(1).setCellValue(DAOManager.getIngresoDAO().getTotalExentasMes(this.mes));
footer.createCell(0).setCellValue("Neto mas Exentas");
footer.createCell(1).setCellFormula("B7+B5");
}
private void fillGastosOperacionalesData() {
int startId = 9;
Row header = sheet.createRow(startId++);
Row costoVenta = sheet.createRow(startId++);
Row porcentajeCostoVenta = sheet.createRow(startId++);
Row remuneraciones = sheet.createRow(startId++);
Row finiquitos = sheet.createRow(startId++);
Row aguinaldo = sheet.createRow(startId++);
Row partime = sheet.createRow(startId++);
Row bonosPersonal = sheet.createRow(startId++);
Row honorariosContador = sheet.createRow(startId++);
Row arriendo = sheet.createRow(startId++);
Row footer = sheet.createRow(startId++);
this.headers.add(header);
this.gastosOperacionalesRows.add(costoVenta);
this.gastosOperacionalesRows.add(porcentajeCostoVenta);
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);
this.footers.add(footer);
header.createCell(0).setCellValue("Gastos Operacionales");
header.createCell(1);
costoVenta.createCell(0).setCellValue("Costo de Venta");
costoVenta.createCell(1).setCellValue(this.estadoResultado.getCostoVenta());
porcentajeCostoVenta.createCell(0).setCellValue("Porcentaje Costo de Venta");
porcentajeCostoVenta.createCell(1).setCellFormula("B11/B4");
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());
footer.createCell(0).setCellValue("Total");
footer.createCell(1).setCellFormula("Sum(B11:B19)");
}
private void fillServiciosData() {
int startId = 21;
Row header = sheet.createRow(startId++);
Row agua = sheet.createRow(startId++);
Row luz = sheet.createRow(startId++);
Row gas = sheet.createRow(startId++);
Row telefono = sheet.createRow(startId++);
Row otro = sheet.createRow(startId++);
Row footer = sheet.createRow(startId++);
this.headers.add(header);
this.serviciosRows.add(agua);
this.serviciosRows.add(luz);
this.serviciosRows.add(gas);
this.serviciosRows.add(telefono);
this.serviciosRows.add(otro);
this.footers.add(footer);
header.createCell(0).setCellValue("Servicios");
header.createCell(1);
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());
otro.createCell(0).setCellValue("Otros");
otro.createCell(1).setCellValue(this.estadoResultado.getOtroServicio());
footer.createCell(0).setCellValue("Total");
footer.createCell(1).setCellFormula("Sum(B23:B27)");
}
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);
int startId = 29;
Row header = sheet.createRow(startId++);
Row cuentaCorrienteFactura = sheet.createRow(startId++);
Row cuentaCorrienteBoleta = sheet.createRow(startId++);
Row cuentaCorrienteSinRespaldo = sheet.createRow(startId++);
Row efectivoFactura = sheet.createRow(startId++);
Row efectivoBoleta = sheet.createRow(startId++);
Row efectivoSinRespaldo = sheet.createRow(startId++);
Row footer = sheet.createRow(startId++);
this.headers.add(header);
this.gastosGeneralesRows.add(cuentaCorrienteFactura);
this.gastosGeneralesRows.add(cuentaCorrienteBoleta);
this.gastosGeneralesRows.add(cuentaCorrienteSinRespaldo);
this.gastosGeneralesRows.add(efectivoFactura);
this.gastosGeneralesRows.add(efectivoBoleta);
this.gastosGeneralesRows.add(efectivoSinRespaldo);
this.footers.add(footer);
header.createCell(0).setCellValue("Gastos Generales");
header.createCell(1);
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));
footer.createCell(0).setCellValue("Total");
footer.createCell(1).setCellFormula("Sum(B31:B36)");
}
private void fillResumenGeneralData() {
int startId = 38;
Row header = sheet.createRow(startId++);
Row utilidad = sheet.createRow(startId++);
Row porcentajePPM = sheet.createRow(startId++);
Row ppmMes = sheet.createRow(startId++);
Row ivaMes = sheet.createRow(startId++);
Row ivaMesPpm = sheet.createRow(startId++);
Row ivaFavor = sheet.createRow(startId++);
Row aPagar = sheet.createRow(startId++);
Row footer = sheet.createRow(startId++);
this.headers.add(header);
this.resumenGeneralRows.add(utilidad);
this.resumenGeneralRows.add(porcentajePPM);
this.resumenGeneralRows.add(ppmMes);
this.resumenGeneralRows.add(ivaMes);
this.resumenGeneralRows.add(ivaMesPpm);
this.resumenGeneralRows.add(ivaFavor);
this.resumenGeneralRows.add(aPagar);
this.footers.add(footer);
header.createCell(0).setCellValue("Resumen General");
header.createCell(1);
utilidad.createCell(0).setCellValue("Utilidad");
utilidad.createCell(1).setCellFormula("B4 - B20 - B28 - B37");
porcentajePPM.createCell(0).setCellValue("Porcentaje PPM");
porcentajePPM.createCell(1).setCellValue(this.estadoResultado.getPpm() / 100);
ppmMes.createCell(0).setCellValue("PPM Mes");
ppmMes.createCell(1).setCellFormula("B8 * B41");
ivaMes.createCell(0).setCellValue("+ IVA Mes");
ivaMes.createCell(1).setCellFormula("B6");
ivaMesPpm.createCell(0).setCellValue("Total PPM + IVA");
ivaMesPpm.createCell(1).setCellFormula("B42 + B43");
ivaFavor.createCell(0).setCellValue("- IVA a Favor");
ivaFavor.createCell(1).setCellValue(this.estadoResultado.getIvaFavor());
aPagar.createCell(0).setCellValue("A Pagar PPM + IVA");
aPagar.createCell(1).setCellFormula("B44 - B45");
footer.createCell(0).setCellValue("Resultado");
footer.createCell(1).setCellFormula("B40 - B46");
}
private void setStyles() {
for (Row title : this.titles) {
title.getCell(0).setCellStyle(this.styles.get("title"));
title.getCell(1).setCellStyle(this.styles.get("title"));
title.setHeightInPoints(30);
} }
private void fillTitle() { for (Row header : this.headers) {
int startRow = 0; header.getCell(0).setCellStyle(this.styles.get("header"));
Row titleMes= this.sheet.createRow(startRow++); header.getCell(1).setCellStyle(this.styles.get("header"));
Row titleLocal = this.sheet.createRow(startRow++); header.setHeightInPoints(20);
this.titles.add(titleMes);
this.titles.add(titleLocal);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy");
String formatedMes= this.mes.format(formatter);
titleMes.createCell(0).setCellValue("Estado Resultado");
titleMes.createCell(1).setCellValue(StringUtils.capitalize(formatedMes));
titleLocal.createCell(0).setCellValue("Local");
titleLocal.createCell(1).setCellValue(StringUtils.capitalize(Configuration.get("nombre_caja")));
} }
private void fillVentaData() { for (Row footer : this.footers) {
int startId = 2; footer.getCell(0).setCellStyle(this.styles.get("footer"));
footer.getCell(1).setCellStyle(this.styles.get("footer_money"));
Row header = this.sheet.createRow(startId++); footer.setHeightInPoints(20);
Row bruto = sheet.createRow(startId++);
Row neto = sheet.createRow(startId++);
Row iva = sheet.createRow(startId++);
Row exentas = sheet.createRow(startId++);
Row footer = sheet.createRow(startId++);
this.headers.add(header);
this.ventaRows.add(bruto);
this.ventaRows.add(neto);
this.ventaRows.add(iva);
this.ventaRows.add(exentas);
this.footers.add(footer);
header.createCell(0).setCellValue("Venta");
header.createCell(1);
bruto.createCell(0).setCellValue("Bruto");
bruto.createCell(1).setCellValue(DAOManager.getIngresoDAO().getTotalIngresoMes(this.mes));
neto.createCell(0).setCellValue("Neto");
neto.createCell(1).setCellFormula("B4/1.19");
iva.createCell(0).setCellValue("IVA");
iva.createCell(1).setCellFormula("B4-B5");
exentas.createCell(0).setCellValue("Exentas");
exentas.createCell(1).setCellValue(DAOManager.getIngresoDAO().getTotalExentasMes(this.mes));
footer.createCell(0).setCellValue("Neto mas Exentas");
footer.createCell(1).setCellFormula("B7+B5");
} }
private void fillGastosOperacionalesData() { for (Row row : this.ventaRows) {
int startId = 9; row.getCell(0).setCellStyle(this.styles.get("regular"));
Row header = sheet.createRow(startId++); row.getCell(1).setCellStyle(this.styles.get("money"));
Row costoVenta = sheet.createRow(startId++); row.setHeightInPoints(15);
Row porcentajeCostoVenta = sheet.createRow(startId++); }
Row remuneraciones = sheet.createRow(startId++); for (Row row : this.gastosOperacionalesRows) {
Row finiquitos = sheet.createRow(startId++); row.getCell(0).setCellStyle(this.styles.get("regular"));
Row aguinaldo = sheet.createRow(startId++); row.getCell(1).setCellStyle(this.styles.get("money"));
Row partime = sheet.createRow(startId++); row.setHeightInPoints(15);
Row bonosPersonal = sheet.createRow(startId++); }
Row honorariosContador = sheet.createRow(startId++); for (Row row : this.serviciosRows) {
Row arriendo = sheet.createRow(startId++); row.getCell(0).setCellStyle(this.styles.get("regular"));
Row footer = sheet.createRow(startId++); row.getCell(1).setCellStyle(this.styles.get("money"));
row.setHeightInPoints(15);
this.headers.add(header); }
this.gastosOperacionalesRows.add(costoVenta); for (Row row : this.gastosGeneralesRows) {
this.gastosOperacionalesRows.add(porcentajeCostoVenta); row.getCell(0).setCellStyle(this.styles.get("regular"));
this.gastosOperacionalesRows.add(remuneraciones); row.getCell(1).setCellStyle(this.styles.get("money"));
this.gastosOperacionalesRows.add(finiquitos); row.setHeightInPoints(15);
this.gastosOperacionalesRows.add(aguinaldo); }
this.gastosOperacionalesRows.add(partime); for (Row row : this.resumenGeneralRows) {
this.gastosOperacionalesRows.add(bonosPersonal); row.getCell(0).setCellStyle(this.styles.get("regular"));
this.gastosOperacionalesRows.add(honorariosContador); row.getCell(1).setCellStyle(this.styles.get("money"));
this.gastosOperacionalesRows.add(arriendo); row.setHeightInPoints(15);
this.footers.add(footer);
header.createCell(0).setCellValue("Gastos Operacionales");
header.createCell(1);
costoVenta.createCell(0).setCellValue("Costo de Venta");
costoVenta.createCell(1).setCellValue(this.estadoResultado.getCostoVenta());
porcentajeCostoVenta.createCell(0).setCellValue("Porcentaje Costo de Venta");
porcentajeCostoVenta.createCell(1).setCellFormula("B11/B4");
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());
footer.createCell(0).setCellValue("Total");
footer.createCell(1).setCellFormula("Sum(B11:B19)");
} }
private void fillServiciosData() { //La fila de porcentaje costo de venta tiene que tener formato de porcentaje
int startId = 21; this.gastosOperacionalesRows.get(1).getCell(1).setCellStyle(this.styles.get("percent"));
Row header = sheet.createRow(startId++);
Row agua = sheet.createRow(startId++);
Row luz = sheet.createRow(startId++);
Row gas = sheet.createRow(startId++);
Row telefono = sheet.createRow(startId++);
Row otro = sheet.createRow(startId++);
Row footer = sheet.createRow(startId++);
this.headers.add(header); //La fila de ppm mes en el resumen general tiene un campo distinto que contiene un porcentaje
this.serviciosRows.add(agua); resumenGeneralRows.get(1).getCell(1).setCellStyle(this.styles.get("percent"));
this.serviciosRows.add(luz);
this.serviciosRows.add(gas);
this.serviciosRows.add(telefono);
this.serviciosRows.add(otro);
this.footers.add(footer);
header.createCell(0).setCellValue("Servicios"); sheet.autoSizeColumn(0);
header.createCell(1); sheet.autoSizeColumn(1);
agua.createCell(0).setCellValue("Agua"); sheet.autoSizeColumn(2);
agua.createCell(1).setCellValue(this.estadoResultado.getAgua()); }
luz.createCell(0).setCellValue("Luz");
luz.createCell(1).setCellValue(this.estadoResultado.getLuz()); private void addBorders() {
gas.createCell(0).setCellValue("Gas"); PropertyTemplate pt = new PropertyTemplate();
gas.createCell(1).setCellValue(this.estadoResultado.getGas()); for (Row header : headers) {
telefono.createCell(0).setCellValue("Telefono"); int rowNum = header.getRowNum();
telefono.createCell(1).setCellValue(this.estadoResultado.getTelefono()); CellRangeAddress range = new CellRangeAddress(rowNum, rowNum, 0, 1);
otro.createCell(0).setCellValue("Otros"); pt.drawBorders(range, BorderStyle.THIN, BorderExtent.OUTSIDE);
otro.createCell(1).setCellValue(this.estadoResultado.getOtroServicio());
footer.createCell(0).setCellValue("Total");
footer.createCell(1).setCellFormula("Sum(B23:B27)");
} }
private void fillGastosGeneralesData() { for (Row footer : footers) {
TipoEgreso facturaGastosGenerales = DAOManager.getTipoEgresoDAO().findByNombre("Factura Gastos Generales").get(0); int rowNum = footer.getRowNum();
TipoEgreso gastoGeneralConBoleta = DAOManager.getTipoEgresoDAO().findByNombre("Gasto General Con Boleta").get(0); CellRangeAddress range = new CellRangeAddress(rowNum, rowNum, 0, 1);
TipoEgreso gastoGeneralSinRespaldo = DAOManager.getTipoEgresoDAO().findByNombre("Gasto General Sin Respaldo").get(0); pt.drawBorders(range, BorderStyle.THIN, BorderExtent.OUTSIDE);
int startId = 29;
Row header = sheet.createRow(startId++);
Row cuentaCorrienteFactura = sheet.createRow(startId++);
Row cuentaCorrienteBoleta = sheet.createRow(startId++);
Row cuentaCorrienteSinRespaldo = sheet.createRow(startId++);
Row efectivoFactura = sheet.createRow(startId++);
Row efectivoBoleta = sheet.createRow(startId++);
Row efectivoSinRespaldo = sheet.createRow(startId++);
Row footer = sheet.createRow(startId++);
this.headers.add(header);
this.gastosGeneralesRows.add(cuentaCorrienteFactura);
this.gastosGeneralesRows.add(cuentaCorrienteBoleta);
this.gastosGeneralesRows.add(cuentaCorrienteSinRespaldo);
this.gastosGeneralesRows.add(efectivoFactura);
this.gastosGeneralesRows.add(efectivoBoleta);
this.gastosGeneralesRows.add(efectivoSinRespaldo);
this.footers.add(footer);
header.createCell(0).setCellValue("Gastos Generales");
header.createCell(1);
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));
footer.createCell(0).setCellValue("Total");
footer.createCell(1).setCellFormula("Sum(B31:B36)");
} }
private void fillResumenGeneralData() { int ventaStart = ventaRows.get(0).getRowNum();
int startId = 38; int ventaEnd = ventaRows.get(ventaRows.size() - 1).getRowNum();
pt.drawBorders(new CellRangeAddress(ventaStart, ventaEnd, 0, 1), BorderStyle.THIN,
BorderExtent.VERTICAL);
Row header = sheet.createRow(startId++); int gastosOperacionalesStart = gastosOperacionalesRows.get(0).getRowNum();
Row utilidad = sheet.createRow(startId++); int gastosOperacionalesEnd = gastosOperacionalesRows.get(gastosOperacionalesRows.size() - 1)
Row porcentajePPM = sheet.createRow(startId++); .getRowNum();
Row ppmMes = sheet.createRow(startId++); pt.drawBorders(new CellRangeAddress(gastosOperacionalesStart, gastosOperacionalesEnd, 0, 1),
Row ivaMes = sheet.createRow(startId++); BorderStyle.THIN, BorderExtent.VERTICAL);
Row ivaMesPpm = sheet.createRow(startId++);
Row ivaFavor = sheet.createRow(startId++);
Row aPagar = sheet.createRow(startId++);
Row footer = sheet.createRow(startId++);
this.headers.add(header); int serviciosStart = serviciosRows.get(0).getRowNum();
this.resumenGeneralRows.add(utilidad); int serviciosEnd = serviciosRows.get(serviciosRows.size() - 1).getRowNum();
this.resumenGeneralRows.add(porcentajePPM); pt.drawBorders(new CellRangeAddress(serviciosStart, serviciosEnd, 0, 1), BorderStyle.THIN,
this.resumenGeneralRows.add(ppmMes); BorderExtent.VERTICAL);
this.resumenGeneralRows.add(ivaMes);
this.resumenGeneralRows.add(ivaMesPpm);
this.resumenGeneralRows.add(ivaFavor);
this.resumenGeneralRows.add(aPagar);
this.footers.add(footer);
header.createCell(0).setCellValue("Resumen General"); int gastosGeneralesStart = gastosGeneralesRows.get(0).getRowNum();
header.createCell(1); int gastosGeneralesEnd = gastosGeneralesRows.get(gastosGeneralesRows.size() - 1).getRowNum();
pt.drawBorders(new CellRangeAddress(gastosGeneralesStart, gastosGeneralesEnd, 0, 1),
BorderStyle.THIN, BorderExtent.VERTICAL);
utilidad.createCell(0).setCellValue("Utilidad"); int resumenStart = resumenGeneralRows.get(0).getRowNum();
utilidad.createCell(1).setCellFormula("B4 - B20 - B28 - B37"); int resumenEnd = resumenGeneralRows.get(resumenGeneralRows.size() - 1).getRowNum();
pt.drawBorders(new CellRangeAddress(resumenStart, resumenEnd, 0, 1), BorderStyle.THIN,
BorderExtent.VERTICAL);
porcentajePPM.createCell(0).setCellValue("Porcentaje PPM"); pt.applyBorders(this.sheet);
porcentajePPM.createCell(1).setCellValue(this.estadoResultado.getPpm() / 100); }
ppmMes.createCell(0).setCellValue("PPM Mes"); public void generarInforme() {
ppmMes.createCell(1).setCellFormula("B8 * B41"); fillTitle();
fillVentaData();
fillGastosOperacionalesData();
fillServiciosData();
fillGastosGeneralesData();
fillResumenGeneralData();
setStyles();
addBorders();
ivaMes.createCell(0).setCellValue("+ IVA Mes"); try (OutputStream fileOut = Files.newOutputStream(this.saveFile)) {
ivaMes.createCell(1).setCellFormula("B6"); wb.write(fileOut);
} catch (IOException e) {
ivaMesPpm.createCell(0).setCellValue("Total PPM + IVA"); e.printStackTrace();
ivaMesPpm.createCell(1).setCellFormula("B42 + B43");
ivaFavor.createCell(0).setCellValue("- IVA a Favor");
ivaFavor.createCell(1).setCellValue(this.estadoResultado.getIvaFavor());
aPagar.createCell(0).setCellValue("A Pagar PPM + IVA");
aPagar.createCell(1).setCellFormula("B44 - B45");
footer.createCell(0).setCellValue("Resultado");
footer.createCell(1).setCellFormula("B40 - B46");
} }
}
private void setStyles() { private HashMap<String, CellStyle> generateStyles() {
for(Row title: this.titles){ Font font = this.wb.createFont();
title.getCell(0).setCellStyle(this.styles.get("title")); font.setBold(true);
title.getCell(1).setCellStyle(this.styles.get("title")); font.setColor(IndexedColors.WHITE.getIndex());
title.setHeightInPoints(30);
}
for (Row header : this.headers) { Font titleFont = this.wb.createFont();
header.getCell(0).setCellStyle(this.styles.get("header")); titleFont.setBold(true);
header.getCell(1).setCellStyle(this.styles.get("header")); titleFont.setFontHeightInPoints((short) 15);
header.setHeightInPoints(20);
}
for (Row footer : this.footers) { CellStyle regularStyle = this.wb.createCellStyle();
footer.getCell(0).setCellStyle(this.styles.get("footer"));
footer.getCell(1).setCellStyle(this.styles.get("footer_money"));
footer.setHeightInPoints(20);
}
for (Row row : this.ventaRows) { CellStyle grayStyle = this.wb.createCellStyle();
row.getCell(0).setCellStyle(this.styles.get("regular")); grayStyle.setFont(font);
row.getCell(1).setCellStyle(this.styles.get("money")); grayStyle.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
row.setHeightInPoints(15); grayStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
}
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("money"));
row.setHeightInPoints(15);
}
//La fila de porcentaje costo de venta tiene que tener formato de porcentaje CellStyle moneyStyle = this.wb.createCellStyle();
this.gastosOperacionalesRows.get(1).getCell(1).setCellStyle(this.styles.get("percent")); moneyStyle
.setDataFormat(this.createHelper.createDataFormat().getFormat("\"$\"#,##0_);(\"$\"#,##0)"));
//La fila de ppm mes en el resumen general tiene un campo distinto que contiene un porcentaje CellStyle percentStyle = this.wb.createCellStyle();
resumenGeneralRows.get(1).getCell(1).setCellStyle(this.styles.get("percent")); percentStyle.setDataFormat(this.createHelper.createDataFormat().getFormat("0.00%"));
sheet.autoSizeColumn(0); CellStyle titleStyle = this.wb.createCellStyle();
sheet.autoSizeColumn(1); titleStyle.setFont(titleFont);
sheet.autoSizeColumn(2);
}
private void addBorders() { CellStyle headerStyle = this.wb.createCellStyle();
PropertyTemplate pt = new PropertyTemplate(); headerStyle.cloneStyleFrom(grayStyle);
for (Row header : headers) { headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
int rowNum = header.getRowNum();
CellRangeAddress range = new CellRangeAddress(rowNum, rowNum, 0, 1);
pt.drawBorders(range, BorderStyle.THIN, BorderExtent.OUTSIDE);
}
for (Row footer : footers) { CellStyle footerStyle = this.wb.createCellStyle();
int rowNum = footer.getRowNum(); footerStyle.cloneStyleFrom(grayStyle);
CellRangeAddress range = new CellRangeAddress(rowNum, rowNum, 0, 1); footerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
pt.drawBorders(range, BorderStyle.THIN, BorderExtent.OUTSIDE);
}
int ventaStart = ventaRows.get(0).getRowNum(); CellStyle footerMoneyStyle = this.wb.createCellStyle();
int ventaEnd = ventaRows.get(ventaRows.size() - 1).getRowNum(); footerMoneyStyle.cloneStyleFrom(footerStyle);
pt.drawBorders(new CellRangeAddress(ventaStart, ventaEnd, 0, 1), BorderStyle.THIN, BorderExtent.VERTICAL); footerMoneyStyle
.setDataFormat(this.createHelper.createDataFormat().getFormat("\"$\"#,##0_);(\"$\"#,##0)"));
int gastosOperacionalesStart = gastosOperacionalesRows.get(0).getRowNum(); HashMap<String, CellStyle> styles = new HashMap<>();
int gastosOperacionalesEnd = gastosOperacionalesRows.get(gastosOperacionalesRows.size() - 1).getRowNum(); styles.put("regular", regularStyle);
pt.drawBorders(new CellRangeAddress(gastosOperacionalesStart, gastosOperacionalesEnd, 0, 1), BorderStyle.THIN, BorderExtent.VERTICAL); styles.put("title", titleStyle);
styles.put("money", moneyStyle);
styles.put("percent", percentStyle);
styles.put("header", headerStyle);
styles.put("footer", footerStyle);
styles.put("footer_money", footerMoneyStyle);
int serviciosStart = serviciosRows.get(0).getRowNum(); return styles;
int serviciosEnd = serviciosRows.get(serviciosRows.size() - 1).getRowNum(); }
pt.drawBorders(new CellRangeAddress(serviciosStart, serviciosEnd, 0, 1), BorderStyle.THIN, BorderExtent.VERTICAL);
int gastosGeneralesStart = gastosGeneralesRows.get(0).getRowNum();
int gastosGeneralesEnd = gastosGeneralesRows.get(gastosGeneralesRows.size() - 1).getRowNum();
pt.drawBorders(new CellRangeAddress(gastosGeneralesStart, gastosGeneralesEnd, 0, 1), BorderStyle.THIN, BorderExtent.VERTICAL);
int resumenStart = resumenGeneralRows.get(0).getRowNum();
int resumenEnd = resumenGeneralRows.get(resumenGeneralRows.size() - 1).getRowNum();
pt.drawBorders(new CellRangeAddress(resumenStart, resumenEnd, 0, 1), BorderStyle.THIN, BorderExtent.VERTICAL);
pt.applyBorders(this.sheet);
}
public void generarInforme() {
fillTitle();
fillVentaData();
fillGastosOperacionalesData();
fillServiciosData();
fillGastosGeneralesData();
fillResumenGeneralData();
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());
Font titleFont = this.wb.createFont();
titleFont.setBold(true);
titleFont.setFontHeightInPoints((short)15);
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 titleStyle = this.wb.createCellStyle();
titleStyle.setFont(titleFont);
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("title", titleStyle);
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

@@ -27,339 +27,370 @@ package danielcortes.xyz.informes;
import danielcortes.xyz.data.DAOManager; import danielcortes.xyz.data.DAOManager;
import danielcortes.xyz.models.caja.SQLiteCajaDAO; import danielcortes.xyz.models.caja.SQLiteCajaDAO;
import danielcortes.xyz.models.informes.libro_de_ventas.InformeLibroDeVentasContent; import danielcortes.xyz.models.informes.libro_de_ventas.InformeLibroDeVentasContent;
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.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.YearMonth; import java.time.YearMonth;
import java.time.ZoneId; import java.time.ZoneId;
import java.util.*; import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderExtent;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.PropertyTemplate;
public class InformeLibroDeVentas { public class InformeLibroDeVentas {
private final String[] titles = {
"", "",
"BOLETA MANUAL", "", "",
"BOLETA FISCAL", "", "", "", "",
"BOLETAS EXENTAS", "", "",
"SUB",
"FACTURA", "", "",
"GUIAS", "", "",
"ESTADISTICAS"
};
private final String[] subtitles = { private final String[] titles = {
"DIA", "FECHA", "", "",
"INICIAL", "FINAL", "VALOR", "BOLETA MANUAL", "", "",
"Z DEL", "Z AL", "INCIAL", "FINAL", "VALOR", "BOLETA FISCAL", "", "", "", "",
"INICIAL", "FINAL", "VALOR", "BOLETAS EXENTAS", "", "",
"TOTAL", "SUB",
"INICIAL", "FINAL", "VALOR", "FACTURA", "", "",
"INICIAL", "FINAL", "VALOR", "GUIAS", "", "",
"TOTAL", "ACUMULADO", "" "ESTADISTICAS"
}; };
private final String[] dias = {"Domingo", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado"}; private final String[] subtitles = {
"DIA", "FECHA",
"INICIAL", "FINAL", "VALOR",
"Z DEL", "Z AL", "INCIAL", "FINAL", "VALOR",
"INICIAL", "FINAL", "VALOR",
"TOTAL",
"INICIAL", "FINAL", "VALOR",
"INICIAL", "FINAL", "VALOR",
"TOTAL", "ACUMULADO", ""
};
private ArrayList<InformeLibroDeVentasContent> informe; private final String[] dias = {"Domingo", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes",
private Path saveFile; "Sabado"};
private ArrayList<Row> dataRows; private ArrayList<InformeLibroDeVentasContent> informe;
private Row footerRow; private Path saveFile;
private ArrayList<Row> headerRows;
private Workbook wb; private ArrayList<Row> dataRows;
private Sheet sheet; private Row footerRow;
private CreationHelper createHelper; private ArrayList<Row> headerRows;
private HashMap<String, CellStyle> styles;
public InformeLibroDeVentas(YearMonth mes, Path saveFile) { private Workbook wb;
new SQLiteCajaDAO().createCajasForMonth(mes); private Sheet sheet;
private CreationHelper createHelper;
private HashMap<String, CellStyle> styles;
this.informe = new ArrayList<>(DAOManager.getLibroDeVentasContentDAO().getInformeMensual(mes)); public InformeLibroDeVentas(YearMonth mes, Path saveFile) {
this.saveFile = saveFile; new SQLiteCajaDAO().createCajasForMonth(mes);
this.dataRows = new ArrayList<>(); this.informe = new ArrayList<>(DAOManager.getLibroDeVentasContentDAO().getInformeMensual(mes));
this.headerRows = new ArrayList<>(); this.saveFile = saveFile;
this.wb = new HSSFWorkbook(); this.dataRows = new ArrayList<>();
this.sheet = wb.createSheet(); this.headerRows = new ArrayList<>();
this.createHelper = wb.getCreationHelper();
this.styles = this.generateStyles(); this.wb = new HSSFWorkbook();
this.sheet = wb.createSheet();
this.createHelper = wb.getCreationHelper();
this.styles = this.generateStyles();
}
private void sortInforme() {
this.informe.sort(Comparator.comparing(InformeLibroDeVentasContent::getFecha));
}
private void fillHeaders() {
Row titles = sheet.createRow(0);
Row subtitles = sheet.createRow(1);
headerRows.add(titles);
headerRows.add(subtitles);
for (int x = 0; x < this.titles.length; x++) {
titles.createCell(x).setCellValue(this.titles[x]);
} }
private void sortInforme() { for (int x = 0; x < this.subtitles.length; x++) {
this.informe.sort(Comparator.comparing(InformeLibroDeVentasContent::getFecha)); subtitles.createCell(x).setCellValue(this.subtitles[x]);
}
}
private void fillData() {
int rowCounter = 2;
for (InformeLibroDeVentasContent data : this.informe) {
int cellCounter = 0;
Row dataRow = sheet.createRow(rowCounter);
dataRows.add(dataRow);
Date fecha = Date.from(data.getFecha().atStartOfDay(ZoneId.systemDefault()).toInstant());
dataRow.createCell(cellCounter++).setCellValue(this.dias[data.getDia()]);
dataRow.createCell(cellCounter++).setCellValue(fecha);
dataRow.createCell(cellCounter++)
.setCellValue(data.getManualesInicial() == null ? "0" : data.getManualesInicial());
dataRow.createCell(cellCounter++)
.setCellValue(data.getManualesFinal() == null ? "0" : data.getManualesFinal());
dataRow.createCell(cellCounter++).setCellValue(data.getManuales());
dataRow.createCell(cellCounter++)
.setCellValue(data.getFiscalesZInicial() == null ? "0" : data.getFiscalesZInicial());
dataRow.createCell(cellCounter++)
.setCellValue(data.getFiscalesZFinal() == null ? "0" : data.getFiscalesZFinal());
dataRow.createCell(cellCounter++)
.setCellValue(data.getFiscalesInicial() == null ? "0" : data.getFiscalesInicial());
dataRow.createCell(cellCounter++)
.setCellValue(data.getFiscalesFinal() == null ? "0" : data.getFiscalesFinal());
dataRow.createCell(cellCounter++).setCellValue(data.getFiscales());
dataRow.createCell(cellCounter++)
.setCellValue(data.getExentasInicial() == null ? "0" : data.getExentasInicial());
dataRow.createCell(cellCounter++)
.setCellValue(data.getExentasFinal() == null ? "0" : data.getExentasFinal());
dataRow.createCell(cellCounter++).setCellValue(data.getExentas());
dataRow.createCell(cellCounter++).setCellValue(data.getSubTotal());
dataRow.createCell(cellCounter++)
.setCellValue(data.getFacturasInicial() == null ? "0" : data.getFacturasInicial());
dataRow.createCell(cellCounter++)
.setCellValue(data.getFacturasFinal() == null ? "0" : data.getFacturasFinal());
dataRow.createCell(cellCounter++).setCellValue(data.getFacturas());
dataRow.createCell(cellCounter++)
.setCellValue(data.getGuiasInicial() == null ? "0" : data.getGuiasInicial());
dataRow.createCell(cellCounter++)
.setCellValue(data.getGuiasFinal() == null ? "0" : data.getGuiasFinal());
dataRow.createCell(cellCounter++).setCellValue(data.getGuias());
dataRow.createCell(cellCounter++).setCellValue(data.getTotal());
if (rowCounter == 2) {
dataRow.createCell(cellCounter).setCellFormula(("U" + (rowCounter + 1)));
} else {
dataRow.createCell(cellCounter)
.setCellFormula(("U" + (rowCounter + 1)) + ("+") + ("V" + (rowCounter)));
}
rowCounter++;
}
}
private void fillTotales() {
int row = 2 + this.informe.size();
this.footerRow = sheet.createRow(row);
this.footerRow.createCell(0).setCellValue("TOTALES");
this.footerRow.createCell(4).setCellFormula("SUM(E" + 3 + ":E" + row + ")");
this.footerRow.createCell(9).setCellFormula("SUM(J" + 3 + ":J" + row + ")");
this.footerRow.createCell(12).setCellFormula("SUM(M" + 3 + ":M" + row + ")");
this.footerRow.createCell(16).setCellFormula("SUM(Q" + 3 + ":Q" + row + ")");
this.footerRow.createCell(19).setCellFormula("SUM(T" + 3 + ":T" + row + ")");
}
private void joinCells() {
this.sheet.addMergedRegion(new CellRangeAddress(0, 0, 2, 4));
this.sheet.addMergedRegion(new CellRangeAddress(0, 0, 5, 9));
this.sheet.addMergedRegion(new CellRangeAddress(0, 0, 10, 12));
this.sheet.addMergedRegion(new CellRangeAddress(0, 0, 14, 16));
this.sheet.addMergedRegion(new CellRangeAddress(0, 0, 17, 19));
this.sheet.addMergedRegion(new CellRangeAddress(0, 0, 20, 22));
}
private void freezeCells() {
this.sheet.createFreezePane(2, 2);
}
private void addBorders() {
int row = 2 + informe.size();
PropertyTemplate pt = new PropertyTemplate();
//Bordes internos
pt.drawBorders(new CellRangeAddress(2, row - 1, 0, 22), BorderStyle.THIN, BorderExtent.ALL);
//Bordes de los headers
pt.drawBorders(new CellRangeAddress(0, 1, 0, 1), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(0, 1, 2, 4), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(0, 1, 5, 9), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(0, 1, 10, 12), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(0, 1, 13, 13), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(0, 1, 14, 16), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(0, 1, 17, 19), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(0, 1, 20, 22), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
//Bordes que agrupan
pt.drawBorders(new CellRangeAddress(2, row, 0, 1), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(2, row, 2, 4), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(2, row, 5, 9), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(2, row, 10, 12), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(2, row, 13, 13), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(2, row, 14, 16), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(2, row, 17, 19), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(2, row, 20, 22), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
//Bordes del total
pt.drawBorders(new CellRangeAddress(row, row, 0, 22), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.applyBorders(this.sheet);
}
private void setStyles() {
//Estilos para los 2 filas de titulos
for (Row header : headerRows) {
Iterator<Cell> cellIterator = header.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
cell.setCellStyle(this.styles.get("header"));
}
} }
private void fillHeaders() { //Estilos para las celdas de los datos
Row titles = sheet.createRow(0); for (Row row : dataRows) {
Row subtitles = sheet.createRow(1); int y = 0;
headerRows.add(titles); //Primeras Celdas
headerRows.add(subtitles); row.getCell(y++).setCellStyle(this.styles.get("dia"));
row.getCell(y++).setCellStyle(this.styles.get("date"));
for (int x = 0; x < this.titles.length; x++) { //Boletas Manuales
titles.createCell(x).setCellValue(this.titles[x]); row.getCell(y++).setCellStyle(this.styles.get("regular"));
} row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("money"));
for (int x = 0; x < this.subtitles.length; x++) { //Boletas Fiscales
subtitles.createCell(x).setCellValue(this.subtitles[x]); row.getCell(y++).setCellStyle(this.styles.get("regular"));
} row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("money"));
//Boletas Exentas
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("money"));
//Sub Total
row.getCell(y++).setCellStyle(this.styles.get("money"));
//Facturas
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("money"));
//Guias
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("money"));
//Estadisticas
row.getCell(y++).setCellStyle(this.styles.get("money"));
row.getCell(y).setCellStyle(this.styles.get("money"));
} }
private void fillData() { //Estilos para los totales del footer
int rowCounter = 2; for (int x = 0; x < 23; x++) {
this.footerRow.getCell(x, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK)
.setCellStyle(this.styles.get("footer"));
}
this.footerRow.getCell(4).setCellStyle(this.styles.get("footer_money"));
this.footerRow.getCell(9).setCellStyle(this.styles.get("footer_money"));
this.footerRow.getCell(12).setCellStyle(this.styles.get("footer_money"));
this.footerRow.getCell(16).setCellStyle(this.styles.get("footer_money"));
this.footerRow.getCell(19).setCellStyle(this.styles.get("footer_money"));
for (InformeLibroDeVentasContent data : this.informe) { //Setea la altura para todas las filas
int cellCounter = 0; this.headerRows.get(0).setHeightInPoints(20);
Row dataRow = sheet.createRow(rowCounter); this.headerRows.get(1).setHeightInPoints(30);
dataRows.add(dataRow); this.footerRow.setHeightInPoints(20);
Date fecha = Date.from(data.getFecha().atStartOfDay(ZoneId.systemDefault()).toInstant());
dataRow.createCell(cellCounter++).setCellValue(this.dias[data.getDia()]); for (Row row : dataRows) {
dataRow.createCell(cellCounter++).setCellValue(fecha); row.setHeightInPoints(15);
dataRow.createCell(cellCounter++).setCellValue(data.getManualesInicial() == null ? "0" : data.getManualesInicial());
dataRow.createCell(cellCounter++).setCellValue(data.getManualesFinal() == null ? "0" : data.getManualesFinal());
dataRow.createCell(cellCounter++).setCellValue(data.getManuales());
dataRow.createCell(cellCounter++).setCellValue(data.getFiscalesZInicial() == null ? "0" : data.getFiscalesZInicial());
dataRow.createCell(cellCounter++).setCellValue(data.getFiscalesZFinal() == null ? "0" : data.getFiscalesZFinal());
dataRow.createCell(cellCounter++).setCellValue(data.getFiscalesInicial() == null ? "0" : data.getFiscalesInicial());
dataRow.createCell(cellCounter++).setCellValue(data.getFiscalesFinal() == null ? "0" : data.getFiscalesFinal());
dataRow.createCell(cellCounter++).setCellValue(data.getFiscales());
dataRow.createCell(cellCounter++).setCellValue(data.getExentasInicial() == null ? "0" : data.getExentasInicial());
dataRow.createCell(cellCounter++).setCellValue(data.getExentasFinal() == null ? "0" : data.getExentasFinal());
dataRow.createCell(cellCounter++).setCellValue(data.getExentas());
dataRow.createCell(cellCounter++).setCellValue(data.getSubTotal());
dataRow.createCell(cellCounter++).setCellValue(data.getFacturasInicial() == null ? "0" : data.getFacturasInicial());
dataRow.createCell(cellCounter++).setCellValue(data.getFacturasFinal() == null ? "0" : data.getFacturasFinal());
dataRow.createCell(cellCounter++).setCellValue(data.getFacturas());
dataRow.createCell(cellCounter++).setCellValue(data.getGuiasInicial() == null ? "0" : data.getGuiasInicial());
dataRow.createCell(cellCounter++).setCellValue(data.getGuiasFinal() == null ? "0" : data.getGuiasFinal());
dataRow.createCell(cellCounter++).setCellValue(data.getGuias());
dataRow.createCell(cellCounter++).setCellValue(data.getTotal());
if (rowCounter == 2) {
dataRow.createCell(cellCounter).setCellFormula(("U" + (rowCounter + 1)));
} else {
dataRow.createCell(cellCounter).setCellFormula(("U" + (rowCounter + 1)) + ("+") + ("V" + (rowCounter)));
}
rowCounter++;
}
} }
private void fillTotales() { //Coloca el ancho como automatico en todas las columnas
int row = 2 + this.informe.size(); for (int x = 0; x <= 23; x++) {
this.footerRow = sheet.createRow(row); sheet.autoSizeColumn(x);
this.footerRow.createCell(0).setCellValue("TOTALES");
this.footerRow.createCell(4).setCellFormula("SUM(E" + 3 + ":E" + row + ")");
this.footerRow.createCell(9).setCellFormula("SUM(J" + 3 + ":J" + row + ")");
this.footerRow.createCell(12).setCellFormula("SUM(M" + 3 + ":M" + row + ")");
this.footerRow.createCell(16).setCellFormula("SUM(Q" + 3 + ":Q" + row + ")");
this.footerRow.createCell(19).setCellFormula("SUM(T" + 3 + ":T" + row + ")");
} }
}
private void joinCells() { public void generarInforme() {
this.sheet.addMergedRegion(new CellRangeAddress(0, 0, 2, 4)); sortInforme();
this.sheet.addMergedRegion(new CellRangeAddress(0, 0, 5, 9)); fillData();
this.sheet.addMergedRegion(new CellRangeAddress(0, 0, 10, 12)); fillHeaders();
this.sheet.addMergedRegion(new CellRangeAddress(0, 0, 14, 16)); fillTotales();
this.sheet.addMergedRegion(new CellRangeAddress(0, 0, 17, 19)); joinCells();
this.sheet.addMergedRegion(new CellRangeAddress(0, 0, 20, 22)); freezeCells();
setStyles();
addBorders();
try (OutputStream fileOut = Files.newOutputStream(this.saveFile)) {
wb.write(fileOut);
} catch (IOException e) {
e.printStackTrace();
} }
}
private void freezeCells() { private HashMap<String, CellStyle> generateStyles() {
this.sheet.createFreezePane(2, 2); Font font = this.wb.createFont();
} font.setBold(true);
font.setColor(IndexedColors.WHITE.getIndex());
private void addBorders() { CellStyle regularStyle = this.wb.createCellStyle();
int row = 2 + informe.size();
PropertyTemplate pt = new PropertyTemplate();
//Bordes internos CellStyle grayStyle = this.wb.createCellStyle();
pt.drawBorders(new CellRangeAddress(2, row - 1, 0, 22), BorderStyle.THIN, BorderExtent.ALL); grayStyle.setFont(font);
grayStyle.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
grayStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//Bordes de los headers CellStyle diaStyle = this.wb.createCellStyle();
pt.drawBorders(new CellRangeAddress(0, 1, 0, 1), BorderStyle.MEDIUM, BorderExtent.OUTSIDE); diaStyle.cloneStyleFrom(grayStyle);
pt.drawBorders(new CellRangeAddress(0, 1, 2, 4), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(0, 1, 5, 9), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(0, 1, 10, 12), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(0, 1, 13, 13), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(0, 1, 14, 16), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(0, 1, 17, 19), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(0, 1, 20, 22), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
//Bordes que agrupan CellStyle dateStyle = this.wb.createCellStyle();
pt.drawBorders(new CellRangeAddress(2, row, 0, 1), BorderStyle.MEDIUM, BorderExtent.OUTSIDE); dateStyle.cloneStyleFrom(grayStyle);
pt.drawBorders(new CellRangeAddress(2, row, 2, 4), BorderStyle.MEDIUM, BorderExtent.OUTSIDE); dateStyle.setDataFormat(this.createHelper.createDataFormat().getFormat("dd/mm/yyyy"));
pt.drawBorders(new CellRangeAddress(2, row, 5, 9), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(2, row, 10, 12), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(2, row, 13, 13), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(2, row, 14, 16), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(2, row, 17, 19), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
pt.drawBorders(new CellRangeAddress(2, row, 20, 22), BorderStyle.MEDIUM, BorderExtent.OUTSIDE);
CellStyle moneyStyle = this.wb.createCellStyle();
moneyStyle
.setDataFormat(this.createHelper.createDataFormat().getFormat("\"$\"#,##0_);(\"$\"#,##0)"));
//Bordes del total CellStyle headerStyle = this.wb.createCellStyle();
pt.drawBorders(new CellRangeAddress(row, row, 0, 22), BorderStyle.MEDIUM, BorderExtent.OUTSIDE); headerStyle.cloneStyleFrom(grayStyle);
headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
headerStyle.setAlignment(HorizontalAlignment.CENTER);
pt.applyBorders(this.sheet); CellStyle footerStyle = this.wb.createCellStyle();
} footerStyle.cloneStyleFrom(grayStyle);
footerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
private void setStyles() { CellStyle footerMoneyStyle = this.wb.createCellStyle();
//Estilos para los 2 filas de titulos footerMoneyStyle.cloneStyleFrom(footerStyle);
for(Row header: headerRows){ footerMoneyStyle
Iterator<Cell> cellIterator = header.cellIterator(); .setDataFormat(this.createHelper.createDataFormat().getFormat("\"$\"#,##0_);(\"$\"#,##0)"));
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
cell.setCellStyle(this.styles.get("header"));
}
}
//Estilos para las celdas de los datos HashMap<String, CellStyle> styles = new HashMap<>();
for (Row row: dataRows) { styles.put("regular", regularStyle);
int y = 0; styles.put("date", dateStyle);
styles.put("dia", diaStyle);
styles.put("money", moneyStyle);
styles.put("header", headerStyle);
styles.put("footer", footerStyle);
styles.put("footer_money", footerMoneyStyle);
//Primeras Celdas return styles;
row.getCell(y++).setCellStyle(this.styles.get("dia")); }
row.getCell(y++).setCellStyle(this.styles.get("date"));
//Boletas Manuales
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("money"));
//Boletas Fiscales
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("money"));
//Boletas Exentas
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("money"));
//Sub Total
row.getCell(y++).setCellStyle(this.styles.get("money"));
//Facturas
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("money"));
//Guias
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("regular"));
row.getCell(y++).setCellStyle(this.styles.get("money"));
//Estadisticas
row.getCell(y++).setCellStyle(this.styles.get("money"));
row.getCell(y).setCellStyle(this.styles.get("money"));
}
//Estilos para los totales del footer
for (int x = 0; x < 23; x++) {
this.footerRow.getCell(x, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellStyle(this.styles.get("footer"));
}
this.footerRow.getCell(4).setCellStyle(this.styles.get("footer_money"));
this.footerRow.getCell(9).setCellStyle(this.styles.get("footer_money"));
this.footerRow.getCell(12).setCellStyle(this.styles.get("footer_money"));
this.footerRow.getCell(16).setCellStyle(this.styles.get("footer_money"));
this.footerRow.getCell(19).setCellStyle(this.styles.get("footer_money"));
//Setea la altura para todas las filas
this.headerRows.get(0).setHeightInPoints(20);
this.headerRows.get(1).setHeightInPoints(30);
this.footerRow.setHeightInPoints(20);
for (Row row: dataRows) {
row.setHeightInPoints(15);
}
//Coloca el ancho como automatico en todas las columnas
for (int x = 0; x <= 23; x++) {
sheet.autoSizeColumn(x);
}
}
public void generarInforme() {
sortInforme();
fillData();
fillHeaders();
fillTotales();
joinCells();
freezeCells();
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 diaStyle = this.wb.createCellStyle();
diaStyle.cloneStyleFrom(grayStyle);
CellStyle dateStyle = this.wb.createCellStyle();
dateStyle.cloneStyleFrom(grayStyle);
dateStyle.setDataFormat(this.createHelper.createDataFormat().getFormat("dd/mm/yyyy"));
CellStyle moneyStyle = this.wb.createCellStyle();
moneyStyle.setDataFormat(this.createHelper.createDataFormat().getFormat("\"$\"#,##0_);(\"$\"#,##0)"));
CellStyle headerStyle = this.wb.createCellStyle();
headerStyle.cloneStyleFrom(grayStyle);
headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
headerStyle.setAlignment(HorizontalAlignment.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("date", dateStyle);
styles.put("dia", diaStyle);
styles.put("money", moneyStyle);
styles.put("header", headerStyle);
styles.put("footer", footerStyle);
styles.put("footer_money", footerMoneyStyle);
return styles;
}
} }

View File

@@ -27,39 +27,40 @@ package danielcortes.xyz.models.caja;
import java.time.LocalDate; import java.time.LocalDate;
public class Caja { public class Caja {
private int id;
private LocalDate fecha;
private int fondo;
public int getId() { private int id;
return id; private LocalDate fecha;
} private int fondo;
public void setId(int id) { public int getId() {
this.id = id; return id;
} }
public LocalDate getFecha() { public void setId(int id) {
return fecha; this.id = id;
} }
public void setFecha(LocalDate fecha) { public LocalDate getFecha() {
this.fecha = fecha; return fecha;
} }
public int getFondo() { public void setFecha(LocalDate fecha) {
return fondo; this.fecha = fecha;
} }
public void setFondo(int fondo) { public int getFondo() {
this.fondo = fondo; return fondo;
} }
@Override public void setFondo(int fondo) {
public String toString() { this.fondo = fondo;
return "Caja{" + }
"id=" + id +
", fecha=" + fecha + @Override
'}'; public String toString() {
} return "Caja{" +
"id=" + id +
", fecha=" + fecha +
'}';
}
} }

View File

@@ -30,18 +30,19 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
public interface CajaDAO { public interface CajaDAO {
List<Caja> getAll();
Optional<Caja> getById(int id); List<Caja> getAll();
Optional<Caja> getByFecha(LocalDate fecha); Optional<Caja> getById(int id);
void insert(Caja caja); Optional<Caja> getByFecha(LocalDate fecha);
void insert(List<Caja> cajas); void insert(Caja caja);
void update(Caja caja); void insert(List<Caja> cajas);
void createCajasForMonth(YearMonth month); void update(Caja caja);
void createCajasForMonth(YearMonth month);
} }

View File

@@ -28,7 +28,6 @@ import danielcortes.xyz.data.DAOManager;
import danielcortes.xyz.data.SQLiteConnectionHolder; import danielcortes.xyz.data.SQLiteConnectionHolder;
import danielcortes.xyz.models.documentos.Documentos; import danielcortes.xyz.models.documentos.Documentos;
import danielcortes.xyz.models.efectivo.Efectivo; import danielcortes.xyz.models.efectivo.Efectivo;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@@ -42,186 +41,189 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public class SQLiteCajaDAO implements CajaDAO { public class SQLiteCajaDAO implements CajaDAO {
private static final Logger LOGGER = Logger.getLogger(SQLiteCajaDAO.class.getName());
private SQLiteConnectionHolder connectionHolder; private static final Logger LOGGER = Logger.getLogger(SQLiteCajaDAO.class.getName());
public SQLiteCajaDAO() { private SQLiteConnectionHolder connectionHolder;
this.connectionHolder = new SQLiteConnectionHolder();
public SQLiteCajaDAO() {
this.connectionHolder = new SQLiteConnectionHolder();
}
@Override
public List<Caja> getAll() {
List<Caja> cajaList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from caja";
PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", new Object[]{query});
while (rs.next()) {
Caja caja = new Caja();
caja.setId(rs.getInt("id"));
caja.setFecha(LocalDate.parse(rs.getString("fecha")));
caja.setFondo(rs.getInt("fondo"));
cajaList.add(caja);
}
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
} }
@Override return cajaList;
public List<Caja> getAll() { }
List<Caja> cajaList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from caja";
PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", new Object[]{query}); @Override
public Optional<Caja> getById(int id) {
Caja caja = null;
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from caja where id = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
while (rs.next()) { LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id});
Caja caja = new Caja();
caja.setId(rs.getInt("id"));
caja.setFecha(LocalDate.parse(rs.getString("fecha")));
caja.setFondo(rs.getInt("fondo"));
cajaList.add(caja);
}
rs.close(); while (rs.next()) {
ps.close(); caja = new Caja();
} catch (SQLException e) { caja.setId(rs.getInt("id"));
LOGGER.log(Level.SEVERE, e.toString(), e); caja.setFecha(LocalDate.parse(rs.getString("fecha")));
} caja.setFondo(rs.getInt("fondo"));
}
return cajaList; rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
return Optional.ofNullable(caja);
}
@Override
public Optional<Caja> getByFecha(LocalDate fecha) {
Caja caja = null;
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from caja where fecha = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, fecha.toString());
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, fecha});
while (rs.next()) {
caja = new Caja();
caja.setId(rs.getInt("id"));
caja.setFecha(LocalDate.parse(rs.getString("fecha")));
caja.setFondo(rs.getInt("fondo"));
}
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
return Optional.ofNullable(caja);
}
@Override
public void insert(Caja caja) {
try (Connection conn = connectionHolder.getConnection()) {
String query = "insert into caja (fecha, fondo) values (?, ?)";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, caja.getFecha().toString());
ps.setInt(2, caja.getFondo());
ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}, {2}",
new Object[]{query, caja.getFecha(), caja.getFondo()});
ps.close();
query = "select last_insert_rowid()";
ps = conn.prepareStatement("select last_insert_rowid()");
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", new Object[]{query});
rs.next();
caja.setId(rs.getInt(1));
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
}
@Override
public void insert(List<Caja> cajas) {
String query = "insert into caja (fecha, fondo) values (?, ?)";
try (Connection conn = connectionHolder.getConnection(); PreparedStatement ps = conn
.prepareStatement(query)) {
for (Caja caja : cajas) {
ps.setString(1, caja.getFecha().toString());
ps.setInt(2, caja.getFondo());
ps.addBatch();
}
ps.executeBatch();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
}
@Override
public void update(Caja caja) {
try (Connection conn = connectionHolder.getConnection()) {
String query = "update caja set fecha = ?, fondo = ? where id = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, caja.getFecha().toString());
ps.setInt(2, caja.getFondo());
ps.setInt(3, caja.getId());
ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}, {2}, {3}",
new Object[]{query, caja.getFecha(), caja.getFondo(), caja.getId()});
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
}
@Override
public void createCajasForMonth(YearMonth mes) {
LocalDate startDate = mes.atDay(1);
LocalDate endDatePlusOne = mes.atEndOfMonth().plusDays(1);
List<Caja> cajas = new ArrayList<>();
while (startDate.isBefore(endDatePlusOne)) {
if (this.getByFecha(startDate).isPresent()) {
startDate = startDate.plusDays(1);
} else {
Caja caja = new Caja();
caja.setFecha(startDate);
cajas.add(caja);
startDate = startDate.plusDays(1);
}
} }
@Override this.insert(cajas);
public Optional<Caja> getById(int id) {
Caja caja = null;
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from caja where id = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id}); for (Caja caja : cajas) {
Efectivo efectivo = new Efectivo();
efectivo.setCaja(caja);
DAOManager.getEfectivoDAO().insertDefaultEfectivo(efectivo);
while (rs.next()) { Documentos documentos = new Documentos();
caja = new Caja(); documentos.setCaja(caja);
caja.setId(rs.getInt("id")); DAOManager.getDocumentosDAO().insertDefaultDocumentos(documentos);
caja.setFecha(LocalDate.parse(rs.getString("fecha")));
caja.setFondo(rs.getInt("fondo"));
}
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
return Optional.ofNullable(caja);
}
@Override
public Optional<Caja> getByFecha(LocalDate fecha) {
Caja caja = null;
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from caja where fecha = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, fecha.toString());
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, fecha});
while (rs.next()) {
caja = new Caja();
caja.setId(rs.getInt("id"));
caja.setFecha(LocalDate.parse(rs.getString("fecha")));
caja.setFondo(rs.getInt("fondo"));
}
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
return Optional.ofNullable(caja);
}
@Override
public void insert(Caja caja) {
try (Connection conn = connectionHolder.getConnection()) {
String query = "insert into caja (fecha, fondo) values (?, ?)";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, caja.getFecha().toString());
ps.setInt(2, caja.getFondo());
ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}, {2}", new Object[]{query, caja.getFecha(), caja.getFondo()});
ps.close();
query = "select last_insert_rowid()";
ps = conn.prepareStatement("select last_insert_rowid()");
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", new Object[]{query});
rs.next();
caja.setId(rs.getInt(1));
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
}
@Override
public void insert(List<Caja> cajas){
String query = "insert into caja (fecha, fondo) values (?, ?)";
try (Connection conn = connectionHolder.getConnection();PreparedStatement ps = conn.prepareStatement(query)) {
for(Caja caja: cajas){
ps.setString(1, caja.getFecha().toString());
ps.setInt(2, caja.getFondo());
ps.addBatch();
}
ps.executeBatch();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
}
@Override
public void update(Caja caja) {
try (Connection conn = connectionHolder.getConnection()) {
String query = "update caja set fecha = ?, fondo = ? where id = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, caja.getFecha().toString());
ps.setInt(2, caja.getFondo());
ps.setInt(3, caja.getId());
ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}, {2}, {3}", new Object[]{query, caja.getFecha(), caja.getFondo(), caja.getId()});
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
}
@Override
public void createCajasForMonth(YearMonth mes) {
LocalDate startDate = mes.atDay(1);
LocalDate endDatePlusOne = mes.atEndOfMonth().plusDays(1);
List<Caja> cajas = new ArrayList<>();
while (startDate.isBefore(endDatePlusOne)) {
if (this.getByFecha(startDate).isPresent()){
startDate = startDate.plusDays(1);
}else{
Caja caja = new Caja();
caja.setFecha(startDate);
cajas.add(caja);
startDate = startDate.plusDays(1);
}
}
this.insert(cajas);
for(Caja caja: cajas){
Efectivo efectivo = new Efectivo();
efectivo.setCaja(caja);
DAOManager.getEfectivoDAO().insertDefaultEfectivo(efectivo);
Documentos documentos = new Documentos();
documentos.setCaja(caja);
DAOManager.getDocumentosDAO().insertDefaultDocumentos(documentos);
}
} }
}
} }

View File

@@ -27,50 +27,51 @@ package danielcortes.xyz.models.calculo_fondo;
import danielcortes.xyz.models.caja.Caja; import danielcortes.xyz.models.caja.Caja;
public class CalculoFondo { public class CalculoFondo {
private int id;
private int valor;
private String descripcion;
private Caja caja;
public int getId() { private int id;
return id; private int valor;
} private String descripcion;
private Caja caja;
public void setId(int id) { public int getId() {
this.id = id; return id;
} }
public int getValor() { public void setId(int id) {
return valor; this.id = id;
} }
public void setValor(int valor) { public int getValor() {
this.valor = valor; return valor;
} }
public String getDescripcion() { public void setValor(int valor) {
return descripcion; this.valor = valor;
} }
public void setDescripcion(String descripcion) { public String getDescripcion() {
this.descripcion = descripcion; return descripcion;
} }
public Caja getCaja() { public void setDescripcion(String descripcion) {
return caja; this.descripcion = descripcion;
} }
public void setCaja(Caja caja) { public Caja getCaja() {
this.caja = caja; return caja;
} }
@Override public void setCaja(Caja caja) {
public String toString() { this.caja = caja;
return "CalculoFondo{" + }
"id=" + id +
", valor=" + valor + @Override
", descripcion='" + descripcion + '\'' + public String toString() {
", caja=" + caja + return "CalculoFondo{" +
'}'; "id=" + id +
} ", valor=" + valor +
", descripcion='" + descripcion + '\'' +
", caja=" + caja +
'}';
}
} }

View File

@@ -27,7 +27,6 @@ package danielcortes.xyz.models.calculo_fondo;
import danielcortes.xyz.data.ConnectionHolder; import danielcortes.xyz.data.ConnectionHolder;
import danielcortes.xyz.models.caja.Caja; import danielcortes.xyz.models.caja.Caja;
import danielcortes.xyz.models.caja.SQLiteCajaDAO; import danielcortes.xyz.models.caja.SQLiteCajaDAO;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@@ -36,39 +35,40 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public abstract class CalculoFondoDAO { public abstract class CalculoFondoDAO {
private static final Logger LOGGER = Logger.getLogger(CalculoFondoDAO.class.getName());
protected ConnectionHolder connectionHolder; private static final Logger LOGGER = Logger.getLogger(CalculoFondoDAO.class.getName());
public abstract List<CalculoFondo> findAll(); protected ConnectionHolder connectionHolder;
public abstract List<CalculoFondo> findByCaja(Caja caja); public abstract List<CalculoFondo> findAll();
public abstract CalculoFondo findById(int id); public abstract List<CalculoFondo> findByCaja(Caja caja);
public abstract boolean insertCalculoFondo(CalculoFondo calculoFondo); public abstract CalculoFondo findById(int id);
public abstract boolean updateCalculoFondo(CalculoFondo calculoFondo); public abstract boolean insertCalculoFondo(CalculoFondo calculoFondo);
public abstract boolean deleteCalculoFondo(CalculoFondo calculoFondo); public abstract boolean updateCalculoFondo(CalculoFondo calculoFondo);
public abstract int getTotalCalculoFondo(Caja caja); public abstract boolean deleteCalculoFondo(CalculoFondo calculoFondo);
protected List<CalculoFondo> calculoFondoFromResultSet(ResultSet rs) throws SQLException { public abstract int getTotalCalculoFondo(Caja caja);
List<CalculoFondo> calculoFondoList = new ArrayList<>();
while (rs.next()) {
int caja_id = rs.getInt("caja_id");
Caja caja = new SQLiteCajaDAO().getById(caja_id).get();
CalculoFondo calculoFondo = new CalculoFondo();
calculoFondo.setId(rs.getInt("id"));
calculoFondo.setValor(rs.getInt("valor"));
calculoFondo.setDescripcion(rs.getString("descripcion"));
calculoFondo.setCaja(caja);
calculoFondoList.add(calculoFondo);
LOGGER.log(Level.FINER, "Se a creo: {0}", calculoFondo); protected List<CalculoFondo> calculoFondoFromResultSet(ResultSet rs) throws SQLException {
List<CalculoFondo> calculoFondoList = new ArrayList<>();
while (rs.next()) {
int caja_id = rs.getInt("caja_id");
Caja caja = new SQLiteCajaDAO().getById(caja_id).get();
CalculoFondo calculoFondo = new CalculoFondo();
calculoFondo.setId(rs.getInt("id"));
calculoFondo.setValor(rs.getInt("valor"));
calculoFondo.setDescripcion(rs.getString("descripcion"));
calculoFondo.setCaja(caja);
calculoFondoList.add(calculoFondo);
LOGGER.log(Level.FINER, "Se a creo: {0}", calculoFondo);
}
return calculoFondoList;
} }
return calculoFondoList;
}
} }

View File

@@ -26,7 +26,6 @@ package danielcortes.xyz.models.calculo_fondo;
import danielcortes.xyz.data.SQLiteConnectionHolder; import danielcortes.xyz.data.SQLiteConnectionHolder;
import danielcortes.xyz.models.caja.Caja; import danielcortes.xyz.models.caja.Caja;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@@ -37,165 +36,170 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public class SQLiteCalculoFondoDAO extends CalculoFondoDAO { public class SQLiteCalculoFondoDAO extends CalculoFondoDAO {
private static final Logger LOGGER = Logger.getLogger(SQLiteCalculoFondoDAO.class.getName());
public SQLiteCalculoFondoDAO() { private static final Logger LOGGER = Logger.getLogger(SQLiteCalculoFondoDAO.class.getName());
this.connectionHolder = new SQLiteConnectionHolder();
public SQLiteCalculoFondoDAO() {
this.connectionHolder = new SQLiteConnectionHolder();
}
@Override
public List<CalculoFondo> findAll() {
List<CalculoFondo> calculoFondoList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from calculo_fondo";
PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", query);
calculoFondoList = this.calculoFondoFromResultSet(rs);
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
} }
return calculoFondoList;
}
@Override @Override
public List<CalculoFondo> findAll() { public List<CalculoFondo> findByCaja(Caja caja) {
List<CalculoFondo> calculoFondoList = new ArrayList<>(); List<CalculoFondo> calculoFondoList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from calculo_fondo"; String query = "select * from calculo_fondo where caja_id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery(); ps.setInt(1, caja.getId());
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", query); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()});
calculoFondoList = this.calculoFondoFromResultSet(rs); calculoFondoList = this.calculoFondoFromResultSet(rs);
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); LOGGER.log(Level.SEVERE, e.toString(), e);
}
return calculoFondoList;
} }
return calculoFondoList;
}
@Override @Override
public List<CalculoFondo> findByCaja(Caja caja) { public CalculoFondo findById(int id) {
List<CalculoFondo> calculoFondoList = new ArrayList<>(); CalculoFondo calculoFondo = null;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from calculo_fondo where caja_id = ?"; String query = "select * from calculo_fondo where id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, caja.getId()); ps.setInt(1, id);
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id});
calculoFondoList = this.calculoFondoFromResultSet(rs); calculoFondo = this.calculoFondoFromResultSet(rs).get(0);
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); LOGGER.log(Level.SEVERE, e.toString(), e);
}
return calculoFondoList;
} }
return calculoFondo;
}
@Override @Override
public CalculoFondo findById(int id) { public boolean insertCalculoFondo(CalculoFondo calculoFondo) {
CalculoFondo calculoFondo = null; int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from calculo_fondo where id = ?"; String query = "insert into calculo_fondo (valor, descripcion, caja_id) values (?, ?, ?)";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, id); ps.setInt(1, calculoFondo.getValor());
ResultSet rs = ps.executeQuery(); ps.setString(2, calculoFondo.getDescripcion());
ps.setInt(3, calculoFondo.getCaja().getId());
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id}); updates = ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY {0} | values: [{1}, {2}, {3}] | updates: {4}",
new Object[]{query, calculoFondo.getValor(), calculoFondo.getDescripcion(),
calculoFondo.getCaja().getId(), updates});
calculoFondo = this.calculoFondoFromResultSet(rs).get(0); ps.close();
rs.close(); ps = conn.prepareStatement("select last_insert_rowid()");
ps.close(); ResultSet rs = ps.executeQuery();
} catch (SQLException e) { LOGGER.log(Level.FINE, "Se ejecuta query: {0}", query);
LOGGER.log(Level.SEVERE, e.toString(), e);
} rs.next();
return calculoFondo; calculoFondo.setId(rs.getInt(1));
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
return false;
} }
return updates > 0;
}
@Override @Override
public boolean insertCalculoFondo(CalculoFondo calculoFondo) { public boolean updateCalculoFondo(CalculoFondo calculoFondo) {
int updates; int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "insert into calculo_fondo (valor, descripcion, caja_id) values (?, ?, ?)"; String query = "update calculo_fondo set valor = ?, descripcion = ?, caja_id = ? where id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, calculoFondo.getValor()); ps.setInt(1, calculoFondo.getValor());
ps.setString(2, calculoFondo.getDescripcion()); ps.setString(2, calculoFondo.getDescripcion());
ps.setInt(3, calculoFondo.getCaja().getId()); ps.setInt(3, calculoFondo.getCaja().getId());
ps.setInt(4, calculoFondo.getId());
updates = ps.executeUpdate(); updates = ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY {0} | values: [{1}, {2}, {3}] | updates: {4}", new Object[]{query, calculoFondo.getValor(), calculoFondo.getDescripcion(), calculoFondo.getCaja().getId(), updates}); LOGGER.log(Level.FINE, "QUERY {0} | values: [{1}, {2}, {3}, {4}] | updates: {5}",
new Object[]{query, calculoFondo.getValor(), calculoFondo.getDescripcion(),
calculoFondo.getCaja().getId(), updates});
ps.close(); ps.close();
} catch (SQLException e) {
ps = conn.prepareStatement("select last_insert_rowid()"); LOGGER.log(Level.SEVERE, e.toString(), e);
ResultSet rs = ps.executeQuery(); return false;
LOGGER.log(Level.FINE, "Se ejecuta query: {0}", query);
rs.next();
calculoFondo.setId(rs.getInt(1));
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
return false;
}
return updates > 0;
} }
return updates > 0;
}
@Override @Override
public boolean updateCalculoFondo(CalculoFondo calculoFondo) { public boolean deleteCalculoFondo(CalculoFondo calculoFondo) {
int updates; int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "update calculo_fondo set valor = ?, descripcion = ?, caja_id = ? where id = ?"; String query = "delete from calculo_fondo where id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, calculoFondo.getValor()); ps.setInt(1, calculoFondo.getId());
ps.setString(2, calculoFondo.getDescripcion()); updates = ps.executeUpdate();
ps.setInt(3, calculoFondo.getCaja().getId());
ps.setInt(4, calculoFondo.getId());
updates = ps.executeUpdate(); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}",
LOGGER.log(Level.FINE, "QUERY {0} | values: [{1}, {2}, {3}, {4}] | updates: {5}", new Object[]{query, calculoFondo.getValor(), calculoFondo.getDescripcion(), calculoFondo.getCaja().getId(), updates}); new Object[]{query, calculoFondo.getId(), updates});
ps.close();
ps.close(); } catch (SQLException e) {
} catch (SQLException e) { LOGGER.log(Level.SEVERE, e.toString(), e);
LOGGER.log(Level.SEVERE, e.toString(), e); return false;
return false;
}
return updates > 0;
} }
return updates > 0;
}
@Override @Override
public boolean deleteCalculoFondo(CalculoFondo calculoFondo) { public int getTotalCalculoFondo(Caja caja) {
int updates; int sum = 0;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "delete from calculo_fondo where id = ?"; String query = "select sum(valor) from calculo_fondo where caja_id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, calculoFondo.getId()); ps.setInt(1, caja.getId());
updates = ps.executeUpdate(); ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}", new Object[]{query, calculoFondo.getId(), updates}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()});
ps.close(); rs.next();
} catch (SQLException e) { sum = rs.getInt(1);
LOGGER.log(Level.SEVERE, e.toString(), e);
return false; ps.close();
} } catch (SQLException e) {
return updates > 0; LOGGER.log(Level.SEVERE, e.toString(), e);
}
@Override
public int getTotalCalculoFondo(Caja caja) {
int sum = 0;
try (Connection conn = connectionHolder.getConnection()) {
String query = "select sum(valor) from calculo_fondo where caja_id = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, caja.getId());
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()});
rs.next();
sum = rs.getInt(1);
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
return sum;
} }
return sum;
}
} }

View File

@@ -27,60 +27,61 @@ package danielcortes.xyz.models.documentos;
import danielcortes.xyz.models.caja.Caja; import danielcortes.xyz.models.caja.Caja;
public class Documentos { public class Documentos {
private int id;
private int cheques;
private int tarjetas;
private int retiros;
private Caja caja;
public int getId() { private int id;
return id; private int cheques;
} private int tarjetas;
private int retiros;
private Caja caja;
public void setId(int id) { public int getId() {
this.id = id; return id;
} }
public int getCheques() { public void setId(int id) {
return cheques; this.id = id;
} }
public void setCheques(int cheques) { public int getCheques() {
this.cheques = cheques; return cheques;
} }
public int getTarjetas() { public void setCheques(int cheques) {
return tarjetas; this.cheques = cheques;
} }
public void setTarjetas(int tarjetas) { public int getTarjetas() {
this.tarjetas = tarjetas; return tarjetas;
} }
public int getRetiros() { public void setTarjetas(int tarjetas) {
return retiros; this.tarjetas = tarjetas;
} }
public void setRetiros(int retiros) { public int getRetiros() {
this.retiros = retiros; return retiros;
} }
public Caja getCaja() { public void setRetiros(int retiros) {
return caja; this.retiros = retiros;
} }
public void setCaja(Caja caja) { public Caja getCaja() {
this.caja = caja; return caja;
} }
@Override public void setCaja(Caja caja) {
public String toString() { this.caja = caja;
return "Documentos{" + }
"id=" + id +
", cheques=" + cheques + @Override
", tarjetas=" + tarjetas + public String toString() {
", retiros=" + retiros + return "Documentos{" +
", caja=" + caja + "id=" + id +
'}'; ", cheques=" + cheques +
} ", tarjetas=" + tarjetas +
", retiros=" + retiros +
", caja=" + caja +
'}';
}
} }

View File

@@ -28,7 +28,6 @@ import danielcortes.xyz.data.ConnectionHolder;
import danielcortes.xyz.models.caja.Caja; import danielcortes.xyz.models.caja.Caja;
import danielcortes.xyz.models.caja.CajaDAO; import danielcortes.xyz.models.caja.CajaDAO;
import danielcortes.xyz.models.caja.SQLiteCajaDAO; import danielcortes.xyz.models.caja.SQLiteCajaDAO;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@@ -37,44 +36,45 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public abstract class DocumentosDAO { public abstract class DocumentosDAO {
private static final Logger LOGGER = Logger.getLogger(DocumentosDAO.class.getName());
protected ConnectionHolder connectionHolder; private static final Logger LOGGER = Logger.getLogger(DocumentosDAO.class.getName());
public abstract List<Documentos> findAll(); protected ConnectionHolder connectionHolder;
public abstract Documentos findById(int id); public abstract List<Documentos> findAll();
public abstract Documentos findByCaja(Caja caja); public abstract Documentos findById(int id);
public abstract boolean insertDocumentos(Documentos documentos); public abstract Documentos findByCaja(Caja caja);
public abstract boolean insertDefaultDocumentos(Documentos documentos); public abstract boolean insertDocumentos(Documentos documentos);
public abstract boolean updateDocumentos(Documentos documentos); public abstract boolean insertDefaultDocumentos(Documentos documentos);
public abstract boolean deleteDocumentos(Documentos documentos); public abstract boolean updateDocumentos(Documentos documentos);
public abstract int getTotalDocumentos(Caja caja); public abstract boolean deleteDocumentos(Documentos documentos);
protected List<Documentos> documentosFromResultSet(ResultSet rs) throws SQLException { public abstract int getTotalDocumentos(Caja caja);
List<Documentos> documentosList = new ArrayList<>();
while (rs.next()) {
CajaDAO cajaDAO = new SQLiteCajaDAO();
Caja caja = cajaDAO.getById(rs.getInt("caja_id")).get();
Documentos documentos = new Documentos(); protected List<Documentos> documentosFromResultSet(ResultSet rs) throws SQLException {
documentos.setCaja(caja); List<Documentos> documentosList = new ArrayList<>();
documentos.setId(rs.getInt("id")); while (rs.next()) {
documentos.setCheques(rs.getInt("cheques")); CajaDAO cajaDAO = new SQLiteCajaDAO();
documentos.setTarjetas(rs.getInt("tarjetas")); Caja caja = cajaDAO.getById(rs.getInt("caja_id")).get();
documentos.setRetiros(rs.getInt("retiros"));
LOGGER.log(Level.FINER, "Se a creo: {0}", documentos); Documentos documentos = new Documentos();
documentos.setCaja(caja);
documentos.setId(rs.getInt("id"));
documentos.setCheques(rs.getInt("cheques"));
documentos.setTarjetas(rs.getInt("tarjetas"));
documentos.setRetiros(rs.getInt("retiros"));
documentosList.add(documentos); LOGGER.log(Level.FINER, "Se a creo: {0}", documentos);
documentosList.add(documentos);
}
return documentosList;
} }
return documentosList;
}
} }

View File

@@ -26,7 +26,6 @@ package danielcortes.xyz.models.documentos;
import danielcortes.xyz.data.SQLiteConnectionHolder; import danielcortes.xyz.data.SQLiteConnectionHolder;
import danielcortes.xyz.models.caja.Caja; import danielcortes.xyz.models.caja.Caja;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@@ -37,205 +36,212 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public class SQLiteDocumentosDAO extends DocumentosDAO { public class SQLiteDocumentosDAO extends DocumentosDAO {
private static final Logger LOGGER = Logger.getLogger(SQLiteDocumentosDAO.class.getName());
public SQLiteDocumentosDAO() { private static final Logger LOGGER = Logger.getLogger(SQLiteDocumentosDAO.class.getName());
this.connectionHolder = new SQLiteConnectionHolder();
public SQLiteDocumentosDAO() {
this.connectionHolder = new SQLiteConnectionHolder();
}
@Override
public List<Documentos> findAll() {
List<Documentos> documentosList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from documentos";
PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", query);
documentosList = this.documentosFromResultSet(rs);
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
} }
return documentosList;
}
@Override @Override
public List<Documentos> findAll() { public Documentos findById(int id) {
List<Documentos> documentosList = new ArrayList<>(); Documentos documentos = null;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from documentos"; String query = "select * from documentos where id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery(); ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", query); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id});
documentosList = this.documentosFromResultSet(rs); List<Documentos> documentosList = this.documentosFromResultSet(rs);
if (documentosList.size() > 0) {
documentos = documentosList.get(0);
}
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); LOGGER.log(Level.SEVERE, e.toString(), e);
}
return documentosList;
} }
return documentos;
}
@Override @Override
public Documentos findById(int id) { public Documentos findByCaja(Caja caja) {
Documentos documentos = null; Documentos documentos = null;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from documentos where id = ?"; String query = "select * from documentos where caja_id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, id); ps.setInt(1, caja.getId());
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()});
List<Documentos> documentosList = this.documentosFromResultSet(rs); List<Documentos> documentosList = this.documentosFromResultSet(rs);
if (documentosList.size() > 0) { if (documentosList.size() > 0) {
documentos = documentosList.get(0); documentos = documentosList.get(0);
} }
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); LOGGER.log(Level.SEVERE, e.toString(), e);
}
return documentos;
} }
return documentos;
}
@Override @Override
public Documentos findByCaja(Caja caja) { public boolean insertDocumentos(Documentos documentos) {
Documentos documentos = null; int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from documentos where caja_id = ?"; String query = "insert into documentos (cheques, tarjetas, retiros, caja_id) values (?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, caja.getId()); ps.setInt(1, documentos.getCheques());
ResultSet rs = ps.executeQuery(); ps.setInt(2, documentos.getTarjetas());
ps.setInt(3, documentos.getRetiros());
ps.setInt(4, documentos.getCaja().getId());
updates = ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()}); LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1}, {2}, {3}, {4}] | updates: {5}",
new Object[]{query, documentos.getCheques(), documentos.getTarjetas(),
documentos.getRetiros(), documentos.getCaja().getId(), updates});
List<Documentos> documentosList = this.documentosFromResultSet(rs); ps.close();
if (documentosList.size() > 0) {
documentos = documentosList.get(0);
}
rs.close(); query = "select last_insert_rowid()";
ps.close(); ps = conn.prepareStatement(query);
} catch (SQLException e) { ResultSet rs = ps.executeQuery();
LOGGER.log(Level.SEVERE, e.toString(), e);
} LOGGER.log(Level.FINE, "QUERY: {0}", query);
return documentos;
rs.next();
documentos.setId(rs.getInt(1));
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
return false;
} }
return updates > 0;
}
@Override @Override
public boolean insertDocumentos(Documentos documentos) { public boolean insertDefaultDocumentos(Documentos documentos) {
int updates; int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "insert into documentos (cheques, tarjetas, retiros, caja_id) values (?,?,?,?)"; String query = "insert into documentos (cheques, tarjetas, retiros, caja_id) values (0,0,0,?)";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, documentos.getCheques()); ps.setInt(1, documentos.getCaja().getId());
ps.setInt(2, documentos.getTarjetas()); updates = ps.executeUpdate();
ps.setInt(3, documentos.getRetiros());
ps.setInt(4, documentos.getCaja().getId());
updates = ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1}, {2}, {3}, {4}] | updates: {5}", new Object[]{query, documentos.getCheques(), documentos.getTarjetas(), documentos.getRetiros(), documentos.getCaja().getId(), updates}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}",
new Object[]{query, documentos.getCaja().getId(), updates});
ps.close(); ps.close();
query = "select last_insert_rowid()"; ps = conn.prepareStatement("select last_insert_rowid()");
ps = conn.prepareStatement(query); ResultSet rs = ps.executeQuery();
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", query); LOGGER.log(Level.FINE, "QUERY: {0}", query);
rs.next(); rs.next();
documentos.setId(rs.getInt(1)); documentos.setId(rs.getInt(1));
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); LOGGER.log(Level.SEVERE, e.toString(), e);
return false; return false;
}
return updates > 0;
} }
return updates > 0;
}
@Override @Override
public boolean insertDefaultDocumentos(Documentos documentos) { public boolean updateDocumentos(Documentos documentos) {
int updates; int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "insert into documentos (cheques, tarjetas, retiros, caja_id) values (0,0,0,?)"; String query = "update documentos set tarjetas = ?, cheques = ?, retiros = ?, caja_id = ? where id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, documentos.getCaja().getId()); ps.setInt(1, documentos.getTarjetas());
updates = ps.executeUpdate(); ps.setInt(2, documentos.getCheques());
ps.setInt(3, documentos.getRetiros());
ps.setInt(4, documentos.getCaja().getId());
ps.setInt(5, documentos.getId());
updates = ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}", new Object[]{query, documentos.getCaja().getId(), updates}); LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1}, {2}, {3}, {4}] | updates: {5}",
new Object[]{query, documentos.getCheques(), documentos.getTarjetas(),
documentos.getRetiros(), documentos.getCaja().getId(), documentos.getId(), updates});
ps.close(); ps.close();
} catch (SQLException e) {
ps = conn.prepareStatement("select last_insert_rowid()"); LOGGER.log(Level.SEVERE, e.toString(), e);
ResultSet rs = ps.executeQuery(); return false;
LOGGER.log(Level.FINE, "QUERY: {0}", query);
rs.next();
documentos.setId(rs.getInt(1));
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
return false;
}
return updates > 0;
} }
return updates > 0;
}
@Override @Override
public boolean updateDocumentos(Documentos documentos) { public boolean deleteDocumentos(Documentos documentos) {
int updates; int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "update documentos set tarjetas = ?, cheques = ?, retiros = ?, caja_id = ? where id = ?"; String query = "delete from documentos where id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, documentos.getTarjetas()); ps.setInt(1, documentos.getId());
ps.setInt(2, documentos.getCheques()); updates = ps.executeUpdate();
ps.setInt(3, documentos.getRetiros());
ps.setInt(4, documentos.getCaja().getId());
ps.setInt(5, documentos.getId());
updates = ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1}, {2}, {3}, {4}] | updates: {5}", new Object[]{query, documentos.getCheques(), documentos.getTarjetas(), documentos.getRetiros(), documentos.getCaja().getId(), documentos.getId(), updates}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}",
new Object[]{query, documentos.getCaja().getId(), updates});
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); LOGGER.log(Level.SEVERE, e.toString(), e);
return false; return false;
}
return updates > 0;
} }
return updates > 0;
}
@Override @Override
public boolean deleteDocumentos(Documentos documentos) { public int getTotalDocumentos(Caja caja) {
int updates; int total = 0;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "delete from documentos where id = ?"; String query = "select cheques + tarjetas + retiros from documentos where caja_id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, documentos.getId()); ps.setInt(1, caja.getId());
updates = ps.executeUpdate(); ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}", new Object[]{query, documentos.getCaja().getId(), updates}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()});
ps.close(); rs.next();
} catch (SQLException e) { total = rs.getInt(1);
LOGGER.log(Level.SEVERE, e.toString(), e);
return false; rs.close();
} ps.close();
return updates > 0; } catch (SQLException e) {
} LOGGER.log(Level.SEVERE, e.toString(), e);
@Override
public int getTotalDocumentos(Caja caja) {
int total = 0;
try (Connection conn = connectionHolder.getConnection()) {
String query = "select cheques + tarjetas + retiros from documentos where caja_id = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, caja.getId());
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()});
rs.next();
total = rs.getInt(1);
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
return total;
} }
return total;
}
} }

View File

@@ -27,120 +27,121 @@ package danielcortes.xyz.models.efectivo;
import danielcortes.xyz.models.caja.Caja; import danielcortes.xyz.models.caja.Caja;
public class Efectivo { public class Efectivo {
private int id;
private int veinteMil;
private int diezMil;
private int cincoMil;
private int dosMil;
private int mil;
private int quinientos;
private int cien;
private int cincuenta;
private int diez;
private Caja caja;
public int getId() { private int id;
return id; private int veinteMil;
} private int diezMil;
private int cincoMil;
private int dosMil;
private int mil;
private int quinientos;
private int cien;
private int cincuenta;
private int diez;
private Caja caja;
public void setId(int id) { public int getId() {
this.id = id; return id;
} }
public int getVeinteMil() { public void setId(int id) {
return veinteMil; this.id = id;
} }
public void setVeinteMil(int veinteMil) { public int getVeinteMil() {
this.veinteMil = veinteMil; return veinteMil;
} }
public int getDiezMil() { public void setVeinteMil(int veinteMil) {
return diezMil; this.veinteMil = veinteMil;
} }
public void setDiezMil(int diezMil) { public int getDiezMil() {
this.diezMil = diezMil; return diezMil;
} }
public int getCincoMil() { public void setDiezMil(int diezMil) {
return cincoMil; this.diezMil = diezMil;
} }
public void setCincoMil(int cincoMil) { public int getCincoMil() {
this.cincoMil = cincoMil; return cincoMil;
} }
public int getDosMil() { public void setCincoMil(int cincoMil) {
return dosMil; this.cincoMil = cincoMil;
} }
public void setDosMil(int dosMil) { public int getDosMil() {
this.dosMil = dosMil; return dosMil;
} }
public int getMil() { public void setDosMil(int dosMil) {
return mil; this.dosMil = dosMil;
} }
public void setMil(int mil) { public int getMil() {
this.mil = mil; return mil;
} }
public int getQuinientos() { public void setMil(int mil) {
return quinientos; this.mil = mil;
} }
public void setQuinientos(int quinientos) { public int getQuinientos() {
this.quinientos = quinientos; return quinientos;
} }
public int getCien() { public void setQuinientos(int quinientos) {
return cien; this.quinientos = quinientos;
} }
public void setCien(int cien) { public int getCien() {
this.cien = cien; return cien;
} }
public int getCincuenta() { public void setCien(int cien) {
return cincuenta; this.cien = cien;
} }
public void setCincuenta(int cincuenta) { public int getCincuenta() {
this.cincuenta = cincuenta; return cincuenta;
} }
public int getDiez() { public void setCincuenta(int cincuenta) {
return diez; this.cincuenta = cincuenta;
} }
public void setDiez(int diez) { public int getDiez() {
this.diez = diez; return diez;
} }
public Caja getCaja() { public void setDiez(int diez) {
return caja; this.diez = diez;
} }
public void setCaja(Caja caja) { public Caja getCaja() {
this.caja = caja; return caja;
} }
@Override public void setCaja(Caja caja) {
public String toString() { this.caja = caja;
return "Efectivo{" + }
"id=" + id +
", veinteMil=" + veinteMil + @Override
", diezMil=" + diezMil + public String toString() {
", cincoMil=" + cincoMil + return "Efectivo{" +
", dosMil=" + dosMil + "id=" + id +
", mil=" + mil + ", veinteMil=" + veinteMil +
", quinientos=" + quinientos + ", diezMil=" + diezMil +
", cien=" + cien + ", cincoMil=" + cincoMil +
", cincuenta=" + cincuenta + ", dosMil=" + dosMil +
", diez=" + diez + ", mil=" + mil +
", caja=" + caja + ", quinientos=" + quinientos +
'}'; ", cien=" + cien +
} ", cincuenta=" + cincuenta +
", diez=" + diez +
", caja=" + caja +
'}';
}
} }

View File

@@ -28,7 +28,6 @@ import danielcortes.xyz.data.ConnectionHolder;
import danielcortes.xyz.models.caja.Caja; import danielcortes.xyz.models.caja.Caja;
import danielcortes.xyz.models.caja.CajaDAO; import danielcortes.xyz.models.caja.CajaDAO;
import danielcortes.xyz.models.caja.SQLiteCajaDAO; import danielcortes.xyz.models.caja.SQLiteCajaDAO;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@@ -37,49 +36,50 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public abstract class EfectivoDAO { public abstract class EfectivoDAO {
private static final Logger LOGGER = Logger.getLogger(EfectivoDAO.class.getName());
protected ConnectionHolder connectionHolder; private static final Logger LOGGER = Logger.getLogger(EfectivoDAO.class.getName());
public abstract List<Efectivo> findAll(); protected ConnectionHolder connectionHolder;
public abstract Efectivo findById(int id); public abstract List<Efectivo> findAll();
public abstract Efectivo findByCaja(Caja caja); public abstract Efectivo findById(int id);
public abstract boolean insertEfectivo(Efectivo efectivo); public abstract Efectivo findByCaja(Caja caja);
public abstract boolean insertDefaultEfectivo(Efectivo efectivo); public abstract boolean insertEfectivo(Efectivo efectivo);
public abstract boolean updateEfectivo(Efectivo efectivo); public abstract boolean insertDefaultEfectivo(Efectivo efectivo);
public abstract boolean deleteEfectivo(Efectivo efectivo); public abstract boolean updateEfectivo(Efectivo efectivo);
public abstract int getTotalEfectivo(Caja caja); public abstract boolean deleteEfectivo(Efectivo efectivo);
protected List<Efectivo> efectivosFromResultSet(ResultSet rs) throws SQLException { public abstract int getTotalEfectivo(Caja caja);
List<Efectivo> efectivoList = new ArrayList<>();
while (rs.next()) {
CajaDAO cajaDAO = new SQLiteCajaDAO();
Caja caja = cajaDAO.getById(rs.getInt("caja_id")).get();
Efectivo efectivo = new Efectivo(); protected List<Efectivo> efectivosFromResultSet(ResultSet rs) throws SQLException {
efectivo.setCaja(caja); List<Efectivo> efectivoList = new ArrayList<>();
efectivo.setId(rs.getInt("id")); while (rs.next()) {
efectivo.setVeinteMil(rs.getInt("veinte_mil")); CajaDAO cajaDAO = new SQLiteCajaDAO();
efectivo.setDiezMil(rs.getInt("diez_mil")); Caja caja = cajaDAO.getById(rs.getInt("caja_id")).get();
efectivo.setCincoMil(rs.getInt("cinco_mil"));
efectivo.setDosMil(rs.getInt("dos_mil"));
efectivo.setMil(rs.getInt("mil"));
efectivo.setQuinientos(rs.getInt("quinientos"));
efectivo.setCien(rs.getInt("cien"));
efectivo.setCincuenta(rs.getInt("cincuenta"));
efectivo.setDiez(rs.getInt("diez"));
LOGGER.log(Level.FINER, "Se a creo: {0}", efectivo); Efectivo efectivo = new Efectivo();
efectivo.setCaja(caja);
efectivo.setId(rs.getInt("id"));
efectivo.setVeinteMil(rs.getInt("veinte_mil"));
efectivo.setDiezMil(rs.getInt("diez_mil"));
efectivo.setCincoMil(rs.getInt("cinco_mil"));
efectivo.setDosMil(rs.getInt("dos_mil"));
efectivo.setMil(rs.getInt("mil"));
efectivo.setQuinientos(rs.getInt("quinientos"));
efectivo.setCien(rs.getInt("cien"));
efectivo.setCincuenta(rs.getInt("cincuenta"));
efectivo.setDiez(rs.getInt("diez"));
efectivoList.add(efectivo); LOGGER.log(Level.FINER, "Se a creo: {0}", efectivo);
}
return efectivoList; efectivoList.add(efectivo);
} }
return efectivoList;
}
} }

View File

@@ -26,7 +26,6 @@ package danielcortes.xyz.models.efectivo;
import danielcortes.xyz.data.SQLiteConnectionHolder; import danielcortes.xyz.data.SQLiteConnectionHolder;
import danielcortes.xyz.models.caja.Caja; import danielcortes.xyz.models.caja.Caja;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@@ -37,216 +36,227 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public class SQLiteEfectivoDAO extends EfectivoDAO { public class SQLiteEfectivoDAO extends EfectivoDAO {
private static final Logger LOGGER = Logger.getLogger(SQLiteEfectivoDAO.class.getName());
public SQLiteEfectivoDAO() { private static final Logger LOGGER = Logger.getLogger(SQLiteEfectivoDAO.class.getName());
this.connectionHolder = new SQLiteConnectionHolder();
public SQLiteEfectivoDAO() {
this.connectionHolder = new SQLiteConnectionHolder();
}
@Override
public List<Efectivo> findAll() {
List<Efectivo> efectivoList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from efectivos";
PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", query);
efectivoList = this.efectivosFromResultSet(rs);
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
} }
@Override return efectivoList;
public List<Efectivo> findAll() { }
List<Efectivo> efectivoList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from efectivos";
PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", query); @Override
public Efectivo findById(int id) {
Efectivo efectivo = null;
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from efectivos where id = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
efectivoList = this.efectivosFromResultSet(rs); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id});
rs.close(); efectivo = this.efectivosFromResultSet(rs).get(0);
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
return efectivoList; rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
} }
@Override return efectivo;
public Efectivo findById(int id) { }
Efectivo efectivo = null;
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from efectivos where id = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id}); @Override
public Efectivo findByCaja(Caja caja) {
Efectivo efectivo = null;
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from efectivos where caja_id = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, caja.getId());
ResultSet rs = ps.executeQuery();
efectivo = this.efectivosFromResultSet(rs).get(0); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()});
rs.close(); List<Efectivo> efectivoList = this.efectivosFromResultSet(rs);
ps.close(); if (efectivoList.size() > 0) {
} catch (SQLException e) { efectivo = efectivoList.get(0);
LOGGER.log(Level.SEVERE, e.toString(), e); }
}
return efectivo; rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
} }
@Override return efectivo;
public Efectivo findByCaja(Caja caja) { }
Efectivo efectivo = null;
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from efectivos where caja_id = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, caja.getId());
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()}); @Override
public boolean insertEfectivo(Efectivo efectivo) {
int updates;
try (Connection conn = connectionHolder.getConnection()) {
String query = "insert into efectivos (veinte_mil, diez_mil, cinco_mil, dos_mil, mil, quinientos, cien, cincuenta, diez, caja_id) values (?,?,?,?,?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, efectivo.getVeinteMil());
ps.setInt(2, efectivo.getDiezMil());
ps.setInt(3, efectivo.getCincoMil());
ps.setInt(4, efectivo.getDosMil());
ps.setInt(5, efectivo.getMil());
ps.setInt(6, efectivo.getQuinientos());
ps.setInt(7, efectivo.getCien());
ps.setInt(8, efectivo.getCincuenta());
ps.setInt(9, efectivo.getDiez());
ps.setInt(10, efectivo.getCaja().getId());
updates = ps.executeUpdate();
List<Efectivo> efectivoList = this.efectivosFromResultSet(rs); LOGGER.log(Level.FINE,
if (efectivoList.size() > 0) { "QUERY: {0} | values: [{1},{2},{3},{4},{5},{6},{7},{8},{9},{10}] | updates: {11}",
efectivo = efectivoList.get(0); new Object[]{query, efectivo.getVeinteMil(), efectivo.getDiezMil(),
} efectivo.getCincoMil(), efectivo.getDosMil(), efectivo.getMil(),
efectivo.getQuinientos(), efectivo.getCien(), efectivo.getCincuenta(),
efectivo.getDiez(), efectivo.getCaja().getId(), updates});
rs.close(); ps.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
return efectivo; query = "select last_insert_rowid()";
ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", query);
rs.next();
efectivo.setId(rs.getInt(1));
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
return false;
} }
return updates > 0;
}
@Override @Override
public boolean insertEfectivo(Efectivo efectivo) { public boolean insertDefaultEfectivo(Efectivo efectivo) {
int updates; int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "insert into efectivos (veinte_mil, diez_mil, cinco_mil, dos_mil, mil, quinientos, cien, cincuenta, diez, caja_id) values (?,?,?,?,?,?,?,?,?,?)"; String query = "insert into efectivos (veinte_mil, diez_mil, cinco_mil, dos_mil, mil, quinientos, cien, cincuenta, diez, caja_id) values (0,0,0,0,0,0,0,0,0,?)";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, efectivo.getVeinteMil()); ps.setInt(1, efectivo.getCaja().getId());
ps.setInt(2, efectivo.getDiezMil()); updates = ps.executeUpdate();
ps.setInt(3, efectivo.getCincoMil());
ps.setInt(4, efectivo.getDosMil());
ps.setInt(5, efectivo.getMil());
ps.setInt(6, efectivo.getQuinientos());
ps.setInt(7, efectivo.getCien());
ps.setInt(8, efectivo.getCincuenta());
ps.setInt(9, efectivo.getDiez());
ps.setInt(10, efectivo.getCaja().getId());
updates = ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1},{2},{3},{4},{5},{6},{7},{8},{9},{10}] | updates: {11}", new Object[]{query, efectivo.getVeinteMil(), efectivo.getDiezMil(), efectivo.getCincoMil(), efectivo.getDosMil(), efectivo.getMil(), efectivo.getQuinientos(), efectivo.getCien(), efectivo.getCincuenta(), efectivo.getDiez(), efectivo.getCaja().getId(), updates}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}",
new Object[]{query, efectivo.getCaja().getId(), updates});
ps.close(); ps.close();
ps = conn.prepareStatement("select last_insert_rowid()");
ResultSet rs = ps.executeQuery();
rs.next();
efectivo.setId(rs.getInt(1));
query = "select last_insert_rowid()"; rs.close();
ps = conn.prepareStatement(query); ps.close();
ResultSet rs = ps.executeQuery(); } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
LOGGER.log(Level.FINE, "QUERY: {0}", query); return false;
rs.next();
efectivo.setId(rs.getInt(1));
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
return false;
}
return updates > 0;
} }
return updates > 0;
}
@Override @Override
public boolean insertDefaultEfectivo(Efectivo efectivo) { public boolean updateEfectivo(Efectivo efectivo) {
int updates; int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "insert into efectivos (veinte_mil, diez_mil, cinco_mil, dos_mil, mil, quinientos, cien, cincuenta, diez, caja_id) values (0,0,0,0,0,0,0,0,0,?)"; String query = "update efectivos set veinte_mil = ?, diez_mil = ?, cinco_mil = ?, dos_mil = ?, mil = ?, quinientos = ?, cien = ?, cincuenta = ?, diez = ?, caja_id = ? where id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, efectivo.getCaja().getId()); ps.setInt(1, efectivo.getVeinteMil());
updates = ps.executeUpdate(); ps.setInt(2, efectivo.getDiezMil());
ps.setInt(3, efectivo.getCincoMil());
ps.setInt(4, efectivo.getDosMil());
ps.setInt(5, efectivo.getMil());
ps.setInt(6, efectivo.getQuinientos());
ps.setInt(7, efectivo.getCien());
ps.setInt(8, efectivo.getCincuenta());
ps.setInt(9, efectivo.getDiez());
ps.setInt(10, efectivo.getCaja().getId());
ps.setInt(11, efectivo.getId());
updates = ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}", new Object[]{query, efectivo.getCaja().getId(), updates}); LOGGER.log(Level.FINE,
"QUERY: {0} | values: [{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11}] | updates: {12}",
new Object[]{query, efectivo.getVeinteMil(), efectivo.getDiezMil(),
efectivo.getCincoMil(), efectivo.getDosMil(), efectivo.getMil(),
efectivo.getQuinientos(), efectivo.getCien(), efectivo.getCincuenta(),
efectivo.getDiez(), efectivo.getCaja().getId(), efectivo.getId(), updates});
ps.close(); ps.close();
} catch (SQLException e) {
ps = conn.prepareStatement("select last_insert_rowid()"); LOGGER.log(Level.SEVERE, e.toString(), e);
ResultSet rs = ps.executeQuery(); return false;
rs.next();
efectivo.setId(rs.getInt(1));
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
return false;
}
return updates > 0;
} }
return updates > 0;
}
@Override @Override
public boolean updateEfectivo(Efectivo efectivo) { public boolean deleteEfectivo(Efectivo efectivo) {
int updates; int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "update efectivos set veinte_mil = ?, diez_mil = ?, cinco_mil = ?, dos_mil = ?, mil = ?, quinientos = ?, cien = ?, cincuenta = ?, diez = ?, caja_id = ? where id = ?"; String query = "delete from efectivos where id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, efectivo.getVeinteMil()); ps.setInt(1, efectivo.getId());
ps.setInt(2, efectivo.getDiezMil()); updates = ps.executeUpdate();
ps.setInt(3, efectivo.getCincoMil());
ps.setInt(4, efectivo.getDosMil());
ps.setInt(5, efectivo.getMil());
ps.setInt(6, efectivo.getQuinientos());
ps.setInt(7, efectivo.getCien());
ps.setInt(8, efectivo.getCincuenta());
ps.setInt(9, efectivo.getDiez());
ps.setInt(10, efectivo.getCaja().getId());
ps.setInt(11, efectivo.getId());
updates = ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}",
new Object[]{query, efectivo.getId(), updates});
LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11}] | updates: {12}", new Object[]{query, efectivo.getVeinteMil(), efectivo.getDiezMil(), efectivo.getCincoMil(), efectivo.getDosMil(), efectivo.getMil(), efectivo.getQuinientos(), efectivo.getCien(), efectivo.getCincuenta(), efectivo.getDiez(), efectivo.getCaja().getId(), efectivo.getId(), updates}); ps.close();
} catch (SQLException e) {
ps.close(); LOGGER.log(Level.SEVERE, e.toString(), e);
} catch (SQLException e) { return false;
LOGGER.log(Level.SEVERE, e.toString(), e);
return false;
}
return updates > 0;
} }
return updates > 0;
}
@Override @Override
public boolean deleteEfectivo(Efectivo efectivo) { public int getTotalEfectivo(Caja caja) {
int updates; int total = 0;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "delete from efectivos where id = ?"; String query = "select veinte_mil + diez_mil + cinco_mil + dos_mil + mil + quinientos + cien + cincuenta + diez from efectivos where caja_id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, efectivo.getId()); ps.setInt(1, caja.getId());
updates = ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}", new Object[]{query, efectivo.getId(), updates}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()});
ps.close(); ResultSet rs = ps.executeQuery();
} catch (SQLException e) { rs.next();
LOGGER.log(Level.SEVERE, e.toString(), e); total = rs.getInt(1);
return false;
} rs.close();
return updates > 0; ps.close();
} } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
@Override
public int getTotalEfectivo(Caja caja) {
int total = 0;
try (Connection conn = connectionHolder.getConnection()) {
String query = "select veinte_mil + diez_mil + cinco_mil + dos_mil + mil + quinientos + cien + cincuenta + diez from efectivos where caja_id = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, caja.getId());
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()});
ResultSet rs = ps.executeQuery();
rs.next();
total = rs.getInt(1);
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
return total;
} }
return total;
}
} }

View File

@@ -29,70 +29,70 @@ import danielcortes.xyz.models.tipo_egreso.TipoEgreso;
public class Egreso { public class Egreso {
private int id; private int id;
private String nro; private String nro;
private String descripcion; private String descripcion;
private int valor; private int valor;
private TipoEgreso tipoEgreso; private TipoEgreso tipoEgreso;
private Caja caja; private Caja caja;
public int getId() { public int getId() {
return id; return id;
} }
public void setId(int id) { public void setId(int id) {
this.id = id; this.id = id;
} }
public String getNro() { public String getNro() {
return nro; return nro;
} }
public void setNro(String nro) { public void setNro(String nro) {
this.nro = nro; this.nro = nro;
} }
public String getDescripcion() { public String getDescripcion() {
return descripcion; return descripcion;
} }
public void setDescripcion(String descripcion) { public void setDescripcion(String descripcion) {
this.descripcion = descripcion; this.descripcion = descripcion;
} }
public int getValor() { public int getValor() {
return valor; return valor;
} }
public void setValor(int valor) { public void setValor(int valor) {
this.valor = valor; this.valor = valor;
} }
public TipoEgreso getTipoEgreso() { public TipoEgreso getTipoEgreso() {
return tipoEgreso; return tipoEgreso;
} }
public void setTipoEgreso(TipoEgreso tipoEgreso) { public void setTipoEgreso(TipoEgreso tipoEgreso) {
this.tipoEgreso = tipoEgreso; this.tipoEgreso = tipoEgreso;
} }
public Caja getCaja() { public Caja getCaja() {
return caja; return caja;
} }
public void setCaja(Caja caja) { public void setCaja(Caja caja) {
this.caja = caja; this.caja = caja;
} }
@Override @Override
public String toString() { public String toString() {
return "Egreso{" + return "Egreso{" +
"id=" + id + "id=" + id +
", nro='" + nro + '\'' + ", nro='" + nro + '\'' +
", descripcion='" + descripcion + '\'' + ", descripcion='" + descripcion + '\'' +
", valor=" + valor + ", valor=" + valor +
", tipoEgreso=" + tipoEgreso + ", tipoEgreso=" + tipoEgreso +
", caja=" + caja + ", caja=" + caja +
'}'; '}';
} }
} }

View File

@@ -31,7 +31,6 @@ import danielcortes.xyz.models.caja.SQLiteCajaDAO;
import danielcortes.xyz.models.tipo_egreso.SQLiteTipoEgresoDAO; import danielcortes.xyz.models.tipo_egreso.SQLiteTipoEgresoDAO;
import danielcortes.xyz.models.tipo_egreso.TipoEgreso; import danielcortes.xyz.models.tipo_egreso.TipoEgreso;
import danielcortes.xyz.models.tipo_egreso.TipoEgresoDAO; import danielcortes.xyz.models.tipo_egreso.TipoEgresoDAO;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.YearMonth; import java.time.YearMonth;
@@ -41,54 +40,55 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public abstract class EgresoDAO { public abstract class EgresoDAO {
private static final Logger LOGGER = Logger.getLogger(EgresoDAO.class.getName());
protected ConnectionHolder connectionHolder; private static final Logger LOGGER = Logger.getLogger(EgresoDAO.class.getName());
public abstract List<Egreso> findAll(); protected ConnectionHolder connectionHolder;
public abstract List<Egreso> findById(int id); public abstract List<Egreso> findAll();
public abstract List<Egreso> findByCaja(Caja caja); public abstract List<Egreso> findById(int id);
public abstract List<Egreso> findByNro(String nro); public abstract List<Egreso> findByCaja(Caja caja);
public abstract List<Egreso> findByTipoEgreso(TipoEgreso tipoEgreso); public abstract List<Egreso> findByNro(String nro);
public abstract boolean insertEgreso(Egreso egreso); public abstract List<Egreso> findByTipoEgreso(TipoEgreso tipoEgreso);
public abstract boolean updateEgreso(Egreso egreso); public abstract boolean insertEgreso(Egreso egreso);
public abstract boolean deleteEgreso(Egreso egreso); public abstract boolean updateEgreso(Egreso egreso);
public abstract int getTotalEgreso(Caja caja); public abstract boolean deleteEgreso(Egreso egreso);
public abstract int getTotalEgresoMesPorTipo(YearMonth mes, TipoEgreso tipo); public abstract int getTotalEgreso(Caja caja);
List<Egreso> egresosFromResultSet(ResultSet rs) throws SQLException { public abstract int getTotalEgresoMesPorTipo(YearMonth mes, TipoEgreso tipo);
ArrayList<Egreso> egresoList = new ArrayList<>();
while (rs.next()) {
int tipoEgresoId = rs.getInt("tipo_egreso_id");
TipoEgresoDAO tipoEgresoDAO = new SQLiteTipoEgresoDAO();
TipoEgreso tipoEgreso = tipoEgresoDAO.findById(tipoEgresoId).get(0);
int cajaId = rs.getInt("caja_id"); List<Egreso> egresosFromResultSet(ResultSet rs) throws SQLException {
CajaDAO cajaDAO = new SQLiteCajaDAO(); ArrayList<Egreso> egresoList = new ArrayList<>();
Caja caja = cajaDAO.getById(cajaId).get(); while (rs.next()) {
int tipoEgresoId = rs.getInt("tipo_egreso_id");
TipoEgresoDAO tipoEgresoDAO = new SQLiteTipoEgresoDAO();
TipoEgreso tipoEgreso = tipoEgresoDAO.findById(tipoEgresoId).get(0);
Egreso egreso = new Egreso(); int cajaId = rs.getInt("caja_id");
CajaDAO cajaDAO = new SQLiteCajaDAO();
Caja caja = cajaDAO.getById(cajaId).get();
egreso.setId(rs.getInt("id")); Egreso egreso = new Egreso();
egreso.setNro(rs.getString("nro"));
egreso.setDescripcion(rs.getString("descripcion"));
egreso.setValor(rs.getInt("valor"));
egreso.setTipoEgreso(tipoEgreso);
egreso.setCaja(caja);
LOGGER.log(Level.FINER, "Se a creado: {0}", egreso); egreso.setId(rs.getInt("id"));
egreso.setNro(rs.getString("nro"));
egreso.setDescripcion(rs.getString("descripcion"));
egreso.setValor(rs.getInt("valor"));
egreso.setTipoEgreso(tipoEgreso);
egreso.setCaja(caja);
egresoList.add(egreso); LOGGER.log(Level.FINER, "Se a creado: {0}", egreso);
}
return egresoList; egresoList.add(egreso);
} }
return egresoList;
}
} }

View File

@@ -27,7 +27,6 @@ package danielcortes.xyz.models.egreso;
import danielcortes.xyz.data.SQLiteConnectionHolder; import danielcortes.xyz.data.SQLiteConnectionHolder;
import danielcortes.xyz.models.caja.Caja; import danielcortes.xyz.models.caja.Caja;
import danielcortes.xyz.models.tipo_egreso.TipoEgreso; import danielcortes.xyz.models.tipo_egreso.TipoEgreso;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@@ -40,237 +39,243 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public class SQLiteEgresoDAO extends EgresoDAO { public class SQLiteEgresoDAO extends EgresoDAO {
private static final Logger LOGGER = Logger.getLogger(SQLiteEgresoDAO.class.getName());
public SQLiteEgresoDAO() { private static final Logger LOGGER = Logger.getLogger(SQLiteEgresoDAO.class.getName());
this.connectionHolder = new SQLiteConnectionHolder();
public SQLiteEgresoDAO() {
this.connectionHolder = new SQLiteConnectionHolder();
}
@Override
public List<Egreso> findAll() {
List<Egreso> egresoList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from egresos";
PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", query);
egresoList = this.egresosFromResultSet(rs);
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
} }
return egresoList;
}
@Override @Override
public List<Egreso> findAll() { public List<Egreso> findById(int id) {
List<Egreso> egresoList = new ArrayList<>(); List<Egreso> egresoList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from egresos"; String query = "select * from egresos where id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery(); ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", query); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id});
egresoList = this.egresosFromResultSet(rs); egresoList = this.egresosFromResultSet(rs);
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); LOGGER.log(Level.SEVERE, e.toString(), e);
}
return egresoList;
} }
return egresoList;
}
@Override @Override
public List<Egreso> findById(int id) { public List<Egreso> findByCaja(Caja caja) {
List<Egreso> egresoList = new ArrayList<>(); List<Egreso> egresoList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from egresos where id = ?"; String query = "select * from egresos where caja_id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, id); ps.setInt(1, caja.getId());
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()});
egresoList = this.egresosFromResultSet(rs); egresoList = this.egresosFromResultSet(rs);
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); LOGGER.log(Level.SEVERE, e.toString(), e);
}
return egresoList;
} }
return egresoList;
}
@Override @Override
public List<Egreso> findByCaja(Caja caja) { public List<Egreso> findByNro(String nro) {
List<Egreso> egresoList = new ArrayList<>(); List<Egreso> egresoList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from egresos where caja_id = ?"; String query = "select * from egresos where nro = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, caja.getId()); ps.setString(1, nro);
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()}); LOGGER.log(Level.FINE, "QUERY: {0} | values {1}", new Object[]{query, nro});
egresoList = this.egresosFromResultSet(rs); egresoList = this.egresosFromResultSet(rs);
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); LOGGER.log(Level.SEVERE, e.toString(), e);
}
return egresoList;
} }
return egresoList;
}
@Override @Override
public List<Egreso> findByNro(String nro) { public List<Egreso> findByTipoEgreso(TipoEgreso tipoEgreso) {
List<Egreso> egresoList = new ArrayList<>(); List<Egreso> egresoList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from egresos where nro = ?"; String query = "select * from egresos where tipo_egreso_id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, nro); ps.setInt(1, tipoEgreso.getId());
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values {1}", new Object[]{query, nro}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, tipoEgreso.getId()});
egresoList = this.egresosFromResultSet(rs); egresoList = this.egresosFromResultSet(rs);
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); LOGGER.log(Level.SEVERE, e.toString(), e);
}
return egresoList;
} }
return egresoList;
}
@Override @Override
public List<Egreso> findByTipoEgreso(TipoEgreso tipoEgreso) { public boolean insertEgreso(Egreso egreso) {
List<Egreso> egresoList = new ArrayList<>(); int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from egresos where tipo_egreso_id = ?"; String query = "insert into egresos (nro, descripcion, valor, tipo_egreso_id, caja_id) values (?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, tipoEgreso.getId()); ps.setString(1, egreso.getNro());
ResultSet rs = ps.executeQuery(); ps.setString(2, egreso.getDescripcion());
ps.setInt(3, egreso.getValor());
ps.setInt(4, egreso.getTipoEgreso().getId());
ps.setInt(5, egreso.getCaja().getId());
updates = ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, tipoEgreso.getId()}); LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1}, {2}, {3}, {4}, {5}] | updates: {6}",
new Object[]{query, egreso.getNro(), egreso.getDescripcion(), egreso.getValor(),
egreso.getTipoEgreso().getId(), egreso.getCaja().getId(), updates});
egresoList = this.egresosFromResultSet(rs); ps.close();
rs.close(); ps = conn.prepareStatement("select last_insert_rowid()");
ps.close(); ResultSet rs = ps.executeQuery();
} catch (SQLException e) { rs.next();
LOGGER.log(Level.SEVERE, e.toString(), e); egreso.setId(rs.getInt(1));
}
return egresoList; rs.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
return false;
} }
return updates > 0;
}
@Override @Override
public boolean insertEgreso(Egreso egreso) { public boolean updateEgreso(Egreso egreso) {
int updates; int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "insert into egresos (nro, descripcion, valor, tipo_egreso_id, caja_id) values (?,?,?,?,?)"; String query = "update egresos set nro = ?, descripcion = ?, valor = ?, tipo_egreso_id = ?, caja_id = ? where id = ? ";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, egreso.getNro()); ps.setString(1, egreso.getNro());
ps.setString(2, egreso.getDescripcion()); ps.setString(2, egreso.getDescripcion());
ps.setInt(3, egreso.getValor()); ps.setInt(3, egreso.getValor());
ps.setInt(4, egreso.getTipoEgreso().getId()); ps.setInt(4, egreso.getTipoEgreso().getId());
ps.setInt(5, egreso.getCaja().getId()); ps.setInt(5, egreso.getCaja().getId());
updates = ps.executeUpdate(); ps.setInt(6, egreso.getId());
updates = ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1}, {2}, {3}, {4}, {5}] | updates: {6}", new Object[]{query, egreso.getNro(), egreso.getDescripcion(), egreso.getValor(), egreso.getTipoEgreso().getId(), egreso.getCaja().getId(), updates}); LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1}, {2}, {3}, {4}, {5}, {6}] | updates: {7}",
new Object[]{query, egreso.getNro(), egreso.getDescripcion(), egreso.getValor(),
egreso.getTipoEgreso().getId(), egreso.getCaja().getId(), egreso.getId(), updates});
ps.close(); ps.close();
} catch (SQLException e) {
ps = conn.prepareStatement("select last_insert_rowid()"); LOGGER.log(Level.SEVERE, e.toString(), e);
ResultSet rs = ps.executeQuery(); return false;
rs.next();
egreso.setId(rs.getInt(1));
rs.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
return false;
}
return updates > 0;
} }
return updates > 0;
}
@Override @Override
public boolean updateEgreso(Egreso egreso) { public boolean deleteEgreso(Egreso egreso) {
int updates; int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "update egresos set nro = ?, descripcion = ?, valor = ?, tipo_egreso_id = ?, caja_id = ? where id = ? "; String query = "delete from egresos where id = ? ";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, egreso.getNro()); ps.setInt(1, egreso.getId());
ps.setString(2, egreso.getDescripcion()); updates = ps.executeUpdate();
ps.setInt(3, egreso.getValor());
ps.setInt(4, egreso.getTipoEgreso().getId());
ps.setInt(5, egreso.getCaja().getId());
ps.setInt(6, egreso.getId());
updates = ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1}, {2}, {3}, {4}, {5}, {6}] | updates: {7}", new Object[]{query, egreso.getNro(), egreso.getDescripcion(), egreso.getValor(), egreso.getTipoEgreso().getId(), egreso.getCaja().getId(), egreso.getId(), updates}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}",
new Object[]{query, egreso.getId(), updates});
ps.close();
ps.close(); } catch (SQLException e) {
} catch (SQLException e) { LOGGER.log(Level.SEVERE, e.toString(), e);
LOGGER.log(Level.SEVERE, e.toString(), e); return false;
return false;
}
return updates > 0;
} }
return updates > 0;
}
@Override @Override
public boolean deleteEgreso(Egreso egreso) { public int getTotalEgreso(Caja caja) {
int updates; int total = 0;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "delete from egresos where id = ? "; String query = "select sum(valor) from egresos where caja_id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, egreso.getId()); ps.setInt(1, caja.getId());
updates = ps.executeUpdate(); ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}", new Object[]{query, egreso.getId(), updates}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()});
ps.close(); rs.next();
} catch (SQLException e) { total = rs.getInt(1);
LOGGER.log(Level.SEVERE, e.toString(), e);
return false; rs.close();
} ps.close();
return updates > 0; } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
} }
return total;
}
@Override @Override
public int getTotalEgreso(Caja caja) { public int getTotalEgresoMesPorTipo(YearMonth mes, TipoEgreso tipo) {
int total = 0; int total = 0;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select sum(valor) from egresos where caja_id = ?"; LocalDate start = mes.atDay(1);
PreparedStatement ps = conn.prepareStatement(query); LocalDate end = mes.atEndOfMonth();
ps.setInt(1, caja.getId()); String query = "select sum(valor) from egresos inner join caja on (egresos.caja_id = caja.id) where fecha between ? and ? and tipo_egreso_id = ?";
ResultSet rs = ps.executeQuery(); PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, start.toString());
ps.setString(2, end.toString());
ps.setInt(3, tipo.getId());
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}, {2}, {3}",
new Object[]{query, start, end, tipo});
rs.next(); rs.next();
total = rs.getInt(1); total = rs.getInt(1);
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); LOGGER.log(Level.SEVERE, e.toString(), e);
}
return total;
}
@Override
public int getTotalEgresoMesPorTipo(YearMonth mes, TipoEgreso tipo) {
int total = 0;
try (Connection conn = connectionHolder.getConnection()) {
LocalDate start = mes.atDay(1);
LocalDate end = mes.atEndOfMonth();
String query = "select sum(valor) from egresos inner join caja on (egresos.caja_id = caja.id) where fecha between ? and ? and tipo_egreso_id = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, start.toString());
ps.setString(2, end.toString());
ps.setInt(3, tipo.getId());
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}, {2}, {3}", new Object[]{query, start, end, tipo});
rs.next();
total = rs.getInt(1);
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
return total;
} }
return total;
}
} }

View File

@@ -3,199 +3,200 @@ package danielcortes.xyz.models.estado_resultado;
import java.time.YearMonth; import java.time.YearMonth;
public class EstadoResultado { public class EstadoResultado {
public static final EstadoResultado emptyEstadoResultado;
static { public static final EstadoResultado emptyEstadoResultado;
emptyEstadoResultado = new EstadoResultado();
emptyEstadoResultado.costoVenta = 0;
emptyEstadoResultado.cuentaCorrienteBoleta = 0;
emptyEstadoResultado.cuentaCorrienteFactura = 0;
emptyEstadoResultado.cuentaCorrienteSinRespaldo = 0;
emptyEstadoResultado.remuneraciones = 0;
emptyEstadoResultado.finiquitos = 0;
emptyEstadoResultado.aguinaldo = 0;
emptyEstadoResultado.bonosPersonal = 0;
emptyEstadoResultado.honorariosContador = 0;
emptyEstadoResultado.arriendo = 0;
emptyEstadoResultado.agua = 0;
emptyEstadoResultado.luz = 0;
emptyEstadoResultado.gas = 0;
emptyEstadoResultado.telefono = 0;
emptyEstadoResultado.otroServicio = 0;
emptyEstadoResultado.ppm = 0d;
emptyEstadoResultado.ivaFavor = 0;
}
private int id; static {
private YearMonth mes; emptyEstadoResultado = new EstadoResultado();
private int costoVenta; emptyEstadoResultado.costoVenta = 0;
private int cuentaCorrienteFactura; emptyEstadoResultado.cuentaCorrienteBoleta = 0;
private int cuentaCorrienteBoleta; emptyEstadoResultado.cuentaCorrienteFactura = 0;
private int cuentaCorrienteSinRespaldo; emptyEstadoResultado.cuentaCorrienteSinRespaldo = 0;
private int remuneraciones; emptyEstadoResultado.remuneraciones = 0;
private int finiquitos; emptyEstadoResultado.finiquitos = 0;
private int aguinaldo; emptyEstadoResultado.aguinaldo = 0;
private int bonosPersonal; emptyEstadoResultado.bonosPersonal = 0;
private int honorariosContador; emptyEstadoResultado.honorariosContador = 0;
private int arriendo; emptyEstadoResultado.arriendo = 0;
private int agua; emptyEstadoResultado.agua = 0;
private int luz; emptyEstadoResultado.luz = 0;
private int gas; emptyEstadoResultado.gas = 0;
private int telefono; emptyEstadoResultado.telefono = 0;
private int otroServicio; emptyEstadoResultado.otroServicio = 0;
private double ppm; emptyEstadoResultado.ppm = 0d;
private int ivaFavor; emptyEstadoResultado.ivaFavor = 0;
}
public int getId() { private int id;
return id; private YearMonth mes;
} private int costoVenta;
private int cuentaCorrienteFactura;
private int cuentaCorrienteBoleta;
private int cuentaCorrienteSinRespaldo;
private int remuneraciones;
private int finiquitos;
private int aguinaldo;
private int bonosPersonal;
private int honorariosContador;
private int arriendo;
private int agua;
private int luz;
private int gas;
private int telefono;
private int otroServicio;
private double ppm;
private int ivaFavor;
public void setId(int id) { public int getId() {
this.id = id; return id;
} }
public YearMonth getMes() { public void setId(int id) {
return mes; this.id = id;
} }
public void setMes(YearMonth mes) { public YearMonth getMes() {
this.mes = mes; return mes;
} }
public int getCostoVenta() { public void setMes(YearMonth mes) {
return costoVenta; this.mes = mes;
} }
public void setCostoVenta(int costoVenta) { public int getCostoVenta() {
this.costoVenta = costoVenta; return costoVenta;
} }
public int getCuentaCorrienteFactura() { public void setCostoVenta(int costoVenta) {
return cuentaCorrienteFactura; this.costoVenta = costoVenta;
} }
public void setCuentaCorrienteFactura(int cuentaCorrienteFactura) { public int getCuentaCorrienteFactura() {
this.cuentaCorrienteFactura = cuentaCorrienteFactura; return cuentaCorrienteFactura;
} }
public int getCuentaCorrienteBoleta() { public void setCuentaCorrienteFactura(int cuentaCorrienteFactura) {
return cuentaCorrienteBoleta; this.cuentaCorrienteFactura = cuentaCorrienteFactura;
} }
public void setCuentaCorrienteBoleta(int cuentaCorrienteBoleta) { public int getCuentaCorrienteBoleta() {
this.cuentaCorrienteBoleta = cuentaCorrienteBoleta; return cuentaCorrienteBoleta;
} }
public int getCuentaCorrienteSinRespaldo() { public void setCuentaCorrienteBoleta(int cuentaCorrienteBoleta) {
return cuentaCorrienteSinRespaldo; this.cuentaCorrienteBoleta = cuentaCorrienteBoleta;
} }
public void setCuentaCorrienteSinRespaldo(int cuentaCorrienteSinRespaldo) { public int getCuentaCorrienteSinRespaldo() {
this.cuentaCorrienteSinRespaldo = cuentaCorrienteSinRespaldo; return cuentaCorrienteSinRespaldo;
} }
public int getRemuneraciones() { public void setCuentaCorrienteSinRespaldo(int cuentaCorrienteSinRespaldo) {
return remuneraciones; this.cuentaCorrienteSinRespaldo = cuentaCorrienteSinRespaldo;
} }
public void setRemuneraciones(int remuneraciones) { public int getRemuneraciones() {
this.remuneraciones = remuneraciones; return remuneraciones;
} }
public int getFiniquitos() { public void setRemuneraciones(int remuneraciones) {
return finiquitos; this.remuneraciones = remuneraciones;
} }
public void setFiniquitos(int finiquitos) { public int getFiniquitos() {
this.finiquitos = finiquitos; return finiquitos;
} }
public int getAguinaldo() { public void setFiniquitos(int finiquitos) {
return aguinaldo; this.finiquitos = finiquitos;
} }
public void setAguinaldo(int aguinaldo) { public int getAguinaldo() {
this.aguinaldo = aguinaldo; return aguinaldo;
} }
public int getBonosPersonal() { public void setAguinaldo(int aguinaldo) {
return bonosPersonal; this.aguinaldo = aguinaldo;
} }
public void setBonosPersonal(int bonosPersonal) { public int getBonosPersonal() {
this.bonosPersonal = bonosPersonal; return bonosPersonal;
} }
public int getHonorariosContador() { public void setBonosPersonal(int bonosPersonal) {
return honorariosContador; this.bonosPersonal = bonosPersonal;
} }
public void setHonorariosContador(int honorariosContador) { public int getHonorariosContador() {
this.honorariosContador = honorariosContador; return honorariosContador;
} }
public int getArriendo() { public void setHonorariosContador(int honorariosContador) {
return arriendo; this.honorariosContador = honorariosContador;
} }
public void setArriendo(int arriendo) { public int getArriendo() {
this.arriendo = arriendo; return arriendo;
} }
public int getAgua() { public void setArriendo(int arriendo) {
return agua; this.arriendo = arriendo;
} }
public void setAgua(int agua) { public int getAgua() {
this.agua = agua; return agua;
} }
public int getLuz() { public void setAgua(int agua) {
return luz; this.agua = agua;
} }
public void setLuz(int luz) { public int getLuz() {
this.luz = luz; return luz;
} }
public int getGas() { public void setLuz(int luz) {
return gas; this.luz = luz;
} }
public void setGas(int gas) { public int getGas() {
this.gas = gas; return gas;
} }
public int getTelefono() { public void setGas(int gas) {
return telefono; this.gas = gas;
} }
public void setTelefono(int telefono) { public int getTelefono() {
this.telefono = telefono; return telefono;
} }
public int getOtroServicio() { public void setTelefono(int telefono) {
return otroServicio; this.telefono = telefono;
} }
public void setOtroServicio(int otroServicio) { public int getOtroServicio() {
this.otroServicio = otroServicio; return otroServicio;
} }
public double getPpm() { public void setOtroServicio(int otroServicio) {
return ppm; this.otroServicio = otroServicio;
} }
public void setPpm(double ppm) { public double getPpm() {
this.ppm = ppm; return ppm;
} }
public void setIvaFavor(int ivaFavor) { public void setPpm(double ppm) {
this.ivaFavor = ivaFavor; this.ppm = ppm;
} }
public int getIvaFavor() { public int getIvaFavor() {
return ivaFavor; return ivaFavor;
} }
public void setIvaFavor(int ivaFavor) {
this.ivaFavor = ivaFavor;
}
} }

View File

@@ -1,7 +1,6 @@
package danielcortes.xyz.models.estado_resultado; package danielcortes.xyz.models.estado_resultado;
import danielcortes.xyz.models.egreso.EgresoDAO; import danielcortes.xyz.models.egreso.EgresoDAO;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.LocalDate; import java.time.LocalDate;
@@ -11,45 +10,49 @@ import java.util.List;
import java.util.logging.Logger; import java.util.logging.Logger;
public abstract class EstadoResultadoDAO { public abstract class EstadoResultadoDAO {
protected static final Logger LOGGER = Logger.getLogger(EgresoDAO.class.getName());
protected static final Logger LOGGER = Logger.getLogger(EgresoDAO.class.getName());
public abstract List<EstadoResultado> findAll();
public abstract List<EstadoResultado> findAll(); public abstract EstadoResultado findById(int id);
public abstract EstadoResultado findById(int id);
public abstract EstadoResultado findByMonth(YearMonth month);
public abstract boolean insertEstadoResultado(EstadoResultado estadoResultado); public abstract EstadoResultado findByMonth(YearMonth month);
public abstract boolean updateEstadoResultado(EstadoResultado estadoResultado);
public abstract boolean deleteEstadoResultado(EstadoResultado estadoResultado);
List<EstadoResultado> estadoResultadosFromResultSet(ResultSet rs) throws SQLException { public abstract boolean insertEstadoResultado(EstadoResultado estadoResultado);
List<EstadoResultado> estadoResultadoList = new ArrayList<>();
while(rs.next()) { public abstract boolean updateEstadoResultado(EstadoResultado estadoResultado);
EstadoResultado estadoResultado = new EstadoResultado();
estadoResultado.setId(rs.getInt("id"));
estadoResultado.setMes(YearMonth.from(LocalDate.parse(rs.getString("mes"))));
estadoResultado.setCostoVenta(rs.getInt("costo_venta"));
estadoResultado.setCuentaCorrienteFactura(rs.getInt("cuenta_corriente_factura"));
estadoResultado.setCuentaCorrienteBoleta(rs.getInt("cuenta_corriente_boleta"));
estadoResultado.setCuentaCorrienteSinRespaldo(rs.getInt("cuenta_corriente_sin_respaldo"));
estadoResultado.setRemuneraciones(rs.getInt("remuneraciones"));
estadoResultado.setFiniquitos(rs.getInt("finiquitos"));
estadoResultado.setAguinaldo(rs.getInt("aguinaldo"));
estadoResultado.setBonosPersonal(rs.getInt("bonos_personal"));
estadoResultado.setHonorariosContador(rs.getInt("honorarios_contador"));
estadoResultado.setArriendo(rs.getInt("arriendo"));
estadoResultado.setAgua(rs.getInt("agua"));
estadoResultado.setLuz(rs.getInt("luz"));
estadoResultado.setGas(rs.getInt("gas"));
estadoResultado.setTelefono(rs.getInt("telefono"));
estadoResultado.setOtroServicio(rs.getInt("otro_servicio"));
estadoResultado.setPpm(rs.getDouble("ppm"));
estadoResultado.setIvaFavor(rs.getInt("ivaFavor"));
estadoResultadoList.add(estadoResultado); public abstract boolean deleteEstadoResultado(EstadoResultado estadoResultado);
}
return estadoResultadoList; List<EstadoResultado> estadoResultadosFromResultSet(ResultSet rs) throws SQLException {
List<EstadoResultado> estadoResultadoList = new ArrayList<>();
while (rs.next()) {
EstadoResultado estadoResultado = new EstadoResultado();
estadoResultado.setId(rs.getInt("id"));
estadoResultado.setMes(YearMonth.from(LocalDate.parse(rs.getString("mes"))));
estadoResultado.setCostoVenta(rs.getInt("costo_venta"));
estadoResultado.setCuentaCorrienteFactura(rs.getInt("cuenta_corriente_factura"));
estadoResultado.setCuentaCorrienteBoleta(rs.getInt("cuenta_corriente_boleta"));
estadoResultado.setCuentaCorrienteSinRespaldo(rs.getInt("cuenta_corriente_sin_respaldo"));
estadoResultado.setRemuneraciones(rs.getInt("remuneraciones"));
estadoResultado.setFiniquitos(rs.getInt("finiquitos"));
estadoResultado.setAguinaldo(rs.getInt("aguinaldo"));
estadoResultado.setBonosPersonal(rs.getInt("bonos_personal"));
estadoResultado.setHonorariosContador(rs.getInt("honorarios_contador"));
estadoResultado.setArriendo(rs.getInt("arriendo"));
estadoResultado.setAgua(rs.getInt("agua"));
estadoResultado.setLuz(rs.getInt("luz"));
estadoResultado.setGas(rs.getInt("gas"));
estadoResultado.setTelefono(rs.getInt("telefono"));
estadoResultado.setOtroServicio(rs.getInt("otro_servicio"));
estadoResultado.setPpm(rs.getDouble("ppm"));
estadoResultado.setIvaFavor(rs.getInt("ivaFavor"));
estadoResultadoList.add(estadoResultado);
} }
return estadoResultadoList;
}
} }

View File

@@ -1,7 +1,6 @@
package danielcortes.xyz.models.estado_resultado; package danielcortes.xyz.models.estado_resultado;
import danielcortes.xyz.data.SQLiteConnectionHolder; import danielcortes.xyz.data.SQLiteConnectionHolder;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@@ -12,183 +11,206 @@ import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
public class SQLiteEstadoResultadoDAO extends EstadoResultadoDAO { public class SQLiteEstadoResultadoDAO extends EstadoResultadoDAO {
private SQLiteConnectionHolder connectionHolder;
public SQLiteEstadoResultadoDAO() { private SQLiteConnectionHolder connectionHolder;
this.connectionHolder = new SQLiteConnectionHolder();
public SQLiteEstadoResultadoDAO() {
this.connectionHolder = new SQLiteConnectionHolder();
}
@Override
public List<EstadoResultado> findAll() {
List<EstadoResultado> estadoResultadoList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from estado_resultado";
PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", new Object[]{query});
estadoResultadoList = this.estadoResultadosFromResultSet(rs);
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
} }
return estadoResultadoList;
}
@Override @Override
public List<EstadoResultado> findAll() { public EstadoResultado findById(int id) {
List<EstadoResultado> estadoResultadoList = new ArrayList<>(); EstadoResultado estadoResultado = null;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from estado_resultado"; String query = "select * from estado_resultado where id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery(); ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", new Object[]{query}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id});
estadoResultadoList = this.estadoResultadosFromResultSet(rs); estadoResultado = this.estadoResultadosFromResultSet(rs).get(0);
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); LOGGER.log(Level.SEVERE, e.toString(), e);
}
return estadoResultadoList;
} }
return estadoResultado;
}
@Override @Override
public EstadoResultado findById(int id) { public EstadoResultado findByMonth(YearMonth month) {
EstadoResultado estadoResultado = null; EstadoResultado estadoResultado = null;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from estado_resultado where id = ?"; String query = "select * from estado_resultado where mes = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, id); ps.setString(1, month.atDay(1).toString());
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, month});
estadoResultado = this.estadoResultadosFromResultSet(rs).get(0); List<EstadoResultado> estadosResultado = this.estadoResultadosFromResultSet(rs);
if (estadosResultado.size() > 0) {
estadoResultado = estadosResultado.get(0);
}
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); LOGGER.log(Level.SEVERE, e.toString(), e);
}
return estadoResultado;
} }
return estadoResultado;
}
@Override @Override
public EstadoResultado findByMonth(YearMonth month) { public boolean insertEstadoResultado(EstadoResultado estadoResultado) {
EstadoResultado estadoResultado = null; int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from estado_resultado where mes = ?"; String query = "insert into estado_resultado (mes, costo_venta, cuenta_corriente_factura, cuenta_corriente_boleta, cuenta_corriente_sin_respaldo, remuneraciones, finiquitos, aguinaldo, bonos_personal, honorarios_contador, arriendo, agua, luz, gas, telefono, otro_servicio, ppm, ivaFavor) values (?, ?, ?, ?, ?, ? , ?, ? , ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, month.atDay(1).toString());
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, month}); ps.setString(1, estadoResultado.getMes().atDay(1).toString());
ps.setInt(2, estadoResultado.getCostoVenta());
ps.setInt(3, estadoResultado.getCuentaCorrienteFactura());
ps.setInt(4, estadoResultado.getCuentaCorrienteBoleta());
ps.setInt(5, estadoResultado.getCuentaCorrienteSinRespaldo());
ps.setInt(6, estadoResultado.getRemuneraciones());
ps.setInt(7, estadoResultado.getFiniquitos());
ps.setInt(8, estadoResultado.getAguinaldo());
ps.setInt(9, estadoResultado.getBonosPersonal());
ps.setInt(10, estadoResultado.getHonorariosContador());
ps.setInt(11, estadoResultado.getArriendo());
ps.setInt(12, estadoResultado.getAgua());
ps.setInt(13, estadoResultado.getLuz());
ps.setInt(14, estadoResultado.getGas());
ps.setInt(15, estadoResultado.getTelefono());
ps.setInt(16, estadoResultado.getOtroServicio());
ps.setDouble(17, estadoResultado.getPpm());
ps.setDouble(18, estadoResultado.getIvaFavor());
updates = ps.executeUpdate();
List<EstadoResultado> estadosResultado = this.estadoResultadosFromResultSet(rs); LOGGER.log(Level.FINE,
if (estadosResultado.size() > 0) { "QUERY: {0} | values: [{1},{2},{3},{4},{5},{6},{7},{8},{9},{10}, {11}, {12}, {13}, {14}, {15}, {16}, {17}, {18}] | updates: {19}",
estadoResultado = estadosResultado.get(0); new Object[]{query, estadoResultado.getMes(), estadoResultado.getCostoVenta(),
} estadoResultado.getCuentaCorrienteFactura(),
estadoResultado.getCuentaCorrienteBoleta(),
estadoResultado.getCuentaCorrienteSinRespaldo(), estadoResultado.getRemuneraciones(),
estadoResultado.getFiniquitos(), estadoResultado.getAguinaldo(),
estadoResultado.getBonosPersonal(), estadoResultado.getHonorariosContador(),
estadoResultado.getArriendo(), estadoResultado.getAgua(), estadoResultado.getLuz(),
estadoResultado.getGas(), estadoResultado.getTelefono(),
estadoResultado.getOtroServicio(), estadoResultado.getPpm(),
estadoResultado.getIvaFavor(), updates});
rs.close(); ps.close();
ps.close();
} catch (SQLException e) { query = "select last_insert_rowid()";
LOGGER.log(Level.SEVERE, e.toString(), e); ps = conn.prepareStatement(query);
} ResultSet rs = ps.executeQuery();
return estadoResultado;
LOGGER.log(Level.FINE, "QUERY: {0}", query);
rs.next();
estadoResultado.setId(rs.getInt(1));
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
return false;
} }
return updates > 0;
}
@Override @Override
public boolean insertEstadoResultado(EstadoResultado estadoResultado) { public boolean updateEstadoResultado(EstadoResultado estadoResultado) {
int updates; int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "insert into estado_resultado (mes, costo_venta, cuenta_corriente_factura, cuenta_corriente_boleta, cuenta_corriente_sin_respaldo, remuneraciones, finiquitos, aguinaldo, bonos_personal, honorarios_contador, arriendo, agua, luz, gas, telefono, otro_servicio, ppm, ivaFavor) values (?, ?, ?, ?, ?, ? , ?, ? , ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; String query = "update estado_resultado set mes = ?, costo_venta = ?, cuenta_corriente_factura = ?, cuenta_corriente_boleta = ?, cuenta_corriente_sin_respaldo = ?, remuneraciones = ?, finiquitos = ?, aguinaldo = ?, bonos_personal = ?, honorarios_contador = ?, arriendo = ?, agua = ?, luz = ?, gas = ?, telefono = ?, otro_servicio = ?, ppm = ?, ivaFavor = ? where id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, estadoResultado.getMes().atDay(1).toString()); ps.setString(1, estadoResultado.getMes().atDay(1).toString());
ps.setInt(2, estadoResultado.getCostoVenta()); ps.setInt(2, estadoResultado.getCostoVenta());
ps.setInt(3, estadoResultado.getCuentaCorrienteFactura()); ps.setInt(3, estadoResultado.getCuentaCorrienteFactura());
ps.setInt(4, estadoResultado.getCuentaCorrienteBoleta()); ps.setInt(4, estadoResultado.getCuentaCorrienteBoleta());
ps.setInt(5, estadoResultado.getCuentaCorrienteSinRespaldo()); ps.setInt(5, estadoResultado.getCuentaCorrienteSinRespaldo());
ps.setInt(6, estadoResultado.getRemuneraciones()); ps.setInt(6, estadoResultado.getRemuneraciones());
ps.setInt(7, estadoResultado.getFiniquitos()); ps.setInt(7, estadoResultado.getFiniquitos());
ps.setInt(8, estadoResultado.getAguinaldo()); ps.setInt(8, estadoResultado.getAguinaldo());
ps.setInt(9, estadoResultado.getBonosPersonal()); ps.setInt(9, estadoResultado.getBonosPersonal());
ps.setInt(10, estadoResultado.getHonorariosContador()); ps.setInt(10, estadoResultado.getHonorariosContador());
ps.setInt(11, estadoResultado.getArriendo()); ps.setInt(11, estadoResultado.getArriendo());
ps.setInt(12, estadoResultado.getAgua()); ps.setInt(12, estadoResultado.getAgua());
ps.setInt(13, estadoResultado.getLuz()); ps.setInt(13, estadoResultado.getLuz());
ps.setInt(14, estadoResultado.getGas()); ps.setInt(14, estadoResultado.getGas());
ps.setInt(15, estadoResultado.getTelefono()); ps.setInt(15, estadoResultado.getTelefono());
ps.setInt(16, estadoResultado.getOtroServicio()); ps.setInt(16, estadoResultado.getOtroServicio());
ps.setDouble(17, estadoResultado.getPpm()); ps.setDouble(17, estadoResultado.getPpm());
ps.setDouble(18, estadoResultado.getIvaFavor()); ps.setDouble(18, estadoResultado.getIvaFavor());
ps.setInt(19, estadoResultado.getId());
updates = ps.executeUpdate(); updates = ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1},{2},{3},{4},{5},{6},{7},{8},{9},{10}, {11}, {12}, {13}, {14}, {15}, {16}, {17}, {18}] | updates: {19}", new Object[]{query, estadoResultado.getMes(), estadoResultado.getCostoVenta(), estadoResultado.getCuentaCorrienteFactura(), estadoResultado.getCuentaCorrienteBoleta(), estadoResultado.getCuentaCorrienteSinRespaldo(), estadoResultado.getRemuneraciones(), estadoResultado.getFiniquitos(), estadoResultado.getAguinaldo(), estadoResultado.getBonosPersonal(), estadoResultado.getHonorariosContador(), estadoResultado.getArriendo(), estadoResultado.getAgua(), estadoResultado.getLuz(), estadoResultado.getGas(), estadoResultado.getTelefono(), estadoResultado.getOtroServicio(), estadoResultado.getPpm(),estadoResultado.getIvaFavor(), updates}); LOGGER.log(Level.FINE,
"QUERY: {0} | values: [{1},{2},{3},{4},{5},{6},{7},{8},{9},{10}, {11}, {12}, {13}, {14}, {15}, {16}, {17}, {18}, {19}] | updates: {20}",
new Object[]{query, estadoResultado.getMes(), estadoResultado.getCostoVenta(),
estadoResultado.getCuentaCorrienteFactura(),
estadoResultado.getCuentaCorrienteBoleta(),
estadoResultado.getCuentaCorrienteSinRespaldo(), estadoResultado.getRemuneraciones(),
estadoResultado.getFiniquitos(), estadoResultado.getAguinaldo(),
estadoResultado.getBonosPersonal(), estadoResultado.getHonorariosContador(),
estadoResultado.getArriendo(), estadoResultado.getAgua(), estadoResultado.getLuz(),
estadoResultado.getGas(), estadoResultado.getTelefono(),
estadoResultado.getOtroServicio(), estadoResultado.getPpm(),
estadoResultado.getIvaFavor(), estadoResultado.getId(), updates});
ps.close(); ps.close();
} catch (SQLException e) {
query = "select last_insert_rowid()"; LOGGER.log(Level.SEVERE, e.toString(), e);
ps = conn.prepareStatement(query); return false;
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", query);
rs.next();
estadoResultado.setId(rs.getInt(1));
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
return false;
}
return updates > 0;
} }
return updates > 0;
}
@Override @Override
public boolean updateEstadoResultado(EstadoResultado estadoResultado) { public boolean deleteEstadoResultado(EstadoResultado estadoResultado) {
int updates; int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "update estado_resultado set mes = ?, costo_venta = ?, cuenta_corriente_factura = ?, cuenta_corriente_boleta = ?, cuenta_corriente_sin_respaldo = ?, remuneraciones = ?, finiquitos = ?, aguinaldo = ?, bonos_personal = ?, honorarios_contador = ?, arriendo = ?, agua = ?, luz = ?, gas = ?, telefono = ?, otro_servicio = ?, ppm = ?, ivaFavor = ? where id = ?"; String query = "delete from estado_resultado where id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, estadoResultado.getId());
updates = ps.executeUpdate();
ps.setString(1, estadoResultado.getMes().atDay(1).toString()); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}",
ps.setInt(2, estadoResultado.getCostoVenta()); new Object[]{query, estadoResultado.getId(), updates});
ps.setInt(3, estadoResultado.getCuentaCorrienteFactura());
ps.setInt(4, estadoResultado.getCuentaCorrienteBoleta());
ps.setInt(5, estadoResultado.getCuentaCorrienteSinRespaldo());
ps.setInt(6, estadoResultado.getRemuneraciones());
ps.setInt(7, estadoResultado.getFiniquitos());
ps.setInt(8, estadoResultado.getAguinaldo());
ps.setInt(9, estadoResultado.getBonosPersonal());
ps.setInt(10, estadoResultado.getHonorariosContador());
ps.setInt(11, estadoResultado.getArriendo());
ps.setInt(12, estadoResultado.getAgua());
ps.setInt(13, estadoResultado.getLuz());
ps.setInt(14, estadoResultado.getGas());
ps.setInt(15, estadoResultado.getTelefono());
ps.setInt(16, estadoResultado.getOtroServicio());
ps.setDouble(17, estadoResultado.getPpm());
ps.setDouble(18, estadoResultado.getIvaFavor());
ps.setInt(19, estadoResultado.getId());
updates = ps.executeUpdate(); ps.close();
} catch (SQLException e) {
LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1},{2},{3},{4},{5},{6},{7},{8},{9},{10}, {11}, {12}, {13}, {14}, {15}, {16}, {17}, {18}, {19}] | updates: {20}", new Object[]{query, estadoResultado.getMes(), estadoResultado.getCostoVenta(), estadoResultado.getCuentaCorrienteFactura(), estadoResultado.getCuentaCorrienteBoleta(), estadoResultado.getCuentaCorrienteSinRespaldo(), estadoResultado.getRemuneraciones(), estadoResultado.getFiniquitos(), estadoResultado.getAguinaldo(), estadoResultado.getBonosPersonal(), estadoResultado.getHonorariosContador(), estadoResultado.getArriendo(), estadoResultado.getAgua(), estadoResultado.getLuz(), estadoResultado.getGas(), estadoResultado.getTelefono(), estadoResultado.getOtroServicio(), estadoResultado.getPpm(),estadoResultado.getIvaFavor(), estadoResultado.getId(), updates}); LOGGER.log(Level.SEVERE, e.toString(), e);
return false;
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
return false;
}
return updates > 0;
}
@Override
public boolean deleteEstadoResultado(EstadoResultado estadoResultado) {
int updates;
try (Connection conn = connectionHolder.getConnection()) {
String query = "delete from estado_resultado where id = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, estadoResultado.getId());
updates = ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}", new Object[]{query, estadoResultado.getId(), updates});
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
return false;
}
return updates > 0;
} }
return updates > 0;
}
} }

View File

@@ -27,50 +27,51 @@ package danielcortes.xyz.models.informes.egresos;
import java.time.LocalDate; import java.time.LocalDate;
public class InformeEgresosContent { public class InformeEgresosContent {
private LocalDate fecha;
private String nro;
private String descripcion;
private int valor;
public LocalDate getFecha() { private LocalDate fecha;
return fecha; private String nro;
} private String descripcion;
private int valor;
public void setFecha(LocalDate fecha) { public LocalDate getFecha() {
this.fecha = fecha; return fecha;
} }
public String getNro() { public void setFecha(LocalDate fecha) {
return nro; this.fecha = fecha;
} }
public void setNro(String nro) { public String getNro() {
this.nro = nro; return nro;
} }
public String getDescripcion() { public void setNro(String nro) {
return descripcion; this.nro = nro;
} }
public void setDescripcion(String descripcion) { public String getDescripcion() {
this.descripcion = descripcion; return descripcion;
} }
public int getValor() { public void setDescripcion(String descripcion) {
return valor; this.descripcion = descripcion;
} }
public void setValor(int valor) { public int getValor() {
this.valor = valor; return valor;
} }
@Override public void setValor(int valor) {
public String toString() { this.valor = valor;
return "InformeEgresosContent{" + }
"fecha=" + fecha +
", nro='" + nro + '\'' + @Override
", descripcion='" + descripcion + '\'' + public String toString() {
", valor=" + valor + return "InformeEgresosContent{" +
'}'; "fecha=" + fecha +
} ", nro='" + nro + '\'' +
", descripcion='" + descripcion + '\'' +
", valor=" + valor +
'}';
}
} }

View File

@@ -25,18 +25,19 @@
package danielcortes.xyz.models.informes.egresos; package danielcortes.xyz.models.informes.egresos;
import danielcortes.xyz.data.ConnectionHolder; import danielcortes.xyz.data.ConnectionHolder;
import java.time.YearMonth; import java.time.YearMonth;
import java.util.List; import java.util.List;
public abstract class InformeEgresosContentDAO { public abstract class InformeEgresosContentDAO {
protected ConnectionHolder connectionHolder;
/** protected ConnectionHolder connectionHolder;
* Genera el informe con nombre muy largo
* /**
* @param mes mes sobre el cual se quiere le informe * Genera el informe con nombre muy largo
* @return lista del objeto que contiene los datos necesarios para el informe *
*/ * @param mes mes sobre el cual se quiere le informe
public abstract List<InformeEgresosContent> getInformeEgresosFactuasMateriaPrima(YearMonth mes, int tipoEgresoId); * @return lista del objeto que contiene los datos necesarios para el informe
*/
public abstract List<InformeEgresosContent> getInformeEgresosFactuasMateriaPrima(YearMonth mes,
int tipoEgresoId);
} }

View File

@@ -25,7 +25,6 @@
package danielcortes.xyz.models.informes.egresos; package danielcortes.xyz.models.informes.egresos;
import danielcortes.xyz.data.SQLiteConnectionHolder; import danielcortes.xyz.data.SQLiteConnectionHolder;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@@ -38,51 +37,54 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public class SQLiteInformeEgresosContentDAO extends InformeEgresosContentDAO { public class SQLiteInformeEgresosContentDAO extends InformeEgresosContentDAO {
private static final Logger LOGGER = Logger.getLogger(InformeEgresosContentDAO.class.getName());
private List<InformeEgresosContent> list; private static final Logger LOGGER = Logger.getLogger(InformeEgresosContentDAO.class.getName());
public SQLiteInformeEgresosContentDAO() { private List<InformeEgresosContent> list;
this.connectionHolder = new SQLiteConnectionHolder();
public SQLiteInformeEgresosContentDAO() {
this.connectionHolder = new SQLiteConnectionHolder();
}
@Override
public List<InformeEgresosContent> getInformeEgresosFactuasMateriaPrima(YearMonth mes,
int tipoEgresoId) {
list = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) {
String query = "select caja.fecha as \"fecha\"," +
"egresos.nro as \"nro\"," +
"egresos.descripcion as \"descripcion\"," +
"egresos.valor as \"valor\"" +
"from egresos inner join caja on egresos.caja_id = caja.id " +
"where caja.fecha between date(?) and date(?) and egresos.tipo_egreso_id = ? " +
"order by caja.fecha;";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, mes.atDay(1).toString());
ps.setString(2, mes.atEndOfMonth().toString());
ps.setInt(3, tipoEgresoId);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1},{2},{3}]",
new Object[]{mes.atDay(1), mes.atEndOfMonth(), tipoEgresoId});
this.fillInforme(rs);
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
} }
return list;
}
@Override private void fillInforme(ResultSet rs) throws SQLException {
public List<InformeEgresosContent> getInformeEgresosFactuasMateriaPrima(YearMonth mes, int tipoEgresoId) { while (rs.next()) {
list = new ArrayList<>(); InformeEgresosContent content = new InformeEgresosContent();
try (Connection conn = connectionHolder.getConnection()) { content.setFecha(LocalDate.parse(rs.getString("fecha")));
content.setDescripcion(rs.getString("descripcion"));
String query = "select caja.fecha as \"fecha\"," + content.setNro(rs.getString("nro"));
"egresos.nro as \"nro\"," + content.setValor(rs.getInt("valor"));
"egresos.descripcion as \"descripcion\"," + LOGGER.log(Level.FINER, "Se a creado: {0}", content);
"egresos.valor as \"valor\"" + list.add(content);
"from egresos inner join caja on egresos.caja_id = caja.id " +
"where caja.fecha between date(?) and date(?) and egresos.tipo_egreso_id = ? " +
"order by caja.fecha;";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, mes.atDay(1).toString());
ps.setString(2, mes.atEndOfMonth().toString());
ps.setInt(3, tipoEgresoId);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1},{2},{3}]", new Object[]{mes.atDay(1), mes.atEndOfMonth(), tipoEgresoId});
this.fillInforme(rs);
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
return list;
}
private void fillInforme(ResultSet rs) throws SQLException {
while (rs.next()) {
InformeEgresosContent content = new InformeEgresosContent();
content.setFecha(LocalDate.parse(rs.getString("fecha")));
content.setDescripcion(rs.getString("descripcion"));
content.setNro(rs.getString("nro"));
content.setValor(rs.getInt("valor"));
LOGGER.log(Level.FINER, "Se a creado: {0}", content);
list.add(content);
}
} }
}
} }

View File

@@ -51,222 +51,223 @@ package danielcortes.xyz.models.informes.libro_de_ventas;
import java.time.LocalDate; import java.time.LocalDate;
public class InformeLibroDeVentasContent { public class InformeLibroDeVentasContent {
private int dia;
private LocalDate fecha;
private String manualesInicial;
private String manualesFinal;
private int manuales;
private String fiscalesZInicial;
private String fiscalesZFinal;
private String fiscalesInicial;
private String fiscalesFinal;
private int fiscales;
private String exentasInicial;
private String exentasFinal;
private int exentas;
private int subTotal;
private String facturasInicial;
private String facturasFinal;
private int facturas;
private String guiasInicial;
private String guiasFinal;
private int guias;
private int total;
public int getDia() { private int dia;
return dia; private LocalDate fecha;
} private String manualesInicial;
private String manualesFinal;
private int manuales;
private String fiscalesZInicial;
private String fiscalesZFinal;
private String fiscalesInicial;
private String fiscalesFinal;
private int fiscales;
private String exentasInicial;
private String exentasFinal;
private int exentas;
private int subTotal;
private String facturasInicial;
private String facturasFinal;
private int facturas;
private String guiasInicial;
private String guiasFinal;
private int guias;
private int total;
public void setDia(int dia) { public int getDia() {
this.dia = dia; return dia;
} }
public LocalDate getFecha() { public void setDia(int dia) {
return fecha; this.dia = dia;
} }
public void setFecha(LocalDate fecha) { public LocalDate getFecha() {
this.fecha = fecha; return fecha;
} }
public String getManualesInicial() { public void setFecha(LocalDate fecha) {
return manualesInicial; this.fecha = fecha;
} }
public void setManualesInicial(String manualesInicial) { public String getManualesInicial() {
this.manualesInicial = manualesInicial; return manualesInicial;
} }
public String getManualesFinal() { public void setManualesInicial(String manualesInicial) {
this.manualesInicial = manualesInicial;
}
return manualesFinal; public String getManualesFinal() {
}
public void setManualesFinal(String manualesFinal) { return manualesFinal;
this.manualesFinal = manualesFinal; }
}
public int getManuales() { public void setManualesFinal(String manualesFinal) {
return manuales; this.manualesFinal = manualesFinal;
} }
public void setManuales(int manuales) { public int getManuales() {
this.manuales = manuales; return manuales;
} }
public String getFiscalesZInicial() { public void setManuales(int manuales) {
return fiscalesZInicial; this.manuales = manuales;
} }
public void setFiscalesZInicial(String fiscalesZInicial) { public String getFiscalesZInicial() {
this.fiscalesZInicial = fiscalesZInicial; return fiscalesZInicial;
} }
public String getFiscalesZFinal() { public void setFiscalesZInicial(String fiscalesZInicial) {
return fiscalesZFinal; this.fiscalesZInicial = fiscalesZInicial;
} }
public void setFiscalesZFinal(String fiscalesZFinal) { public String getFiscalesZFinal() {
this.fiscalesZFinal = fiscalesZFinal; return fiscalesZFinal;
} }
public String getFiscalesInicial() { public void setFiscalesZFinal(String fiscalesZFinal) {
return fiscalesInicial; this.fiscalesZFinal = fiscalesZFinal;
} }
public void setFiscalesInicial(String fiscalesInicial) { public String getFiscalesInicial() {
this.fiscalesInicial = fiscalesInicial; return fiscalesInicial;
} }
public String getFiscalesFinal() { public void setFiscalesInicial(String fiscalesInicial) {
return fiscalesFinal; this.fiscalesInicial = fiscalesInicial;
} }
public void setFiscalesFinal(String fiscalesFinal) { public String getFiscalesFinal() {
this.fiscalesFinal = fiscalesFinal; return fiscalesFinal;
} }
public int getFiscales() { public void setFiscalesFinal(String fiscalesFinal) {
return fiscales; this.fiscalesFinal = fiscalesFinal;
} }
public void setFiscales(int fiscales) { public int getFiscales() {
this.fiscales = fiscales; return fiscales;
} }
public String getExentasInicial() { public void setFiscales(int fiscales) {
return exentasInicial; this.fiscales = fiscales;
} }
public void setExentasInicial(String exentasInicial) { public String getExentasInicial() {
this.exentasInicial = exentasInicial; return exentasInicial;
} }
public String getExentasFinal() { public void setExentasInicial(String exentasInicial) {
return exentasFinal; this.exentasInicial = exentasInicial;
} }
public void setExentasFinal(String exentasFinal) { public String getExentasFinal() {
this.exentasFinal = exentasFinal; return exentasFinal;
} }
public int getExentas() { public void setExentasFinal(String exentasFinal) {
return exentas; this.exentasFinal = exentasFinal;
} }
public void setExentas(int exentas) { public int getExentas() {
this.exentas = exentas; return exentas;
} }
public int getSubTotal() { public void setExentas(int exentas) {
return subTotal; this.exentas = exentas;
} }
public void setSubTotal(int sub_total) { public int getSubTotal() {
this.subTotal = sub_total; return subTotal;
} }
public String getFacturasInicial() { public void setSubTotal(int sub_total) {
return facturasInicial; this.subTotal = sub_total;
} }
public void setFacturasInicial(String facturasInicial) { public String getFacturasInicial() {
this.facturasInicial = facturasInicial; return facturasInicial;
} }
public String getFacturasFinal() { public void setFacturasInicial(String facturasInicial) {
return facturasFinal; this.facturasInicial = facturasInicial;
} }
public void setFacturasFinal(String facturasFinal) { public String getFacturasFinal() {
this.facturasFinal = facturasFinal; return facturasFinal;
} }
public int getFacturas() { public void setFacturasFinal(String facturasFinal) {
return facturas; this.facturasFinal = facturasFinal;
} }
public void setFacturas(int facturas) { public int getFacturas() {
this.facturas = facturas; return facturas;
} }
public String getGuiasInicial() { public void setFacturas(int facturas) {
return guiasInicial; this.facturas = facturas;
} }
public void setGuiasInicial(String guiasInicial) { public String getGuiasInicial() {
this.guiasInicial = guiasInicial; return guiasInicial;
} }
public String getGuiasFinal() { public void setGuiasInicial(String guiasInicial) {
return guiasFinal; this.guiasInicial = guiasInicial;
} }
public void setGuiasFinal(String guiasFinal) { public String getGuiasFinal() {
this.guiasFinal = guiasFinal; return guiasFinal;
} }
public int getGuias() { public void setGuiasFinal(String guiasFinal) {
return guias; this.guiasFinal = guiasFinal;
} }
public void setGuias(int guias) { public int getGuias() {
this.guias = guias; return guias;
} }
public int getTotal() { public void setGuias(int guias) {
return total; this.guias = guias;
} }
public void setTotal(int total) { public int getTotal() {
this.total = total; return total;
} }
public void setTotal(int total) {
this.total = total;
}
@Override @Override
public String toString() { public String toString() {
return "InformeLibroDeVentasContent{" + return "InformeLibroDeVentasContent{" +
"dia=" + dia + "dia=" + dia +
", fecha=" + fecha + ", fecha=" + fecha +
", manualesInicial='" + manualesInicial + '\'' + ", manualesInicial='" + manualesInicial + '\'' +
", manualesFinal='" + manualesFinal + '\'' + ", manualesFinal='" + manualesFinal + '\'' +
", manuales=" + manuales + ", manuales=" + manuales +
", fiscalesZInicial='" + fiscalesZInicial + '\'' + ", fiscalesZInicial='" + fiscalesZInicial + '\'' +
", fiscalesZFinal='" + fiscalesZFinal + '\'' + ", fiscalesZFinal='" + fiscalesZFinal + '\'' +
", fiscalesInicial='" + fiscalesInicial + '\'' + ", fiscalesInicial='" + fiscalesInicial + '\'' +
", fiscalesFinal='" + fiscalesFinal + '\'' + ", fiscalesFinal='" + fiscalesFinal + '\'' +
", fiscales=" + fiscales + ", fiscales=" + fiscales +
", exentasInicial='" + exentasInicial + '\'' + ", exentasInicial='" + exentasInicial + '\'' +
", exentasFinal='" + exentasFinal + '\'' + ", exentasFinal='" + exentasFinal + '\'' +
", exentas=" + exentas + ", exentas=" + exentas +
", subTotal=" + subTotal + ", subTotal=" + subTotal +
", facturasInicial='" + facturasInicial + '\'' + ", facturasInicial='" + facturasInicial + '\'' +
", facturasFinal='" + facturasFinal + '\'' + ", facturasFinal='" + facturasFinal + '\'' +
", facturas=" + facturas + ", facturas=" + facturas +
", guiasInicial='" + guiasInicial + '\'' + ", guiasInicial='" + guiasInicial + '\'' +
", guiasFinal='" + guiasFinal + '\'' + ", guiasFinal='" + guiasFinal + '\'' +
", guias=" + guias + ", guias=" + guias +
", total=" + total + ", total=" + total +
'}'; '}';
} }
} }

View File

@@ -25,18 +25,18 @@
package danielcortes.xyz.models.informes.libro_de_ventas; package danielcortes.xyz.models.informes.libro_de_ventas;
import danielcortes.xyz.data.ConnectionHolder; import danielcortes.xyz.data.ConnectionHolder;
import java.time.YearMonth; import java.time.YearMonth;
import java.util.Collection; import java.util.Collection;
public abstract class InformeLibroDeVentasContentDAO { public abstract class InformeLibroDeVentasContentDAO {
protected ConnectionHolder connectionHolder;
/** protected ConnectionHolder connectionHolder;
* Genera el contenido del informes mensual
* /**
* @param mes el que se necesita el informes * Genera el contenido del informes mensual
* @return Lista con las columnas principales necesarias para el informes *
*/ * @param mes el que se necesita el informes
public abstract Collection<InformeLibroDeVentasContent> getInformeMensual(YearMonth mes); * @return Lista con las columnas principales necesarias para el informes
*/
public abstract Collection<InformeLibroDeVentasContent> getInformeMensual(YearMonth mes);
} }

View File

@@ -50,7 +50,6 @@ package danielcortes.xyz.models.informes.libro_de_ventas;
import danielcortes.xyz.data.SQLiteConnectionHolder; import danielcortes.xyz.data.SQLiteConnectionHolder;
import danielcortes.xyz.utils.NaturalOrderComparator; import danielcortes.xyz.utils.NaturalOrderComparator;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@@ -64,214 +63,226 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public class SQLiteInformeLibroDeVentasContentDAO extends InformeLibroDeVentasContentDAO { public class SQLiteInformeLibroDeVentasContentDAO extends InformeLibroDeVentasContentDAO {
private static final Logger LOGGER = Logger.getLogger(SQLiteInformeLibroDeVentasContentDAO.class.getName());
private HashMap<Integer, InformeLibroDeVentasContent> map; private static final Logger LOGGER = Logger
.getLogger(SQLiteInformeLibroDeVentasContentDAO.class.getName());
public SQLiteInformeLibroDeVentasContentDAO() { private HashMap<Integer, InformeLibroDeVentasContent> map;
this.connectionHolder = new SQLiteConnectionHolder();
public SQLiteInformeLibroDeVentasContentDAO() {
this.connectionHolder = new SQLiteConnectionHolder();
}
@Override
public Collection<InformeLibroDeVentasContent> getInformeMensual(YearMonth date) {
this.map = new HashMap<>();
try (Connection conn = connectionHolder.getConnection()) {
String queryTotales =
"select " +
"caja.id as \"caja\"," +
"strftime(\"%w\", caja.fecha) as \"dia\"," +
"caja.fecha as \"fecha\"," +
"sum(case when ingresos.tipo_ingreso_id = 2 then ingresos.valor else 0 end) as \"manuales\","
+
"sum(case when ingresos.tipo_ingreso_id = 1 then ingresos.valor else 0 end) as \"fiscales\","
+
"sum(case when ingresos.tipo_ingreso_id = 5 then ingresos.valor else 0 end) as \"exentas\","
+
"sum(case when ingresos.tipo_ingreso_id in (2, 1, 5) then ingresos.valor else 0 end) as \"sub_total\","
+
"sum(case when ingresos.tipo_ingreso_id = 3 then ingresos.valor else 0 end) as \"facturas\","
+
"sum(case when ingresos.tipo_ingreso_id = 4 then ingresos.valor else 0 end) as \"guias\","
+
"sum(case when ingresos.valor not null then ingresos.valor else 0 end) as \"total\" "
+
"from caja left join ingresos on (caja.id = ingresos.caja_id) " +
"where caja.fecha between date(?) and date(?) " +
"group by caja.fecha;";
PreparedStatement ps = conn.prepareStatement(queryTotales);
ps.setString(1, date.atDay(1).toString());
ps.setString(2, date.atEndOfMonth().toString());
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1},{2}]",
new Object[]{queryTotales, date.atDay(1), date.atEndOfMonth()});
this.fillTotalesFromResultSet(rs);
String queryNumeros =
"select\n" +
"caja.id as \"caja\"," +
"caja.fecha as \"fecha\"," +
"ingresos.nro_inicial as \"inicial\"," +
"ingresos.nro_final as \"final\"," +
"ingresos.nro_z_inicial as \"z_inicial\"," +
"ingresos.nro_z_final as \"z_final\"," +
"ingresos.tipo_ingreso_id as \"tipo_ingreso\" " +
"from caja join ingresos on (caja.id = ingresos.caja_id) " +
"where caja.fecha between date(?) and date(?);";
ps = conn.prepareStatement(queryNumeros);
ps.setString(1, date.atDay(1).toString());
ps.setString(2, date.atEndOfMonth().toString());
rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1},{2}]",
new Object[]{queryNumeros, date.atDay(1), date.atEndOfMonth()});
this.fillBoletasFromResultSet(rs);
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
} }
@Override return map.values();
public Collection<InformeLibroDeVentasContent> getInformeMensual(YearMonth date) { }
this.map = new HashMap<>();
try (Connection conn = connectionHolder.getConnection()) {
String queryTotales =
"select " +
"caja.id as \"caja\"," +
"strftime(\"%w\", caja.fecha) as \"dia\"," +
"caja.fecha as \"fecha\"," +
"sum(case when ingresos.tipo_ingreso_id = 2 then ingresos.valor else 0 end) as \"manuales\"," +
"sum(case when ingresos.tipo_ingreso_id = 1 then ingresos.valor else 0 end) as \"fiscales\"," +
"sum(case when ingresos.tipo_ingreso_id = 5 then ingresos.valor else 0 end) as \"exentas\"," +
"sum(case when ingresos.tipo_ingreso_id in (2, 1, 5) then ingresos.valor else 0 end) as \"sub_total\"," +
"sum(case when ingresos.tipo_ingreso_id = 3 then ingresos.valor else 0 end) as \"facturas\"," +
"sum(case when ingresos.tipo_ingreso_id = 4 then ingresos.valor else 0 end) as \"guias\"," +
"sum(case when ingresos.valor not null then ingresos.valor else 0 end) as \"total\" " +
"from caja left join ingresos on (caja.id = ingresos.caja_id) " +
"where caja.fecha between date(?) and date(?) " +
"group by caja.fecha;";
PreparedStatement ps = conn.prepareStatement(queryTotales);
ps.setString(1, date.atDay(1).toString());
ps.setString(2, date.atEndOfMonth().toString());
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1},{2}]", new Object[]{queryTotales, date.atDay(1), date.atEndOfMonth()}); private void fillTotalesFromResultSet(ResultSet rs) throws SQLException {
while (rs.next()) {
this.fillTotalesFromResultSet(rs); InformeLibroDeVentasContent informe = new InformeLibroDeVentasContent();
informe.setDia(rs.getInt("dia"));
String queryNumeros = informe.setFecha(LocalDate.parse(rs.getString("fecha")));
"select\n" + informe.setManuales(rs.getInt("manuales"));
"caja.id as \"caja\"," + informe.setFiscales(rs.getInt("fiscales"));
"caja.fecha as \"fecha\"," + informe.setExentas(rs.getInt("exentas"));
"ingresos.nro_inicial as \"inicial\"," + informe.setSubTotal(rs.getInt("sub_total"));
"ingresos.nro_final as \"final\"," + informe.setFacturas(rs.getInt("facturas"));
"ingresos.nro_z_inicial as \"z_inicial\"," + informe.setGuias(rs.getInt("guias"));
"ingresos.nro_z_final as \"z_final\"," + informe.setTotal(rs.getInt("total"));
"ingresos.tipo_ingreso_id as \"tipo_ingreso\" " + LOGGER.log(Level.FINER, "Se a creado una linea del informe con los totales {0}", informe);
"from caja join ingresos on (caja.id = ingresos.caja_id) " + map.put(rs.getInt("caja"), informe);
"where caja.fecha between date(?) and date(?);";
ps = conn.prepareStatement(queryNumeros);
ps.setString(1, date.atDay(1).toString());
ps.setString(2, date.atEndOfMonth().toString());
rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1},{2}]", new Object[]{queryNumeros, date.atDay(1), date.atEndOfMonth()});
this.fillBoletasFromResultSet(rs);
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
return map.values();
} }
}
private void fillTotalesFromResultSet(ResultSet rs) throws SQLException { private void fillBoletasFromResultSet(ResultSet rs) throws SQLException {
while (rs.next()) { Comparator<String> comparator = new NaturalOrderComparator();
InformeLibroDeVentasContent informe = new InformeLibroDeVentasContent(); while (rs.next()) {
informe.setDia(rs.getInt("dia")); InformeLibroDeVentasContent informe = map.get(rs.getInt("caja"));
informe.setFecha(LocalDate.parse(rs.getString("fecha"))); int tipoIngreso = rs.getInt("tipo_ingreso");
informe.setManuales(rs.getInt("manuales")); switch (tipoIngreso) {
informe.setFiscales(rs.getInt("fiscales")); case 1:
informe.setExentas(rs.getInt("exentas")); String fiscalesInicial = rs.getString("inicial");
informe.setSubTotal(rs.getInt("sub_total")); String fiscalesFinal = rs.getString("final");
informe.setFacturas(rs.getInt("facturas")); String fiscalesZInicial = rs.getString("z_inicial");
informe.setGuias(rs.getInt("guias")); String fiscalesZFinal = rs.getString("z_final");
informe.setTotal(rs.getInt("total"));
LOGGER.log(Level.FINER, "Se a creado una linea del informe con los totales {0}", informe);
map.put(rs.getInt("caja"), informe);
}
}
private void fillBoletasFromResultSet(ResultSet rs) throws SQLException { if (informe.getFiscalesInicial() != null) {
Comparator<String> comparator = new NaturalOrderComparator(); if (comparator.compare(fiscalesInicial, informe.getFiscalesInicial()) < 0) {
while (rs.next()) { informe.setFiscalesInicial(fiscalesInicial);
InformeLibroDeVentasContent informe = map.get(rs.getInt("caja"));
int tipoIngreso = rs.getInt("tipo_ingreso");
switch (tipoIngreso) {
case 1:
String fiscalesInicial = rs.getString("inicial");
String fiscalesFinal = rs.getString("final");
String fiscalesZInicial = rs.getString("z_inicial");
String fiscalesZFinal = rs.getString("z_final");
if (informe.getFiscalesInicial() != null) {
if (comparator.compare(fiscalesInicial, informe.getFiscalesInicial()) < 0) {
informe.setFiscalesInicial(fiscalesInicial);
}
} else {
informe.setFiscalesInicial(fiscalesInicial);
}
if (informe.getFiscalesFinal() != null) {
if (comparator.compare(fiscalesFinal, informe.getFiscalesFinal()) > 0) {
informe.setFiscalesFinal(fiscalesFinal);
}
} else {
informe.setFiscalesFinal(fiscalesFinal);
}
if (informe.getFiscalesZInicial() != null) {
if (comparator.compare(fiscalesZInicial, informe.getFiscalesZInicial()) < 0) {
informe.setFiscalesZInicial(fiscalesZInicial);
}
} else {
informe.setFiscalesZInicial(fiscalesZInicial);
}
if (informe.getFiscalesZFinal() != null) {
if (comparator.compare(fiscalesZFinal, informe.getFiscalesZFinal()) > 0) {
informe.setFiscalesZFinal(fiscalesZFinal);
}
} else {
informe.setFiscalesZFinal(fiscalesZFinal);
}
break;
case 2:
String manualesInicial = rs.getString("inicial");
String manualesFinal = rs.getString("final");
if (informe.getManualesInicial() != null) {
if (comparator.compare(manualesInicial, informe.getManualesInicial()) < 0) {
informe.setManualesInicial(manualesInicial);
}
} else {
informe.setManualesInicial(manualesInicial);
}
if (informe.getManualesFinal() != null) {
if (comparator.compare(manualesFinal, informe.getManualesFinal()) > 0) {
informe.setManualesFinal(manualesFinal);
}
} else {
informe.setManualesFinal(manualesFinal);
}
break;
case 3:
String facturasInicial = rs.getString("inicial");
String facturasFinal = rs.getString("final");
if (informe.getFacturasInicial() != null) {
if (comparator.compare(facturasInicial, informe.getFacturasInicial()) < 0) {
informe.setFacturasInicial(facturasInicial);
}
} else {
informe.setFacturasInicial(facturasInicial);
}
if (informe.getFacturasFinal() != null) {
if (comparator.compare(facturasFinal, informe.getFacturasFinal()) > 0) {
informe.setFacturasFinal(facturasFinal);
}
} else {
informe.setFacturasFinal(facturasFinal);
}
break;
case 4:
String guiasInicial = rs.getString("inicial");
String guiasFinal = rs.getString("final");
if (informe.getGuiasInicial() != null) {
if (comparator.compare(guiasInicial, informe.getGuiasInicial()) < 0) {
informe.setGuiasInicial(guiasInicial);
}
} else {
informe.setGuiasInicial(guiasInicial);
}
if (informe.getGuiasFinal() != null) {
if (comparator.compare(guiasFinal, informe.getGuiasFinal()) > 0) {
informe.setGuiasFinal(guiasFinal);
}
} else {
informe.setGuiasFinal(guiasFinal);
}
break;
case 5:
String exentasInicial = rs.getString("inicial");
String exentasFinal = rs.getString("final");
if (informe.getExentasInicial() != null) {
if (comparator.compare(exentasInicial, informe.getExentasInicial()) < 0) {
informe.setExentasInicial(exentasInicial);
}
} else {
informe.setExentasInicial(exentasInicial);
}
if (informe.getExentasFinal() != null) {
if (comparator.compare(exentasFinal, informe.getExentasFinal()) > 0) {
informe.setExentasFinal(exentasFinal);
}
} else {
informe.setExentasFinal(exentasFinal);
}
break;
} }
LOGGER.log(Level.FINER, "Se termino de llenar la linea del informe resultando en: {0}", informe); } else {
} informe.setFiscalesInicial(fiscalesInicial);
}
if (informe.getFiscalesFinal() != null) {
if (comparator.compare(fiscalesFinal, informe.getFiscalesFinal()) > 0) {
informe.setFiscalesFinal(fiscalesFinal);
}
} else {
informe.setFiscalesFinal(fiscalesFinal);
}
if (informe.getFiscalesZInicial() != null) {
if (comparator.compare(fiscalesZInicial, informe.getFiscalesZInicial()) < 0) {
informe.setFiscalesZInicial(fiscalesZInicial);
}
} else {
informe.setFiscalesZInicial(fiscalesZInicial);
}
if (informe.getFiscalesZFinal() != null) {
if (comparator.compare(fiscalesZFinal, informe.getFiscalesZFinal()) > 0) {
informe.setFiscalesZFinal(fiscalesZFinal);
}
} else {
informe.setFiscalesZFinal(fiscalesZFinal);
}
break;
case 2:
String manualesInicial = rs.getString("inicial");
String manualesFinal = rs.getString("final");
if (informe.getManualesInicial() != null) {
if (comparator.compare(manualesInicial, informe.getManualesInicial()) < 0) {
informe.setManualesInicial(manualesInicial);
}
} else {
informe.setManualesInicial(manualesInicial);
}
if (informe.getManualesFinal() != null) {
if (comparator.compare(manualesFinal, informe.getManualesFinal()) > 0) {
informe.setManualesFinal(manualesFinal);
}
} else {
informe.setManualesFinal(manualesFinal);
}
break;
case 3:
String facturasInicial = rs.getString("inicial");
String facturasFinal = rs.getString("final");
if (informe.getFacturasInicial() != null) {
if (comparator.compare(facturasInicial, informe.getFacturasInicial()) < 0) {
informe.setFacturasInicial(facturasInicial);
}
} else {
informe.setFacturasInicial(facturasInicial);
}
if (informe.getFacturasFinal() != null) {
if (comparator.compare(facturasFinal, informe.getFacturasFinal()) > 0) {
informe.setFacturasFinal(facturasFinal);
}
} else {
informe.setFacturasFinal(facturasFinal);
}
break;
case 4:
String guiasInicial = rs.getString("inicial");
String guiasFinal = rs.getString("final");
if (informe.getGuiasInicial() != null) {
if (comparator.compare(guiasInicial, informe.getGuiasInicial()) < 0) {
informe.setGuiasInicial(guiasInicial);
}
} else {
informe.setGuiasInicial(guiasInicial);
}
if (informe.getGuiasFinal() != null) {
if (comparator.compare(guiasFinal, informe.getGuiasFinal()) > 0) {
informe.setGuiasFinal(guiasFinal);
}
} else {
informe.setGuiasFinal(guiasFinal);
}
break;
case 5:
String exentasInicial = rs.getString("inicial");
String exentasFinal = rs.getString("final");
if (informe.getExentasInicial() != null) {
if (comparator.compare(exentasInicial, informe.getExentasInicial()) < 0) {
informe.setExentasInicial(exentasInicial);
}
} else {
informe.setExentasInicial(exentasInicial);
}
if (informe.getExentasFinal() != null) {
if (comparator.compare(exentasFinal, informe.getExentasFinal()) > 0) {
informe.setExentasFinal(exentasFinal);
}
} else {
informe.setExentasFinal(exentasFinal);
}
break;
}
LOGGER.log(Level.FINER, "Se termino de llenar la linea del informe resultando en: {0}",
informe);
} }
}
} }

View File

@@ -28,90 +28,91 @@ import danielcortes.xyz.models.caja.Caja;
import danielcortes.xyz.models.tipo_ingreso.TipoIngreso; import danielcortes.xyz.models.tipo_ingreso.TipoIngreso;
public class Ingreso { public class Ingreso {
private int id;
private int valor;
private String nroZInicial;
private String nroZFinal;
private String nroInicial;
private String nroFinal;
private TipoIngreso tipoIngreso;
private Caja caja;
public int getId() { private int id;
return id; private int valor;
} private String nroZInicial;
private String nroZFinal;
private String nroInicial;
private String nroFinal;
private TipoIngreso tipoIngreso;
private Caja caja;
public void setId(int id) { public int getId() {
this.id = id; return id;
} }
public int getValor() { public void setId(int id) {
return valor; this.id = id;
} }
public void setValor(int valor) { public int getValor() {
this.valor = valor; return valor;
} }
public String getNroZInicial() { public void setValor(int valor) {
return nroZInicial; this.valor = valor;
} }
public void setNroZInicial(String nroZInicial) { public String getNroZInicial() {
this.nroZInicial = nroZInicial; return nroZInicial;
} }
public String getNroZFinal() { public void setNroZInicial(String nroZInicial) {
return nroZFinal; this.nroZInicial = nroZInicial;
} }
public void setNroZFinal(String nroZFinal) { public String getNroZFinal() {
this.nroZFinal = nroZFinal; return nroZFinal;
} }
public String getNroInicial() { public void setNroZFinal(String nroZFinal) {
return nroInicial; this.nroZFinal = nroZFinal;
} }
public void setNroInicial(String nroInicial) { public String getNroInicial() {
this.nroInicial = nroInicial; return nroInicial;
} }
public String getNroFinal() { public void setNroInicial(String nroInicial) {
return nroFinal; this.nroInicial = nroInicial;
} }
public void setNroFinal(String nroFinal) { public String getNroFinal() {
this.nroFinal = nroFinal; return nroFinal;
} }
public TipoIngreso getTipoIngreso() { public void setNroFinal(String nroFinal) {
return tipoIngreso; this.nroFinal = nroFinal;
} }
public void setTipoIngreso(TipoIngreso tipoIngreso) { public TipoIngreso getTipoIngreso() {
this.tipoIngreso = tipoIngreso; return tipoIngreso;
} }
public Caja getCaja() { public void setTipoIngreso(TipoIngreso tipoIngreso) {
return caja; this.tipoIngreso = tipoIngreso;
} }
public void setCaja(Caja caja) { public Caja getCaja() {
this.caja = caja; return caja;
} }
@Override public void setCaja(Caja caja) {
public String toString() { this.caja = caja;
return "Ingreso{" + }
"id=" + id +
", valor=" + valor + @Override
", nroZInicial='" + nroZInicial + '\'' + public String toString() {
", nroZFinal='" + nroZFinal + '\'' + return "Ingreso{" +
", nroInicial='" + nroInicial + '\'' + "id=" + id +
", nroFinal='" + nroFinal + '\'' + ", valor=" + valor +
", tipoIngreso=" + tipoIngreso + ", nroZInicial='" + nroZInicial + '\'' +
", caja=" + caja + ", nroZFinal='" + nroZFinal + '\'' +
'}'; ", nroInicial='" + nroInicial + '\'' +
} ", nroFinal='" + nroFinal + '\'' +
", tipoIngreso=" + tipoIngreso +
", caja=" + caja +
'}';
}
} }

View File

@@ -32,7 +32,6 @@ import danielcortes.xyz.models.caja.SQLiteCajaDAO;
import danielcortes.xyz.models.tipo_ingreso.SQLiteTipoIngresoDAO; import danielcortes.xyz.models.tipo_ingreso.SQLiteTipoIngresoDAO;
import danielcortes.xyz.models.tipo_ingreso.TipoIngreso; import danielcortes.xyz.models.tipo_ingreso.TipoIngreso;
import danielcortes.xyz.models.tipo_ingreso.TipoIngresoDAO; import danielcortes.xyz.models.tipo_ingreso.TipoIngresoDAO;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.YearMonth; import java.time.YearMonth;
@@ -42,57 +41,58 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public abstract class IngresoDAO { public abstract class IngresoDAO {
private static final Logger LOGGER = Logger.getLogger(IngresoDAO.class.getName());
protected ConnectionHolder connectionHolder; private static final Logger LOGGER = Logger.getLogger(IngresoDAO.class.getName());
public abstract List<Ingreso> findAll(); protected ConnectionHolder connectionHolder;
public abstract List<Ingreso> findByCaja(Caja caja); public abstract List<Ingreso> findAll();
public abstract List<Ingreso> findById(int id); public abstract List<Ingreso> findByCaja(Caja caja);
public abstract List<Ingreso> findByTipoIngreso(TipoIngreso tipoIngreso); public abstract List<Ingreso> findById(int id);
public abstract boolean insertIngreso(Ingreso ingreso); public abstract List<Ingreso> findByTipoIngreso(TipoIngreso tipoIngreso);
public abstract boolean updateIngreso(Ingreso ingreso); public abstract boolean insertIngreso(Ingreso ingreso);
public abstract boolean deleteIngreso(Ingreso ingreso); public abstract boolean updateIngreso(Ingreso ingreso);
public abstract int getTotalIngreso(Caja caja); public abstract boolean deleteIngreso(Ingreso ingreso);
public abstract int getTotalIngresoMes(YearMonth mes); public abstract int getTotalIngreso(Caja caja);
public abstract int getTotalExentasMes(YearMonth mes); public abstract int getTotalIngresoMes(YearMonth mes);
public abstract int getTotalExentasMes(YearMonth mes);
List<Ingreso> ingresosFromResultSet(ResultSet rs) throws SQLException { List<Ingreso> ingresosFromResultSet(ResultSet rs) throws SQLException {
ArrayList<Ingreso> ingresosList = new ArrayList<>(); ArrayList<Ingreso> ingresosList = new ArrayList<>();
while (rs.next()) { while (rs.next()) {
int tipoIngresoId = rs.getInt("tipo_ingreso_id"); int tipoIngresoId = rs.getInt("tipo_ingreso_id");
TipoIngresoDAO tipoEgresoDAO = new SQLiteTipoIngresoDAO(); TipoIngresoDAO tipoEgresoDAO = new SQLiteTipoIngresoDAO();
TipoIngreso tipoIngreso = tipoEgresoDAO.findById(tipoIngresoId).get(0); TipoIngreso tipoIngreso = tipoEgresoDAO.findById(tipoIngresoId).get(0);
int cajaId = rs.getInt("caja_id"); int cajaId = rs.getInt("caja_id");
CajaDAO cajaDAO = new SQLiteCajaDAO(); CajaDAO cajaDAO = new SQLiteCajaDAO();
Caja caja = cajaDAO.getById(cajaId).get(); Caja caja = cajaDAO.getById(cajaId).get();
Ingreso ingreso = new Ingreso(); Ingreso ingreso = new Ingreso();
ingreso.setId(rs.getInt("id")); ingreso.setId(rs.getInt("id"));
ingreso.setValor(rs.getInt("valor")); ingreso.setValor(rs.getInt("valor"));
ingreso.setNroZInicial(rs.getString("nro_z_inicial")); ingreso.setNroZInicial(rs.getString("nro_z_inicial"));
ingreso.setNroZFinal(rs.getString("nro_z_final")); ingreso.setNroZFinal(rs.getString("nro_z_final"));
ingreso.setNroInicial(rs.getString("nro_inicial")); ingreso.setNroInicial(rs.getString("nro_inicial"));
ingreso.setNroFinal(rs.getString("nro_final")); ingreso.setNroFinal(rs.getString("nro_final"));
ingreso.setTipoIngreso(tipoIngreso); ingreso.setTipoIngreso(tipoIngreso);
ingreso.setCaja(caja); ingreso.setCaja(caja);
LOGGER.log(Level.FINER, "Se a creado: {0}", ingreso); LOGGER.log(Level.FINER, "Se a creado: {0}", ingreso);
ingresosList.add(ingreso); ingresosList.add(ingreso);
}
return ingresosList;
} }
return ingresosList;
}
} }

View File

@@ -27,7 +27,6 @@ package danielcortes.xyz.models.ingreso;
import danielcortes.xyz.data.SQLiteConnectionHolder; import danielcortes.xyz.data.SQLiteConnectionHolder;
import danielcortes.xyz.models.caja.Caja; import danielcortes.xyz.models.caja.Caja;
import danielcortes.xyz.models.tipo_ingreso.TipoIngreso; import danielcortes.xyz.models.tipo_ingreso.TipoIngreso;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@@ -40,245 +39,253 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public class SQLiteIngresoDAO extends IngresoDAO { public class SQLiteIngresoDAO extends IngresoDAO {
private static final Logger LOGGER = Logger.getLogger(SQLiteIngresoDAO.class.getName());
public SQLiteIngresoDAO() { private static final Logger LOGGER = Logger.getLogger(SQLiteIngresoDAO.class.getName());
this.connectionHolder = new SQLiteConnectionHolder();
public SQLiteIngresoDAO() {
this.connectionHolder = new SQLiteConnectionHolder();
}
@Override
public List<Ingreso> findAll() {
List<Ingreso> ingresosList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from ingresos";
PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", query);
ingresosList = this.ingresosFromResultSet(rs);
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
} }
return ingresosList;
}
@Override @Override
public List<Ingreso> findAll() { public List<Ingreso> findByCaja(Caja caja) {
List<Ingreso> ingresosList = new ArrayList<>(); List<Ingreso> ingresosList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from ingresos"; String query = "select * from ingresos where caja_id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery(); ps.setInt(1, caja.getId());
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", query); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()});
ingresosList = this.ingresosFromResultSet(rs); ingresosList = this.ingresosFromResultSet(rs);
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); e.printStackTrace();
}
return ingresosList;
} }
return ingresosList;
}
@Override @Override
public List<Ingreso> findByCaja(Caja caja) { public List<Ingreso> findById(int id) {
List<Ingreso> ingresosList = new ArrayList<>(); List<Ingreso> ingresosList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from ingresos where caja_id = ?"; String query = "select * from ingresos where id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, caja.getId()); ps.setInt(1, id);
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id});
ingresosList = this.ingresosFromResultSet(rs); ingresosList = this.ingresosFromResultSet(rs);
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); LOGGER.log(Level.SEVERE, e.toString(), e);
}
return ingresosList;
} }
return ingresosList;
}
@Override @Override
public List<Ingreso> findById(int id) { public List<Ingreso> findByTipoIngreso(TipoIngreso tipoIngreso) {
List<Ingreso> ingresosList = new ArrayList<>(); List<Ingreso> ingresosList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from ingresos where id = ?"; String query = "select ingresos.* from ingresos inner join tipos_ingreso on (ingresos.tipo_ingreso_id = tipos_ingreso.id) where ingresos.tipo_ingreso_id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, id); ps.setInt(1, tipoIngreso.getId());
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, tipoIngreso.getId()});
ingresosList = this.ingresosFromResultSet(rs); ingresosList = this.ingresosFromResultSet(rs);
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); LOGGER.log(Level.SEVERE, e.toString(), e);
}
return ingresosList;
} }
return ingresosList;
}
@Override @Override
public List<Ingreso> findByTipoIngreso(TipoIngreso tipoIngreso) { public boolean insertIngreso(Ingreso ingreso) {
List<Ingreso> ingresosList = new ArrayList<>(); int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select ingresos.* from ingresos inner join tipos_ingreso on (ingresos.tipo_ingreso_id = tipos_ingreso.id) where ingresos.tipo_ingreso_id = ?"; String query = "insert into ingresos (valor, nro_z_inicial, nro_z_final, nro_inicial, nro_final, tipo_ingreso_id, caja_id) values (?,?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, tipoIngreso.getId()); ps.setInt(1, ingreso.getValor());
ResultSet rs = ps.executeQuery(); ps.setString(2, ingreso.getNroZInicial());
ps.setString(3, ingreso.getNroZFinal());
ps.setString(4, ingreso.getNroInicial());
ps.setString(5, ingreso.getNroFinal());
ps.setInt(6, ingreso.getTipoIngreso().getId());
ps.setInt(7, ingreso.getCaja().getId());
updates = ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, tipoIngreso.getId()}); LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1},{2},{3},{4},{5},{6},{7}] | updates: {8}",
new Object[]{query, ingreso.getValor(), ingreso.getNroZInicial(), ingreso.getNroZFinal(),
ingreso.getNroInicial(), ingreso.getNroFinal(), ingreso.getTipoIngreso().getId(),
ingreso.getCaja().getId(), updates});
ps.close();
ingresosList = this.ingresosFromResultSet(rs); ps = conn.prepareStatement("select last_insert_rowid()");
ResultSet rs = ps.executeQuery();
rs.next();
ingreso.setId(rs.getInt(1));
rs.close(); rs.close();
ps.close(); } catch (SQLException e) {
} catch (SQLException e) { LOGGER.log(Level.SEVERE, e.toString(), e);
LOGGER.log(Level.SEVERE, e.toString(), e); return false;
}
return ingresosList;
} }
return updates > 0;
}
@Override @Override
public boolean insertIngreso(Ingreso ingreso) { public boolean updateIngreso(Ingreso ingreso) {
int updates; int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "insert into ingresos (valor, nro_z_inicial, nro_z_final, nro_inicial, nro_final, tipo_ingreso_id, caja_id) values (?,?,?,?,?,?,?)"; String query = "update ingresos set valor = ?, nro_z_inicial = ?, nro_z_final = ?, nro_inicial = ?, nro_final = ?, tipo_ingreso_id = ?, caja_id = ? where id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, ingreso.getValor()); ps.setInt(1, ingreso.getValor());
ps.setString(2, ingreso.getNroZInicial()); ps.setString(2, ingreso.getNroZInicial());
ps.setString(3, ingreso.getNroZFinal()); ps.setString(3, ingreso.getNroZFinal());
ps.setString(4, ingreso.getNroInicial()); ps.setString(4, ingreso.getNroInicial());
ps.setString(5, ingreso.getNroFinal()); ps.setString(5, ingreso.getNroFinal());
ps.setInt(6, ingreso.getTipoIngreso().getId()); ps.setInt(6, ingreso.getTipoIngreso().getId());
ps.setInt(7, ingreso.getCaja().getId()); ps.setInt(7, ingreso.getCaja().getId());
updates = ps.executeUpdate(); ps.setInt(8, ingreso.getId());
updates = ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1},{2},{3},{4},{5},{6},{7}] | updates: {8}", new Object[]{query, ingreso.getValor(), ingreso.getNroZInicial(), ingreso.getNroZFinal(), ingreso.getNroInicial(), ingreso.getNroFinal(), ingreso.getTipoIngreso().getId(), ingreso.getCaja().getId(), updates}); LOGGER
.log(Level.FINE, "QUERY: {0} | values: [{1},{2},{3},{4},{5},{6},{7},{8}] | updates: {9}",
new Object[]{query, ingreso.getValor(), ingreso.getNroZInicial(),
ingreso.getNroZFinal(), ingreso.getNroInicial(), ingreso.getNroFinal(),
ingreso.getTipoIngreso().getId(), ingreso.getCaja().getId(), ingreso.getId(),
updates});
ps.close(); ps.close();
} catch (SQLException e) {
ps = conn.prepareStatement("select last_insert_rowid()"); LOGGER.log(Level.SEVERE, e.toString(), e);
ResultSet rs = ps.executeQuery(); return false;
rs.next();
ingreso.setId(rs.getInt(1));
rs.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
return false;
}
return updates > 0;
} }
return updates > 0;
}
@Override @Override
public boolean updateIngreso(Ingreso ingreso) { public boolean deleteIngreso(Ingreso ingreso) {
int updates; int updates;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "update ingresos set valor = ?, nro_z_inicial = ?, nro_z_final = ?, nro_inicial = ?, nro_final = ?, tipo_ingreso_id = ?, caja_id = ? where id = ?"; String query = "delete from ingresos where id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, ingreso.getValor()); ps.setInt(1, ingreso.getId());
ps.setString(2, ingreso.getNroZInicial()); updates = ps.executeUpdate();
ps.setString(3, ingreso.getNroZFinal());
ps.setString(4, ingreso.getNroInicial());
ps.setString(5, ingreso.getNroFinal());
ps.setInt(6, ingreso.getTipoIngreso().getId());
ps.setInt(7, ingreso.getCaja().getId());
ps.setInt(8, ingreso.getId());
updates = ps.executeUpdate();
LOGGER.log(Level.FINE, "QUERY: {0} | values: [{1},{2},{3},{4},{5},{6},{7},{8}] | updates: {9}", new Object[]{query, ingreso.getValor(), ingreso.getNroZInicial(), ingreso.getNroZFinal(), ingreso.getNroInicial(), ingreso.getNroFinal(), ingreso.getTipoIngreso().getId(), ingreso.getCaja().getId(), ingreso.getId(), updates}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}",
new Object[]{query, ingreso.getId(), updates});
ps.close();
ps.close(); } catch (SQLException e) {
} catch (SQLException e) { LOGGER.log(Level.SEVERE, e.toString(), e);
LOGGER.log(Level.SEVERE, e.toString(), e); return false;
return false;
}
return updates > 0;
} }
return updates > 0;
}
@Override @Override
public boolean deleteIngreso(Ingreso ingreso) { public int getTotalIngreso(Caja caja) {
int updates; int total = 0;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "delete from ingresos where id = ?"; String query = "select sum(valor) from ingresos where caja_id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, ingreso.getId()); ps.setInt(1, caja.getId());
updates = ps.executeUpdate(); ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}", new Object[]{query, ingreso.getId(), updates}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()});
ps.close(); rs.next();
} catch (SQLException e) { total = rs.getInt(1);
LOGGER.log(Level.SEVERE, e.toString(), e);
return false; rs.close();
} ps.close();
return updates > 0; } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
} }
return total;
}
@Override @Override
public int getTotalIngreso(Caja caja) { public int getTotalIngresoMes(YearMonth mes) {
int total = 0; int total = 0;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select sum(valor) from ingresos where caja_id = ?"; LocalDate start = mes.atDay(1);
PreparedStatement ps = conn.prepareStatement(query); LocalDate end = mes.atEndOfMonth();
ps.setInt(1, caja.getId()); String query =
ResultSet rs = ps.executeQuery(); "select sum(valor) from ingresos inner join caja on (ingresos.caja_id == caja.id) where caja.fecha between ? and ? and ingresos.tipo_ingreso_id != 5";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, start.toString());
ps.setString(2, end.toString());
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}, {2}", new Object[]{query, start, end});
rs.next(); rs.next();
total = rs.getInt(1); total = rs.getInt(1);
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); LOGGER.log(Level.SEVERE, e.toString(), e);
}
return total;
} }
return total;
}
@Override @Override
public int getTotalIngresoMes(YearMonth mes) { public int getTotalExentasMes(YearMonth mes) {
int total = 0; int total = 0;
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
LocalDate start = mes.atDay(1); LocalDate start = mes.atDay(1);
LocalDate end = mes.atEndOfMonth(); LocalDate end = mes.atEndOfMonth();
String query = String query =
"select sum(valor) from ingresos inner join caja on (ingresos.caja_id == caja.id) where caja.fecha between ? and ? and ingresos.tipo_ingreso_id != 5"; "select sum(valor) from ingresos inner join caja on (ingresos.caja_id == caja.id) where caja.fecha between ? and ? and ingresos.tipo_ingreso_id = 5";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, start.toString()); ps.setString(1, start.toString());
ps.setString(2, end.toString()); ps.setString(2, end.toString());
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}, {2}", new Object[]{query, start, end}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}, {2}", new Object[]{query, start, end});
rs.next(); rs.next();
total = rs.getInt(1); total = rs.getInt(1);
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); LOGGER.log(Level.SEVERE, e.toString(), e);
}
return total;
}
@Override
public int getTotalExentasMes(YearMonth mes) {
int total = 0;
try (Connection conn = connectionHolder.getConnection()) {
LocalDate start = mes.atDay(1);
LocalDate end = mes.atEndOfMonth();
String query =
"select sum(valor) from ingresos inner join caja on (ingresos.caja_id == caja.id) where caja.fecha between ? and ? and ingresos.tipo_ingreso_id = 5";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, start.toString());
ps.setString(2, end.toString());
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}, {2}", new Object[]{query, start, end});
rs.next();
total = rs.getInt(1);
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
return total;
} }
return total;
}
} }

View File

@@ -25,7 +25,6 @@
package danielcortes.xyz.models.tipo_egreso; package danielcortes.xyz.models.tipo_egreso;
import danielcortes.xyz.data.SQLiteConnectionHolder; import danielcortes.xyz.data.SQLiteConnectionHolder;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@@ -36,71 +35,72 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public class SQLiteTipoEgresoDAO extends TipoEgresoDAO { public class SQLiteTipoEgresoDAO extends TipoEgresoDAO {
private static final Logger LOGGER = Logger.getLogger(SQLiteTipoEgresoDAO.class.getName());
public SQLiteTipoEgresoDAO() { private static final Logger LOGGER = Logger.getLogger(SQLiteTipoEgresoDAO.class.getName());
this.connectionHolder = new SQLiteConnectionHolder();
public SQLiteTipoEgresoDAO() {
this.connectionHolder = new SQLiteConnectionHolder();
}
@Override
public List<TipoEgreso> findAll() {
List<TipoEgreso> tipoEgresoList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from tipos_egreso";
PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", query);
tipoEgresoList = this.tipoEgresoFromResultSet(rs);
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
} }
return tipoEgresoList;
}
@Override @Override
public List<TipoEgreso> findAll() { public List<TipoEgreso> findById(int id) {
List<TipoEgreso> tipoEgresoList = new ArrayList<>(); List<TipoEgreso> tipoEgresoList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from tipos_egreso"; String query = "select * from tipos_egreso where id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery(); ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", query); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id});
tipoEgresoList = this.tipoEgresoFromResultSet(rs); tipoEgresoList = this.tipoEgresoFromResultSet(rs);
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); LOGGER.log(Level.SEVERE, e.toString(), e);
}
return tipoEgresoList;
} }
return tipoEgresoList;
}
@Override @Override
public List<TipoEgreso> findById(int id) { public List<TipoEgreso> findByNombre(String nombre) {
List<TipoEgreso> tipoEgresoList = new ArrayList<>(); List<TipoEgreso> tipoEgresoList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from tipos_egreso where id = ?"; String query = "select * from tipos_egreso where nombre = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, id); ps.setString(1, nombre);
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, nombre});
tipoEgresoList = this.tipoEgresoFromResultSet(rs); tipoEgresoList = this.tipoEgresoFromResultSet(rs);
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e); LOGGER.log(Level.SEVERE, e.toString(), e);
}
return tipoEgresoList;
}
@Override
public List<TipoEgreso> findByNombre(String nombre) {
List<TipoEgreso> tipoEgresoList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from tipos_egreso where nombre = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, nombre);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, nombre});
tipoEgresoList = this.tipoEgresoFromResultSet(rs);
rs.close();
ps.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
return tipoEgresoList;
} }
return tipoEgresoList;
}
} }

View File

@@ -49,42 +49,43 @@
package danielcortes.xyz.models.tipo_egreso; package danielcortes.xyz.models.tipo_egreso;
public class TipoEgreso { public class TipoEgreso {
private int id;
private String nombre;
public TipoEgreso(int id, String nombre) { private int id;
this.id = id; private String nombre;
this.nombre = nombre;
}
public TipoEgreso(String nombre) { public TipoEgreso(int id, String nombre) {
this.nombre = nombre; this.id = id;
} this.nombre = nombre;
}
public TipoEgreso() { public TipoEgreso(String nombre) {
} this.nombre = nombre;
}
public String getNombre() { public TipoEgreso() {
return nombre; }
}
public void setNombre(String nombre) { public String getNombre() {
this.nombre = nombre; return nombre;
} }
public int getId() { public void setNombre(String nombre) {
return id; this.nombre = nombre;
} }
public void setId(int id) { public int getId() {
this.id = id; return id;
} }
@Override public void setId(int id) {
public String toString() { this.id = id;
return "TipoEgreso{" + }
"id=" + id +
", nombre='" + nombre + '\'' + @Override
'}'; public String toString() {
} return "TipoEgreso{" +
"id=" + id +
", nombre='" + nombre + '\'' +
'}';
}
} }

View File

@@ -49,7 +49,6 @@
package danielcortes.xyz.models.tipo_egreso; package danielcortes.xyz.models.tipo_egreso;
import danielcortes.xyz.data.ConnectionHolder; import danielcortes.xyz.data.ConnectionHolder;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@@ -58,27 +57,28 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public abstract class TipoEgresoDAO { public abstract class TipoEgresoDAO {
private static final Logger LOGGER = Logger.getLogger(TipoEgresoDAO.class.getName());
protected ConnectionHolder connectionHolder; private static final Logger LOGGER = Logger.getLogger(TipoEgresoDAO.class.getName());
public abstract List<TipoEgreso> findAll(); protected ConnectionHolder connectionHolder;
public abstract List<TipoEgreso> findById(int id); public abstract List<TipoEgreso> findAll();
public abstract List<TipoEgreso> findByNombre(String nombre); public abstract List<TipoEgreso> findById(int id);
List<TipoEgreso> tipoEgresoFromResultSet(ResultSet rs) throws SQLException { public abstract List<TipoEgreso> findByNombre(String nombre);
ArrayList<TipoEgreso> tipoEgresoList = new ArrayList<>();
while (rs.next()) {
TipoEgreso tipoEgreso = new TipoEgreso();
tipoEgreso.setId(rs.getInt("id"));
tipoEgreso.setNombre(rs.getString("nombre"));
LOGGER.log(Level.FINER, "Se a creado {0}", tipoEgreso); List<TipoEgreso> tipoEgresoFromResultSet(ResultSet rs) throws SQLException {
ArrayList<TipoEgreso> tipoEgresoList = new ArrayList<>();
while (rs.next()) {
TipoEgreso tipoEgreso = new TipoEgreso();
tipoEgreso.setId(rs.getInt("id"));
tipoEgreso.setNombre(rs.getString("nombre"));
tipoEgresoList.add(tipoEgreso); LOGGER.log(Level.FINER, "Se a creado {0}", tipoEgreso);
}
return tipoEgresoList; tipoEgresoList.add(tipoEgreso);
} }
return tipoEgresoList;
}
} }

View File

@@ -1,13 +1,14 @@
package danielcortes.xyz.models.tipo_egreso; package danielcortes.xyz.models.tipo_egreso;
public class TipoEgresoToStringWrapper extends TipoEgreso { public class TipoEgresoToStringWrapper extends TipoEgreso {
public TipoEgresoToStringWrapper(TipoEgreso tipoEgreso){
this.setId(tipoEgreso.getId());
this.setNombre(tipoEgreso.getNombre());
}
@Override public TipoEgresoToStringWrapper(TipoEgreso tipoEgreso) {
public String toString() { this.setId(tipoEgreso.getId());
return this.getNombre(); this.setNombre(tipoEgreso.getNombre());
} }
@Override
public String toString() {
return this.getNombre();
}
} }

View File

@@ -25,7 +25,6 @@
package danielcortes.xyz.models.tipo_ingreso; package danielcortes.xyz.models.tipo_ingreso;
import danielcortes.xyz.data.SQLiteConnectionHolder; import danielcortes.xyz.data.SQLiteConnectionHolder;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@@ -36,72 +35,73 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public class SQLiteTipoIngresoDAO extends TipoIngresoDAO { public class SQLiteTipoIngresoDAO extends TipoIngresoDAO {
private static final Logger LOGGER = Logger.getLogger(SQLiteTipoIngresoDAO.class.getName());
public SQLiteTipoIngresoDAO() { private static final Logger LOGGER = Logger.getLogger(SQLiteTipoIngresoDAO.class.getName());
this.connectionHolder = new SQLiteConnectionHolder();
public SQLiteTipoIngresoDAO() {
this.connectionHolder = new SQLiteConnectionHolder();
}
@Override
public List<TipoIngreso> findAll() {
List<TipoIngreso> tiposIngresoList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from tipos_ingreso";
PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", query);
tiposIngresoList = this.tiposIngresoFromResultSet(rs);
rs.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
} }
return tiposIngresoList;
}
@Override @Override
public List<TipoIngreso> findAll() { public List<TipoIngreso> findById(int id) {
List<TipoIngreso> tiposIngresoList = new ArrayList<>(); List<TipoIngreso> tiposIngresoList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from tipos_ingreso"; String query = "select * from tipos_ingreso where id = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery(); ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0}", query); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id});
tiposIngresoList = this.tiposIngresoFromResultSet(rs); tiposIngresoList = this.tiposIngresoFromResultSet(rs);
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
}
return tiposIngresoList;
} }
return tiposIngresoList;
}
@Override @Override
public List<TipoIngreso> findById(int id) { public List<TipoIngreso> findByNombre(String nombre) {
List<TipoIngreso> tiposIngresoList = new ArrayList<>(); List<TipoIngreso> tiposIngresoList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) { try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from tipos_ingreso where id = ?"; String query = "select * from tipos_ingreso where nombre = ?";
PreparedStatement ps = conn.prepareStatement(query); PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, id); ps.setString(1, nombre);
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, id}); LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, nombre});
tiposIngresoList = this.tiposIngresoFromResultSet(rs); tiposIngresoList = this.tiposIngresoFromResultSet(rs);
rs.close(); rs.close();
ps.close(); ps.close();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
}
return tiposIngresoList;
}
@Override
public List<TipoIngreso> findByNombre(String nombre) {
List<TipoIngreso> tiposIngresoList = new ArrayList<>();
try (Connection conn = connectionHolder.getConnection()) {
String query = "select * from tipos_ingreso where nombre = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, nombre);
ResultSet rs = ps.executeQuery();
LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, nombre});
tiposIngresoList = this.tiposIngresoFromResultSet(rs);
rs.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
return tiposIngresoList;
} }
return tiposIngresoList;
}
} }

View File

@@ -49,42 +49,43 @@
package danielcortes.xyz.models.tipo_ingreso; package danielcortes.xyz.models.tipo_ingreso;
public class TipoIngreso { public class TipoIngreso {
private int id;
private String nombre;
public TipoIngreso(int id, String nombre) { private int id;
this.id = id; private String nombre;
this.nombre = nombre;
}
public TipoIngreso(String nombre) { public TipoIngreso(int id, String nombre) {
this.nombre = nombre; this.id = id;
} this.nombre = nombre;
}
public TipoIngreso() { public TipoIngreso(String nombre) {
} this.nombre = nombre;
}
public int getId() { public TipoIngreso() {
return id; }
}
public void setId(int id) { public int getId() {
this.id = id; return id;
} }
public String getNombre() { public void setId(int id) {
return nombre; this.id = id;
} }
public void setNombre(String nombre) { public String getNombre() {
this.nombre = nombre; return nombre;
} }
@Override public void setNombre(String nombre) {
public String toString() { this.nombre = nombre;
return "TipoIngreso{" + }
"id=" + id +
", nombre='" + nombre + '\'' + @Override
'}'; public String toString() {
} return "TipoIngreso{" +
"id=" + id +
", nombre='" + nombre + '\'' +
'}';
}
} }

View File

@@ -25,7 +25,6 @@
package danielcortes.xyz.models.tipo_ingreso; package danielcortes.xyz.models.tipo_ingreso;
import danielcortes.xyz.data.ConnectionHolder; import danielcortes.xyz.data.ConnectionHolder;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
@@ -34,27 +33,28 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public abstract class TipoIngresoDAO { public abstract class TipoIngresoDAO {
private static final Logger LOGGER = Logger.getLogger(SQLiteTipoIngresoDAO.class.getName());
protected ConnectionHolder connectionHolder; private static final Logger LOGGER = Logger.getLogger(SQLiteTipoIngresoDAO.class.getName());
public abstract List<TipoIngreso> findAll(); protected ConnectionHolder connectionHolder;
public abstract List<TipoIngreso> findById(int id); public abstract List<TipoIngreso> findAll();
public abstract List<TipoIngreso> findByNombre(String nombre); public abstract List<TipoIngreso> findById(int id);
List<TipoIngreso> tiposIngresoFromResultSet(ResultSet rs) throws SQLException { public abstract List<TipoIngreso> findByNombre(String nombre);
ArrayList<TipoIngreso> tiposIngresoList = new ArrayList<>();
while (rs.next()) {
TipoIngreso tipoIngreso = new TipoIngreso();
tipoIngreso.setId(rs.getInt("id"));
tipoIngreso.setNombre(rs.getString("nombre"));
LOGGER.log(Level.FINE, "Se a creado: {0]", tipoIngreso); List<TipoIngreso> tiposIngresoFromResultSet(ResultSet rs) throws SQLException {
ArrayList<TipoIngreso> tiposIngresoList = new ArrayList<>();
while (rs.next()) {
TipoIngreso tipoIngreso = new TipoIngreso();
tipoIngreso.setId(rs.getInt("id"));
tipoIngreso.setNombre(rs.getString("nombre"));
tiposIngresoList.add(tipoIngreso); LOGGER.log(Level.FINE, "Se a creado: {0]", tipoIngreso);
}
return tiposIngresoList; tiposIngresoList.add(tipoIngreso);
} }
return tiposIngresoList;
}
} }

View File

@@ -1,14 +1,15 @@
package danielcortes.xyz.models.tipo_ingreso; package danielcortes.xyz.models.tipo_ingreso;
public class TipoIngresoToStringWrapper extends TipoIngreso{ public class TipoIngresoToStringWrapper extends TipoIngreso {
public TipoIngresoToStringWrapper(TipoIngreso tipoIngreso) {
this.setId(tipoIngreso.getId()); public TipoIngresoToStringWrapper(TipoIngreso tipoIngreso) {
this.setNombre(tipoIngreso.getNombre()); this.setId(tipoIngreso.getId());
} this.setNombre(tipoIngreso.getNombre());
}
@Override @Override
public String toString() { public String toString() {
return this.getNombre(); return this.getNombre();
} }
} }

View File

@@ -1,99 +1,108 @@
package danielcortes.xyz.models.version; package danielcortes.xyz.models.version;
import danielcortes.xyz.data.SQLiteConnectionHolder; import danielcortes.xyz.data.SQLiteConnectionHolder;
import java.io.BufferedReader;
import java.io.*; import java.io.File;
import java.sql.*; import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
public class SQLiteVersionDAO extends VersionDAO { public class SQLiteVersionDAO extends VersionDAO {
private static final Logger LOGGER = Logger.getLogger(SQLiteVersionDAO.class.getName());
public SQLiteVersionDAO() { private static final Logger LOGGER = Logger.getLogger(SQLiteVersionDAO.class.getName());
this.connectionHolder = new SQLiteConnectionHolder();
public SQLiteVersionDAO() {
this.connectionHolder = new SQLiteConnectionHolder();
}
private boolean tableVersionsExists() {
try {
DatabaseMetaData md = this.connectionHolder.getConnection().getMetaData();
ResultSet rs = md.getTables(null, null, "version", null);
boolean exists = rs.next();
rs.close();
return exists;
} catch (SQLException e) {
e.printStackTrace();
return false;
} }
}
private boolean tableVersionsExists() { private int getCurrentVersion() {
try { if (tableVersionsExists()) {
DatabaseMetaData md = this.connectionHolder.getConnection().getMetaData(); try (Connection conn = this.connectionHolder.getConnection()) {
ResultSet rs = md.getTables(null, null, "version", null); String query = "SELECT version FROM version LIMIT 1";
boolean exists = rs.next(); PreparedStatement ps = conn.prepareStatement(query);
rs.close(); ResultSet rs = ps.executeQuery();
return exists; rs.next();
} catch (SQLException e) { int version = rs.getInt(1);
e.printStackTrace();
return false; rs.close();
} ps.close();
return version;
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
} }
return 0;
}
private int getCurrentVersion() { private InputStream getVersionScript(int version) {
if (tableVersionsExists()) { try {
try (Connection conn = this.connectionHolder.getConnection()) { ZipFile zipFile = new ZipFile(new File("data/version_scripts"));
String query = "SELECT version FROM version LIMIT 1"; ZipEntry zipEntry = zipFile.getEntry(version + ".sql");
PreparedStatement ps = conn.prepareStatement(query); return zipFile.getInputStream(zipEntry);
ResultSet rs = ps.executeQuery(); } catch (IOException e) {
e.printStackTrace();
rs.next(); }
int version = rs.getInt(1); return new InputStream() {
@Override
rs.close(); public int read() {
ps.close();
return version;
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.toString(), e);
}
}
return 0; return 0;
} }
};
}
private InputStream getVersionScript(int version){ private void executeVersionScript(int version) {
try { try (Connection conn = this.connectionHolder.getConnection()) {
ZipFile zipFile = new ZipFile(new File("data/version_scripts")); Statement statement = conn.createStatement();
ZipEntry zipEntry = zipFile.getEntry(version + ".sql"); InputStream inputStream = getVersionScript(version);
return zipFile.getInputStream(zipEntry); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
} catch (IOException e) { String line;
e.printStackTrace(); while ((line = reader.readLine()) != null) {
} statement.addBatch(line);
return new InputStream() { }
@Override reader.close();
public int read(){
return 0;
}
};
}
private void executeVersionScript(int version){ statement.executeBatch();
try (Connection conn = this.connectionHolder.getConnection()) { statement.close();
Statement statement = conn.createStatement(); } catch (SQLException e) {
InputStream inputStream = getVersionScript(version); e.printStackTrace();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); LOGGER.log(Level.SEVERE, e.toString(), e);
String line; } catch (IOException e) {
while ((line = reader.readLine()) != null) { e.printStackTrace();
statement.addBatch(line);
}
reader.close();
statement.executeBatch();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
LOGGER.log(Level.SEVERE, e.toString(), e);
} catch (IOException e) {
e.printStackTrace();
}
} }
}
@Override @Override
public void updateTo(int version) { public void updateTo(int version) {
int currentVersion = this.getCurrentVersion(); int currentVersion = this.getCurrentVersion();
while (currentVersion < version) { while (currentVersion < version) {
currentVersion++; currentVersion++;
executeVersionScript(currentVersion); executeVersionScript(currentVersion);
}
} }
}
} }

View File

@@ -3,6 +3,8 @@ package danielcortes.xyz.models.version;
import danielcortes.xyz.data.ConnectionHolder; import danielcortes.xyz.data.ConnectionHolder;
public abstract class VersionDAO { public abstract class VersionDAO {
protected ConnectionHolder connectionHolder;
public abstract void updateTo(int version); protected ConnectionHolder connectionHolder;
public abstract void updateTo(int version);
} }

View File

@@ -25,104 +25,105 @@ package danielcortes.xyz.utils;
import java.util.Comparator; import java.util.Comparator;
public class NaturalOrderComparator implements Comparator { public class NaturalOrderComparator implements Comparator {
static char charAt(String s, int i) {
return i >= s.length() ? 0 : s.charAt(i);
}
int compareRight(String a, String b) { static char charAt(String s, int i) {
int bias = 0, ia = 0, ib = 0; return i >= s.length() ? 0 : s.charAt(i);
}
// The longest run of digits wins. That aside, the greatest int compareRight(String a, String b) {
// value wins, but we can't know that it will until we've scanned int bias = 0, ia = 0, ib = 0;
// both numbers to know that they have the same magnitude, so we
// remember it in BIAS.
for (; ; ia++, ib++) {
char ca = charAt(a, ia);
char cb = charAt(b, ib);
if (!Character.isDigit(ca) && !Character.isDigit(cb)) { // The longest run of digits wins. That aside, the greatest
return bias; // value wins, but we can't know that it will until we've scanned
} // both numbers to know that they have the same magnitude, so we
if (!Character.isDigit(ca)) { // remember it in BIAS.
return -1; for (; ; ia++, ib++) {
} char ca = charAt(a, ia);
if (!Character.isDigit(cb)) { char cb = charAt(b, ib);
return +1;
}
if (ca == 0 && cb == 0) {
return bias;
}
if (bias == 0) { if (!Character.isDigit(ca) && !Character.isDigit(cb)) {
if (ca < cb) { return bias;
bias = -1; }
} else if (ca > cb) { if (!Character.isDigit(ca)) {
bias = +1; return -1;
} }
} if (!Character.isDigit(cb)) {
return +1;
}
if (ca == 0 && cb == 0) {
return bias;
}
if (bias == 0) {
if (ca < cb) {
bias = -1;
} else if (ca > cb) {
bias = +1;
} }
}
} }
}
public int compare(Object o1, Object o2) { public int compare(Object o1, Object o2) {
String a = o1.toString(); String a = o1.toString();
String b = o2.toString(); String b = o2.toString();
int ia = 0, ib = 0; int ia = 0, ib = 0;
int nza = 0, nzb = 0; int nza = 0, nzb = 0;
char ca, cb; char ca, cb;
while (true) { while (true) {
// Only count the number of zeroes leading the last number compared // Only count the number of zeroes leading the last number compared
nza = nzb = 0; nza = nzb = 0;
ca = charAt(a, ia); ca = charAt(a, ia);
cb = charAt(b, ib); cb = charAt(b, ib);
// skip over leading spaces or zeros // skip over leading spaces or zeros
while (Character.isSpaceChar(ca) || ca == '0') { while (Character.isSpaceChar(ca) || ca == '0') {
if (ca == '0') { if (ca == '0') {
nza++; nza++;
} else { } else {
// Only count consecutive zeroes // Only count consecutive zeroes
nza = 0; nza = 0;
}
ca = charAt(a, ++ia);
}
while (Character.isSpaceChar(cb) || cb == '0') {
if (cb == '0') {
nzb++;
} else {
// Only count consecutive zeroes
nzb = 0;
}
cb = charAt(b, ++ib);
}
// Process run of digits
if (Character.isDigit(ca) && Character.isDigit(cb)) {
int bias = compareRight(a.substring(ia), b.substring(ib));
if (bias != 0) {
return bias;
}
}
if (ca == 0 && cb == 0) {
// The strings compare the same. Perhaps the caller
// will want to call strcmp to break the tie.
return nza - nzb;
}
if (ca < cb) {
return -1;
}
if (ca > cb) {
return +1;
}
++ia;
++ib;
} }
ca = charAt(a, ++ia);
}
while (Character.isSpaceChar(cb) || cb == '0') {
if (cb == '0') {
nzb++;
} else {
// Only count consecutive zeroes
nzb = 0;
}
cb = charAt(b, ++ib);
}
// Process run of digits
if (Character.isDigit(ca) && Character.isDigit(cb)) {
int bias = compareRight(a.substring(ia), b.substring(ib));
if (bias != 0) {
return bias;
}
}
if (ca == 0 && cb == 0) {
// The strings compare the same. Perhaps the caller
// will want to call strcmp to break the tie.
return nza - nzb;
}
if (ca < cb) {
return -1;
}
if (ca > cb) {
return +1;
}
++ia;
++ib;
} }
}
} }

View File

@@ -27,38 +27,43 @@ package danielcortes.xyz.utils;
import java.util.Objects; import java.util.Objects;
public class Pair<L, R> { public class Pair<L, R> {
private final L left;
private final R right;
public Pair(L left, R right) { private final L left;
this.left = left; private final R right;
this.right = right;
}
public L getLeft() { public Pair(L left, R right) {
return left; this.left = left;
} this.right = right;
}
public R getRight() { public L getLeft() {
return right; return left;
} }
@Override public R getRight() {
public boolean equals(Object o) { return right;
if (this == o) return true; }
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return left.equals(pair.left) &&
right.equals(pair.right);
}
@Override @Override
public int hashCode() { public boolean equals(Object o) {
return Objects.hash(left, right); if (this == o) {
return true;
} }
if (o == null || getClass() != o.getClass()) {
return false;
}
Pair<?, ?> pair = (Pair<?, ?>) o;
return left.equals(pair.left) &&
right.equals(pair.right);
}
@Override @Override
public String toString() { public int hashCode() {
return "{left=" + left + ", right=" + right + "}"; return Objects.hash(left, right);
} }
@Override
public String toString() {
return "{left=" + left + ", right=" + right + "}";
}
} }

View File

@@ -25,7 +25,8 @@
package danielcortes.xyz.utils; package danielcortes.xyz.utils;
public class StringUtils { public class StringUtils {
public static String capitalize(String string) {
return string.substring(0, 1).toUpperCase() + string.substring(1); public static String capitalize(String string) {
} return string.substring(0, 1).toUpperCase() + string.substring(1);
}
} }

View File

@@ -28,316 +28,463 @@ 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.NumberFormatedTextField; import danielcortes.xyz.views.components.NumberFormatedTextField;
import java.awt.Dimension;
import javax.swing.*; import java.awt.Font;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.border.TitledBorder; import javax.swing.border.TitledBorder;
import java.awt.*;
public class ArqueoView { public class ArqueoView {
private JPanel contentPanel;
private NumberFormatedTextField veinteMilField;
private NumberFormatedTextField diezMilField;
private NumberFormatedTextField cincoMilField;
private NumberFormatedTextField dosMilField;
private NumberFormatedTextField milField;
private NumberFormatedTextField quinientosField;
private NumberFormatedTextField cienField;
private NumberFormatedTextField cincuentaField;
private NumberFormatedTextField diezField;
private NumberFormatedTextField chequesField;
private NumberFormatedTextField tarjetasField;
private NumberFormatedTextField efectivoField;
private NumberFormatedTextField documentosField;
private NumberFormatedTextField egresosField;
private NumberFormatedTextField rendidoField;
private JButton guardarEfectivoButton;
private JButton guardarDocumentosButton;
private JButton calcularFondoButton;
private NumberFormatedTextField diferenciaField;
private NumberFormatedTextField debeRendirField;
private NumberFormatedTextField retiroField;
public JPanel getContentPanel() { private JPanel contentPanel;
return contentPanel; private NumberFormatedTextField veinteMilField;
} private NumberFormatedTextField diezMilField;
private NumberFormatedTextField cincoMilField;
private NumberFormatedTextField dosMilField;
private NumberFormatedTextField milField;
private NumberFormatedTextField quinientosField;
private NumberFormatedTextField cienField;
private NumberFormatedTextField cincuentaField;
private NumberFormatedTextField diezField;
private NumberFormatedTextField chequesField;
private NumberFormatedTextField tarjetasField;
private NumberFormatedTextField efectivoField;
private NumberFormatedTextField documentosField;
private NumberFormatedTextField egresosField;
private NumberFormatedTextField rendidoField;
private JButton guardarEfectivoButton;
private JButton guardarDocumentosButton;
private JButton calcularFondoButton;
private NumberFormatedTextField diferenciaField;
private NumberFormatedTextField debeRendirField;
private NumberFormatedTextField retiroField;
public NumberFormatedTextField getVeinteMilField() { {
return veinteMilField;
}
public NumberFormatedTextField getDiezMilField() {
return diezMilField;
}
public NumberFormatedTextField getCincoMilField() {
return cincoMilField;
}
public NumberFormatedTextField getDosMilField() {
return dosMilField;
}
public NumberFormatedTextField getMilField() {
return milField;
}
public NumberFormatedTextField getQuinientosField() {
return quinientosField;
}
public NumberFormatedTextField getCienField() {
return cienField;
}
public NumberFormatedTextField getCincuentaField() {
return cincuentaField;
}
public NumberFormatedTextField getDiezField() {
return diezField;
}
public NumberFormatedTextField getChequesField() {
return chequesField;
}
public NumberFormatedTextField getTarjetasField() {
return tarjetasField;
}
public NumberFormatedTextField getEfectivoField() {
return efectivoField;
}
public NumberFormatedTextField getDocumentosField() {
return documentosField;
}
public NumberFormatedTextField getEgresosField() {
return egresosField;
}
public NumberFormatedTextField getRendidoField() {
return rendidoField;
}
public JButton getGuardarEfectivoButton() {
return guardarEfectivoButton;
}
public JButton getGuardarDocumentosButton() {
return guardarDocumentosButton;
}
public JButton getCalcularFondoButton() {
return calcularFondoButton;
}
public NumberFormatedTextField getDiferenciaField() {
return diferenciaField;
}
public NumberFormatedTextField getDebeRendirField() {
return debeRendirField;
}
public NumberFormatedTextField getRetiroField() {
return retiroField;
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer // GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<< // >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE! // DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$(); $$$setupUI$$$();
} }
/** public JPanel getContentPanel() {
* Method generated by IntelliJ IDEA GUI Designer return contentPanel;
* >>> IMPORTANT!! <<< }
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
contentPanel = new JPanel();
contentPanel.setLayout(new GridLayoutManager(3, 2, new Insets(0, 0, 0, 0), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(7, 2, new Insets(10, 10, 10, 10), -1, -1));
contentPanel.add(panel1, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
panel1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Resumen"));
final JLabel label1 = new JLabel();
label1.setText("Total Egresos");
panel1.add(label1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
egresosField = new NumberFormatedTextField();
egresosField.setEditable(false);
egresosField.setText("");
panel1.add(egresosField, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
diferenciaField = new NumberFormatedTextField();
diferenciaField.setEditable(false);
Font diferenciaFieldFont = this.$$$getFont$$$(null, Font.BOLD, -1, diferenciaField.getFont());
if (diferenciaFieldFont != null) diferenciaField.setFont(diferenciaFieldFont);
diferenciaField.setText("");
panel1.add(diferenciaField, new GridConstraints(6, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label2 = new JLabel();
label2.setText("Diferencia");
panel1.add(label2, new GridConstraints(6, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JSeparator separator1 = new JSeparator();
panel1.add(separator1, new GridConstraints(3, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
final JLabel label3 = new JLabel();
label3.setText("Debe Rendir");
panel1.add(label3, new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
debeRendirField = new NumberFormatedTextField();
debeRendirField.setEditable(false);
Font debeRendirFieldFont = this.$$$getFont$$$(null, Font.BOLD, -1, debeRendirField.getFont());
if (debeRendirFieldFont != null) debeRendirField.setFont(debeRendirFieldFont);
debeRendirField.setText("");
panel1.add(debeRendirField, new GridConstraints(5, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
rendidoField = new NumberFormatedTextField();
rendidoField.setEditable(false);
Font rendidoFieldFont = this.$$$getFont$$$(null, Font.BOLD, -1, rendidoField.getFont());
if (rendidoFieldFont != null) rendidoField.setFont(rendidoFieldFont);
rendidoField.setText("");
panel1.add(rendidoField, new GridConstraints(4, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label4 = new JLabel();
label4.setText("Rendido");
panel1.add(label4, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label5 = new JLabel();
label5.setText("Total Documentos");
panel1.add(label5, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
documentosField = new NumberFormatedTextField();
documentosField.setEditable(false);
documentosField.setText("");
panel1.add(documentosField, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label6 = new JLabel();
label6.setText("Total Efectivo");
panel1.add(label6, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
efectivoField = new NumberFormatedTextField();
efectivoField.setEditable(false);
efectivoField.setText("");
panel1.add(efectivoField, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, -1));
contentPanel.add(panel2, new GridConstraints(0, 0, 3, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayoutManager(10, 2, new Insets(10, 10, 10, 10), -1, -1));
panel2.add(panel3, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
panel3.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Detalle Efectivo", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, this.$$$getFont$$$(null, -1, -1, panel3.getFont())));
final JLabel label7 = new JLabel();
label7.setText("$20000");
panel3.add(label7, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
veinteMilField = new NumberFormatedTextField();
veinteMilField.setText("");
panel3.add(veinteMilField, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
final JLabel label8 = new JLabel();
label8.setText("$10000");
panel3.add(label8, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
diezMilField = new NumberFormatedTextField();
diezMilField.setText("");
panel3.add(diezMilField, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
cincoMilField = new NumberFormatedTextField();
cincoMilField.setText("");
panel3.add(cincoMilField, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
final JLabel label9 = new JLabel();
label9.setText("$5000");
panel3.add(label9, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label10 = new JLabel();
label10.setText("$2000");
panel3.add(label10, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
dosMilField = new NumberFormatedTextField();
dosMilField.setText("");
panel3.add(dosMilField, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
milField = new NumberFormatedTextField();
milField.setText("");
panel3.add(milField, new GridConstraints(4, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
final JLabel label11 = new JLabel();
label11.setText("$1000");
panel3.add(label11, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label12 = new JLabel();
label12.setText("$500");
panel3.add(label12, new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
quinientosField = new NumberFormatedTextField();
quinientosField.setText("");
panel3.add(quinientosField, new GridConstraints(5, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
final JLabel label13 = new JLabel();
label13.setText("$100");
panel3.add(label13, new GridConstraints(6, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
cienField = new NumberFormatedTextField();
cienField.setText("");
panel3.add(cienField, new GridConstraints(6, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
final JLabel label14 = new JLabel();
label14.setText("$50");
panel3.add(label14, new GridConstraints(7, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
cincuentaField = new NumberFormatedTextField();
cincuentaField.setText("");
panel3.add(cincuentaField, new GridConstraints(7, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
final JLabel label15 = new JLabel();
label15.setText("$10");
panel3.add(label15, new GridConstraints(8, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
diezField = new NumberFormatedTextField();
diezField.setText("");
panel3.add(diezField, new GridConstraints(8, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
guardarEfectivoButton = new JButton();
guardarEfectivoButton.setText("Guardar");
panel3.add(guardarEfectivoButton, new GridConstraints(9, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
final JPanel panel4 = new JPanel();
panel4.setLayout(new GridLayoutManager(4, 2, new Insets(10, 10, 10, 10), -1, -1));
panel2.add(panel4, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
panel4.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Detalle Documentos", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, this.$$$getFont$$$(null, -1, -1, panel4.getFont())));
chequesField = new NumberFormatedTextField();
chequesField.setText("");
panel4.add(chequesField, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label16 = new JLabel();
label16.setText("Tarjetas de Credito");
panel4.add(label16, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
tarjetasField = new NumberFormatedTextField();
tarjetasField.setText("");
panel4.add(tarjetasField, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
guardarDocumentosButton = new JButton();
guardarDocumentosButton.setText("Guardar");
panel4.add(guardarDocumentosButton, new GridConstraints(3, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label17 = new JLabel();
label17.setText("Cheques al Dia");
panel4.add(label17, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
retiroField = new NumberFormatedTextField();
retiroField.setText("");
panel4.add(retiroField, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label18 = new JLabel();
label18.setText("Retiro");
panel4.add(label18, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel5 = new JPanel();
panel5.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
contentPanel.add(panel5, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
calcularFondoButton = new JButton();
calcularFondoButton.setText("Calcular Fondo");
panel5.add(calcularFondoButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Spacer spacer1 = new Spacer();
contentPanel.add(spacer1, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
}
/** public NumberFormatedTextField getVeinteMilField() {
* @noinspection ALL return veinteMilField;
*/ }
private Font $$$getFont$$$(String fontName, int style, int size, Font currentFont) {
if (currentFont == null) return null;
String resultName;
if (fontName == null) {
resultName = currentFont.getName();
} else {
Font testFont = new Font(fontName, Font.PLAIN, 10);
if (testFont.canDisplay('a') && testFont.canDisplay('1')) {
resultName = fontName;
} else {
resultName = currentFont.getName();
}
}
return new Font(resultName, style >= 0 ? style : currentFont.getStyle(), size >= 0 ? size : currentFont.getSize());
}
/** public NumberFormatedTextField getDiezMilField() {
* @noinspection ALL return diezMilField;
*/ }
public JComponent $$$getRootComponent$$$() {
return contentPanel; public NumberFormatedTextField getCincoMilField() {
return cincoMilField;
}
public NumberFormatedTextField getDosMilField() {
return dosMilField;
}
public NumberFormatedTextField getMilField() {
return milField;
}
public NumberFormatedTextField getQuinientosField() {
return quinientosField;
}
public NumberFormatedTextField getCienField() {
return cienField;
}
public NumberFormatedTextField getCincuentaField() {
return cincuentaField;
}
public NumberFormatedTextField getDiezField() {
return diezField;
}
public NumberFormatedTextField getChequesField() {
return chequesField;
}
public NumberFormatedTextField getTarjetasField() {
return tarjetasField;
}
public NumberFormatedTextField getEfectivoField() {
return efectivoField;
}
public NumberFormatedTextField getDocumentosField() {
return documentosField;
}
public NumberFormatedTextField getEgresosField() {
return egresosField;
}
public NumberFormatedTextField getRendidoField() {
return rendidoField;
}
public JButton getGuardarEfectivoButton() {
return guardarEfectivoButton;
}
public JButton getGuardarDocumentosButton() {
return guardarDocumentosButton;
}
public JButton getCalcularFondoButton() {
return calcularFondoButton;
}
public NumberFormatedTextField getDiferenciaField() {
return diferenciaField;
}
public NumberFormatedTextField getDebeRendirField() {
return debeRendirField;
}
public NumberFormatedTextField getRetiroField() {
return retiroField;
}
/**
* Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR
* call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
contentPanel = new JPanel();
contentPanel.setLayout(new GridLayoutManager(3, 2, new Insets(0, 0, 0, 0), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(7, 2, new Insets(10, 10, 10, 10), -1, -1));
contentPanel.add(panel1,
new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
panel1
.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Resumen"));
final JLabel label1 = new JLabel();
label1.setText("Total Egresos");
panel1.add(label1,
new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
egresosField = new NumberFormatedTextField();
egresosField.setEditable(false);
egresosField.setText("");
panel1.add(egresosField, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
diferenciaField = new NumberFormatedTextField();
diferenciaField.setEditable(false);
Font diferenciaFieldFont = this.$$$getFont$$$(null, Font.BOLD, -1, diferenciaField.getFont());
if (diferenciaFieldFont != null) {
diferenciaField.setFont(diferenciaFieldFont);
} }
diferenciaField.setText("");
panel1.add(diferenciaField, new GridConstraints(6, 1, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label2 = new JLabel();
label2.setText("Diferencia");
panel1.add(label2,
new GridConstraints(6, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
final JSeparator separator1 = new JSeparator();
panel1.add(separator1,
new GridConstraints(3, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_WANT_GROW, null, null,
null, 0, false));
final JLabel label3 = new JLabel();
label3.setText("Debe Rendir");
panel1.add(label3,
new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
debeRendirField = new NumberFormatedTextField();
debeRendirField.setEditable(false);
Font debeRendirFieldFont = this.$$$getFont$$$(null, Font.BOLD, -1, debeRendirField.getFont());
if (debeRendirFieldFont != null) {
debeRendirField.setFont(debeRendirFieldFont);
}
debeRendirField.setText("");
panel1.add(debeRendirField, new GridConstraints(5, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
rendidoField = new NumberFormatedTextField();
rendidoField.setEditable(false);
Font rendidoFieldFont = this.$$$getFont$$$(null, Font.BOLD, -1, rendidoField.getFont());
if (rendidoFieldFont != null) {
rendidoField.setFont(rendidoFieldFont);
}
rendidoField.setText("");
panel1.add(rendidoField, new GridConstraints(4, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label4 = new JLabel();
label4.setText("Rendido");
panel1.add(label4,
new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
final JLabel label5 = new JLabel();
label5.setText("Total Documentos");
panel1.add(label5,
new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
documentosField = new NumberFormatedTextField();
documentosField.setEditable(false);
documentosField.setText("");
panel1.add(documentosField, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label6 = new JLabel();
label6.setText("Total Efectivo");
panel1.add(label6,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
efectivoField = new NumberFormatedTextField();
efectivoField.setEditable(false);
efectivoField.setText("");
panel1.add(efectivoField, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, -1));
contentPanel.add(panel2,
new GridConstraints(0, 0, 3, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
final JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayoutManager(10, 2, new Insets(10, 10, 10, 10), -1, -1));
panel2.add(panel3,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
panel3.setBorder(BorderFactory
.createTitledBorder(BorderFactory.createEtchedBorder(), "Detalle Efectivo",
TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION,
this.$$$getFont$$$(null, -1, -1, panel3.getFont())));
final JLabel label7 = new JLabel();
label7.setText("$20000");
panel3.add(label7,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
veinteMilField = new NumberFormatedTextField();
veinteMilField.setText("");
panel3.add(veinteMilField, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
final JLabel label8 = new JLabel();
label8.setText("$10000");
panel3.add(label8,
new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
diezMilField = new NumberFormatedTextField();
diezMilField.setText("");
panel3.add(diezMilField, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
cincoMilField = new NumberFormatedTextField();
cincoMilField.setText("");
panel3.add(cincoMilField, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
final JLabel label9 = new JLabel();
label9.setText("$5000");
panel3.add(label9,
new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
final JLabel label10 = new JLabel();
label10.setText("$2000");
panel3.add(label10,
new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
dosMilField = new NumberFormatedTextField();
dosMilField.setText("");
panel3.add(dosMilField, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
milField = new NumberFormatedTextField();
milField.setText("");
panel3.add(milField, new GridConstraints(4, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
final JLabel label11 = new JLabel();
label11.setText("$1000");
panel3.add(label11,
new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
final JLabel label12 = new JLabel();
label12.setText("$500");
panel3.add(label12,
new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
quinientosField = new NumberFormatedTextField();
quinientosField.setText("");
panel3.add(quinientosField, new GridConstraints(5, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
final JLabel label13 = new JLabel();
label13.setText("$100");
panel3.add(label13,
new GridConstraints(6, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
cienField = new NumberFormatedTextField();
cienField.setText("");
panel3.add(cienField, new GridConstraints(6, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
final JLabel label14 = new JLabel();
label14.setText("$50");
panel3.add(label14,
new GridConstraints(7, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
cincuentaField = new NumberFormatedTextField();
cincuentaField.setText("");
panel3.add(cincuentaField, new GridConstraints(7, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
final JLabel label15 = new JLabel();
label15.setText("$10");
panel3.add(label15,
new GridConstraints(8, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
diezField = new NumberFormatedTextField();
diezField.setText("");
panel3.add(diezField, new GridConstraints(8, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
guardarEfectivoButton = new JButton();
guardarEfectivoButton.setText("Guardar");
panel3.add(guardarEfectivoButton, new GridConstraints(9, 0, 1, 2, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(200, -1), null, 0, false));
final JPanel panel4 = new JPanel();
panel4.setLayout(new GridLayoutManager(4, 2, new Insets(10, 10, 10, 10), -1, -1));
panel2.add(panel4,
new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
panel4.setBorder(BorderFactory
.createTitledBorder(BorderFactory.createEtchedBorder(), "Detalle Documentos",
TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION,
this.$$$getFont$$$(null, -1, -1, panel4.getFont())));
chequesField = new NumberFormatedTextField();
chequesField.setText("");
panel4.add(chequesField, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label16 = new JLabel();
label16.setText("Tarjetas de Credito");
panel4.add(label16,
new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
tarjetasField = new NumberFormatedTextField();
tarjetasField.setText("");
panel4.add(tarjetasField, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
guardarDocumentosButton = new JButton();
guardarDocumentosButton.setText("Guardar");
panel4.add(guardarDocumentosButton,
new GridConstraints(3, 0, 1, 2, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label17 = new JLabel();
label17.setText("Cheques al Dia");
panel4.add(label17,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
retiroField = new NumberFormatedTextField();
retiroField.setText("");
panel4.add(retiroField, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label18 = new JLabel();
label18.setText("Retiro");
panel4.add(label18,
new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
final JPanel panel5 = new JPanel();
panel5.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
contentPanel.add(panel5,
new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
calcularFondoButton = new JButton();
calcularFondoButton.setText("Calcular Fondo");
panel5.add(calcularFondoButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Spacer spacer1 = new Spacer();
contentPanel.add(spacer1, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0,
false));
}
/**
* @noinspection ALL
*/
private Font $$$getFont$$$(String fontName, int style, int size, Font currentFont) {
if (currentFont == null) {
return null;
}
String resultName;
if (fontName == null) {
resultName = currentFont.getName();
} else {
Font testFont = new Font(fontName, Font.PLAIN, 10);
if (testFont.canDisplay('a') && testFont.canDisplay('1')) {
resultName = fontName;
} else {
resultName = currentFont.getName();
}
}
return new Font(resultName, style >= 0 ? style : currentFont.getStyle(),
size >= 0 ? size : currentFont.getSize());
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPanel;
}
} }

View File

@@ -2,56 +2,65 @@ package danielcortes.xyz.views;
import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.uiDesigner.core.GridLayoutManager;
import java.awt.CardLayout;
import javax.swing.*; import java.awt.Insets;
import java.awt.*; import javax.swing.JComponent;
import javax.swing.JPanel;
public class BaseLayout { public class BaseLayout {
private JPanel contentPanel;
private JPanel sidePanel;
private JPanel mainPanel;
public JPanel getContentPanel() { private JPanel contentPanel;
return contentPanel; private JPanel sidePanel;
} private JPanel mainPanel;
public JPanel getSidePanel() { {
return sidePanel;
}
public JPanel getMainPanel() {
return mainPanel;
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer // GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<< // >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE! // DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$(); $$$setupUI$$$();
} }
/** public JPanel getContentPanel() {
* Method generated by IntelliJ IDEA GUI Designer return contentPanel;
* >>> IMPORTANT!! <<< }
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
contentPanel = new JPanel();
contentPanel.setLayout(new GridLayoutManager(1, 2, new Insets(10, 10, 10, 10), -1, -1));
sidePanel = new JPanel();
sidePanel.setLayout(new CardLayout(0, 0));
contentPanel.add(sidePanel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_VERTICAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
mainPanel = new JPanel();
mainPanel.setLayout(new CardLayout(0, 0));
contentPanel.add(mainPanel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
}
/** public JPanel getSidePanel() {
* @noinspection ALL return sidePanel;
*/ }
public JComponent $$$getRootComponent$$$() {
return contentPanel; public JPanel getMainPanel() {
} return mainPanel;
}
/**
* Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR
* call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
contentPanel = new JPanel();
contentPanel.setLayout(new GridLayoutManager(1, 2, new Insets(10, 10, 10, 10), -1, -1));
sidePanel = new JPanel();
sidePanel.setLayout(new CardLayout(0, 0));
contentPanel.add(sidePanel,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_VERTICAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
mainPanel = new JPanel();
mainPanel.setLayout(new CardLayout(0, 0));
contentPanel.add(mainPanel,
new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null,
null, null, 0, false));
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPanel;
}
} }

View File

@@ -28,98 +28,126 @@ import com.github.lgooddatepicker.components.DatePicker;
import com.intellij.uiDesigner.core.GridConstraints; 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 java.awt.CardLayout;
import javax.swing.*; import java.awt.Dimension;
import java.awt.*; import java.awt.Insets;
import javax.swing.ButtonGroup;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
public class CajasView { public class CajasView {
private JToggleButton egresosButton;
private JToggleButton ingresosButton;
private JPanel contentPanel;
private JPanel cardPanel;
private JPanel controlsPanel;
private JToggleButton arqueoButton;
private DatePicker datePicker;
public JToggleButton getEgresosButton() { private JToggleButton egresosButton;
return egresosButton; private JToggleButton ingresosButton;
} private JPanel contentPanel;
private JPanel cardPanel;
private JPanel controlsPanel;
private JToggleButton arqueoButton;
private DatePicker datePicker;
public JToggleButton getIngresosButton() { {
return ingresosButton;
}
public JToggleButton getArqueoButton() {
return arqueoButton;
}
public DatePicker getDatePicker() {
return datePicker;
}
public JPanel getContentPanel() {
return contentPanel;
}
public JPanel getCardPanel() {
return cardPanel;
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer // GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<< // >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE! // DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$(); $$$setupUI$$$();
} }
/** public JToggleButton getEgresosButton() {
* Method generated by IntelliJ IDEA GUI Designer return egresosButton;
* >>> IMPORTANT!! <<< }
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
contentPanel = new JPanel();
contentPanel.setLayout(new GridLayoutManager(2, 1, new Insets(10, 10, 10, 10), -1, -1));
cardPanel = new JPanel();
cardPanel.setLayout(new CardLayout(0, 0));
contentPanel.add(cardPanel, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
controlsPanel = new JPanel();
controlsPanel.setLayout(new GridLayoutManager(1, 5, new Insets(0, 0, 0, 0), -1, -1));
contentPanel.add(controlsPanel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false));
egresosButton = new JToggleButton();
egresosButton.setText("Egresos");
egresosButton.setMnemonic('E');
egresosButton.setDisplayedMnemonicIndex(0);
controlsPanel.add(egresosButton, new GridConstraints(0, 3, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(200, -1), null, 0, false));
ingresosButton = new JToggleButton();
ingresosButton.setText("Ingresos");
ingresosButton.setMnemonic('I');
ingresosButton.setDisplayedMnemonicIndex(0);
controlsPanel.add(ingresosButton, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(200, -1), null, 0, false));
arqueoButton = new JToggleButton();
arqueoButton.setText("Arqueo");
arqueoButton.setMnemonic('A');
arqueoButton.setDisplayedMnemonicIndex(0);
controlsPanel.add(arqueoButton, new GridConstraints(0, 4, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(200, -1), null, 0, false));
datePicker = new DatePicker();
controlsPanel.add(datePicker, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final Spacer spacer1 = new Spacer();
controlsPanel.add(spacer1, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
ButtonGroup buttonGroup;
buttonGroup = new ButtonGroup();
buttonGroup.add(egresosButton);
buttonGroup.add(ingresosButton);
buttonGroup.add(arqueoButton);
}
/** public JToggleButton getIngresosButton() {
* @noinspection ALL return ingresosButton;
*/ }
public JComponent $$$getRootComponent$$$() {
return contentPanel; public JToggleButton getArqueoButton() {
} return arqueoButton;
}
public DatePicker getDatePicker() {
return datePicker;
}
public JPanel getContentPanel() {
return contentPanel;
}
public JPanel getCardPanel() {
return cardPanel;
}
/**
* Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR
* call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
contentPanel = new JPanel();
contentPanel.setLayout(new GridLayoutManager(2, 1, new Insets(10, 10, 10, 10), -1, -1));
cardPanel = new JPanel();
cardPanel.setLayout(new CardLayout(0, 0));
contentPanel.add(cardPanel,
new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
controlsPanel = new JPanel();
controlsPanel.setLayout(new GridLayoutManager(1, 5, new Insets(0, 0, 0, 0), -1, -1));
contentPanel.add(controlsPanel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_NORTH,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null,
null, 0, false));
egresosButton = new JToggleButton();
egresosButton.setText("Egresos");
egresosButton.setMnemonic('E');
egresosButton.setDisplayedMnemonicIndex(0);
controlsPanel.add(egresosButton,
new GridConstraints(0, 3, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null,
new Dimension(200, -1), null, 0, false));
ingresosButton = new JToggleButton();
ingresosButton.setText("Ingresos");
ingresosButton.setMnemonic('I');
ingresosButton.setDisplayedMnemonicIndex(0);
controlsPanel.add(ingresosButton,
new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null,
new Dimension(200, -1), null, 0, false));
arqueoButton = new JToggleButton();
arqueoButton.setText("Arqueo");
arqueoButton.setMnemonic('A');
arqueoButton.setDisplayedMnemonicIndex(0);
controlsPanel.add(arqueoButton,
new GridConstraints(0, 4, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null,
new Dimension(200, -1), null, 0, false));
datePicker = new DatePicker();
controlsPanel.add(datePicker,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
final Spacer spacer1 = new Spacer();
controlsPanel.add(spacer1, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null,
0, false));
ButtonGroup buttonGroup;
buttonGroup = new ButtonGroup();
buttonGroup.add(egresosButton);
buttonGroup.add(ingresosButton);
buttonGroup.add(arqueoButton);
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPanel;
}
} }

View File

@@ -28,163 +28,221 @@ import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.uiDesigner.core.GridLayoutManager;
import danielcortes.xyz.views.components.NumberFormatedTextField; import danielcortes.xyz.views.components.NumberFormatedTextField;
import danielcortes.xyz.views.components.table_model.FondoTableModel; import danielcortes.xyz.views.components.table_model.FondoTableModel;
import java.awt.Dimension;
import javax.swing.*; import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowSorter;
import javax.swing.table.TableModel; import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter; import javax.swing.table.TableRowSorter;
import java.awt.*;
public class CalcularFondoView { public class CalcularFondoView {
private JPanel contentPanel;
private JTable table;
private JButton guardarButton;
private JButton editarButton;
private JButton eliminarButton;
private JTextField descripcionField;
private NumberFormatedTextField fondoField;
private NumberFormatedTextField sumaField;
private NumberFormatedTextField depositoField;
private NumberFormatedTextField valorField;
private FondoTableModel tableModel; private JPanel contentPanel;
private JTable table;
private JButton guardarButton;
private JButton editarButton;
private JButton eliminarButton;
private JTextField descripcionField;
private NumberFormatedTextField fondoField;
private NumberFormatedTextField sumaField;
private NumberFormatedTextField depositoField;
private NumberFormatedTextField valorField;
public CalcularFondoView() { private FondoTableModel tableModel;
$$$setupUI$$$();
this.fillDefaultsValues(); public CalcularFondoView() {
} $$$setupUI$$$();
this.fillDefaultsValues();
}
public JPanel getContentPanel() { public JPanel getContentPanel() {
return contentPanel; return contentPanel;
} }
public JTable getTable() { public JTable getTable() {
return table; return table;
} }
public JButton getGuardarButton() { public JButton getGuardarButton() {
return guardarButton; return guardarButton;
} }
public JButton getEditarButton() { public JButton getEditarButton() {
return editarButton; return editarButton;
} }
public JButton getEliminarButton() { public JButton getEliminarButton() {
return eliminarButton; return eliminarButton;
} }
public JTextField getDescripcionField() { public JTextField getDescripcionField() {
return descripcionField; return descripcionField;
} }
public NumberFormatedTextField getFondoField() { public NumberFormatedTextField getFondoField() {
return fondoField; return fondoField;
} }
public NumberFormatedTextField getSumaField() { public NumberFormatedTextField getSumaField() {
return sumaField; return sumaField;
} }
public NumberFormatedTextField getDepositoField() { public NumberFormatedTextField getDepositoField() {
return depositoField; return depositoField;
} }
public NumberFormatedTextField getValorField() { public NumberFormatedTextField getValorField() {
return valorField; return valorField;
} }
public FondoTableModel getTableModel() { public FondoTableModel getTableModel() {
return tableModel; return tableModel;
} }
private void createUIComponents() { private void createUIComponents() {
this.createTable(); this.createTable();
} }
private void createTable() { private void createTable() {
this.tableModel = new FondoTableModel(); this.tableModel = new FondoTableModel();
this.table = new JTable(this.tableModel); this.table = new JTable(this.tableModel);
RowSorter<TableModel> sorter = new TableRowSorter<>(this.tableModel); RowSorter<TableModel> sorter = new TableRowSorter<>(this.tableModel);
this.table.setRowSorter(sorter); this.table.setRowSorter(sorter);
this.table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); this.table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
} }
private void fillDefaultsValues() { private void fillDefaultsValues() {
this.valorField.setValue(0); this.valorField.setValue(0);
this.depositoField.setValue(0); this.depositoField.setValue(0);
this.fondoField.setValue(0); this.fondoField.setValue(0);
this.sumaField.setValue(0); this.sumaField.setValue(0);
this.depositoField.setValue(0); this.depositoField.setValue(0);
} }
/** /**
* Method generated by IntelliJ IDEA GUI Designer * Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR
* >>> IMPORTANT!! <<< * call it in your code!
* DO NOT edit this method OR call it in your code! *
* * @noinspection ALL
* @noinspection ALL */
*/ private void $$$setupUI$$$() {
private void $$$setupUI$$$() { createUIComponents();
createUIComponents(); contentPanel = new JPanel();
contentPanel = new JPanel(); contentPanel.setLayout(new GridLayoutManager(4, 1, new Insets(10, 10, 10, 10), -1, -1));
contentPanel.setLayout(new GridLayoutManager(4, 1, new Insets(10, 10, 10, 10), -1, -1)); final JScrollPane scrollPane1 = new JScrollPane();
final JScrollPane scrollPane1 = new JScrollPane(); contentPanel.add(scrollPane1,
contentPanel.add(scrollPane1, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
scrollPane1.setViewportView(table); GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW,
final JPanel panel1 = new JPanel(); GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null,
panel1.setLayout(new GridLayoutManager(2, 3, new Insets(0, 0, 0, 0), -1, -1)); null, null, 0, false));
contentPanel.add(panel1, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); scrollPane1.setViewportView(table);
fondoField = new NumberFormatedTextField(); final JPanel panel1 = new JPanel();
panel1.add(fondoField, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false)); panel1.setLayout(new GridLayoutManager(2, 3, new Insets(0, 0, 0, 0), -1, -1));
final JLabel label1 = new JLabel(); contentPanel.add(panel1,
label1.setText("Fondo"); new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
panel1.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
final JLabel label2 = new JLabel(); GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
label2.setText("Suma de dinero"); null, 0, false));
panel1.add(label2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); fondoField = new NumberFormatedTextField();
final JLabel label3 = new JLabel(); panel1.add(fondoField, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER,
label3.setText("Deposito"); GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
panel1.add(label3, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
sumaField = new NumberFormatedTextField(); final JLabel label1 = new JLabel();
sumaField.setEditable(false); label1.setText("Fondo");
panel1.add(sumaField, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false)); panel1.add(label1,
depositoField = new NumberFormatedTextField(); new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
depositoField.setEditable(false); GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
panel1.add(depositoField, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false)); false));
final JPanel panel2 = new JPanel(); final JLabel label2 = new JLabel();
panel2.setLayout(new GridLayoutManager(2, 2, new Insets(0, 0, 0, 0), -1, -1)); label2.setText("Suma de dinero");
contentPanel.add(panel2, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel1.add(label2,
valorField = new NumberFormatedTextField(); new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
panel2.add(valorField, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false)); GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
descripcionField = new JTextField(); false));
panel2.add(descripcionField, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false)); final JLabel label3 = new JLabel();
final JLabel label4 = new JLabel(); label3.setText("Deposito");
label4.setText("Valor"); panel1.add(label3,
panel2.add(label4, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
final JLabel label5 = new JLabel(); GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
label5.setText("Descripcion"); false));
panel2.add(label5, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); sumaField = new NumberFormatedTextField();
final JPanel panel3 = new JPanel(); sumaField.setEditable(false);
panel3.setLayout(new GridLayoutManager(1, 3, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(sumaField, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER,
contentPanel.add(panel3, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
guardarButton = new JButton(); GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
guardarButton.setText("Guardar"); depositoField = new NumberFormatedTextField();
panel3.add(guardarButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); depositoField.setEditable(false);
editarButton = new JButton(); panel1.add(depositoField, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_CENTER,
editarButton.setText("Editar"); GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
panel3.add(editarButton, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
eliminarButton = new JButton(); final JPanel panel2 = new JPanel();
eliminarButton.setText("Eliminar"); panel2.setLayout(new GridLayoutManager(2, 2, new Insets(0, 0, 0, 0), -1, -1));
panel3.add(eliminarButton, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); contentPanel.add(panel2,
} new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
valorField = new NumberFormatedTextField();
panel2.add(valorField, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
descripcionField = new JTextField();
panel2.add(descripcionField, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label4 = new JLabel();
label4.setText("Valor");
panel2.add(label4,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
final JLabel label5 = new JLabel();
label5.setText("Descripcion");
panel2.add(label5,
new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
final JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayoutManager(1, 3, new Insets(0, 0, 0, 0), -1, -1));
contentPanel.add(panel3,
new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
guardarButton = new JButton();
guardarButton.setText("Guardar");
panel3.add(guardarButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
editarButton = new JButton();
editarButton.setText("Editar");
panel3.add(editarButton, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
eliminarButton = new JButton();
eliminarButton.setText("Eliminar");
panel3.add(eliminarButton, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
}
/** /**
* @noinspection ALL * @noinspection ALL
*/ */
public JComponent $$$getRootComponent$$$() { public JComponent $$$getRootComponent$$$() {
return contentPanel; return contentPanel;
} }
} }

View File

@@ -30,222 +30,305 @@ import com.intellij.uiDesigner.core.Spacer;
import danielcortes.xyz.models.tipo_egreso.TipoEgresoToStringWrapper; import danielcortes.xyz.models.tipo_egreso.TipoEgresoToStringWrapper;
import danielcortes.xyz.views.components.NumberFormatedTextField; import danielcortes.xyz.views.components.NumberFormatedTextField;
import danielcortes.xyz.views.components.table_model.EgresosTableModel; import danielcortes.xyz.views.components.table_model.EgresosTableModel;
import java.awt.Color;
import javax.swing.*; import java.awt.Dimension;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowSorter;
import javax.swing.table.TableRowSorter; import javax.swing.table.TableRowSorter;
import java.awt.*;
public class EgresosView { public class EgresosView {
public JPanel contentPanel;
private JTable egresosTable; public JPanel contentPanel;
private JButton guardarButton; private JTable egresosTable;
private NumberFormatedTextField valorField; private JButton guardarButton;
private JTextField descripcionField; private NumberFormatedTextField valorField;
private JTextField nroField; private JTextField descripcionField;
private NumberFormatedTextField totalEgresosField; private JTextField nroField;
private JComboBox<TipoEgresoToStringWrapper> tipoCombo; private NumberFormatedTextField totalEgresosField;
private JComboBox<TipoEgresoToStringWrapper> tipoCombo;
private JButton eliminarButton; private JButton eliminarButton;
private JLabel errorNumero; private JLabel errorNumero;
private JLabel errorDescripcion; private JLabel errorDescripcion;
private JLabel errorValor; private JLabel errorValor;
private JLabel errorTipoEgreso; private JLabel errorTipoEgreso;
private JButton editarButton; private JButton editarButton;
private EgresosTableModel egresosTableModel; private EgresosTableModel egresosTableModel;
private void createUIComponents() { {
createEgresosTable();
createTipoCombo();
}
private void createEgresosTable() {
egresosTableModel = new EgresosTableModel();
egresosTable = new JTable(egresosTableModel);
RowSorter<EgresosTableModel> sorter = new TableRowSorter<>(egresosTableModel);
egresosTable.setRowSorter(sorter);
egresosTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
private void createTipoCombo() {
this.tipoCombo = new JComboBox<>();
}
public JPanel getContentPanel() {
return contentPanel;
}
public JButton getGuardarButton() {
return guardarButton;
}
public JButton getEliminarButton() {
return eliminarButton;
}
public JButton getEditarButton() {
return editarButton;
}
public NumberFormatedTextField getValorField() {
return valorField;
}
public JTextField getDescripcionField() {
return descripcionField;
}
public JTextField getNroField() {
return nroField;
}
public NumberFormatedTextField getTotalEgresosField() {
return totalEgresosField;
}
public JComboBox<TipoEgresoToStringWrapper> getTipoCombo() {
return tipoCombo;
}
public JTable getEgresosTable() {
return egresosTable;
}
public EgresosTableModel getEgresosTableModel() {
return egresosTableModel;
}
public JLabel getErrorNumero() {
return errorNumero;
}
public JLabel getErrorDescripcion() {
return errorDescripcion;
}
public JLabel getErrorValor() {
return errorValor;
}
public JLabel getErrorTipoEgreso() {
return errorTipoEgreso;
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer // GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<< // >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE! // DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$(); $$$setupUI$$$();
} }
/** private void createUIComponents() {
* Method generated by IntelliJ IDEA GUI Designer createEgresosTable();
* >>> IMPORTANT!! <<< createTipoCombo();
* DO NOT edit this method OR call it in your code! }
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
contentPanel = new JPanel();
contentPanel.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(3, 1, new Insets(10, 10, 10, 10), -1, -1));
contentPanel.add(panel1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
panel1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Egresos"));
final JScrollPane scrollPane1 = new JScrollPane();
panel1.add(scrollPane1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
scrollPane1.setViewportView(egresosTable);
final JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayoutManager(3, 4, new Insets(0, 0, 0, 0), -1, -1));
panel1.add(panel2, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final JLabel label1 = new JLabel();
label1.setText("");
panel2.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label2 = new JLabel();
label2.setText("Descripcion");
panel2.add(label2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
descripcionField = new JTextField();
panel2.add(descripcionField, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
nroField = new JTextField();
panel2.add(nroField, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
valorField = new NumberFormatedTextField();
panel2.add(valorField, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label3 = new JLabel();
label3.setText("Valor");
panel2.add(label3, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label4 = new JLabel();
label4.setText("Tipo");
panel2.add(label4, new GridConstraints(0, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
panel2.add(tipoCombo, new GridConstraints(1, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
errorNumero = new JLabel();
errorNumero.setEnabled(true);
errorNumero.setForeground(new Color(-65536));
errorNumero.setText("Error");
errorNumero.setVisible(false);
panel2.add(errorNumero, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
errorDescripcion = new JLabel();
errorDescripcion.setEnabled(true);
errorDescripcion.setForeground(new Color(-65536));
errorDescripcion.setText("Error");
errorDescripcion.setVisible(false);
panel2.add(errorDescripcion, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
errorValor = new JLabel();
errorValor.setEnabled(true);
errorValor.setForeground(new Color(-65536));
errorValor.setText("Error");
errorValor.setVisible(false);
panel2.add(errorValor, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
errorTipoEgreso = new JLabel();
errorTipoEgreso.setEnabled(true);
errorTipoEgreso.setForeground(new Color(-65536));
errorTipoEgreso.setText("Error");
errorTipoEgreso.setVisible(false);
panel2.add(errorTipoEgreso, new GridConstraints(2, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayoutManager(1, 3, new Insets(0, 0, 0, 0), -1, -1));
panel1.add(panel3, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final JPanel panel4 = new JPanel();
panel4.setLayout(new GridLayoutManager(1, 3, new Insets(0, 0, 0, 0), -1, -1));
panel3.add(panel4, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
guardarButton = new JButton();
guardarButton.setText("Añadir");
guardarButton.setMnemonic('A');
guardarButton.setDisplayedMnemonicIndex(0);
panel4.add(guardarButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
eliminarButton = new JButton();
eliminarButton.setEnabled(false);
eliminarButton.setText("Eliminar");
eliminarButton.setMnemonic('E');
eliminarButton.setDisplayedMnemonicIndex(0);
panel4.add(eliminarButton, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
editarButton = new JButton();
editarButton.setEnabled(false);
editarButton.setText("Editar");
editarButton.setMnemonic('D');
editarButton.setDisplayedMnemonicIndex(1);
panel4.add(editarButton, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final Spacer spacer1 = new Spacer();
panel3.add(spacer1, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
final JPanel panel5 = new JPanel();
panel5.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
panel3.add(panel5, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final JLabel label5 = new JLabel();
label5.setText("Total Egresos:");
panel5.add(label5, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
totalEgresosField = new NumberFormatedTextField();
totalEgresosField.setEditable(false);
panel5.add(totalEgresosField, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
}
/** private void createEgresosTable() {
* @noinspection ALL egresosTableModel = new EgresosTableModel();
*/ egresosTable = new JTable(egresosTableModel);
public JComponent $$$getRootComponent$$$() {
return contentPanel; RowSorter<EgresosTableModel> sorter = new TableRowSorter<>(egresosTableModel);
} egresosTable.setRowSorter(sorter);
egresosTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
private void createTipoCombo() {
this.tipoCombo = new JComboBox<>();
}
public JPanel getContentPanel() {
return contentPanel;
}
public JButton getGuardarButton() {
return guardarButton;
}
public JButton getEliminarButton() {
return eliminarButton;
}
public JButton getEditarButton() {
return editarButton;
}
public NumberFormatedTextField getValorField() {
return valorField;
}
public JTextField getDescripcionField() {
return descripcionField;
}
public JTextField getNroField() {
return nroField;
}
public NumberFormatedTextField getTotalEgresosField() {
return totalEgresosField;
}
public JComboBox<TipoEgresoToStringWrapper> getTipoCombo() {
return tipoCombo;
}
public JTable getEgresosTable() {
return egresosTable;
}
public EgresosTableModel getEgresosTableModel() {
return egresosTableModel;
}
public JLabel getErrorNumero() {
return errorNumero;
}
public JLabel getErrorDescripcion() {
return errorDescripcion;
}
public JLabel getErrorValor() {
return errorValor;
}
public JLabel getErrorTipoEgreso() {
return errorTipoEgreso;
}
/**
* Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR
* call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
contentPanel = new JPanel();
contentPanel.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(3, 1, new Insets(10, 10, 10, 10), -1, -1));
contentPanel.add(panel1,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
panel1
.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Egresos"));
final JScrollPane scrollPane1 = new JScrollPane();
panel1.add(scrollPane1,
new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null,
null, null, 0, false));
scrollPane1.setViewportView(egresosTable);
final JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayoutManager(3, 4, new Insets(0, 0, 0, 0), -1, -1));
panel1.add(panel2,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
final JLabel label1 = new JLabel();
label1.setText("");
panel2.add(label1,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
final JLabel label2 = new JLabel();
label2.setText("Descripcion");
panel2.add(label2,
new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
descripcionField = new JTextField();
panel2.add(descripcionField, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
nroField = new JTextField();
panel2.add(nroField, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
valorField = new NumberFormatedTextField();
panel2.add(valorField, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label3 = new JLabel();
label3.setText("Valor");
panel2.add(label3,
new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
final JLabel label4 = new JLabel();
label4.setText("Tipo");
panel2.add(label4,
new GridConstraints(0, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
panel2.add(tipoCombo, new GridConstraints(1, 3, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
errorNumero = new JLabel();
errorNumero.setEnabled(true);
errorNumero.setForeground(new Color(-65536));
errorNumero.setText("Error");
errorNumero.setVisible(false);
panel2.add(errorNumero,
new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
errorDescripcion = new JLabel();
errorDescripcion.setEnabled(true);
errorDescripcion.setForeground(new Color(-65536));
errorDescripcion.setText("Error");
errorDescripcion.setVisible(false);
panel2.add(errorDescripcion,
new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
errorValor = new JLabel();
errorValor.setEnabled(true);
errorValor.setForeground(new Color(-65536));
errorValor.setText("Error");
errorValor.setVisible(false);
panel2.add(errorValor,
new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
errorTipoEgreso = new JLabel();
errorTipoEgreso.setEnabled(true);
errorTipoEgreso.setForeground(new Color(-65536));
errorTipoEgreso.setText("Error");
errorTipoEgreso.setVisible(false);
panel2.add(errorTipoEgreso,
new GridConstraints(2, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
final JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayoutManager(1, 3, new Insets(0, 0, 0, 0), -1, -1));
panel1.add(panel3,
new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
final JPanel panel4 = new JPanel();
panel4.setLayout(new GridLayoutManager(1, 3, new Insets(0, 0, 0, 0), -1, -1));
panel3.add(panel4,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
guardarButton = new JButton();
guardarButton.setText("Añadir");
guardarButton.setMnemonic('A');
guardarButton.setDisplayedMnemonicIndex(0);
panel4.add(guardarButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
eliminarButton = new JButton();
eliminarButton.setEnabled(false);
eliminarButton.setText("Eliminar");
eliminarButton.setMnemonic('E');
eliminarButton.setDisplayedMnemonicIndex(0);
panel4.add(eliminarButton, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
editarButton = new JButton();
editarButton.setEnabled(false);
editarButton.setText("Editar");
editarButton.setMnemonic('D');
editarButton.setDisplayedMnemonicIndex(1);
panel4.add(editarButton, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final Spacer spacer1 = new Spacer();
panel3.add(spacer1, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null,
0, false));
final JPanel panel5 = new JPanel();
panel5.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
panel3.add(panel5,
new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
final JLabel label5 = new JLabel();
label5.setText("Total Egresos:");
panel5.add(label5,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
totalEgresosField = new NumberFormatedTextField();
totalEgresosField.setEditable(false);
panel5.add(totalEgresosField, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPanel;
}
} }

File diff suppressed because it is too large Load Diff

View File

@@ -27,79 +27,102 @@ package danielcortes.xyz.views;
import com.intellij.uiDesigner.core.GridConstraints; 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 java.awt.Insets;
import javax.swing.*; import javax.swing.BorderFactory;
import java.awt.*; import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
public class InformesSideBar { public class InformesSideBar {
private JButton generarLibroVentasButton;
private JPanel contentPanel;
private JButton GenerarEgresosFacturasMateriaPrimaButton;
private JButton estadoResultadoButton;
private JButton volverButton;
public JPanel getContentPanel() { private JButton generarLibroVentasButton;
return contentPanel; private JPanel contentPanel;
} private JButton GenerarEgresosFacturasMateriaPrimaButton;
private JButton estadoResultadoButton;
private JButton volverButton;
public JButton getInformeLibroDeVentasButton() { {
return generarLibroVentasButton;
}
public JButton getGenerarEgresosFacturasMateriaPrimaButton() {
return GenerarEgresosFacturasMateriaPrimaButton;
}
public JButton getEstadoResultadoButton() {
return estadoResultadoButton;
}
public JButton getVolverButton() {
return volverButton;
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer // GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<< // >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE! // DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$(); $$$setupUI$$$();
} }
/** public JPanel getContentPanel() {
* Method generated by IntelliJ IDEA GUI Designer return contentPanel;
* >>> IMPORTANT!! <<< }
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
contentPanel = new JPanel();
contentPanel.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(5, 1, new Insets(10, 10, 10, 10), -1, -1));
contentPanel.add(panel1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
panel1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Informes Mensuales"));
generarLibroVentasButton = new JButton();
generarLibroVentasButton.setText("Libro de Ventas Mensual");
panel1.add(generarLibroVentasButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
GenerarEgresosFacturasMateriaPrimaButton = new JButton();
GenerarEgresosFacturasMateriaPrimaButton.setText("Informe de Egresos");
panel1.add(GenerarEgresosFacturasMateriaPrimaButton, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Spacer spacer1 = new Spacer();
panel1.add(spacer1, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
estadoResultadoButton = new JButton();
estadoResultadoButton.setText("Estado Resultado");
panel1.add(estadoResultadoButton, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
volverButton = new JButton();
volverButton.setText("Volver");
panel1.add(volverButton, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
}
/** public JButton getInformeLibroDeVentasButton() {
* @noinspection ALL return generarLibroVentasButton;
*/ }
public JComponent $$$getRootComponent$$$() {
return contentPanel; public JButton getGenerarEgresosFacturasMateriaPrimaButton() {
} return GenerarEgresosFacturasMateriaPrimaButton;
}
public JButton getEstadoResultadoButton() {
return estadoResultadoButton;
}
public JButton getVolverButton() {
return volverButton;
}
/**
* Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR
* call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
contentPanel = new JPanel();
contentPanel.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(5, 1, new Insets(10, 10, 10, 10), -1, -1));
contentPanel.add(panel1,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
panel1.setBorder(
BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Informes Mensuales"));
generarLibroVentasButton = new JButton();
generarLibroVentasButton.setText("Libro de Ventas Mensual");
panel1.add(generarLibroVentasButton,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
GenerarEgresosFacturasMateriaPrimaButton = new JButton();
GenerarEgresosFacturasMateriaPrimaButton.setText("Informe de Egresos");
panel1.add(GenerarEgresosFacturasMateriaPrimaButton,
new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Spacer spacer1 = new Spacer();
panel1.add(spacer1, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0,
false));
estadoResultadoButton = new JButton();
estadoResultadoButton.setText("Estado Resultado");
panel1.add(estadoResultadoButton, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
volverButton = new JButton();
volverButton.setText("Volver");
panel1.add(volverButton, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPanel;
}
} }

View File

@@ -27,251 +27,347 @@ package danielcortes.xyz.views;
import com.intellij.uiDesigner.core.GridConstraints; 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.models.tipo_ingreso.TipoIngreso;
import danielcortes.xyz.models.tipo_ingreso.TipoIngresoToStringWrapper; import danielcortes.xyz.models.tipo_ingreso.TipoIngresoToStringWrapper;
import danielcortes.xyz.views.components.NumberFormatedTextField; import danielcortes.xyz.views.components.NumberFormatedTextField;
import danielcortes.xyz.views.components.table_model.IngresosTableModel; import danielcortes.xyz.views.components.table_model.IngresosTableModel;
import java.awt.Color;
import javax.swing.*; import java.awt.Dimension;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowSorter;
import javax.swing.table.TableRowSorter; import javax.swing.table.TableRowSorter;
import java.awt.*;
public class IngresosView { public class IngresosView {
private JPanel contentPanel;
private JTable ingresosTable;
private JButton guardarButton;
private JButton eliminarButton;
private NumberFormatedTextField totalIngresoField;
private NumberFormatedTextField valorField;
private JComboBox<TipoIngresoToStringWrapper> tipoCombo;
private JLabel errorTipoIngreso;
private JLabel errorValor;
private JButton editarButton;
private JTextField nroInicialField;
private JTextField nroFinalField;
private JLabel errorNroInicial;
private JLabel errorNroFinal;
private JTextField nroZInicialField;
private JTextField nroZFinalField;
private JLabel errorNroZFinal;
private JLabel errorNroZInicial;
private IngresosTableModel ingresosTableModel; private JPanel contentPanel;
private JTable ingresosTable;
private JButton guardarButton;
private JButton eliminarButton;
private NumberFormatedTextField totalIngresoField;
private NumberFormatedTextField valorField;
private JComboBox<TipoIngresoToStringWrapper> tipoCombo;
private JLabel errorTipoIngreso;
private JLabel errorValor;
private JButton editarButton;
private JTextField nroInicialField;
private JTextField nroFinalField;
private JLabel errorNroInicial;
private JLabel errorNroFinal;
private JTextField nroZInicialField;
private JTextField nroZFinalField;
private JLabel errorNroZFinal;
private JLabel errorNroZInicial;
private void createUIComponents() { private IngresosTableModel ingresosTableModel;
this.createIngresosTable();
this.createTipoCombo();
}
private void createIngresosTable() { {
this.ingresosTableModel = new IngresosTableModel();
this.ingresosTable = new JTable(ingresosTableModel);
RowSorter<IngresosTableModel> sorter = new TableRowSorter<>(ingresosTableModel);
this.ingresosTable.setRowSorter(sorter);
this.ingresosTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
private void createTipoCombo() {
this.tipoCombo = new JComboBox<>();
}
public JPanel getContentPanel() {
return contentPanel;
}
public JTable getIngresosTable() {
return ingresosTable;
}
public JButton getGuardarButton() {
return guardarButton;
}
public JButton getEliminarButton() {
return eliminarButton;
}
public NumberFormatedTextField getTotalIngresoField() {
return totalIngresoField;
}
public NumberFormatedTextField getValorField() {
return valorField;
}
public JComboBox<TipoIngresoToStringWrapper> getTipoCombo() {
return tipoCombo;
}
public JLabel getErrorTipoIngreso() {
return errorTipoIngreso;
}
public JLabel getErrorValor() {
return errorValor;
}
public JButton getEditarButton() {
return editarButton;
}
public JTextField getNroInicialField() {
return nroInicialField;
}
public JTextField getNroFinalField() {
return nroFinalField;
}
public JLabel getErrorNroInicial() {
return errorNroInicial;
}
public JLabel getErrorNroFinal() {
return errorNroFinal;
}
public IngresosTableModel getIngresosTableModel() {
return ingresosTableModel;
}
public JTextField getNroZInicialField() {
return nroZInicialField;
}
public JTextField getNroZFinalField() {
return nroZFinalField;
}
public JLabel getErrorNroZFinal() {
return errorNroZFinal;
}
public JLabel getErrorNroZInicial() {
return errorNroZInicial;
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer // GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<< // >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE! // DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$(); $$$setupUI$$$();
} }
/** private void createUIComponents() {
* Method generated by IntelliJ IDEA GUI Designer this.createIngresosTable();
* >>> IMPORTANT!! <<< this.createTipoCombo();
* DO NOT edit this method OR call it in your code! }
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
contentPanel = new JPanel();
contentPanel.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(3, 1, new Insets(10, 10, 10, 10), -1, -1));
contentPanel.add(panel1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
panel1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Ingresos"));
final JScrollPane scrollPane1 = new JScrollPane();
panel1.add(scrollPane1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
scrollPane1.setViewportView(ingresosTable);
final JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayoutManager(3, 6, new Insets(0, 0, 0, 0), -1, -1));
panel1.add(panel2, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(150, -1), null, 0, false));
final JLabel label1 = new JLabel();
label1.setText("Tipo");
panel2.add(label1, new GridConstraints(0, 5, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final DefaultComboBoxModel defaultComboBoxModel1 = new DefaultComboBoxModel();
tipoCombo.setModel(defaultComboBoxModel1);
panel2.add(tipoCombo, new GridConstraints(1, 5, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label2 = new JLabel();
label2.setText("Valor");
panel2.add(label2, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
valorField = new NumberFormatedTextField();
panel2.add(valorField, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label3 = new JLabel();
label3.setText("N° Inicial");
panel2.add(label3, new GridConstraints(0, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label4 = new JLabel();
label4.setText("N° Final");
panel2.add(label4, new GridConstraints(0, 4, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
nroInicialField = new JTextField();
panel2.add(nroInicialField, new GridConstraints(1, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
nroFinalField = new JTextField();
panel2.add(nroFinalField, new GridConstraints(1, 4, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
errorTipoIngreso = new JLabel();
errorTipoIngreso.setForeground(new Color(-65536));
errorTipoIngreso.setText("Label");
errorTipoIngreso.setVisible(false);
panel2.add(errorTipoIngreso, new GridConstraints(2, 5, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
errorNroInicial = new JLabel();
errorNroInicial.setForeground(new Color(-65536));
errorNroInicial.setText("Label");
errorNroInicial.setVisible(false);
panel2.add(errorNroInicial, new GridConstraints(2, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
errorNroFinal = new JLabel();
errorNroFinal.setForeground(new Color(-65536));
errorNroFinal.setText("Label");
errorNroFinal.setVisible(false);
panel2.add(errorNroFinal, new GridConstraints(2, 4, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label5 = new JLabel();
label5.setText("N° Z Inicial");
panel2.add(label5, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label6 = new JLabel();
label6.setText("N° Z Final");
panel2.add(label6, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
nroZInicialField = new JTextField();
panel2.add(nroZInicialField, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
nroZFinalField = new JTextField();
panel2.add(nroZFinalField, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
errorNroZInicial = new JLabel();
errorNroZInicial.setForeground(new Color(-65536));
errorNroZInicial.setText("Label");
errorNroZInicial.setVisible(false);
panel2.add(errorNroZInicial, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
errorNroZFinal = new JLabel();
errorNroZFinal.setForeground(new Color(-65536));
errorNroZFinal.setText("Label");
errorNroZFinal.setVisible(false);
panel2.add(errorNroZFinal, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayoutManager(1, 3, new Insets(0, 0, 0, 0), -1, -1));
panel1.add(panel3, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final JPanel panel4 = new JPanel();
panel4.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
panel3.add(panel4, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final JLabel label7 = new JLabel();
label7.setText("Total Ingresos");
panel4.add(label7, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
totalIngresoField = new NumberFormatedTextField();
totalIngresoField.setEditable(false);
panel4.add(totalIngresoField, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JPanel panel5 = new JPanel();
panel5.setLayout(new GridLayoutManager(1, 3, new Insets(0, 0, 0, 0), -1, -1));
panel3.add(panel5, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
guardarButton = new JButton();
guardarButton.setText("Añadir");
guardarButton.setMnemonic('A');
guardarButton.setDisplayedMnemonicIndex(0);
panel5.add(guardarButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
eliminarButton = new JButton();
eliminarButton.setText("Eliminar");
panel5.add(eliminarButton, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
editarButton = new JButton();
editarButton.setText("Editar");
panel5.add(editarButton, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final Spacer spacer1 = new Spacer();
panel3.add(spacer1, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
}
/** private void createIngresosTable() {
* @noinspection ALL this.ingresosTableModel = new IngresosTableModel();
*/ this.ingresosTable = new JTable(ingresosTableModel);
public JComponent $$$getRootComponent$$$() {
return contentPanel; RowSorter<IngresosTableModel> sorter = new TableRowSorter<>(ingresosTableModel);
} this.ingresosTable.setRowSorter(sorter);
this.ingresosTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
private void createTipoCombo() {
this.tipoCombo = new JComboBox<>();
}
public JPanel getContentPanel() {
return contentPanel;
}
public JTable getIngresosTable() {
return ingresosTable;
}
public JButton getGuardarButton() {
return guardarButton;
}
public JButton getEliminarButton() {
return eliminarButton;
}
public NumberFormatedTextField getTotalIngresoField() {
return totalIngresoField;
}
public NumberFormatedTextField getValorField() {
return valorField;
}
public JComboBox<TipoIngresoToStringWrapper> getTipoCombo() {
return tipoCombo;
}
public JLabel getErrorTipoIngreso() {
return errorTipoIngreso;
}
public JLabel getErrorValor() {
return errorValor;
}
public JButton getEditarButton() {
return editarButton;
}
public JTextField getNroInicialField() {
return nroInicialField;
}
public JTextField getNroFinalField() {
return nroFinalField;
}
public JLabel getErrorNroInicial() {
return errorNroInicial;
}
public JLabel getErrorNroFinal() {
return errorNroFinal;
}
public IngresosTableModel getIngresosTableModel() {
return ingresosTableModel;
}
public JTextField getNroZInicialField() {
return nroZInicialField;
}
public JTextField getNroZFinalField() {
return nroZFinalField;
}
public JLabel getErrorNroZFinal() {
return errorNroZFinal;
}
public JLabel getErrorNroZInicial() {
return errorNroZInicial;
}
/**
* Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR
* call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
contentPanel = new JPanel();
contentPanel.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(3, 1, new Insets(10, 10, 10, 10), -1, -1));
contentPanel.add(panel1,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
panel1.setBorder(
BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Ingresos"));
final JScrollPane scrollPane1 = new JScrollPane();
panel1.add(scrollPane1,
new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null,
null, null, 0, false));
scrollPane1.setViewportView(ingresosTable);
final JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayoutManager(3, 6, new Insets(0, 0, 0, 0), -1, -1));
panel1.add(panel2,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null,
new Dimension(150, -1), null, 0, false));
final JLabel label1 = new JLabel();
label1.setText("Tipo");
panel2.add(label1,
new GridConstraints(0, 5, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
final DefaultComboBoxModel defaultComboBoxModel1 = new DefaultComboBoxModel();
tipoCombo.setModel(defaultComboBoxModel1);
panel2.add(tipoCombo, new GridConstraints(1, 5, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label2 = new JLabel();
label2.setText("Valor");
panel2.add(label2,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
valorField = new NumberFormatedTextField();
panel2.add(valorField, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JLabel label3 = new JLabel();
label3.setText("N° Inicial");
panel2.add(label3,
new GridConstraints(0, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
final JLabel label4 = new JLabel();
label4.setText("N° Final");
panel2.add(label4,
new GridConstraints(0, 4, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
nroInicialField = new JTextField();
panel2.add(nroInicialField, new GridConstraints(1, 3, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
nroFinalField = new JTextField();
panel2.add(nroFinalField, new GridConstraints(1, 4, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
errorTipoIngreso = new JLabel();
errorTipoIngreso.setForeground(new Color(-65536));
errorTipoIngreso.setText("Label");
errorTipoIngreso.setVisible(false);
panel2.add(errorTipoIngreso,
new GridConstraints(2, 5, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
errorNroInicial = new JLabel();
errorNroInicial.setForeground(new Color(-65536));
errorNroInicial.setText("Label");
errorNroInicial.setVisible(false);
panel2.add(errorNroInicial,
new GridConstraints(2, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
errorNroFinal = new JLabel();
errorNroFinal.setForeground(new Color(-65536));
errorNroFinal.setText("Label");
errorNroFinal.setVisible(false);
panel2.add(errorNroFinal,
new GridConstraints(2, 4, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
final JLabel label5 = new JLabel();
label5.setText("N° Z Inicial");
panel2.add(label5,
new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
final JLabel label6 = new JLabel();
label6.setText("N° Z Final");
panel2.add(label6,
new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
nroZInicialField = new JTextField();
panel2.add(nroZInicialField, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
nroZFinalField = new JTextField();
panel2.add(nroZFinalField, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
errorNroZInicial = new JLabel();
errorNroZInicial.setForeground(new Color(-65536));
errorNroZInicial.setText("Label");
errorNroZInicial.setVisible(false);
panel2.add(errorNroZInicial,
new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
errorNroZFinal = new JLabel();
errorNroZFinal.setForeground(new Color(-65536));
errorNroZFinal.setText("Label");
errorNroZFinal.setVisible(false);
panel2.add(errorNroZFinal,
new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
final JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayoutManager(1, 3, new Insets(0, 0, 0, 0), -1, -1));
panel1.add(panel3,
new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
final JPanel panel4 = new JPanel();
panel4.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
panel3.add(panel4,
new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
final JLabel label7 = new JLabel();
label7.setText("Total Ingresos");
panel4.add(label7,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
totalIngresoField = new NumberFormatedTextField();
totalIngresoField.setEditable(false);
panel4.add(totalIngresoField, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final JPanel panel5 = new JPanel();
panel5.setLayout(new GridLayoutManager(1, 3, new Insets(0, 0, 0, 0), -1, -1));
panel3.add(panel5,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
guardarButton = new JButton();
guardarButton.setText("Añadir");
guardarButton.setMnemonic('A');
guardarButton.setDisplayedMnemonicIndex(0);
panel5.add(guardarButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
eliminarButton = new JButton();
eliminarButton.setText("Eliminar");
panel5.add(eliminarButton, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
editarButton = new JButton();
editarButton.setText("Editar");
panel5.add(editarButton, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
final Spacer spacer1 = new Spacer();
panel3.add(spacer1,
new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPanel;
}
} }

View File

@@ -3,69 +3,84 @@ package danielcortes.xyz.views;
import com.intellij.uiDesigner.core.GridConstraints; 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 java.awt.Insets;
import javax.swing.*; import javax.swing.BorderFactory;
import java.awt.*; import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
public class MainSideBar { public class MainSideBar {
private JPanel contentPanel;
private JButton informesMensualesButton;
private JButton cajasButton;
private JPanel buttonPanel;
public JPanel getContentPanel() { private JPanel contentPanel;
return contentPanel; private JButton informesMensualesButton;
} private JButton cajasButton;
private JPanel buttonPanel;
public JPanel getButtonPanel() { {
return buttonPanel;
}
public JButton getInformesMensualesButton() {
return informesMensualesButton;
}
public JButton getCajasButton() {
return cajasButton;
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer // GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<< // >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE! // DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$(); $$$setupUI$$$();
} }
/** public JPanel getContentPanel() {
* Method generated by IntelliJ IDEA GUI Designer return contentPanel;
* >>> IMPORTANT!! <<< }
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
contentPanel = new JPanel();
contentPanel.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayoutManager(3, 1, new Insets(10, 10, 10, 10), -1, -1));
contentPanel.add(buttonPanel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
buttonPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), null));
cajasButton = new JButton();
cajasButton.setText("Cajas");
buttonPanel.add(cajasButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Spacer spacer1 = new Spacer();
buttonPanel.add(spacer1, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
informesMensualesButton = new JButton();
informesMensualesButton.setText("Informes Mensuales");
buttonPanel.add(informesMensualesButton, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
}
/** public JPanel getButtonPanel() {
* @noinspection ALL return buttonPanel;
*/ }
public JComponent $$$getRootComponent$$$() {
return contentPanel; public JButton getInformesMensualesButton() {
} return informesMensualesButton;
}
public JButton getCajasButton() {
return cajasButton;
}
/**
* Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR
* call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
contentPanel = new JPanel();
contentPanel.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayoutManager(3, 1, new Insets(10, 10, 10, 10), -1, -1));
contentPanel.add(buttonPanel,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
buttonPanel
.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), null));
cajasButton = new JButton();
cajasButton.setText("Cajas");
buttonPanel.add(cajasButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Spacer spacer1 = new Spacer();
buttonPanel.add(spacer1, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0,
false));
informesMensualesButton = new JButton();
informesMensualesButton.setText("Informes Mensuales");
buttonPanel.add(informesMensualesButton,
new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPanel;
}
} }

View File

@@ -1,61 +1,61 @@
package danielcortes.xyz.views.components; package danielcortes.xyz.views.components;
import org.mariuszgromada.math.mxparser.Expression;
import javax.swing.*;
import java.awt.event.FocusEvent; import java.awt.event.FocusEvent;
import java.awt.event.FocusListener; import java.awt.event.FocusListener;
import java.text.NumberFormat; import java.text.NumberFormat;
import javax.swing.JTextField;
import org.mariuszgromada.math.mxparser.Expression;
public class DoubleFormatedTextField extends JTextField { public class DoubleFormatedTextField extends JTextField {
private double value;
private NumberFormat nf;
public DoubleFormatedTextField() { private double value;
super(); private NumberFormat nf;
this.nf = NumberFormat.getIntegerInstance(); public DoubleFormatedTextField() {
this.nf.setMaximumFractionDigits(2); super();
this.addFocusListener(new FocusListener() { this.nf = NumberFormat.getIntegerInstance();
@Override this.nf.setMaximumFractionDigits(2);
public void focusGained(FocusEvent e) {
DoubleFormatedTextField.this.select(0, getText().length());
}
@Override this.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) { @Override
DoubleFormatedTextField.this.readValue(); public void focusGained(FocusEvent e) {
DoubleFormatedTextField.this.formatText(); DoubleFormatedTextField.this.select(0, getText().length());
} }
});
@Override
public void focusLost(FocusEvent e) {
DoubleFormatedTextField.this.readValue();
DoubleFormatedTextField.this.formatText();
}
});
}
public double getValue() {
this.readValue();
return this.value;
}
public void setValue(double value) {
this.value = value;
this.formatText();
}
private void readValue() {
String currentText = this.getText();
String stripedDots = currentText.replace(".", "");
String replacedPeriods = stripedDots.replace(",", ".");
Expression expression = new Expression(replacedPeriods);
if (expression.checkSyntax()) {
this.value = expression.calculate();
} else {
this.value = 0;
} }
public double getValue() { }
this.readValue();
return this.value;
}
public void setValue(double value) { private void formatText() {
this.value = value; this.setText(nf.format(this.value));
this.formatText(); }
}
private void readValue() {
String currentText = this.getText();
String stripedDots = currentText.replace(".", "");
String replacedPeriods = stripedDots.replace(",", ".");
Expression expression = new Expression(replacedPeriods);
if (expression.checkSyntax()) {
this.value = expression.calculate();
} else {
this.value = 0;
}
}
private void formatText() {
this.setText(nf.format(this.value));
}
} }

View File

@@ -24,94 +24,94 @@
package danielcortes.xyz.views.components; package danielcortes.xyz.views.components;
import org.mariuszgromada.math.mxparser.Expression;
import javax.swing.*;
import java.awt.event.FocusEvent; import java.awt.event.FocusEvent;
import java.awt.event.FocusListener; import java.awt.event.FocusListener;
import java.text.NumberFormat; import java.text.NumberFormat;
import javax.swing.JTextField;
import org.mariuszgromada.math.mxparser.Expression;
/** /**
* Crea un JTextField que formatea automaticamente su texto como un integer el cual se puede obtener * Crea un JTextField que formatea automaticamente su texto como un integer el cual se puede obtener
* con el metodo getValue. Ademas de tener comportamientos especiales: * con el metodo getValue. Ademas de tener comportamientos especiales: - Al ganar foco se selecciona
* - Al ganar foco se selecciona todo el texto. * todo el texto. - Al perder foco formatea el texto como numero. - Evalua la operacion matematica
* - Al perder foco formatea el texto como numero. * que se ingrese en el campo
* - Evalua la operacion matematica que se ingrese en el campo
*/ */
public class NumberFormatedTextField extends JTextField { public class NumberFormatedTextField extends JTextField {
private int value;
private NumberFormat nf; private int value;
private NumberFormat nf;
/**
* Crea una instacia del objeto
*/
public NumberFormatedTextField() {
super();
this.nf = NumberFormat.getIntegerInstance();
this.addFocusListener(new FieldFocusListener());
}
/**
* Llama a readValue por un bug seguramente relacionado con el focus listener: - No actualizaba el
* valor al momento de hacer requestfocus a otro componente, probablemente porque no alcanza a
* realizarse la accion antes que ocurra la siguiente
* <p>
* Fuerza a que se lea el valor en el textfield antes de retornarlo
*/
public int getValue() {
this.readValue();
return this.value;
}
/**
* Guarda el integer entregado y lo muestra en el campo.
*/
public void setValue(int value) {
this.value = value;
this.setText(nf.format(value));
}
/**
* Lee el valor en el texto, ejecuta la operacion matematica que en caso que exista una y la
* almacena en el valor Si la operacion matematica es invalida, almacenara un 0
*/
private void readValue() {
String currentText = this.getText();
String stripedDots = currentText.replace(".", "");
Expression expression = new Expression(stripedDots);
if (expression.checkSyntax()) {
this.value = (int) Math.floor(expression.calculate());
} else {
this.value = 0;
}
}
/**
* Formatea el value y lo muestra en el field
*/
private void formatText() {
this.setText(nf.format(this.value));
}
private class FieldFocusListener implements FocusListener {
/** /**
* Crea una instacia del objeto * Selecciona todo al momento de ganar foco
*/ */
public NumberFormatedTextField() { @Override
super(); public void focusGained(FocusEvent e) {
NumberFormatedTextField.this.select(0, getText().length());
this.nf = NumberFormat.getIntegerInstance();
this.addFocusListener(new FieldFocusListener());
} }
/** /**
* Llama a readValue por un bug seguramente relacionado con el focus listener: * Actualiza el texto y el valor interno al perder el foco
* - No actualizaba el valor al momento de hacer requestfocus a otro componente, probablemente porque no alcanza
* a realizarse la accion antes que ocurra la siguiente
* <p>
* Fuerza a que se lea el valor en el textfield antes de retornarlo
*/ */
public int getValue() { @Override
this.readValue(); public void focusLost(FocusEvent e) {
return this.value; NumberFormatedTextField.this.readValue();
} NumberFormatedTextField.this.formatText();
/**
* Guarda el integer entregado y lo muestra en el campo.
*/
public void setValue(int value) {
this.value = value;
this.setText(nf.format(value));
}
/**
* Lee el valor en el texto, ejecuta la operacion matematica que en caso que exista una y la almacena en el valor
* Si la operacion matematica es invalida, almacenara un 0
*/
private void readValue() {
String currentText = this.getText();
String stripedDots = currentText.replace(".", "");
Expression expression = new Expression(stripedDots);
if (expression.checkSyntax()) {
this.value = (int) Math.floor(expression.calculate());
} else {
this.value = 0;
}
}
/**
* Formatea el value y lo muestra en el field
*/
private void formatText() {
this.setText(nf.format(this.value));
}
private class FieldFocusListener implements FocusListener {
/**
* Selecciona todo al momento de ganar foco
*/
@Override
public void focusGained(FocusEvent e) {
NumberFormatedTextField.this.select(0, getText().length());
}
/**
* Actualiza el texto y el valor interno al perder el foco
*/
@Override
public void focusLost(FocusEvent e) {
NumberFormatedTextField.this.readValue();
NumberFormatedTextField.this.formatText();
}
} }
}
} }

View File

@@ -24,68 +24,69 @@
package danielcortes.xyz.views.components; package danielcortes.xyz.views.components;
import javax.swing.*;
import java.time.Year; import java.time.Year;
import javax.swing.AbstractSpinnerModel;
public class YearSpinnerModel extends AbstractSpinnerModel { public class YearSpinnerModel extends AbstractSpinnerModel {
private int value;
private String showingValue;
public YearSpinnerModel() { private int value;
this.value = Year.now().getValue(); private String showingValue;
this.showingValue = String.valueOf(value);
public YearSpinnerModel() {
this.value = Year.now().getValue();
this.showingValue = String.valueOf(value);
}
@Override
public Object getValue() {
return this.showingValue;
}
@Override
public void setValue(Object value) {
this.showingValue = String.valueOf(value);
this.value = Integer.parseInt(this.showingValue);
}
@Override
public Object getNextValue() {
if (this.value == 9999) {
return null;
} }
@Override if (this.value > 9999) {
public Object getValue() { this.value = 9999;
return this.showingValue; this.showingValue = String.valueOf(this.value);
} else if (this.value < 0) {
this.value = 0;
this.showingValue = String.valueOf(this.value);
} else {
this.value++;
this.showingValue = String.valueOf(value);
} }
@Override this.fireStateChanged();
public void setValue(Object value) { return this.showingValue;
this.showingValue = String.valueOf(value); }
this.value = Integer.parseInt(this.showingValue);
@Override
public Object getPreviousValue() {
if (this.value == 0) {
return null;
} }
@Override if (this.value > 9999) {
public Object getNextValue() { this.value = 9999;
if (this.value == 9999) { this.showingValue = String.valueOf(this.value);
return null; } else if (this.value < 0) {
} this.value = 0;
this.showingValue = String.valueOf(this.value);
if (this.value > 9999) { } else {
this.value = 9999; this.value--;
this.showingValue = String.valueOf(this.value); this.showingValue = String.valueOf(value);
} else if (this.value < 0) {
this.value = 0;
this.showingValue = String.valueOf(this.value);
} else {
this.value++;
this.showingValue = String.valueOf(value);
}
this.fireStateChanged();
return this.showingValue;
} }
@Override this.fireStateChanged();
public Object getPreviousValue() { return this.showingValue;
if (this.value == 0) { }
return null;
}
if (this.value > 9999) {
this.value = 9999;
this.showingValue = String.valueOf(this.value);
} else if (this.value < 0) {
this.value = 0;
this.showingValue = String.valueOf(this.value);
} else {
this.value--;
this.showingValue = String.valueOf(value);
}
this.fireStateChanged();
return this.showingValue;
}
} }

View File

@@ -25,80 +25,80 @@
package danielcortes.xyz.views.components.table_model; package danielcortes.xyz.views.components.table_model;
import danielcortes.xyz.models.egreso.Egreso; import danielcortes.xyz.models.egreso.Egreso;
import javax.swing.table.AbstractTableModel;
import java.text.NumberFormat; import java.text.NumberFormat;
import java.util.ArrayList; import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class EgresosTableModel extends AbstractTableModel { public class EgresosTableModel extends AbstractTableModel {
private String[] columns;
private ArrayList<Egreso> rows;
private NumberFormat nf;
public EgresosTableModel() { private String[] columns;
super(); private ArrayList<Egreso> rows;
this.columns = new String[]{"", "Descripcion", "Valor", "Tipo"}; private NumberFormat nf;
this.rows = new ArrayList<>();
this.nf = NumberFormat.getIntegerInstance();
public EgresosTableModel() {
super();
this.columns = new String[]{"", "Descripcion", "Valor", "Tipo"};
this.rows = new ArrayList<>();
this.nf = NumberFormat.getIntegerInstance();
}
@Override
public String getColumnName(int col) {
return columns[col];
}
@Override
public int getColumnCount() {
return columns.length;
}
@Override
public int getRowCount() {
return rows.size();
}
@Override
public Object getValueAt(int row, int col) {
switch (col) {
case 0:
return rows.get(row).getNro();
case 1:
return rows.get(row).getDescripcion();
case 2:
return nf.format(rows.get(row).getValor());
case 3:
return rows.get(row).getTipoEgreso().getNombre();
} }
return null;
}
@Override public void addRow(Egreso egreso) {
public String getColumnName(int col) { rows.add(egreso);
return columns[col]; this.fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1);
}
public void removeRow(int row) {
this.rows.remove(row);
this.fireTableRowsDeleted(row, row);
}
public void removeRows() {
int rowCount = getRowCount();
if (rowCount > 0) {
this.rows.clear();
this.fireTableRowsDeleted(0, rowCount - 1);
} }
}
@Override public Egreso getEgreso(int row) {
public int getColumnCount() { return rows.get(row);
return columns.length; }
}
@Override public void setEgreso(int editingId, Egreso egreso) {
public int getRowCount() { this.rows.set(editingId, egreso);
return rows.size(); this.fireTableRowsUpdated(0, getRowCount() - 1);
} }
@Override
public Object getValueAt(int row, int col) {
switch (col) {
case 0:
return rows.get(row).getNro();
case 1:
return rows.get(row).getDescripcion();
case 2:
return nf.format(rows.get(row).getValor());
case 3:
return rows.get(row).getTipoEgreso().getNombre();
}
return null;
}
public void addRow(Egreso egreso) {
rows.add(egreso);
this.fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1);
}
public void removeRow(int row) {
this.rows.remove(row);
this.fireTableRowsDeleted(row, row);
}
public void removeRows() {
int rowCount = getRowCount();
if (rowCount > 0) {
this.rows.clear();
this.fireTableRowsDeleted(0, rowCount - 1);
}
}
public Egreso getEgreso(int row) {
return rows.get(row);
}
public void setEgreso(int editingId, Egreso egreso) {
this.rows.set(editingId, egreso);
this.fireTableRowsUpdated(0, getRowCount() - 1);
}
} }

View File

@@ -25,77 +25,76 @@
package danielcortes.xyz.views.components.table_model; package danielcortes.xyz.views.components.table_model;
import danielcortes.xyz.models.calculo_fondo.CalculoFondo; import danielcortes.xyz.models.calculo_fondo.CalculoFondo;
import javax.swing.table.AbstractTableModel;
import java.text.NumberFormat; import java.text.NumberFormat;
import java.util.ArrayList; import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class FondoTableModel extends AbstractTableModel { public class FondoTableModel extends AbstractTableModel {
private String[] columns; private String[] columns;
private ArrayList<CalculoFondo> rows; private ArrayList<CalculoFondo> rows;
private NumberFormat nf; private NumberFormat nf;
public FondoTableModel() { public FondoTableModel() {
super(); super();
this.columns = new String[]{"Valor", "Descripcion"}; this.columns = new String[]{"Valor", "Descripcion"};
this.rows = new ArrayList<>(); this.rows = new ArrayList<>();
this.nf = NumberFormat.getIntegerInstance(); this.nf = NumberFormat.getIntegerInstance();
}
@Override
public String getColumnName(int col) {
return columns[col];
}
@Override
public int getColumnCount() {
return columns.length;
}
@Override
public int getRowCount() {
return rows.size();
}
public void addRow(CalculoFondo calculoFondo) {
rows.add(calculoFondo);
this.fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1);
}
public void removeRow(int row) {
this.rows.remove(row);
this.fireTableRowsDeleted(row, row);
}
public void removeRows() {
int rowCount = getRowCount();
if (rowCount > 0) {
this.rows.clear();
this.fireTableRowsDeleted(0, rowCount - 1);
} }
}
@Override public void setCalculoFondo(int editingId, CalculoFondo calculoFondo) {
public String getColumnName(int col) { this.rows.set(editingId, calculoFondo);
return columns[col]; this.fireTableRowsUpdated(0, getRowCount() - 1);
}
@Override
public Object getValueAt(int row, int col) {
switch (col) {
case 0:
return nf.format(rows.get(row).getValor());
case 1:
return rows.get(row).getDescripcion();
} }
return null;
}
@Override public CalculoFondo getCalculoFondo(int row) {
public int getColumnCount() { return rows.get(row);
return columns.length; }
}
@Override
public int getRowCount() {
return rows.size();
}
public void addRow(CalculoFondo calculoFondo) {
rows.add(calculoFondo);
this.fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1);
}
public void removeRow(int row) {
this.rows.remove(row);
this.fireTableRowsDeleted(row, row);
}
public void removeRows() {
int rowCount = getRowCount();
if (rowCount > 0) {
this.rows.clear();
this.fireTableRowsDeleted(0, rowCount - 1);
}
}
public void setCalculoFondo(int editingId, CalculoFondo calculoFondo) {
this.rows.set(editingId, calculoFondo);
this.fireTableRowsUpdated(0, getRowCount() - 1);
}
@Override
public Object getValueAt(int row, int col) {
switch (col) {
case 0:
return nf.format(rows.get(row).getValor());
case 1:
return rows.get(row).getDescripcion();
}
return null;
}
public CalculoFondo getCalculoFondo(int row) {
return rows.get(row);
}
} }

View File

@@ -25,82 +25,83 @@
package danielcortes.xyz.views.components.table_model; package danielcortes.xyz.views.components.table_model;
import danielcortes.xyz.models.ingreso.Ingreso; import danielcortes.xyz.models.ingreso.Ingreso;
import javax.swing.table.AbstractTableModel;
import java.text.NumberFormat; import java.text.NumberFormat;
import java.util.ArrayList; import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class IngresosTableModel extends AbstractTableModel { public class IngresosTableModel extends AbstractTableModel {
private String[] columns;
private ArrayList<Ingreso> rows;
private NumberFormat nf;
public IngresosTableModel() { private String[] columns;
super(); private ArrayList<Ingreso> rows;
this.columns = new String[]{"Valor", "N° Z Inicial", "N° Z Final", "N° Inicial", "N° Final", "Tipo"}; private NumberFormat nf;
this.rows = new ArrayList<>();
this.nf = NumberFormat.getIntegerInstance();
}
@Override public IngresosTableModel() {
public String getColumnName(int col) { super();
return this.columns[col]; this.columns = new String[]{"Valor", "N° Z Inicial", "N° Z Final", "N° Inicial", "N° Final",
} "Tipo"};
this.rows = new ArrayList<>();
this.nf = NumberFormat.getIntegerInstance();
}
@Override @Override
public int getColumnCount() { public String getColumnName(int col) {
return this.columns.length; return this.columns[col];
} }
@Override @Override
public int getRowCount() { public int getColumnCount() {
return this.rows.size(); return this.columns.length;
} }
@Override @Override
public Object getValueAt(int row, int col) { public int getRowCount() {
switch (col) { return this.rows.size();
case 0: }
return nf.format(this.rows.get(row).getValor());
case 1:
return this.rows.get(row).getNroZInicial();
case 2:
return this.rows.get(row).getNroZFinal();
case 3:
return this.rows.get(row).getNroInicial();
case 4:
return this.rows.get(row).getNroFinal();
case 5:
return this.rows.get(row).getTipoIngreso().getNombre();
}
return null;
}
public void addRow(Ingreso ingreso) { @Override
this.rows.add(ingreso); public Object getValueAt(int row, int col) {
this.fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1); switch (col) {
case 0:
return nf.format(this.rows.get(row).getValor());
case 1:
return this.rows.get(row).getNroZInicial();
case 2:
return this.rows.get(row).getNroZFinal();
case 3:
return this.rows.get(row).getNroInicial();
case 4:
return this.rows.get(row).getNroFinal();
case 5:
return this.rows.get(row).getTipoIngreso().getNombre();
} }
return null;
}
public void removeRow(int row) { public void addRow(Ingreso ingreso) {
this.rows.remove(row); this.rows.add(ingreso);
this.fireTableRowsDeleted(row, row); this.fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1);
} }
public void removeRows() { public void removeRow(int row) {
int rowCount = getRowCount(); this.rows.remove(row);
if (rowCount > 0) { this.fireTableRowsDeleted(row, row);
this.rows.clear(); }
this.fireTableRowsDeleted(0, rowCount - 1);
}
}
public Ingreso getIngreso(int row) { public void removeRows() {
return this.rows.get(row); int rowCount = getRowCount();
if (rowCount > 0) {
this.rows.clear();
this.fireTableRowsDeleted(0, rowCount - 1);
} }
}
public void setIngreso(int editingId, Ingreso ingreso) { public Ingreso getIngreso(int row) {
this.rows.set(editingId, ingreso); return this.rows.get(row);
this.fireTableRowsUpdated(getRowCount() - 2, getRowCount() - 1); }
}
public void setIngreso(int editingId, Ingreso ingreso) {
this.rows.set(editingId, ingreso);
this.fireTableRowsUpdated(getRowCount() - 2, getRowCount() - 1);
}
} }

View File

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

View File

@@ -29,160 +29,201 @@ 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 danielcortes.xyz.views.listeners.WindowClosingListener;
import java.awt.Insets;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.YearMonth; import java.time.YearMonth;
import java.util.ArrayList; import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.KeyStroke;
import javax.swing.SpinnerModel;
public class MonthSelectDialog extends JDialog { public class MonthSelectDialog extends JDialog {
private JPanel contentPane;
private JButton buttonOK;
private JButton buttonCancel;
private JComboBox<String> monthCombo;
private JSpinner yearSpinner;
private ArrayList<String> months; private JPanel contentPane;
private JButton buttonOK;
private JButton buttonCancel;
private JComboBox<String> monthCombo;
private JSpinner yearSpinner;
private boolean acepted; private ArrayList<String> months;
public MonthSelectDialog() { private boolean acepted;
$$$setupUI$$$();
setup(); public MonthSelectDialog() {
$$$setupUI$$$();
setup();
}
private void setup() {
this.setContentPane(contentPane);
this.setModalityType(ModalityType.APPLICATION_MODAL);
this.getRootPane().setDefaultButton(buttonOK);
this.buttonOK.addActionListener(e -> onOK());
this.buttonCancel.addActionListener(e -> onCancel());
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
this.addWindowListener((WindowClosingListener) e -> onCancel());
this.contentPane
.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
this.setLocationRelativeTo(null);
pack();
}
public YearMonth execute() {
setVisible(true);
if (this.isAcepted()) {
return this.getMonth();
} else {
return null;
}
}
private void onOK() {
this.acepted = true;
dispose();
}
private void onCancel() {
this.acepted = false;
dispose();
}
private boolean isAcepted() {
return this.acepted;
}
private YearMonth getMonth() {
int year = Integer.valueOf((String) yearSpinner.getValue());
int month = this.months.indexOf(this.monthCombo.getSelectedItem()) + 1;
return YearMonth.of(year, month);
}
private void createUIComponents() {
createYearSpinner();
createMonthCombo();
}
private void createYearSpinner() {
SpinnerModel model = new YearSpinnerModel();
this.yearSpinner = new JSpinner();
this.yearSpinner.setModel(model);
((JSpinner.DefaultEditor) this.yearSpinner.getEditor()).getTextField().setEditable(true);
}
private void createMonthCombo() {
months = new ArrayList<>();
months.add("Enero");
months.add("Febrero");
months.add("Marzo");
months.add("Abril");
months.add("Mayo");
months.add("Junio");
months.add("Julio");
months.add("Agosto");
months.add("Septiembre");
months.add("Octubre");
months.add("Noviembre");
months.add("Diciembre");
monthCombo = new JComboBox<>();
for (String month : months) {
monthCombo.addItem(month);
} }
private void setup() { int currentMonth = LocalDate.now().getMonth().getValue() - 1;
this.setContentPane(contentPane); monthCombo.setSelectedIndex(currentMonth);
this.setModalityType(ModalityType.APPLICATION_MODAL); }
this.getRootPane().setDefaultButton(buttonOK);
this.buttonOK.addActionListener(e -> onOK()); /**
* Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR
* call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
contentPane = new JPanel();
contentPane.setLayout(new GridLayoutManager(2, 1, new Insets(10, 10, 10, 10), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(panel1,
new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null,
null, null, 0, false));
final Spacer spacer1 = new Spacer();
panel1.add(spacer1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null,
0, false));
final JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1, true, false));
panel1.add(panel2,
new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
buttonOK = new JButton();
buttonOK.setText("OK");
panel2.add(buttonOK, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
buttonCancel = new JButton();
buttonCancel.setText("Cancelar");
panel2.add(buttonCancel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayoutManager(3, 2, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(panel3,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
final JLabel label1 = new JLabel();
label1.setText("Mes");
panel3.add(label1,
new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
panel3.add(monthCombo, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label2 = new JLabel();
label2.setText("Año");
panel3.add(label2,
new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
panel3.add(yearSpinner, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label3 = new JLabel();
label3.setText("Seleccione Mes y Año");
panel3.add(label3,
new GridConstraints(0, 0, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
}
this.buttonCancel.addActionListener(e -> onCancel()); /**
* @noinspection ALL
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); */
this.addWindowListener((WindowClosingListener) e -> onCancel()); public JComponent $$$getRootComponent$$$() {
this.contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); return contentPane;
}
this.setLocationRelativeTo(null);
pack();
}
public YearMonth execute() {
setVisible(true);
if (this.isAcepted()) {
return this.getMonth();
} else {
return null;
}
}
private void onOK() {
this.acepted = true;
dispose();
}
private void onCancel() {
this.acepted = false;
dispose();
}
private boolean isAcepted() {
return this.acepted;
}
private YearMonth getMonth() {
int year = Integer.valueOf((String) yearSpinner.getValue());
int month = this.months.indexOf(this.monthCombo.getSelectedItem()) + 1;
return YearMonth.of(year, month);
}
private void createUIComponents() {
createYearSpinner();
createMonthCombo();
}
private void createYearSpinner() {
SpinnerModel model = new YearSpinnerModel();
this.yearSpinner = new JSpinner();
this.yearSpinner.setModel(model);
((JSpinner.DefaultEditor) this.yearSpinner.getEditor()).getTextField().setEditable(true);
}
private void createMonthCombo() {
months = new ArrayList<>();
months.add("Enero");
months.add("Febrero");
months.add("Marzo");
months.add("Abril");
months.add("Mayo");
months.add("Junio");
months.add("Julio");
months.add("Agosto");
months.add("Septiembre");
months.add("Octubre");
months.add("Noviembre");
months.add("Diciembre");
monthCombo = new JComboBox<>();
for (String month : months) {
monthCombo.addItem(month);
}
int currentMonth = LocalDate.now().getMonth().getValue() - 1;
monthCombo.setSelectedIndex(currentMonth);
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
contentPane = new JPanel();
contentPane.setLayout(new GridLayoutManager(2, 1, new Insets(10, 10, 10, 10), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(panel1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false));
final Spacer spacer1 = new Spacer();
panel1.add(spacer1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
final JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1, true, false));
panel1.add(panel2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
buttonOK = new JButton();
buttonOK.setText("OK");
panel2.add(buttonOK, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
buttonCancel = new JButton();
buttonCancel.setText("Cancelar");
panel2.add(buttonCancel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayoutManager(3, 2, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(panel3, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final JLabel label1 = new JLabel();
label1.setText("Mes");
panel3.add(label1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
panel3.add(monthCombo, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label2 = new JLabel();
label2.setText("Año");
panel3.add(label2, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
panel3.add(yearSpinner, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label3 = new JLabel();
label3.setText("Seleccione Mes y Año");
panel3.add(label3, new GridConstraints(0, 0, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPane;
}
} }

View File

@@ -30,116 +30,145 @@ 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 danielcortes.xyz.views.listeners.WindowClosingListener;
import java.awt.Insets;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class TipoEgresoSelectDialog extends JDialog { public class TipoEgresoSelectDialog extends JDialog {
private JPanel contentPane;
private JButton buttonOK;
private JButton buttonCancel;
private JComboBox<TipoEgresoToStringWrapper> tipoEgresoCombo;
private boolean acepted; private JPanel contentPane;
private JButton buttonOK;
private JButton buttonCancel;
private JComboBox<TipoEgresoToStringWrapper> tipoEgresoCombo;
public TipoEgresoSelectDialog() { private boolean acepted;
$$$setupUI$$$();
this.setup(); public TipoEgresoSelectDialog() {
$$$setupUI$$$();
this.setup();
}
private void setup() {
this.setContentPane(contentPane);
this.setModalityType(ModalityType.APPLICATION_MODAL);
this.getRootPane().setDefaultButton(buttonOK);
this.buttonOK.addActionListener(e -> onOK());
this.buttonCancel.addActionListener(e -> onCancel());
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
this.addWindowListener((WindowClosingListener) e -> onCancel());
this.contentPane
.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
this.setLocationRelativeTo(null);
this.pack();
}
public TipoEgreso execute() {
this.setVisible(true);
if (this.isAcepted()) {
return this.getTipoEgreso();
} else {
return null;
} }
}
private void setup() { private void onOK() {
this.setContentPane(contentPane); this.acepted = true;
this.setModalityType(ModalityType.APPLICATION_MODAL); dispose();
this.getRootPane().setDefaultButton(buttonOK); }
this.buttonOK.addActionListener(e -> onOK()); private void onCancel() {
this.buttonCancel.addActionListener(e -> onCancel()); this.acepted = false;
dispose();
}
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); public boolean isAcepted() {
this.addWindowListener((WindowClosingListener) e -> onCancel()); return this.acepted;
this.contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); }
this.setLocationRelativeTo(null); public TipoEgreso getTipoEgreso() {
this.pack(); return (TipoEgreso) tipoEgresoCombo.getSelectedItem();
}
private void createUIComponents() {
createTipoEgresoCombo();
}
private void createTipoEgresoCombo() {
tipoEgresoCombo = new JComboBox<>();
for (TipoEgreso tipoEgreso : DAOManager.getTipoEgresoDAO().findAll()) {
tipoEgresoCombo.addItem(new TipoEgresoToStringWrapper(tipoEgreso));
} }
}
public TipoEgreso execute() { /**
this.setVisible(true); * Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR
* call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
contentPane = new JPanel();
contentPane.setLayout(new GridLayoutManager(2, 1, new Insets(10, 10, 10, 10), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(panel1,
new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null,
null, null, 0, false));
final JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1, true, false));
panel1.add(panel2,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
buttonOK = new JButton();
buttonOK.setText("OK");
panel2.add(buttonOK, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
buttonCancel = new JButton();
buttonCancel.setText("Cancel");
panel2.add(buttonCancel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER,
GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(panel3,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null, 0, false));
panel3.add(tipoEgresoCombo, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST,
GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label1 = new JLabel();
label1.setText("Seleccione el Tipo de Egreso:");
panel3.add(label1,
new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
false));
}
if (this.isAcepted()) { /**
return this.getTipoEgreso(); * @noinspection ALL
} else { */
return null; public JComponent $$$getRootComponent$$$() {
} return contentPane;
} }
private void onOK() {
this.acepted = true;
dispose();
}
private void onCancel() {
this.acepted = false;
dispose();
}
public boolean isAcepted() {
return this.acepted;
}
public TipoEgreso getTipoEgreso() {
return (TipoEgreso) tipoEgresoCombo.getSelectedItem();
}
private void createUIComponents() {
createTipoEgresoCombo();
}
private void createTipoEgresoCombo() {
tipoEgresoCombo = new JComboBox<>();
for (TipoEgreso tipoEgreso : DAOManager.getTipoEgresoDAO().findAll()) {
tipoEgresoCombo.addItem(new TipoEgresoToStringWrapper(tipoEgreso));
}
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
contentPane = new JPanel();
contentPane.setLayout(new GridLayoutManager(2, 1, new Insets(10, 10, 10, 10), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(panel1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false));
final JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1, true, false));
panel1.add(panel2, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
buttonOK = new JButton();
buttonOK.setText("OK");
panel2.add(buttonOK, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
buttonCancel = new JButton();
buttonCancel.setText("Cancel");
panel2.add(buttonCancel, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(panel3, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
panel3.add(tipoEgresoCombo, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JLabel label1 = new JLabel();
label1.setText("Seleccione el Tipo de Egreso:");
panel3.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPane;
}
} }

View File

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

View File

@@ -4,10 +4,12 @@ import java.awt.event.FocusEvent;
import java.awt.event.FocusListener; import java.awt.event.FocusListener;
public interface FocusLostListener extends FocusListener { public interface FocusLostListener extends FocusListener {
@Override
default void focusGained(FocusEvent e){ }
@Override @Override
void focusLost(FocusEvent e); default void focusGained(FocusEvent e) {
}
@Override
void focusLost(FocusEvent e);
} }

View File

@@ -7,12 +7,24 @@ import java.awt.event.WindowListener;
* Simple wraper for WindowListener to simple use the windowClosing method in a lambda function * Simple wraper for WindowListener to simple use the windowClosing method in a lambda function
*/ */
public interface WindowClosingListener extends WindowListener { 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); 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);
} }