Files
zyt/server/app/adminapi/lists/doctor/AppointmentLists.php
T
2026-05-14 16:23:29 +08:00

457 lines
18 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace app\adminapi\lists\doctor;
use app\adminapi\lists\BaseAdminDataLists;
use app\common\model\DiagnosisViewRecord;
use app\common\model\doctor\Appointment;
use app\common\model\tcm\Prescription;
use app\common\model\auth\AdminRole;
use app\common\model\dict\DictData;
use app\common\lists\ListsExtendInterface;
use app\common\lists\ListsSearchInterface;
use app\common\lists\Traits\HasDataScopeFilter;
use think\facade\Db;
/**
* 医生预约列表
* Class AppointmentLists
* @package app\adminapi\lists\doctor
*/
class AppointmentLists extends BaseAdminDataLists implements ListsSearchInterface, ListsExtendInterface
{
use HasDataScopeFilter;
/**
* 诊单编辑/详情「挂号记录」Tab:按诊单 ID 拉全量挂号,不做医生/医助角色收窄与数据范围过滤。
* 须同时传 patient_id(挂号表存的是诊单 id)与本开关,避免列表页被滥用拓宽可见范围。
*/
private function appointmentListsScopeRelaxedForDiagnosis(): bool
{
return (int) ($this->params['diag_scope_relax'] ?? 0) === 1
&& (int) ($this->params['patient_id'] ?? 0) > 0;
}
/**
* 数据隔离:医生或医助(u.assistant_id = diag.assistant_id)命中可见集合;progress_board 场景放开(看板跨医生查看)
*/
private function applyDataScopeForAppointment($query, bool $progressBoard): void
{
if ($progressBoard) {
return;
}
if ($this->appointmentListsScopeRelaxedForDiagnosis()) {
return;
}
if (!$this->dataScopeShouldApply()) {
return;
}
$ids = $this->getDataScopeVisibleAdminIds();
if ($ids === null) {
return;
}
if ($ids === []) {
$query->whereRaw('0 = 1');
return;
}
$inList = implode(',', $ids);
$query->whereRaw("(a.doctor_id IN ({$inList}) OR u.assistant_id IN ({$inList}))");
}
/**
* 按医助筛选:诊单指派医助或挂号记录上的医助任一命中即可
*
* @param mixed $query
*/
private function applyAssistantIdFilter($query): void
{
$aid = (int) ($this->params['assistant_id'] ?? 0);
if ($aid <= 0) {
return;
}
$query->where(function ($q) use ($aid): void {
$q->where('u.assistant_id', $aid)->whereOr('a.assistant_id', $aid);
});
}
/**
* 渠道筛选:与 AppointmentLogic 一致,兼容仅有 channel_source、仅有 channels、或两者皆有的表结构
*
* @param mixed $query
*/
private function applyChannelSourceFilter($query, string $chFilter): void
{
if ($chFilter === '') {
return;
}
$tblFields = Db::name('doctor_appointment')->getTableFields();
$cols = \is_array($tblFields) ? $tblFields : [];
$hasChannelSource = \in_array('channel_source', $cols, true);
$hasChannels = \in_array('channels', $cols, true);
if (!$hasChannelSource && !$hasChannels) {
return;
}
$query->where(function ($q) use ($chFilter, $hasChannelSource, $hasChannels): void {
if ($hasChannelSource && $hasChannels) {
$q->where('a.channel_source', '=', $chFilter)
->whereOr('a.channels', '=', $chFilter);
if (is_numeric($chFilter)) {
$q->whereOr('a.channels', '=', (int) $chFilter);
}
return;
}
if ($hasChannelSource) {
$q->where('a.channel_source', '=', $chFilter);
return;
}
$q->where('a.channels', '=', $chFilter);
if (is_numeric($chFilter)) {
$q->whereOr('a.channels', '=', (int) $chFilter);
}
});
}
/**
* @notes 设置搜索条件
* @return array
*/
public function setSearch(): array
{
return [];
}
/**
* @notes 获取列表
* @return array
*/
public function lists(): array
{
// 获取当前管理员的角色ID
$roleIds = AdminRole::where('admin_id', $this->adminId)->column('role_id');
// 处理患者姓名搜索
if (!empty($this->params['patient_name'])) {
$this->searchWhere[] = ['u.patient_name', 'like', '%' . $this->params['patient_name'] . '%'];
}
// 处理医生姓名搜索
if (!empty($this->params['doctor_name'])) {
$this->searchWhere[] = ['ad.name', 'like', '%' . $this->params['doctor_name'] . '%'];
}
// 处理状态搜索
if (isset($this->params['status']) && $this->params['status'] !== '') {
$this->searchWhere[] = ['a.status', '=', $this->params['status']];
}
// 渠道字典 value(命中 channel_source 或 legacy channels
$chFilter = isset($this->params['channel_source']) ? trim((string) $this->params['channel_source']) : '';
// 处理日期范围搜索
if (!empty($this->params['start_date']) && !empty($this->params['end_date'])) {
$this->searchWhere[] = ['a.appointment_date', 'between', [$this->params['start_date'], $this->params['end_date']]];
} elseif (!empty($this->params['start_date'])) {
$this->searchWhere[] = ['a.appointment_date', '>=', $this->params['start_date']];
} elseif (!empty($this->params['end_date'])) {
$this->searchWhere[] = ['a.appointment_date', '<=', $this->params['end_date']];
}
// 诊单维度患者(挂号表 patient_id 存诊单 id
if (!empty($this->params['patient_id'])) {
$this->searchWhere[] = ['a.patient_id', '=', (int) $this->params['patient_id']];
}
// 按接诊医生筛选(管理端医生进度看板等)
if (!empty($this->params['doctor_id'])) {
$this->searchWhere[] = ['a.doctor_id', '=', (int) $this->params['doctor_id']];
}
// 排除已取消挂号 status=2(医生进度看板等;未显式筛选「已取消」时生效)
if ((int) ($this->params['exclude_cancelled'] ?? 0) === 1) {
$sf = $this->params['status'] ?? '';
if ($sf === '' || (int) $sf !== 2) {
$this->searchWhere[] = ['a.status', '<>', 2];
}
}
// 构建查询(searchWhere 为空时避免部分环境下 where([]) 异常)
$query = Appointment::alias('a')
->with('diagnosis')
->leftJoin('tcm_diagnosis u', 'a.patient_id = u.id')
->leftJoin('admin ad', 'a.doctor_id = ad.id')
->leftJoin('admin asst', 'u.assistant_id = asst.id')
->field('a.*, u.patient_name as patient_name, u.phone as patient_phone, u.gender as gender, u.age as age, u.weight as weight, u.height as height, u.assistant_id as assistant_id, ad.name as doctor_name, asst.name as assistant_name, u.id as diagnosis_id, a.assistant_id as appointment_assistant_id');
if ($this->searchWhere !== []) {
$query->where($this->searchWhere);
}
$this->applyAssistantIdFilter($query);
$this->applyChannelSourceFilter($query, $chFilter);
// 是否确认诊单:1=已确认 0=未确认
if (isset($this->params['diagnosis_confirmed']) && $this->params['diagnosis_confirmed'] !== '') {
$confirmed = (int)$this->params['diagnosis_confirmed'];
$tbl = (new DiagnosisViewRecord())->getTable();
$subSql = "SELECT 1 FROM {$tbl} dvr WHERE dvr.diagnosis_id = u.id AND dvr.is_confirmed = 1 AND dvr.delete_time IS NULL";
if ($confirmed === 1) {
$query->whereExists($subSql);
} else {
$query->whereNotExists($subSql);
}
}
// 面诊进度看板:可切换查看各医生挂号,不按当前账号角色收窄
$progressBoard = (int) ($this->params['progress_board'] ?? 0) === 1;
$diagScopeRelax = $this->appointmentListsScopeRelaxedForDiagnosis();
if (!$progressBoard && !$diagScopeRelax) {
// 如果是医生角色(role_id=1),只显示挂自己号的预约
if (in_array(1, $roleIds)) {
$query->where('a.doctor_id', $this->adminId);
}
// 如果是医助角色(role_id=2),只显示自己添加的患者的预约
if (in_array(2, $roleIds)) {
$query->where('u.assistant_id', $this->adminId);
}
}
$this->applyDataScopeForAppointment($query, $progressBoard);
// 诊单软删除后不再展示对应挂号(leftJoin 时无诊单或诊单未删)
$query->whereRaw('(u.id IS NULL OR u.delete_time IS NULL)');
$lists = $query
->order('a.status', 'asc')
->order('a.appointment_date', 'asc')
->order('a.appointment_time', 'asc')
->limit($this->limitOffset, $this->limitLength)
->select()
->toArray();
// 添加状态、类型描述及确认诊单状态
$diagnosisIds = array_filter(array_unique(array_column($lists, 'diagnosis_id')));
$confirmedMap = [];
if (!empty($diagnosisIds)) {
$confirmedIds = \think\facade\Db::name('diagnosis_view_records')
->whereIn('diagnosis_id', $diagnosisIds)
->where('is_confirmed', 1)
->whereNull('delete_time')
->column('diagnosis_id');
$confirmedMap = array_flip($confirmedIds ?: []);
}
// 开方状态:诊单是否有处方(按 diagnosis_id 查)
// prescription_today_only=1:仅统计「今日创建」的处方(医生进度看板用,与历史处方区分)
$rxTodayOnly = (int) ($this->params['prescription_today_only'] ?? 0) === 1;
$prescribedDiagnosisIds = [];
if (!empty($diagnosisIds)) {
$rxQ = Prescription::whereIn('diagnosis_id', $diagnosisIds)
->whereNull('delete_time')
->where('void_status', 0);
if ($rxTodayOnly) {
$dayStart = strtotime(date('Y-m-d 00:00:00'));
$dayEnd = strtotime(date('Y-m-d 23:59:59'));
$rxQ->whereBetween('create_time', [$dayStart, $dayEnd]);
}
$prescribedDiagnosisIds = $rxQ->column('diagnosis_id');
$prescribedDiagnosisIds = array_flip($prescribedDiagnosisIds ?: []);
}
// 当前页预约关联的处方(按 appointment_id,取最新一条):用于「开方/查看」与审核状态
$appointmentIds = array_filter(array_map('intval', array_column($lists, 'id')));
$rxByAppointmentId = [];
if (!empty($appointmentIds)) {
$rxRows = Prescription::whereIn('appointment_id', $appointmentIds)
->whereNull('delete_time')
->where('void_status', 0)
->order('id', 'desc')
->field(['id', 'appointment_id', 'audit_status', 'void_status', 'is_system_auto'])
->select()
->toArray();
foreach ($rxRows as $rx) {
$aid = (int) ($rx['appointment_id'] ?? 0);
if ($aid > 0 && !isset($rxByAppointmentId[$aid])) {
$rxByAppointmentId[$aid] = $rx;
}
}
}
$channelNameByValue = DictData::where('type_value', 'channels')->column('name', 'value');
foreach ($lists as &$item) {
$statusMap = [
1 => '已预约',
2 => '已取消',
3 => '已完成',
4 => '已过号',
];
$item['status_desc'] = $statusMap[$item['status']] ?? '未知';
$typeMap = [
'video' => '视频问诊',
'text' => '图文问诊',
'phone' => '电话问诊',
];
$item['appointment_type_desc'] = $typeMap[$item['appointment_type']] ?? '未知';
$periodRaw = (string) ($item['period'] ?? ($item['type'] ?? ''));
$periodMap = [
'morning' => '上午',
'afternoon' => '下午',
'all' => '全天',
];
$item['period_desc'] = $periodMap[$periodRaw] ?? ($periodRaw !== '' ? $periodRaw : '—');
$srcKey = trim((string) ($item['channel_source'] ?? ''));
if ($srcKey === '' && isset($item['channels']) && $item['channels'] !== '' && $item['channels'] !== null) {
$srcKey = trim((string) $item['channels']);
}
if ($srcKey !== '') {
$item['channel_source_desc'] = (string) ($channelNameByValue[$srcKey] ?? $channelNameByValue[(string) (int) $srcKey] ?? $srcKey);
} else {
$item['channel_source_desc'] = '—';
}
$item['diagnosis_confirmed'] = isset($confirmedMap[$item['diagnosis_id'] ?? 0]) ? 1 : 0;
$item['has_prescription'] = isset($prescribedDiagnosisIds[$item['diagnosis_id'] ?? 0]) ? 1 : 0;
$apptId = (int) ($item['id'] ?? 0);
$apptRx = $rxByAppointmentId[$apptId] ?? null;
$item['prescription_audit_status'] = $apptRx !== null ? (int) ($apptRx['audit_status'] ?? -1) : -1;
$item['prescription_void_status'] = $apptRx !== null ? (int) ($apptRx['void_status'] ?? 0) : 0;
$item['prescription_is_system_auto'] = $apptRx !== null ? (int) ($apptRx['is_system_auto'] ?? 0) : 0;
// 格式化时间戳为日期时间
if (isset($item['create_time']) && is_numeric($item['create_time'])) {
$item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
}
if (isset($item['update_time']) && is_numeric($item['update_time'])) {
$item['update_time'] = date('Y-m-d H:i:s', $item['update_time']);
}
}
return $lists;
}
/**
* 列表 count / Tab 角标统计共用的过滤条件(不依赖 lists() 对 searchWhere 的副作用)
* @param mixed $query
* @param bool $applyStatusFilter 为 false 时按状态分组统计各 Tab 数量
*/
private function applyAppointmentCountFilters($query, bool $applyStatusFilter): void
{
$roleIds = AdminRole::where('admin_id', $this->adminId)->column('role_id');
if (!empty($this->params['patient_name'])) {
$query->where('u.patient_name', 'like', '%' . $this->params['patient_name'] . '%');
}
if (!empty($this->params['doctor_name'])) {
$query->where('ad.name', 'like', '%' . $this->params['doctor_name'] . '%');
}
if ($applyStatusFilter && isset($this->params['status']) && $this->params['status'] !== '') {
$query->where('a.status', '=', $this->params['status']);
}
$chFilter = isset($this->params['channel_source']) ? trim((string) $this->params['channel_source']) : '';
if (!empty($this->params['start_date']) && !empty($this->params['end_date'])) {
$query->whereBetween('a.appointment_date', [$this->params['start_date'], $this->params['end_date']]);
} elseif (!empty($this->params['start_date'])) {
$query->where('a.appointment_date', '>=', $this->params['start_date']);
} elseif (!empty($this->params['end_date'])) {
$query->where('a.appointment_date', '<=', $this->params['end_date']);
}
if (!empty($this->params['patient_id'])) {
$query->where('a.patient_id', '=', (int) $this->params['patient_id']);
}
if (!empty($this->params['doctor_id'])) {
$query->where('a.doctor_id', '=', (int) $this->params['doctor_id']);
}
$this->applyAssistantIdFilter($query);
$this->applyChannelSourceFilter($query, $chFilter);
if ((int) ($this->params['exclude_cancelled'] ?? 0) === 1) {
$sf = $this->params['status'] ?? '';
if ($sf === '' || (int) $sf !== 2) {
$query->where('a.status', '<>', 2);
}
}
if (isset($this->params['diagnosis_confirmed']) && $this->params['diagnosis_confirmed'] !== '') {
$confirmed = (int)$this->params['diagnosis_confirmed'];
$tbl = (new DiagnosisViewRecord())->getTable();
$subSql = "SELECT 1 FROM {$tbl} dvr WHERE dvr.diagnosis_id = u.id AND dvr.is_confirmed = 1 AND dvr.delete_time IS NULL";
if ($confirmed === 1) {
$query->whereExists($subSql);
} else {
$query->whereNotExists($subSql);
}
}
$progressBoard = (int) ($this->params['progress_board'] ?? 0) === 1;
$diagScopeRelax = $this->appointmentListsScopeRelaxedForDiagnosis();
if (!$progressBoard && !$diagScopeRelax) {
if (in_array(1, $roleIds)) {
$query->where('a.doctor_id', $this->adminId);
}
if (in_array(2, $roleIds)) {
$query->where('u.assistant_id', $this->adminId);
}
}
$this->applyDataScopeForAppointment($query, $progressBoard);
$query->whereRaw('(u.id IS NULL OR u.delete_time IS NULL)');
}
/**
* @notes 获取数量
* @return int
*/
public function count(): int
{
$query = Appointment::alias('a')
->leftJoin('tcm_diagnosis u', 'a.patient_id = u.id')
->leftJoin('admin ad', 'a.doctor_id = ad.id');
$this->applyAppointmentCountFilters($query, true);
return (int)$query->count();
}
/**
* @notes 扩展字段:按需返回各状态数量(一次 GROUP BY,替代前端 4 次列表请求)
* @return array
*/
public function extend(): array
{
if (empty($this->params['include_status_counts'])) {
return [];
}
$query = Appointment::alias('a')
->leftJoin('tcm_diagnosis u', 'a.patient_id = u.id')
->leftJoin('admin ad', 'a.doctor_id = ad.id');
$this->applyAppointmentCountFilters($query, false);
$rows = $query->field('a.status, COUNT(*) AS cnt')
->group('a.status')
->select()
->toArray();
$out = [1 => 0, 2 => 0, 3 => 0, 4 => 0];
foreach ($rows as $r) {
$s = (int)($r['status'] ?? 0);
if (array_key_exists($s, $out)) {
$out[$s] = (int)($r['cnt'] ?? 0);
}
}
return ['status_count' => $out];
}
}