diff --git a/src/main/java/model/DAO/DAOLicense.java b/src/main/java/model/DAO/DAOLicense.java index 758730d..dafa613 100644 --- a/src/main/java/model/DAO/DAOLicense.java +++ b/src/main/java/model/DAO/DAOLicense.java @@ -95,4 +95,108 @@ public void activate(License license, int userId) { } } } + + /** + * Generate a new License to sell + * @return the sequence of the License if operation succeed, none otherwise + */ + public String generateLicense(){ + final int length = 8; + License l = new License(length); + String insertQuery = "INSERT INTO TalkAID2.license (Sequence, ID_User, ExpirationDate) VALUES (?, ?, ?);"; + Connection connection = null; + PreparedStatement preparedStatement = null; + + try { + connection = DAOConnection.getConnection(); + preparedStatement = connection.prepareStatement(insertQuery); + preparedStatement.setString(1, l.getSequence()); + preparedStatement.setInt(2, 0); + preparedStatement.setDate(3, null); + preparedStatement.executeUpdate(); + return l.getSequence(); + } catch (SQLException e) { + e.printStackTrace(); + return null; + } finally { + try { + if (preparedStatement != null) preparedStatement.close(); + DAOConnection.releaseConnection(connection); + } catch (SQLException e) { + // Handle the exception (e.g., log or throw) + e.printStackTrace(); + } + } + } + + + /** + * Generate an invitation code for a new patient + * @param userId the ID of a speech therapist + * @return the sequence of the invitation if operation succeed, none otherwise + */ + public String generateInvitation(int userId){ + final int length = 4; + License l = new License(length); + String insertQuery = "INSERT INTO TalkAID2.license (Sequence, ID_User, ExpirationDate) VALUES (?,?,?);"; + Connection connection = null; + PreparedStatement preparedStatement = null; + + try { + connection = DAOConnection.getConnection(); + preparedStatement = connection.prepareStatement(insertQuery); + preparedStatement.setString(1, l.getSequence()); + preparedStatement.setInt(2, userId); + preparedStatement.setDate(3, l.getExpirationDate()); + preparedStatement.executeUpdate(); + return l.getSequence(); + } catch (SQLException e) { + e.printStackTrace(); + return null; + } finally { + try { + if (preparedStatement != null) preparedStatement.close(); + DAOConnection.releaseConnection(connection); + } catch (SQLException e) { + // Handle the exception (e.g., log or throw) + e.printStackTrace(); + } + } + } + + public boolean deleteLicense(String code) { + Connection connection = null; + PreparedStatement preparedStatement = null; + + try { + // Get database connection + connection = DAOConnection.getConnection(); + + // Prepare the SQL query + String query = "DELETE FROM TalkAID2.license WHERE Sequence = ?"; + preparedStatement = connection.prepareStatement(query); + + // Set parameter for the prepared statement + preparedStatement.setString(1, code); + + // Execute update and return boolean based on the affected rows + int rowsAffected = preparedStatement.executeUpdate(); + return rowsAffected > 0; + + } catch (SQLException e) { + e.printStackTrace(); + } finally { + // Close the statement and release the connection + try { + if (preparedStatement != null) preparedStatement.close(); + DAOConnection.releaseConnection(connection); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + // If exception occurs, return false + return false; + } + } \ No newline at end of file diff --git a/src/main/java/model/DAO/DAOPersonalInfo.java b/src/main/java/model/DAO/DAOPersonalInfo.java index 9dbb2a1..a171f9d 100644 --- a/src/main/java/model/DAO/DAOPersonalInfo.java +++ b/src/main/java/model/DAO/DAOPersonalInfo.java @@ -96,5 +96,45 @@ public PersonalInfo getPersonalInfo(int id) { return null; // Return null if personal_info does not exist } + + public boolean deleteRegistry(int createdUserId) { + Connection connection = null; + PreparedStatement preparedStatement = null; + + try { + connection = DAOConnection.getConnection(); + connection.setAutoCommit(false); // Start a transaction + + String sql = "DELETE FROM personal_info WHERE ID_user = ?"; + preparedStatement = connection.prepareStatement(sql); + preparedStatement.setInt(1, createdUserId); + int rowAffected = preparedStatement.executeUpdate(); + + connection.commit(); // Commit the transaction + + return rowAffected > 0; // Return true if the deletion was successful + + } catch (SQLException e) { + // Handle the exception (e.g., log or throw) + e.printStackTrace(); + try { + if (connection != null) { + connection.rollback(); // Rollback the transaction in case of an exception + } + } catch (SQLException ex) { + ex.printStackTrace(); + } + } finally { + try { + if (preparedStatement != null) preparedStatement.close(); + DAOConnection.releaseConnection(connection); + } catch (SQLException e) { + // Handle the exception (e.g., log or throw) + e.printStackTrace(); + } + } + + return false; // Default to false if an exception occurs + } } diff --git a/src/main/java/model/DAO/DAOUser.java b/src/main/java/model/DAO/DAOUser.java index cfa5fa2..ed611e0 100644 --- a/src/main/java/model/DAO/DAOUser.java +++ b/src/main/java/model/DAO/DAOUser.java @@ -331,4 +331,47 @@ public boolean updateEmailTime(String id, String value) { // Default to false if an exception occurs return false; } + + /** + * Deletes a user from the User table based on an ID or an email. + * + * @param idOrEmail Either an Integer representing the User's ID or a String representing the User's email. + * @return true if the user was successfully deleted; false otherwise. + */ + public boolean deleteUserByIdOrEmail(Object idOrEmail) { + Connection connection = null; + PreparedStatement preparedStatement = null; + + try { + connection = DAOConnection.getConnection(); + String query = null; + + if (idOrEmail instanceof Integer) { + query = "DELETE FROM user WHERE ID = ?"; + } else if (idOrEmail instanceof String) { + query = "DELETE FROM user WHERE Email = ?"; + } + + preparedStatement = connection.prepareStatement(query); + preparedStatement.setObject(1, idOrEmail); + + int rowsDeleted = preparedStatement.executeUpdate(); + + return rowsDeleted > 0; + } catch (SQLException e) { + // Handle the exception (e.g., log or throw) + e.printStackTrace(); + } finally { + try { + if (preparedStatement != null) preparedStatement.close(); + DAOConnection.releaseConnection(connection); + } catch (SQLException e) { + // Handle the exception (e.g., log or throw) + e.printStackTrace(); + } + } + + // Default to false if an exception occurs + return false; + } } diff --git a/src/main/java/model/entity/License.java b/src/main/java/model/entity/License.java index e9716be..259d96a 100644 --- a/src/main/java/model/entity/License.java +++ b/src/main/java/model/entity/License.java @@ -1,6 +1,8 @@ package model.entity; +import java.security.SecureRandom; import java.sql.Date; +import java.time.LocalDate; public class License { private String sequence; @@ -8,6 +10,16 @@ public class License { private Date expirationDate; private boolean active; + public License() {} + //Constructor for creating a pin or a license based on n + public License(int n){ + this.sequence = generatePin(n); + if (n == 4){ + LocalDate d = LocalDate.now(); + d = d.plusDays(7); + this.expirationDate = java.sql.Date.valueOf(d); + } + } // Getter and Setter methods public String getSequence() { @@ -41,4 +53,23 @@ public boolean isActive() { public void setActive(boolean active) { this.active = active; } + + private String generatePin(int n){ + SecureRandom random = new SecureRandom(); + + String digits; + + if(n==4){ + digits = "0123456789"; + }else{ + digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + } + + StringBuilder pin = new StringBuilder(); + for(int i = 0; i < n; i++) { + pin.append(digits.charAt(random.nextInt(digits.length()))); + } + + return pin.toString(); + } } diff --git a/src/main/java/model/service/license/LicenseActivation.java b/src/main/java/model/service/license/LicenseActivation.java index 4b6ed54..644e21b 100644 --- a/src/main/java/model/service/license/LicenseActivation.java +++ b/src/main/java/model/service/license/LicenseActivation.java @@ -31,14 +31,11 @@ public void activate(License license, int userId) { daoLicense.activate(license, userId); } - public void generatePin(int therapistId) { - //TODO - // Implement the logic to generate a new license with a 4-character pin - // and associate it with the provided therapistId + public String generatePin(int therapistId) { + return daoLicense.generateInvitation(therapistId); } - public void generateLicense() { - //TODO - // Implement the logic to generate a new license with 8 characters and therapistId 0 + public String generateLicense() { + return daoLicense.generateLicense(); } } \ No newline at end of file diff --git a/src/main/java/model/service/license/LicenseActivationInterface.java b/src/main/java/model/service/license/LicenseActivationInterface.java index 5ef6887..38c1cf9 100644 --- a/src/main/java/model/service/license/LicenseActivationInterface.java +++ b/src/main/java/model/service/license/LicenseActivationInterface.java @@ -39,11 +39,11 @@ public interface LicenseActivationInterface { * * @param therapistId รจ l'identificativo del terapeuta */ - void generatePin(int therapistId); + String generatePin(int therapistId); /** * genera una nuova licenza da 8 caratteri e con ID terapeuta 0 */ - void generateLicense(); + String generateLicense(); } \ No newline at end of file diff --git a/src/test/java/model/DAO/DAOLicenseTest.java b/src/test/java/model/DAO/DAOLicenseTest.java new file mode 100644 index 0000000..7ec3330 --- /dev/null +++ b/src/test/java/model/DAO/DAOLicenseTest.java @@ -0,0 +1,98 @@ +package model.DAO; + +import model.entity.License; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.sql.SQLException; + +import static org.junit.jupiter.api.Assertions.*; + +class DAOLicenseTest { + + private DAOLicense daoLicense; + private String generatedLicense; + private String generatedInvitation; + + @BeforeEach + void setup() { + daoLicense = new DAOLicense(); + } + + @Test + void testGetLicenseByCode() { + // Mock the license code + String code = "0D47AB8F"; + + // Call the method to test + License license = daoLicense.getLicenseByCode(code); + + // Check the returned license + assertNotNull(license, "License should not be null"); + assertEquals(code, license.getSequence(), "Sequence should match"); + // Add more assertions based on your specific requirements + } + + @Test + void testGenerateLicense() { + // Call the method to generate a license + generatedLicense = daoLicense.generateLicense(); + + // Check if the generated license sequence is not null + assertNotNull(generatedLicense, "Generated license sequence should not be null"); + assertEquals(8, generatedLicense.length(), "Generated license sequence should have the specified length"); + + boolean result1 = daoLicense.deleteLicense(generatedLicense); + assertTrue(result1, "The license should be deleted"); + + boolean result3 = daoLicense.deleteLicense(generatedLicense); + assertFalse(result3, "The license can't be deleted"); + } + + @Test + void testGenerateInvitation() { + // Mock therapist ID + int therapistId = 123; + + // Call the method to generate an invitation + generatedInvitation = daoLicense.generateInvitation(therapistId); + + // Check if the generated invitation sequence is not null + assertNotNull(generatedInvitation, "Generated invitation sequence should not be null"); + assertEquals(4, generatedInvitation.length(), "Generated invitation sequence should have the specified length"); + // Additional assertions if needed + + boolean result2 = daoLicense.deleteLicense(generatedInvitation); + assertTrue(result2, "The invitation should be deleted"); + + + boolean result4 = daoLicense.deleteLicense(generatedInvitation); + assertFalse(result4, "The invitation can't be deleted"); + } + + + @Test + void testActivateLicense() { + // Mock the license and user ID + License license = new License(); + license.setSequence("BDC3"); + license.setIdUser(4); + license.setExpirationDate(java.sql.Date.valueOf("2024-06-27")); + license.setActive(true); + + int userId = 4; + + // Call the method to test + daoLicense.activate(license, userId); + + // After activation, let's retrieve the updated license + License updatedLicense = daoLicense.getLicenseByCode(license.getSequence()); + + // Check the updated license + assertNotNull(updatedLicense, "Updated license should not be null"); + assertEquals(userId, updatedLicense.getIdUser(), "User ID should be updated"); + assertTrue(updatedLicense.isActive(), "License should be activated"); + // Add more assertions based on your specific requirements + } +} + diff --git a/src/test/java/model/DAO/DAOPersonalInfoTest.java b/src/test/java/model/DAO/DAOPersonalInfoTest.java new file mode 100644 index 0000000..9fb5c90 --- /dev/null +++ b/src/test/java/model/DAO/DAOPersonalInfoTest.java @@ -0,0 +1,54 @@ +package model.DAO; + +import model.DAO.DAOPersonalInfo; +import model.entity.PersonalInfo; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.sql.Date; + +import static org.junit.jupiter.api.Assertions.*; + +class DAOPersonalInfoTest { + + private DAOPersonalInfo daoPersonalInfo; + private int createdUserId = 0; + + @BeforeEach + void setUp() { + daoPersonalInfo = new DAOPersonalInfo(); + String email = "newuser@example.com"; + String password = "password123"; + int therapistId = 8; + // Call the method to test + createdUserId = new DAOUser().createUser(email, password, therapistId); + } + + @Test + void testCreateRegistryAndRetrievePersonalInfo() { + // Mock user data + String firstName = "Tester"; + String lastName = "Tester"; + + // Call the method to create a registry + boolean registryCreated = daoPersonalInfo.createRegistry(createdUserId, firstName, lastName); + + // Check if the registry creation was successful + assertTrue(registryCreated, "User registry should be created successfully"); + + // Call the method to retrieve personal information + PersonalInfo retrievedPersonalInfo = daoPersonalInfo.getPersonalInfo(createdUserId); + + // Check if personal information is retrieved successfully + assertNotNull(retrievedPersonalInfo, "Retrieved personal information should not be null"); + assertEquals(createdUserId, retrievedPersonalInfo.getIdUser(), "User IDs should match"); + assertEquals(firstName, retrievedPersonalInfo.getFirstname(), "First names should match"); + assertEquals(lastName, retrievedPersonalInfo.getLastname(), "Last names should match"); + + // Clean up: + assertTrue(daoPersonalInfo.deleteRegistry(createdUserId)); + new DAOUser().deleteUserByIdOrEmail(createdUserId); + assertFalse(daoPersonalInfo.deleteRegistry(createdUserId)); + } +} + diff --git a/src/test/java/model/DAO/DAOUserTest.java b/src/test/java/model/DAO/DAOUserTest.java new file mode 100644 index 0000000..96e34f3 --- /dev/null +++ b/src/test/java/model/DAO/DAOUserTest.java @@ -0,0 +1,136 @@ +package model.DAO; + +import model.entity.User; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class DAOUserTest { + + private DAOUser daoUser; + + @BeforeEach + void setup() { + daoUser = new DAOUser(); + } + + @Test + void testCheckIfEmailExists() { + // Existing email in the table + String existingEmail = "johndoa@example.com"; + + // Call the method to test + boolean emailExists = daoUser.checkIfEmailExists(existingEmail); + + // Check the result + assertTrue(emailExists, "Existing email should be found in the table"); + + // Non-existing email in the table + String nonExistingEmail = "nonexistent@example.com"; + + // Call the method to test + boolean nonExistingEmailExists = daoUser.checkIfEmailExists(nonExistingEmail); + + // Check the result + assertFalse(nonExistingEmailExists, "Non-existing email should not be found in the table"); + } + + @Test + void testCreateUser() { + // Mock user data + String email = "newuser@example.com"; + String password = "password123"; + int therapistId = 8; + + // Call the method to test + int createdUserId = daoUser.createUser(email, password, therapistId); + + // Check the result + assertTrue(createdUserId > 0, "New user should be created with a positive ID"); + + // Clean up: Delete the created user + assertTrue(daoUser.deleteUserByIdOrEmail(createdUserId)); + assertFalse(daoUser.deleteUserByIdOrEmail("newuser@example.com")); + + } + + @Test + void testGetUserByIdOrEmail() { + // Existing user ID in the table + int existingUserId = 8; + + // Call the method to test + User existingUserById = daoUser.getUserByIdOrEmail(existingUserId); + + // Check the result + assertNotNull(existingUserById, "Existing user by ID should be found in the table"); + assertEquals(existingUserId, existingUserById.getId(), "User ID should match"); + + // Existing email in the table + String existingEmail = "johndoa@example.com"; + + // Call the method to test + User existingUserByEmail = daoUser.getUserByIdOrEmail(existingEmail); + + // Check the result + assertNotNull(existingUserByEmail, "Existing user by email should be found in the table"); + assertEquals(existingEmail, existingUserByEmail.getEmail(), "User email should match"); + + // Non-existing ID or email + Object nonExistingIdOrEmail = "nonexistent"; + + // Call the method to test + User nonExistingUser = daoUser.getUserByIdOrEmail(nonExistingIdOrEmail); + + // Check the result + assertNull(nonExistingUser, "Non-existing user should not be found in the table"); + } + + @Test + void testResetPassword() { + // Mock user email and new password + String userEmail = "johndoa@example.com"; + String newPassword = "newpassword123"; + + // Call the method to test + boolean passwordReset = daoUser.resetPassword(userEmail, newPassword); + + // Check the result + assertTrue(passwordReset, "Password should be successfully reset"); + + daoUser.resetPassword(userEmail, "$2a$12$WE/ZQ5SqrkMPjNT57Mje.ePEVdUEm8tTeIlldM35DEuLEVQYuUxmm"); + } + + @Test + void testUpdateAnalyticsPreference() { + // Mock user ID and analytics value + String userId = "8"; + boolean newAnalyticsValue = true; + + // Call the method to test + boolean analyticsUpdated = daoUser.updateAnalyticsPreference(userId, newAnalyticsValue); + + // Check the result + assertTrue(analyticsUpdated, "Analytics preference should be successfully updated"); + + daoUser.updateAnalyticsPreference(userId, false); + } + + @Test + void testUpdateEmailTime() { + // Mock user ID and new email time + String userId = "8"; + String newEmailTime = "18:30|19:00"; + + // Call the method to test + boolean emailTimeUpdated = daoUser.updateEmailTime(userId, newEmailTime); + + // Check the result + assertTrue(emailTimeUpdated, "Email time should be successfully updated"); + + // Clean up: Reset the email time back to the original + daoUser.updateEmailTime(userId, "17:16|17:19"); + } +} +