diff --git a/DeleteEmployeeConsole.java b/DeleteEmployeeConsole.java new file mode 100644 index 0000000..ccaef29 --- /dev/null +++ b/DeleteEmployeeConsole.java @@ -0,0 +1,64 @@ +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Optional; +import java.util.Scanner; + +/** PT4 console-menu interaction. Pass a role from a real authenticated session. */ +public final class DeleteEmployeeConsole { + private DeleteEmployeeConsole() { } + + public static void run(Scanner scanner, Connection connection, UserRole authenticatedRole) { + if (authenticatedRole != UserRole.HR_ADMIN) { + System.out.println("Access denied. HR Administrator privileges are required."); + return; + } + + System.out.print("Enter Employee ID to delete: "); + String rawId = scanner.nextLine().trim(); + final int empID; + try { + empID = Integer.parseInt(rawId); + if (empID <= 0) throw new NumberFormatException(); + } catch (NumberFormatException ex) { + System.out.println("Invalid employee ID. Enter a positive whole number."); + return; + } + + EmployeeDeletionService service = new EmployeeDeletionService(connection); + try { + Optional result = + service.findById(empID, authenticatedRole); + if (!result.isPresent()) { + System.out.println("No matching employee found."); + return; + } + + EmployeeDeletionService.EmployeeSummary employee = result.get(); + System.out.println("Employee found:"); + System.out.println("ID: " + employee.empID); + System.out.println("Name: " + employee.firstName + " " + employee.lastName); + System.out.println("WARNING: Deletion also removes this employee's payroll history, " + + "address, demographics, division, and job assignments."); + System.out.print("Are you sure you want to delete this employee? (Y/N): "); + String confirm = scanner.nextLine().trim(); + if (confirm.equalsIgnoreCase("N")) { + System.out.println("Deletion canceled."); + return; + } + + if (!confirm.equalsIgnoreCase("Y")) { + System.out.println("Invaild input. Please enter Y or N."); + return; + } + + if (service.deleteEmployee(empID, authenticatedRole)) { + System.out.println("Employee successfully deleted."); + } else { + System.out.println("Employee no longer exists; nothing was deleted."); + } + } catch (SQLException ex) { + System.out.println("Deletion failed. Database changes were rolled back."); + System.err.println("Database error: " + ex.getMessage()); + } + } +} diff --git a/EmployeeDeletionService.java b/EmployeeDeletionService.java new file mode 100644 index 0000000..ce66c98 --- /dev/null +++ b/EmployeeDeletionService.java @@ -0,0 +1,117 @@ +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Optional; + +/** Database operations for PT4. Uses an existing JDBC connection from the application. */ +public final class EmployeeDeletionService { + private final Connection connection; + + public EmployeeDeletionService(Connection connection) { + if (connection == null) throw new IllegalArgumentException("Connection is required"); + this.connection = connection; + } + + /** Lightweight record: never display SSN or other sensitive attributes in confirmation. */ + public static final class EmployeeSummary { + public final int empID; + public final String firstName; + public final String lastName; + + EmployeeSummary(int empID, String firstName, String lastName) { + this.empID = empID; + this.firstName = firstName; + this.lastName = lastName; + } + } + + /** Retrieve the employee for the confirmation prompt. */ + public Optional findById(int empID, UserRole role) throws SQLException { + checkAdmin(role); + if (empID <= 0) throw new IllegalArgumentException("Employee ID must be positive"); + String sql = "SELECT empID, Fname, Lname FROM employees WHERE empID = ?"; + try (PreparedStatement ps = connection.prepareStatement(sql)) { + ps.setInt(1, empID); + try (ResultSet rs = ps.executeQuery()) { + if (!rs.next()) return Optional.empty(); + return Optional.of(new EmployeeSummary( + rs.getInt("empID"), rs.getString("Fname"), rs.getString("Lname"))); + } + } + } + + /** + * Permanently delete one employee and its child rows as a single transaction. + * HR authorization must originate from the application's authenticated session. + * Caller must pass an ordinary, non-transactional JDBC connection (autoCommit=true). + * Throws on failure, and rolls back all deletes. + */ + public boolean deleteEmployee(int empID, UserRole role) throws SQLException { + checkAdmin(role); + if (empID <= 0) throw new IllegalArgumentException("Employee ID must be positive"); + if (!connection.getAutoCommit()) { + throw new SQLException("Deletion requires a connection with autoCommit enabled"); + } + + connection.setAutoCommit(false); + try { + // Lock target employee while deleting; avoids conflicting writes to the row. + if (!employeeExistsForUpdate(empID)) { + connection.rollback(); + return false; + } + + // Delete children first, because the MySQL foreign keys may restrict parent deletion. + deleteChildren("DELETE FROM payroll WHERE empID = ?", empID); + deleteChildren("DELETE FROM employee_job_titles WHERE empID = ?", empID); + deleteChildren("DELETE FROM employee_division WHERE empid = ?", empID); + deleteChildren("DELETE FROM demographics WHERE empID = ?", empID); + deleteChildren("DELETE FROM addresses WHERE empID = ?", empID); + + int deleted; + try (PreparedStatement ps = connection.prepareStatement( + "DELETE FROM employees WHERE empID = ?")) { + ps.setInt(1, empID); + deleted = ps.executeUpdate(); + } + if (deleted != 1) { + throw new SQLException("Expected exactly one employee deletion, got " + deleted); + } + connection.commit(); + return true; + } catch (SQLException | RuntimeException ex) { + try { + connection.rollback(); + } catch (SQLException rollbackError) { + ex.addSuppressed(rollbackError); + } + throw ex; + } finally { + connection.setAutoCommit(true); + } + } + + private boolean employeeExistsForUpdate(int empID) throws SQLException { + try (PreparedStatement ps = connection.prepareStatement( + "SELECT empID FROM employees WHERE empID = ? FOR UPDATE")) { + ps.setInt(1, empID); + try (ResultSet rs = ps.executeQuery()) { + return rs.next(); + } + } + } + + private void deleteChildren(String sql, int empID) throws SQLException { + try (PreparedStatement ps = connection.prepareStatement(sql)) { + ps.setInt(1, empID); + ps.executeUpdate(); + } + } + + private static void checkAdmin(UserRole role) { + if (role != UserRole.HR_ADMIN) { + throw new SecurityException("Only HR Administrators may delete employees"); + } + } +} diff --git a/UserRole.java b/UserRole.java new file mode 100644 index 0000000..c8c1b78 --- /dev/null +++ b/UserRole.java @@ -0,0 +1,5 @@ +/** Roles assigned by the application's authenticated session. */ +public enum UserRole { + HR_ADMIN, + EMPLOYEE +}