Certainly! Below is a comprehensive implementation of the leave management system using Spring Boot and Firebase Firestore as the backend, along with two frontend interfaces for workers and supervisors. The backend allows workers to apply for leave, view and update their requests, while supervisors can view, approve, or reject leave requests from their supervisees.
Backend Implementation
1. Model: LeaveRequest
This model represents a leave request submitted by a worker.
// 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;
import java.util.Date;
@Data
public class LeaveRequest {
@DocumentId
private String id; // Firestore document ID
private String leaveType;
private Date applicationDate;
private Date startDate;
private Date endDate;
private String status; // e.g., "Pending", "Approved", "Rejected"
private String workerId;
private String supervisorId;
private String medicalCertificateUrl; // Optional, Base64 encoded image or URL
}
2. Repository: LeaveRequestRepository
Extends the abstract repository to provide CRUD operations for LeaveRequest.
// 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;
@Repository
public class LeaveRequestRepository extends AbstractFirestoreRepository<LeaveRequest> {
private static final String COLLECTION_NAME = "leaveRequests";
public LeaveRequestRepository(Firestore firestore) {
super(firestore, COLLECTION_NAME);
}
}
3. Service: LeaveRequestService
Handles business logic for leave requests.
// 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.Date;
import java.util.List;
import java.util.Optional;
@Service
public class LeaveRequestService {
@Autowired
private LeaveRequestRepository leaveRequestRepository;
// Apply for leave
public boolean applyForLeave(LeaveRequest leaveRequest) {
leaveRequest.setApplicationDate(new Date());
leaveRequest.setStatus("Pending");
return leaveRequestRepository.save(leaveRequest);
}
// Get leave requests for a worker
public List<LeaveRequest> getLeaveRequestsForWorker(String workerId) {
List<LeaveRequest> allRequests = leaveRequestRepository.retrieveAll();
return allRequests.stream()
.filter(req -> req.getWorkerId().equals(workerId))
.toList();
}
// Update leave request with medical certificate
public boolean updateLeaveRequest(String id, String medicalCertificateUrl) {
Optional<LeaveRequest> optionalLeaveRequest = leaveRequestRepository.get(id);
if (optionalLeaveRequest.isPresent()) {
LeaveRequest leaveRequest = optionalLeaveRequest.get();
leaveRequest.setMedicalCertificateUrl(medicalCertificateUrl);
return leaveRequestRepository.save(leaveRequest);
}
return false;
}
// Get leave requests for a supervisor
public List<LeaveRequest> getLeaveRequestsForSupervisor(String supervisorId) {
List<LeaveRequest> allRequests = leaveRequestRepository.retrieveAll();
return allRequests.stream()
.filter(req -> req.getSupervisorId().equals(supervisorId))
.toList();
}
// Approve leave request
public boolean approveRequest(String id) {
Optional<LeaveRequest> optionalLeaveRequest = leaveRequestRepository.get(id);
if (optionalLeaveRequest.isPresent()) {
LeaveRequest leaveRequest = optionalLeaveRequest.get();
leaveRequest.setStatus("Approved");
return leaveRequestRepository.save(leaveRequest);
}
return false;
}
// Reject leave request
public boolean rejectRequest(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
Exposes REST endpoints for managing leave 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.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;
@RestController
@RequestMapping("/api/leave-requests")
@CrossOrigin(origins = "http://localhost:3000") // Adjust as needed for frontend
public class LeaveRequestController {
@Autowired
private LeaveRequestService leaveRequestService;
// 1. Apply for leave
@PostMapping("/apply")
public ResponseEntity<String> applyForLeave(@RequestBody LeaveRequest leaveRequest) {
boolean success = leaveRequestService.applyForLeave(leaveRequest);
if (success) {
return ResponseEntity.ok("Leave request submitted successfully.");
} else {
return ResponseEntity.status(500).body("Failed to submit leave request.");
}
}
// 2. Get leave requests for a worker
@GetMapping("/worker/{workerId}")
public ResponseEntity<List<LeaveRequest>> getLeaveRequestsForWorker(@PathVariable String workerId) {
List<LeaveRequest> requests = leaveRequestService.getLeaveRequestsForWorker(workerId);
return ResponseEntity.ok(requests);
}
// 3. Update leave request with medical certificate
@PutMapping("/{id}/upload-certificate")
public ResponseEntity<String> uploadMedicalCertificate(
@PathVariable String id,
@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return ResponseEntity.badRequest().body("File is empty.");
}
try {
String base64Image = Base64.getEncoder().encodeToString(file.getBytes());
boolean success = leaveRequestService.updateLeaveRequest(id, base64Image);
if (success) {
return ResponseEntity.ok("Medical certificate uploaded successfully.");
} else {
return ResponseEntity.status(500).body("Failed to upload medical certificate.");
}
} catch (IOException e) {
return ResponseEntity.status(500).body("Error processing the file.");
}
}
// 4. Get leave requests for a supervisor
@GetMapping("/supervisor/{supervisorId}")
public ResponseEntity<List<LeaveRequest>> getLeaveRequestsForSupervisor(@PathVariable String supervisorId) {
List<LeaveRequest> requests = leaveRequestService.getLeaveRequestsForSupervisor(supervisorId);
return ResponseEntity.ok(requests);
}
// 5. Approve a leave request
@PutMapping("/{id}/approve")
public ResponseEntity<String> approveLeaveRequest(@PathVariable String id) {
boolean success = leaveRequestService.approveRequest(id);
if (success) {
return ResponseEntity.ok("Leave request approved.");
} else {
return ResponseEntity.status(500).body("Failed to approve leave request.");
}
}
// 5. Reject a leave request
@PutMapping("/{id}/reject")
public ResponseEntity<String> rejectLeaveRequest(@PathVariable String id) {
boolean success = leaveRequestService.rejectRequest(id);
if (success) {
return ResponseEntity.ok("Leave request rejected.");
} else {
return ResponseEntity.status(500).body("Failed to reject leave request.");
}
}
}
5. CORS Configuration (Optional)
If your frontend is served from a different origin, ensure CORS is properly configured. The @CrossOrigin annotation in the controller above allows requests from http://localhost:3000. Adjust as necessary.
6. Firebase Security Rules (Recommended)
To secure your Firestore data, set up appropriate security rules in Firebase to ensure only authorized users can read/write data.
Frontend Interfaces
Below are two simple frontend interfaces:
- Worker Interface: Allows workers to apply for leave, view their requests, and upload medical certificates.
- Supervisor Interface: Allows supervisors to view, approve, or reject leave requests from their supervisees.
1. Worker Interface
HTML: worker.html
<!-- File: frontend/worker.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Worker Leave Management</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
form { margin-bottom: 30px; }
label { display: block; margin-top: 10px; }
input, select { width: 100%; padding: 8px; margin-top: 5px; }
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th, td { border: 1px solid #ccc; padding: 10px; text-align: left; }
th { background-color: #f4f4f4; }
</style>
</head>
<body>
<h1>Worker Leave Management</h1>
<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 Leave Type</option>
<option value="Annual">Annual</option>
<option value="Sick">Sick</option>
<option value="Other">Other</option>
</select>
<label for="startDate">Start Date:</label>
<input type="date" id="startDate" required>
<label for="endDate">End Date:</label>
<input type="date" id="endDate" required>
<button type="submit">Submit Leave Request</button>
</form>
<h2>Your Leave Requests</h2>
<table id="leaveRequestsTable">
<thead>
<tr>
<th>ID</th>
<th>Leave Type</th>
<th>Application Date</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>
<script>
const backendUrl = 'http://localhost:8081/api/leave-requests';
document.getElementById('applyLeaveForm').addEventListener('submit', async (e) => {
e.preventDefault();
const workerId = document.getElementById('workerId').value;
const supervisorId = document.getElementById('supervisorId').value;
const leaveType = document.getElementById('leaveType').value;
const startDate = document.getElementById('startDate').value;
const endDate = document.getElementById('endDate').value;
const leaveRequest = {
workerId,
supervisorId,
leaveType,
startDate: new Date(startDate),
endDate: new Date(endDate)
};
try {
const response = await fetch(`${backendUrl}/apply`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(leaveRequest)
});
const result = await response.text();
alert(result);
fetchLeaveRequests();
} catch (error) {
console.error('Error applying for leave:', error);
}
});
async function fetchLeaveRequests() {
const workerId = document.getElementById('workerId').value;
if (!workerId) {
alert('Please enter your Worker ID to fetch leave requests.');
return;
}
try {
const response = await fetch(`${backendUrl}/worker/${workerId}`);
const requests = await response.json();
const tbody = document.querySelector('#leaveRequestsTable tbody');
tbody.innerHTML = '';
requests.forEach(req => {
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${req.id}</td>
<td>${req.leaveType}</td>
<td>${new Date(req.applicationDate._seconds * 1000).toLocaleDateString()}</td>
<td>${new Date(req.startDate._seconds * 1000).toLocaleDateString()}</td>
<td>${new Date(req.endDate._seconds * 1000).toLocaleDateString()}</td>
<td>${req.status}</td>
<td>
${req.medicalCertificateUrl ? '<a href="data:image/*;base64,' + req.medicalCertificateUrl + '" target="_blank">View</a>' : 'N/A'}
</td>
<td>
${req.leaveType === 'Sick' && !req.medicalCertificateUrl ? `
<input type="file" id="file-${req.id}">
<button onclick="uploadCertificate('${req.id}')">Upload</button>
` : '—'}
</td>
`;
tbody.appendChild(tr);
});
} catch (error) {
console.error('Error fetching leave requests:', error);
}
}
async function uploadCertificate(id) {
const fileInput = document.getElementById(`file-${id}`);
if (fileInput.files.length === 0) {
alert('Please select a file to upload.');
return;
}
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch(`${backendUrl}/${id}/upload-certificate`, {
method: 'PUT',
body: formData
});
const result = await response.text();
alert(result);
fetchLeaveRequests();
} catch (error) {
console.error('Error uploading medical certificate:', error);
}
}
// Fetch leave requests when Worker ID changes
document.getElementById('workerId').addEventListener('blur', fetchLeaveRequests);
</script>
</body>
</html>
Usage Instructions:
- Run the Backend: Ensure your Spring Boot application is running on
localhost:8081.
- Open Worker Interface: Open
worker.html in your web browser.
- Apply for Leave:
- Enter your
Worker ID and Supervisor ID.
- Select
Leave Type (e.g., Annual, Sick).
- Choose
Start Date and End Date.
- Click
Submit Leave Request.
- View Leave Requests:
- Enter your
Worker ID.
- Your leave requests will appear in the table below.
- Upload Medical Certificate (if applicable):
- For sick leave requests without a medical certificate, an upload option will appear.
- Select an image file and click
Upload.
2. Supervisor Interface
HTML: supervisor.html
<!-- File: frontend/supervisor.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Supervisor Leave Management</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
input { width: 100%; padding: 8px; margin-top: 10px; }
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th, td { border: 1px solid #ccc; padding: 10px; text-align: left; }
th { background-color: #f4f4f4; }
button { padding: 5px 10px; margin-right: 5px; }
</style>
</head>
<body>
<h1>Supervisor Leave Management</h1>
<h2>View Leave Requests</h2>
<label for="supervisorId">Supervisor ID:</label>
<input type="text" id="supervisorId">
<button onclick="fetchLeaveRequests()">Fetch Leave Requests</button>
<table id="supervisorLeaveRequestsTable">
<thead>
<tr>
<th>ID</th>
<th>Worker ID</th>
<th>Leave Type</th>
<th>Application Date</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>
<script>
const backendUrl = 'http://localhost:8081/api/leave-requests';
async function fetchLeaveRequests() {
const supervisorId = document.getElementById('supervisorId').value;
if (!supervisorId) {
alert('Please enter your Supervisor ID.');
return;
}
try {
const response = await fetch(`${backendUrl}/supervisor/${supervisorId}`);
const requests = await response.json();
const tbody = document.querySelector('#supervisorLeaveRequestsTable tbody');
tbody.innerHTML = '';
requests.forEach(req => {
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${req.id}</td>
<td>${req.workerId}</td>
<td>${req.leaveType}</td>
<td>${new Date(req.applicationDate._seconds * 1000).toLocaleDateString()}</td>
<td>${new Date(req.startDate._seconds * 1000).toLocaleDateString()}</td>
<td>${new Date(req.endDate._seconds * 1000).toLocaleDateString()}</td>
<td>${req.status}</td>
<td>
${req.medicalCertificateUrl ? '<a href="data:image/*;base64,' + req.medicalCertificateUrl + '" target="_blank">View</a>' : 'N/A'}
</td>
<td>
${req.status === 'Pending' ? `
<button onclick="approveRequest('${req.id}')">Approve</button>
<button onclick="rejectRequest('${req.id}')">Reject</button>
` : '—'}
</td>
`;
tbody.appendChild(tr);
});
} catch (error) {
console.error('Error fetching leave requests:', error);
}
}
async function approveRequest(id) {
if (!confirm('Are you sure you want to approve this leave request?')) return;
try {
const response = await fetch(`${backendUrl}/${id}/approve`, { method: 'PUT' });
const result = await response.text();
alert(result);
fetchLeaveRequests();
} catch (error) {
console.error('Error approving leave request:', error);
}
}
async function rejectRequest(id) {
if (!confirm('Are you sure you want to reject this leave request?')) return;
try {
const response = await fetch(`${backendUrl}/${id}/reject`, { method: 'PUT' });
const result = await response.text();
alert(result);
fetchLeaveRequests();
} catch (error) {
console.error('Error rejecting leave request:', error);
}
}
</script>
</body>
</html>
Usage Instructions:
- Run the Backend: Ensure your Spring Boot application is running on
localhost:8081.
- Open Supervisor Interface: Open
supervisor.html in your web browser.
- View Leave Requests:
- Enter your
Supervisor ID.
- Click
Fetch Leave Requests.
- All pending, approved, and rejected leave requests from your supervisees will appear in the table.
- Approve/Reject Requests:
- For each pending request, click
Approve or Reject as needed.
- Confirm the action in the prompt.
- The status will update accordingly.
Key Points and Considerations
-
Authentication & Authorization:
- The current implementation assumes that
workerId and supervisorId are correctly provided.
- For a production system, implement proper authentication (e.g., JWT tokens) and verify that users can only perform actions they are authorized to.
-
File Storage:
- Medical certificates are stored as Base64 encoded strings in Firestore. For larger files or better performance, consider using Firebase Storage and storing the URLs in Firestore.
-
Date Handling:
- Firestore stores dates as timestamps. Ensure correct conversion between client-side JavaScript
Date objects and Firestore timestamps.
-
Error Handling:
- Enhance error handling on both frontend and backend for better user experience and debugging.
-
UI Enhancements:
- The provided frontend interfaces are basic. Consider using frameworks like React, Vue, or Angular for a more robust UI.
-
CORS Configuration:
- Adjust the
@CrossOrigin annotation in the controller based on where your frontend is hosted.
-
Security Rules:
- Implement Firebase Firestore security rules to restrict data access based on user roles and IDs.
-
Testing:
- Thoroughly test all functionalities to ensure data integrity and security.
Conclusion
This implementation provides a foundational structure for a leave management system using Spring Boot and Firebase Firestore. It includes backend functionalities for applying, viewing, updating, approving, and rejecting leave requests, along with simple frontend interfaces for interaction. Ensure to enhance and secure the system based on your specific requirements and best practices.