com.endro.belajar.controller.InvoiceProdukController.java Source code

Java tutorial

Introduction

Here is the source code for com.endro.belajar.controller.InvoiceProdukController.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 com.endro.belajar.controller;

import com.endro.belajar.config.Database;
import com.endro.belajar.dao.InvoiceDao;
import com.endro.belajar.dao.PelangganDao;
import com.endro.belajar.dao.ProdukDao;
import com.endro.belajar.entity.InvoiceOrder;
import com.endro.belajar.entity.InvoiceOrderProduk;

import com.endro.belajar.entity.Pelanggan;
import com.endro.belajar.entity.Produk;
import com.endro.belajar.entity.SalesOrder;
import com.endro.belajar.entity.SalesOrderProduk;
import com.endro.belajar.gui.ConnectionDialog;
import com.endro.belajar.gui.DialogExportPenjualan;
import com.endro.belajar.gui.InvoicePenjualan;
import com.endro.belajar.gui.MasterPelanggan;
import com.mcm.comp.BeanProperties;
import com.mcm.comp.BeansInterface;
import com.mcm.comp.JLookupMultiValuesEvents;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;

import java.sql.SQLException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableModel;
import mcm.al.grid.ChangeProcessor;
import mcm.al.grid.GridBeansDataLoader;
import mcm.al.grid.GridEditor;
import mcm.al.grid.TableChangeListener;
import mcm.al.util.Utility;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JasperViewer;
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.Row;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 *
 * @author it6
 */
public class InvoiceProdukController {

    private InvoicePenjualan dialogInvoice;
    private MasterPelanggan masterInvoice;
    private DialogExportPenjualan dialogExport;
    private ConnectionDialog dialogCon;

    private InvoiceDao invoiceDao = null;
    private PelangganDao pelangganDao = null;
    private ProdukDao produkDao = null;

    private Pelanggan pelanggan;
    private InvoiceOrder invoice;
    private InvoiceOrderProduk invoiceProduk;
    private Produk produk;
    private SalesOrder salesOrder;

    private double totalitem = 0;
    private double total = 0;

    private TableChangeListener listener;

    public InvoiceProdukController() throws SQLException {
        invoiceDao = new InvoiceDao();
        pelangganDao = new PelangganDao();
        produkDao = new ProdukDao();
        listener = new TableChangeListener();
    }

    public void showFramePenjualan() throws SQLException {
        initFrameMaster();

        loadDataInvoice();
        clickedbuttonExport();
        clickedRightTable();
        clickedTablePelanggan();
        clickedbuttonNew();
        clickedbuttonUpdate();
        clickedbuttonDelete();

        masterInvoice.setModal(true);
        masterInvoice.setVisible(true);
    }

    private void initFrameMaster() {
        if (masterInvoice == null) {
            masterInvoice = new MasterPelanggan();
        }
    }

    private void initDialogPenjualan() {
        if (dialogInvoice == null) {
            dialogInvoice = new InvoicePenjualan();
            dialogInvoice.setLocationRelativeTo(null);
        }

        loadDataProduk();
        initLookupKonsumen();
        initLookupSOKonsumen();
        clickedTutupButton();
        clickedbuttonSimpan();
        //                fillDiskon();
    }

    private void initDialogExport() {
        if (dialogExport == null) {
            dialogExport = new DialogExportPenjualan();
            dialogExport.setLocationRelativeTo(null);
        }

        clickedbuttonExportDialog();
    }

    Integer idPelanggan = 0;

    private void initLookupKonsumen() {
        dialogInvoice.getLookupKonsumen().setSetting(new BeansInterface() {
            @Override
            public List<Object> getListBeans() {
                List<Object> list = new ArrayList<>();
                try {
                    list = Arrays.asList(pelangganDao.findAll().toArray());
                } catch (SQLException ex) {
                    Logger.getLogger(InvoiceProdukController.class.getName()).log(Level.SEVERE, null, ex);
                }
                return list;
            }

            @Override
            public ArrayList<BeanProperties> getProperties() {
                ArrayList<BeanProperties> prop = new ArrayList<>();
                prop.add(new BeanProperties("pk", "ID", Integer.class));
                prop.add(new BeanProperties("nama", "Nama Pelanggan", String.class));
                prop.add(new BeanProperties("alamat", "Alamat", String.class));
                prop.add(new BeanProperties("telepon", "No Telephone", String.class));

                return prop;
            }
        }, 0, 1, new int[] { 0, 2, 3 });

        dialogInvoice.getLookupKonsumen().setMultiValuesEventHandler(new JLookupMultiValuesEvents() {

            @Override
            public void onChange(Object o, Object[] os) {
                dialogInvoice.getTextTelephone().setText(os[2].toString());
                dialogInvoice.getTextAlamat().setText(os[1].toString());
                dialogInvoice.getTextContact().setText("-");

                dialogInvoice.getLookupSOPelanggan().setJLookUpEnabled(true);
                dialogInvoice.getLookupSOPelanggan().setValue(null, null);
                DefaultTableModel tableModel = (DefaultTableModel) dialogInvoice.getTableProduk().getModel();
                for (int row = dialogInvoice.getTableProduk().getRowCount() - 1; row >= 0; row--) {
                    tableModel.removeRow(row);
                }
                tableModel = null;
                idPelanggan = Integer.valueOf(os[0].toString());
            }

        }, true);
    }

    private void initLookupSOKonsumen() {
        dialogInvoice.getLookupSOPelanggan().setSetting(new BeansInterface() {
            @Override
            public List<Object> getListBeans() {
                List<Object> list = new ArrayList<>();
                try {
                    list = Arrays.asList(invoiceDao.findSOByPelanggan(idPelanggan).toArray());
                } catch (SQLException ex) {
                    Logger.getLogger(InvoiceProdukController.class.getName()).log(Level.SEVERE, null, ex);
                }
                return list;
            }

            @Override
            public ArrayList<BeanProperties> getProperties() {
                ArrayList<BeanProperties> prop = new ArrayList<>();
                prop.add(new BeanProperties("pelangganfk", "ID", Integer.class));
                prop.add(new BeanProperties("nomortransaksi", "Nomor Transaksi", String.class));

                return prop;
            }
        }, 0, 1, new int[] { 1 });

        dialogInvoice.getLookupSOPelanggan().setMultiValuesEventHandler(new JLookupMultiValuesEvents() {
            @Override
            public void onChange(Object o, Object[] os) {
                try {
                    salesOrder = new SalesOrder();
                    salesOrder = invoiceDao.findSoByNomorTransaksiParent(os[0].toString());
                    DefaultTableModel tableModel = (DefaultTableModel) dialogInvoice.getTableProduk().getModel();
                    for (int row = dialogInvoice.getTableProduk().getRowCount() - 1; row >= 0; row--) {
                        tableModel.removeRow(row);
                    }
                    tableModel = null;

                    for (SalesOrderProduk so : salesOrder.getSalesOrderProduk()) {
                        Object[] newRow = { so.getPk(), so.getProdukfk(), so.getKodeproduk(), so.getSalesfk(),
                                so.getHarga(), so.getJumlah(), so.getTotalqty() };
                        Utility.addTableRow(dialogInvoice.getTableProduk(), newRow);
                    }
                    dialogInvoice.getTextInformasiPosting().setText(salesOrder.getInformasiposting());
                    dialogInvoice.getAreaAlamatPengiriman().setText(salesOrder.getAlamatpengiriman());
                    //Double diskon = Double.valueOf(salesOrder.getDiskonfaktur())
                    dialogInvoice.getSpinnerDiskon().setValue(salesOrder.getDiskonfaktur());
                    dialogInvoice.getTextTotalSetelahDiskon()
                            .setText(String.valueOf(salesOrder.getTotalsetelahdiskon()));
                    dialogInvoice.getTextHargaTotal().setText(String.valueOf(salesOrder.getTotalbelumdiskon()));
                    System.out.println(salesOrder.getPk());
                } catch (SQLException ex) {
                    Logger.getLogger(InvoiceProdukController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }, true);
    }

    private void loadDataProduk() {
        try {
            GridBeansDataLoader loader = new GridBeansDataLoader();
            loader.renderTable(new BeansInterface() {
                @Override
                public List<Object> getListBeans() {
                    List<Object> returnList = new ArrayList<>();
                    try {
                        returnList = Arrays.asList(invoice.getInvoiceProduk().toArray());
                    } catch (NullPointerException ex) {

                    }
                    return returnList;
                }

                @Override
                public ArrayList<BeanProperties> getProperties() {
                    ArrayList<BeanProperties> prop = new ArrayList<>();
                    prop.add(new BeanProperties("pk", "PK", Integer.class));
                    prop.add(new BeanProperties("produkfk", "Produk FK", String.class));
                    prop.add(new BeanProperties("kodeproduk", "Kode Produk", String.class));
                    prop.add(new BeanProperties("invoicefk", "Invoice FK", String.class));
                    prop.add(new BeanProperties("harga", "Harga", Double.class));
                    prop.add(new BeanProperties("jumlah", "Qyt", Integer.class));
                    prop.add(new BeanProperties("totalqty", "Total Qyt", Double.class));
                    return prop;
                }
            }, dialogInvoice.getTableProduk(), false);

            listener.clearListener();
            dialogInvoice.getTableProduk().getModel().addTableModelListener(listener);
            listener.setGrid(dialogInvoice.getTableProduk());
            listener.setChangeProcessor(new ChangeProcessor() {
                @Override
                public void doChange(int i) {
                    fillSumTotalItemDiskon();
                }
            });

        } catch (Exception ex) {
            Logger.getLogger(InvoiceProdukController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void clickedbuttonSimpan() {
        dialogInvoice.getButtonSimpan().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                invoice.setNomortransaksi(dialogInvoice.getTextNoTransaksi().getText());
                invoice.setTanggal(dialogInvoice.getChooserTanggal().getDate());
                invoice.setInformasiposting(dialogInvoice.getTextInformasiPosting().getText());
                invoice.setAlamatpengiriman(dialogInvoice.getAreaAlamatPengiriman().getText());
                invoice.setDiskonfaktur(Double.valueOf(dialogInvoice.getSpinnerDiskon().getValue().toString()));
                invoice.setTotalbelumdiskon(Double.valueOf(dialogInvoice.getTextHargaTotal().getText()));
                invoice.setTotalsetelahdiskon(Double.valueOf(dialogInvoice.getTextTotalSetelahDiskon().getText()));
                invoice.setPelangganfk((Integer) dialogInvoice.getLookupKonsumen().getSelectedKey());
                invoice.setNoso((String) dialogInvoice.getLookupSOPelanggan().getSelectedValue());
                invoice.setInvoiceProduk(daftarInvoiceProduk());

                System.out.println("No transaksi " + invoice.getNomortransaksi());
                System.out.println("Tanggal " + invoice.getTanggal());
                System.out.println("Informasi posting " + invoice.getInformasiposting());
                System.out.println("Alamat pengiriman " + invoice.getAlamatpengiriman());
                System.out.println("Diskon Faktur " + invoice.getDiskonfaktur());
                System.out.println("Total belum diskon " + invoice.getTotalbelumdiskon());
                System.out.println("Total setelah diskon " + invoice.getTotalsetelahdiskon());
                System.out.println("Pelanggan FK " + invoice.getPelangganfk());
                System.out.println("NO SO " + invoice.getNoso());

                for (InvoiceOrderProduk ip : invoice.getInvoiceProduk()) {
                    System.out.println(ip.getPk());
                    System.out.println(ip.getProdukfk());
                    System.out.println(ip.getKodeproduk());
                    System.out.println(ip.getInvoicefk());
                    System.out.println(ip.getHarga());
                    System.out.println(ip.getJumlah());
                    System.out.println(ip.getTotalqty());
                }

                try {
                    invoiceDao.insertUpdateInvoice(invoice);
                } catch (SQLException ex) {
                    ex.printStackTrace();
                    ;
                }
                dialogInvoice.dispose();
                dialogInvoice.setVisible(false);
                dialogInvoice = null;
                loadDataInvoice();
            }
        });
    }

    private void loadDataInvoice() {
        try {
            initFrameMaster();
            GridBeansDataLoader loader = new GridBeansDataLoader();
            loader.renderTable(new BeansInterface() {
                @Override
                public List<Object> getListBeans() {

                    List<Object> returnList = new ArrayList<>();
                    try {
                        returnList = Arrays.asList(invoiceDao.findAll().toArray());

                    } catch (SQLException ex) {
                        Logger.getLogger(InvoiceProdukController.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    return returnList;
                }

                @Override
                public ArrayList<BeanProperties> getProperties() {
                    ArrayList<BeanProperties> prop = new ArrayList<>();
                    prop.add(new BeanProperties("pk", "ID", Integer.class));
                    prop.add(new BeanProperties("nomortransaksi", "No Transaksi", String.class));
                    prop.add(new BeanProperties("tanggal", "Tanggal", Date.class));
                    prop.add(new BeanProperties("informasiposting", "Informasi Posting", String.class));
                    prop.add(new BeanProperties("totalbelumdiskon", "Total Belum Diskon", String.class));
                    prop.add(new BeanProperties("totalsetelahdiskon", "Total Setelah Diskon", String.class));
                    prop.add(new BeanProperties("alamatpengiriman", "Alamat Pengiriman", String.class));

                    return prop;
                }
            }, masterInvoice.getTablePelanggan(), false);

        } catch (Exception ex) {
            Logger.getLogger(InvoiceProdukController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void clickedRightTable() {
        masterInvoice.getTablePelanggan().addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                int row = masterInvoice.getTablePelanggan().rowAtPoint(e.getPoint());
                if (row >= 0 && row < masterInvoice.getTablePelanggan().getRowCount()) {
                    masterInvoice.getTablePelanggan().setRowSelectionInterval(row, row);
                } else {
                    masterInvoice.getTablePelanggan().clearSelection();
                }

                if (e.getButton() == MouseEvent.BUTTON3) {
                    JPopupMenu popup = popupMenuTable(row);
                    popup.show(e.getComponent(), e.getX(), e.getY());
                }
            }

            private JPopupMenu popupMenuTable(Integer row) {
                JPopupMenu menu = new JPopupMenu();
                JMenuItem cetakNota = new JMenuItem("Cetak Nota");
                menu.add(cetakNota);
                cetakNota.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        try {
                            Integer primaryKey = (Integer) masterInvoice.getTablePelanggan().getValueAt(row, 0);
                            Map<String, Object> map = new HashMap<>();
                            map.put("invoicepk", primaryKey);

                            Connection koneksi = Database.getKonekPenjualan();
                            JasperPrint jasPrint = JasperFillManager.fillReport(getClass().getResourceAsStream(
                                    "/com/endro/belajar/report/NotaTransaksi.jasper"), map, koneksi);
                            JasperViewer.viewReport(jasPrint, false);
                        } catch (JRException ex) {
                            Logger.getLogger(InvoiceProdukController.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (Exception ex) {
                            Logger.getLogger(InvoiceProdukController.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                });
                return menu;
            }

        });
    }

    private void clickedTablePelanggan() {
        masterInvoice.getTablePelanggan().addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1 & e.getClickCount() == 2) {
                    showDialogPenjualan();
                }
            }
        });
    }

    private void showDialogPenjualan() {
        clearObject();

        initDialogPenjualan();
        Integer selectedRow = masterInvoice.getTablePelanggan().getSelectedRow();
        Integer id = (Integer) masterInvoice.getTablePelanggan().getValueAt(selectedRow, 0);

        try {
            invoice = invoiceDao.findById(id);
            loadDataProduk();
            fiilPelangganForm();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        dialogInvoice.setModal(true);
        dialogInvoice.setVisible(true);
    }

    private void fiilPelangganForm() {
        dialogInvoice.getTextNoTransaksi().setText(invoice.getNomortransaksi());
        dialogInvoice.getChooserTanggal().setDate(invoice.getTanggal());
        dialogInvoice.getTextInformasiPosting().setText(invoice.getInformasiposting());
        if (invoice.getPelanggan() == null) {
            dialogInvoice.getLookupKonsumen().setValue(null, null);
            dialogInvoice.getTextAlamat().setText("-");
            dialogInvoice.getTextContact().setText("-");
            dialogInvoice.getTextTelephone().setText("-");
        } else {
            dialogInvoice.getLookupKonsumen().setValue(invoice.getPelanggan().getPk(),
                    invoice.getPelanggan().getNama());
            dialogInvoice.getTextAlamat().setText(invoice.getPelanggan().getAlamat());
            dialogInvoice.getTextContact().setText(invoice.getPelanggan().getKontak());
            dialogInvoice.getTextTelephone().setText(invoice.getPelanggan().getTelepon());
        }
        dialogInvoice.getLookupSOPelanggan().setValue(invoice, invoice.getNoso());
        dialogInvoice.getAreaAlamatPengiriman().setText(invoice.getAlamatpengiriman());
        dialogInvoice.getSpinnerDiskon().setValue(invoice.getDiskonfaktur());
        String hargaTotal = String.valueOf(invoice.getTotalbelumdiskon());
        String totalSetDis = String.valueOf(invoice.getTotalsetelahdiskon());
        dialogInvoice.getTextHargaTotal().setText(hargaTotal);
        dialogInvoice.getTextTotalSetelahDiskon().setText(totalSetDis);
    }

    private void fillSumTotalItemDiskon() {
        Integer itemTotal = 0;
        Integer rowCount = dialogInvoice.getTableProduk().getRowCount();

        for (int i = 0; i < rowCount; i++) {
            Integer x = (Integer) dialogInvoice.getTableProduk().getValueAt(i, 5);
            itemTotal = itemTotal + x;
            if (dialogInvoice.getTableProduk().getRowHeight(i) == 1) {
                Integer xx = (Integer) dialogInvoice.getTableProduk().getValueAt(i, 5);
                itemTotal = itemTotal - xx;
            }
        }
        dialogInvoice.getTextTotalItem().setText(itemTotal.toString());
    }

    //    private void fillDiskon() {
    //        dialogInvoice.getSpinnerDiskon().addChangeListener(new ChangeListener() {
    //            @Override
    //            public void stateChanged(ChangeEvent e) {
    //                Double diskon = Double.parseDouble(dialogInvoice.getSpinnerDiskon().getValue().toString());
    //                Double totalbelumdiskon = Double.parseDouble(dialogInvoice.getTextHargaTotal().getText());
    //                Double totalsetelahDiskon = totalbelumdiskon - diskon;
    //
    //                dialogInvoice.getTextTotalSetelahDiskon().setText(totalsetelahDiskon.toString());
    //            }
    //        });
    //    }

    private void clearObject() {
        dialogInvoice = null;
        invoice = null;
        produk = null;
        pelanggan = null;
        invoiceProduk = null;
    }

    private void clickedbuttonNew() {
        masterInvoice.getButtonNew().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                clearObject();
                showDialogPenjualan();
            }

            private void showDialogPenjualan() {
                initDialogPenjualan();
                invoice = new InvoiceOrder();
                loadTextFaktur();
                loadDataProduk();
                dialogInvoice.setModal(true);
                dialogInvoice.setVisible(true);
            }

            private void loadTextFaktur() {
                try {
                    String notransaksi = invoiceDao.findFaktur();
                    dialogInvoice.getTextNoTransaksi().setText(notransaksi);
                } catch (SQLException ex) {
                    Logger.getLogger(InvoiceProdukController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        });
    }

    private void clickedTutupButton() {
        dialogInvoice.getButtonTutup().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                dialogInvoice.dispose();
                dialogInvoice.setVisible(false);
                dialogInvoice = null;
            }
        });
    }

    private void clickedbuttonUpdate() {
        clearObject();
        masterInvoice.getButtonEdit().addMouseListener(new MouseAdapter() {

            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1) {
                    try {
                        showDialogPenjualan();
                    } catch (ArrayIndexOutOfBoundsException ex) {
                        JOptionPane.showMessageDialog(masterInvoice,
                                "Harap pilih data yang akan dirubah terlebih dahulu");
                    }
                }
            }
        });
    }

    private void clickedbuttonDelete() {
        masterInvoice.getButtonDelete().addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    Integer row = masterInvoice.getTablePelanggan().getSelectedRow();
                    Integer id = (Integer) masterInvoice.getTablePelanggan().getValueAt(row, 0);

                    if (e.getButton() == MouseEvent.BUTTON1) {
                        int pesan = JOptionPane.showConfirmDialog(masterInvoice,
                                "Apakah anda ingin menghapus ID pelanggan " + id + "?", "Hapus Pelanggan",
                                JOptionPane.OK_CANCEL_OPTION);
                        if (pesan == JOptionPane.YES_OPTION) {
                            invoiceDao.deleteInvoice(id);
                        }
                        loadDataInvoice();

                    }
                } catch (SQLException ex) {
                    Logger.getLogger(InvoiceProdukController.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ArrayIndexOutOfBoundsException ex) {
                    JOptionPane.showMessageDialog(masterInvoice, "Harap pilih data terlebih dahulu");
                }
            }
        });
    }

    private List<InvoiceOrderProduk> daftarInvoiceProduk() {
        List<InvoiceOrderProduk> listInvprod = new ArrayList<>();
        JTable tableInvProd = dialogInvoice.getTableProduk();

        List<Integer> rowsAdded = listener.getRowsAdded();
        rowsAdded.stream().forEach(added -> {
            InvoiceOrderProduk invoProd = new InvoiceOrderProduk();
            invoProd.setPk((int) tableInvProd.getValueAt(added, 0));
            invoProd.setProdukfk((int) tableInvProd.getValueAt(added, 1));
            invoProd.setKodeproduk((String) tableInvProd.getValueAt(added, 2));
            invoProd.setInvoicefk((int) tableInvProd.getValueAt(added, 3));
            invoProd.setHarga((double) tableInvProd.getValueAt(added, 4));
            invoProd.setJumlah((int) tableInvProd.getValueAt(added, 5));
            invoProd.setTotalqty((double) tableInvProd.getValueAt(added, 6));
            invoProd.setEditstate(InvoiceOrderProduk.EDIT_STATE_ADD);

            listInvprod.add(invoProd);
        });

        List<Integer> rowsUpdated = listener.getRowsUpdated();
        rowsUpdated.stream().forEach(updated -> {
            InvoiceOrderProduk invoProd = new InvoiceOrderProduk();
            invoProd.setPk((int) tableInvProd.getValueAt(updated, 0));
            invoProd.setProdukfk((int) tableInvProd.getValueAt(updated, 1));
            invoProd.setKodeproduk((String) tableInvProd.getValueAt(updated, 2));
            invoProd.setInvoicefk((int) tableInvProd.getValueAt(updated, 3));
            invoProd.setHarga((double) tableInvProd.getValueAt(updated, 4));
            invoProd.setJumlah((int) tableInvProd.getValueAt(updated, 5));
            invoProd.setTotalqty((double) tableInvProd.getValueAt(updated, 6));
            invoProd.setEditstate(InvoiceOrderProduk.EDIT_STATE_UPDATE);

            listInvprod.add(invoProd);
        });

        List<Integer> rowsDeleted = listener.getRowsRemoved();
        rowsDeleted.stream().forEach(deleted -> {
            InvoiceOrderProduk invoProd = new InvoiceOrderProduk();
            invoProd.setPk((int) tableInvProd.getValueAt(deleted, 0));
            invoProd.setProdukfk((int) tableInvProd.getValueAt(deleted, 1));
            invoProd.setKodeproduk((String) tableInvProd.getValueAt(deleted, 2));
            invoProd.setInvoicefk((int) tableInvProd.getValueAt(deleted, 3));
            invoProd.setHarga((double) tableInvProd.getValueAt(deleted, 4));
            invoProd.setJumlah((int) tableInvProd.getValueAt(deleted, 5));
            invoProd.setTotalqty((double) tableInvProd.getValueAt(deleted, 6));
            invoProd.setEditstate(InvoiceOrderProduk.EDIT_STATE_DELETE);

            listInvprod.add(invoProd);
        });

        return listInvprod;
    }

    private void clickedbuttonExport() {
        clearObject();
        masterInvoice.getButtonExport().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                initDialogExport();
                dialogExport.setModal(true);
                dialogExport.setVisible(true);
            }
        });
    }

    private void clickedbuttonExportDialog() {
        dialogExport.getButtonExport().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    LocalDate tanggalAwal = dialogExport.getTanggalAwalChooser().getDate().toInstant()
                            .atZone(ZoneId.systemDefault()).toLocalDate();
                    LocalDate tanggalAkhir = dialogExport.getTanggalAkhirChooser().getDate().toInstant()
                            .atZone(ZoneId.systemDefault()).toLocalDate();

                    List<InvoiceOrder> daftar = invoiceDao.findAllByTanggal(tanggalAwal, tanggalAkhir);
                    processConvertExcel(daftar);
                } catch (SQLException | IOException ex) {
                    Logger.getLogger(InvoiceProdukController.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NullPointerException ex) {
                    JOptionPane.showMessageDialog(dialogExport, "Form tanggal diisi dengan lengkap!");
                } finally {
                    dialogExport.dispose();
                    dialogExport = null;
                }
            }

            private void processConvertExcel(List<InvoiceOrder> daftarInvoice)
                    throws FileNotFoundException, IOException {
                Integer returnVal = dialogExport.getChooserSaveFile().showOpenDialog(dialogExport);

                if (returnVal == dialogExport.getChooserSaveFile().APPROVE_OPTION) {
                    XSSFWorkbook workbook = new XSSFWorkbook();
                    XSSFSheet sheet = workbook.createSheet("Just Example");

                    List<InvoiceOrder> list = daftarInvoice;

                    Integer rowTable = 0;
                    Integer cellTable = 0;
                    CellStyle cellStyleTanggal = workbook.createCellStyle();
                    CellStyle cellStyleHeader = workbook.createCellStyle();
                    CellStyle cellStyleDouble = workbook.createCellStyle();

                    CreationHelper createHelper = workbook.getCreationHelper();
                    XSSFFont font = workbook.createFont();

                    cellStyleTanggal.setDataFormat(createHelper.createDataFormat().getFormat("dd/mm/yyyy"));
                    cellStyleDouble.setDataFormat(
                            createHelper.createDataFormat().getFormat("[$Rp-421]#,##0.0000;-[$Rp-421]#,##0.0000"));
                    font.setBold(true);
                    cellStyleHeader.setFont(font);
                    cellStyleHeader.setWrapText(true);
                    //cellStyleHeader.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
                    cellStyleHeader.setFillPattern(FillPatternType.DIAMONDS);
                    for (InvoiceOrder order : list) {
                        Row row = sheet.createRow(rowTable);

                        if (rowTable == 0) {
                            sheet.setColumnWidth(0, 2000);
                            Cell cellHeader = row.createCell(0);
                            cellHeader.setCellValue("ID");
                            cellHeader.setCellStyle(cellStyleHeader);

                            sheet.setColumnWidth(1, 5000);
                            cellHeader = row.createCell(1);
                            cellHeader.setCellValue("Nomor Transaksi");
                            cellHeader.setCellStyle(cellStyleHeader);

                            sheet.setColumnWidth(2, 4000);
                            cellHeader = row.createCell(2);
                            cellHeader.setCellValue("Tanggal");
                            cellHeader.setCellStyle(cellStyleHeader);

                            sheet.setColumnWidth(3, 6000 * 3);
                            cellHeader = row.createCell(3);
                            cellHeader.setCellValue("Informasi Posting");
                            cellHeader.setCellStyle(cellStyleHeader);

                            sheet.setColumnWidth(4, 4850);
                            cellHeader = row.createCell(4);
                            cellHeader.setCellValue("Total Sebelum Diskon");
                            cellHeader.setCellStyle(cellStyleHeader);

                            sheet.setColumnWidth(5, 5000);
                            cellHeader = row.createCell(5);
                            cellHeader.setCellValue("Diskon");
                            cellHeader.setCellStyle(cellStyleHeader);

                            sheet.setColumnWidth(6, 4500);
                            cellHeader = row.createCell(6);
                            cellHeader.setCellValue("Total Setelah Diskon");
                            cellHeader.setCellStyle(cellStyleHeader);

                            sheet.setColumnWidth(7, 5000 * 2);
                            cellHeader = row.createCell(7);
                            cellHeader.setCellValue("Alamat Pengiriman");
                            cellHeader.setCellStyle(cellStyleHeader);
                        } else {
                            row.createCell(0).setCellValue((Integer) order.getPk());
                            row.createCell(1).setCellValue((String) order.getNomortransaksi());

                            Cell cellTanggal = row.createCell(2);
                            cellTanggal.setCellValue((Date) order.getTanggal());
                            cellTanggal.setCellStyle(cellStyleTanggal);

                            row.createCell(3).setCellValue((String) order.getInformasiposting());

                            Cell cellDouble = row.createCell(4);
                            cellDouble.setCellValue(order.getTotalbelumdiskon());
                            cellDouble.setCellStyle(cellStyleDouble);

                            cellDouble = row.createCell(5);
                            cellDouble.setCellValue(order.getDiskonfaktur());
                            cellDouble.setCellStyle(cellStyleDouble);

                            cellDouble = row.createCell(6);
                            cellDouble.setCellValue(order.getTotalsetelahdiskon());
                            cellDouble.setCellStyle(cellStyleDouble);

                            row.createCell(7).setCellValue((String) order.getAlamatpengiriman() == null ? "Null"
                                    : order.getAlamatpengiriman());
                        }
                        rowTable++;
                    }

                    File file = dialogExport.getChooserSaveFile().getSelectedFile();

                    FileOutputStream outputStream = new FileOutputStream(file + File.separator + "Penjualan.xlsx");
                    workbook.write(outputStream);

                    int pesan = JOptionPane.showConfirmDialog(dialogExport,
                            "Telah tersimpan di " + file + File.separator
                                    + "Penjualan.xlsx \n Apakah anda ingin membuka file tersebut?",
                            "Notification", JOptionPane.OK_CANCEL_OPTION);
                    if (pesan == JOptionPane.YES_OPTION) {
                        if ("Linux".equals(System.getProperty("os.name"))) {
                            String runPenjualan = "xdg-open " + file + File.separator + "Penjualan.xlsx";
                            Runtime.getRuntime().exec(runPenjualan);
                        } else if ("Windows".equals(System.getProperty("os.name"))) {
                            String runPenjualan = "excel.exe /r" + file + File.separator + "Penjualan.xlsx";
                            Runtime.getRuntime().exec(runPenjualan);
                        }
                    }
                } else {
                    dialogExport.getChooserSaveFile().cancelSelection();
                }
            }
        });
    }
}