first commit

This commit is contained in:
Your Name
2026-09-08 11:40:15 +08:00
commit a5353f7eb5
9568 changed files with 1646214 additions and 0 deletions
@@ -0,0 +1,491 @@
<?php
namespace app\adminapi\lists\doctor;
use app\adminapi\lists\BaseAdminDataLists;
use app\adminapi\logic\dept\DeptLogic;
use app\common\model\auth\AdminDept;
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);
});
}
/**
* 按部门筛选:接诊医生、诊单医助或挂号医助所属部门命中子树即可(选父级含子级)
*
* @param mixed $query
*/
private function applyAssistantDeptIdFilter($query): void
{
if (!isset($this->params['assistant_dept_id']) || $this->params['assistant_dept_id'] === '' || (int) $this->params['assistant_dept_id'] <= 0) {
return;
}
$rootDeptId = (int) $this->params['assistant_dept_id'];
$deptIds = DeptLogic::getSelfAndDescendantIds($rootDeptId);
$deptIds = array_values(array_filter(array_map('intval', $deptIds), static function (int $id): bool {
return $id > 0;
}));
if ($deptIds === []) {
$query->whereRaw('0 = 1');
return;
}
$inList = implode(',', $deptIds);
$adTbl = (new AdminDept())->getTable();
$query->whereRaw(
"(EXISTS (SELECT 1 FROM `{$adTbl}` ad WHERE ad.`admin_id` = a.`doctor_id` AND ad.`dept_id` IN ({$inList}))"
. " OR EXISTS (SELECT 1 FROM `{$adTbl}` ad WHERE ad.`admin_id` = u.`assistant_id` AND ad.`dept_id` IN ({$inList}))"
. " OR EXISTS (SELECT 1 FROM `{$adTbl}` ad WHERE ad.`admin_id` = a.`assistant_id` AND ad.`dept_id` IN ({$inList})))"
);
}
/**
* 渠道筛选:与 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->applyAssistantDeptIdFilter($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->applyAssistantDeptIdFilter($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];
}
}
@@ -0,0 +1,76 @@
<?php
namespace app\adminapi\lists\doctor;
use app\adminapi\lists\BaseAdminDataLists;
use app\common\model\doctor\Medicine;
use app\common\lists\ListsSearchInterface;
/**
* 药品库列表
*/
class MedicineLists extends BaseAdminDataLists implements ListsSearchInterface
{
/**
* 设置搜索条件
*/
public function setSearch(): array
{
return [
'%like%' => ['supplier'],
'=' => ['status'],
];
}
/**
* name 参数:中文等按名称模糊;纯英文字母按拼音首字母字段 + 名称模糊(OR)
*/
private function appendMedicineNameSearch($query): void
{
$keyword = trim((string) ($this->params['name'] ?? ''));
if ($keyword === '') {
return;
}
if (preg_match('/^[a-zA-Z]+$/', $keyword)) {
$kw = strtolower($keyword);
$query->where(function ($q) use ($kw, $keyword) {
$q->where('name_pinyin_abbr', 'like', '%' . $kw . '%')
->whereOr('name', 'like', '%' . $keyword . '%');
});
} else {
$query->where('name', 'like', '%' . $keyword . '%');
}
}
/**
* 列表字段
*/
public function lists(): array
{
$query = Medicine::where($this->searchWhere);
$this->appendMedicineNameSearch($query);
return $query
->field([
'id', 'name', 'name_pinyin_abbr', 'supplier', 'unit',
'settlement_price', 'retail_price', 'stock',
'image', 'status', 'remark',
'create_time', 'update_time',
])
->limit($this->limitOffset, $this->limitLength)
->order(['id' => 'desc'])
->select()
->toArray();
}
/**
* 列表数量
*/
public function count(): int
{
$query = Medicine::where($this->searchWhere);
$this->appendMedicineNameSearch($query);
return $query->count();
}
}
@@ -0,0 +1,70 @@
<?php
namespace app\adminapi\lists\doctor;
use app\adminapi\lists\BaseAdminDataLists;
use app\common\model\doctor\Roster;
use app\common\lists\ListsSearchInterface;
/**
* 医生排班列表
* Class RosterLists
* @package app\adminapi\lists\doctor
*/
class RosterLists extends BaseAdminDataLists implements ListsSearchInterface
{
/**
* @notes 设置搜索条件
* @return array
*/
public function setSearch(): array
{
return [
'=' => ['doctor_id', 'period', 'status'],
];
}
/**
* @notes 获取列表
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function lists(): array
{
$where = $this->searchWhere;
// 处理日期范围搜索
if (!empty($this->params['start_date']) && !empty($this->params['end_date'])) {
$where[] = ['date', 'between', [$this->params['start_date'], $this->params['end_date']]];
}
$lists = Roster::where($where)
->field([
'id', 'doctor_id', 'date', 'period', 'start_time', 'end_time', 'shift_type', 'slot_minutes',
'status', 'quota', 'max_patients', 'booked_count', 'remark', 'create_time', 'update_time',
])
->order(['date' => 'asc', 'start_time' => 'asc', 'id' => 'asc'])
->select()
->toArray();
return $lists;
}
/**
* @notes 获取数量
* @return int
*/
public function count(): int
{
$where = $this->searchWhere;
// 处理日期范围搜索
if (!empty($this->params['start_date']) && !empty($this->params['end_date'])) {
$where[] = ['date', 'between', [$this->params['start_date'], $this->params['end_date']]];
}
return Roster::where($where)->count();
}
}
@@ -0,0 +1,516 @@
<?php
namespace app\adminapi\lists\doctor;
use app\adminapi\lists\BaseAdminDataLists;
use app\common\model\doctor\Appointment;
use app\common\model\auth\Admin;
/**
* 医生统计列表
* Class StatisticsLists
* @package app\adminapi\lists\doctor
*/
class StatisticsLists extends BaseAdminDataLists
{
protected $type = 'doctor';
/**
* @param string $type 统计类型:doctor(医生统计) 或 dept(部门统计)
*/
public function __construct($type = 'doctor')
{
parent::__construct();
$this->type = $type;
}
/**
* @notes 搜索条件
* @return array
*/
public function setSearch(): array
{
return [];
}
/**
* @notes 获取列表
* @return array
*/
public function lists(): array
{
if ($this->type === 'dept') {
return $this->getDeptStatistics();
}
$doctorId = $this->params['doctor_id'] ?? '';
$timeType = $this->params['time_type'] ?? 'today';
$startDate = $this->params['start_date'] ?? '';
$endDate = $this->params['end_date'] ?? '';
// 计算时间范围
list($startDate, $endDate, $timeRangeText) = $this->getTimeRange($timeType, $startDate, $endDate);
// 获取医生列表(role_id=1 表示医生角色)
$doctorAdminIds = \app\common\model\auth\AdminRole::where('role_id', 1)->column('admin_id');
if (empty($doctorAdminIds)) {
return [];
}
// 查询1:获取预约统计数据(快速查询,只查appointment表)
$statisticsData = \think\facade\Db::name('doctor_appointment')
->field([
'doctor_id',
'COUNT(*) as total_count',
'SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as registered_count',
'SUM(CASE WHEN status = 3 THEN 1 ELSE 0 END) as completed_count',
'SUM(CASE WHEN status = 4 THEN 1 ELSE 0 END) as missed_count',
'SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) as cancelled_count'
])
->whereIn('doctor_id', $doctorAdminIds)
->where('appointment_date', '>=', $startDate)
->where('appointment_date', '<=', $endDate);
if ($doctorId) {
$statisticsData->where('doctor_id', $doctorId);
}
$statisticsData = $statisticsData->group('doctor_id')->select()->toArray();
// 将统计数据按 doctor_id 索引
$statsMap = [];
foreach ($statisticsData as $stat) {
$statsMap[$stat['doctor_id']] = $stat;
}
// 诊单数:统计期内该医生挂号对应的 distinct 诊单(patient_id 存的是诊单 id
$diagnosisCountQuery = \think\facade\Db::name('doctor_appointment')
->field('doctor_id, COUNT(DISTINCT patient_id) as diagnosis_count')
->whereIn('doctor_id', $doctorAdminIds)
->where('appointment_date', '>=', $startDate)
->where('appointment_date', '<=', $endDate);
if ($doctorId) {
$diagnosisCountQuery->where('doctor_id', $doctorId);
}
$diagnosisCountRows = $diagnosisCountQuery->group('doctor_id')->select()->toArray();
$diagnosisCountMap = [];
foreach ($diagnosisCountRows as $row) {
$diagnosisCountMap[(int) $row['doctor_id']] = (int) $row['diagnosis_count'];
}
// 成交单:上述诊单中存在有效处方(未删除、未作废)的数量
$dealCountQuery = \think\facade\Db::name('doctor_appointment')->alias('apt')
->join('tcm_prescription rx', 'rx.diagnosis_id = apt.patient_id')
->field('apt.doctor_id, COUNT(DISTINCT apt.patient_id) as deal_count')
->whereIn('apt.doctor_id', $doctorAdminIds)
->where('apt.appointment_date', '>=', $startDate)
->where('apt.appointment_date', '<=', $endDate)
->whereNull('rx.delete_time')
->whereRaw('IFNULL(rx.void_status, 0) <> 1');
if ($doctorId) {
$dealCountQuery->where('apt.doctor_id', $doctorId);
}
$dealCountRows = $dealCountQuery->group('apt.doctor_id')->select()->toArray();
$dealCountMap = [];
foreach ($dealCountRows as $row) {
$dealCountMap[(int) $row['doctor_id']] = (int) $row['deal_count'];
}
// 获取医生信息
$doctorQuery = Admin::field('id,name')->whereIn('id', $doctorAdminIds);
if ($doctorId) {
$doctorQuery->where('id', $doctorId);
}
$doctors = $doctorQuery->select()->toArray();
// 查询2:获取部门统计信息(通过assistant_id直接关联,按部门和状态分组统计数量)
$doctorIdsWithAppointments = array_keys($statsMap);
$deptStatsMap = [];
$deptStatusMap = [];
$channelStatsMap = [];
$channelStatusMap = [];
if (!empty($doctorIdsWithAppointments)) {
// 通过 assistant_id → admin_dept → dept 获取部门统计(按状态分组)
$deptStats = \think\facade\Db::name('doctor_appointment')
->alias('apt')
->leftJoin('admin_dept ad', 'apt.assistant_id = ad.admin_id')
->leftJoin('dept dept', 'ad.dept_id = dept.id')
->field([
'apt.doctor_id',
'dept.id as dept_id',
'dept.name as dept_name',
'apt.status',
'COUNT(*) as count'
])
->whereIn('apt.doctor_id', $doctorIdsWithAppointments)
->where('apt.appointment_date', '>=', $startDate)
->where('apt.appointment_date', '<=', $endDate)
->whereNotNull('dept.id')
->group('apt.doctor_id, dept.id, apt.status')
->select()
->toArray();
// 组装部门统计数据:医生ID => "部门1(数量1) 部门2(数量2)"
// 同时组装部门状态数据:医生ID => 部门ID => 状态 => 数量
foreach ($deptStats as $stat) {
$doctorId = $stat['doctor_id'];
$deptId = $stat['dept_id'];
$deptName = $stat['dept_name'];
$status = $stat['status'];
$count = $stat['count'];
// 组装部门统计数据
if (!isset($deptStatsMap[$doctorId])) {
$deptStatsMap[$doctorId] = [];
}
if (!isset($deptStatsMap[$doctorId][$deptId])) {
$deptStatsMap[$doctorId][$deptId] = [
'dept_name' => $deptName,
'total_count' => 0
];
}
$deptStatsMap[$doctorId][$deptId]['total_count'] += $count;
// 组装部门状态数据
if (!isset($deptStatusMap[$doctorId])) {
$deptStatusMap[$doctorId] = [];
}
if (!isset($deptStatusMap[$doctorId][$deptId])) {
$deptStatusMap[$doctorId][$deptId] = [
'dept_name' => $deptName,
'statuses' => []
];
}
$deptStatusMap[$doctorId][$deptId]['statuses'][$status] = $count;
}
// 格式化部门统计数据
foreach ($deptStatsMap as $doctorId => &$depts) {
$formattedDepts = [];
foreach ($depts as $dept) {
$formattedDepts[] = $dept['dept_name'] . '(' . $dept['total_count'] . ')';
}
$deptStatsMap[$doctorId] = $formattedDepts;
}
// 获取渠道字典(dict_data.value => name),与挂号创建时 channel_source 存字典 value 一致
$channelDict = \think\facade\Db::name('dict_data')
->where('type_value', 'channels')
->column('name', 'value');
// 渠道:业务保存的是 channel_source(字典 value 字符串,见 AppointmentLogic::create);旧库可能仅有 channels(tinyint)
$channelBuckets = [];
$channelStatusBuckets = [];
try {
$channelStats = \think\facade\Db::name('doctor_appointment')
->field('doctor_id, channel_source, status, COUNT(*) as channel_count')
->whereIn('doctor_id', $doctorIdsWithAppointments)
->where('appointment_date', '>=', $startDate)
->where('appointment_date', '<=', $endDate)
->where('channel_source', '<>', '')
->group('doctor_id, channel_source, status')
->select()
->toArray();
foreach ($channelStats as $stat) {
$did = (int) $stat['doctor_id'];
$src = trim((string) ($stat['channel_source'] ?? ''));
$status = $stat['status'];
$cnt = (int) ($stat['channel_count'] ?? 0);
if ($src === '' || $cnt < 1) {
continue;
}
// 组装渠道统计数据
if (!isset($channelBuckets[$did])) {
$channelBuckets[$did] = [];
}
if (!isset($channelBuckets[$did][$src])) {
$channelBuckets[$did][$src] = 0;
}
$channelBuckets[$did][$src] += $cnt;
// 组装渠道状态数据
if (!isset($channelStatusBuckets[$did])) {
$channelStatusBuckets[$did] = [];
}
if (!isset($channelStatusBuckets[$did][$src])) {
$channelStatusBuckets[$did][$src] = [];
}
$channelStatusBuckets[$did][$src][$status] = $cnt;
}
} catch (\Throwable) {
// 无 channel_source 字段等
}
$mergeLegacyChannels = static function (array &$buckets, array &$statusBuckets, array $rows): void {
foreach ($rows as $stat) {
$did = (int) $stat['doctor_id'];
$key = (string) (int) ($stat['channels'] ?? 0);
$status = $stat['status'];
$cnt = (int) ($stat['channel_count'] ?? 0);
if ($key === '0' || $cnt < 1) {
continue;
}
// 组装渠道统计数据
if (!isset($buckets[$did])) {
$buckets[$did] = [];
}
if (!isset($buckets[$did][$key])) {
$buckets[$did][$key] = 0;
}
$buckets[$did][$key] += $cnt;
// 组装渠道状态数据
if (!isset($statusBuckets[$did])) {
$statusBuckets[$did] = [];
}
if (!isset($statusBuckets[$did][$key])) {
$statusBuckets[$did][$key] = [];
}
$statusBuckets[$did][$key][$status] = $cnt;
}
};
try {
$legacyStats = \think\facade\Db::name('doctor_appointment')
->field('doctor_id, channels, status, COUNT(*) as channel_count')
->whereIn('doctor_id', $doctorIdsWithAppointments)
->where('appointment_date', '>=', $startDate)
->where('appointment_date', '<=', $endDate)
->where('channels', '>', 0)
->where(function ($q) {
$q->whereNull('channel_source')->whereOr('channel_source', '=', '');
})
->group('doctor_id, channels, status')
->select()
->toArray();
$mergeLegacyChannels($channelBuckets, $channelStatusBuckets, $legacyStats);
} catch (\Throwable) {
try {
$legacyStats = \think\facade\Db::name('doctor_appointment')
->field('doctor_id, channels, status, COUNT(*) as channel_count')
->whereIn('doctor_id', $doctorIdsWithAppointments)
->where('appointment_date', '>=', $startDate)
->where('appointment_date', '<=', $endDate)
->where('channels', '>', 0)
->group('doctor_id, channels, status')
->select()
->toArray();
$mergeLegacyChannels($channelBuckets, $channelStatusBuckets, $legacyStats);
} catch (\Throwable) {
// 无 channels 字段
}
}
foreach ($channelBuckets as $did => $byKey) {
$parts = [];
foreach ($byKey as $key => $cnt) {
$label = $channelDict[$key] ?? $channelDict[(string) $key] ?? $key;
$parts[] = $label . '(' . $cnt . ')';
}
$channelStatsMap[$did] = $parts;
}
// 组装渠道状态明细数据
foreach ($channelStatusBuckets as $did => $byKey) {
foreach ($byKey as $key => $statuses) {
$label = $channelDict[$key] ?? $channelDict[(string) $key] ?? $key;
if (!isset($channelStatusMap[$did])) {
$channelStatusMap[$did] = [];
}
$channelStatusMap[$did][] = [
'channel_name' => $label,
'statuses' => $statuses
];
}
}
}
// 组装结果
$result = [];
foreach ($doctors as $doctor) {
$stat = $statsMap[$doctor['id']] ?? [
'total_count' => 0,
'registered_count' => 0,
'completed_count' => 0,
'missed_count' => 0,
'cancelled_count' => 0
];
$did = (int) $doctor['id'];
$diagnosisCount = $diagnosisCountMap[$did] ?? 0;
$dealCount = $dealCountMap[$did] ?? 0;
$dealRate = $diagnosisCount > 0
? round(($dealCount / $diagnosisCount) * 100, 2)
: 0;
// 计算完成率
$completionRate = $stat['total_count'] > 0
? round(($stat['completed_count'] / $stat['total_count']) * 100, 2)
: 0;
// 格式化部门状态明细
$deptStatusDetails = [];
if (isset($deptStatusMap[$doctor['id']])) {
foreach ($deptStatusMap[$doctor['id']] as $deptId => $deptInfo) {
$deptStatusDetails[] = [
'dept_id' => $deptId,
'dept_name' => $deptInfo['dept_name'],
'statuses' => $deptInfo['statuses']
];
}
}
// 格式化渠道状态明细
$channelStatusDetails = [];
if (isset($channelStatusMap[$doctor['id']])) {
$channelStatusDetails = $channelStatusMap[$doctor['id']];
}
$result[] = [
'doctor_id' => $doctor['id'],
'doctor_name' => $doctor['name'],
'total_count' => (int)$stat['total_count'] ?? 0,
'registered_count' => (int)$stat['registered_count'] ?? 0,
'completed_count' => (int)$stat['completed_count'] ?? 0,
'missed_count' => (int)$stat['missed_count'] ?? 0,
'cancelled_count' => (int)$stat['cancelled_count'] ?? 0,
'diagnosis_count' => $diagnosisCount ?? 0,
'deal_count' => $dealCount ?? 0,
'deal_rate' => $dealRate ?? 0,
'completion_rate' => $completionRate ?? 0,
'dept_status_details' => $deptStatusDetails,
'channel_status_details' => $channelStatusDetails,
'time_range' => $timeRangeText
];
}
return $result;
}
/**
* @notes 获取部门统计数据
* @return array
*/
private function getDeptStatistics()
{
$deptId = $this->params['dept_id'] ?? '';
$timeType = $this->params['time_type'] ?? 'today';
$startDate = $this->params['start_date'] ?? '';
$endDate = $this->params['end_date'] ?? '';
// 计算时间范围
list($startDate, $endDate, $timeRangeText) = $this->getTimeRange($timeType, $startDate, $endDate);
// 查询部门统计数据
$deptStatsQuery = \think\facade\Db::name('doctor_appointment')
->alias('apt')
->leftJoin('zyt_admin_dept ad', 'apt.assistant_id = ad.admin_id')
->leftJoin('zyt_dept dept', 'ad.dept_id = dept.id')
->field([
'dept.id as dept_id',
'dept.name as dept_name',
'COUNT(*) as total_count',
'SUM(CASE WHEN apt.status = 1 THEN 1 ELSE 0 END) as registered_count',
'SUM(CASE WHEN apt.status = 3 THEN 1 ELSE 0 END) as completed_count',
'SUM(CASE WHEN apt.status = 2 THEN 1 ELSE 0 END) as canceled_count',
'SUM(CASE WHEN apt.status = 4 THEN 1 ELSE 0 END) as expired_count'
])
->where('apt.appointment_date', '>=', $startDate)
->where('apt.appointment_date', '<=', $endDate)
->whereNotNull('dept.id');
if ($deptId) {
$deptStatsQuery->where('dept.id', $deptId);
}
$deptStats = $deptStatsQuery->group('dept.id')->select()->toArray();
// 组装结果
$result = [];
foreach ($deptStats as $stat) {
// 计算完成率
$completionRate = $stat['total_count'] > 0
? round(($stat['completed_count'] / $stat['total_count']) * 100, 2)
: 0;
$result[] = [
'dept_id' => $stat['dept_id'],
'dept_name' => $stat['dept_name'],
'total_count' => (int)$stat['total_count'] ?? 0,
'registered_count' => (int)$stat['registered_count'] ?? 0,
'completed_count' => (int)$stat['completed_count'] ?? 0,
'canceled_count' => (int)$stat['canceled_count'] ?? 0,
'expired_count' => (int)$stat['expired_count'] ?? 0,
'completion_rate' => $completionRate,
'time_range' => $timeRangeText
];
}
return $result;
}
/**
* @notes 获取时间范围
* @param string $timeType
* @param string $customStartDate
* @param string $customEndDate
* @return array
*/
private function getTimeRange($timeType, $customStartDate, $customEndDate)
{
$today = date('Y-m-d');
switch ($timeType) {
case 'today':
$startDate = $today;
$endDate = $today;
$timeRangeText = '今天 (' . $today . ')';
break;
case 'week':
$startDate = date('Y-m-d', strtotime('-6 days'));
$endDate = $today;
$timeRangeText = '最近7天 (' . $startDate . ' 至 ' . $endDate . ')';
break;
case 'month':
$startDate = date('Y-m-d', strtotime('-29 days'));
$endDate = $today;
$timeRangeText = '最近30天 (' . $startDate . ' 至 ' . $endDate . ')';
break;
case 'custom':
if ($customStartDate && $customEndDate) {
$startDate = $customStartDate;
$endDate = $customEndDate;
$timeRangeText = '自定义 (' . $startDate . ' 至 ' . $endDate . ')';
} else {
$startDate = $today;
$endDate = $today;
$timeRangeText = '今天 (' . $today . ')';
}
break;
default:
$startDate = $today;
$endDate = $today;
$timeRangeText = '今天 (' . $today . ')';
}
return [$startDate, $endDate, $timeRangeText];
}
/**
* @notes 获取数量
* @return int
*/
public function count(): int
{
return count($this->lists());
}
}