package com.cartunesks.casa_pos; import java.io.IOException; import java.time.LocalDate; import java.util.Collections; import java.util.Comparator; import java.util.function.Consumer; import java.util.stream.Collectors; import org.controlsfx.control.Notifications; import org.controlsfx.control.textfield.TextFields; import org.kordamp.ikonli.javafx.FontIcon; import com.cartunesks.casa_pos.util.AppUtils; import com.cartunesks.casa_pos.util.Operator; import com.cartunesks.casa_pos.util.PopupUtils; import com.cartunesks.casa_pos.util.database.DatabaseConnection; import com.cartunesks.casa_pos.util.database.DatabaseInitializer; import com.cartunesks.casa_pos.util.database.SimpleCypher; import com.cartunesks.casa_pos.util.format.PositiveIntegerStringConverter; import entities.AutoCompleteClient; import entities.Client; import entities.ClientsController; import entities.Employee; import entities.EmployeesController; import entities.FinancersController; import entities.NewClientController; import entities.Permission; import entities.VendorsController; import inventory.AutoCompModelQty; import inventory.Inventory; import inventory.InventoryController; import inventory.MasterDataController; import inventory.NewInventoryController; import invoices.Invoice; import invoices.InvoicesController; import invoices.NewInvoiceController; import items.Item; import items.ItemInfoController; import items.ItemsController; import items.ItemsControllerMode; import javafx.beans.binding.Bindings; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TextField; import javafx.scene.control.TextFormatter; import orders.NewOrderController; import orders.NewReturnController; import orders.Order; import orders.OrderType; import orders.OrdersController; import payments.Payment; import payments.PaymentInfoController; import payments.PaymentsController; import payments.TaxesController; import schedule.ScheduleController; public class PrimaryController { @FXML private Button loginButton; @FXML private FontIcon loginFontIcon, userFontIcon; private final ObservableList autoCompleteModels = FXCollections.observableArrayList(); private final ObservableList autoCompleteClients = FXCollections.observableArrayList(); private final static ObjectProperty USER = new SimpleObjectProperty<>(); @FXML private void initialize(){ if (DatabaseConnection.isConnectionAvailable()) { // Initialize database enums before launching the application DatabaseInitializer.initializeEnums(); } else { PopupUtils.loadPopup(DatabaseConfigController.class, "DatabaseConfig", "Connect to Database"); } loginButton.textProperty().bind( Bindings.createStringBinding( () -> getUser() == null ? "Login" : getUser().getName(), userProperty() ) ); loginFontIcon.visibleProperty().bind(USER.isNull()); userFontIcon.visibleProperty().bind(loginFontIcon.visibleProperty().not()); TextFields .bindAutoCompletion(modelQuickSearchTextField, input -> { if (input.getUserText().length() < 2) { return Collections.emptyList(); } return autoCompleteModels.stream() .filter(s -> s.model().contains(input.getUserText().toUpperCase())) .sorted(Comparator.comparingInt(s -> s.model().length())) .collect(Collectors.toList()); }) .setOnAutoCompleted( e -> { String model = e.getCompletion().model(); openExistingInventory(SimpleCypher.getInventoryByModel(model)); modelQuickSearchTextField.clear(); }); TextFields .bindAutoCompletion(clientQuickSearchTextField, input -> { if (input.getUserText().length() < 2) { return Collections.emptyList(); } return autoCompleteClients.stream().filter(s -> s.getName().toLowerCase().contains(input.getUserText().toLowerCase())).collect(Collectors.toList()); }) .setOnAutoCompleted( e -> { openExistingClient(SimpleCypher.getClientData(e.getCompletion().getId())); clientQuickSearchTextField.clear(); }); invoiceTextField.setTextFormatter(new TextFormatter<>(new PositiveIntegerStringConverter())); orderTextField.setTextFormatter(new TextFormatter<>(new PositiveIntegerStringConverter())); var stores = SimpleCypher.getStores(); if (stores.isEmpty()) { PopupUtils.showErrorPopup( "Create A Store", """ A Store must be created to create Inventory items, Orders, and Invoices! Create a store now to use CASA. The tab for creating a store will appear upon acknowledgement of this error. """ ); openStoresForFirstCreation(); } else if (stores.stream().noneMatch(store -> store.getId() == ConfigManager.getDefaultStoreId())) { PopupUtils.showErrorPopup( "Set Default Store", """ Each device must designate a default Store. The default store can be changed at any time. The popup for selecting your default store will appear upon acknowledgement of this error. """ ); openSettingsForInvalidStore(); } } // FXML by default will run the method called initialize() if it public or annotated @FXML // Therefore, any initializing methods that are ran from primary controller must be renamed // to init() otherwise the method will run as soon as the fxml is loaded, hence it runs twice @FXML TabPane contentTabPane; public void openTab(Class controllerClass, String fxmlPath, String tabName, Permission permission) { if (PopupUtils.checkPermission(permission)) openTab(controllerClass, fxmlPath, tabName); } public void openTab(Class controllerClass, String fxmlPath, String tabName, Consumer controllerSetup, Permission permission) { if (PopupUtils.checkPermission(permission)) openTab(controllerClass, fxmlPath, tabName, controllerSetup); } //Standard method public void openTab(Class controllerClass, String fxmlPath, String tabName) { try { FXMLLoader loader = new FXMLLoader(controllerClass.getResource(fxmlPath + ".fxml")); Node node = loader.load(); Tab tab = new Tab(tabName); tab.setContent(node); contentTabPane.getTabs().add(tab); contentTabPane.getSelectionModel().select(tab); } catch (IOException e) { e.printStackTrace(); } } //Overloaded method for setting up controllers when neccessary public void openTab(Class controllerClass, String fxmlPath, String tabName, Consumer controllerSetup) { try { FXMLLoader loader = new FXMLLoader(controllerClass.getResource(fxmlPath + ".fxml")); Node node = loader.load(); T controller = loader.getController(); controllerSetup.accept(controller); // Perform custom setup actions Tab tab = new Tab(tabName); tab.setContent(node); contentTabPane.getTabs().add(tab); contentTabPane.getSelectionModel().select(tab); } catch (IOException e) { e.printStackTrace(); } } @FXML private void clockInOrOut() { PopupUtils.loadPopup( ClockInController.class , "ClockIn" , "Employee Clock In/Out" ); } @FXML private void loginOrSignOut() { if (getUser() == null) { Employee newUser = PopupUtils.loadPopup( SignInController.class, "SignIn", "Sign In", null, SignInController::getUser ); if (newUser != null) { UserSession.startSession(newUser); } } else { UserSession.stopSession(); } } public static ObjectProperty userProperty() { return USER; } public static Employee getUser() { return userProperty().get(); } public static void setUser(Employee newUser) { userProperty().set(newUser); } public void clearTabs() { contentTabPane.getTabs().clear(); } public void openInvoices() { openTab( InvoicesController.class , "Invoices" , "Search Invoices" , con -> { con.setPrimaryController(this); con.init(); con.getInvoiceFiltersController().fromDatePicker.setValue(LocalDate.now()); con.search(); } ); } public void openInvoicesByModel(String model) { openTab( InvoicesController.class , "Invoices" , "Search Invoices", con -> { con.setPrimaryController(this); con.init(); con.getInvoiceFiltersController().modelOperatorChoiceBox.setValue(Operator.EQUALS); con.getInvoiceFiltersController().modelTextField.setText(model); con.getInvoiceFiltersController().fromDatePicker.setValue(LocalDate.now().minusYears(1)); con.search(); } ); } public void openInvoicesByClient(String clientName) { openTab( InvoicesController.class , "Invoices" , "Search Invoices" , con -> { con.setPrimaryController(this); con.init(); con.getInvoiceFiltersController().anonymousCheckBox.setSelected(false); con.getInvoiceFiltersController().nameOperatorChoiceBox.setValue(Operator.EQUALS); con.getInvoiceFiltersController().nameTextField.setText(clientName); con.getInvoiceFiltersController().fromDatePicker.setValue(LocalDate.now().minusYears(1)); con.search(); } ); } public void openNewInvoice() { openTab( NewInvoiceController.class, "NewInvoice", "New Invoice", con -> { con.setPrimaryController(this); con.init(); }, Permission.active //use active to just do a general check that someone is logged in ); } public void openExistingInvoice(Invoice selectedInvoice) { openTab( NewInvoiceController.class, "NewInvoice", "Invoice #" + selectedInvoice.getInvoiceNum() + (selectedInvoice.getClient() == null ? "" : ": " + selectedInvoice.getClient().getName()), con -> { con.setPrimaryController(this); con.setInvoice(selectedInvoice); con.init(); con.cancel(); //populates invoice and disables form for initial state } ); } public void openFinancers() { openTab(FinancersController.class, "Financers", "Financers", Permission.openFinancers); } @FXML public void openClients() { openTab( ClientsController.class , "Clients" , "Search Clients" , con -> con.setPrimaryController(this) ); } public void openNewClient() { openTab(NewClientController.class,"NewClient","Add New Client"); } public void openExistingClient(Client existingClient) { openTab(NewClientController.class, "NewClient", "Client: " + existingClient.getName(), controller -> { controller.setPrimaryController(this); controller.populateExistingClient(existingClient); } ); } public void openInventory() { openTab( InventoryController.class , "Inventory" , "Inventory" , inventoryController -> inventoryController.setPrimaryController(this) ); } public void openExistingInventory(Inventory selectedInv) { openTab(NewInventoryController.class, "NewInventory", "Edit " + selectedInv.getModel(), controller -> { controller.setInventory(selectedInv); controller.init(); controller.populateInventory(); controller.setPrimaryController(this); }); } public void openNewInventory() { openTab(NewInventoryController.class, "NewInventory", "Add New Inventory", controller -> { controller.init(); controller.setPrimaryController(this); }); } public void openItems() { openTab( ItemsController.class, "Items", "Itemized Inventory", controller -> { controller.setPrimaryController(this); controller.setMode(ItemsControllerMode.STANDARD); }); } public void openItemsByModel(String model) { openTab(ItemsController.class, "Items", "Itemized Inventory", controller -> { controller.setPrimaryController(this); controller.setMode(ItemsControllerMode.STANDARD); controller.getItemFiltersController().modelOperatorChoiceBox.setValue(Operator.EQUALS); controller.getItemFiltersController().modelTextField.setText(model); controller.search(); }); } public void openExistingItem(Item selectedItem) { openTab( ItemInfoController.class , "ItemInfo" , "Item Info: " + selectedItem.getModel() , controller -> controller.populateItem(selectedItem) ); } public void openVendors() { openTab(VendorsController.class, "Vendors", "Vendors", Permission.openVendors); } public void openOrders() { openTab( OrdersController.class, "Orders", "Search Orders", ordersController -> { ordersController.setPrimaryController(this); ordersController.init(); ordersController.getOrderFiltersController().fromDatePicker.setValue(LocalDate.now().minusMonths(1)); ordersController.search(); } ); } public void openOrdersByModel(String model) { openTab( OrdersController.class, "Orders", "Search Orders", ordersController -> { ordersController.setPrimaryController(this); ordersController.init(); ordersController.getOrderFiltersController().modelOperatorChoiceBox.setValue(Operator.EQUALS); ordersController.getOrderFiltersController().modelTextField.setText(model); ordersController.getOrderFiltersController().fromDatePicker.setValue(LocalDate.now().minusYears(1)); ordersController.search(); } ); } public void openNewOrder() { openTab(NewOrderController.class, "NewOrder", "New Order", controller -> { controller.setPrimaryController(this); controller.init(); }, Permission.createOrder ); } public void openExistingOrder(Order existingOrder) { openTab(NewOrderController.class, "NewOrder", "View Order #" + existingOrder.getOrderNum(), controller -> { controller.setPrimaryController(this); controller.setOrder(existingOrder); controller.init(); controller.populateExistingOrder(existingOrder); } ); } public void openNewReturn() { openTab(NewReturnController.class, "NewReturn", "New Return", controller -> { controller.setPrimaryController(this); controller.init(); }, Permission.createOrder ); } public void openExistingReturn(Order ExistingReturn) { openTab(NewReturnController.class, "NewReturn", "View Return #" + ExistingReturn.getOrderNum(), controller -> { controller.setPrimaryController(this); controller.setOrder(ExistingReturn); controller.init(); controller.populateExistingReturn(ExistingReturn); } ); } public void openPayments() { openTab( PaymentsController.class, "Payments", "Payments", con -> { con.setPrimaryController(this); con.init(); con.getFilterController().setDefaultFilters(); con.search(); } , Permission.openPayments ); } public void openPaymentsByEntity(int entityId) { openTab( PaymentsController.class, "Payments", "Payments", con -> { con.setPrimaryController(this); con.init(); con.getFilterController().getEntityIdFormatter().setValue(entityId); con.search(); } , Permission.openPayments ); } public void openExistingPayment(Payment p) { openTab( PaymentInfoController.class, "PaymentInfo", p.toString(), con -> { con.setPayment(p); } , Permission.openPayments ); } @FXML private void openTaxes() { openTab(TaxesController.class, "Taxes", "Taxes", Permission.openTaxes); } @FXML private void openEmployees() { openTab(EmployeesController.class, "Employees", "Employees", Permission.openEmployees); } @FXML private void openStoresForFirstCreation() { openTab(EmployeesController.class, "Stores", "Stores"); } @FXML private void openStores() { openTab(EmployeesController.class, "Stores", "Stores", Permission.openStores); } @FXML private void openMasterData() { openTab(MasterDataController.class, "MasterData", "Master Data", Permission.openMasterData); } @FXML private void openSchedule() { Tab tab = new Tab("Schedule"); ScheduleController scheduleController = new ScheduleController(this); //Instantiating the controller creates and populates the Calendar // Remove the default calendar.css stylesheet Node calendarView = scheduleController.getCalendarView(); calendarView.getStyleClass().removeIf(stylesheet -> stylesheet.contains("calendar.css")); tab.setContent(calendarView); contentTabPane.getTabs().add(tab); contentTabPane.getSelectionModel().select(tab); // How to create a new resource calendar view (don't forget to uncomment the import): //ResourceCalendarView resourceCalendarView = new ResourceCalendarView<>(); } //Don't check permission because it is needed private void openSettingsForInvalidStore() { PopupUtils.loadPopup( SettingsController.class , "Settings" , "CASA Application Settings" ); } @FXML private void openSettings() { PopupUtils.loadPopup( SettingsController.class , "Settings" , "CASA Application Settings" , Permission.openSettings ); } @FXML private TextField invoiceTextField; //TextField On Action @FXML private void searchInvoice() { try { int invoiceNum = Integer.parseInt(invoiceTextField.getText()); Invoice inv = SimpleCypher.getInvoiceData(invoiceNum); if (inv != null) openExistingInvoice(inv); } catch (NumberFormatException nfe) { Notifications.create() .title("Invalid Invoice Search Input") .text("You must enter an integer invoice number to perform an Invoice Quick Search.") .showError(); } invoiceTextField.clear(); } @FXML private TextField orderTextField; //TextField On Action @FXML private void searchOrder() { try { int orderNum = Integer.parseInt(orderTextField.getText()); Order order = SimpleCypher.getOrderData(orderNum); if (order != null) { if (order.getType() == OrderType.RETURN_ORDER) openExistingReturn(order); else openExistingOrder(order); } } catch (NumberFormatException nfe) { Notifications.create() .title("Invalid Order Search Input") .text("You must enter an integer order number to perform an Order Quick Search.") .showError(); } orderTextField.clear(); } //TextField On Key Typed @FXML TextField modelQuickSearchTextField; @FXML private void modelAutoComplete() { String input = modelQuickSearchTextField.getText().toUpperCase(); if (input.length() == 2) { var queryTask = SimpleCypher.getModelQtyAutoComplete(input); queryTask.setOnSucceeded(event -> autoCompleteModels.setAll(queryTask.getValue())); // Start the task asynchronously Thread queryThread = new Thread(queryTask); queryThread.setDaemon(true); // Set as daemon thread to allow application exit queryThread.start(); } } //TextField On Key Typed @FXML TextField clientQuickSearchTextField; @FXML private void clientAutoComplete() { AppUtils.clientAutoComplete(clientQuickSearchTextField, autoCompleteClients); } //modelQuickSearchTextField On Action @FXML private void upcSearch() { String upcInput = modelQuickSearchTextField.getText(); Inventory inventory = SimpleCypher.getInventoryByUpc(upcInput); if (inventory != null) openExistingInventory(inventory); modelQuickSearchTextField.clear(); } @FXML private void lightMode() { Scene scene = loginButton.getScene(); if (scene != null) { scene.getRoot().getStyleClass().remove("dark-mode"); } App.isDarkModeEnabled = false; } @FXML private void darkMode() { Scene scene = loginButton.getScene(); if (scene != null) { if (!scene.getRoot().getStyleClass().contains("dark-mode")) { scene.getRoot().getStyleClass().add("dark-mode"); } } App.isDarkModeEnabled = true; } @FXML private void popDrawer() { boolean result = CashDrawerService.popDrawer(); if (result) { Notifications.create() .title("Cash Drawer") .text("Drawer popped successfully.") .showInformation(); } else { Notifications.create() .title("Cash Drawer Error") .text("Failed to pop the cash drawer. Check settings and hardware.") .showError(); } } }