Skip to content
Snippets Groups Projects
Commit b92c807d authored by Burhan Akbar's avatar Burhan Akbar
Browse files

Approval dashboard functionality

parents 1c4e36f9 6d8cbeea
Branches
No related tags found
No related merge requests found
Showing
with 590 additions and 192 deletions
/*
Navicat Premium Data Transfer
Navicat Premium Dump SQL
Source Server : wyl
Source Server Type : MySQL
Source Server Version : 80031
Source Server : Root
Source Server Type : MariaDB
Source Server Version : 101107 (10.11.7-MariaDB)
Source Host : localhost:3306
Source Schema : health_care
Source Schema : healthcare
Target Server Type : MySQL
Target Server Version : 80031
Target Server Type : MariaDB
Target Server Version : 101107 (10.11.7-MariaDB)
File Encoding : 65001
Date: 09/12/2024 10:09:27
Date: 11/12/2024 22:08:40
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for care_homes
-- ----------------------------
DROP TABLE IF EXISTS `care_homes`;
CREATE TABLE `care_homes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`address` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`status` enum('approved','rejected','pending') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT 'pending',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of care_homes
-- ----------------------------
INSERT INTO `care_homes` VALUES (1, 'Hospital1', 'Cardiff', 'pending');
INSERT INTO `care_homes` VALUES (2, 'Hospital2', 'Cardiff', 'pending');
INSERT INTO `care_homes` VALUES (3, 'Hospital3', 'London', 'pending');
INSERT INTO `care_homes` VALUES (4, 'Hospital4', 'London', 'pending');
INSERT INTO `care_homes` VALUES (5, 'Hospital5', 'Manchester', 'pending');
INSERT INTO `care_homes` VALUES (6, 'Hospital6', 'Manchester', 'pending');
INSERT INTO `care_homes` VALUES (7, 'Hospital7', 'Cardiff', 'pending');
INSERT INTO `care_homes` VALUES (8, 'Hospital8', 'Cardiff', 'pending');
INSERT INTO `care_homes` VALUES (9, 'Hospital9', 'Cardiff', 'pending');
INSERT INTO `care_homes` VALUES (10, 'Hospital10', 'Cardiff', 'pending');
-- ----------------------------
-- Table structure for common_admin
-- ----------------------------
DROP TABLE IF EXISTS `common_admin`;
CREATE TABLE `common_admin` (
`id` int NOT NULL AUTO_INCREMENT,
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`type` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`roleId` int NULL DEFAULT NULL,
`roleId` int(11) NULL DEFAULT NULL,
`phone` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`status` int NULL DEFAULT NULL,
`status` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of common_admin
......@@ -45,13 +71,13 @@ INSERT INTO `common_admin` VALUES (3, '123cmy@qq.com', '$2a$10$u2KxNBaHuTVwX7Kud
-- ----------------------------
DROP TABLE IF EXISTS `device`;
CREATE TABLE `device` (
`id` int NOT NULL AUTO_INCREMENT,
`hospitalId` int NULL DEFAULT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`hospitalId` int(11) NULL DEFAULT NULL,
`name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`type` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`freeTime` datetime NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = DYNAMIC;
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of device
......@@ -67,36 +93,35 @@ INSERT INTO `device` VALUES (5, 2, 'instrument5', 'instrument', '2024-12-05 10:3
-- ----------------------------
DROP TABLE IF EXISTS `hospital`;
CREATE TABLE `hospital` (
`id` int NOT NULL AUTO_INCREMENT,
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`amountPatient` int NULL DEFAULT NULL,
`maxAmount` int NULL DEFAULT NULL,
`amountPatient` int(11) NULL DEFAULT NULL,
`maxAmount` int(11) NULL DEFAULT NULL,
`type` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`address` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`phone` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`status` int NULL DEFAULT NULL,
`roleId` int NULL DEFAULT NULL,
`status` int(11) NULL DEFAULT NULL,
`roleId` int(11) NULL DEFAULT NULL,
`email` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`patientId` int NULL DEFAULT NULL,
`deviceId` int NULL DEFAULT NULL,
`patientId` int(11) NULL DEFAULT NULL,
`deviceId` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of hospital
-- ----------------------------
INSERT INTO `hospital` VALUES (1, 'hospital0', 3, 100, 'hospital', 'road', '145267', 1, 3, 'agag', '$2a$10$wvAZoj4V51MH/MLhVIrnG.NrY07/.Gn9Ar6JsyzRAubWtqbWzgKie', 0, 0);
INSERT INTO `hospital` VALUES (2, 'hospital1', 5, 200, 'hospital', 'beijing', '6371', 1, 3, 'soga', '$2a$10$wvAZoj4V51MH/MLhVIrnG.NrY07/.Gn9Ar6JsyzRAubWtqbWzgKie', 0, 0);
INSERT INTO `hospital` VALUES (3, 'hospital2', 10, 50, 'hospital', 'cardiff', '123', 1, 3, 'hospital2@qq.com', '$2a$10$wvAZoj4V51MH/MLhVIrnG.NrY07/.Gn9Ar6JsyzRAubWtqbWzgKie', 0, 0);
INSERT INTO `hospital` VALUES (1, 'hospital1', 5, 200, 'hospital', 'beijing', '6371', 1, 3, 'hospital1@qq.com', '$2a$10$wvAZoj4V51MH/MLhVIrnG.NrY07/.Gn9Ar6JsyzRAubWtqbWzgKie', 0, 0);
INSERT INTO `hospital` VALUES (2, 'hospital2', 10, 50, 'hospital', 'cardiff', '123', 1, 3, 'hospital2@qq.com', '$2a$10$wvAZoj4V51MH/MLhVIrnG.NrY07/.Gn9Ar6JsyzRAubWtqbWzgKie', 0, 0);
-- ----------------------------
-- Table structure for hospital_device
-- ----------------------------
DROP TABLE IF EXISTS `hospital_device`;
CREATE TABLE `hospital_device` (
`hospitalId` int NULL DEFAULT NULL,
`deviceId` int NULL DEFAULT NULL
`hospitalId` int(11) NULL DEFAULT NULL,
`deviceId` int(11) NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
......@@ -108,24 +133,24 @@ CREATE TABLE `hospital_device` (
-- ----------------------------
DROP TABLE IF EXISTS `nurse`;
CREATE TABLE `nurse` (
`id` int NOT NULL AUTO_INCREMENT,
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`status` int NULL DEFAULT NULL,
`hospitalId` int NULL DEFAULT NULL,
`status` int(11) NULL DEFAULT NULL,
`hospitalId` int(11) NULL DEFAULT NULL,
`type` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`age` int NULL DEFAULT NULL,
`age` int(11) NULL DEFAULT NULL,
`phone` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`email` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`address` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = DYNAMIC;
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of nurse
-- ----------------------------
INSERT INTO `nurse` VALUES (1, 'nn', 0, 2, 'nurse', 23, '111', '23453', 'Cardiff');
INSERT INTO `nurse` VALUES (2, 'Li Xiaoming', 1, 2, 'nurse', 25, '222', '4399', 'Cardiff');
INSERT INTO `nurse` VALUES (3, 'Sun Hao', 1, 0, 'nurse', 24, '123', '23576', 'Bute');
INSERT INTO `nurse` VALUES (3, 'Sun Hao', 1, 2, 'nurse', 24, '123', '23576', 'Bute');
INSERT INTO `nurse` VALUES (4, 'Wang Xiaoming', 0, 2, 'nurse', 26, '333', '34578', 'Cardiff');
INSERT INTO `nurse` VALUES (5, 'Tian Hao', 0, 2, 'nurse', 30, '321', '24353', 'Cardiff');
......@@ -134,18 +159,18 @@ INSERT INTO `nurse` VALUES (5, 'Tian Hao', 0, 2, 'nurse', 30, '321', '24353', 'C
-- ----------------------------
DROP TABLE IF EXISTS `patient`;
CREATE TABLE `patient` (
`id` int NOT NULL AUTO_INCREMENT,
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`roleId` int NULL DEFAULT NULL,
`status` int NULL DEFAULT NULL,
`hospitalId` int NULL DEFAULT NULL,
`roleId` int(11) NULL DEFAULT NULL,
`status` int(11) NULL DEFAULT NULL,
`hospitalId` int(11) NULL DEFAULT NULL,
`type` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`age` int NULL DEFAULT NULL,
`age` int(11) NULL DEFAULT NULL,
`phone` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
`email` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = DYNAMIC;
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of patient
......@@ -161,8 +186,8 @@ INSERT INTO `patient` VALUES (5, 'Xia Yu', '$2a$10$obgmyiqAuhIkBjuw3bROr.LkCh.Nb
-- ----------------------------
DROP TABLE IF EXISTS `patient_hospital`;
CREATE TABLE `patient_hospital` (
`hosptialId` int NULL DEFAULT NULL,
`patientId` int NULL DEFAULT NULL
`hosptialId` int(11) NULL DEFAULT NULL,
`patientId` int(11) NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
......@@ -174,7 +199,7 @@ CREATE TABLE `patient_hospital` (
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`roleId` int NULL DEFAULT NULL,
`roleId` int(11) NULL DEFAULT NULL,
`type` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
......@@ -191,10 +216,10 @@ INSERT INTO `role` VALUES (3, 'HOSPITAL');
-- ----------------------------
DROP TABLE IF EXISTS `super_admin`;
CREATE TABLE `super_admin` (
`id` int NOT NULL AUTO_INCREMENT,
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`password` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`roleId` int NULL DEFAULT NULL,
`roleId` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
......@@ -203,35 +228,4 @@ CREATE TABLE `super_admin` (
-- ----------------------------
INSERT INTO `super_admin` VALUES (1, '2649783657@qq.com', '$2a$10$5UzuKUxgR8H0RzLYrP.BUu8.76yKwMD4XkvJIu/xxB7AAHWfphFQm', 0);
-- ----------------------------
-- Procedure structure for reset_primary_keys
-- ----------------------------
DROP PROCEDURE IF EXISTS `reset_primary_keys`;
delimiter ;;
CREATE PROCEDURE `reset_primary_keys`()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE current_id INT DEFAULT 0;
DECLARE cur CURSOR FOR
SELECT id FROM common_admin ORDER BY id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur;
-- 重新更新每一条记录的 ID
read_loop: LOOP
FETCH cur INTO current_id;
IF done THEN
LEAVE read_loop;
END IF;
-- 根据新的排序修改 ID
UPDATE common_admin SET id = current_id - 1 WHERE id = current_id;
END LOOP;
CLOSE cur;
END
;;
delimiter ;
SET FOREIGN_KEY_CHECKS = 1;
......@@ -54,6 +54,7 @@ public class CommonAdminHospitalController {
public ResponseEntity<String> deleteHospital(@PathVariable int id) {
try {
commonAdminHospitalService.deleteHospital(id);
commonAdminHospitalService.resetHospitalIds(); // Reset IDs after deletion
return ResponseEntity.ok("Hospital deleted successfully!");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
......@@ -61,6 +62,7 @@ public class CommonAdminHospitalController {
}
}
@GetMapping("/nurses")
public List<NurseVO> getNurses(@RequestParam(value = "name", required = false) String name,
@RequestParam(value = "hospitalId", required = false) Integer hospitalId) {
......@@ -70,4 +72,16 @@ public class CommonAdminHospitalController {
return commonAdminHospitalService.searchNurses(name, hospitalId);
}
@GetMapping("/{id}")
public ResponseEntity<HospitalDTO> getHospitalById(@PathVariable int id) {
HospitalDTO hospital = commonAdminHospitalService.getHospitalById(id);
if (hospital != null) {
return ResponseEntity.ok(hospital);
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(null);
}
}
}
......@@ -68,14 +68,37 @@ public class NursingHomeController {
@GetMapping("/search")
public Result<List<HospitalDTO>> searchHospitals(@RequestParam(required = false) String name) {
try {
log.info("Searching hospitals with name: {}", name);
if (name == null || name.trim().isEmpty()) {
return nursingHomeService.getAvailableBeds();
}
return nursingHomeService.searchHospitals(name.trim());
} catch (Exception e) {
log.error("Error searching hospitals: ", e);
return Result.error("Error searching hospitals: " + e.getMessage());
log.error("Search error: ", e);
return Result.error("Search failed: " + e.getMessage());
}
}
@PutMapping("/{id}/approval")
public Result<String> updateApprovalStatus(
@PathVariable Integer id,
@RequestParam String status) {
try {
log.info("Updating approval status for hospital {}: {}", id, status);
return nursingHomeService.updateApprovalStatus(id, status);
} catch (Exception e) {
log.error("Error updating approval status: ", e);
return Result.error("Failed to update approval status");
}
}
@GetMapping("/pending")
public Result<List<HospitalDTO>> getPendingApprovals() {
try {
log.info("Fetching pending approvals");
return nursingHomeService.getPendingApprovals();
} catch (Exception e) {
log.error("Error fetching pending approvals: ", e);
return Result.error("Failed to fetch pending approvals");
}
}
}
......@@ -15,8 +15,7 @@ public class CommonAdminHospitalMapper {
@Autowired
JdbcTemplate jdbcTemplate;
// 更新医院信息
public int update(HospitalDTO hospital) {
String sql = "UPDATE hospital SET name=?, address=?, phone=?, totalBeds=?, availableBeds=?, occupancyRate=? WHERE id=?";
return jdbcTemplate.update(sql, hospital.getName(), hospital.getAddress(), hospital.getPhone(),
......
......@@ -5,6 +5,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Repository
......@@ -13,33 +15,64 @@ public class NursingHomeMapper {
@Autowired
private JdbcTemplate jdbcTemplate;
public List<HospitalDTO> searchHospitals(String name) {
String sql = """
SELECT
id, name, address, phone, maxAmount,
amountPatient, status, approval_status
FROM hospital
WHERE status = 1
AND name LIKE CONCAT('%', ?, '%')
ORDER BY name ASC
""";
return jdbcTemplate.query(sql,
ps -> ps.setString(1, name),
this::mapToDTO);
}
public List<HospitalDTO> findAllNursingHomes() {
String sql = """
SELECT
id,
name,
address,
phone,
maxAmount,
amountPatient,
status
id, name, address, phone, maxAmount,
amountPatient, status, approval_status
FROM hospital
WHERE status = 1
""";
return jdbcTemplate.query(sql, (rs, rowNum) -> {
HospitalDTO dto = new HospitalDTO();
dto.setId(rs.getInt("id"));
dto.setName(rs.getString("name"));
dto.setLocation(rs.getString("address"));
dto.setPhone(rs.getString("phone"));
dto.setTotalBeds(rs.getInt("maxAmount"));
int maxAmount = rs.getInt("maxAmount");
int amountPatient = rs.getInt("amountPatient");
dto.setAvailableBeds(maxAmount - amountPatient);
dto.setOccupancyRate(calculateOccupancy(maxAmount, amountPatient));
return dto;
});
return jdbcTemplate.query(sql, this::mapToDTO);
}
public List<HospitalDTO> getPendingApprovals() {
String sql = """
SELECT
id, name, address, phone, maxAmount,
amountPatient, status, approval_status
FROM hospital
WHERE approval_status = 'PENDING'
""";
return jdbcTemplate.query(sql, this::mapToDTO);
}
public int updateApprovalStatus(int id, String status) {
String sql = "UPDATE hospital SET approval_status = ? WHERE id = ?";
return jdbcTemplate.update(sql, status, id);
}
private HospitalDTO mapToDTO(ResultSet rs, int rowNum) throws SQLException {
HospitalDTO dto = new HospitalDTO();
dto.setId(rs.getInt("id"));
dto.setName(rs.getString("name"));
dto.setLocation(rs.getString("address"));
dto.setPhone(rs.getString("phone"));
int maxAmount = rs.getInt("maxAmount");
int amountPatient = rs.getInt("amountPatient");
dto.setTotalBeds(maxAmount);
dto.setAvailableBeds(maxAmount - amountPatient);
dto.setOccupancyRate(calculateOccupancy(maxAmount, amountPatient));
dto.setApprovalStatus(rs.getString("approval_status"));
return dto;
}
private double calculateOccupancy(int maxAmount, int amountPatient) {
......@@ -49,15 +82,10 @@ public class NursingHomeMapper {
public int insertHospital(HospitalDTO dto) {
String sql = """
INSERT INTO hospital (
name,
address,
phone,
maxAmount,
amountPatient,
status,
type,
roleId
) VALUES (?, ?, ?, ?, ?, 1, 'hospital', 3)
name, address, phone, maxAmount,
amountPatient, status, type, roleId,
approval_status
) VALUES (?, ?, ?, ?, ?, 1, 'hospital', 3, 'PENDING')
""";
return jdbcTemplate.update(sql,
......@@ -107,36 +135,4 @@ public class NursingHomeMapper {
""";
return jdbcTemplate.update(sql, currentPatients, hospitalId, currentPatients);
}
public List<HospitalDTO> searchHospitals(String name) {
String sql = """
SELECT
id,
name,
address,
phone,
maxAmount,
amountPatient
FROM hospital
WHERE status = 1
AND name LIKE CONCAT('%', ?, '%')
ORDER BY name ASC
""";
return jdbcTemplate.query(sql,
ps -> ps.setString(1, name),
(rs, rowNum) -> {
HospitalDTO dto = new HospitalDTO();
dto.setId(rs.getInt("id"));
dto.setName(rs.getString("name"));
dto.setLocation(rs.getString("address"));
dto.setPhone(rs.getString("phone"));
int maxAmount = rs.getInt("maxAmount");
int amountPatient = rs.getInt("amountPatient");
dto.setTotalBeds(maxAmount);
dto.setAvailableBeds(maxAmount - amountPatient);
dto.setOccupancyRate(calculateOccupancy(maxAmount, amountPatient));
return dto;
});
}
}
\ No newline at end of file
......@@ -12,4 +12,5 @@ public class HospitalDTO {
private int totalBeds;
private int availableBeds;
private double occupancyRate;
private String approvalStatus;
}
\ No newline at end of file
......@@ -15,4 +15,6 @@ public class HospitalVO {
private String status_str;
private int maxAmount;
private int amountPatient;
private String approvalStatus;
private String approvalStatus_str;
}
......@@ -18,8 +18,15 @@ public interface CommonAdminHospitalService {
void updateHospital(HospitalDTO hospital);
void editHospital(HospitalDTO hospital);
void deleteHospital(int id);
HospitalDTO getHospitalById(int id);
void resetHospitalIds();
List<NurseVO> getAllNurses();
List<NurseVO> searchNurses(String name, Integer hospitalId);
......
......@@ -12,4 +12,6 @@ public interface NursingHomeService {
Result<List<HospitalDTO>> getAllPatients();
Result<String> updateBedCount(int hospitalId, int currentPatients);
Result<List<HospitalDTO>> searchHospitals(String name);
Result<String> updateApprovalStatus(Integer hospitalId, String status);
Result<List<HospitalDTO>> getPendingApprovals();
}
\ No newline at end of file
......@@ -51,9 +51,14 @@ public class CommonAdminHospitalServiceImp implements CommonAdminHospitalService
double occupancyRate = 1.0 - (double) hospital.getAvailableBeds() / hospital.getTotalBeds();
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);
String sql = "INSERT INTO hospital (name, address, phone, maxAmount, amountPatient) VALUES (?, ?, ?, ?, ?)";
jdbcTemplate.update(sql,
hospital.getName(),
hospital.getAddress(),
hospital.getPhone(),
hospital.getTotalBeds(),
hospital.getAvailableBeds()
);
}
@Override
......@@ -63,26 +68,59 @@ public class CommonAdminHospitalServiceImp implements CommonAdminHospitalService
@Override
public void updateHospital(HospitalDTO hospital) {
}
@Override
public void editHospital(HospitalDTO hospital) {
if (hospital.getId() <= 0 || hospital.getName() == null || hospital.getAddress() == null ||
hospital.getPhone() == null || hospital.getTotalBeds() <= 0 || hospital.getAvailableBeds() < 0) {
throw new IllegalArgumentException("Invalid hospital data: Missing or incorrect fields.");
}
String sql = "UPDATE hospital SET name = ?, address = ?, phone = ?, totalBeds = ?, availableBeds = ?, occupancyRate = ? WHERE id = ?";
// 更新占用率计算(可选,具体依项目需求)
double occupancyRate = 1.0 - (double) hospital.getAvailableBeds() / hospital.getTotalBeds();
int rowsUpdated = jdbcTemplate.update(sql, hospital.getName(), hospital.getAddress(), hospital.getPhone(),
hospital.getTotalBeds(), hospital.getAvailableBeds(), occupancyRate, hospital.getId());
if (rowsUpdated == 0) {
throw new IllegalArgumentException("No hospital found with ID " + hospital.getId());
}
// SQL 语句更新医院数据
String sql = "UPDATE hospital SET name = ?, address = ?, phone = ?, maxAmount = ?, amountPatient = ? WHERE id = ?";
jdbcTemplate.update(sql, hospital.getName(), hospital.getAddress(), hospital.getPhone(),
hospital.getTotalBeds(), hospital.getAvailableBeds(), hospital.getId());
}
@Override
public void deleteHospital(int id) {
String sql = "DELETE FROM hospital WHERE id = ?";
jdbcTemplate.update(sql, id);
String deleteSql = "DELETE FROM hospital WHERE id = ?";
jdbcTemplate.update(deleteSql, id);
}
@Override
public HospitalDTO getHospitalById(int id) {
String sql = "SELECT * FROM hospital WHERE id = ?";
List<HospitalDTO> hospitals = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(HospitalDTO.class), id);
return hospitals.isEmpty() ? null : hospitals.get(0);
}
@Override
public void resetHospitalIds() {
try {
// Step 1: 创建一个变量用于更新行号
String setRowNumber = "SET @row_number = 0;";
jdbcTemplate.execute(setRowNumber);
// Step 2: 重新更新表的 ID 顺序
String updateIds = "UPDATE hospital SET id = (@row_number := @row_number + 1);";
jdbcTemplate.execute(updateIds);
// Step 3: 重置 AUTO_INCREMENT
String resetAutoIncrement = "ALTER TABLE hospital AUTO_INCREMENT = 1;";
jdbcTemplate.execute(resetAutoIncrement);
System.out.println("Hospital IDs reset successfully.");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Failed to reset hospital IDs: " + e.getMessage());
}
}
......
......@@ -11,12 +11,17 @@ import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.stream.Collectors;
@Service
@Transactional
@Slf4j
@Transactional
public class NursingHomeServiceImp implements NursingHomeService {
private static final String STATUS_PENDING = "PENDING";
private static final String STATUS_APPROVED = "APPROVED";
private static final String STATUS_REJECTED = "REJECTED";
private final NursingHomeMapper nursingHomeMapper;
@Autowired
......@@ -25,35 +30,43 @@ public class NursingHomeServiceImp implements NursingHomeService {
}
@Override
@Transactional(readOnly = true)
public Result<List<HospitalDTO>> getAvailableBeds() {
try {
List<HospitalDTO> hospitals = nursingHomeMapper.findAllNursingHomes();
if (hospitals == null || hospitals.isEmpty()) {
return Result.error("No hospitals available");
hospitals = hospitals.stream()
.filter(h -> STATUS_APPROVED.equals(h.getApprovalStatus()))
.collect(Collectors.toList());
if (hospitals.isEmpty()) {
return Result.error("No approved hospitals available");
}
return Result.success(hospitals);
} catch (DataAccessException e) {
return Result.error("Database error: " + e.getMessage());
} catch (Exception e) {
return Result.error("Internal server error");
log.error("Error fetching available beds: {}", e.getMessage(), e);
return Result.error("Failed to fetch available beds");
}
}
@Override
@Transactional
public Result<HospitalDTO> insertPatientInfo(HospitalDTO hospitalDTO) {
try {
if (!validateHospitalData(hospitalDTO)) {
return Result.error("Invalid hospital data");
}
hospitalDTO.setApprovalStatus(STATUS_PENDING);
int result = nursingHomeMapper.insertHospital(hospitalDTO);
if (result > 0) {
log.info("Successfully inserted hospital: {}", hospitalDTO.getName());
return Result.success(hospitalDTO);
}
return Result.error("Failed to insert hospital");
} catch (DataAccessException e) {
return Result.error("Database error: " + e.getMessage());
} catch (Exception e) {
return Result.error("Internal server error");
log.error("Database error while inserting hospital: {}", e.getMessage(), e);
return Result.error("Database error occurred");
}
}
......@@ -108,22 +121,73 @@ public class NursingHomeServiceImp implements NursingHomeService {
@Transactional(readOnly = true)
public Result<List<HospitalDTO>> searchHospitals(String name) {
try {
log.info("Searching hospitals with name: {}", name);
if (name == null || name.trim().isEmpty()) {
return Result.error("Search term cannot be empty");
}
List<HospitalDTO> hospitals = nursingHomeMapper.searchHospitals(name);
return hospitals.isEmpty() ?
Result.error("No hospitals found") :
Result.success(hospitals);
} catch (Exception e) {
log.error("Search error: ", e);
return Result.error("Search failed");
}
}
List<HospitalDTO> hospitals = nursingHomeMapper.searchHospitals(name.trim());
if (hospitals.isEmpty()) {
log.info("No hospitals found matching: {}", name);
return Result.error("No hospitals found");
@Override
@Transactional
public Result<String> updateApprovalStatus(Integer hospitalId, String status) {
try {
log.info("Updating approval status for hospital {}: {}", hospitalId, status);
if (hospitalId == null || hospitalId <= 0) {
log.warn("Invalid hospital ID: {}", hospitalId);
return Result.error("Invalid hospital ID");
}
if (!isValidApprovalStatus(status)) {
log.warn("Invalid approval status: {}", status);
return Result.error("Invalid approval status");
}
int result = nursingHomeMapper.updateApprovalStatus(hospitalId, status.toUpperCase());
if (result > 0) {
log.info("Successfully updated approval status for hospital {}", hospitalId);
return Result.success("Approval status updated successfully");
}
log.warn("Hospital not found with ID: {}", hospitalId);
return Result.error("Hospital not found");
} catch (DataAccessException e) {
log.error("Database error while updating approval status: {}", e.getMessage(), e);
return Result.error("Database error occurred");
} catch (Exception e) {
log.error("Unexpected error while updating approval status: {}", e.getMessage(), e);
return Result.error("Failed to update approval status");
}
}
log.info("Found {} hospitals matching search term", hospitals.size());
return Result.success(hospitals);
@Override
@Transactional(readOnly = true)
public Result<List<HospitalDTO>> getPendingApprovals() {
try {
log.info("Fetching pending approval hospitals");
List<HospitalDTO> pendingHospitals = nursingHomeMapper.getPendingApprovals();
if (pendingHospitals.isEmpty()) {
log.info("No pending approvals found");
return Result.error("No pending approvals");
}
log.info("Found {} pending approvals", pendingHospitals.size());
return Result.success(pendingHospitals);
} catch (DataAccessException e) {
log.error("Database error while fetching pending approvals: {}", e.getMessage(), e);
return Result.error("Database error occurred");
} catch (Exception e) {
log.error("Error searching hospitals: ", e);
return Result.error("Failed to search hospitals");
log.error("Unexpected error while fetching pending approvals: {}", e.getMessage(), e);
return Result.error("Failed to fetch pending approvals");
}
}
......@@ -139,4 +203,17 @@ public class NursingHomeServiceImp implements NursingHomeService {
hospitalDTO.getAvailableBeds() >= 0 &&
hospitalDTO.getAvailableBeds() <= hospitalDTO.getTotalBeds();
}
private boolean isValidStatus(String status) {
return status != null &&
(status.equals("APPROVED") ||
status.equals("REJECTED") ||
status.equals("PENDING"));
}
private boolean isValidApprovalStatus(String status) {
if (status == null) return false;
return List.of(STATUS_PENDING, STATUS_APPROVED, STATUS_REJECTED)
.contains(status.toUpperCase());
}
}
\ No newline at end of file
......@@ -342,3 +342,20 @@ footer {
padding: 1rem;
}
.approval-pending {
background-color: var(--warning-color);
color: white;
padding: 0.25rem 0.5rem;
border-radius: 4px;
}
.approval-rejected {
background-color: var(--danger-color);
color: white;
}
.approval-approved {
background-color: var(--success-color);
color: white;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Care Home Approval System</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="/css/common.css">
<style>
.approval-dashboard {
background-color: #ffffff;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
padding: 20px;
margin-top: 20px;
}
.status-badge {
padding: 5px 10px;
border-radius: 15px;
font-size: 0.9em;
font-weight: 500;
}
.status-pending {
background-color: #ffc107;
color: #000;
}
.status-approved {
background-color: #28a745;
color: #fff;
}
.status-rejected {
background-color: #dc3545;
color: #fff;
}
.action-buttons button {
margin: 0 5px;
}
</style>
</head>
<body>
<div id="container">
<!-- Reuse your existing top navigation -->
<div id="top">
<span class="brand">Digital Insight for Health</span>
<span id="showSpan"></span>
</div>
<div class="main-content">
<div class="approval-dashboard">
<h2>Pending Approvals</h2>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Location</th>
<th>Contact</th>
<th>Beds</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="pendingTableBody">
<!-- Dynamically populated -->
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- Approval Modal -->
<div class="modal fade" id="approvalModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Confirm Action</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<p id="modalMessage"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="confirmAction">Confirm</button>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script src="/js/approvalSystem.js"></script>
</body>
</html>
......@@ -180,6 +180,71 @@
});
}
function openEditHospitalModal(hospitalId) {
fetch(`/commonAdmin/hospital/${hospitalId}`)
.then(response => {
if (!response.ok) throw new Error("Failed to fetch hospital data.");
return 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';
const saveButton = document.getElementById('save-hospital-btn');
saveButton.replaceWith(saveButton.cloneNode(true));
document.getElementById('save-hospital-btn').addEventListener('click', () => updateHospital(hospitalId));
})
.catch(error => {
console.error("Error loading hospital data:", error);
alert("Failed to load hospital data.");
});
}
function updateHospital(hospitalId) {
const hospitalData = {
id: hospitalId,
name: document.getElementById('modal-name').value.trim(),
location: document.getElementById('modal-location') ? document.getElementById('modal-location').value.trim() : "", // 如果 location 是可选的
address: document.getElementById('modal-address').value.trim(),
phone: document.getElementById('modal-phone').value.trim(),
totalBeds: parseInt(document.getElementById('modal-totalBeds').value.trim()),
availableBeds: parseInt(document.getElementById('modal-availableBeds').value.trim())
};
console.log("Updating hospital with data:", hospitalData);
if (!hospitalData.name || !hospitalData.address || !hospitalData.phone ||
isNaN(hospitalData.totalBeds) || isNaN(hospitalData.availableBeds)) {
alert("All fields are required!");
return;
}
fetch(`/commonAdmin/hospital/update/${hospitalId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(hospitalData),
})
.then(response => {
if (response.ok) {
alert("Hospital updated successfully!");
closeHospitalModal();
loadHospitals(); // Reload hospital list
} 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 loadHospitals(filters = {}) {
const query = new URLSearchParams(filters).toString();
fetch(`/commonAdmin/hospital/all?${query}`)
......@@ -202,6 +267,35 @@
`;
tableBody.appendChild(row);
});
document.querySelectorAll(".editButton").forEach(button => {
button.addEventListener("click", () => {
const hospitalId = button.getAttribute("data-id");
openEditHospitalModal(hospitalId);
});
});
document.querySelectorAll(".deleteButton").forEach(button => {
button.addEventListener("click", () => {
const hospitalId = button.getAttribute("data-id");
if (confirm("Are you sure you want to delete this hospital?")) {
fetch(`/commonAdmin/hospital/delete/${hospitalId}`, {
method: "DELETE",
})
.then(response => {
if (!response.ok) {
return response.text().then(text => { throw new Error(text); });
}
alert("Hospital deleted successfully!");
loadHospitals();
})
.catch(error => {
console.error("Error deleting hospital:", error);
alert(`Failed to delete hospital: ${error.message}`);
});
}
});
});
})
.catch(error => console.error("Error loading hospitals:", error));
}
......@@ -251,7 +345,6 @@
loadHospitals();
});
// Add close button event listener
document.getElementById('close-hospital-modal').addEventListener('click', closeHospitalModal);
}
......
......@@ -52,29 +52,43 @@ $(document).ready(function () {
function updateTable(hospitals) {
const tbody = $('#hospitalTable tbody');
tbody.empty();
if (!hospitals || hospitals.length === 0) {
showNoDataMessage();
return;
}
hospitals.forEach(function(hospital) {
const tr = `
<tr>
<td>${hospital.id}</td>
<td>${hospital.name || ''}</td>
<td>${hospital.location || ''}</td>
<td>${hospital.phone || ''}</td>
<td>${hospital.totalBeds || 0}</td>
<td>${hospital.availableBeds || 0}</td>
<td>${Math.round(hospital.occupancyRate)}%</td>
<td>
<button class="btn edit-btn" data-id="${hospital.id}">
<i class="fas fa-edit"></i>
</button>
<button class="btn delete-btn" data-id="${hospital.id}">
<i class="fas fa-trash"></i>
</button>
</td>
</tr>
`;
tbody.append(tr);
// Only show approved hospitals
if (hospital.approvalStatus === 'APPROVED') {
const tr = $('<tr>').append(
$('<td>').text(hospital.name),
$('<td>').text(hospital.location),
$('<td>').text(hospital.phone),
$('<td>').text(hospital.totalBeds),
$('<td>').text(hospital.availableBeds),
$('<td>').text(hospital.occupancyRate + '%'),
$('<td>').append(
$('<span>')
.addClass('status-badge')
.addClass('approval-' + hospital.approvalStatus.toLowerCase())
.text(hospital.approvalStatus)
)
);
tbody.append(tr);
}
});
if (tbody.children().length === 0) {
tbody.append(
$('<tr>').append(
$('<td>')
.attr('colspan', '7')
.addClass('no-data')
.text('No approved hospitals found')
)
);
}
}
function initializeEventHandlers() {
......@@ -334,6 +348,24 @@ $(document).ready(function () {
// Add fade effects for smoother transitions
$('.table-container').hide().fadeIn();
// Add new function for admin approval handling
function handleApproval(hospitalId, status) {
$.ajax({
url: `${API_BASE_URL}/approval/${hospitalId}`,
method: 'PUT',
data: { status: status },
success: function(response) {
if(response.code === 1) {
showSuccess(`Hospital ${status.toLowerCase()} successfully`);
loadHospitals();
} else {
showError(response.msg || DEFAULT_ERROR);
}
},
error: handleAjaxError
});
}
});
function handleSignOut() {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment