Skip to content
Snippets Groups Projects
Commit d1b03643 authored by Mingyuan Chen's avatar Mingyuan Chen
Browse files

Updated fuzzy query and delete features

parent 5acbc71f
No related branches found
No related tags found
1 merge request!59Updated fuzzy query and delete features
package com.cardiff.client_project.controller.admin;
import com.cardiff.client_project.pojo.dto.HospitalDTO;
import com.cardiff.client_project.service.CommonAdminHospitalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/commonAdmin/hospital")
public class CommonAdminHospitalController {
@Autowired
private CommonAdminHospitalService commonAdminHospitalService;
@GetMapping("/all")
public List<HospitalDTO> getAllHospitals(@RequestParam(value = "name", required = false) String name,
@RequestParam(value = "location", required = false) String location) {
if (name == null && location == null) {
return commonAdminHospitalService.getAllHospitals();
}
return commonAdminHospitalService.searchHospitals(name, location);
}
@PostMapping("/add")
public ResponseEntity<String> addHospital(@RequestBody HospitalDTO hospital) {
try {
commonAdminHospitalService.addHospital(hospital);
return ResponseEntity.ok("Hospital added successfully!");
} catch (Exception e) {
e.printStackTrace(); // Print error log
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Error adding hospital: " + e.getMessage());
}
}
@PutMapping("/update")
public ResponseEntity<String> updateHospital(@RequestBody HospitalDTO hospital) {
commonAdminHospitalService.updateHospital(hospital);
return ResponseEntity.ok("Hospital updated successfully!");
}
@DeleteMapping("/delete/{id}")
public ResponseEntity<String> deleteHospital(@PathVariable int id) {
commonAdminHospitalService.deleteHospital(id);
return ResponseEntity.ok("Hospital deleted successfully!");
}
}
package com.cardiff.client_project.mapper;
import com.cardiff.client_project.pojo.dto.HospitalDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class CommonAdminHospitalMapper {
@Autowired
JdbcTemplate jdbcTemplate;
// Query all hospital information
public List<HospitalDTO> findAll() {
String sql = "SELECT * FROM hospital";
return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(HospitalDTO.class));
}
// Add Hospital Information
public int save(HospitalDTO hospital) {
String sql = "INSERT INTO hospital (name, location, phone, totalBeds, availableBeds, occupancyRate) VALUES (?, ?, ?, ?, ?, ?)";
return jdbcTemplate.update(sql, hospital.getName(), hospital.getLocation(), hospital.getPhone(), hospital.getTotalBeds(), hospital.getAvailableBeds(), hospital.getOccupancyRate());
}
// Update Hospital Information
public int update(HospitalDTO hospital) {
String sql = "UPDATE hospital SET name=?, location=?, phone=?, totalBeds=?, availableBeds=?, occupancyRate=? WHERE id=?";
return jdbcTemplate.update(sql, hospital.getName(), hospital.getLocation(), hospital.getPhone(), hospital.getTotalBeds(), hospital.getAvailableBeds(), hospital.getOccupancyRate(), hospital.getId());
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hospital Management</title>
<link rel="stylesheet" type="text/css" href="../css/admin.css">
</head>
<body>
<nav class="sidebar">
<div class="text-lg font-semibold">System</div>
<a href="#" data-content="hospital">Hospital</a>
<a href="#" data-content="patient">Nursing staff</a>
<a href="#" data-content="logout">LogOut</a>
</nav>
<div class="content">
<div id="dynamic-content">
<h1>Welcome to the Management System</h1>
<p>Select an option from the sidebar to get started.</p>
</div>
</div>
<!-- Modal for Adding or Editing Hospital -->
<div id="hospital-modal" class="modal" style="display: none;">
<div class="modal-content">
<h2 id="modal-title">Add New Hospital</h2>
<label for="modal-name">Name</label>
<input type="text" id="modal-name" placeholder="Enter name" />
<label for="modal-location">Location</label>
<input type="text" id="modal-location" placeholder="Enter location" />
<label for="modal-phone">Phone</label>
<input type="text" id="modal-phone" placeholder="Enter phone number" />
<label for="modal-totalBeds">Total Beds</label>
<input type="number" id="modal-totalBeds" placeholder="Enter total beds" />
<label for="modal-availableBeds">Available Beds</label>
<input type="number" id="modal-availableBeds" placeholder="Enter available beds" />
<div class="modal-footer">
<button id="save-hospital-btn">Save</button>
<button id="close-hospital-modal">Close</button>
</div>
</div>
</div>
<script>
const dynamicContent = document.getElementById("dynamic-content");
function loadHospitalInterface() {
dynamicContent.innerHTML = `
<div id="toolbar">
<label for="searchName">Name</label>
<input type="text" id="searchName" placeholder="Search by name" />
<label for="searchLocation">Location</label>
<input type="text" id="searchLocation" placeholder="Search by location" />
<button id="searchButton">Search</button>
<button id="allButton">All</button>
<button id="addHospitalButton">Add Hospital</button>
</div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Location</th>
<th>Phone</th>
<th>Total Beds</th>
<th>Available Beds</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="table-body"></tbody>
</table>
`;
document.getElementById('searchButton').addEventListener('click', () => {
const name = document.getElementById('searchName').value;
const location = document.getElementById('searchLocation').value;
loadHospitals({ name, location });
});
document.getElementById('allButton').addEventListener('click', () => {
loadHospitals();
});
document.getElementById('addHospitalButton').addEventListener('click', () => {
openAddHospitalModal();
});
loadHospitals();
}
function openAddHospitalModal() {
document.getElementById('modal-title').innerText = "Add New Hospital";
document.getElementById('hospital-modal').style.display = 'flex';
// Clear the input fields in the modal box
document.getElementById('modal-name').value = '';
document.getElementById('modal-location').value = '';
document.getElementById('modal-phone').value = '';
document.getElementById('modal-totalBeds').value = '';
document.getElementById('modal-availableBeds').value = '';
// Bind save button event
document.getElementById('save-hospital-btn').onclick = saveHospital;
}
// Save new hospital information
function saveHospital() {
const name = document.getElementById('modal-name').value;
const location = document.getElementById('modal-location').value;
const phone = document.getElementById('modal-phone').value;
const totalBeds = document.getElementById('modal-totalBeds').value;
const availableBeds = document.getElementById('modal-availableBeds').value;
const newHospital = {
name,
location,
phone,
totalBeds: parseInt(totalBeds, 10),
availableBeds: parseInt(availableBeds, 10),
};
console.log("Sending data to backend:", newHospital); // Print the sent data
fetch('/commonAdmin/hospital/add', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newHospital),
})
.then((response) => {
if (response.ok) {
alert("Hospital added successfully!");
document.getElementById('hospital-modal').style.display = 'none';
loadHospitals();
} else {
throw new Error("Failed to add hospital");
}
})
.catch((error) => {
console.error(error); // Print error message
alert("An error occurred while adding the hospital.");
});
}
// Load hospital list
function loadHospitals(filters = {}) {
const query = new URLSearchParams(filters).toString();
fetch(`/commonAdmin/hospital/all?${query}`)
.then((response) => response.json())
.then((data) => {
const tableBody = document.getElementById('table-body');
tableBody.innerHTML = '';
data.forEach((hospital) => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${hospital.id}</td>
<td>${hospital.name}</td>
<td>${hospital.location}</td>
<td>${hospital.phone}</td>
<td>${hospital.totalBeds}</td>
<td>${hospital.availableBeds}</td>
<td>
<button data-id="${hospital.id}" class="editButton">Edit</button>
<button data-id="${hospital.id}" class="deleteButton">Delete</button>
</td>
`;
tableBody.appendChild(row);
});
document.querySelectorAll('.editButton').forEach(button => {
button.addEventListener('click', handleEditHospital);
});
document.querySelectorAll('.deleteButton').forEach(button => {
button.addEventListener('click', handleDeleteHospital);
});
})
.catch((error) => console.error(error));
}
// Processing editing hospital
function handleEditHospital(event) {
const id = event.target.dataset.id;
fetch(`/commonAdmin/hospital/all`)
.then((response) => response.json())
.then((data) => {
const hospital = data.find((h) => h.id === parseInt(id, 10));
if (hospital) {
document.getElementById('modal-title').innerText = "Edit Hospital";
document.getElementById('modal-name').value = hospital.name;
document.getElementById('modal-location').value = hospital.location;
document.getElementById('modal-phone').value = hospital.phone;
document.getElementById('modal-totalBeds').value = hospital.totalBeds;
document.getElementById('modal-availableBeds').value = hospital.availableBeds;
document.getElementById('hospital-modal').style.display = 'flex';
document.getElementById('save-hospital-btn').onclick = () => saveEditedHospital(id);
}
})
.catch((error) => console.error('Error loading hospital data:', error));
}
// Save the edited hospital information
function saveEditedHospital(id) {
const updatedHospital = {
id: parseInt(id, 10),
name: document.getElementById('modal-name').value,
location: document.getElementById('modal-location').value,
phone: document.getElementById('modal-phone').value,
totalBeds: parseInt(document.getElementById('modal-totalBeds').value, 10),
availableBeds: parseInt(document.getElementById('modal-availableBeds').value, 10),
};
fetch('/commonAdmin/hospital/update', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updatedHospital),
})
.then(() => {
alert('Hospital updated successfully!');
document.getElementById('hospital-modal').style.display = 'none';
loadHospitals();
})
.catch((error) => console.error('Error updating hospital:', error));
}
// Delete hospital
function handleDeleteHospital(event) {
const id = event.target.dataset.id;
fetch(`/commonAdmin/hospital/delete/${id}`, { method: 'DELETE' })
.then(() => loadHospitals())
.catch((error) => console.error(error));
}
// Close the mode box
document.getElementById('close-hospital-modal').addEventListener('click', () => {
document.getElementById('hospital-modal').style.display = 'none';
});
// Initializes sidebar navigation events
document.querySelectorAll(".sidebar a").forEach(link => {
link.addEventListener("click", function (event) {
event.preventDefault();
const contentKey = this.getAttribute("data-content");
if (contentKey === "hospital") {
loadHospitalInterface();
}
});
});
</script>
</body>
</html>
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment