232 预约管理-》门诊预约挂号:打开界面报错且无医生排班预约号源数据

This commit is contained in:
HuangXinQuan
2026-03-26 17:09:08 +08:00
parent 3f0fa3bbb3
commit 11cf88fd49
22 changed files with 1411 additions and 764 deletions

View File

@@ -0,0 +1,40 @@
package com.openhis.appointmentmanage.domain;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* 预约挂号提交表单 (防篡改设计)
*/
@Data
public class AppointmentBookDTO implements Serializable {
@NotNull(message = "号源槽位ID不能为空")
private Long slotId;
// 兼容前端发来的旧字段,即使发了我们底层也不用,防报错接收
private Long ticketId;
private Long patientId;
@NotBlank(message = "患者姓名不能为空")
private String patientName;
@NotBlank(message = "就诊卡号不能为空")
private String medicalCard;
@NotBlank(message = "手机号不能为空")
private String phone;
private Integer gender;
// 前端传的 tenant_id我们为了兼容它带下划线的写法
private Integer tenant_id;
// 前端还会强行发这俩危险字段,我们只管接收堵口子,到了后端全丢弃不用
private BigDecimal fee;
private String regType;
}

View File

@@ -0,0 +1,15 @@
package com.openhis.appointmentmanage.domain;
import lombok.Data;
/**
* 医生余号汇总DTO按号源池聚合
*/
@Data
public class DoctorAvailabilityDTO {
private Long doctorId;
private String doctorName;
private Integer available;
private String ticketType;
}

View File

