/* * MIT License * * Copyright (c) 2018-2019 Daniel Cortes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package danielcortes.xyz.controllers; import danielcortes.xyz.controllers.actions.NextAction; import danielcortes.xyz.models.caja.Caja; import danielcortes.xyz.models.documentos.Documentos; import danielcortes.xyz.models.documentos.DocumentosDAO; import danielcortes.xyz.models.efectivo.Efectivo; import danielcortes.xyz.models.efectivo.EfectivoDAO; import danielcortes.xyz.models.egreso.EgresoDAO; import danielcortes.xyz.models.ingreso.IngresoDAO; import danielcortes.xyz.views.ArqueoView; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; /** * Controlador destinado a la vista ArqueoView * Maneja su contenido y las acciones que esta realiza. */ public class ArqueoController { private ArqueoView view; private Caja caja; private Efectivo efectivo; private Documentos documentos; private EfectivoDAO efectivoDAO; private DocumentosDAO documentosDAO; private IngresoDAO ingresoDAO; private EgresoDAO egresoDAO; /** * Crea el controlador y ejecuta el metodo que genera los eventos para su vista. * */ public ArqueoController(ArqueoView view, EfectivoDAO efectivoDAO, DocumentosDAO documentosDAO, IngresoDAO ingresoDAO, EgresoDAO egresoDAO) { this.view = view; this.efectivoDAO = efectivoDAO; this.documentosDAO = documentosDAO; this.ingresoDAO = ingresoDAO; this.egresoDAO = egresoDAO; 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 = this.efectivoDAO.findByCaja(this.caja); this.view.getVeinteMilField().setText(String.valueOf(efectivo.getVeinteMil())); this.view.getDiezMilField().setText(String.valueOf(efectivo.getDiezMil())); this.view.getCincoMilField().setText(String.valueOf(efectivo.getCincoMil())); this.view.getDosMilField().setText(String.valueOf(efectivo.getDosMil())); this.view.getMilField().setText(String.valueOf(efectivo.getMil())); this.view.getQuinientosField().setText(String.valueOf(efectivo.getQuinientos())); this.view.getCienField().setText(String.valueOf(efectivo.getCien())); this.view.getCincuentaField().setText(String.valueOf(efectivo.getCincuenta())); this.view.getDiezField().setText(String.valueOf(efectivo.getDiez())); } /** * Rellea los campos de documentos con la instancia de documentos que pertenece a la caja */ private void fillDocumentos() { this.documentos = this.documentosDAO.findByCaja(caja); this.view.getTarjetasField().setText(String.valueOf(documentos.getTarjetas())); this.view.getChequesField().setText(String.valueOf(documentos.getCheques())); } /** * Llama a todos los metodos que llenan y calculan los campos de resumen */ private void fillResumen() { this.updateResumenEfectivo(); this.updateResumenDocumentos(); this.updateResumenIngresos(); this.updateResumenEgresos(); this.updateResumenArqueo(); } /** * Calcula el total de efectivo y lo muestra en el efectivoField */ private void updateResumenEfectivo() { JTextField efectivoField = this.view.getEfectivoField(); int total = 0; total += this.efectivo.getDiez(); total += this.efectivo.getCincuenta(); total += this.efectivo.getCien(); total += this.efectivo.getQuinientos(); total += this.efectivo.getMil(); total += this.efectivo.getDosMil(); total += this.efectivo.getCincoMil(); total += this.efectivo.getDiezMil(); total += this.efectivo.getVeinteMil(); efectivoField.setText(String.valueOf(total)); } /** * Calcula el total de documentos y lo muestra en el documentosField */ private void updateResumenDocumentos() { JTextField documentosField = this.view.getDocumentosField(); int total = 0; total += this.documentos.getCheques(); total += this.documentos.getTarjetas(); documentosField.setText(String.valueOf(total)); } /** * Obtiene el total de ingresos para la caja y lo muestra en el campo ingresosField */ private void updateResumenIngresos() { int total = this.ingresoDAO.getTotalIngreso(this.caja); this.view.getIngresosField().setText(String.valueOf(total)); } /** * Obtiene el total de egresos y lo muestra en el campo de egresosField */ private void updateResumenEgresos() { int total = this.egresoDAO.getTotalEgreso(this.caja); this.view.getEgresosField().setText(String.valueOf(total)); } /** * Calcula los datos de arqueo, rendido y ajuste y los muestra en sus campos correspondientes */ private void updateResumenArqueo() { int totalEfectivo = Integer.parseInt(this.view.getEfectivoField().getText()); int totalDocumentos = Integer.parseInt(this.view.getDocumentosField().getText()); int totalIngresos = Integer.parseInt(this.view.getIngresosField().getText()); int totalEgresos = Integer.parseInt(this.view.getEgresosField().getText()); int rendido = totalDocumentos + totalEfectivo + totalEgresos; int diferencia = rendido - totalIngresos; this.view.getRendidoField().setText(String.valueOf(rendido)); this.view.getDebeRendirField().setText(String.valueOf(totalIngresos)); this.view.getDiferenciaField().setText(String.valueOf(diferencia)); if(diferencia < 0) { this.view.getDiferenciaField().setForeground(new Color(255,0,0)); }else{ this.view.getDiferenciaField().setForeground(new Color(0,0,0)); } } /** * Setea los eventos de los fields de la vista */ private void setUpViewEvents() { this.view.getVeinteMilField().getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("ENTER"),"nextField"); this.view.getDiezMilField().getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("ENTER"),"nextField"); this.view.getCincoMilField().getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("ENTER"),"nextField"); this.view.getDosMilField().getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("ENTER"),"nextField"); this.view.getMilField().getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("ENTER"),"nextField"); this.view.getQuinientosField().getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("ENTER"),"nextField"); this.view.getCienField().getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("ENTER"),"nextField"); this.view.getCincuentaField().getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("ENTER"),"nextField"); this.view.getDiezField().getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("ENTER"),"save"); this.view.getVeinteMilField().getActionMap().put("nextField", new NextAction(this.view.getDiezMilField())); this.view.getDiezMilField().getActionMap().put("nextField", new NextAction(this.view.getCincoMilField())); this.view.getCincoMilField().getActionMap().put("nextField", new NextAction(this.view.getDosMilField())); this.view.getDosMilField().getActionMap().put("nextField", new NextAction(this.view.getMilField())); this.view.getMilField().getActionMap().put("nextField", new NextAction(this.view.getQuinientosField())); this.view.getQuinientosField().getActionMap().put("nextField", new NextAction(this.view.getCienField())); this.view.getCienField().getActionMap().put("nextField", new NextAction(this.view.getCincuentaField())); this.view.getCincuentaField().getActionMap().put("nextField", new NextAction(this.view.getDiezField())); this.view.getDiezField().getActionMap().put("save", new GuardarEfectivoAction(this)); this.view.getChequesField().getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("ENTER"),"nextField"); this.view.getTarjetasField().getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("ENTER"),"save"); this.view.getChequesField().getActionMap().put("nextField", new NextAction(this.view.getTarjetasField())); this.view.getTarjetasField().getActionMap().put("save", new GuardarDocumentosAction(this)); this.view.getGuardarEfectivoButton().addActionListener(e -> guardarEfectivoActionListener()); this.view.getGuardarDocumentosButton().addActionListener(e -> guardarDocumentosActionListener()); } /** * 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.normalizeEfectivoInput(); this.hiddeEfectivoErrorMessages(); 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.normalizeDocumentosInput(); this.hiddeDocumentosErrorMessages(); this.guardarDocumentos(); } /** * 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() { String diez = this.view.getDiezField().getText(); String cincuenta = this.view.getCincuentaField().getText(); String cien = this.view.getCienField().getText(); String quinientos = this.view.getQuinientosField().getText(); String mil = this.view.getMilField().getText(); String dosMil = this.view.getDosMilField().getText(); String cincoMil = this.view.getCincoMilField().getText(); String diezMil = this.view.getDiezMilField().getText(); String veinteMil = this.view.getVeinteMilField().getText(); if (this.validateEfectivoInput(diez, cincuenta, cien, quinientos, mil, dosMil, cincoMil, diezMil, veinteMil)) { this.efectivo.setDiez(Integer.valueOf(diez)); this.efectivo.setCincuenta(Integer.valueOf(cincuenta)); this.efectivo.setCien(Integer.valueOf(cien)); this.efectivo.setQuinientos(Integer.valueOf(quinientos)); this.efectivo.setMil(Integer.valueOf(mil)); this.efectivo.setDosMil(Integer.valueOf(dosMil)); this.efectivo.setCincoMil(Integer.valueOf(cincoMil)); this.efectivo.setDiezMil(Integer.valueOf(diezMil)); this.efectivo.setVeinteMil(Integer.valueOf(veinteMil)); this.efectivoDAO.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() { String tarjetas = this.view.getTarjetasField().getText(); String cheques = this.view.getChequesField().getText(); if (this.validateDocumentosInput(tarjetas, cheques)) { this.documentos.setTarjetas(Integer.valueOf(tarjetas)); this.documentos.setCheques(Integer.valueOf(cheques)); this.documentosDAO.updateDocumentos(documentos); this.updateResumenDocumentos(); this.updateResumenArqueo(); } } /** * Llama a las validaciones necesarias para el input de Efectivo * @return si es que paso todas las validaciones. */ private boolean validateEfectivoInput(String diez, String cincuenta, String cien, String quinientos, String mil, String dosMil, String cincoMil, String diezMil, String veinteMil) { boolean diezValidation = validateEfectivoMoneda(diez, this.view.getErrorDiez()); boolean cincuentaValidation = validateEfectivoMoneda(cincuenta, this.view.getErrorCincuenta()); boolean cienValidation = validateEfectivoMoneda(cien, this.view.getErrorCien()); boolean quinientosValidation = validateEfectivoMoneda(quinientos, this.view.getErrorQuinientos()); boolean milValidation = validateEfectivoMoneda(mil, this.view.getErrorMil()); boolean dosMilValidation = validateEfectivoMoneda(dosMil, this.view.getErrorDosMil()); boolean cincoMilValidation = validateEfectivoMoneda(cincoMil, this.view.getErrorCincoMil()); boolean diezMilValidation = validateEfectivoMoneda(diezMil, this.view.getErrorDiezMil()); boolean veinteMilValidation = validateEfectivoMoneda(veinteMil, this.view.getErrorVeinteMil()); return diezValidation && cincuentaValidation && cienValidation && quinientosValidation && milValidation && dosMilValidation && cincoMilValidation && diezMilValidation && veinteMilValidation; } /** * Llama a las validaciones necesarias el input de Documentos * @return si es que todas las validaciones fueron correctas */ private boolean validateDocumentosInput(String tarjetas, String cheques) { boolean tarjetasValidation = validateDocumentosValor(tarjetas, this.view.getErrorTarjetas()); boolean chequesValidation = validateDocumentosValor(cheques, this.view.getErrorCheques()); return tarjetasValidation && chequesValidation; } /** * Valida el valor entregado contra las siguientes pruebas * - Es null * - Esta vacio * - Los caracteres no son solamente digitos * - El largo es mayor que diez * Setea un mensaje de error correspondiente en el errorLabel entregado. * @return cuando cualquiera de los casos anteriores sea true se retorna falso, si no retorna true. */ private boolean validateEfectivoMoneda(String valor, JLabel errorLabel) { if (valor == null) { errorLabel.setText("Hubo un problema con los datos"); errorLabel.setVisible(true); return false; } if (valor.isEmpty()) { errorLabel.setText("El campo esta vacio"); errorLabel.setVisible(true); return false; } if (!valor.chars().allMatch(Character::isDigit)) { errorLabel.setText("Deben ser numeros"); errorLabel.setVisible(true); return false; } if (valor.length() > 10) { errorLabel.setText("El numero ingresado es demasiado largo"); errorLabel.setVisible(true); return false; } return true; } /** * Valida el valor entregado contra las siguientes pruebas * - Es null * - Esta vacio * - Los caracteres no son solamente digitos * - El largo es mayor que diez * Setea un mensaje de error correspondiente en el errorLabel entregado. * @return cuando cualquiera de los casos anteriores sea true se retorna falso, si no retorna true. */ private boolean validateDocumentosValor(String valor, JLabel errorLabel) { if (valor == null) { errorLabel.setText("Hubo un problema con los datos"); errorLabel.setVisible(true); return false; } if (valor.isEmpty()) { errorLabel.setText("El campo esta vacio"); errorLabel.setVisible(true); return false; } if (!valor.chars().allMatch(Character::isDigit)) { errorLabel.setText("Deben ser numeros"); errorLabel.setVisible(true); return false; } if (valor.length() > 10) { errorLabel.setText("El numero ingresado es demasiado largo"); errorLabel.setVisible(true); return false; } return true; } /** * Esconde los mensajes de error de los campos de efectivo */ private void hiddeEfectivoErrorMessages() { this.view.getErrorDiez().setVisible(false); this.view.getErrorCincuenta().setVisible(false); this.view.getErrorCien().setVisible(false); this.view.getErrorQuinientos().setVisible(false); this.view.getErrorMil().setVisible(false); this.view.getErrorDosMil().setVisible(false); this.view.getErrorCincoMil().setVisible(false); this.view.getErrorDiezMil().setVisible(false); this.view.getErrorVeinteMil().setVisible(false); } /** * Esconde los mensajes de error en los campos de documentos */ private void hiddeDocumentosErrorMessages(){ this.view.getErrorTarjetas().setVisible(false); this.view.getErrorCheques().setVisible(false); } /** * Ejecuta trim sobre todos los campos de efectivo */ private void normalizeEfectivoInput() { this.view.getDiezField().setText(this.view.getDiezField().getText().trim()); this.view.getCincuentaField().setText(this.view.getCincuentaField().getText().trim()); this.view.getCienField().setText(this.view.getCienField().getText().trim()); this.view.getQuinientosField().setText(this.view.getQuinientosField().getText().trim()); this.view.getMilField().setText(this.view.getMilField().getText().trim()); this.view.getDosMilField().setText(this.view.getDosMilField().getText().trim()); this.view.getCincoMilField().setText(this.view.getCincoMilField().getText().trim()); this.view.getDiezMilField().setText(this.view.getDiezMilField().getText().trim()); this.view.getVeinteMilField().setText(this.view.getVeinteMilField().getText().trim()); } /** * Ejecuta trim sobre todos los campos de documentos */ private void normalizeDocumentosInput() { this.view.getChequesField().setText(this.view.getChequesField().getText().trim()); this.view.getTarjetasField().setText(this.view.getTarjetasField().getText().trim()); } private class GuardarEfectivoAction extends AbstractAction{ ArqueoController controller; GuardarEfectivoAction(ArqueoController controller){ this.controller = controller; } @Override public void actionPerformed(ActionEvent e) { this.controller.guardarEfectivoActionListener(); } } private class GuardarDocumentosAction extends AbstractAction{ ArqueoController controller; GuardarDocumentosAction(ArqueoController controller){ this.controller = controller; } @Override public void actionPerformed(ActionEvent e) { this.controller.guardarDocumentosActionListener(); } } }