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

Fixed an issue where id cannot be automatically sorted and location cannot be...

Fixed an issue where id cannot be automatically sorted and location cannot be displayed normally after deletion.
parent 0b929da1
No related branches found
No related tags found
1 merge request!64Fixed an issue where id cannot be automatically sorted and location cannot be...
...@@ -5,7 +5,6 @@ import com.cardiff.client_project.service.CommonAdminHospitalService; ...@@ -5,7 +5,6 @@ import com.cardiff.client_project.service.CommonAdminHospitalService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
...@@ -32,7 +31,7 @@ public class CommonAdminHospitalController { ...@@ -32,7 +31,7 @@ public class CommonAdminHospitalController {
commonAdminHospitalService.addHospital(hospital); commonAdminHospitalService.addHospital(hospital);
return ResponseEntity.ok("Hospital added successfully!"); return ResponseEntity.ok("Hospital added successfully!");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); // Print error log e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Error adding hospital: " + e.getMessage()); .body("Error adding hospital: " + e.getMessage());
} }
...@@ -40,27 +39,29 @@ public class CommonAdminHospitalController { ...@@ -40,27 +39,29 @@ public class CommonAdminHospitalController {
@GetMapping("/currentUser") @GetMapping("/currentUser")
public ResponseEntity<String> getCurrentUser() { public ResponseEntity<String> getCurrentUser() {
try { String username = "admin";
String username = SecurityContextHolder.getContext().getAuthentication().getName();
return ResponseEntity.ok(username); return ResponseEntity.ok(username);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Unable to fetch current user.");
} }
}
@PutMapping("/update") @PutMapping("/update")
public ResponseEntity<String> updateHospital(@RequestBody HospitalDTO hospital) { public ResponseEntity<String> updateHospital(@RequestBody HospitalDTO hospital) {
try {
commonAdminHospitalService.updateHospital(hospital); commonAdminHospitalService.updateHospital(hospital);
return ResponseEntity.ok("Hospital updated successfully!"); return ResponseEntity.ok("Hospital updated successfully!");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Error updating hospital: " + e.getMessage());
}
} }
@DeleteMapping("/delete/{id}") @DeleteMapping("/delete/{id}")
public ResponseEntity<String> deleteHospital(@PathVariable int id) { public ResponseEntity<String> deleteHospital(@PathVariable int id) {
try {
commonAdminHospitalService.deleteHospital(id); commonAdminHospitalService.deleteHospital(id);
return ResponseEntity.ok("Hospital deleted successfully!"); return ResponseEntity.ok("Hospital deleted successfully!");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Failed to delete hospital: " + e.getMessage());
}
} }
} }
...@@ -33,4 +33,6 @@ public class CommonAdminHospitalMapper { ...@@ -33,4 +33,6 @@ public class CommonAdminHospitalMapper {
} }
} }
...@@ -6,6 +6,7 @@ import lombok.Data; ...@@ -6,6 +6,7 @@ import lombok.Data;
public class HospitalDTO { public class HospitalDTO {
private int id; private int id;
private String name; private String name;
private String address;
private String location; private String location;
private String phone; private String phone;
private int totalBeds; private int totalBeds;
......
...@@ -35,21 +35,20 @@ public class CommonAdminHospitalServiceImp implements CommonAdminHospitalService ...@@ -35,21 +35,20 @@ public class CommonAdminHospitalServiceImp implements CommonAdminHospitalService
@Override @Override
public void addHospital(HospitalDTO hospital) { public void addHospital(HospitalDTO hospital) {
if (hospital.getName() == null || hospital.getLocation() == null || if (hospital.getName() == null || hospital.getAddress() == null || // 修改为 address
hospital.getPhone() == null || hospital.getTotalBeds() <= 0 || hospital.getPhone() == null || hospital.getTotalBeds() <= 0 ||
hospital.getAvailableBeds() < 0) { hospital.getAvailableBeds() < 0) {
throw new IllegalArgumentException("Invalid hospital data: Missing or incorrect fields."); throw new IllegalArgumentException("Invalid hospital data: Missing or incorrect fields.");
} }
String sql = "INSERT INTO hospital (name, location, phone, totalBeds, availableBeds, occupancyRate) VALUES (?, ?, ?, ?, ?, ?)";
double occupancyRate = 1.0 - (double) hospital.getAvailableBeds() / hospital.getTotalBeds(); double occupancyRate = 1.0 - (double) hospital.getAvailableBeds() / hospital.getTotalBeds();
jdbcTemplate.update(sql, hospital.getName(), hospital.getLocation(), hospital.getPhone(), String sql = "INSERT INTO hospital (name, address, phone, totalBeds, availableBeds, occupancyRate) VALUES (?, ?, ?, ?, ?, ?)";
jdbcTemplate.update(sql, hospital.getName(), hospital.getAddress(), hospital.getPhone(),
hospital.getTotalBeds(), hospital.getAvailableBeds(), occupancyRate); hospital.getTotalBeds(), hospital.getAvailableBeds(), occupancyRate);
} }
@Override @Override
public void updateHospital(HospitalDTO hospital) { public void updateHospital(HospitalDTO hospital) {
if (hospital.getId() <= 0 || hospital.getName() == null || hospital.getLocation() == null || if (hospital.getId() <= 0 || hospital.getName() == null || hospital.getLocation() == null ||
...@@ -68,10 +67,23 @@ public class CommonAdminHospitalServiceImp implements CommonAdminHospitalService ...@@ -68,10 +67,23 @@ public class CommonAdminHospitalServiceImp implements CommonAdminHospitalService
} }
} }
@Override @Override
public void deleteHospital(int id) { public void deleteHospital(int id) {
String sql = "DELETE FROM hospital WHERE id=?"; // Delete the specified record.
jdbcTemplate.update(sql, id); String deleteSql = "DELETE FROM hospital WHERE id = ?";
jdbcTemplate.update(deleteSql, id);
// Reorder ID
String reorderSql = "SET @new_id = 0; " +
"UPDATE hospital SET id = (@new_id := @new_id + 1); " +
"ALTER TABLE hospital AUTO_INCREMENT = 1;";
for (String sql : reorderSql.split(";")) {
if (!sql.trim().isEmpty()) {
jdbcTemplate.execute(sql.trim());
}
}
} }
} }
...@@ -14,9 +14,7 @@ ...@@ -14,9 +14,7 @@
<a><div onclick="chooseOut()">Sign Out</div></a> <a><div onclick="chooseOut()">Sign Out</div></a>
</nav> </nav>
<div class="content"> <div class="content">
<div id="user-info" style="text-align: right; padding: 10px; font-weight: bold;"></div> <div id="user-info" style="text-align: right; padding: 10px; font-weight: bold;"></div>
<div id="dynamic-content"> <div id="dynamic-content">
<h1>Welcome to the Management System</h1> <h1>Welcome to the Management System</h1>
<p>Select an option from the sidebar to get started.</p> <p>Select an option from the sidebar to get started.</p>
...@@ -29,8 +27,8 @@ ...@@ -29,8 +27,8 @@
<h2 id="modal-title">Add New Hospital</h2> <h2 id="modal-title">Add New Hospital</h2>
<label for="modal-name">Name</label> <label for="modal-name">Name</label>
<input type="text" id="modal-name" placeholder="Enter name" /> <input type="text" id="modal-name" placeholder="Enter name" />
<label for="modal-location">Location</label> <label for="modal-address">Address</label>
<input type="text" id="modal-location" placeholder="Enter location" /> <input type="text" id="modal-address" placeholder="Enter address" />
<label for="modal-phone">Phone</label> <label for="modal-phone">Phone</label>
<input type="text" id="modal-phone" placeholder="Enter phone number" /> <input type="text" id="modal-phone" placeholder="Enter phone number" />
<label for="modal-totalBeds">Total Beds</label> <label for="modal-totalBeds">Total Beds</label>
...@@ -47,19 +45,13 @@ ...@@ -47,19 +45,13 @@
<script> <script>
const dynamicContent = document.getElementById("dynamic-content"); const dynamicContent = document.getElementById("dynamic-content");
// Load the current login user information
function loadCurrentUser() { function loadCurrentUser() {
fetch('/commonAdmin/hospital/currentUser') fetch('/commonAdmin/hospital/currentUser')
.then(response => { .then(response => {
if (!response.ok) { if (!response.ok) throw new Error("Failed to fetch current user.");
throw new Error("Failed to fetch current user.");
}
return response.text(); return response.text();
}) })
.then(username => { .then(username => {
if (!username) {
throw new Error("No username received from server.");
}
document.getElementById('user-info').innerText = `Logged in as: ${username}`; document.getElementById('user-info').innerText = `Logged in as: ${username}`;
}) })
.catch(error => { .catch(error => {
...@@ -69,10 +61,9 @@ ...@@ -69,10 +61,9 @@
} }
function chooseOut() { function chooseOut() {
window.location.href="/logout" window.location.href = "/logout";
} }
// Initialize load user information
loadCurrentUser(); loadCurrentUser();
function loadHospitalInterface() { function loadHospitalInterface() {
...@@ -80,8 +71,8 @@ ...@@ -80,8 +71,8 @@
<div id="toolbar"> <div id="toolbar">
<label for="searchName">Name</label> <label for="searchName">Name</label>
<input type="text" id="searchName" placeholder="Search by name" /> <input type="text" id="searchName" placeholder="Search by name" />
<label for="searchLocation">Location</label> <label for="searchAddress">Address</label>
<input type="text" id="searchLocation" placeholder="Search by location" /> <input type="text" id="searchAddress" placeholder="Search by address" />
<button id="searchButton">Search</button> <button id="searchButton">Search</button>
<button id="allButton">All</button> <button id="allButton">All</button>
<button id="addHospitalButton">Add Hospital</button> <button id="addHospitalButton">Add Hospital</button>
...@@ -91,7 +82,7 @@ ...@@ -91,7 +82,7 @@
<tr> <tr>
<th>ID</th> <th>ID</th>
<th>Name</th> <th>Name</th>
<th>Location</th> <th>Address</th>
<th>Phone</th> <th>Phone</th>
<th>Total Beds</th> <th>Total Beds</th>
<th>Available Beds</th> <th>Available Beds</th>
...@@ -102,20 +93,7 @@ ...@@ -102,20 +93,7 @@
</table> </table>
`; `;
document.getElementById('searchButton').addEventListener('click', () => { bindToolbarEvents();
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(); loadHospitals();
} }
...@@ -123,89 +101,168 @@ ...@@ -123,89 +101,168 @@
document.getElementById('modal-title').innerText = "Add New Hospital"; document.getElementById('modal-title').innerText = "Add New Hospital";
document.getElementById('hospital-modal').style.display = 'flex'; document.getElementById('hospital-modal').style.display = 'flex';
// Clear the input fields in the modal box // Reset modal content
document.getElementById('modal-name').value = ''; document.getElementById('modal-name').value = '';
document.getElementById('modal-location').value = ''; document.getElementById('modal-address').value = '';
document.getElementById('modal-phone').value = ''; document.getElementById('modal-phone').value = '';
document.getElementById('modal-totalBeds').value = ''; document.getElementById('modal-totalBeds').value = '';
document.getElementById('modal-availableBeds').value = ''; document.getElementById('modal-availableBeds').value = '';
// Bind save button event
document.getElementById('save-hospital-btn').onclick = saveHospital; document.getElementById('save-hospital-btn').onclick = saveHospital;
} }
// Save new hospital information function closeHospitalModal() {
document.getElementById('hospital-modal').style.display = 'none';
}
function saveHospital() { function saveHospital() {
const name = document.getElementById('modal-name').value; const hospitalData = {
const location = document.getElementById('modal-location').value; name: document.getElementById('modal-name').value.trim(),
const phone = document.getElementById('modal-phone').value; address: document.getElementById('modal-address').value.trim(),
const totalBeds = document.getElementById('modal-totalBeds').value; phone: document.getElementById('modal-phone').value.trim(),
const availableBeds = document.getElementById('modal-availableBeds').value; totalBeds: parseInt(document.getElementById('modal-totalBeds').value, 10),
availableBeds: parseInt(document.getElementById('modal-availableBeds').value, 10),
const newHospital = {
name,
location,
phone,
totalBeds: parseInt(totalBeds, 10),
availableBeds: parseInt(availableBeds, 10),
}; };
if (!hospitalData.name || !hospitalData.address || !hospitalData.phone ||
isNaN(hospitalData.totalBeds) || isNaN(hospitalData.availableBeds)) {
alert("All fields are required!");
return;
}
fetch('/commonAdmin/hospital/add', { fetch('/commonAdmin/hospital/add', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newHospital), body: JSON.stringify(hospitalData),
}) }).then(response => {
.then((response) => {
if (response.ok) { if (response.ok) {
alert("Hospital added successfully!"); alert("Hospital saved successfully!");
document.getElementById('hospital-modal').style.display = 'none'; closeHospitalModal();
loadHospitals(); loadHospitals();
} else { } else {
throw new Error("Failed to add hospital"); return response.text().then(text => { throw new Error(text); });
} }
}) }).catch(error => {
.catch((error) => { console.error("Error adding hospital:", error);
console.error(error); alert("Failed to save hospital: " + error.message);
alert("An error occurred while adding the hospital.");
}); });
} }
function loadHospitals(filters = {}) { function loadHospitals(filters = {}) {
const query = new URLSearchParams(filters).toString(); const query = new URLSearchParams(filters).toString();
fetch(`/commonAdmin/hospital/all?${query}`) fetch(`/commonAdmin/hospital/all?${query}`)
.then((response) => response.json()) .then(response => response.json())
.then((data) => { .then(data => {
const tableBody = document.getElementById('table-body'); const tableBody = document.getElementById('table-body');
tableBody.innerHTML = ''; tableBody.innerHTML = '';
data.forEach((hospital) => {
data.forEach(hospital => {
const row = document.createElement('tr'); const row = document.createElement('tr');
row.innerHTML = ` row.innerHTML = `
<td>${hospital.id}</td> <td>${hospital.id}</td>
<td>${hospital.name}</td> <td>${hospital.name}</td>
<td>${hospital.location}</td> <td>${hospital.address}</td>
<td>${hospital.phone}</td> <td>${hospital.phone}</td>
<td>${hospital.totalBeds}</td> <td>${hospital.totalBeds}</td>
<td>${hospital.availableBeds}</td> <td>${hospital.availableBeds}</td>
<td> <td>
<button data-id="${hospital.id}" class="editButton">Edit</button> <button class="editButton" data-id="${hospital.id}">Edit</button>
<button data-id="${hospital.id}" class="deleteButton">Delete</button> <button class="deleteButton" data-id="${hospital.id}">Delete</button>
</td> </td>
`; `;
tableBody.appendChild(row); tableBody.appendChild(row);
}); });
document.querySelectorAll('.editButton').forEach(button => { bindRowEvents();
button.addEventListener('click', handleEditHospital); })
.catch(error => console.error("Error loading hospitals:", error));
}
function handleDeleteHospital(event) {
const id = event.target.getAttribute('data-id');
if (confirm(`Are you sure you want to delete the hospital with ID ${id}?`)) {
fetch(`/commonAdmin/hospital/delete/${id}`, { method: 'DELETE' })
.then(response => {
if (response.ok) {
alert("Deleted successfully!");
loadHospitals();
} else {
throw new Error("Failed to delete hospital.");
}
})
.catch(error => console.error("Error deleting hospital:", error));
}
}
function handleEditHospital(event) {
const id = event.target.getAttribute('data-id');
fetch(`/commonAdmin/hospital/${id}`)
.then(response => response.json())
.then(hospital => {
document.getElementById('modal-title').innerText = "Edit Hospital";
document.getElementById('modal-name').value = hospital.name;
document.getElementById('modal-address').value = hospital.address;
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 = () => updateHospital(id);
})
.catch(error => console.error("Error fetching hospital details:", error));
}
function updateHospital(id) {
const hospitalData = {
id,
name: document.getElementById('modal-name').value.trim(),
address: document.getElementById('modal-address').value.trim(),
phone: document.getElementById('modal-phone').value.trim(),
totalBeds: parseInt(document.getElementById('modal-totalBeds').value, 10),
availableBeds: parseInt(document.getElementById('modal-availableBeds').value, 10),
};
if (!hospitalData.name || !hospitalData.address || !hospitalData.phone ||
isNaN(hospitalData.totalBeds) || isNaN(hospitalData.availableBeds)) {
alert("All fields are required!");
return;
}
fetch('/commonAdmin/hospital/update', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(hospitalData),
}).then(response => {
if (response.ok) {
alert("Hospital updated successfully!");
closeHospitalModal();
loadHospitals();
} else {
return response.text().then(text => { throw new Error(text); });
}
}).catch(error => {
console.error("Error updating hospital:", error);
alert("Failed to update hospital: " + error.message);
}); });
}
function bindToolbarEvents() {
document.getElementById('addHospitalButton').addEventListener('click', openAddHospitalModal);
}
function bindRowEvents() {
document.querySelectorAll('.deleteButton').forEach(button => { document.querySelectorAll('.deleteButton').forEach(button => {
button.addEventListener('click', handleDeleteHospital); button.addEventListener('click', handleDeleteHospital);
}); });
})
.catch((error) => console.error(error)); document.querySelectorAll('.editButton').forEach(button => {
button.addEventListener('click', handleEditHospital);
});
} }
// Initializes the loading of the hospital management interface document.getElementById('close-hospital-modal').addEventListener('click', closeHospitalModal);
document.querySelectorAll(".sidebar a").forEach(link => { document.querySelectorAll(".sidebar a").forEach(link => {
link.addEventListener("click", function(event) { link.addEventListener("click", function(event) {
event.preventDefault(); event.preventDefault();
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment