Sure! Below is a comprehensive implementation of the leave management system you described using Spring Boot with Firestore as the backend and two frontend interfaces using HTML, JavaScript, and CSS. This implementation includes:
-
Backend Components:
- Model:
LeaveRequest
- Repository:
LeaveRequestRepository
- Service:
LeaveRequestService
- Controller:
LeaveRequestController
-
Frontend Interfaces:
- Worker Interface: Allows workers to apply for leave, view their requests, and update requests.
- Supervisor Interface: Allows supervisors to view, approve, or reject leave requests from their supervised workers.
Backend Implementation
1. Model: LeaveRequest.java
Create a model package under com.g4t4.home_cleaning_scheduler and add the LeaveRequest class.
// File: backend/src/main/java/com/g4t4/home_cleaning_scheduler/model/LeaveRequest.java
package com.g4t4.home_cleaning_scheduler.model;
import com.g4t4.home_cleaning_scheduler.utils.DocumentId;
import lombok.Data;
@Data
public class LeaveRequest {
@DocumentId
private String id;
private String leaveType;
private String applicationDate; // ISO date string e.g., "2023-10-01"
private String startDate;
private String endDate;
private String status; // e.g., "PENDING", "APPROVED", "REJECTED"
private String workerId;
private String supervisorId;
private String medicalCertificateUrl; // URL or base64 string of the image
}
2. Repository: LeaveRequestRepository.java
Create a repository package and implement LeaveRequestRepository extending AbstractFirestoreRepository.
// File: backend/src/main/java/com/g4t4/home_cleaning_scheduler/repository/LeaveRequestRepository.java
package com.g4t4.home_cleaning_scheduler.repository;
import com.g4t4.home_cleaning_scheduler.model.LeaveRequest;
import com.google.cloud.firestore.Firestore;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Repository
public class LeaveRequestRepository extends AbstractFirestoreRepository<LeaveRequest> {
public LeaveRequestRepository(Firestore firestore) {
super(firestore, "leaveRequests");
}
public List<LeaveRequest> findByWorkerId(String workerId) {
return getCollectionReference()
.whereEqualTo("workerId", workerId)
.get()
.map(querySnapshot -> querySnapshot.getDocuments().stream()
.map(doc -> doc.toObject(getType()))
.collect(Collectors.toList()))
.exceptionally(e -> {
log.error("Error fetching leave requests for workerId={} : {}", workerId, e.getMessage());
return List.of();
})
.join();
}
public List<LeaveRequest> findBySupervisorId(String supervisorId) {
return getCollectionReference()
.whereEqualTo("supervisorId", supervisorId)
.get()
.map(querySnapshot -> querySnapshot.getDocuments().stream()
.map(doc -> doc.toObject(getType()))
.collect(Collectors.toList()))
.exceptionally(e -> {
log.error("Error fetching leave requests for supervisorId={} : {}", supervisorId, e.getMessage());
return List.of();
})
.join();
}
// Additional methods if needed
}
3. Service: LeaveRequestService.java
Create a service package and implement the LeaveRequestService to handle business logic.
// File: backend/src/main/java/com/g4t4/home_cleaning_scheduler/service/LeaveRequestService.java
package com.g4t4.home_cleaning_scheduler.service;
import com.g4t4.home_cleaning_scheduler.model.LeaveRequest;
import com.g4t4.home_cleaning_scheduler.repository.LeaveRequestRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class LeaveRequestService {
@Autowired
private LeaveRequestRepository leaveRequestRepository;
public boolean applyForLeave(LeaveRequest leaveRequest) {
leaveRequest.setStatus("PENDING");
return leaveRequestRepository.save(leaveRequest);
}
public List<LeaveRequest> getLeaveRequestsByWorker(String workerId) {
return leaveRequestRepository.findByWorkerId(workerId);
}
public List<LeaveRequest> getLeaveRequestsBySupervisor(String supervisorId) {
return leaveRequestRepository.findBySupervisorId(supervisorId);
}
public Optional<LeaveRequest> getLeaveRequestById(String id) {
return leaveRequestRepository.get(id);
}
public boolean updateLeaveRequest(LeaveRequest leaveRequest) {
return leaveRequestRepository.save(leaveRequest);
}
public boolean approveLeaveRequest(String id) {
Optional<LeaveRequest> optionalLeaveRequest = leaveRequestRepository.get(id);
if (optionalLeaveRequest.isPresent()) {
LeaveRequest leaveRequest = optionalLeaveRequest.get();
leaveRequest.setStatus("APPROVED");
return leaveRequestRepository.save(leaveRequest);
}
return false;
}
public boolean rejectLeaveRequest(String id) {
Optional<LeaveRequest> optionalLeaveRequest = leaveRequestRepository.get(id);
if (optionalLeaveRequest.isPresent()) {
LeaveRequest leaveRequest = optionalLeaveRequest.get();
leaveRequest.setStatus("REJECTED");
return leaveRequestRepository.save(leaveRequest);
}
return false;
}
}
4. Controller: LeaveRequestController.java
Create a controller package and implement REST endpoints to handle requests.
// File: backend/src/main/java/com/g4t4/home_cleaning_scheduler/controller/LeaveRequestController.java
package com.g4t4.home_cleaning_scheduler.controller;
import com.g4t4.home_cleaning_scheduler.model.LeaveRequest;
import com.g4t4.home_cleaning_scheduler.service.LeaveRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/leaverequests")
@CrossOrigin(origins = "*") // Adjust as needed for security
public class LeaveRequestController {
@Autowired
private LeaveRequestService leaveRequestService;
// 1. Apply for leave
@PostMapping("/apply")
public ResponseEntity<String> applyForLeave(
@RequestParam String leaveType,
@RequestParam String applicationDate,
@RequestParam String startDate,
@RequestParam String endDate,
@RequestParam String workerId,
@RequestParam String supervisorId,
@RequestParam(required = false) MultipartFile medicalCertificate
) {
LeaveRequest leaveRequest = new LeaveRequest();
leaveRequest.setLeaveType(leaveType);
leaveRequest.setApplicationDate(applicationDate);
leaveRequest.setStartDate(startDate);
leaveRequest.setEndDate(endDate);
leaveRequest.setWorkerId(workerId);
leaveRequest.setSupervisorId(supervisorId);
if ("MEDICAL".equalsIgnoreCase(leaveType) && medicalCertificate != null && !medicalCertificate.isEmpty()) {
try {
byte[] bytes = medicalCertificate.getBytes();
String encodedImage = Base64.getEncoder().encodeToString(bytes);
leaveRequest.setMedicalCertificateUrl(encodedImage); // For simplicity, storing as base64 string
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error processing medical certificate.");
}
}
boolean success = leaveRequestService.applyForLeave(leaveRequest);
if (success) {
return ResponseEntity.ok("Leave request submitted successfully.");
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to submit leave request.");
}
}
// 2. Get leave requests for a worker
@GetMapping("/worker/{workerId}")
public ResponseEntity<List<LeaveRequest>> getLeaveRequestsByWorker(@PathVariable String workerId) {
List<LeaveRequest> leaveRequests = leaveRequestService.getLeaveRequestsByWorker(workerId);
return ResponseEntity.ok(leaveRequests);
}
// 3. Update leave request to upload medical certificate
@PutMapping("/update/{id}")
public ResponseEntity<String> updateLeaveRequest(
@PathVariable String id,
@RequestParam(required = false) MultipartFile medicalCertificate
) {
Optional<LeaveRequest> optionalLeaveRequest = leaveRequestService.getLeaveRequestById(id);
if (optionalLeaveRequest.isPresent()) {
LeaveRequest leaveRequest = optionalLeaveRequest.get();
if ("MEDICAL".equalsIgnoreCase(leaveRequest.getLeaveType())) {
if (medicalCertificate != null && !medicalCertificate.isEmpty()) {
try {
byte[] bytes = medicalCertificate.getBytes();
String encodedImage = Base64.getEncoder().encodeToString(bytes);
leaveRequest.setMedicalCertificateUrl(encodedImage);
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error processing medical certificate.");
}
} else {
return ResponseEntity.badRequest().body("Medical certificate file is required.");
}
boolean updated = leaveRequestService.updateLeaveRequest(leaveRequest);
if (updated) {
return ResponseEntity.ok("Leave request updated successfully.");
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to update leave request.");
}
} else {
return ResponseEntity.badRequest().body("Only medical leave requests can be updated with a certificate.");
}
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Leave request not found.");
}
}
// 4. Supervisor views all requests
@GetMapping("/supervisor/{supervisorId}")
public ResponseEntity<List<LeaveRequest>> getLeaveRequestsBySupervisor(@PathVariable String supervisorId) {
List<LeaveRequest> leaveRequests = leaveRequestService.getLeaveRequestsBySupervisor(supervisorId);
return ResponseEntity.ok(leaveRequests);
}
// 5. Supervisor approves a request
@PostMapping("/approve/{id}")
public ResponseEntity<String> approveLeaveRequest(@PathVariable String id) {
boolean success = leaveRequestService.approveLeaveRequest(id);
if (success) {
return ResponseEntity.ok("Leave request approved.");
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to approve leave request.");
}
}
// 5. Supervisor rejects a request
@PostMapping("/reject/{id}")
public ResponseEntity<String> rejectLeaveRequest(@PathVariable String id) {
boolean success = leaveRequestService.rejectLeaveRequest(id);
if (success) {
return ResponseEntity.ok("Leave request rejected.");
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to reject leave request.");
}
}
}
5. CORS Configuration (Optional)
If you encounter CORS issues, you can configure global CORS settings.
// File: backend/src/main/java/com/g4t4/home_cleaning_scheduler/config/CorsConfig.java
package com.g4t4.home_cleaning_scheduler.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("*") // Change to specific origins in production
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*");
}
}
6. Application Entry Point
Ensure your application has the main entry point.
// File: backend/src/main/java/com/g4t4/home_cleaning_scheduler/HomeCleaningSchedulerApplication.java
package com.g4t4.home_cleaning_scheduler;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HomeCleaningSchedulerApplication {
public static void main(String[] args) {
SpringApplication.run(HomeCleaningSchedulerApplication.class, args);
}
}
7. Running the Backend
Frontend Implementation
We'll create two simple frontend interfaces:
- Worker Interface: Allows workers to apply for leave, view their leave requests, and update requests.
- Supervisor Interface: Allows supervisors to view, approve, or reject leave requests from their supervised workers.
1. Worker Interface
Create an index.html file for the worker interface.
<!-- File: frontend/worker.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Worker Dashboard</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.section {
margin-bottom: 40px;
}
input, select, button, textarea {
display: block;
margin: 10px 0;
padding: 8px;
width: 300px;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h1>Worker Dashboard</h1>
<div class="section">
<h2>Apply for Leave</h2>
<form id="applyLeaveForm">
<label for="workerId">Worker ID:</label>
<input type="text" id="workerId" required>
<label for="supervisorId">Supervisor ID:</label>
<input type="text" id="supervisorId" required>
<label for="leaveType">Leave Type:</label>
<select id="leaveType" required>
<option value="">Select Type</option>
<option value="VACATION">Vacation</option>
<option value="SICK">Sick</option>
<option value="MEDICAL">Medical</option>
<!-- Add more types as needed -->
</select>
<label for="applicationDate">Application Date:</label>
<input type="date" id="applicationDate" required>
<label for="startDate">Start Date:</label>
<input type="date" id="startDate" required>
<label for="endDate">End Date:</label>
<input type="date" id="endDate" required>
<label for="medicalCertificate">Medical Certificate (optional):</label>
<input type="file" id="medicalCertificate" accept="image/*">
<button type="submit">Submit Leave Request</button>
</form>
<div id="applyLeaveStatus"></div>
</div>
<div class="section">
<h2>Your Leave Requests</h2>
<button onclick="fetchLeaveRequests()">Refresh List</button>
<table id="leaveRequestsTable">
<thead>
<tr>
<th>ID</th>
<th>Type</th>
<th>Applied On</th>
<th>Start Date</th>
<th>End Date</th>
<th>Status</th>
<th>Medical Certificate</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<!-- Leave requests will be populated here -->
</tbody>
</table>
</div>
<script>
const backendUrl = 'http://localhost:8081/api/leaverequests';
document.getElementById('applyLeaveForm').addEventListener('submit', function(event) {
event.preventDefault();
const workerId = document.getElementById('workerId').value;
const supervisorId = document.getElementById('supervisorId').value;
const leaveType = document.getElementById('leaveType').value;
const applicationDate = document.getElementById('applicationDate').value;
const startDate = document.getElementById('startDate').value;
const endDate = document.getElementById('endDate').value;
const medicalCertificate = document.getElementById('medicalCertificate').files[0];
const formData = new FormData();
formData.append('workerId', workerId);
formData.append('supervisorId', supervisorId);
formData.append('leaveType', leaveType);
formData.append('applicationDate', applicationDate);
formData.append('startDate', startDate);
formData.append('endDate', endDate);
if (leaveType === 'MEDICAL' && medicalCertificate) {
formData.append('medicalCertificate', medicalCertificate);
}
fetch(`${backendUrl}/apply`, {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
document.getElementById('applyLeaveStatus').innerText = data;
fetchLeaveRequests(); // Refresh the leave requests list
})
.catch(error => {
document.getElementById('applyLeaveStatus').innerText = 'Error submitting leave request.';
console.error('Error:', error);
});
});
function fetchLeaveRequests() {
const workerId = document.getElementById('workerId').value;
if (!workerId) {
alert('Please enter your Worker ID to fetch leave requests.');
return;
}
fetch(`${backendUrl}/worker/${workerId}`)
.then(response => response.json())
.then(data => {
const tbody = document.getElementById('leaveRequestsTable').getElementsByTagName('tbody')[0];
tbody.innerHTML = '';
data.forEach(request => {
const row = tbody.insertRow();
row.insertCell(0).innerText = request.id;
row.insertCell(1).innerText = request.leaveType;
row.insertCell(2).innerText = request.applicationDate;
row.insertCell(3).innerText = request.startDate;
row.insertCell(4).innerText = request.endDate;
row.insertCell(5).innerText = request.status;
if (request.medicalCertificateUrl) {
const img = document.createElement('img');
img.src = `data:image/*;base64,${request.medicalCertificateUrl}`;
img.alt = 'Medical Certificate';
img.width = 100;
row.insertCell(6).appendChild(img);
} else {
row.insertCell(6).innerText = 'N/A';
}
// Actions
const actionsCell = row.insertCell(7);
if (request.leaveType === 'MEDICAL' && !request.medicalCertificateUrl && request.status === 'PENDING') {
const uploadBtn = document.createElement('button');
uploadBtn.innerText = 'Upload Certificate';
uploadBtn.onclick = () => uploadCertificate(request.id);
actionsCell.appendChild(uploadBtn);
} else {
actionsCell.innerHTML = '—';
}
});
})
.catch(error => {
console.error('Error fetching leave requests:', error);
});
}
function uploadCertificate(id) {
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = 'image/*';
fileInput.onchange = () => {
const file = fileInput.files[0];
if (file) {
const formData = new FormData();
formData.append('medicalCertificate', file);
fetch(`${backendUrl}/update/${id}`, {
method: 'PUT',
body: formData
})
.then(response => response.text())
.then(data => {
alert(data);
fetchLeaveRequests();
})
.catch(error => {
alert('Error uploading medical certificate.');
console.error('Error:', error);
});
}
};
fileInput.click();
}
</script>
</body>
</html>
Instructions to Test the Worker Interface:
- Save the above HTML code as
worker.html in a frontend directory.
- Open
worker.html in your web browser.
- Apply for Leave:
- Enter your
Worker ID and your Supervisor ID.
- Select the
Leave Type (e.g., Vacation, Sick, Medical).
- Choose the
Application Date, Start Date, and End Date.
- If
Leave Type is Medical, optionally upload a medical certificate image.
- Click on Submit Leave Request.
- View Leave Requests:
- To view your leave requests, enter your
Worker ID and click on Refresh List.
- Upload Medical Certificate:
- For medical leave requests without a certificate, click on Upload Certificate to add one.
2. Supervisor Interface
Create a supervisor.html file for the supervisor interface.
<!-- File: frontend/supervisor.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Supervisor Dashboard</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.section {
margin-bottom: 40px;
}
input, button, select, textarea {
display: block;
margin: 10px 0;
padding: 8px;
width: 300px;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
}
th {
background-color: #f2f2f2;
}
.action-btn {
margin-right: 5px;
padding: 5px 10px;
}
</style>
</head>
<body>
<h1>Supervisor Dashboard</h1>
<div class="section">
<h2>View Leave Requests from Your Workers</h2>
<form id="supervisorForm">
<label for="supervisorId">Supervisor ID:</label>
<input type="text" id="supervisorId" required>
<button type="submit">Fetch Leave Requests</button>
</form>
<div id="supervisorStatus"></div>
</div>
<div class="section">
<h2>Leave Requests</h2>
<table id="supervisorLeaveRequestsTable">
<thead>
<tr>
<th>ID</th>
<th>Worker ID</th>
<th>Type</th>
<th>Applied On</th>
<th>Start Date</th>
<th>End Date</th>
<th>Status</th>
<th>Medical Certificate</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<!-- Leave requests will be populated here -->
</tbody>
</table>
</div>
<script>
const backendUrl = 'http://localhost:8081/api/leaverequests';
document.getElementById('supervisorForm').addEventListener('submit', function(event) {
event.preventDefault();
const supervisorId = document.getElementById('supervisorId').value;
fetch(`${backendUrl}/supervisor/${supervisorId}`)
.then(response => response.json())
.then(data => {
const tbody = document.getElementById('supervisorLeaveRequestsTable').getElementsByTagName('tbody')[0];
tbody.innerHTML = '';
data.forEach(request => {
const row = tbody.insertRow();
row.insertCell(0).innerText = request.id;
row.insertCell(1).innerText = request.workerId;
row.insertCell(2).innerText = request.leaveType;
row.insertCell(3).innerText = request.applicationDate;
row.insertCell(4).innerText = request.startDate;
row.insertCell(5).innerText = request.endDate;
row.insertCell(6).innerText = request.status;
if (request.medicalCertificateUrl) {
const img = document.createElement('img');
img.src = `data:image/*;base64,${request.medicalCertificateUrl}`;
img.alt = 'Medical Certificate';
img.width = 100;
row.insertCell(7).appendChild(img);
} else {
row.insertCell(7).innerText = 'N/A';
}
// Actions
const actionsCell = row.insertCell(8);
if (request.status === 'PENDING') {
const approveBtn = document.createElement('button');
approveBtn.innerText = 'Approve';
approveBtn.className = 'action-btn';
approveBtn.onclick = () => updateLeaveRequestStatus(request.id, 'approve');
const rejectBtn = document.createElement('button');
rejectBtn.innerText = 'Reject';
rejectBtn.className = 'action-btn';
rejectBtn.onclick = () => updateLeaveRequestStatus(request.id, 'reject');
actionsCell.appendChild(approveBtn);
actionsCell.appendChild(rejectBtn);
} else {
actionsCell.innerHTML = '—';
}
});
})
.catch(error => {
document.getElementById('supervisorStatus').innerText = 'Error fetching leave requests.';
console.error('Error:', error);
});
});
function updateLeaveRequestStatus(id, action) {
fetch(`${backendUrl}/${action}/${id}`, {
method: 'POST'
})
.then(response => response.text())
.then(data => {
alert(data);
// Refresh the list
document.getElementById('supervisorForm').dispatchEvent(new Event('submit'));
})
.catch(error => {
alert('Error updating leave request.');
console.error('Error:', error);
});
}
</script>
</body>
</html>
Instructions to Test the Supervisor Interface:
- Save the above HTML code as
supervisor.html in the frontend directory.
- Open
supervisor.html in your web browser.
- View Leave Requests:
- Enter your
Supervisor ID.
- Click on Fetch Leave Requests to view all leave requests from your supervised workers.
- Approve/Reject Requests:
- For each pending leave request, click on Approve or Reject to update the request status.
Notes and Considerations
-
Authentication & Authorization:
- This implementation does not include authentication and authorization. In a production environment, ensure that only authenticated workers and supervisors can access their respective functionalities.
- Consider using tokens (e.g., JWT) to secure the REST endpoints.
-
Medical Certificate Handling:
- For simplicity, medical certificates are stored as Base64-encoded strings in Firestore. This is not recommended for large files or sensitive information.
- In a real-world application, consider using Firebase Storage or another secure storage service to handle file uploads and store URLs in Firestore.
-
Data Validation:
- Additional data validation can be implemented to ensure data integrity (e.g., ensuring start date is before end date).
-
Error Handling:
- Improved error handling and user feedback mechanisms can enhance user experience.
-
User Interface Enhancements:
- The frontend interfaces are kept simple for demonstration purposes. You can enhance them using frameworks like React, Vue, or Angular for a better user experience.
-
CORS Configuration:
- While the provided
@CrossOrigin(origins = "*") annotation allows all origins, you should restrict this in a production environment to specific domains to enhance security.
-
Supervisor & Worker ID Management:
- The system assumes that Worker IDs and Supervisor IDs are managed externally. Ensure that these IDs are unique and properly associated in your organizational context.
-
Firestore Rules:
- Ensure that Firestore security rules are properly configured to prevent unauthorized data access or modifications.
Conclusion
This implementation provides a basic structure for a leave management system with worker and supervisor functionalities using Spring Boot and Firestore. You can further enhance and customize it based on your specific requirements and security considerations.