package controller;
import Entities.*;
import com.jfoenix.controls.*;
import constant.Language;
import handler.CreatePdf;
import handler.SceneHandler;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import message.InfoMessage;
import org.codehaus.plexus.util.StringUtils;
import security.InterfaceLanguage;
import security.UserSession;
import utility.ConnectionUtil;
import utility.DateUtil;
import javax.persistence.TypedQuery;
import java.net.URL;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RentController implements Initializable {
/*
-1 Car Table view Definition
-2 Customer Table view Definition
-3 Customer Search field and Car Search field Difintion
-4 Lower half Pane which contains evrything without upper half (Definition)
-5 Second Driver Pane (Definition )
-6 Mixed variables Defintion
-7 Variables for Date validation Definition
-8 variables for arethmatic Definition
-9 Radio button(of Car) controller line 165
-10 Radio button(of Customer) controller line 181
-11 Car Search Controller line 198
-12 Customer Search Controller line 222
-13 retrieve Customer Data inside Customer Table view (this function inside initialize method) line 273
-14 retrieve Car Data inside Customer Table view (this function inside initialize method) line 305
-15 customer sellection on mouse double click (this function inside initialize method) line 333
-16 Car sellection on mouse double click (this function inside initialize method) line 363
-17 fill All combo boxes (this function inside initialize method) from line 388 to line 430
-18 calcualte all calculation of rent (this function inside initialize method) line 435
-19 Dates validation Controller (this function inside initialize method) line 449
*/
private static final Pattern VALID_STRING_REGEX =
Pattern.compile("^[a-z-A-Z\\p{InArabic}\\s]*$", Pattern.CASE_INSENSITIVE);
private static final Pattern VALID_PHONE_NUMBER_REGEX =
Pattern.compile("^\\d+$");
//***** Section number __1__ 'Car Table view' *****
@FXML
@FXML
private TableView<Car> carTable;
@FXML
private TableColumn<Car, String> carPlateNumber, carYear, carOwnerName, carMileage, kiloMeters, carSize, carDoorsNumber, carChassisNumber, carLicenseExpirationDate, carExtraInfo, carModel, carState, carInsurance, carType, carColor, carEngineStatus, carEngineNumber;
//***** Section number __2__ 'Customer Table view' *****
@FXML
@FXML
private TableView<Customer> customerTable;
@FXML
private TableColumn<Customer, String> firstName;
@FXML
private TableColumn<Customer, String> middleName;
@FXML
private TableColumn<Customer, String> lastName;
@FXML
private TableColumn<Customer, String> ssn;
@FXML
private TableColumn<Customer, String> currentCredit;
@FXML
private TableColumn<Customer, String> licenseNumber;
@FXML
private TableColumn<Customer, String> licenseExpiration;
@FXML
private TableColumn<Customer, String> birthDate;
@FXML
private TableColumn<Customer, String> bloodType;
@FXML
private TableColumn<Customer, String> email;
@FXML
private TableColumn<Customer, String> address;
@FXML
private TableColumn<Customer, String> passportNumber;
@FXML
private TableColumn<Customer, String> phoneNumber;
@FXML
private TableColumn<Customer, String> alternativePhone;
@FXML
private TableColumn<Customer, String> country;
// @FXML public Label customerCurrentCreditLabel;
//***** Section number __3__ 'Customer Search field and Car Search field ' *****
@FXML
public JFXTextField carSearch;
@FXML
public JFXTextField customerSearch;
@FXML
JFXRadioButton customerRadio;
@FXML
JFXRadioButton carRadio;
@FXML
JFXButton addSecondDriverButton;
//***** Section number __4__ Lower half Pane which contains evrything without upper half *****
@FXML
public Pane halfPane;
@FXML
private Pane searchPane;
@FXML
public Label driverNameLabel
; @FXML
public Label currentCreditLabel
; @FXML
public Label expirationLabel
; @FXML
public Label subModelLabel
; @FXML
@FXML
@FXML
public Label customerPhoneNumberLabel
;
@FXML
private JFXButton rentBtn;
@FXML
private JFXComboBox<String> openingCombo;
@FXML
private JFXTextField downPaymentField;
@FXML
private DatePicker startDate;
@FXML
private JFXComboBox<String> closingCombo;
@FXML
private JFXTextField depositField;
@FXML
private JFXTextField currentMileageField;
@FXML
private Label totalExtraDaysLabel
; @FXML
private DatePicker endDate;
@FXML
private Label totalDurationLabel
; @FXML
private JFXComboBox<String> paymentCombo;
@FXML
private JFXTextField pricePerDayField;
@FXML
private Label finalPriceLabel
; @FXML
@FXML
private Label priceLabel
; @FXML
private JFXComboBox<Double> taxCombo;
@FXML
private JFXTextField allowedMileageField;
@FXML
private JFXComboBox<String> currentFuelField;
@FXML
private Label remainingAmountLabel
; @FXML
private JFXTextArea notesField;
//***** Section number __5__ 'Second Driver Pane ' *****
@FXML
private Pane secondDiverPane;
@FXML
private JFXTextField SecondDriverName;
@FXML
private JFXTextField secondDriverLicenceNumber;
@FXML
private JFXTextField secondDriverSsnPass;
@FXML
private JFXComboBox<String> secondDriverNationality;
@FXML
private JFXComboBox<String> secondDriverLicenceCountry;
@FXML
private DatePicker secondDriverLicenceExpiration;
@FXML
private Label secondDriverNameLabel
; @FXML
private JFXTextField secondDriverMiddleName;
@FXML
private JFXTextField secondDriverLastName;
@FXML
private Label secondDriverExpirationLabel
;
@FXML
private JFXTextField secondDriverPhone;
@FXML
private Label secondDriverPhoneLabel
; @FXML
JFXButton backButton;
@FXML
JFXToggleButton unlimitedBtn;
//***** Section number __6__ 'Mixed variables' *****
public static Car selectedCar;
public static Customer selectedCustomer;
public int i;
public ObservableList<Car> list = FXCollections.observableArrayList();
public ObservableList<Customer> customerObservableList = FXCollections.observableArrayList();
//***** Section number __7__ 'Variables for Date validation ' *****
private static long today;
private static long start;
private static long tomorrow;
private static long end;
private static Date time
; private static LocalTime n;
//***** Section number __8__ 'variables for arethmatic ' *****
public long difference;
private static double remaining;
private static double total;
public static double b;
public static double remainingCustomerCredit;
//***** Section number __9__ Radio button(of Car) controller *****
@FXML
carScroll.setVisible(true);
carScroll.setDisable(false);
carTable.setVisible(true);
carTable.setDisable(false);
carSearch.setDisable(false);
carSearch.setEditable(true);
customerScroll.setVisible(false);
customerTable.setVisible(false);
customerSearch.setVisible(true);
customerSearch.setDisable(true);
i = 1;
}
//***** Section number __10__ Radio button(of Customer) controller *****
@FXML
customerScroll.setVisible(true);
customerTable.setVisible(true);
customerSearch.setEditable(true);
customerSearch.setDisable(false);
carScroll.setVisible(false);
carTable.setVisible(false);
carSearch.setEditable(false);
carSearch.setDisable(true);
i = 2;
}
//***** Section number __11__ Car Search Controller *****
private void CarSearch() {
FilteredList<Car> filteredList = new FilteredList<>(list, e -> true);
carSearch.setOnKeyReleased(ex -> {
carSearch.textProperty().addListener((observableValue, oldValue, newValue) -> {
filteredList.setPredicate((Predicate<? super Car>) car -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter
= newValue.
toLowerCase(); return String.
valueOf(car.
getPlateNumber()).
toLowerCase().
contains(lowerCaseFilter
); });
});
SortedList<Car> sortedList = new SortedList<>(filteredList);
sortedList.comparatorProperty().bind(carTable.comparatorProperty());
carTable.setItems(sortedList);
});
}
//***** Section number __12__ Customer Search Controller *****
private void CustomerSearch() {
FilteredList<Customer> customerFilteredList = new FilteredList<>(customerObservableList, e -> true);
customerSearch.setOnKeyReleased(ex -> {
customerSearch.textProperty().addListener((observableValue, oldValue, newValue) -> {
customerFilteredList.setPredicate((Predicate<? super Customer>) customer -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter
= newValue.
toLowerCase(); if (String.
valueOf(customer.
getFirstName()).
toLowerCase().
indexOf(lowerCaseFilter
) != -1) { return true;
} else if (String.
valueOf(customer.
getMiddleName()).
toLowerCase().
indexOf(lowerCaseFilter
) != -1) { return true;
} else if (String.
valueOf(customer.
getLastName()).
toLowerCase().
indexOf(lowerCaseFilter
) != -1) { return true;
} else if (String.
valueOf(customer.
getSsn()).
toLowerCase().
indexOf(lowerCaseFilter
) != -1) { return true;
} else if (String.
valueOf(customer.
getLicenseNumber()).
toLowerCase().
indexOf(lowerCaseFilter
) != -1) { return true;
} else if (String.
valueOf(customer.
getEmail()).
toLowerCase().
indexOf(lowerCaseFilter
) != -1) { return true;
} else if (String.
valueOf(customer.
getPassportNumber()).
toLowerCase().
indexOf(lowerCaseFilter
) != -1) { return true;
} else if (String.
valueOf(customer.
getPhoneNumber()).
toLowerCase().
indexOf(lowerCaseFilter
) != -1) { return true;
} else if (String.
valueOf(customer.
getAlternativeNumber()).
toLowerCase().
indexOf(lowerCaseFilter
) != -1) { return true;
} else if (String.
valueOf(customer.
getCountry()).
toLowerCase().
indexOf(lowerCaseFilter
) != -1) { return true;
}
return false;
});
});
SortedList<Customer> customerSortedList = new SortedList<>(customerFilteredList);
customerSortedList.comparatorProperty().bind(customerTable.comparatorProperty());
customerTable.setItems(customerSortedList);
});
}
@Override
if (!ConnectionUtil.getEntityManager().getTransaction().isActive()) {
ConnectionUtil.getEntityManager().getTransaction().begin();
}
//for car table
list.clear();
customerObservableList.clear();
//***** Section number __13__ retrieve Customer Data inside Customer Table view (this function inside initialize method) *****
try {
//TODO where c.carStatus='2L'
List<Car> cars = ConnectionUtil.getEntityManager().createQuery("select c from Car c where c.carStatus.carStatusName = 'Available' ", Car.class).getResultList();
list.addAll(cars);
carPlateNumber.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getPlateNumber()));
carYear.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getYear()));
carOwnerName.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getOwnerName()));
carMileage.
setCellValueFactory(data
-> new SimpleStringProperty
(String.
valueOf(data.
getValue().
getCarMileage()))); kiloMeters.
setCellValueFactory(data
-> new SimpleStringProperty
(String.
valueOf(data.
getValue().
getCarKilometers()))); carSize.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getCarSize()));
carEngineNumber.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getCarEngineNumber()));
carChassisNumber.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getCarChassisNumber()));
carLicenseExpirationDate.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getLicenseExpirationDate().toString()));
carExtraInfo.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getExtraInformation()));
carModel.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getModel().getSubModelType()));
carState.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getCarStatus().getCarStatusName()));
carInsurance.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getCarInsurance().getCarInsuranceType()));
carType.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getCarPowerType().getPowerType()));
carColor.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getCarColor().getColorName()));
carTable.setItems(list);
}
//***** Section number __14__ retrieve Car Data inside Customer Table view (this function inside initialize method) *****
try {
List<Customer> customers = ConnectionUtil.getEntityManager().createQuery(" select c FROM Customer c where c.isBlocked=false ", Customer.class).getResultList();
customerObservableList.addAll(customers);
firstName.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getFirstName()));
middleName.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getMiddleName()));
lastName.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getLastName()));
ssn.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getSsn()));
currentCredit.setCellValueFactory(data -> new SimpleStringProperty("" + data.getValue().getCurrentCredit()));
licenseNumber.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getLicenseNumber()));
licenseExpiration.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getLicenseExpirationDate().toString()));
birthDate.setCellValueFactory(data -> new SimpleStringProperty("" + data.getValue().getBirthDate()));
bloodType.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getBloodType()));
email.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getEmail()));
address.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getAddress()));
passportNumber.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getPassportNumber()));
phoneNumber.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getPhoneNumber()));
alternativePhone.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getAlternativeNumber()));
country.setCellValueFactory(data -> {
Country country = data.getValue().getCountry();
if (country != null) {
return new SimpleStringProperty(country.getCountryName());
}
return null;
});
customerTable.setItems(customerObservableList);
}
CarSearch();
CustomerSearch();
//***** Section number __15__ customer sellection on mouse double click (this function inside initialize method) *****
// for customer selection
customerTable.setRowFactory(tv -> {
TableRow<Customer> row = new TableRow<>();
row.setOnMouseClicked(event -> {
selectedCustomer = null;
selectedCustomer = customerTable.getSelectionModel().getSelectedItem();
if (event.getClickCount() == 2 && (!row.isEmpty())) {
driverNameLabel.setText(selectedCustomer.getFirstName() + " " + selectedCustomer.getMiddleName() + " " + selectedCustomer.getLastName());
currentCreditLabel.setText("" + selectedCustomer.getCurrentCredit());
expirationLabel.setText("" + selectedCustomer.getLicenseExpirationDate());
customerPhoneNumberLabel.setText("" + selectedCustomer.getPhoneNumber());
// TODO fix it
//customerCurrentCreditLabel.setText(""+selectedCustomer.getCurrentCredit());
carRadio.setDisable(false);
customerSearch.setText(selectedCustomer.getFirstName() + " " + selectedCustomer.getMiddleName() + " " + selectedCustomer.getLastName());
}
});
return row;
});
//***** Section number __16__ Car sellection on mouse double click (this function inside initialize method) *****
// for car selection
carTable.setRowFactory(tv -> {
TableRow<Car> row = new TableRow<>();
row.setOnMouseClicked(event -> {
selectedCar = null;
selectedCar = carTable.getSelectionModel().getSelectedItem();
if (event.getClickCount() == 2 && (!row.isEmpty())) {
try {
modelLabel.setText(selectedCar.getModel().getCarModel().getModelName());
subModelLabel.setText(selectedCar.getModel().getSubModelType());
plateLabel.setText(selectedCar.getPlateNumber());
}
carSearch.setText(selectedCar.getPlateNumber() + " " + selectedCar.getModel().getCarModel().getModelName());
halfPane.setDisable(false);
rentBtn.setDisable(false);
addSecondDriverButton.setVisible(true);
currentMileageField.setText("" + selectedCar.getCarMileage());
}
});
return row;
});
//***** Section number __17__ fill All combo boxes (this function inside initialize method) *****
ObservableList<String> Fueloptions =
FXCollections.observableArrayList(
"0",
"25",
"50",
"75",
"100"
);
currentFuelField.getItems().clear();
currentFuelField.setItems(Fueloptions);
ObservableList<String> paymentOptions =
FXCollections.observableArrayList(
"cash",
"visa",
"cheque"
);
paymentCombo.getItems().clear();
paymentCombo.setItems(paymentOptions);
taxCombo.getItems().clear();
List<Tax> ta = ConnectionUtil.getEntityManager().createQuery("select t from Tax t ", Tax.class).getResultList();
for (Tax t : ta) {
taxCombo.getItems().add(t.getTaxValue());
}
openingCombo.getItems().clear();
closingCombo.getItems().clear();
List<Branch> branches = ConnectionUtil.getEntityManager().createQuery(" select b from Branch b ", Branch.class).getResultList();
for (Branch b : branches) {
openingCombo.getItems().add(b.getBranchCity());
closingCombo.getItems().add(b.getBranchCity());
}
//TODO abu salah >>> try to make search field inside the comboBoxes
secondDriverNationality.getItems().clear();
secondDriverLicenceCountry.getItems().clear();
List<Country> countryList = ConnectionUtil.getEntityManager().createQuery(" select c from Country c ", Country.class).getResultList();
for (Country country1 : countryList) {
secondDriverNationality.getItems().add(country1.getCountryName());
secondDriverLicenceCountry.getItems().add(country1.getCountryName());
}
//***** Section number __18__ calculate all calculation of rent (this function inside initialize method) *****
depositField.textProperty().addListener((obs, oldText, newText) -> {
b
= ((Integer.
parseInt(totalDurationLabel.
getText()) * (Double.
parseDouble(pricePerDayField.
getText()))) + (Integer.
parseInt(totalExtraDaysLabel.
getText()) * (Double.
parseDouble(pricePerDayField.
getText())))); double tx
= Double.
parseDouble(taxCombo.
getSelectionModel().
getSelectedItem().
toString()) * b
; total = b ;
finalPriceLabel.setText(total + " JD");
taxLabel.setText(taxFormat + " JD");
String downPayment
= downPaymentField.
getText();
double downPaymentValue
= !StringUtils.
isEmpty(downPayment
) ? Double.
parseDouble(downPayment
) : 0;
if (selectedCustomer.getCurrentCredit() != 0) {
remaining = total - downPaymentValue - selectedCustomer.getCurrentCredit();
} else {
remaining = total - downPaymentValue;
}
priceLabel.setText((b-tx) + " JD");
remainingAmountLabel.setText(remaining + " JD");
});
//***** Section number __19__ Dates validation Controller (this function inside initialize method) *****
startDate.valueProperty().addListener((ov, oldValue, newValue) -> {
startWithNullEnd();
});
endDate.valueProperty().addListener((ov, oldValue, newValue) -> {
startWithNotNullEnd();
});
pricePerDayField.textProperty().addListener((ov, oldText, newText) -> {
depositField.setText("0");
priceLabel.setText("0");
taxLabel.setText("0");
finalPriceLabel.setText("0");
remainingAmountLabel.setText("0");
});
downPaymentField.textProperty().addListener((ov, oldText, newText) -> {
depositField.setText("0");
priceLabel.setText("0");
taxLabel.setText("0");
finalPriceLabel.setText("0");
remainingAmountLabel.setText("0");
});
}
//***** Section number __20__ Add second driver Controller *****
if (SecondDriverName.getText().isEmpty() || (!checkString(SecondDriverName.getText()))) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Empty Field", "Please insert second driver first name").show();
} else {
new InfoMessage("حقل فارغ", "الرجاء إدخال الإسم الأول للسائق الثاني").show();
}
} else if (secondDriverMiddleName.getText().isEmpty() || (!checkString(secondDriverMiddleName.getText()))) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Empty Field", "Please insert second driver middle name").show();
} else {
new InfoMessage("حقل فارغ", "الرجاء إدخال الإسم الأوسط للسائق الثاني").show();
}
} else if (secondDriverLastName.getText().isEmpty() || (!checkString(secondDriverLastName.getText()))) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Empty Field", "Please insert second driver last name").show();
} else {
new InfoMessage("حقل فارغ", "الرجاء إدخال الإسم الأخير للسائق الثاني").show();
}
} else if (secondDriverPhone.getText().isEmpty()) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Empty Field", "Please insert second driver phone number").show();
} else {
new InfoMessage("حقل فارغ", "الرجاء إدخال رقم الهاتف للسائق الثاني").show();
}
} else if (secondDriverLicenceNumber.getText().isEmpty()) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Empty Field", "Please insert second driver licence number").show();
} else {
new InfoMessage("حقل فارغ", "الرجاء إدخال رقم الرخصة للسائق الثاني").show();
}
} else if (secondDriverSsnPass.getText().isEmpty()) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Empty Field", "Please insert second driver SSN or Passport number").show();
} else {
new InfoMessage("حقل فارغ", "الرجاء إدخال الرقم الوطني أو رقم جواز السفر للسائق الثاني").show();
}
} else if (secondDriverNationality.getSelectionModel().getSelectedItem() == null) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Empty Field", "Please select second driver nationality").show();
} else {
new InfoMessage("حقل فارغ", "الرجاء إدخال الجنسية للسائق الثاني").show();
}
} else if (secondDriverLicenceCountry.getSelectionModel().getSelectedItem() == null) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Empty Field", "Please select second driver licence country").show();
} else {
new InfoMessage("حقل فارغ", "الرجاء إدخال مكان إصدار الرخصة للسائق الثاني").show();
}
} else if (secondDriverLicenceExpiration.getValue() == null) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Empty Field", "Please select second driver licence expiration date").show();
} else {
new InfoMessage("حقل فارغ", "الرجاء إدخال تاريخ إنتهاء الرخصة للسائق الثاني").show();
}
} else {
secondDiverPane.setVisible(false);
searchPane.setVisible(true);
customerScroll.setDisable(false);
customerSearch.setDisable(false);
customerRadio.setDisable(false);
customerScroll.setVisible(false);
// secondDriverMiddleNameLabel.setText("" + secondDriverMiddleName.getText());
// secondDriverLastNameLabel.setText("" + secondDriverLastName.getText());
secondDriverNameLabel.setText(SecondDriverName.getText() + " " + secondDriverMiddleName.getText() + " " + secondDriverLastName.getText());
secondDriverExpirationLabel.setText(secondDriverLicenceExpiration.getValue() + "");
secondDriverPhoneLabel.setText(secondDriverPhone.getText());
}
if (selectedCustomer.
getCurrentCredit() > Double.
parseDouble(finalPriceLabel.
getText())) { remainingCustomerCredit
= selectedCustomer.
getCurrentCredit() - Double.
parseDouble(finalPriceLabel.
getText()); } else {
remainingCustomerCredit = 0;
}
}
//***** Section number __21__ Start Date validation *****
public void startWithNullEnd() {
today
= Date.
valueOf(LocalDate.
now()).
getTime(); start
= Date.
valueOf(startDate.
getValue()).
getTime();
tomorrow = today + 86400000;
if (((endDate.getValue() != null && start < today) || (endDate.getValue() != null && start > tomorrow) || (endDate.getValue() != null && start > end))) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Invalid Date", "please select Start Date between today and tomorrow and not after end date").show();
} else {
new InfoMessage("تاريخ غير صالح", "يرجى تحديد تاريخ البدء بين اليوم وغدا وليس بعد تاريخ الانتهاء").show();
}
} else if ((endDate.getValue() == null && start < today) || (endDate.getValue() == null && start > tomorrow)) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Invalid Date", "please select Start Date between today and tomorrow").show();
} else {
new InfoMessage("تاريخ غير صالح", "يرجى تحديد تاريخ البدء بين اليوم وغدا").show();
}
} else if ((endDate.getValue() == null && start == today) || (endDate.getValue() == null && start == tomorrow)) {
difference = 0L;
totalDurationLabel.setText("" + difference);
startDate.setDisable(true);
endDate.setDisable(false);
} else {
difference = (start - end) / (-60 * 60 * 24 * 1000);
totalDurationLabel.setText("" + difference);
startDate.setDisable(true);
endDate.setDisable(false);
return;
}
}
if (unlimitedBtn.isSelected()) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
allowedMileageField.setVisible(false);
unlimitedBtn.setText("Allowed mileage");
} else {
allowedMileageField.setVisible(false);
unlimitedBtn.setText("تحديد مسافة");
}
}
else {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
unlimitedBtn.setText("Unlimited mileage");
allowedMileageField.setVisible(true);
} else {
allowedMileageField.setVisible(true);
unlimitedBtn.setText("مسافة غير محدودة");
}
}
}
//***** Section number __22__ End Dates validation Controller *****
public void startWithNotNullEnd() {
today
= Date.
valueOf(LocalDate.
now()).
getTime(); String a
= startDate.
getValue().
toString(); String e
= endDate.
getValue().
toString(); start
= Date.
valueOf(startDate.
getValue()).
getTime(); tomorrow = today + 86400000;
end
= Date.
valueOf(endDate.
getValue()).
getTime();
if (end < start) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Invalid Date", "Please select END DATE not before start date").show();
} else {
new InfoMessage("تاريخ غير صالح", "يرجى تحديد تاريخ الانتهاء بعد تاريخ البدء").show();
}
} else {
difference = (start - end) / (-60 * 60 * 24 * 1000);
totalDurationLabel.setText("" + difference);
if (difference < 0) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Invalid Date", "please correct end date selection it is cannot be before start date").show();
} else {
new InfoMessage("تاريخ غير صالح", "يرجى تصحيح اختيار تاريخ الانتهاء ، فلا يمكن أن يكون قبل تاريخ البدء").show();
}
startDate.setDisable(false);
endDate.setDisable(true);
} else {
startDate.setDisable(false);
endDate.setDisable(true);
}
}
return;
}
//***** Section number __23__ checking lowest half fields if is empty and show alert box *****
//TODO handel it on 'tab' key
if (startDate.getValue() == null) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Start Date", "Please select Start Date").show();
} else {
new InfoMessage("تاريخ البدء", "يرجى اختيار تاريخ البدء").show();
}
} else if (endDate.getValue() == null) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("End Date", "Please Select End Date").show();
} else {
new InfoMessage("تاريخ الإنتهاء", "يرجى اختيار تاريخ الإنتهاء").show();
}
} else if (paymentCombo.getSelectionModel().getSelectedItem() == null) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Payment Method", "Please insert Payment Method").show();
} else {
new InfoMessage("طريقة الدفع", "الرجاء ادخال طريقة دفع").show();
}
} else if (taxCombo.getSelectionModel().getSelectedItem() == null) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Tax Type", "Please insert Tax").show();
} else {
new InfoMessage("نوع الضريبة", "الرجاء إدخال نوع الضريبة").show();
}
} else if (pricePerDayField.getText().isEmpty()) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Price Per Day", "Please insert Price Per Day").show();
} else {
new InfoMessage("السعر ليوم واحد", "الرجاء ادخال السعر ليوم").show();
}
} else if (downPaymentField.getText().isEmpty()) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Down Payment", "Please insert Down Payment value").show();
} else {
new InfoMessage("الدفعة الأولى", "الرجاء إدخال قيمة الدفعة الأولى").show();
}
}
}
//***** Section number __24__ rent controller *****
if (selectedCar == null) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Car Selection", "Please select Car from Table view").show();
} else {
new InfoMessage("اختيار السيارة", "يرجى اختيار سيارة من جدول عرص السيارات").show();
}
} else if (selectedCustomer == null) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Customer Selection", "Please select Customer from Table view").show();
} else {
new InfoMessage("اختيار العميل", "يرجى اختيار عميل من جدول عرص العملاء").show();
}
} else if (depositField.getText().isEmpty()) {
// TODO cheack about if the value == 0
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Deposit ", "Please insert Deposit Value").show();
} else {
new InfoMessage("التأمين ", "الرجاء إدخال قيمة التأمين").show();
}
} else if (allowedMileageField.getText().isEmpty() && !unlimitedBtn.isSelected()) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Allowed Mileage", "Please insert Allowed Mileage").show();
} else {
new InfoMessage("المسافة المسحوح بها", "الرجاء إدخال عدد الكيلومترات المسموح بها").show();
}
} else if (currentMileageField.getText().isEmpty()) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Current mileage", "Please insert Current Mileage").show();
} else {
new InfoMessage("القراءة الحالية لعداد المسافات", "الرجاء إدخال قراءة المسافة المقطوعة الحالية").show();
}
} else if (currentFuelField.getSelectionModel().getSelectedItem() == null) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Curent Fuel", "Please insert Current Fuel").show();
} else {
new InfoMessage("كمية الوقود الحالية", "الرجاء إدخال كمية الوقود الحالية").show();
}
} else if (closingCombo.getSelectionModel().getSelectedItem() == null) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Closing Branch", "Please select Closing Branch").show();
} else {
new InfoMessage("إلاق في فرع", "الرجاء إختيار الفرع الذي سيتم إغلاق العقد فيه").show();
}
} else if (openingCombo.getSelectionModel().getSelectedItem() == null) {
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Opening Branch", "Please select Opening Branch ").show();
} else {
new InfoMessage("فرع فتح العقد", "الرجاء إختيار الفرع المراد فتح العقد به").show();
}
} else {
rentBtn.setDisable(true);
OpenContract openContract = new OpenContract();
ClientDriver clientDriver = new ClientDriver();
openContract.
setYear(Integer.
parseInt(String.
valueOf(startDate.
getValue().
getYear()))); if (!unlimitedBtn.isSelected()) {
openContract.
setAllowedMileage(Double.
parseDouble(allowedMileageField.
getText())); }
openContract.setContractState("Opened");
openContract.
setCurrentFuel(Integer.
parseInt(currentFuelField.
getSelectionModel().
getSelectedItem().
toString())); openContract.
setCurrentMileage(Double.
parseDouble(currentMileageField.
getText())); openContract.
setDepositValue(Double.
parseDouble(depositField.
getText())); openContract.
setDownPayment(Double.
parseDouble(downPaymentField.
getText())); openContract.setExpectedEndDate(endDate.getValue());
openContract.
setPricePerDay(Double.
parseDouble(pricePerDayField.
getText())); openContract.
setRemainingAmount(Double.
parseDouble(remainingAmountLabel.
getText().
replace("JD",
""))); openContract.setStartDate(startDate.getValue());
openContract.
setTotalDuration(Integer.
parseInt(totalDurationLabel.
getText())); openContract.
setTotalExtraDays(Integer.
parseInt(totalExtraDaysLabel.
getText())); openContract.
setTotalPrice(Double.
parseDouble(finalPriceLabel.
getText().
replace("JD",
"")));
openContract.setNotes(notesField.getText());
openContract.setType("Individual");
openContract.
setTaxAmount(Double.
parseDouble(taxLabel.
getText().
substring(0, taxLabel.
getText().
length() - 2))); openContract.
setPrice(Double.
parseDouble(priceLabel.
getText().
substring(0, priceLabel.
getText().
length() - 2))); openContract.setUserId(UserSession.getInstance().getUserId());
openContract.setCar(selectedCar);
openContract.setStartHour(DateUtil.getCurrentHour());
openContract.setExpectedEndHour(DateUtil.getCurrentHour());
Car car = ConnectionUtil.getEntityManager().find(Car.class, selectedCar.getCarId());
CarStatus carStatus = ConnectionUtil.getEntityManager().find(CarStatus.class, 2L);
car.setCarStatus(carStatus);
car.
setCarMileage(Double.
parseDouble(currentMileageField.
getText())); car.setCurrentLoction(openingCombo.getSelectionModel().getSelectedItem());
TypedQuery<Branch> branchQuery = ConnectionUtil.getEntityManager().createQuery("select x from Branch x where x.branchCity = :v ", Branch.class);
Branch closedBranch = branchQuery.setParameter("v", closingCombo.getSelectionModel().getSelectedItem()).getSingleResult();
openContract.setClosedBranch(closedBranch);
Branch openedBranch = branchQuery.setParameter("v", openingCombo.getSelectionModel().getSelectedItem()).getSingleResult();
openContract.setOpenedBranch(openedBranch);
PaymentHistory paymentHistory = new PaymentHistory();
paymentHistory.
setPaymentTypeName(String.
valueOf(paymentCombo.
getSelectionModel().
getSelectedItem()));
paymentHistory.
setPaymentValue(Double.
parseDouble(downPaymentField.
getText())); paymentHistory.setContractPayment(openContract);
List<Tax> t = ConnectionUtil.getEntityManager().createQuery("select x from Tax x where x.taxValue = :v ", Tax.class).setParameter("v", taxCombo.getSelectionModel().getSelectedItem()).getResultList();
openContract.setTax(t.get(0));
List<Customer> customerList = new ArrayList<>();
customerList.add(selectedCustomer);
openContract.setCustomerContract(selectedCustomer);
selectedCustomer.setCurrentCredit(remainingCustomerCredit);
if (!(secondDriverNameLabel.getText().isEmpty())) {
clientDriver.setFirstName(SecondDriverName.getText());
clientDriver.setMiddleName(secondDriverMiddleName.getText());
clientDriver.setLastName(secondDriverLastName.getText());
clientDriver.setLicenseNumber(secondDriverLicenceNumber.getText());
clientDriver.setPhoneNumber(secondDriverPhone.getText());
clientDriver.setSsn(secondDriverSsnPass.getText());
TypedQuery<Country> countryQuery = ConnectionUtil.getEntityManager().createQuery(" select x from Country x where x.countryName = :v ", Country.class);
Country secondDriverCountry = countryQuery.setParameter("v", secondDriverNationality.getSelectionModel().getSelectedItem()).getSingleResult();
clientDriver.setCountry(secondDriverCountry);
Country secondLicenceCountry = countryQuery.setParameter("v", secondDriverLicenceCountry.getSelectionModel().getSelectedItem()).getSingleResult();
clientDriver.setLicenseCountry(secondLicenceCountry);
clientDriver.
setLicenseExpiration(Date.
valueOf(secondDriverLicenceExpiration.
getValue()));
clientDriver.setOpenContract(openContract);
clientDriver.setDriverOfCustomer(customerList);
ConnectionUtil.getEntityManager().persist(clientDriver);
}
List<PaymentHistory> paymentHistories = new ArrayList<>();
paymentHistories.add(paymentHistory);
openContract.setContractPaymentHistory(paymentHistories);
ConnectionUtil.getEntityManager().persist(openContract);
ConnectionUtil.getEntityManager().persist(selectedCustomer);
Actions actions = new Actions();
actions.setActionDate(LocalDate.now().toString() + " " + LocalTime.now().toString());
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
actions.setActionInfo("New OPEN CONTRACT added");
} else {
actions.setActionInfo(" تم فتح عقد جديد بنجاح");
}
actions.setActionUser(UserSession.getInstance().getUsername());
ConnectionUtil.getEntityManager().persist(actions);
if(!ConnectionUtil.getEntityManager().getTransaction().isActive()){
ConnectionUtil.getEntityManager().getTransaction().begin();
}
ConnectionUtil.getEntityManager().getTransaction().commit();
ConnectionUtil.getEntityManager().refresh(openContract);
customerRadio.setDisable(true);
carRadio.setDisable(true);
customerSearch.setDisable(true);
carSearch.setDisable(true);
startDate.setEditable(true);
endDate.setEditable(true);
paymentCombo.setEditable(true);
taxCombo.setEditable(true);
pricePerDayField.setDisable(true);
downPaymentField.setDisable(true);
depositField.setDisable(true);
allowedMileageField.setDisable(true);
currentMileageField.setDisable(true);
currentFuelField.setDisable(true);
closingCombo.setDisable(true);
openingCombo.setDisable(true);
if (InterfaceLanguage.getInstance().getLanguage() == Language.ENGLISH) {
new InfoMessage("Done", "Congrats new OPEN CONTRACT added").show();
} else {
new InfoMessage("تمت العملية بنجاح", "مبروك تم فتح عقد جديد بنجاح").show();
}
OpenContract numb = ConnectionUtil.getEntityManager().createQuery("select o from OpenContract o where o.startDate = :a and o.expectedEndDate = :b and o.car = :c ",OpenContract.class).setParameter("a",startDate.getValue()).setParameter("b",endDate.getValue()).setParameter("c",selectedCar).getSingleResult();
long contNumb = numb.getOpenContractId();
CreatePdf createPdf = new CreatePdf(
// TODO create static contract number & issue place
contNumb,
selectedCustomer.getFirstName() + " " + selectedCustomer.getMiddleName() + " " + selectedCustomer.getLastName(),
selectedCustomer.getCountry().getCountryName() + "",
selectedCustomer.getBirthDate() + "",
selectedCustomer.getLicenseNumber() + "",
selectedCustomer.getLicenseCountry().getCountryName()+"",
selectedCustomer.getLicenseExpirationDate() + "",
(clientDriver.getFirstName()==null ? "-" : clientDriver.getFirstName()) + " " + (clientDriver.getMiddleName()==null ? "-" : clientDriver.getMiddleName()) + " " + (clientDriver.getLastName()==null ? "-" :clientDriver.getLastName()),
(clientDriver.getLicenseNumber()==null ? "-" : clientDriver.getLicenseNumber()) + "",
(clientDriver.getLicenseExpiration()==null ? "-" : clientDriver.getLicenseExpiration()) + "",
selectedCustomer.getPhoneNumber() + "",
selectedCustomer.getAddress() + "",
//selectedCar.getCarInsurance().getCarInsuranceType() + "",
selectedCar.getPlateNumber() + "",
selectedCar.getModel().getCarModel().getModelName() + "",
selectedCar.getModel().getSubModelType() + "",
selectedCar.getCarColor().getColorName() + "",
startDate.getValue().toString() + "",
endDate.getValue() + "",
DateUtil.getCurrentHour() + "",
currentMileageField.getText() + "",
endDate.getValue().toString() + "",
totalDurationLabel.getText() + "",
pricePerDayField.getText() + "",
depositField.getText() + "",
priceLabel.getText() + "",
taxLabel.getText() + "",
finalPriceLabel.getText() + "",
String.
valueOf(remainingCustomerCredit
+ Double.
parseDouble(downPaymentField.
getText()))+ " JD",
remainingAmountLabel.getText() + "",
numb.getExpectedEndHour() + ""
);
try {
createPdf.printReport();
}
ConnectionUtil.getEntityManager().refresh(openContract);
// to close the scene
Stage stagePrev = (Stage) rentBtn.getScene().getWindow();
stagePrev.close();
}
}
searchPane.setVisible(false);
secondDiverPane.setVisible(true);
}
secondDiverPane.setVisible(false);
searchPane.setVisible(true);
customerScroll.setDisable(false);
customerSearch.setDisable(false);
customerRadio.setDisable(false);
customerScroll.setVisible(false);
}
private static boolean checkNumber
(String emailStr
) { Matcher matcher = VALID_PHONE_NUMBER_REGEX.matcher(emailStr);
return matcher.find();
}
private static boolean checkString
(String emailStr
) { Matcher matcher = VALID_STRING_REGEX.matcher(emailStr);
return matcher.find();
}
}
//TODO
// Date localDate = Date.valueOf(LocalDate.now());
// long x = ((localDate.getTime()) - (Date.valueOf(endDate.getValue()).getTime()) /(-60 * 60 * 24 * 1000));
// totalExtraDaysLabel.setText("");
//
//// if ((Date.valueOf(LocalDate.now()).getTime()) <= (Date.valueOf(endDate.getValue()).getTime()) ){
//// System.out.println("no");
//// }