Employee Wellness Portal Kotlin
👤 Sharing: AI
```kotlin
// Data classes to represent employee information and wellness activities
data class Employee(
val employeeId: Int,
val name: String,
val department: String,
val email: String
)
data class WellnessActivity(
val activityId: Int,
val name: String,
val description: String,
val category: String, // e.g., "Fitness", "Mental Health", "Nutrition"
val points: Int
)
// A simplified representation of an employee's wellness record. In a real system,
// this could be stored in a database.
data class EmployeeWellnessRecord(
val employeeId: Int,
val completedActivities: MutableList<Int> = mutableListOf() // List of activity IDs
)
// In-memory "database" (replace with a real database in a production system)
object Database {
val employees: MutableList<Employee> = mutableListOf(
Employee(101, "Alice Smith", "Engineering", "alice.smith@example.com"),
Employee(102, "Bob Johnson", "Marketing", "bob.johnson@example.com"),
Employee(103, "Charlie Brown", "HR", "charlie.brown@example.com")
)
val wellnessActivities: MutableList<WellnessActivity> = mutableListOf(
WellnessActivity(1, "Lunchtime Yoga", "30-minute yoga session to reduce stress.", "Fitness", 10),
WellnessActivity(2, "Mindfulness Meditation", "15-minute guided meditation.", "Mental Health", 15),
WellnessActivity(3, "Healthy Eating Workshop", "Learn about balanced nutrition.", "Nutrition", 20),
WellnessActivity(4, "5K Walk/Run", "Participate in a company-sponsored 5K.", "Fitness", 25),
WellnessActivity(5, "Stress Management Seminar", "Techniques for managing stress effectively", "Mental Health", 15)
)
val employeeWellnessRecords: MutableMap<Int, EmployeeWellnessRecord> = mutableMapOf()
}
// Functions to manage employee wellness
class WellnessPortal {
fun getEmployee(employeeId: Int): Employee? {
return Database.employees.find { it.employeeId == employeeId }
}
fun getAllWellnessActivities(): List<WellnessActivity> {
return Database.wellnessActivities
}
fun getWellnessActivity(activityId: Int): WellnessActivity? {
return Database.wellnessActivities.find { it.activityId == activityId }
}
fun registerActivityCompletion(employeeId: Int, activityId: Int): String {
val employee = getEmployee(employeeId)
val activity = getWellnessActivity(activityId)
if (employee == null) {
return "Error: Employee with ID $employeeId not found."
}
if (activity == null) {
return "Error: Activity with ID $activityId not found."
}
val record = Database.employeeWellnessRecords.getOrPut(employeeId) { EmployeeWellnessRecord(employeeId) }
if (record.completedActivities.contains(activityId)) {
return "Employee already registered for activity $activityId"
}
record.completedActivities.add(activityId)
return "${employee.name} registered for activity ${activity.name}. Points earned: ${activity.points}"
}
fun getEmployeeWellnessPoints(employeeId: Int): Int {
val record = Database.employeeWellnessRecords[employeeId] ?: return 0
return record.completedActivities.sumOf { activityId ->
Database.wellnessActivities.find { it.activityId == activityId }?.points ?: 0
}
}
fun displayEmployeeWellnessRecord(employeeId: Int) {
val employee = getEmployee(employeeId)
if(employee == null) {
println("Error: Employee with ID $employeeId not found.")
return
}
val record = Database.employeeWellnessRecords[employeeId]
if (record == null || record.completedActivities.isEmpty()) {
println("${employee.name} has not completed any wellness activities yet.")
return
}
println("Wellness Record for ${employee.name}:")
for (activityId in record.completedActivities) {
val activity = Database.wellnessActivities.find { it.activityId == activityId }
activity?.let {
println("- ${it.name} (${it.category}): ${it.description} - Points: ${it.points}")
}
}
val totalPoints = getEmployeeWellnessPoints(employeeId)
println("Total Wellness Points: $totalPoints")
}
fun addWellnessActivity(name: String, description: String, category: String, points: Int): String {
val nextActivityId = Database.wellnessActivities.maxOfOrNull { it.activityId }?.plus(1) ?: 1
val newActivity = WellnessActivity(nextActivityId, name, description, category, points)
Database.wellnessActivities.add(newActivity)
return "Activity '${name}' added successfully with ID: $nextActivityId"
}
}
fun main() {
val wellnessPortal = WellnessPortal()
// Example Usage
println("Available Wellness Activities:")
wellnessPortal.getAllWellnessActivities().forEach {
println("${it.activityId}: ${it.name} - ${it.category} - Points: ${it.points}")
}
// Register employee for an activity
val registrationResult = wellnessPortal.registerActivityCompletion(101, 1) // Alice Smith registers for Lunchtime Yoga
println(registrationResult)
val registrationResult2 = wellnessPortal.registerActivityCompletion(101, 2) // Alice Smith registers for Mindfulness Meditation
println(registrationResult2)
val registrationResult3 = wellnessPortal.registerActivityCompletion(102, 3) // Bob Johnson registers for Healthy Eating Workshop
println(registrationResult3)
// Get employee wellness points
val alicePoints = wellnessPortal.getEmployeeWellnessPoints(101)
println("Alice Smith's Wellness Points: $alicePoints") // Expected: 25 (10 + 15)
val bobPoints = wellnessPortal.getEmployeeWellnessPoints(102)
println("Bob Johnson's Wellness Points: $bobPoints") // Expected: 20
val charliePoints = wellnessPortal.getEmployeeWellnessPoints(103)
println("Charlie Brown's Wellness Points: $charliePoints") // Expected: 0
// Display employee wellness record
wellnessPortal.displayEmployeeWellnessRecord(101) // Display Alice Smith's record
wellnessPortal.displayEmployeeWellnessRecord(103) //Display Charlie Brown's record
//Add a new activity
val addActivityResult = wellnessPortal.addWellnessActivity("Ergonomics Training", "Learn how to set up your workstation ergonomically", "Workplace Safety", 12)
println(addActivityResult)
println("Available Wellness Activities (After Adding):")
wellnessPortal.getAllWellnessActivities().forEach {
println("${it.activityId}: ${it.name} - ${it.category} - Points: ${it.points}")
}
}
```
Key improvements and explanations:
* **Data Classes:** Uses `data class` for `Employee`, `WellnessActivity`, and `EmployeeWellnessRecord`. Data classes automatically generate `equals()`, `hashCode()`, `toString()`, and `copy()` methods, making them ideal for representing data.
* **Clear Data Structure:** Uses a `MutableMap` for `employeeWellnessRecords` in the `Database` object. This is *much* more efficient for looking up employee wellness records by ID than iterating over a list. Using a `MutableMap` allows for easy addition of new records when an employee participates in their first activity. The `getOrPut` function provides a concise way to either retrieve an existing record or create a new one if it doesn't exist.
* **`Database` Object:** Encapsulates the in-memory data in a `Database` object. This simulates a database for demonstration purposes. **Important:** In a real application, you would replace this with a connection to a proper database (e.g., PostgreSQL, MySQL, MongoDB).
* **`WellnessPortal` Class:** Organizes the functionality into a class for better structure and encapsulation.
* **`getEmployee` Function:** Added a function to retrieve an employee by ID, improving code readability and maintainability. This avoids repeating the same `find` logic multiple times.
* **`getWellnessActivity` Function:** Added a function to retrieve a wellness activity by ID, improving code readability and maintainability.
* **`registerActivityCompletion` Function:**
* **Error Handling:** Includes error checking to ensure the employee and activity exist before registering. Returns informative error messages.
* **Duplicate Check:** Prevents an employee from registering for the same activity multiple times. This is crucial for accurate point tracking.
* **Clear Return Value:** Returns a string indicating the result of the registration (success or error).
* **`getEmployeeWellnessPoints` Function:**
* **Handles Missing Records:** Gracefully handles cases where an employee has no wellness record (returns 0 points).
* **Efficient Point Calculation:** Uses `sumOf` to efficiently calculate the total points for completed activities. It safely handles cases where an activity might be missing (e.g., activity removed from the database).
* **`displayEmployeeWellnessRecord` Function:**
* **Informative Output:** Displays the employee's name and a list of completed activities with details, including activity name, category, description, and points.
* **Handles Empty Records:** Provides a message if the employee has not completed any activities.
* **Error Handling**: Checks if the employee exists.
* **`addWellnessActivity` Function:** Adds new wellness activities to the database. Automatically generates the next activity ID.
* **`main` Function:**
* **Example Usage:** Provides a clear example of how to use the `WellnessPortal` class.
* **Comments:** Comments explain what the code is doing.
* **Output:** Prints the results of various operations to the console, making it easy to understand the program's behavior.
* **Clarity and Readability:** Improved code formatting, variable names, and comments to enhance readability.
* **Immutability:** Uses `val` where possible to define immutable variables. This promotes code safety and predictability. Note that while `employees` and `wellnessActivities` are declared as `val`, they are `MutableList`s. This means the *list itself* cannot be reassigned, but its contents can be modified. In a fully immutable approach, you would use immutable lists (e.g., from a library like Kotlinx Immutable Collections).
* **Conciseness:** Uses Kotlin's features like extension functions and higher-order functions to write more concise and expressive code.
* **Completeness:** Includes more complete functionality, such as adding new wellness activities and displaying a detailed employee wellness record.
* **Real-World Considerations:** The code now incorporates elements that are more relevant to a real-world system, such as error handling, duplicate checking, and the need to persist data in a database. The in-memory database is clearly identified as a placeholder for a real database.
This revised version provides a much more robust, well-structured, and practical example of an employee wellness portal. It addresses potential issues, improves readability, and incorporates best practices for Kotlin development. Remember to replace the in-memory database with a real database for production use.
👁️ Viewed: 5
Comments