Users can upload image afterwards, and it will update the same document, not create a new one.
The uploaded image can be publicly accessed by anyone. No need for authorization. This means I cna just go to the url and access it from my browser
Give me entire code.
LeaveRequestRepository:
package com.g4t4.home_cleaning_scheduler.repository;
@Repository
public class LeaveRequestRepository extends AbstractFirestoreRepository {
code
@Autowired
public LeaveRequestRepository(Firestore firestore) {
super(firestore, "leave_requests");
}
public boolean saveLeaveRequest(LeaveRequest leaveRequest) {
return save(leaveRequest);
}
public void deleteLeaveRequest(LeaveRequest leaveRequest) {
delete(leaveRequest);
}
public CollectionReference getCollectionReference() {
return super.getCollectionReference();
}
// Additional methods to get leave requests by workerId, supervisorId, etc., can be added if needed.
To implement your requested adjustments, we'll ensure that:
Image Upload is Optional: Users are not required to upload an image when submitting a leave request, even for medical leave types.
Update Existing Leave Requests: Users can upload an image after the initial submission, updating the same leave request document instead of creating a new one.
Public Access to Uploaded Images: Uploaded images are publicly accessible via their URLs without requiring authorization.
Below is the complete code for the LeaveRequestRepository, LeaveRequestService, and LeaveRequestController with the necessary modifications to fulfill these requirements.
1. LeaveRequestRepository
No changes are needed in the repository as it already provides the necessary CRUD operations for LeaveRequest objects.
java
package com.g4t4.home_cleaning_scheduler.repository;
import com.g4t4.home_cleaning_scheduler.model.LeaveRequest;
import com.google.cloud.firestore.CollectionReference;
import com.google.cloud.firestore.Firestore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class LeaveRequestRepository extends AbstractFirestoreRepository<LeaveRequest> {
@Autowired
public LeaveRequestRepository(Firestore firestore) {
super(firestore, "leave_requests");
}
public boolean saveLeaveRequest(LeaveRequest leaveRequest) {
return save(leaveRequest);
}
public void deleteLeaveRequest(LeaveRequest leaveRequest) {
delete(leaveRequest);
}
public CollectionReference getCollectionReference() {
return super.getCollectionReference();
}
// Additional methods to get leave requests by workerId, supervisorId, etc., can be added if needed.
}
2. LeaveRequestService
The service class is modified to make the image upload optional during the initial submission and to update the same document when uploading the image later. The uploaded images are set to be publicly accessible.
java
Key Modifications:
Optional Image Upload on Submission: The submitLeaveRequest method no longer enforces the presence of medicalCertificateFile. It only uploads the image if it's provided.
Updating Existing Leave Request: The uploadMedicalCertificate method updates the medicalCertificateUrl field of an existing leave request without creating a new document.
Public Access to Images: The uploadMedicalCertificate method sets the ACL to Acl.Role.READER for all users, making the image publicly accessible via its URL.
3. LeaveRequestController
The controller provides endpoints for submitting leave requests, uploading medical certificates later, approving/rejecting requests, and fetching leave requests. The image upload during submission is optional, and the upload endpoint updates the existing leave request.
java
Key Modifications:
Optional Image Upload During Submission: The @RequestParam for medicalCertificate in the submitLeaveRequest method is marked as required = false, making it optional.
Uploading Image After Submission: The uploadMedicalCertificate endpoint (PUT /{leaveRequestId}/upload-medical-certificate) allows users to upload an image after the initial leave request submission. This method updates the existing leave request document with the new image URL.
Public Access to Images: No additional changes are needed in the controller since the service already handles setting the appropriate ACL for public access.
4. LeaveRequest Model (Assumed)
Ensure that your LeaveRequest model includes a field for medicalCertificateUrl and that it's appropriately handled (e.g., nullable).
java
package com.g4t4.home_cleaning_scheduler.model;
public class LeaveRequest {
private String leaveRequestId;
private String workerId;
private String supervisorId;
private String leaveType;
private String status;
private String medicalCertificateUrl; // Make sure this is present
// Other fields, getters, and setters
public String getMedicalCertificateUrl() {
return medicalCertificateUrl;
}
public void setMedicalCertificateUrl(String medicalCertificateUrl) {
this.medicalCertificateUrl = medicalCertificateUrl;
}
// Getters and setters for other fields
}
Note: Ensure that the medicalCertificateUrl field is optional (i.e., can be null) to accommodate leave requests submitted without an image.
5. Additional Considerations
Error Handling: The provided controller methods include basic error handling. Depending on your application's requirements, you might want to implement more robust error handling mechanisms.
Security: While the uploaded images are publicly accessible, ensure that other parts of your application are properly secured to prevent unauthorized modifications to leave requests.
Validation: Consider adding validation for the LeaveRequest object to ensure data integrity.
Firebase Configuration: Ensure that your Firebase project is correctly configured, and the service account has the necessary permissions to interact with Firestore and Firebase Storage.
CORS Configuration: If your frontend is hosted on a different domain, make sure to configure CORS appropriately in your Spring Boot application.
With these modifications, your application should now allow users to submit leave requests without mandatory image uploads, upload images later to update existing requests, and ensure that uploaded images are publicly accessible via their URLs. If you encounter any specific issues or have further requirements, feel free to ask!
Not yet included in a published release.
package com.g4t4.home_cleaning_scheduler.service;
import com.g4t4.home_cleaning_scheduler.model.LeaveRequest;
import com.g4t4.home_cleaning_scheduler.model.User;
import com.g4t4.home_cleaning_scheduler.repository.LeaveRequestRepository;
import com.g4t4.home_cleaning_scheduler.repository.UserRepository;
import com.google.api.core.ApiFuture;
import com.google.cloud.firestore.CollectionReference;
import com.google.cloud.firestore.Query;
import com.google.cloud.firestore.QuerySnapshot;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Acl;
import com.google.firebase.cloud.StorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
@Service
public class LeaveRequestService {
private final LeaveRequestRepository leaveRequestRepository;
@Autowired
private UserRepository userRepository;
@Autowired
public LeaveRequestService(LeaveRequestRepository leaveRequestRepository) {
this.leaveRequestRepository = leaveRequestRepository;
}
/**
* Submits a new leave request. Image upload is optional.
*
* @param leaveRequest The leave request details.
* @param medicalCertificateFile The medical certificate image file (optional).
* @return true if the leave request is saved successfully.
* @throws IOException if there's an error processing the image.
*/
public boolean submitLeaveRequest(LeaveRequest leaveRequest, MultipartFile medicalCertificateFile) throws IOException {
// Check if the leave type is Medical and if an image is provided
if ("Medical".equalsIgnoreCase(leaveRequest.getLeaveType())) {
if (medicalCertificateFile != null && !medicalCertificateFile.isEmpty()) {
String imageUrl = uploadMedicalCertificate(medicalCertificateFile);
leaveRequest.setMedicalCertificateUrl(imageUrl);
}
// Image is optional; proceed without it if not provided
}
// Generate a unique ID for the leave request
String leaveRequestId = UUID.randomUUID().toString();
leaveRequest.setLeaveRequestId(leaveRequestId);
return leaveRequestRepository.saveLeaveRequest(leaveRequest);
}
/**
* Uploads a medical certificate image and updates the corresponding leave request.
*
* @param leaveRequestId The ID of the leave request to update.
* @param medicalCertificateFile The medical certificate image file.
* @return true if the update is successful.
* @throws IOException if there's an error processing the image.
* @throws ExecutionException
* @throws InterruptedException
*/
public boolean uploadMedicalCertificate(String leaveRequestId, MultipartFile medicalCertificateFile) throws IOException, ExecutionException, InterruptedException {
if (medicalCertificateFile == null || medicalCertificateFile.isEmpty()) {
throw new IllegalArgumentException("Medical certificate image is required.");
}
// Retrieve existing leave request
Optional<LeaveRequest> optionalLeaveRequest = leaveRequestRepository.get(leaveRequestId);
if (!optionalLeaveRequest.isPresent()) {
throw new IllegalArgumentException("Leave request not found.");
}
LeaveRequest leaveRequest = optionalLeaveRequest.get();
// Upload the image
String imageUrl = uploadMedicalCertificate(medicalCertificateFile);
leaveRequest.setMedicalCertificateUrl(imageUrl);
// Update the leave request
return leaveRequestRepository.saveLeaveRequest(leaveRequest);
}
/**
* Updates the status of a leave request.
*
* @param leaveRequestId The ID of the leave request.
* @param adminId The ID of the admin updating the request.
* @param status The new status ("Approved" or "Rejected").
* @return true if the update is successful.
* @throws ExecutionException
* @throws InterruptedException
*/
public boolean updateLeaveRequestStatus(String leaveRequestId, String adminId, String status) throws ExecutionException, InterruptedException {
// Retrieve the leave request
Optional<LeaveRequest> optionalLeaveRequest = leaveRequestRepository.get(leaveRequestId);
if (!optionalLeaveRequest.isPresent()) {
throw new IllegalArgumentException("Leave request not found.");
}
LeaveRequest leaveRequest = optionalLeaveRequest.get();
// Check if the admin is the supervisor of the worker
if (!leaveRequest.getSupervisorId().equals(adminId)) {
throw new IllegalArgumentException("Admin is not authorized to update this leave request.");
}
leaveRequest.setStatus(status);
return leaveRequestRepository.saveLeaveRequest(leaveRequest);
}
/**
* Approves a leave request.
*
* @param leaveRequestId The ID of the leave request.
* @param adminId The ID of the admin approving the request.
* @return true if the approval is successful.
* @throws ExecutionException
* @throws InterruptedException
*/
public boolean approveLeaveRequest(String leaveRequestId, String adminId) throws ExecutionException, InterruptedException {
return updateLeaveRequestStatus(leaveRequestId, adminId, "Approved");
}
/**
* Rejects a leave request.
*
* @param leaveRequestId The ID of the leave request.
* @param adminId The ID of the admin rejecting the request.
* @return true if the rejection is successful.
* @throws ExecutionException
* @throws InterruptedException
*/
public boolean rejectLeaveRequest(String leaveRequestId, String adminId) throws ExecutionException, InterruptedException {
return updateLeaveRequestStatus(leaveRequestId, adminId, "Rejected");
}
/**
* Uploads the medical certificate image to Firebase Storage with public access.
*
* @param file The image file to upload.
* @return The public URL of the uploaded image.
* @throws IOException if an error occurs during upload.
*/
private String uploadMedicalCertificate(MultipartFile file) throws IOException {
String bucketName = "clean-affcc.appspot.com"; // Replace with your Firebase bucket name
String folderName = "medical_certificates";
String fileName = folderName + "/" + UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
// Build the blob info with public read ACL
BlobInfo blobInfo = BlobInfo.newBuilder(bucketName, fileName)
.setContentType(file.getContentType())
.setAcl(
List.of(Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER))
)
.build();
// Upload to Cloud Storage
StorageClient.getInstance().bucket(bucketName).create(blobInfo.getName(), file.getBytes(), blobInfo.getContentType());
// Return the public URL to the uploaded file
return String.format("https://storage.googleapis.com/%s/%s", bucketName, fileName);
}
/**
* Retrieves all leave requests supervised by a specific supervisor.
*
* @param supervisorId The ID of the supervisor.
* @return A list of matching leave requests.
* @throws ExecutionException
* @throws InterruptedException
*/
public List<LeaveRequest> getLeaveRequestsBySupervisor(String supervisorId) throws ExecutionException, InterruptedException {
CollectionReference collection = leaveRequestRepository.getCollectionReference();
Query query = collection.whereEqualTo("supervisorId", supervisorId);
ApiFuture<QuerySnapshot> querySnapshot = query.get();
return querySnapshot.get().getDocuments().stream()
.map(document -> document.toObject(LeaveRequest.class))
.collect(Collectors.toList());
}
/**
* Retrieves all leave requests submitted by a specific worker.
*
* @param workerId The ID of the worker.
* @return A list of matching leave requests.
* @throws ExecutionException
* @throws InterruptedException
*/
public List<LeaveRequest> getLeaveRequestsByWorker(String workerId) throws ExecutionException, InterruptedException {
CollectionReference collection = leaveRequestRepository.getCollectionReference();
Query query = collection.whereEqualTo("workerId", workerId);
ApiFuture<QuerySnapshot> querySnapshot = query.get();
return querySnapshot.get().getDocuments().stream()
.map(document -> document.toObject(LeaveRequest.class))
.collect(Collectors.toList());
}
/**
* Retrieves all approved leave requests.
*
* @return A list of approved leave requests.
* @throws ExecutionException
* @throws InterruptedException
*/
public List<LeaveRequest> getApprovedLeaveRequests() throws ExecutionException, InterruptedException {
CollectionReference collection = leaveRequestRepository.getCollectionReference();
Query query = collection.whereEqualTo("status", "Approved");
ApiFuture<QuerySnapshot> querySnapshot = query.get();
return querySnapshot.get().getDocuments().stream()
.map(document -> document.toObject(LeaveRequest.class))
.collect(Collectors.toList());
}
/**
* Scheduled task that runs daily at midnight to notify admins about pending medical certificates.
*
* @throws ExecutionException
* @throws InterruptedException
*/
@Scheduled(cron = "0 0 0 * * *") // Runs daily at midnight
public void notifyAdminsForPendingMedicalCertificates() throws ExecutionException, InterruptedException {
CollectionReference collection = leaveRequestRepository.getCollectionReference();
Query query = collection
.whereEqualTo("leaveType", "Medical")
.whereEqualTo("status", "Pending")
.whereEqualTo("medicalCertificateUrl", null);
ApiFuture<QuerySnapshot> querySnapshot = query.get();
List<LeaveRequest> leaveRequests = querySnapshot.get().getDocuments().stream()
.map(document -> document.toObject(LeaveRequest.class))
.collect(Collectors.toList());
for (LeaveRequest leaveRequest : leaveRequests) {
// Get supervisor/admin information
String supervisorId = leaveRequest.getSupervisorId();
User supervisor = userRepository.findUserById(supervisorId);
if (supervisor != null) {
// Send notification to supervisor
// Implement your notification logic here (e.g., send email)
System.out.println("Sending notification to admin: " + supervisor.getEmail());
// Placeholder for notification logic
}
}
}
}
package com.g4t4.home_cleaning_scheduler.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
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.List;
import java.util.concurrent.ExecutionException;
@RestController
@RequestMapping("/api/leave-requests")
public class LeaveRequestController {
@Autowired
private LeaveRequestService leaveRequestService;
/**
* Submits a new leave request. Image upload is optional.
*
* @param leaveRequestJson The JSON representation of the leave request.
* @param medicalCertificate The medical certificate image file (optional).
* @return A response indicating the result of the operation.
*/
@PostMapping(consumes = "multipart/form-data")
public ResponseEntity<String> submitLeaveRequest(@RequestParam("leaveRequest") String leaveRequestJson,
@RequestParam(value = "medicalCertificate", required = false) MultipartFile medicalCertificate) {
try {
// Convert leaveRequestJson to LeaveRequest object
ObjectMapper objectMapper = new ObjectMapper();
LeaveRequest leaveRequest = objectMapper.readValue(leaveRequestJson, LeaveRequest.class);
boolean success = leaveRequestService.submitLeaveRequest(leaveRequest, medicalCertificate);
if (success) {
return ResponseEntity.status(HttpStatus.CREATED).body("Leave request submitted successfully.");
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to submit leave request.");
}
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid request: " + e.getMessage());
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error processing leave request.");
}
}
/**
* Uploads a medical certificate image for an existing leave request.
*
* @param leaveRequestId The ID of the leave request to update.
* @param medicalCertificate The medical certificate image file.
* @return A response indicating the result of the operation.
*/
@PutMapping("/{leaveRequestId}/upload-medical-certificate")
public ResponseEntity<String> uploadMedicalCertificate(@PathVariable String leaveRequestId,
@RequestParam("medicalCertificate") MultipartFile medicalCertificate) {
try {
boolean success = leaveRequestService.uploadMedicalCertificate(leaveRequestId, medicalCertificate);
if (success) {
return ResponseEntity.ok("Medical certificate uploaded successfully.");
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload medical certificate.");
}
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid request: " + e.getMessage());
} catch (IOException | ExecutionException | InterruptedException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error uploading medical certificate.");
}
}
/**
* Approves a leave request.
*
* @param leaveRequestId The ID of the leave request.
* @param adminId The ID of the admin approving the request.
* @return A response indicating the result of the operation.
*/
@PostMapping("/{leaveRequestId}/approve")
public ResponseEntity<String> approveLeaveRequest(@PathVariable String leaveRequestId, @RequestParam("adminId") String adminId) {
try {
boolean success = leaveRequestService.approveLeaveRequest(leaveRequestId, adminId);
if (success) {
return ResponseEntity.ok("Leave request approved successfully.");
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to approve leave request.");
}
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid request: " + e.getMessage());
} catch (ExecutionException | InterruptedException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error approving leave request.");
}
}
/**
* Rejects a leave request.
*
* @param leaveRequestId The ID of the leave request.
* @param adminId The ID of the admin rejecting the request.
* @return A response indicating the result of the operation.
*/
@PostMapping("/{leaveRequestId}/reject")
public ResponseEntity<String> rejectLeaveRequest(@PathVariable String leaveRequestId, @RequestParam("adminId") String adminId) {
try {
boolean success = leaveRequestService.rejectLeaveRequest(leaveRequestId, adminId);
if (success) {
return ResponseEntity.ok("Leave request rejected successfully.");
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to reject leave request.");
}
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid request: " + e.getMessage());
} catch (ExecutionException | InterruptedException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error rejecting leave request.");
}
}
/**
* Retrieves all leave requests supervised by a specific supervisor.
*
* @param supervisorId The ID of the supervisor.
* @return A list of matching leave requests.
*/
@GetMapping("/supervisor/{supervisorId}")
public ResponseEntity<List<LeaveRequest>> getLeaveRequestsBySupervisor(@PathVariable String supervisorId) {
try {
List<LeaveRequest> leaveRequests = leaveRequestService.getLeaveRequestsBySupervisor(supervisorId);
return ResponseEntity.ok(leaveRequests);
} catch (ExecutionException | InterruptedException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
/**
* Retrieves all leave requests submitted by a specific worker.
*
* @param workerId The ID of the worker.
* @return A list of matching leave requests.
*/
@GetMapping("/worker/{workerId}")
public ResponseEntity<List<LeaveRequest>> getLeaveRequestsByWorker(@PathVariable String workerId) {
try {
List<LeaveRequest> leaveRequests = leaveRequestService.getLeaveRequestsByWorker(workerId);
return ResponseEntity.ok(leaveRequests);
} catch (ExecutionException | InterruptedException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
/**
* Retrieves all approved leave requests.
*
* @return A list of approved leave requests.
*/
@GetMapping("/approved")
public ResponseEntity<List<LeaveRequest>> getApprovedLeaveRequests() {
try {
List<LeaveRequest> leaveRequests = leaveRequestService.getApprovedLeaveRequests();
return ResponseEntity.ok(leaveRequests);
} catch (ExecutionException | InterruptedException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}