com.northcoders.controller.BookingReportsController.java Source code

Java tutorial

Introduction

Here is the source code for com.northcoders.controller.BookingReportsController.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.northcoders.controller;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.northcoders.model.Booking;
import com.northcoders.model.PaymentTransaction;
import com.northcoders.model.Room;
import com.northcoders.model.RoomStatus;
import com.northcoders.model.RoomType;
import com.northcoders.services.BookingClient;
import com.northcoders.services.PaymentTransactionClient;
import com.northcoders.services.RoomClient;
import com.northcoders.services.RoomStatusClient;
import com.northcoders.services.RoomTypeClient;
import com.northcoders.view.AutoCompleteComboBoxListener;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.ListView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;

/**
 *
 * @author equadrado
 */
public class BookingReportsController {

    @FXML
    private AnchorPane bookingReportsDocument;
    @FXML
    private TableView<Booking> table_b;
    @FXML
    private TableColumn id;
    @FXML
    private TableColumn customerId;
    @FXML
    private TableColumn roomId;
    @FXML
    private TableColumn startDate;
    @FXML
    private TableColumn endDate;
    @FXML
    private TableColumn totalPrice;
    @FXML
    private TableColumn paymentTransactionList;
    @FXML
    private TableColumn specialRequest;
    @FXML
    private DatePicker pickDateEnd;
    @FXML
    private DatePicker pickDateStart;
    @FXML
    private ComboBox<RoomStatus> cbox_rstatus;
    @FXML
    private CheckBox ckboc_rstatus;
    @FXML
    private ComboBox<Room> cbox_room;
    @FXML
    private CheckBox ckboc_room;
    @FXML
    private Button btnGenerate;
    @FXML
    private ComboBox<RoomType> cbox_rtype;
    @FXML
    private CheckBox ckboc_rtype;
    @FXML
    private TextField txt_customerID;
    @FXML
    private TextField txt_totalPrice;
    @FXML
    private Button btnClear;
    @FXML
    private ListView<PaymentTransaction> lst_paymentTransactionList;

    private Booking actual_b;
    private Booking search_b;

    private ObservableList<AutoCompleteComboBoxListener> acs = FXCollections.observableArrayList();

    private AdminConfigMainController adminConfigMainController;

    private ObservableList<Booking> bookings = FXCollections.observableArrayList();
    private ObservableList<RoomType> roomtypes = FXCollections.observableArrayList();
    private ObservableList<Room> rooms = FXCollections.observableArrayList();
    private ObservableList<RoomStatus> roomstatus = FXCollections.observableArrayList();
    private ObservableList<PaymentTransaction> paymenttransaction = FXCollections.observableArrayList();

    private String conditions = "Start Date:XX/XX/XXXX End Date:XX/XX/XXXX";

    public void initialize() {

        table_b.setOnKeyReleased((KeyEvent t) -> {
            TablePosition tp;
            switch (t.getCode()) {
            //other code cut out here
            case Z:
                if (t.isControlDown()) {
                    //                        if (!deletedLines.isEmpty()) {
                    //                            items.add(deletedLines.pop());
                    //                        }
                    //                        break; //don't break for regular Z
                }
            default:
                if (t.getCode().isLetterKey() || t.getCode().isDigitKey()) {
                    //                        lastKey = t.getText();
                    tp = table_b.getFocusModel().getFocusedCell();
                    table_b.edit(tp.getRow(), tp.getTableColumn());
                    //                        lastKey = null;
                }
            }
        });

        id.setCellValueFactory(new PropertyValueFactory<Booking, Integer>("id"));
        roomId.setCellValueFactory(new PropertyValueFactory<Booking, String>("roomId"));
        customerId.setCellValueFactory(new PropertyValueFactory<Booking, String>("customerId"));
        startDate.setCellValueFactory(new PropertyValueFactory<Booking, String>("startDate"));
        endDate.setCellValueFactory(new PropertyValueFactory<Booking, String>("endDate"));
        totalPrice.setCellValueFactory(new PropertyValueFactory<Booking, String>("totalPrice"));
        paymentTransactionList
                .setCellValueFactory(new PropertyValueFactory<Booking, String>("paymentTransactionList"));
        specialRequest.setCellValueFactory(new PropertyValueFactory<Booking, String>("specialRequest"));

        actual_b = new Booking();

        cbox_rstatus.setItems(loadRoomStatusTable());
        cbox_rtype.setItems(loadRoomTypeTable());
        cbox_room.setItems(loadRoomTable());

        table_b.getSelectionModel().selectedItemProperty()
                .addListener((v, oldValue, newValue) -> updateSelected((Booking) newValue));

        btnGenerate.setOnAction(e -> generate());

        btnClear.setOnAction(e -> clear());

        //        addAutoCompleteComboBoxListener(cbox_room);
        //        visibleList.setItems(acs);
    }

    private void updateSelected(Booking newValue) {
        if (newValue != null) {
            actual_b = newValue;

            txt_totalPrice.setText(String.format("%1$,.2f", actual_b.getTotalPrice()));
            txt_customerID.setText(actual_b.getCustomerId().getId().toString());
            pickDateStart.setValue(strToLocalDate(actual_b.getStartDate().toString()));
            pickDateEnd.setValue(strToLocalDate(actual_b.getEndDate().toString()));

            cbox_rstatus.getSelectionModel().select(actual_b.getRoomId().getRoomStatusId().getId());
            cbox_rtype.getSelectionModel().select(actual_b.getRoomId().getRoomTypeId().getId());
            cbox_room.getSelectionModel().select(actual_b.getRoomId().getId());

            lst_paymentTransactionList.setItems(loadPaymentTransactionTable(actual_b.getId()));

        }
    }

    public static final LocalDate strToLocalDate(String dateString) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy"); // Sun Mar 26 00:00:00 EDT 2017
        LocalDate localDate = LocalDate.parse(dateString, formatter);

        return localDate;
    }

    public static final String dateToStr(Date date) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        String strDate = dateFormat.format(date);

        return strDate;
    }

    public static final String dateTimeToStr(Date date) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        String strDate = dateFormat.format(date);

        return strDate;
    }

    void addAutoCompleteComboBoxListener(ComboBox cb) {
        AutoCompleteComboBoxListener ac = new AutoCompleteComboBoxListener<>(cb);
        acs.add(ac);
    }

    private void clear() {
        // clear all search fields end edit mode
        txt_totalPrice.setText("");
        txt_customerID.setText("");
        pickDateStart.setValue(null);
        pickDateEnd.setValue(null);

        cbox_rstatus.getSelectionModel().select(-1);
        cbox_rtype.getSelectionModel().select(-1);
        cbox_room.getSelectionModel().select(-1);

        lst_paymentTransactionList.setItems(FXCollections.observableArrayList());

        ckboc_room.setSelected(false);
        ckboc_rstatus.setSelected(false);
        ckboc_rtype.setSelected(false);
    }

    private void generate() {
        loadTable();

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

    private void deleteData() {
        try {
            (new RoomTypeClient()).delete(actual_b.getId());
            loadTable();
        } catch (Exception ex) {
            Logger.getLogger(RoomTypeController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void loadTable() {
        search_b = new Booking();

        search_b.setRoomId(cbox_room.getSelectionModel().getSelectedItem());
        //        search_b.setRoomId(cbox_bype.getSelectionModel().getSelectedItem().getId());
        //        search_b.setStartDate(pickDateStart.chronologyProperty().getValue());
        //        search_b.setEndDate(pickDateEnd.chronologyProperty().getValue());

        table_b.setItems(search(search_b));

    }

    public ObservableList<RoomType> loadRoomTypeTable() {
        roomtypes.clear();

        try {
            for (RoomType item : (new RoomTypeClient()).findAll()) {
                roomtypes.add(item);
                //                roomtypes.add(item.getTitle());
            }
        } catch (Exception ex) {
            Logger.getLogger(RoomTypeController.class.getName()).log(Level.SEVERE, null, ex);
        }

        return roomtypes;
    }

    public ObservableList<RoomStatus> loadRoomStatusTable() {
        roomstatus.clear();

        try {
            for (RoomStatus item : (new RoomStatusClient()).findAll()) {
                roomstatus.add(item);
                //                roomstatus.add(item.getDescription());
            }
        } catch (Exception ex) {
            Logger.getLogger(RoomTypeController.class.getName()).log(Level.SEVERE, null, ex);
        }

        return roomstatus;
    }

    public ObservableList<Room> loadRoomTable() {
        rooms.clear();

        try {
            for (Room item : (new RoomClient()).findAll()) {
                rooms.add(item);
            }
        } catch (Exception ex) {
            Logger.getLogger(BookingReportsController.class.getName()).log(Level.SEVERE, null, ex);
        }

        return rooms;
    }

    public ObservableList<PaymentTransaction> loadPaymentTransactionTable(int id) {
        paymenttransaction.clear();

        try {
            for (PaymentTransaction item : (new PaymentTransactionClient()).findByBookingId(id)) {
                paymenttransaction.add(item);
            }
        } catch (Exception ex) {
            Logger.getLogger(BookingReportsController.class.getName()).log(Level.SEVERE, null, ex);
        }

        return paymenttransaction;
    }

    public ObservableList<Booking> getAll() {
        bookings.clear();

        try {
            for (Booking item : (new BookingClient()).findAll()) {
                bookings.add(item);
            }
        } catch (Exception ex) {
            Logger.getLogger(BookingReportsController.class.getName()).log(Level.SEVERE, null, ex);
        }

        return bookings;
    }

    public ObservableList<Booking> search(Booking search) {
        bookings.clear();

        try {
            for (Booking item : (new BookingClient()).search(search)) {
                item.setPaymentTransactionList((new PaymentTransactionClient()).findByBookingId(item.getId()));
                bookings.add(item);
            }
        } catch (Exception ex) {
            Logger.getLogger(BookingReportsController.class.getName()).log(Level.SEVERE, null, ex);
        }

        return bookings;
    }

    public void injectMainController(AdminConfigMainController maincontroller) {
        this.adminConfigMainController = maincontroller;
    }

    @FXML
    private void generatePdf() throws Exception {
        BaseFont bf;
        Font font;
        try {
            conditions = "Filtered by: Start Date:2017-03-15 End Date:2017-03-28";

            /* Step-2: Initialize PDF documents - logical objects */
            Document my_pdf_report = new Document(PageSize.LETTER.rotate());
            PdfWriter.getInstance(my_pdf_report, new FileOutputStream("pdf_booking_report.pdf"));
            my_pdf_report.open();
            //we have four columns in our table
            PdfPTable my_report_table = new PdfPTable(6);
            //create a cell object
            PdfPCell table_cell;

            bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            font = new Font(bf, 16);
            my_pdf_report.add(new Paragraph("Administration Report", font));
            font = new Font(bf, 12);
            my_pdf_report.add(new Paragraph("Filter applied:" + conditions, font));
            my_pdf_report.add(new Paragraph(" "));

            table_cell = new PdfPCell(new Phrase("Customer"));
            my_report_table.addCell(table_cell);
            table_cell = new PdfPCell(new Phrase("Start Date"));
            my_report_table.addCell(table_cell);
            table_cell = new PdfPCell(new Phrase("End Date"));
            my_report_table.addCell(table_cell);
            table_cell = new PdfPCell(new Phrase("Room"));
            my_report_table.addCell(table_cell);
            table_cell = new PdfPCell(new Phrase("Amount"));
            my_report_table.addCell(table_cell);
            table_cell = new PdfPCell(new Phrase("Transactions"));
            my_report_table.addCell(table_cell);

            for (Booking item : bookings) {
                String customer_b = item.getCustomerId().getId() + " " + item.getCustomerId().getFirstName() + " "
                        + item.getCustomerId().getLastName();
                table_cell = new PdfPCell(new Phrase(customer_b));
                my_report_table.addCell(table_cell);

                String date_start_b = dateToStr(item.getStartDate());
                table_cell = new PdfPCell(new Phrase(date_start_b));
                my_report_table.addCell(table_cell);

                String date_end_b = dateToStr(item.getEndDate());
                table_cell = new PdfPCell(new Phrase(date_end_b));
                my_report_table.addCell(table_cell);

                String room_b = String.valueOf(item.getRoomId().getRoomNumber());
                table_cell = new PdfPCell(new Phrase(room_b));
                my_report_table.addCell(table_cell);

                String price_b = String.format("%1$,.2f", item.getTotalPrice());
                table_cell = new PdfPCell(new Phrase(price_b));
                my_report_table.addCell(table_cell);

                String transaction_b = "";
                for (PaymentTransaction trans : item.getPaymentTransactionList()) {
                    transaction_b += String.format("%1$,.2f", trans.getAmount()) + " "
                            + trans.getPaymentTypeId().getDescription() + "\n";
                }
                table_cell = new PdfPCell(new Phrase(transaction_b));
                my_report_table.addCell(table_cell);
            }

            /* Attach report table to PDF */
            my_pdf_report.add(my_report_table);
            my_pdf_report.add(new Paragraph(" "));
            font = new Font(bf, 6);
            my_pdf_report.add(new Paragraph("Report Time:" + dateTimeToStr(new Date())));
            my_pdf_report.close();

        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}