diff --git a/dist/Programa Caja.jar b/dist/Programa Caja.jar index 60ce547..aaff2b2 100644 Binary files a/dist/Programa Caja.jar and b/dist/Programa Caja.jar differ diff --git a/src/danielcortes/xyz/controllers/InformesSideBarController.java b/src/danielcortes/xyz/controllers/InformesSideBarController.java index 9112164..a02d14e 100644 --- a/src/danielcortes/xyz/controllers/InformesSideBarController.java +++ b/src/danielcortes/xyz/controllers/InformesSideBarController.java @@ -26,8 +26,9 @@ package danielcortes.xyz.controllers; import danielcortes.xyz.data.Configuration; import danielcortes.xyz.informes.InformeEgresos; -import danielcortes.xyz.informes.InformeLibroDeVentas; +import danielcortes.xyz.informes.InformeLibroDeVentasToExcel; import danielcortes.xyz.models.tipo_egreso.TipoEgreso; +import danielcortes.xyz.utils.SaveFile; import danielcortes.xyz.utils.StringUtils; import danielcortes.xyz.views.InformesSideBar; import danielcortes.xyz.views.dialogs.InformeGeneratedConfirmation; @@ -37,6 +38,7 @@ import danielcortes.xyz.views.dialogs.XLSFileChooser; import java.nio.file.Path; import java.time.YearMonth; import java.time.format.DateTimeFormatter; +import org.apache.poi.ss.usermodel.Workbook; public class InformesSideBarController { @@ -75,8 +77,10 @@ public class InformesSideBarController { return; } - InformeLibroDeVentas informe = new InformeLibroDeVentas(month, saveFile); - informe.generarInforme(); + InformeLibroDeVentasToExcel informe = new InformeLibroDeVentasToExcel(month, saveFile); + Workbook wb = informe.generarInforme(); + + SaveFile.save(wb, saveFile); new InformeGeneratedConfirmation(saveFile).execute(); } diff --git a/src/danielcortes/xyz/data/DAOManager.java b/src/danielcortes/xyz/data/DAOManager.java index 606fc89..693424f 100644 --- a/src/danielcortes/xyz/data/DAOManager.java +++ b/src/danielcortes/xyz/data/DAOManager.java @@ -38,8 +38,6 @@ import danielcortes.xyz.models.estado_resultado.EstadoResultadoDAO; import danielcortes.xyz.models.estado_resultado.SQLiteEstadoResultadoDAO; import danielcortes.xyz.models.informes.egresos.InformeEgresosContentDAO; import danielcortes.xyz.models.informes.egresos.SQLiteInformeEgresosContentDAO; -import danielcortes.xyz.models.informes.libro_de_ventas.InformeLibroDeVentasContentDAO; -import danielcortes.xyz.models.informes.libro_de_ventas.SQLiteInformeLibroDeVentasContentDAO; import danielcortes.xyz.models.ingreso.IngresoDAO; import danielcortes.xyz.models.ingreso.SQLiteIngresoDAO; import danielcortes.xyz.models.tipo_egreso.SQLiteTipoEgresoDAO; @@ -57,7 +55,6 @@ public class DAOManager { 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; @@ -71,7 +68,6 @@ public class DAOManager { efectivoDAO = new SQLiteEfectivoDAO(); egresoDAO = new SQLiteEgresoDAO(); egresosContentDAO = new SQLiteInformeEgresosContentDAO(); - libroDeVentasContentDAO = new SQLiteInformeLibroDeVentasContentDAO(); ingresoDAO = new SQLiteIngresoDAO(); tipoEgresoDAO = new SQLiteTipoEgresoDAO(); tipoIngresoDAO = new SQLiteTipoIngresoDAO(); @@ -103,10 +99,6 @@ public class DAOManager { return egresosContentDAO; } - public static InformeLibroDeVentasContentDAO getLibroDeVentasContentDAO() { - return libroDeVentasContentDAO; - } - public static IngresoDAO getIngresoDAO() { return ingresoDAO; } diff --git a/src/danielcortes/xyz/informes/InformeLibroDeVentas.java b/src/danielcortes/xyz/informes/InformeLibroDeVentas.java index 6d119f8..0dbf16d 100644 --- a/src/danielcortes/xyz/informes/InformeLibroDeVentas.java +++ b/src/danielcortes/xyz/informes/InformeLibroDeVentas.java @@ -1,396 +1,90 @@ -/* - * 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.informes; import danielcortes.xyz.data.DAOManager; -import danielcortes.xyz.models.caja.SQLiteCajaDAO; -import danielcortes.xyz.models.informes.libro_de_ventas.InformeLibroDeVentasContent; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.Path; +import danielcortes.xyz.models.caja.Caja; +import danielcortes.xyz.models.caja.CajaDAO; +import danielcortes.xyz.models.ingreso.IngresoDAO; +import danielcortes.xyz.models.tipo_ingreso.TipoIngreso; +import danielcortes.xyz.models.tipo_ingreso.TipoIngresoDAO; +import java.time.LocalDate; import java.time.YearMonth; -import java.time.ZoneId; -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{ + HashMap informe; + private InformeLibroDeVentas(){} - private final String[] titles = { - "", "", - "BOLETA MANUAL", "", "", - "BOLETA FISCAL", "", "", "", "", - "BOLETAS EXENTAS", "", "", - "SUB", - "FACTURA", "", "", - "GUIAS", "", "", - "ESTADISTICAS" - }; - - 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 final String[] dias = {"Domingo", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", - "Sabado"}; - - private ArrayList informe; - private Path saveFile; - - private ArrayList dataRows; - private Row footerRow; - private ArrayList headerRows; - - private Workbook wb; - private Sheet sheet; - private CreationHelper createHelper; - private HashMap styles; - - public InformeLibroDeVentas(YearMonth mes, Path saveFile) { - new SQLiteCajaDAO().createCajasForMonth(mes); - - this.informe = new ArrayList<>(DAOManager.getLibroDeVentasContentDAO().getInformeMensual(mes)); - this.saveFile = saveFile; - - this.dataRows = new ArrayList<>(); - this.headerRows = new ArrayList<>(); - - this.wb = new HSSFWorkbook(); - this.sheet = wb.createSheet(); - this.createHelper = wb.getCreationHelper(); - - this.styles = this.generateStyles(); + public LibroDeVentas get(LocalDate localDate){ + return informe.get(localDate); } - private void sortInforme() { - this.informe.sort(Comparator.comparing(InformeLibroDeVentasContent::getFecha)); + public int size(){ + return informe.size(); } - private void fillHeaders() { - Row titles = sheet.createRow(0); - Row subtitles = sheet.createRow(1); + private void put(LocalDate date, LibroDeVentas libroDeVentas){ + this.informe.put(date, libroDeVentas); + } - headerRows.add(titles); - headerRows.add(subtitles); - for (int x = 0; x < this.titles.length; x++) { - titles.createCell(x).setCellValue(this.titles[x]); + public static InformeLibroDeVentas generate(YearMonth mes) { + InformeLibroDeVentas informeLibroDeVentas = new InformeLibroDeVentas(); + informeLibroDeVentas.informe = new HashMap<>(); + + LocalDate currentDate = mes.atDay(1); + LocalDate endDatePlusOne = mes.atEndOfMonth().plusDays(1); + + CajaDAO cajaDAO = DAOManager.getCajaDAO(); + IngresoDAO ingresoDAO = DAOManager.getIngresoDAO(); + TipoIngresoDAO tipoIngresoDAO = DAOManager.getTipoIngresoDAO(); + + TipoIngreso boletaFiscal = tipoIngresoDAO.findByNombre("Boletas Fiscales").get(0); + TipoIngreso boletaManual = tipoIngresoDAO.findByNombre("Boletas Manuales").get(0); + TipoIngreso boletaExenta = tipoIngresoDAO.findByNombre("Boleta Exenta").get(0); + TipoIngreso factura = tipoIngresoDAO.findByNombre("Facturas").get(0); + TipoIngreso guias = tipoIngresoDAO.findByNombre("Guias").get(0); + + while (currentDate.isBefore(endDatePlusOne)) { + Caja caja = cajaDAO.getByFecha(currentDate).orElse(Caja.EMPTY); + + LibroDeVentas data = new LibroDeVentas(); + informeLibroDeVentas.put(currentDate, data); + + data.setDia(currentDate.getDayOfWeek().getValue()); + data.setFecha(currentDate); + + data.setManuales(ingresoDAO.getTotalIngresoEnCajaPorTipo(caja, boletaManual)); + data.setManualesInicial( + ingresoDAO.getPrimerNroInicialDeCajaDeTipo(caja, boletaManual).orElse("0")); + data.setManualesFinal( + ingresoDAO.getUltimoNroFinalDeCajaDeTipo(caja, boletaManual).orElse("0")); + + data.setFiscales(ingresoDAO.getTotalIngresoEnCajaPorTipo(caja, boletaFiscal)); + data.setFiscalesInicial( + ingresoDAO.getPrimerNroInicialDeCajaDeTipo(caja, boletaFiscal).orElse("0")); + data.setFiscalesFinal( + ingresoDAO.getUltimoNroFinalDeCajaDeTipo(caja, boletaFiscal).orElse("0")); + data.setFiscalesZInicial(ingresoDAO.getPrimerNroZInicialDeCaja(caja).orElse("0")); + data.setFiscalesZFinal(ingresoDAO.getUltimoNroZFinalDeCaja(caja).orElse("0")); + + data.setExentas(ingresoDAO.getTotalIngresoEnCajaPorTipo(caja, boletaExenta)); + data.setExentasInicial( + ingresoDAO.getPrimerNroInicialDeCajaDeTipo(caja, boletaExenta).orElse("0")); + data.setExentasFinal( + ingresoDAO.getUltimoNroFinalDeCajaDeTipo(caja, boletaExenta).orElse("0")); + + data.setFacturas(ingresoDAO.getTotalIngresoEnCajaPorTipo(caja, factura)); + data.setFacturasInicial( + ingresoDAO.getPrimerNroInicialDeCajaDeTipo(caja, factura).orElse("0")); + data.setFacturasFinal(ingresoDAO.getUltimoNroFinalDeCajaDeTipo(caja, factura).orElse("0")); + + data.setGuias(ingresoDAO.getTotalIngresoEnCajaPorTipo(caja, guias)); + data.setGuiasInicial(ingresoDAO.getPrimerNroInicialDeCajaDeTipo(caja, guias).orElse("0")); + data.setGuiasFinal(ingresoDAO.getUltimoNroFinalDeCajaDeTipo(caja, guias).orElse("0")); + + currentDate = currentDate.plusDays(1); } - for (int x = 0; x < this.subtitles.length; x++) { - 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 cellIterator = header.cellIterator(); - while (cellIterator.hasNext()) { - Cell cell = cellIterator.next(); - cell.setCellStyle(this.styles.get("header")); - } - } - - //Estilos para las celdas de los datos - for (Row row : dataRows) { - int y = 0; - - //Primeras Celdas - 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 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 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; + return informeLibroDeVentas; } } diff --git a/src/danielcortes/xyz/informes/InformeLibroDeVentasToExcel.java b/src/danielcortes/xyz/informes/InformeLibroDeVentasToExcel.java new file mode 100644 index 0000000..45a2a1c --- /dev/null +++ b/src/danielcortes/xyz/informes/InformeLibroDeVentasToExcel.java @@ -0,0 +1,387 @@ +/* + * 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.informes; + +import java.nio.file.Path; +import java.time.LocalDate; +import java.time.YearMonth; +import java.time.ZoneId; +import java.util.ArrayList; +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 InformeLibroDeVentasToExcel { + + private final String[] titles = { + "", "", + "BOLETA MANUAL", "", "", + "BOLETA FISCAL", "", "", "", "", + "BOLETAS EXENTAS", "", "", + "SUB", + "FACTURA", "", "", + "GUIAS", "", "", + "ESTADISTICAS" + }; + + 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 final String[] dias = {"Lunes", "Martes", "Miercoles", "Jueves", "Viernes", + "Sabado", "Domingo"}; + + private YearMonth mes; + + private InformeLibroDeVentas informe; + + private ArrayList dataRows; + private Row footerRow; + private ArrayList headerRows; + + private Workbook wb; + private Sheet sheet; + private CreationHelper createHelper; + private HashMap styles; + + public InformeLibroDeVentasToExcel(YearMonth mes, Path saveFile) { + this.mes = mes; + this.informe = InformeLibroDeVentas.generate(mes); + + this.dataRows = new ArrayList<>(); + this.headerRows = new ArrayList<>(); + + this.wb = new HSSFWorkbook(); + this.sheet = wb.createSheet(); + this.createHelper = wb.getCreationHelper(); + + this.styles = this.generateStyles(); + } + + 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]); + } + + for (int x = 0; x < this.subtitles.length; x++) { + subtitles.createCell(x).setCellValue(this.subtitles[x]); + } + } + + private void fillData() { + int rowCounter = 2; + + LocalDate currentDate = this.mes.atDay(1); + LocalDate endDatePlusOne = this.mes.atEndOfMonth().plusDays(1); + + while (currentDate.isBefore(endDatePlusOne)) { + LibroDeVentas data = this.informe.get(currentDate); + Row dataRow = sheet.createRow(rowCounter); + dataRows.add(dataRow); + Date fecha = Date.from(data.getFecha().atStartOfDay(ZoneId.systemDefault()).toInstant()); + + int cellCounter = 0; + dataRow.createCell(cellCounter++).setCellValue(this.dias[data.getDia() - 1]); + 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++).setCellFormula( + "E" + (rowCounter + 1) + "+J" + (rowCounter + 1) + "+M" + (rowCounter + 1)); + + 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++; + currentDate = currentDate.plusDays(1); + } + } + + 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 cellIterator = header.cellIterator(); + while (cellIterator.hasNext()) { + Cell cell = cellIterator.next(); + cell.setCellStyle(this.styles.get("header")); + } + } + + //Estilos para las celdas de los datos + for (Row row : dataRows) { + int y = 0; + + //Primeras Celdas + 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 Workbook generarInforme() { + fillData(); + fillHeaders(); + fillTotales(); + joinCells(); + freezeCells(); + setStyles(); + addBorders(); + + return wb; + } + + + private HashMap 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 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; + } +} diff --git a/src/danielcortes/xyz/models/informes/libro_de_ventas/InformeLibroDeVentasContent.java b/src/danielcortes/xyz/informes/LibroDeVentas.java similarity index 95% rename from src/danielcortes/xyz/models/informes/libro_de_ventas/InformeLibroDeVentasContent.java rename to src/danielcortes/xyz/informes/LibroDeVentas.java index 46be3ca..33662fa 100644 --- a/src/danielcortes/xyz/models/informes/libro_de_ventas/InformeLibroDeVentasContent.java +++ b/src/danielcortes/xyz/informes/LibroDeVentas.java @@ -46,11 +46,11 @@ * SOFTWARE. */ -package danielcortes.xyz.models.informes.libro_de_ventas; +package danielcortes.xyz.informes; import java.time.LocalDate; -public class InformeLibroDeVentasContent { +public class LibroDeVentas { private int dia; private LocalDate fecha; @@ -65,7 +65,6 @@ public class InformeLibroDeVentasContent { private String exentasInicial; private String exentasFinal; private int exentas; - private int subTotal; private String facturasInicial; private String facturasFinal; private int facturas; @@ -99,7 +98,6 @@ public class InformeLibroDeVentasContent { } public String getManualesFinal() { - return manualesFinal; } @@ -179,14 +177,6 @@ public class InformeLibroDeVentasContent { this.exentas = exentas; } - public int getSubTotal() { - return subTotal; - } - - public void setSubTotal(int sub_total) { - this.subTotal = sub_total; - } - public String getFacturasInicial() { return facturasInicial; } @@ -243,10 +233,9 @@ public class InformeLibroDeVentasContent { this.total = total; } - @Override public String toString() { - return "InformeLibroDeVentasContent{" + + return "LibroDeVentas{" + "dia=" + dia + ", fecha=" + fecha + ", manualesInicial='" + manualesInicial + '\'' + @@ -260,7 +249,6 @@ public class InformeLibroDeVentasContent { ", exentasInicial='" + exentasInicial + '\'' + ", exentasFinal='" + exentasFinal + '\'' + ", exentas=" + exentas + - ", subTotal=" + subTotal + ", facturasInicial='" + facturasInicial + '\'' + ", facturasFinal='" + facturasFinal + '\'' + ", facturas=" + facturas + diff --git a/src/danielcortes/xyz/models/caja/Caja.java b/src/danielcortes/xyz/models/caja/Caja.java index 5152efa..ebb0543 100644 --- a/src/danielcortes/xyz/models/caja/Caja.java +++ b/src/danielcortes/xyz/models/caja/Caja.java @@ -27,11 +27,16 @@ package danielcortes.xyz.models.caja; import java.time.LocalDate; public class Caja { + public final static Caja EMPTY = new Caja(); private int id; private LocalDate fecha; private int fondo; + public Caja(){ + + } + public int getId() { return id; } diff --git a/src/danielcortes/xyz/models/informes/libro_de_ventas/InformeLibroDeVentasContentDAO.java b/src/danielcortes/xyz/models/informes/libro_de_ventas/InformeLibroDeVentasContentDAO.java deleted file mode 100644 index 05cf75f..0000000 --- a/src/danielcortes/xyz/models/informes/libro_de_ventas/InformeLibroDeVentasContentDAO.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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.models.informes.libro_de_ventas; - -import danielcortes.xyz.data.ConnectionHolder; -import java.time.YearMonth; -import java.util.Collection; - -public abstract class InformeLibroDeVentasContentDAO { - - protected ConnectionHolder connectionHolder; - - /** - * Genera el contenido del informes mensual - * - * @param mes el que se necesita el informes - * @return Lista con las columnas principales necesarias para el informes - */ - public abstract Collection getInformeMensual(YearMonth mes); -} diff --git a/src/danielcortes/xyz/models/informes/libro_de_ventas/SQLiteInformeLibroDeVentasContentDAO.java b/src/danielcortes/xyz/models/informes/libro_de_ventas/SQLiteInformeLibroDeVentasContentDAO.java deleted file mode 100644 index a3ff9a9..0000000 --- a/src/danielcortes/xyz/models/informes/libro_de_ventas/SQLiteInformeLibroDeVentasContentDAO.java +++ /dev/null @@ -1,288 +0,0 @@ -/* - * 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. - */ - -/* - * 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.models.informes.libro_de_ventas; - -import danielcortes.xyz.data.SQLiteConnectionHolder; -import danielcortes.xyz.utils.NaturalOrderComparator; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.time.LocalDate; -import java.time.YearMonth; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashMap; -import java.util.logging.Level; -import java.util.logging.Logger; - -public class SQLiteInformeLibroDeVentasContentDAO extends InformeLibroDeVentasContentDAO { - - private static final Logger LOGGER = Logger - .getLogger(SQLiteInformeLibroDeVentasContentDAO.class.getName()); - - private HashMap map; - - public SQLiteInformeLibroDeVentasContentDAO() { - this.connectionHolder = new SQLiteConnectionHolder(); - } - - @Override - public Collection 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); - } - - return map.values(); - } - - private void fillTotalesFromResultSet(ResultSet rs) throws SQLException { - while (rs.next()) { - InformeLibroDeVentasContent informe = new InformeLibroDeVentasContent(); - informe.setDia(rs.getInt("dia")); - informe.setFecha(LocalDate.parse(rs.getString("fecha"))); - informe.setManuales(rs.getInt("manuales")); - informe.setFiscales(rs.getInt("fiscales")); - informe.setExentas(rs.getInt("exentas")); - informe.setSubTotal(rs.getInt("sub_total")); - informe.setFacturas(rs.getInt("facturas")); - informe.setGuias(rs.getInt("guias")); - 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 { - Comparator comparator = new NaturalOrderComparator(); - while (rs.next()) { - 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); - } - } -} diff --git a/src/danielcortes/xyz/models/ingreso/IngresoDAO.java b/src/danielcortes/xyz/models/ingreso/IngresoDAO.java index 49aeab2..01afe90 100644 --- a/src/danielcortes/xyz/models/ingreso/IngresoDAO.java +++ b/src/danielcortes/xyz/models/ingreso/IngresoDAO.java @@ -37,6 +37,7 @@ import java.sql.SQLException; import java.time.YearMonth; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; @@ -66,6 +67,15 @@ public abstract class IngresoDAO { public abstract int getTotalExentasMes(YearMonth mes); + public abstract int getTotalIngresoEnCajaPorTipo(Caja caja, TipoIngreso tipoIngreso); + + public abstract Optional getPrimerNroInicialDeCajaDeTipo(Caja caja, TipoIngreso tipoIngreso); + + public abstract Optional getUltimoNroFinalDeCajaDeTipo(Caja caja, TipoIngreso tipoIngreso); + + public abstract Optional getPrimerNroZInicialDeCaja(Caja caja); + + public abstract Optional getUltimoNroZFinalDeCaja(Caja caja); List ingresosFromResultSet(ResultSet rs) throws SQLException { ArrayList ingresosList = new ArrayList<>(); diff --git a/src/danielcortes/xyz/models/ingreso/SQLiteIngresoDAO.java b/src/danielcortes/xyz/models/ingreso/SQLiteIngresoDAO.java index 39e032f..5546e30 100644 --- a/src/danielcortes/xyz/models/ingreso/SQLiteIngresoDAO.java +++ b/src/danielcortes/xyz/models/ingreso/SQLiteIngresoDAO.java @@ -35,6 +35,7 @@ import java.time.LocalDate; import java.time.YearMonth; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; @@ -49,38 +50,34 @@ public class SQLiteIngresoDAO extends IngresoDAO { @Override public List findAll() { List ingresosList = new ArrayList<>(); + String query = "select * from ingresos"; + 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(); + try (PreparedStatement ps = conn.prepareStatement(query)) { + try (ResultSet rs = ps.executeQuery()) { + LOGGER.log(Level.FINE, "QUERY: {0}", query); + ingresosList = this.ingresosFromResultSet(rs); + } + } } catch (SQLException e) { LOGGER.log(Level.SEVERE, e.toString(), e); } + return ingresosList; } @Override public List findByCaja(Caja caja) { List ingresosList = new ArrayList<>(); + String query = "select * from ingresos where caja_id = ?"; try (Connection conn = connectionHolder.getConnection()) { - String query = "select * from ingresos 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()}); - - ingresosList = this.ingresosFromResultSet(rs); - - rs.close(); - ps.close(); + try (PreparedStatement ps = conn.prepareStatement(query)) { + ps.setInt(1, caja.getId()); + try (ResultSet rs = ps.executeQuery()) { + LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, caja.getId()}); + ingresosList = this.ingresosFromResultSet(rs); + } + } } catch (SQLException e) { e.printStackTrace(); } @@ -90,18 +87,16 @@ public class SQLiteIngresoDAO extends IngresoDAO { @Override public List findById(int id) { List ingresosList = new ArrayList<>(); + String query = "select * from ingresos where id = ?"; try (Connection conn = connectionHolder.getConnection()) { - String query = "select * from ingresos where id = ?"; - PreparedStatement ps = conn.prepareStatement(query); - ps.setInt(1, id); - ResultSet rs = ps.executeQuery(); + try (PreparedStatement ps = conn.prepareStatement(query)) { + ps.setInt(1, id); + try (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, id}); - - ingresosList = this.ingresosFromResultSet(rs); - - rs.close(); - ps.close(); + ingresosList = this.ingresosFromResultSet(rs); + } + } } catch (SQLException e) { LOGGER.log(Level.SEVERE, e.toString(), e); } @@ -111,18 +106,16 @@ public class SQLiteIngresoDAO extends IngresoDAO { @Override public List findByTipoIngreso(TipoIngreso tipoIngreso) { List ingresosList = new ArrayList<>(); + String query = "select ingresos.* from ingresos inner join tipos_ingreso on (ingresos.tipo_ingreso_id = tipos_ingreso.id) where ingresos.tipo_ingreso_id = ?"; 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 = ?"; - PreparedStatement ps = conn.prepareStatement(query); - ps.setInt(1, tipoIngreso.getId()); - ResultSet rs = ps.executeQuery(); - - LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", new Object[]{query, tipoIngreso.getId()}); - - ingresosList = this.ingresosFromResultSet(rs); - - rs.close(); - ps.close(); + try (PreparedStatement ps = conn.prepareStatement(query)) { + ps.setInt(1, tipoIngreso.getId()); + try (ResultSet rs = ps.executeQuery()) { + LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}", + new Object[]{query, tipoIngreso.getId()}); + ingresosList = this.ingresosFromResultSet(rs); + } + } } catch (SQLException e) { LOGGER.log(Level.SEVERE, e.toString(), e); } @@ -132,31 +125,31 @@ public class SQLiteIngresoDAO extends IngresoDAO { @Override public boolean insertIngreso(Ingreso ingreso) { int updates; + String query = "insert into ingresos (valor, nro_z_inicial, nro_z_final, nro_inicial, nro_final, tipo_ingreso_id, caja_id) values (?,?,?,?,?,?,?)"; 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 (?,?,?,?,?,?,?)"; - PreparedStatement ps = conn.prepareStatement(query); - ps.setInt(1, ingreso.getValor()); - 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(); + try (PreparedStatement ps = conn.prepareStatement(query)) { + ps.setInt(1, ingreso.getValor()); + 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},{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}] | updates: {8}", + new Object[]{query, ingreso.getValor(), ingreso.getNroZInicial(), + ingreso.getNroZFinal(), + ingreso.getNroInicial(), ingreso.getNroFinal(), ingreso.getTipoIngreso().getId(), + ingreso.getCaja().getId(), updates}); + } - ps.close(); - - ps = conn.prepareStatement("select last_insert_rowid()"); - ResultSet rs = ps.executeQuery(); - rs.next(); - ingreso.setId(rs.getInt(1)); - - rs.close(); + try (PreparedStatement ps = conn.prepareStatement("select last_insert_rowid()")) { + try (ResultSet rs = ps.executeQuery()) { + rs.next(); + ingreso.setId(rs.getInt(1)); + } + } } catch (SQLException e) { LOGGER.log(Level.SEVERE, e.toString(), e); return false; @@ -167,27 +160,27 @@ public class SQLiteIngresoDAO extends IngresoDAO { @Override public boolean updateIngreso(Ingreso ingreso) { int updates; + String query = "update ingresos set valor = ?, nro_z_inicial = ?, nro_z_final = ?, nro_inicial = ?, nro_final = ?, tipo_ingreso_id = ?, caja_id = ? where id = ?"; 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 = ?"; - PreparedStatement ps = conn.prepareStatement(query); - ps.setInt(1, ingreso.getValor()); - 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()); - ps.setInt(8, ingreso.getId()); - updates = ps.executeUpdate(); + try (PreparedStatement ps = conn.prepareStatement(query)) { + ps.setInt(1, ingreso.getValor()); + 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()); + 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}); - - ps.close(); + 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}); + } } catch (SQLException e) { LOGGER.log(Level.SEVERE, e.toString(), e); return false; @@ -198,16 +191,16 @@ public class SQLiteIngresoDAO extends IngresoDAO { @Override public boolean deleteIngreso(Ingreso ingreso) { int updates; + String query = "delete from ingresos where id = ?"; try (Connection conn = connectionHolder.getConnection()) { - String query = "delete from ingresos where id = ?"; - PreparedStatement ps = conn.prepareStatement(query); - ps.setInt(1, ingreso.getId()); - updates = ps.executeUpdate(); + try (PreparedStatement ps = conn.prepareStatement(query)) { + ps.setInt(1, ingreso.getId()); + updates = ps.executeUpdate(); - LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}", - new Object[]{query, ingreso.getId(), updates}); + LOGGER.log(Level.FINE, "QUERY: {0} | values: {1} | updates: {2}", + new Object[]{query, ingreso.getId(), updates}); - ps.close(); + } } catch (SQLException e) { LOGGER.log(Level.SEVERE, e.toString(), e); return false; @@ -218,19 +211,16 @@ public class SQLiteIngresoDAO extends IngresoDAO { @Override public int getTotalIngreso(Caja caja) { int total = 0; + String query = "select sum(valor) from ingresos where caja_id = ?"; try (Connection conn = connectionHolder.getConnection()) { - String query = "select sum(valor) from ingresos 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(); + try (PreparedStatement ps = conn.prepareStatement(query)) { + ps.setInt(1, caja.getId()); + try (ResultSet rs = ps.executeQuery()) { + if(rs.next()){ + total = rs.getInt(1); + } + } + } } catch (SQLException e) { LOGGER.log(Level.SEVERE, e.toString(), e); } @@ -240,23 +230,21 @@ public class SQLiteIngresoDAO extends IngresoDAO { @Override public int getTotalIngresoMes(YearMonth mes) { int total = 0; + 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"; 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(); + try (PreparedStatement ps = conn.prepareStatement(query)) { + LocalDate start = mes.atDay(1); + LocalDate end = mes.atEndOfMonth(); + ps.setString(1, start.toString()); + ps.setString(2, end.toString()); - LOGGER.log(Level.FINE, "QUERY: {0} | values: {1}, {2}", new Object[]{query, start, end}); - - rs.next(); - total = rs.getInt(1); - - rs.close(); - ps.close(); + try (ResultSet rs = ps.executeQuery()) { + if(rs.next()){ + total = rs.getInt(1); + } + } + } } catch (SQLException e) { LOGGER.log(Level.SEVERE, e.toString(), e); } @@ -266,26 +254,143 @@ public class SQLiteIngresoDAO extends IngresoDAO { @Override public int getTotalExentasMes(YearMonth mes) { int total = 0; + 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"; 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(); + try (PreparedStatement ps = conn.prepareStatement(query)) { + LocalDate start = mes.atDay(1); + LocalDate end = mes.atEndOfMonth(); + ps.setString(1, start.toString()); + ps.setString(2, end.toString()); + try (ResultSet rs = ps.executeQuery()) { + if(rs.next()){ + total = rs.getInt(1); + } + } + } } catch (SQLException e) { LOGGER.log(Level.SEVERE, e.toString(), e); } return total; } + + @Override + public int getTotalIngresoEnCajaPorTipo(Caja caja, TipoIngreso tipoIngreso) { + if (caja == Caja.EMPTY) { + return 0; + } + + int total = 0; + String query = "select sum(valor) from ingresos where caja_id = ? and tipo_ingreso_id = ?"; + try (Connection conn = connectionHolder.getConnection()) { + try (PreparedStatement ps = conn.prepareStatement(query)) { + ps.setInt(1, caja.getId()); + ps.setInt(2, tipoIngreso.getId()); + try (ResultSet rs = ps.executeQuery()) { + if(rs.next()){ + total = rs.getInt(1); + } + } + } + } catch (SQLException e) { + LOGGER.log(Level.SEVERE, e.toString(), e); + } + return total; + } + + @Override + public Optional getPrimerNroInicialDeCajaDeTipo(Caja caja, TipoIngreso tipoIngreso) { + if (caja == Caja.EMPTY) { + return Optional.of("0"); + } + + String nroInicial = null; + + String query = "select nro_inicial from ingresos where caja_id = ? and tipo_ingreso_id = ? order by nro_inicial asc limit 1"; + try (Connection conn = connectionHolder.getConnection()) { + try (PreparedStatement ps = conn.prepareStatement(query)) { + ps.setInt(1, caja.getId()); + ps.setInt(2, tipoIngreso.getId()); + try (ResultSet rs = ps.executeQuery()) { + if(rs.next()) { + nroInicial = rs.getString(1); + } + } + } + } catch (SQLException e) { + LOGGER.log(Level.SEVERE, e.toString(), e); + } + return Optional.ofNullable(nroInicial); + } + + @Override + public Optional getUltimoNroFinalDeCajaDeTipo(Caja caja, TipoIngreso tipoIngreso) { + if (caja == Caja.EMPTY) { + return Optional.of("0"); + } + String nroFinal = null; + String query = "select nro_final from ingresos where caja_id = ? and tipo_ingreso_id = ? order by nro_inicial desc limit 1"; + try (Connection conn = connectionHolder.getConnection()) { + try (PreparedStatement ps = conn.prepareStatement(query)) { + ps.setInt(1, caja.getId()); + ps.setInt(2, tipoIngreso.getId()); + try (ResultSet rs = ps.executeQuery()) { + if(rs.next()){ + nroFinal = rs.getString(1); + } + } + } + } catch (SQLException e) { + LOGGER.log(Level.SEVERE, e.toString(), e); + e.printStackTrace(); + } + return Optional.ofNullable(nroFinal); + } + + @Override + public Optional getPrimerNroZInicialDeCaja(Caja caja) { + if (caja == Caja.EMPTY) { + return Optional.of("0"); + } + String nroZInicial = null; + String query = "select nro_z_inicial from ingresos where caja_id = ? and tipo_ingreso_id = 1 order by nro_inicial desc limit 1"; + try (Connection conn = connectionHolder.getConnection()) { + try (PreparedStatement ps = conn.prepareStatement(query)) { + ps.setInt(1, caja.getId()); + try (ResultSet rs = ps.executeQuery()) { + if(rs.next()){ + nroZInicial = rs.getString(1); + } + } + } + } catch (SQLException e) { + LOGGER.log(Level.SEVERE, e.toString(), e); + e.printStackTrace(); + } + return Optional.ofNullable(nroZInicial); + } + + @Override + public Optional getUltimoNroZFinalDeCaja(Caja caja) { + if (caja == Caja.EMPTY) { + return Optional.of("0"); + } + String nroZFinal = null; + String query = "select nro_z_final from ingresos where caja_id = ? and tipo_ingreso_id = 1 order by nro_inicial desc limit 1"; + try (Connection conn = connectionHolder.getConnection()) { + try(PreparedStatement ps = conn.prepareStatement(query)){ + ps.setInt(1, caja.getId()); + try(ResultSet rs = ps.executeQuery()){ + if(rs.next()){ + nroZFinal = rs.getString(1); + } + } + } + } catch (SQLException e) { + LOGGER.log(Level.SEVERE, e.toString(), e); + e.printStackTrace(); + } + return Optional.ofNullable(nroZFinal); + } + } diff --git a/src/danielcortes/xyz/utils/SaveFile.java b/src/danielcortes/xyz/utils/SaveFile.java new file mode 100644 index 0000000..26dae57 --- /dev/null +++ b/src/danielcortes/xyz/utils/SaveFile.java @@ -0,0 +1,18 @@ +package danielcortes.xyz.utils; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import org.apache.poi.ss.usermodel.Workbook; + +public class SaveFile { + public static void save(Workbook wb, Path saveFile){ + try (OutputStream fileOut = Files.newOutputStream(saveFile)) { + wb.write(fileOut); + } catch (IOException e) { + e.printStackTrace(); + } + } + +}