@@ -33,7 +33,7 @@ public class ScheduleSlot extends HisBaseEntity {
private Integer status;
/** 预约订单ID */
private Integer orderId;
private Long orderId;
/** 预计叫号时间 */
private LocalTime expectTime;

View File

@@ -0,0 +1,42 @@
package com.openhis.appointmentmanage.domain;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalTime;
/**
* 专门用于承接底层的号源池与具体槽位联查结果 (不对外暴露)
*/
@Data
public class TicketSlotDTO {
// 基础信息
private Long slotId;
private Long scheduleId;
private String doctor;
private Long doctorId;
private Long departmentId;
private String departmentName;
private String fee;
private String patientName;
private String medicalCard;
private Long patientId;
private String phone;
private Integer orderStatus;
// 底层逻辑判断专属字段
private Integer slotStatus;
private LocalTime expectTime;
private LocalDate scheduleDate;
private Integer regType;
private Integer poolStatus;
private String stopReason;
private Boolean isStopped;
public Boolean getIsStopped() {
return isStopped;
}
public void setIsStopped(Boolean isStopped) {
this.isStopped = isStopped;
}
}

View File

@@ -0,0 +1,43 @@
package com.openhis.appointmentmanage.dto;
import lombok.Data;
import java.io.Serializable;
/**
* 门诊预约挂号查询条件 DTO
*/
@Data
public class TicketQueryDTO implements Serializable {
private static final long serialVersionUID = 1L;
// 看诊日期 (例如: 2026-03-25)
private String date;
// 号源状态 (unbooked, booked, checked, cancelled, all)
private String status;
// 号源类型 (general: 普通号, expert: 专家号)
private String type;
// 科室名称 (例如: 内科)
private String department;
// 医生ID
private Long doctorId;
// 患者姓名 (模糊搜索)
private String name;
// 就诊卡号 (模糊搜索)
private String card;
// 手机号 (模糊搜索)
private String phone;
// 当前页码 (默认第一页)
private Integer page = 1;
// 每页显示条数 (默认查20条)
private Integer limit = 20;
}

View File

@@ -2,8 +2,39 @@ package com.openhis.appointmentmanage.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.openhis.appointmentmanage.domain.SchedulePool;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;
@Repository
public interface SchedulePoolMapper extends BaseMapper<SchedulePool> {
/**
* 按号源池实时重算统计值,避免并发场景下计数漂移。
*
* 说明available_num 在当前项目中可能为数据库生成列,因此这里仅维护
* booked_num / locked_num剩余号由数据库或查询逻辑计算。
*/
@Update("""
UPDATE adm_schedule_pool p
SET
booked_num = COALESCE((
SELECT COUNT(1)
FROM adm_schedule_slot s
WHERE s.pool_id = p.id
AND s.delete_flag = '0'
AND s.status = 1
), 0),
locked_num = COALESCE((
SELECT COUNT(1)
FROM adm_schedule_slot s
WHERE s.pool_id = p.id
AND s.delete_flag = '0'
AND s.status = 3
), 0),
update_time = now()
WHERE p.id = #{poolId}
AND p.delete_flag = '0'
""")
int refreshPoolStats(@Param("poolId") Long poolId);
}

View File

@@ -1,10 +1,53 @@
package com.openhis.appointmentmanage.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.openhis.appointmentmanage.domain.DoctorAvailabilityDTO;
import com.openhis.appointmentmanage.domain.ScheduleSlot;
import com.openhis.appointmentmanage.domain.TicketSlotDTO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.openhis.appointmentmanage.dto.TicketQueryDTO;
import java.util.List;
import org.springframework.stereotype.Repository;
import org.apache.ibatis.annotations.Param;
@Repository
public interface ScheduleSlotMapper extends BaseMapper<ScheduleSlot> {
//
// 多表查询排班信息展示来预约挂号
List<TicketSlotDTO> selectAllTicketSlots();
/**
* 根据槽位ID精确查出完整的聚合信息
*/
TicketSlotDTO selectTicketSlotById(@Param("id") Long id);
/**
* 原子抢占槽位:仅当当前状态=0(可用)时更新为1(已预约)。
*/
int lockSlotForBooking(@Param("slotId") Long slotId);
/**
* 按主键更新槽位状态。
*/
int updateSlotStatus(@Param("slotId") Long slotId, @Param("status") Integer status);
/**
* 根据槽位ID查询所属号源池ID。
*/
Long selectPoolIdBySlotId(@Param("slotId") Long slotId);
/**
* 预约成功后回填对应订单ID到号源槽位。
*/
int bindOrderToSlot(@Param("slotId") Long slotId, @Param("orderId") Long orderId);
/**
* 带分页和动态条件过滤的真实查询接口
*/
Page<TicketSlotDTO> selectTicketSlotsPage(Page<TicketSlotDTO> page, @Param("query") TicketQueryDTO query);
/**
* 按号源池聚合医生余号(不受分页影响)。
*/
List<DoctorAvailabilityDTO> selectDoctorAvailabilitySummary(@Param("query") TicketQueryDTO query);
}

View File

@@ -74,10 +74,10 @@ public interface ITicketService extends IService<Ticket> {
/**
* 预约号源
*
* @param params 预约参数
* @param dto 预约参数
* @return 结果
*/
int bookTicket(Map<String, Object> params);
int bookTicket(com.openhis.appointmentmanage.domain.AppointmentBookDTO dto);
/**
* 取消预约
@@ -85,7 +85,7 @@ public interface ITicketService extends IService<Ticket> {
* @param ticketId 号源ID
* @return 结果
*/
int cancelTicket(Long ticketId);
int cancelTicket(Long slotId);
/**
* 取号
@@ -93,7 +93,7 @@ public interface ITicketService extends IService<Ticket> {
* @param ticketId 号源ID
* @return 结果
*/
int checkInTicket(Long ticketId);
int checkInTicket(Long slotId);
/**
* 停诊
@@ -101,5 +101,5 @@ public interface ITicketService extends IService<Ticket> {
* @param ticketId 号源ID
* @return 结果
*/
int cancelConsultation(Long ticketId);
int cancelConsultation(Long slotId);
}

View File

@@ -4,10 +4,9 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.core.common.utils.AssignSeqUtil;
import com.openhis.clinical.domain.Order;
import com.openhis.clinical.domain.Ticket;
import com.openhis.clinical.mapper.OrderMapper;
import com.openhis.clinical.mapper.TicketMapper;
import com.openhis.clinical.service.IOrderService;
import com.openhis.common.constant.CommonConstants.AppointmentOrderStatus;
import com.openhis.common.enums.AssignSeqEnum;
import org.springframework.stereotype.Service;
@@ -23,9 +22,6 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements
@Resource
private OrderMapper orderMapper;
@Resource
private TicketMapper ticketMapper;
@Resource
private AssignSeqUtil assignSeqUtil;
@@ -86,25 +82,20 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements
@Override
public Order createAppointmentOrder(Map<String, Object> params) {
Long slotId = params.get("slotId") != null ? Long.valueOf(params.get("slotId").toString()) : null;
Long slotId = (Long) params.get("slotId");
if (slotId == null) {
throw new RuntimeException("号源ID不能为空");
}
Ticket ticket = ticketMapper.selectTicketById(slotId);
if (ticket == null) {
throw new RuntimeException("号源不存在");
}
Order order = new Order();
String orderNo = assignSeqUtil.getSeq(AssignSeqEnum.ORDER_NUM.getPrefix(), 18);
order.setOrderNo(orderNo);
Long patientId = params.get("patientId") != null ? Long.valueOf(params.get("patientId").toString()) : null;
String patientName = params.get("patientName") != null ? params.get("patientName").toString() : null;
String medicalCard = params.get("medicalCard") != null ? params.get("medicalCard").toString() : null;
String phone = params.get("phone") != null ? params.get("phone").toString() : null;
Integer gender = params.get("gender") != null ? Integer.valueOf(params.get("gender").toString()) : null;
Long patientId = (Long) params.get("patientId");
String patientName = (String) params.get("patientName");
String medicalCard = (String) params.get("medicalCard");
String phone = (String) params.get("phone");
Integer gender = (Integer) params.get("gender");
order.setPatientId(patientId);
order.setPatientName(patientName);
@@ -113,28 +104,31 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements
order.setGender(gender);
order.setSlotId(slotId);
order.setDepartmentId(ticket.getDepartmentId());
order.setDepartmentName(ticket.getDepartment());
order.setDoctorId(ticket.getDoctorId());
order.setDoctorName(ticket.getDoctor());
order.setScheduleId((Long) params.get("scheduleId"));
order.setDepartmentId((Long) params.get("departmentId"));
order.setDepartmentName((String) params.get("departmentName"));
order.setDoctorId((Long) params.get("doctorId"));
order.setDoctorName((String) params.get("doctorName"));
String regType = params.get("regType") != null ? params.get("regType").toString() : "普通";
order.setRegType(regType);
String regType = (String) params.get("regType");
order.setRegType(regType != null ? regType : "普通");
BigDecimal fee = params.get("fee") != null ? new BigDecimal(params.get("fee").toString()) : BigDecimal.ZERO;
order.setFee(fee);
BigDecimal fee = parseFee(params.get("fee"));
order.setFee(fee != null ? fee : BigDecimal.ZERO);
Date appointmentDate = new Date();
order.setAppointmentDate(appointmentDate);
order.setAppointmentTime(new Date());
order.setStatus(1);
// appointmentDate / appointmentTime 由调用方TicketServiceImpl在强类型上下文中
// 提前合并为 java.util.Date此处直接使用不再重复做 LocalDate + LocalTime 类型转换。
Date appointmentDateTime = params.get("appointmentDate") instanceof Date
? (Date) params.get("appointmentDate")
: new Date(); // 兜底:正常业务不应走到这里
order.setAppointmentDate(appointmentDateTime);
order.setAppointmentTime(appointmentDateTime);
order.setStatus(AppointmentOrderStatus.BOOKED);
order.setPayStatus(0);
order.setVersion(0);
// 设置租户ID
Integer tenantId = params.get("tenant_id") != null ? Integer.valueOf(params.get("tenant_id").toString()) : null;
order.setTenantId(tenantId);
order.setTenantId((Integer) params.get("tenant_id"));
order.setCreateTime(new Date());
order.setUpdateTime(new Date());
@@ -144,16 +138,40 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements
return order;
}
private BigDecimal parseFee(Object feeObj) {
if (feeObj == null) {
return BigDecimal.ZERO;
}
if (feeObj instanceof BigDecimal) {
return (BigDecimal) feeObj;
}
if (feeObj instanceof Number) {
return BigDecimal.valueOf(((Number) feeObj).doubleValue());
}
if (feeObj instanceof String) {
String feeStr = ((String) feeObj).trim();
if (feeStr.isEmpty()) {
return BigDecimal.ZERO;
}
try {
return new BigDecimal(feeStr);
} catch (NumberFormatException e) {
throw new RuntimeException("挂号费格式错误: " + feeStr);
}
}
throw new RuntimeException("挂号费类型错误: " + feeObj.getClass().getName());
}
@Override
public int cancelAppointmentOrder(Long orderId, String cancelReason) {
Order order = orderMapper.selectOrderById(orderId);
if (order == null) {
throw new RuntimeException("订单不存在");
}
if (order.getStatus() == 3) {
if (AppointmentOrderStatus.CANCELLED.equals(order.getStatus())) {
throw new RuntimeException("订单已取消");
}
if (order.getStatus() == 2) {
if (AppointmentOrderStatus.CHECKED_IN.equals(order.getStatus())) {
throw new RuntimeException("订单已完成,无法取消");
}

View File

@@ -2,17 +2,27 @@ package com.openhis.clinical.service.impl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.openhis.appointmentmanage.domain.TicketSlotDTO;
import com.openhis.appointmentmanage.mapper.SchedulePoolMapper;
import com.openhis.appointmentmanage.mapper.ScheduleSlotMapper;
import com.openhis.clinical.domain.Order;
import com.openhis.clinical.domain.Ticket;
import com.openhis.clinical.mapper.TicketMapper;
import com.openhis.clinical.service.IOrderService;
import com.openhis.clinical.service.ITicketService;
import com.openhis.common.constant.CommonConstants.AppointmentOrderStatus;
import com.openhis.common.constant.CommonConstants.SlotStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;
@@ -33,6 +43,12 @@ public class TicketServiceImpl extends ServiceImpl<TicketMapper, Ticket> impleme
@Resource
private IOrderService orderService;
@Resource
private ScheduleSlotMapper scheduleSlotMapper;
@Resource
private SchedulePoolMapper schedulePoolMapper;
/**
* 查询号源列表
*
@@ -47,7 +63,7 @@ public class TicketServiceImpl extends ServiceImpl<TicketMapper, Ticket> impleme
/**
* 分页查询号源列表
*
* @param page 分页参数
* @param page 分页参数
* @param ticket 号源信息
* @return 号源集合
*/
@@ -114,154 +130,183 @@ public class TicketServiceImpl extends ServiceImpl<TicketMapper, Ticket> impleme
/**
* 预约号源
*
* @param params 预约参数
* @param dto 预约参数
* @return 结果
*/
@Override
@Transactional(rollbackFor = Exception.class)
public int bookTicket(Map<String, Object> params) {
Long ticketId = Long.valueOf(params.get("ticketId").toString());
Long patientId = params.get("patientId") != null ? Long.valueOf(params.get("patientId").toString()) : null;
String patientName = params.get("patientName") != null ? params.get("patientName").toString() : null;
String medicalCard = params.get("medicalCard") != null ? params.get("medicalCard").toString() : null;
String phone = params.get("phone") != null ? params.get("phone").toString() : null;
logger.debug("开始预约号源ticketId: {}, patientId: {}, patientName: {}", ticketId, patientId, patientName);
Ticket ticket = ticketMapper.selectTicketById(ticketId);
if (ticket == null) {
logger.error("号源不存在ticketId: {}", ticketId);
throw new RuntimeException("号源不存在");
public int bookTicket(com.openhis.appointmentmanage.domain.AppointmentBookDTO dto) {
Long slotId = dto.getSlotId();
logger.debug("开始执行纯净打单路线slotId: {}, patientName: {}", slotId, dto.getPatientName());
// 1. 直查物理大底座!
TicketSlotDTO slot = scheduleSlotMapper.selectTicketSlotById(slotId);
if (slot == null) {
logger.error("安全拦截号源底库核对失败slotId: {}", slotId);
throw new RuntimeException("号源数据不存在");
}
logger.debug("查询到号源信息id: {}, status: {}, deleteFlag: {}", ticket.getId(), ticket.getStatus(), ticket.getDeleteFlag());
// 详细调试:检查状态字符串的详细信息
String status = ticket.getStatus();
logger.debug("状态字符串详细信息: value='{}', length={}, isNull={}", status, status != null ? status.length() : "null", status == null);
if (status != null) {
StringBuilder charInfo = new StringBuilder();
for (int i = 0; i < status.length(); i++) {
charInfo.append(status.charAt(i)).append("(").append((int) status.charAt(i)).append(") ");
}
logger.debug("状态字符串字符信息: {}", charInfo.toString());
if (slot.getSlotStatus() != null && !SlotStatus.AVAILABLE.equals(slot.getSlotStatus())) {
throw new RuntimeException("手慢了!该号源已刚刚被他人抢占");
}
// 详细调试:检查每个状态比较的结果
boolean isUnbooked = "unbooked".equals(status);
boolean isLocked = "locked".equals(status);
boolean isCancelled = "cancelled".equals(status);
boolean isChecked = "checked".equals(status);
boolean isBooked = "booked".equals(status);
logger.debug("状态比较结果: unbooked={}, locked={}, cancelled={}, checked={}, booked={}",
isUnbooked, isLocked, isCancelled, isChecked, isBooked);
if (!isUnbooked && !isLocked && !isCancelled && !isChecked && !isBooked) {
logger.error("号源不可预约id: {}, status: {}", ticket.getId(), ticket.getStatus());
throw new RuntimeException("号源不可预约");
if (Boolean.TRUE.equals(slot.getIsStopped())) {
throw new RuntimeException("该排班医生已停诊");
}
params.put("slotId", ticketId);
Order order = orderService.createAppointmentOrder(params);
// 原子抢占:避免并发下同一槽位被重复预约
int lockRows = scheduleSlotMapper.lockSlotForBooking(slotId);
if (lockRows <= 0) {
throw new RuntimeException("手慢了!该号源已刚刚被他人抢占");
}
Ticket updateTicket = new Ticket();
updateTicket.setId(ticketId);
updateTicket.setStatus("booked");
updateTicket.setPatientId(patientId);
updateTicket.setPatientName(patientName);
updateTicket.setMedicalCard(medicalCard);
updateTicket.setPhone(phone);
updateTicket.setAppointmentDate(new Date());
updateTicket.setAppointmentTime(new Date());
int result = ticketMapper.updateById(updateTicket);
logger.debug("预约成功更新号源状态为bookedresult: {}", result);
return result;
// 2. 将 DTO 安全降级转换为 Map 给最底层的建单工厂
// 因为建单方法非常底层,通用性强,为了不影响它,我们在这里安全组装 Map
// 在持有强类型 DTO 的地方提前合并日期+时间,转为 java.util.Date 后再传入 Map
// 避免将 LocalDate/LocalTime 装箱为 Object 跨层传递时可能出现的类型映射失败(如 MyBatis 将
// PostgreSQL date 类型映射为 java.sql.Date 导致 slot.getScheduleDate() 返回 null
LocalDate scheduleDate = slot.getScheduleDate();
LocalTime expectTime = slot.getExpectTime();
Date appointmentDateTime;
if (scheduleDate != null && expectTime != null) {
LocalDateTime ldt = LocalDateTime.of(scheduleDate, expectTime);
appointmentDateTime = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
} else {
// 理论上不应走到这里,若走到说明号源池数据异常
appointmentDateTime = new Date();
}
Map<String, Object> safeParams = new java.util.HashMap<>();
safeParams.put("slotId", slotId);
safeParams.put("scheduleId", slot.getScheduleId());
// 直接传入已合并的 Date 对象OrderServiceImpl 无需再做类型转换
safeParams.put("appointmentDate", appointmentDateTime);
safeParams.put("appointmentTime", appointmentDateTime);
safeParams.put("patientId", dto.getPatientId());
safeParams.put("patientName", dto.getPatientName());
safeParams.put("medicalCard", dto.getMedicalCard());
safeParams.put("phone", dto.getPhone());
safeParams.put("gender", dto.getGender());
safeParams.put("tenant_id", dto.getTenant_id());
// 3. 【绝对防御】:强制覆盖!不管前端 DTO 传了什么鬼,全以底层数据库物理表为准!
safeParams.put("departmentId", slot.getDepartmentId());
safeParams.put("departmentName", slot.getDepartmentName());
safeParams.put("doctorId", slot.getDoctorId());
safeParams.put("doctorName", slot.getDoctor());
safeParams.put("fee", toBigDecimal(slot.getFee()));
safeParams.put("regType", slot.getRegType() != null && slot.getRegType() == 1 ? "专家" : "普通");
// 4. 收银台建单!
Order order = orderService.createAppointmentOrder(safeParams);
if (order == null || order.getId() == null) {
throw new RuntimeException("预约订单创建失败");
}
// 5. 回填订单ID到号源槽位保证号源与订单一一关联
int bindRows = scheduleSlotMapper.bindOrderToSlot(slotId, order.getId());
if (bindRows <= 0) {
throw new RuntimeException("预约成功但号源回填订单失败,请重试");
}
refreshPoolStatsBySlotId(slotId);
return 1;
}
/**
* 取消预约
*
* @param ticketId 号源ID
* @param slotId 槽位ID
* @return 结果
*/
@Override
@Transactional(rollbackFor = Exception.class)
public int cancelTicket(Long ticketId) {
Ticket ticket = ticketMapper.selectTicketById(ticketId);
if (ticket == null) {
throw new RuntimeException("号源不存在");
public int cancelTicket(Long slotId) {
TicketSlotDTO slot = scheduleSlotMapper.selectTicketSlotById(slotId);
if (slot == null) {
throw new RuntimeException("号源槽位不存在");
}
if (!"booked".equals(ticket.getStatus()) && !"locked".equals(ticket.getStatus())) {
if (slot.getSlotStatus() == null || !SlotStatus.BOOKED.equals(slot.getSlotStatus())) {
throw new RuntimeException("号源不可取消预约");
}
List<Order> orders = orderService.selectOrderBySlotId(ticketId);
for(Order order:orders){
List<Order> orders = orderService.selectOrderBySlotId(slotId);
if (orders == null || orders.isEmpty()) {
throw new RuntimeException("当前号源没有可取消的预约订单");
}
for (Order order : orders) {
orderService.cancelAppointmentOrder(order.getId(), "患者取消预约");
}
ticket.setStatus("unbooked");
ticket.setPatientId(null);
ticket.setPatientName(null);
ticket.setMedicalCard(null);
ticket.setPhone(null);
ticket.setAppointmentDate(null);
ticket.setAppointmentTime(null);
return ticketMapper.updateTicket(ticket);
int updated = scheduleSlotMapper.updateSlotStatus(slotId, SlotStatus.AVAILABLE);
if (updated > 0) {
refreshPoolStatsBySlotId(slotId);
}
return updated;
}
/**
* 取号
*
* @param ticketId 号源ID
* @param slotId 槽位ID
* @return 结果
*/
@Override
public int checkInTicket(Long ticketId) {
// 获取号源信息
Ticket ticket = ticketMapper.selectTicketById(ticketId);
if (ticket == null) {
throw new RuntimeException("号源不存在");
@Transactional(rollbackFor = Exception.class)
public int checkInTicket(Long slotId) {
List<Order> orders = orderService.selectOrderBySlotId(slotId);
if (orders == null || orders.isEmpty()) {
throw new RuntimeException("当前号源没有可取号的预约订单");
}
if (!"booked".equals(ticket.getStatus()) && !"locked".equals(ticket.getStatus())) {
throw new RuntimeException("号源不可取号");
}
// 更新号源状态为已取号
ticket.setStatus("checked");
return ticketMapper.updateTicket(ticket);
Order latestOrder = orders.get(0);
return orderService.updateOrderStatusById(latestOrder.getId(), AppointmentOrderStatus.CHECKED_IN);
}
/**
* 停诊
*
* @param ticketId 号源ID
* @param slotId 槽位ID
* @return 结果
*/
@Override
@Transactional(rollbackFor = Exception.class)
public int cancelConsultation(Long ticketId) {
// 获取号源信息
Ticket ticket = ticketMapper.selectTicketById(ticketId);
if (ticket == null) {
throw new RuntimeException("号源不存在");
public int cancelConsultation(Long slotId) {
TicketSlotDTO slot = scheduleSlotMapper.selectTicketSlotById(slotId);
if (slot == null) {
throw new RuntimeException("号源槽位不存在");
}
// 检查是否存在相关订单,如果存在则取消
List<Order> orders = orderService.selectOrderBySlotId(ticketId);
for(Order order:orders){
List<Order> orders = orderService.selectOrderBySlotId(slotId);
for (Order order : orders) {
orderService.cancelAppointmentOrder(order.getId(), "医生停诊");
}
// 更新号源状态为已取消
ticket.setStatus("cancelled");
ticket.setPatientId(null);
ticket.setPatientName(null);
ticket.setMedicalCard(null);
ticket.setPhone(null);
ticket.setAppointmentDate(null);
ticket.setAppointmentTime(null);
return ticketMapper.updateTicket(ticket);
int updated = scheduleSlotMapper.updateSlotStatus(slotId, SlotStatus.STOPPED);
if (updated > 0) {
refreshPoolStatsBySlotId(slotId);
}
return updated;
}
/**
* 根据槽位ID找到号源池并刷新 booked_num / locked_num 统计。
*/
private void refreshPoolStatsBySlotId(Long slotId) {
Long poolId = scheduleSlotMapper.selectPoolIdBySlotId(slotId);
if (poolId != null) {
schedulePoolMapper.refreshPoolStats(poolId);
}
}
private BigDecimal toBigDecimal(String fee) {
if (fee == null || fee.trim().isEmpty()) {
return BigDecimal.ZERO;
}
try {
return new BigDecimal(fee.trim());
} catch (NumberFormatException e) {
throw new RuntimeException("挂号费格式错误: " + fee);
}
}
}

View File

@@ -0,0 +1,309 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.openhis.appointmentmanage.mapper.ScheduleSlotMapper">
<!-- 注意这里的 resultType 指向了您刚建好的 DTO 实体类 -->
<select id="selectAllTicketSlots" resultType="com.openhis.appointmentmanage.domain.TicketSlotDTO">
SELECT
s.id AS slotId,
p.schedule_id AS scheduleId,
p.doctor_name AS doctor,
p.dept_id AS departmentId,
p.fee AS fee,
o.patient_id AS patientId,
o.patient_name AS patientName,
o.medical_card AS medicalCard,
o.phone AS phone,
o.status AS orderStatus,
s.status AS slotStatus,
s.expect_time AS expectTime,
p.schedule_date AS scheduleDate,
d.reg_type AS regType,
p.status AS poolStatus,
p.stop_reason AS stopReason,
d.is_stopped AS isStopped
FROM
adm_schedule_slot s
INNER JOIN adm_schedule_pool p ON s.pool_id = p.id
LEFT JOIN adm_doctor_schedule d ON p.schedule_id = d.id
LEFT JOIN (
SELECT DISTINCT
ON (slot_id) slot_id,
patient_id,
patient_name,
medical_card,
phone,
status
FROM
order_main
WHERE
status IN (1, 2)
ORDER BY
slot_id,
create_time DESC
) o ON o.slot_id = s.id
WHERE
p.delete_flag = '0'
AND s.delete_flag = '0'
ORDER BY
p.schedule_date,
p.doctor_id,
s.expect_time
</select>
<select id="selectTicketSlotById" resultType="com.openhis.appointmentmanage.domain.TicketSlotDTO">
SELECT
s.id AS slotId,
p.schedule_id AS scheduleId,
p.doctor_name AS doctor,
p.doctor_id AS doctorId,
p.dept_id AS departmentId,
org.name AS departmentName,
p.fee AS fee,
o.patient_id AS patientId,
o.patient_name AS patientName,
o.medical_card AS medicalCard,
o.phone AS phone,
o.status AS orderStatus,
s.status AS slotStatus,
s.expect_time AS expectTime,
p.schedule_date AS scheduleDate,
d.reg_type AS regType,
p.status AS poolStatus,
p.stop_reason AS stopReason,
d.is_stopped AS isStopped
FROM
adm_schedule_slot s
INNER JOIN adm_schedule_pool p ON s.pool_id = p.id
LEFT JOIN adm_doctor_schedule d ON p.schedule_id = d.id
LEFT JOIN adm_organization org ON p.dept_id = org.id
AND org.delete_flag = '0'
LEFT JOIN (
SELECT DISTINCT
ON (slot_id) slot_id,
patient_id,
patient_name,
medical_card,
phone,
status
FROM
order_main
WHERE
status IN (1, 2)
ORDER BY
slot_id,
create_time DESC
) o ON o.slot_id = s.id
WHERE
s.id = #{id}
</select>
<update id="lockSlotForBooking">
UPDATE adm_schedule_slot
SET
status = 1,
update_time = now()
WHERE
id = #{slotId}
AND status = 0
AND delete_flag = '0'
</update>
<update id="updateSlotStatus">
UPDATE adm_schedule_slot
SET
status = #{status},
<if test="status == 0">
order_id = NULL,
</if>
update_time = now()
WHERE
id = #{slotId}
AND delete_flag = '0'
</update>
<select id="selectPoolIdBySlotId" resultType="java.lang.Long">
SELECT pool_id
FROM adm_schedule_slot
WHERE id = #{slotId}
AND delete_flag = '0'
</select>
<update id="bindOrderToSlot">
UPDATE adm_schedule_slot
SET
order_id = #{orderId},
update_time = now()
WHERE
id = #{slotId}
AND status = 1
AND delete_flag = '0'
</update>
<select id="selectTicketSlotsPage" resultType="com.openhis.appointmentmanage.domain.TicketSlotDTO">
SELECT
s.id AS slotId,
p.schedule_id AS scheduleId,
p.doctor_name AS doctor,
p.doctor_id AS doctorId,
p.dept_id AS departmentId,
org.name AS departmentName,
p.fee AS fee,
o.patient_id AS patientId,
o.patient_name AS patientName,
o.medical_card AS medicalCard,
o.phone AS phone,
o.status AS orderStatus,
s.status AS slotStatus,
s.expect_time AS expectTime,
p.schedule_date AS scheduleDate,
d.reg_type AS regType,
p.status AS poolStatus,
p.stop_reason AS stopReason,
d.is_stopped AS isStopped
FROM
adm_schedule_slot s
INNER JOIN adm_schedule_pool p ON s.pool_id = p.id
LEFT JOIN adm_doctor_schedule d ON p.schedule_id = d.id
LEFT JOIN adm_organization org ON p.dept_id = org.id
AND org.delete_flag = '0'
LEFT JOIN (
SELECT DISTINCT
ON (slot_id) slot_id,
patient_id,
patient_name,
medical_card,
phone,
status
FROM
order_main
WHERE
status IN (1, 2)
ORDER BY
slot_id,
create_time DESC
) o ON o.slot_id = s.id
<where>
p.delete_flag = '0'
AND s.delete_flag = '0' <!-- 1. 按日期查 -->
<if test="query.date != null and query.date != ''">
AND p.schedule_date = CAST(#{query.date} AS DATE)
</if>
<!-- 2. 按科室查 -->
<if test="query.department != null and query.department != '' and query.department != 'all'">
AND org.name = #{query.department}
</if>
<if test="query.doctorId != null">
AND p.doctor_id = #{query.doctorId}
</if>
<!-- 3. 按号源类型查 (专家/普通) -->
<if test="query.type != null and query.type != ''">
<choose>
<when test="query.type == 'expert'">
AND d.reg_type = 1
</when>
<when test="query.type == 'general'">
AND (
d.reg_type != 1
OR d.reg_type IS NULL
)
</when>
</choose>
</if>
<!-- 4. 模糊搜索患者信息 -->
<if test="query.name != null and query.name != ''">
AND o.patient_name LIKE CONCAT('%', #{query.name}, '%')
</if>
<if test="query.card != null and query.card != ''">
AND o.medical_card LIKE CONCAT('%', #{query.card}, '%')
</if>
<if test="query.phone != null and query.phone != ''">
AND o.phone LIKE CONCAT('%', #{query.phone}, '%')
</if>
<!-- 5. 核心:解答您疑问的 4 种业务状态的复合查询! -->
<if test="query.status != null and query.status != '' and query.status != 'all'">
<choose>
<when test="query.status == 'unbooked'">
AND s.status = 0
AND (
d.is_stopped IS NULL
OR d.is_stopped = FALSE
)
</when>
<when test="query.status == 'booked'">
AND s.status = 1
AND o.status = 1
AND (
d.is_stopped IS NULL
OR d.is_stopped = FALSE
)
</when>
<when test="query.status == 'checked'">
AND s.status = 1
AND o.status = 2
AND (
d.is_stopped IS NULL
OR d.is_stopped = FALSE
)
</when>
<when test="query.status == 'cancelled'">
AND (
s.status = 2
OR d.is_stopped = TRUE
)
</when>
</choose>
</if>
</where>
ORDER BY
p.schedule_date DESC,
s.expect_time ASC
</select>
<select id="selectDoctorAvailabilitySummary" resultType="com.openhis.appointmentmanage.domain.DoctorAvailabilityDTO">
SELECT
p.doctor_id AS doctorId,
p.doctor_name AS doctorName,
COALESCE(SUM(GREATEST(COALESCE(p.total_quota, 0) - COALESCE(p.booked_num, 0) - COALESCE(p.locked_num, 0), 0)), 0) AS available,
CASE
WHEN MAX(CASE WHEN d.reg_type = 1 THEN 1 ELSE 0 END) = 1 THEN 'expert'
ELSE 'general'
END AS ticketType
FROM
adm_schedule_pool p
LEFT JOIN adm_doctor_schedule d ON p.schedule_id = d.id
LEFT JOIN adm_organization org ON p.dept_id = org.id
AND org.delete_flag = '0'
<where>
p.delete_flag = '0'
<if test="query.date != null and query.date != ''">
AND p.schedule_date = CAST(#{query.date} AS DATE)
</if>
<if test="query.department != null and query.department != '' and query.department != 'all'">
AND org.name = #{query.department}
</if>
<if test="query.type != null and query.type != '' and query.type != 'all'">
<choose>
<when test="query.type == 'expert'">
AND d.reg_type = 1
</when>
<when test="query.type == 'general'">
AND (d.reg_type != 1 OR d.reg_type IS NULL)
</when>
</choose>
</if>
<if test="query.doctorId != null">
AND p.doctor_id = #{query.doctorId}
</if>
</where>
GROUP BY
p.doctor_id,
p.doctor_name
ORDER BY
p.doctor_name ASC
</select>
</mapper>