sistemafacturacionlibros.VentanaCheckout.java Source code

Java tutorial

Introduction

Here is the source code for sistemafacturacionlibros.VentanaCheckout.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sistemafacturacionlibros;

import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Arielo
 */
public class VentanaCheckout extends javax.swing.JFrame {

    Connection c = null;
    Statement stmt = null;
    Conexion miconexion = new Conexion();

    int empleado = Conexion.getUserID();
    int cliente = Conexion.getClienteID();
    private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
    private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD);

    /**
     * Creates new form VentanaCheckout
     */
    public VentanaCheckout() {
        initComponents();
        miconexion.CrearCarrito();
        chk_table.getTableHeader().setReorderingAllowed(false);
        chk_table.setAutoCreateRowSorter(true);

        c = Conexion.dbConnector();
        String v = Conexion.getSelectedName();
        RefreshTablaCarrito();
        chk_cliente.setText(v);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        JPanelTable = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        chk_table = new javax.swing.JTable();
        JPanelBtn = new javax.swing.JPanel();
        btn_volver = new javax.swing.JButton();
        btn_compra = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        chk_cliente = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        chk_LabelTotal = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        chk_table.setAutoCreateRowSorter(true);
        chk_table.setModel(new javax.swing.table.DefaultTableModel(new Object[][] {

        }, new String[] { "ID", "Titulo", "Autor", "Precio", "Cantidad" }) {
            boolean[] canEdit = new boolean[] { false, false, false, false, true };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        });
        chk_table.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(chk_table);

        javax.swing.GroupLayout JPanelTableLayout = new javax.swing.GroupLayout(JPanelTable);
        JPanelTable.setLayout(JPanelTableLayout);
        JPanelTableLayout
                .setHorizontalGroup(JPanelTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 481, Short.MAX_VALUE));
        JPanelTableLayout
                .setVerticalGroup(JPanelTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(JPanelTableLayout.createSequentialGroup().addContainerGap()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 289,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

        btn_volver.setText("Volver");
        btn_volver.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_volverActionPerformed(evt);
            }
        });

        btn_compra.setText("Procesar compra");
        btn_compra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_compraActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout JPanelBtnLayout = new javax.swing.GroupLayout(JPanelBtn);
        JPanelBtn.setLayout(JPanelBtnLayout);
        JPanelBtnLayout
                .setHorizontalGroup(JPanelBtnLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(JPanelBtnLayout.createSequentialGroup().addContainerGap().addComponent(btn_volver)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btn_compra, javax.swing.GroupLayout.PREFERRED_SIZE, 174,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(55, 55, 55)));
        JPanelBtnLayout
                .setVerticalGroup(JPanelBtnLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(btn_compra, javax.swing.GroupLayout.PREFERRED_SIZE, 60,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btn_volver, javax.swing.GroupLayout.DEFAULT_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));

        chk_cliente.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(jPanel1Layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup().addComponent(chk_cliente,
                        javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap()));
        jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(chk_cliente, javax.swing.GroupLayout.Alignment.TRAILING,
                        javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setText("Total:");

        chk_LabelTotal.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel2.setText("Cliente:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(JPanelTable, javax.swing.GroupLayout.DEFAULT_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout
                                .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createSequentialGroup().addGap(57, 57, 57)
                                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 67,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(8, 8, 8)
                                        .addComponent(chk_LabelTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 144,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel2).addGap(18, 18, 18).addComponent(jPanel1,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addComponent(JPanelBtn, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                        .addGap(2, 2, 2)));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup().addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(0, 0, Short.MAX_VALUE))
                                        .addComponent(chk_LabelTotal, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                layout.createSequentialGroup()
                                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jLabel2).addGap(18, 18, 18)))
                        .addComponent(JPanelTable, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(JPanelBtn, javax.swing.GroupLayout.PREFERRED_SIZE,
                                javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap()));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btn_compraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_compraActionPerformed
        // TODO add your handling code here:
        int dialogButton = JOptionPane.YES_NO_OPTION;
        int response = JOptionPane.showConfirmDialog(rootPane, "Esta accion es irreversible, continuar?",
                "Confirmar transaccion", dialogButton);

        if (response == JOptionPane.NO_OPTION) {
            System.out.println("No button clicked");
        } else if (response == JOptionPane.YES_OPTION) {
            System.out.println("Yes button clicked");
            TerminarTransaccion();

            try {
                PDFCreator pdf = new PDFCreator();
                Document document = new Document();
                PdfWriter.getInstance(document, new FileOutputStream("Factura " + chk_cliente.getText() + ".pdf"));
                document.open();
                pdf.addMetaData(document);
                pdf.addTitlePage(document, createTable(), chk_LabelTotal.getText());
                document.close();
                JOptionPane.showMessageDialog(rootPane, "PDF Factura generada!");
                DeleteCarrito();

            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (response == JOptionPane.CLOSED_OPTION) {
            System.out.println("JOptionPane closed");
        }
        RefreshTablaCarrito();

    }//GEN-LAST:event_btn_compraActionPerformed

    private void btn_volverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_volverActionPerformed
        // TODO add your handling code here:
        VentanaPrincipal vp = new VentanaPrincipal();
        vp.setVisible(true);
        vp.setTitle("Ventana Principal");
        CloseFrame();
    }//GEN-LAST:event_btn_volverActionPerformed

    public void CloseFrame() {
        super.dispose();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VentanaCheckout.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VentanaCheckout.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VentanaCheckout.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VentanaCheckout.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VentanaCheckout().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel JPanelBtn;
    private javax.swing.JPanel JPanelTable;
    private javax.swing.JButton btn_compra;
    private javax.swing.JButton btn_volver;
    private javax.swing.JLabel chk_LabelTotal;
    private javax.swing.JLabel chk_cliente;
    private javax.swing.JTable chk_table;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

    private void RefreshTablaCarrito() {
        try {
            String sql = "Select IDLibro,Titulo,Autor,Precio,Cantidad FROM Carrito";
            PreparedStatement pst = c.prepareStatement(sql);
            ResultSet rs = pst.executeQuery();
            ResultSetMetaData rsMd = rs.getMetaData();
            int numeroColumnas = rsMd.getColumnCount();

            DefaultTableModel modelo = (DefaultTableModel) chk_table.getModel();
            modelo.setRowCount(0);

            while (rs.next()) {
                Object[] fila = new Object[numeroColumnas];
                for (int y = 0; y < numeroColumnas; y++) {
                    fila[y] = rs.getObject(y + 1);
                }
                modelo.addRow(fila);
            }

            pst.close();
            rs.close();

            //Set total label
            String total = String.valueOf(calcularPrecioCarrito());
            chk_LabelTotal.setText(total);
            System.out.println(calcularPrecioCarrito());
        } catch (Exception e) {
            System.out.println("RefreshCarrito" + e.getMessage());
        }
    }

    public double calcularPrecioCarrito() {

        double total = 0;

        try {
            String sql = "SELECT Sum(Precio) as Precio, " + "Sum(Cantidad) as Cantidad, "
                    + "Sum(Precio*Cantidad) as Result " + "FROM Carrito;";

            PreparedStatement pst = c.prepareStatement(sql);
            ResultSet rs = pst.executeQuery();

            while (rs.next()) {
                total = rs.getDouble("Result");
            }

            pst.close();
            rs.close();
        } catch (SQLException sQLException) {
        }
        return total;
    }

    public ArrayList<Double> calcularPrecioLibro() {

        double precio = 0;
        ArrayList<Double> precioArray = new ArrayList<Double>();
        int i = 0;

        try {
            String sql = "SELECT Precio, Cantidad, (Precio*Cantidad) AS Result FROM Carrito;";

            PreparedStatement pst = c.prepareStatement(sql);
            ResultSet rs = pst.executeQuery();

            while (rs.next()) {
                precio = rs.getDouble("Result");
                precioArray.add(precio);
                i++;
            }

            pst.close();
            rs.close();
        } catch (SQLException sQLException) {
        }
        return precioArray;
    }

    public void InsertarVentaIndividual(int libro, double precioLibro) {

        try {

            String sql = "INSERT INTO Ventas(IDLibro, IDEmpleado, IDCliente, PrecioTotal) " + "VALUES(" + libro
                    + "," + empleado + "," + cliente + "," + precioLibro + ")";

            PreparedStatement pst = c.prepareStatement(sql);
            pst.execute();

            pst.close();

        } catch (Exception e) {
            System.err.println("InsertarVenta" + e.getClass().getName() + ": " + e.getMessage());
        }
    }

    public void TerminarTransaccion() {

        int totalRows = chk_table.getRowCount();
        ArrayList<Double> arrayPrecios = calcularPrecioLibro();

        for (int i = 0; i < totalRows; i++) {
            InsertarVentaIndividual((int) chk_table.getValueAt(i, 0), arrayPrecios.get(i));
        }
    }

    //    public void writeCSVfile(JTable table) throws IOException, ClassNotFoundException, SQLException{
    //        Writer writer = null;
    //        DefaultTableModel dtm = (DefaultTableModel) table.getModel();
    //        int nRow = dtm.getRowCount();
    //        int nCol = dtm.getColumnCount();
    //        try {
    //            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("file.csv"), "utf-8"));
    //
    //            //write the header information
    //            StringBuffer bufferHeader = new StringBuffer();
    //            for (int j = 0; j < nCol; j++) {
    //                bufferHeader.append(dtm.getColumnName(j));
    //                if (j!=nCol) bufferHeader.append(",");
    //            }
    //            writer.write(bufferHeader.toString() + "\r\n");
    //
    //           //write row information
    //            for (int i = 0 ; i < nRow ; i++){
    //                 StringBuffer buffer = new StringBuffer();
    //                for (int j = 0 ; j < nCol ; j++){
    //                    buffer.append(dtm.getValueAt(i,j));
    //                    if (j!=nCol) buffer.append(", ");
    //                }
    //                writer.write(buffer.toString() + "\r\n");
    //            }
    //        } finally {
    //              writer.close();
    //        }
    //    }
    private PdfPTable createTable() throws BadElementException {

        PdfPTable table = new PdfPTable(7);

        try {
            String sql = "select L.ID, " + "L.Titulo, L.Autor, " + "L.Editora, L.Edicion, "
                    + "C.Precio, C.Cantidad " + "from Libros as L " + "inner join Carrito as C "
                    + "on C.IDLibro = L.ID";
            PreparedStatement pst = c.prepareStatement(sql);
            ResultSet rs = pst.executeQuery();
            ResultSetMetaData rsMd = rs.getMetaData();
            //            int numeroColumnas = rsMd.getColumnCount();

            //            DefaultTableModel modelo = (DefaultTableModel) chk_table.getModel();
            //            modelo.setRowCount(0);
            PdfPCell c1 = new PdfPCell(new Phrase("IDLibro"));
            c1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(c1);

            c1 = new PdfPCell(new Phrase("Ttulo"));
            c1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(c1);

            c1 = new PdfPCell(new Phrase("Autor"));
            c1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(c1);
            table.setHeaderRows(1);

            c1 = new PdfPCell(new Phrase("Editora"));
            c1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(c1);
            table.setHeaderRows(1);

            c1 = new PdfPCell(new Phrase("Edicin"));
            c1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(c1);
            table.setHeaderRows(1);

            c1 = new PdfPCell(new Phrase("Precio"));
            c1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(c1);
            table.setHeaderRows(1);

            c1 = new PdfPCell(new Phrase("Cantidad"));
            c1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(c1);
            table.setHeaderRows(1);

            while (rs.next()) {
                table.addCell(rs.getString("ID"));
                table.addCell(rs.getString("Titulo"));
                table.addCell(rs.getString("Autor"));
                table.addCell(rs.getString("Editora"));
                table.addCell(rs.getString("Edicion"));
                table.addCell(rs.getString("Cantidad"));
                table.addCell(rs.getString("Precio"));
            }

            pst.close();
            rs.close();

        } catch (Exception e) {
            System.out.println("RefreshCarrito" + e.getMessage());
        }
        return table;

    }

    public void DeleteCarrito() throws SQLException {

        String sql = "DELETE FROM Carrito";
        PreparedStatement pst = c.prepareStatement(sql);
        pst.execute();

    }
}