新增功能

This commit is contained in:
Your Name
2026-04-01 09:46:25 +08:00
parent 099bc1dd22
commit a780356908
332 changed files with 7845 additions and 866 deletions
+2 -1
View File
@@ -3,6 +3,7 @@ declare (strict_types = 1);
namespace app;
use app\common\service\TrtcCloudRecordingService;
use think\Service;
/**
@@ -17,6 +18,6 @@ class AppService extends Service
public function boot()
{
// 服务启动
TrtcCloudRecordingService::applyRecordingSslCaBundleEarly();
}
}
@@ -197,7 +197,19 @@ class DiagnosisController extends BaseAdminController
}
return $this->fail(DiagnosisLogic::getError());
}
/**
* @notes 指派医助操作记录
* @return \think\response\Json
*/
public function assignLogList()
{
$params = (new DiagnosisValidate())->goCheck('id');
$result = DiagnosisLogic::assignLogList((int) $params['id']);
return $this->data($result);
}
/**
* @notes 获取通话签名
* @return \think\response\Json
@@ -316,10 +328,11 @@ class DiagnosisController extends BaseAdminController
$params['admin_id'] = (int)$this->adminId;
$result = DiagnosisLogic::bindCallRoom($params);
if ($result) {
return $this->success('', [], 1, 1);
if ($result === false) {
return $this->fail(DiagnosisLogic::getError());
}
return $this->fail(DiagnosisLogic::getError());
return $this->success('', is_array($result) ? $result : [], 1, 0);
}
/**
@@ -67,13 +67,46 @@ class PrescriptionController extends BaseAdminController
public function detail()
{
$params = (new PrescriptionValidate())->get()->goCheck('detail');
$detail = PrescriptionLogic::detail((int)$params['id']);
$detail = PrescriptionLogic::detail((int) $params['id'], (int) $this->adminId, $this->adminInfo);
if (!$detail) {
return $this->fail('处方不存在');
$msg = PrescriptionLogic::getError();
return $this->fail($msg !== '' ? $msg : '处方不存在');
}
return $this->data($detail);
}
/**
* @notes 审核处方(通过 / 驳回,驳回即作废)
*/
public function audit()
{
$params = (new PrescriptionValidate())->post()->goCheck('audit');
$ok = PrescriptionLogic::audit(
(int) $params['id'],
(string) $params['action'],
(string) ($params['remark'] ?? ''),
(int) $this->adminId,
$this->adminInfo
);
if (!$ok) {
return $this->fail(PrescriptionLogic::getError());
}
$msg = $params['action'] === 'reject' ? '已驳回并作废处方' : '审核通过';
$wecom = PrescriptionLogic::consumeLastAuditWecomNotify();
$data = [];
if (is_array($wecom)) {
$data['wecom_notify_ok'] = !empty($wecom['ok']);
if (empty($wecom['ok']) && !empty($wecom['message'])) {
$data['wecom_notify_hint'] = (string) $wecom['message'];
}
}
return $this->success($msg, $data);
}
/**
* @notes 根据诊单获取处方列表
*/
@@ -59,12 +59,18 @@ class AppointmentLists extends BaseAdminDataLists implements ListsSearchInterfac
$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']];
}
// 构建查询
$query = Appointment::alias('a')
->with('diagnosis')
->leftJoin('tcm_diagnosis u', 'a.patient_id = u.id')
->leftJoin('admin ad', 'a.doctor_id = ad.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, ad.name as doctor_name, u.id as diagnosis_id')
->leftJoin('admin asst', 'a.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, ad.name as doctor_name, asst.name as assistant_name, u.id as diagnosis_id')
->where($this->searchWhere);
// 是否确认诊单:1=已确认 0=未确认
@@ -88,6 +94,9 @@ class AppointmentLists extends BaseAdminDataLists implements ListsSearchInterfac
if (in_array(2, $roleIds)) {
$query->where('u.assistant_id', $this->adminId);
}
// 诊单软删除后不再展示对应挂号(leftJoin 时无诊单或诊单未删)
$query->whereRaw('(u.id IS NULL OR u.delete_time IS NULL)');
$lists = $query
->order('a.status', 'asc')
@@ -116,6 +125,23 @@ class AppointmentLists extends BaseAdminDataLists implements ListsSearchInterfac
->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')
->order('id', 'desc')
->field(['id', 'appointment_id', 'audit_status', 'void_status'])
->select()
->toArray();
foreach ($rxRows as $rx) {
$aid = (int) ($rx['appointment_id'] ?? 0);
if ($aid > 0 && !isset($rxByAppointmentId[$aid])) {
$rxByAppointmentId[$aid] = $rx;
}
}
}
foreach ($lists as &$item) {
$statusMap = [
1 => '已预约',
@@ -135,6 +161,11 @@ class AppointmentLists extends BaseAdminDataLists implements ListsSearchInterfac
$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;
// 格式化时间戳为日期时间
if (isset($item['create_time']) && is_numeric($item['create_time'])) {
$item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
@@ -173,6 +204,10 @@ class AppointmentLists extends BaseAdminDataLists implements ListsSearchInterfac
$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 (isset($this->params['diagnosis_confirmed']) && $this->params['diagnosis_confirmed'] !== '') {
$confirmed = (int)$this->params['diagnosis_confirmed'];
$tbl = (new DiagnosisViewRecord())->getTable();
@@ -190,6 +225,8 @@ class AppointmentLists extends BaseAdminDataLists implements ListsSearchInterfac
if (in_array(2, $roleIds)) {
$query->where('u.assistant_id', $this->adminId);
}
$query->whereRaw('(u.id IS NULL OR u.delete_time IS NULL)');
}
/**
@@ -69,6 +69,39 @@ class StatisticsLists extends BaseAdminDataLists
$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) {
@@ -104,30 +137,99 @@ class StatisticsLists extends BaseAdminDataLists
$deptStatsMap[$stat['doctor_id']][] = $stat['dept_name'] . '(' . $stat['dept_count'] . ')';
}
// 获取渠道字典数据
// 获取渠道字典dict_data.value => name),与挂号创建时 channel_source 存字典 value 一致
$channelDict = \think\facade\Db::name('dict_data')
->where('type_value', 'channels')
->column('name', 'value');
// 获取渠道统计信息(channels字段,按渠道分组统计数量)
$channelStats = \think\facade\Db::name('doctor_appointment')
->field('doctor_id, channels, COUNT(*) as channel_count')
->whereIn('doctor_id', $doctorIdsWithAppointments)
->where('appointment_date', '>=', $startDate)
->where('appointment_date', '<=', $endDate)
->whereNotNull('channels')
->where('channels', '<>', '')
->group('doctor_id, channels')
->select()
->toArray();
// 组装渠道统计数据:医生ID => "渠道名称1(数量1) 渠道名称2(数量2)"
foreach ($channelStats as $stat) {
if (!isset($channelStatsMap[$stat['doctor_id']])) {
$channelStatsMap[$stat['doctor_id']] = [];
// 渠道:业务保存的是 channel_source(字典 value 字符串,见 AppointmentLogic::create);旧库可能仅有 channels(tinyint)
$channelBuckets = [];
try {
$channelStats = \think\facade\Db::name('doctor_appointment')
->field('doctor_id, channel_source, COUNT(*) as channel_count')
->whereIn('doctor_id', $doctorIdsWithAppointments)
->where('appointment_date', '>=', $startDate)
->where('appointment_date', '<=', $endDate)
->where('channel_source', '<>', '')
->group('doctor_id, channel_source')
->select()
->toArray();
foreach ($channelStats as $stat) {
$did = (int) $stat['doctor_id'];
$src = trim((string) ($stat['channel_source'] ?? ''));
$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;
}
$channelName = $channelDict[$stat['channels']] ?? $stat['channels'];
$channelStatsMap[$stat['doctor_id']][] = $channelName . '(' . $stat['channel_count'] . ')';
} catch (\Throwable) {
// 无 channel_source 字段等
}
$mergeLegacyChannels = static function (array &$buckets, array $rows): void {
foreach ($rows as $stat) {
$did = (int) $stat['doctor_id'];
$key = (string) (int) ($stat['channels'] ?? 0);
$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;
}
};
try {
$legacyStats = \think\facade\Db::name('doctor_appointment')
->field('doctor_id, channels, 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')
->select()
->toArray();
$mergeLegacyChannels($channelBuckets, $legacyStats);
} catch (\Throwable) {
try {
$legacyStats = \think\facade\Db::name('doctor_appointment')
->field('doctor_id, channels, COUNT(*) as channel_count')
->whereIn('doctor_id', $doctorIdsWithAppointments)
->where('appointment_date', '>=', $startDate)
->where('appointment_date', '<=', $endDate)
->where('channels', '>', 0)
->group('doctor_id, channels')
->select()
->toArray();
$mergeLegacyChannels($channelBuckets, $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;
}
}
@@ -142,6 +244,13 @@ class StatisticsLists extends BaseAdminDataLists
'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)
@@ -155,6 +264,9 @@ class StatisticsLists extends BaseAdminDataLists
'completed_count' => (int)$stat['completed_count'],
'missed_count' => (int)$stat['missed_count'],
'cancelled_count' => (int)$stat['cancelled_count'],
'diagnosis_count' => $diagnosisCount,
'deal_count' => $dealCount,
'deal_rate' => $dealRate,
'completion_rate' => $completionRate,
'dept_stats' => isset($deptStatsMap[$doctor['id']]) ? implode(' ', $deptStatsMap[$doctor['id']]) : '未分配',
'channel_stats' => isset($channelStatsMap[$doctor['id']]) ? implode(' ', $channelStatsMap[$doctor['id']]) : '未设置',
@@ -81,6 +81,7 @@ class OrderLists extends BaseAdminDataLists implements ListsSearchInterface
if (!empty($this->params['patient_keyword'])) {
$where[] = ['patient_id', 'in', function ($query) {
$query->table('zyt_tcm_diagnosis')
->whereNull('delete_time')
->where('patient_name|patient_phone', 'like', '%' . $this->params['patient_keyword'] . '%')
->field('id');
}];
@@ -126,6 +127,7 @@ class OrderLists extends BaseAdminDataLists implements ListsSearchInterface
if (!empty($this->params['patient_keyword'])) {
$where[] = ['patient_id', 'in', function ($query) {
$query->table('zyt_tcm_diagnosis')
->whereNull('delete_time')
->where('patient_name|patient_phone', 'like', '%' . $this->params['patient_keyword'] . '%')
->field('id');
}];
@@ -77,47 +77,63 @@ class DiagnosisLists extends BaseAdminDataLists implements ListsSearchInterface
}
}
// 挂号日期筛选:当天/明天/后天
// 挂号日期筛选:当天/明天/后天(1=已预约 3=已完成 4=已过号,需展示以便取消等操作)
if (!empty($this->params['appointment_date'])) {
$aptDate = addslashes($this->params['appointment_date']);
$aptTbl = (new Appointment())->getTable();
$diagTbl = (new Diagnosis())->getTable();
$query->whereExists("SELECT 1 FROM {$aptTbl} apt WHERE apt.patient_id = {$diagTbl}.patient_id AND apt.appointment_date = '{$aptDate}' AND apt.status IN (1,3)");
$query->whereExists("SELECT 1 FROM {$aptTbl} apt WHERE apt.patient_id = {$diagTbl}.id AND apt.appointment_date = '{$aptDate}' AND apt.status IN (1,3,4)");
}
// 挂号状态:1=已挂号 0=未挂号
// 挂号状态:1=已挂号(含已预约/已完成/已过号)0=未挂号
if (isset($this->params['has_appointment']) && $this->params['has_appointment'] !== '') {
$aptTbl = (new Appointment())->getTable();
$diagTbl = (new Diagnosis())->getTable();
if ((int)$this->params['has_appointment'] === 1) {
$query->whereExists("SELECT 1 FROM {$aptTbl} apt WHERE apt.patient_id = {$diagTbl}.patient_id AND apt.status IN (1,3)");
$query->whereExists("SELECT 1 FROM {$aptTbl} apt WHERE apt.patient_id = {$diagTbl}.id AND apt.status IN (1,3,4)");
} else {
$query->whereNotExists("SELECT 1 FROM {$aptTbl} apt WHERE apt.patient_id = {$diagTbl}.patient_id AND apt.status IN (1,3)");
$query->whereNotExists("SELECT 1 FROM {$aptTbl} apt WHERE apt.patient_id = {$diagTbl}.id AND apt.status IN (1,3,4)");
}
}
// 按挂号日期+时间升序。若传了 appointment_date(当天/明天等筛选),只按「该日」的挂号排序与展示,避免仍按历史最早一天把昨天号顶到最前
$diagTbl = (new Diagnosis())->getTable();
$aptTbl = (new Appointment())->getTable();
$minAptDateCond = '';
if (!empty($this->params['appointment_date'])) {
$sortAptDate = addslashes((string) $this->params['appointment_date']);
$minAptDateCond = " AND apt.appointment_date = '{$sortAptDate}'";
}
$minAptExpr = '(SELECT MIN(CONCAT(apt.appointment_date, \' \', IFNULL(NULLIF(TRIM(apt.appointment_time), \'\'), \'00:00:00\'))) FROM ' . $aptTbl . ' apt WHERE apt.patient_id = ' . $diagTbl . '.id AND apt.status IN (1,3,4)' . $minAptDateCond . ')';
$lists = $query
->with(['DiagnosisViewRecord'])
->field(['id', 'patient_id', 'patient_name', 'id_card', 'phone', 'gender', 'age', 'diagnosis_date', 'diagnosis_type', 'syndrome_type', 'assistant_id', 'status', 'create_time', 'update_time'])
->append(['gender_desc', 'status_desc', 'diagnosis_date_text'])
->order(['id' => 'desc'])
->orderRaw('IFNULL(' . $minAptExpr . ", '9999-12-31 23:59:59') ASC, {$diagTbl}.id DESC")
->limit($this->limitOffset, $this->limitLength)
->select()
->toArray();
// 关联挂号信息:获取患者最新有效挂号(已预约或已完成
$patientIds = array_filter(array_unique(array_column($lists, 'patient_id')));
if (!empty($patientIds)) {
// 关联挂号doctor_appointment.patient_id 存诊单主键 id(与 Appointment 列表 join 一致
$diagnosisIds = array_filter(array_unique(array_column($lists, 'id')));
if (!empty($diagnosisIds)) {
$appointmentMap = [];
$subQuery = Appointment::where('patient_id', 'in', $patientIds)
->where('status', 'in', [1, 3]) // 1=已预约 3=已完成
->field('id, patient_id, doctor_id, appointment_date, appointment_time, create_time')
->order('id', 'desc');
$subQuery = Appointment::where('patient_id', 'in', $diagnosisIds)
->where('status', 'in', [1, 3, 4]); // 1=已预约 3=已完成 4=已过号
if (!empty($this->params['appointment_date'])) {
$subQuery->where('appointment_date', (string) $this->params['appointment_date']);
}
$subQuery
->field('id, patient_id, doctor_id, appointment_date, appointment_time, status, create_time')
->order('appointment_date', 'asc')
->order('appointment_time', 'asc')
->order('id', 'asc');
$appointments = $subQuery->select()->toArray();
foreach ($appointments as $apt) {
$pid = $apt['patient_id'];
if (!isset($appointmentMap[$pid])) {
$appointmentMap[$pid] = $apt;
$did = $apt['patient_id'];
if (!isset($appointmentMap[$did])) {
$appointmentMap[$did] = $apt;
}
}
// 获取医生名称
@@ -129,10 +145,11 @@ class DiagnosisLists extends BaseAdminDataLists implements ListsSearchInterface
}
// 合并到诊单列表
foreach ($lists as &$item) {
$apt = $appointmentMap[$item['patient_id']] ?? null;
$apt = $appointmentMap[$item['id']] ?? null;
if ($apt) {
$item['has_appointment'] = 1;
$item['appointment_id'] = $apt['id'];
$item['appointment_status'] = (int) ($apt['status'] ?? 0);
$item['appointment_doctor_id'] = $apt['doctor_id'];
$item['appointment_doctor_name'] = $doctorNames[$apt['doctor_id']] ?? '-';
$timePart = $apt['appointment_time'] ?? '';
@@ -143,6 +160,7 @@ class DiagnosisLists extends BaseAdminDataLists implements ListsSearchInterface
} else {
$item['has_appointment'] = 0;
$item['appointment_id'] = null;
$item['appointment_status'] = 0;
$item['appointment_doctor_id'] = null;
$item['appointment_doctor_name'] = '';
$item['appointment_time_text'] = '';
@@ -152,6 +170,7 @@ class DiagnosisLists extends BaseAdminDataLists implements ListsSearchInterface
foreach ($lists as &$item) {
$item['has_appointment'] = 0;
$item['appointment_id'] = null;
$item['appointment_status'] = 0;
$item['appointment_doctor_id'] = null;
$item['appointment_doctor_name'] = '';
$item['appointment_time_text'] = '';
@@ -277,7 +296,7 @@ class DiagnosisLists extends BaseAdminDataLists implements ListsSearchInterface
$aptDate = addslashes($this->params['appointment_date']);
$aptTbl = (new Appointment())->getTable();
$diagTbl = (new Diagnosis())->getTable();
$query->whereExists("SELECT 1 FROM {$aptTbl} apt WHERE apt.patient_id = {$diagTbl}.patient_id AND apt.appointment_date = '{$aptDate}' AND apt.status IN (1,3)");
$query->whereExists("SELECT 1 FROM {$aptTbl} apt WHERE apt.patient_id = {$diagTbl}.id AND apt.appointment_date = '{$aptDate}' AND apt.status IN (1,3,4)");
}
// 挂号状态
@@ -285,9 +304,9 @@ class DiagnosisLists extends BaseAdminDataLists implements ListsSearchInterface
$aptTbl = (new Appointment())->getTable();
$diagTbl = (new Diagnosis())->getTable();
if ((int)$this->params['has_appointment'] === 1) {
$query->whereExists("SELECT 1 FROM {$aptTbl} apt WHERE apt.patient_id = {$diagTbl}.patient_id AND apt.status IN (1,3)");
$query->whereExists("SELECT 1 FROM {$aptTbl} apt WHERE apt.patient_id = {$diagTbl}.id AND apt.status IN (1,3,4)");
} else {
$query->whereNotExists("SELECT 1 FROM {$aptTbl} apt WHERE apt.patient_id = {$diagTbl}.patient_id AND apt.status IN (1,3)");
$query->whereNotExists("SELECT 1 FROM {$aptTbl} apt WHERE apt.patient_id = {$diagTbl}.id AND apt.status IN (1,3,4)");
}
}
@@ -6,6 +6,7 @@ namespace app\adminapi\lists\tcm;
use app\adminapi\lists\BaseAdminDataLists;
use app\common\lists\ListsSearchInterface;
use app\adminapi\logic\tcm\PrescriptionLogic;
use app\common\model\tcm\Prescription;
/**
@@ -19,24 +20,86 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
public function setSearch(): array
{
return [
'=' => ['is_shared'],
'%like%' => ['prescription_name', 'patient_name', 'sn']
'%like%' => ['patient_name', 'sn'],
'between_time' => 'create_time',
];
}
/** 创建人(医师账号)多选,参数 creator_ids:数组或逗号分隔 ID */
private function applyCreatorIdsFilter($query): void
{
$raw = $this->params['creator_ids'] ?? null;
if ($raw === null || $raw === '') {
return;
}
$ids = \is_array($raw) ? $raw : explode(',', (string) $raw);
$ids = array_values(array_filter(array_map('intval', $ids), static function (int $id): bool {
return $id > 0;
}));
if ($ids === []) {
return;
}
$query->whereIn('creator_id', $ids);
}
/**
* audit_filterpassed=已通过,not_passed=未通过(待审+驳回),pendingrejected
*/
private function applyAuditFilter($query): void
{
$af = (string) ($this->params['audit_filter'] ?? '');
if ($af === '' || $af === 'all') {
return;
}
switch ($af) {
case 'passed':
$query->where('audit_status', '=', 1);
break;
case 'not_passed':
$query->whereIn('audit_status', [0, 2]);
break;
case 'pending':
$query->where('audit_status', '=', 0);
break;
case 'rejected':
$query->where('audit_status', '=', 2);
break;
default:
break;
}
}
private function applyVisibilityScope($query): void
{
$query->where(function ($query) {
if (!empty($this->adminInfo['root']) && (int) $this->adminInfo['root'] === 1) {
return;
}
$adminId = $this->adminId;
$roleIds = array_values(array_unique(array_map('intval', $this->adminInfo['role_id'] ?? [])));
$query->where(function ($q) use ($adminId, $roleIds) {
$q->whereOr('is_shared', '=', 1);
$q->whereOr('creator_id', '=', $adminId);
foreach ($roleIds as $rid) {
if ($rid > 0) {
$q->whereOrRaw('FIND_IN_SET(?, `visible_role_ids`)', [(string) $rid]);
}
}
});
});
}
/**
* @notes 获取列表
*/
public function lists(): array
{
$lists = Prescription::where($this->searchWhere)
->where(function ($query) {
// 如果不是共享的,只能看到自己创建的
$query->whereOr([
['is_shared', '=', 1],
['creator_id', '=', $this->adminId]
]);
})
$query = Prescription::where($this->searchWhere);
$this->applyAuditFilter($query);
$this->applyVisibilityScope($query);
$this->applyCreatorIdsFilter($query);
$lists = $query
->whereNull('delete_time')
->order('id', 'desc')
->limit($this->limitOffset, $this->limitLength)
@@ -51,7 +114,10 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
$item['usage_notes'] = $item['usage_notes'] ?? '';
$item['usage_days'] = $item['usage_days'] ?? 7;
$item['is_shared'] = $item['is_shared'] ?? 0;
$item['audit_status'] = (int) ($item['audit_status'] ?? 1);
$item['void_status'] = (int) ($item['void_status'] ?? 0);
$item['visible_role_ids'] = PrescriptionLogic::visibleRoleIdsToArray((string) ($item['visible_role_ids'] ?? ''));
// 将 dietary_taboo 从逗号分隔的字符串转换为数组(前端需要数组格式)
if (!empty($item['dietary_taboo']) && is_string($item['dietary_taboo'])) {
$item['dietary_taboo'] = array_filter(explode(',', $item['dietary_taboo']));
@@ -68,15 +134,11 @@ class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterfa
*/
public function count(): int
{
return Prescription::where($this->searchWhere)
->where(function ($query) {
// 如果不是共享的,只能看到自己创建的
$query->whereOr([
['is_shared', '=', 1],
['creator_id', '=', $this->adminId]
]);
})
->whereNull('delete_time')
->count();
$query = Prescription::where($this->searchWhere);
$this->applyAuditFilter($query);
$this->applyVisibilityScope($query);
$this->applyCreatorIdsFilter($query);
return $query->whereNull('delete_time')->count();
}
}
@@ -186,6 +186,25 @@ class AppointmentLogic extends BaseLogic
try {
Db::startTrans();
// 同一诊单患者在「所选预约日」仅允许一条「已预约」或「已过号」记录(与 appointment_date 一致,不能误用服务器当天拦其它日期)
$apptDate = trim((string) ($params['appointment_date'] ?? ''));
if ($apptDate === '') {
self::setError('预约日期不能为空');
Db::rollback();
return false;
}
$patientSameDay = Appointment::where('patient_id', (int) $params['patient_id'])
->where('appointment_date', $apptDate)
->whereIn('status', [1, 4])
->find();
if ($patientSameDay) {
self::setError('该患者在所选日期已有挂号(已预约或已过号),无法重复预约');
Db::rollback();
return false;
}
// 1. 检查时间段是否已被预约(每个时间段只能预约1次)
// 统一时间格式为 HH:MM:SS
$appointmentTime = strlen($params['appointment_time']) == 5
@@ -214,7 +233,7 @@ class AppointmentLogic extends BaseLogic
'appointment_time' => $appointmentTime,
'appointment_type' => $params['appointment_type'] ?? 'video',
'remark' => $params['remark'] ?? '',
'channel_source' => $params['channel_source'] ?? '',
'channels' => $params['channel_source'] ?? '',
'status' => 1,
'create_time' => time(),
'update_time' => time(),
@@ -245,6 +264,19 @@ class AppointmentLogic extends BaseLogic
return false;
}
$st = (int) $appointment->status;
if ($st === 2) {
return true;
}
if ($st === 3) {
self::setError('预约已完成,无法取消');
return false;
}
if ($st !== 1 && $st !== 4) {
self::setError('当前状态不可取消');
return false;
}
$appointment->status = 2; // 已取消
$appointment->update_time = time();
$appointment->save();
@@ -367,12 +399,13 @@ class AppointmentLogic extends BaseLogic
self::setError('预约记录不存在');
return false;
}
if ($appointment->status != 1) {
if ($appointment->status == 3) {
self::setError('该预约已处理,无法完成');
return false;
}
$appointment->status = 3; // 已完成
$appointment->update_time = time();
$appointment->save();
+332 -41
View File
@@ -16,6 +16,7 @@ namespace app\adminapi\logic\tcm;
use app\common\logic\BaseLogic;
use app\common\model\tcm\Diagnosis;
use app\common\model\tcm\DiagnosisAssignLog;
use app\common\model\tcm\ImChatMessage;
use app\common\model\DiagnosisViewRecord;
use think\facade\Db;
@@ -91,11 +92,11 @@ class DiagnosisLogic extends BaseLogic
if (isset($params['diagnosis_date'])) {
$params['diagnosis_date'] = strtotime($params['diagnosis_date']);
}
$model = Diagnosis::create($params);
// 自动为患者创建 TRTC 账号
self::createPatientTrtcAccount($model->patient_id);
self::createPatientTrtcAccount($model->id);
return $model->id;
} catch (\Exception $e) {
@@ -450,23 +451,102 @@ class DiagnosisLogic extends BaseLogic
}
/**
* @notes 指派医助
* @notes 指派医助(每次成功更新写入一条操作记录,批量指派为多次接口调用各记一条)
* @param array $params
* @return bool
*/
public static function assign(array $params): bool
{
try {
Diagnosis::where('id', $params['id'])->update([
'assistant_id' => $params['assistant_id']
$id = (int) ($params['id'] ?? 0);
$toAssistantId = (int) ($params['assistant_id'] ?? 0);
if ($id <= 0) {
self::setError('诊单不存在');
return false;
}
$diagnosis = Diagnosis::where('id', $id)->whereNull('delete_time')->find();
if (!$diagnosis) {
self::setError('诊单不存在');
return false;
}
$fromAssistantId = (int) ($diagnosis->getAttr('assistant_id') ?? 0);
Db::startTrans();
Diagnosis::where('id', $id)->whereNull('delete_time')->update([
'assistant_id' => $toAssistantId,
]);
$req = request();
$admin = $req->adminInfo ?? [];
DiagnosisAssignLog::create([
'diagnosis_id' => $id,
'from_assistant_id' => $fromAssistantId,
'to_assistant_id' => $toAssistantId,
'operator_admin_id' => (int) ($admin['admin_id'] ?? 0),
'operator_name' => (string) ($admin['name'] ?? ''),
'operator_account' => (string) ($admin['account'] ?? ''),
'ip' => (string) ($req->ip() ?? ''),
'create_time' => time(),
]);
Db::commit();
return true;
} catch (\Exception $e) {
Db::rollback();
self::setError($e->getMessage());
return false;
}
}
/**
* @notes 诊单指派医助操作记录列表
*/
public static function assignLogList(int $diagnosisId): array
{
$rows = DiagnosisAssignLog::where('diagnosis_id', $diagnosisId)
->order('id', 'desc')
->select()
->toArray();
$adminIds = [];
foreach ($rows as $r) {
if (!empty($r['from_assistant_id'])) {
$adminIds[] = (int) $r['from_assistant_id'];
}
if (!empty($r['to_assistant_id'])) {
$adminIds[] = (int) $r['to_assistant_id'];
}
}
$adminIds = array_values(array_unique(array_filter($adminIds)));
$nameMap = [];
if ($adminIds !== []) {
$nameMap = \app\common\model\auth\Admin::whereIn('id', $adminIds)->column('name', 'id');
}
foreach ($rows as &$r) {
$fromId = (int) ($r['from_assistant_id'] ?? 0);
$toId = (int) ($r['to_assistant_id'] ?? 0);
$r['from_assistant_name'] = $fromId > 0
? (string) ($nameMap[$fromId] ?? ('ID:' . $fromId))
: '—';
$r['to_assistant_name'] = $toId > 0
? (string) ($nameMap[$toId] ?? ('ID:' . $toId))
: '—';
$r['create_time_text'] = !empty($r['create_time'])
? date('Y-m-d H:i:s', (int) $r['create_time'])
: '';
}
unset($r);
return $rows;
}
/**
* @notes 获取通话签名
* @param array $params
@@ -1152,47 +1232,195 @@ class DiagnosisLogic extends BaseLogic
{
try {
// 获取当前管理员ID(从参数中获取)
$adminId = $params['admin_id'] ?? 0;
if (!$adminId) {
$adminId = (int)($params['admin_id'] ?? 0);
$diagnosisId = (int)($params['diagnosis_id'] ?? 0);
if ($adminId <= 0) {
self::setError('获取管理员信息失败');
return false;
}
// 查找最近的通话记录
$record = \app\common\model\tcm\CallRecord::where('diagnosis_id', $params['diagnosis_id'])
if ($diagnosisId <= 0) {
self::setError('诊单ID无效');
return false;
}
// 优先匹配「当前医生 + 进行中」,与 startCloudRecording / bindCallRoom 一致
$record = \app\common\model\tcm\CallRecord::where('diagnosis_id', $diagnosisId)
->where('caller_id', $adminId)
->where('status', 1)
->order('id', 'desc')
->find();
if ($record) {
$taskId = trim((string)($record['cloud_recording_task_id'] ?? ''));
if ($taskId !== '') {
\app\common\service\TrtcCloudRecordingService::stopRecording(
\app\common\service\TrtcCloudRecordingService::trtcSdkAppId(),
$taskId
);
if (!$record) {
$record = \app\common\model\tcm\CallRecord::where('diagnosis_id', $diagnosisId)
->where('status', 1)
->order('id', 'desc')
->find();
if ($record) {
\think\facade\Log::warning('endCall: 未匹配 caller_id,已回退到该诊单最新进行中记录', [
'diagnosis_id' => $diagnosisId,
'admin_id' => $adminId,
'record_caller_id' => $record['caller_id'] ?? null,
'call_record_id' => $record['id'] ?? null,
]);
}
$endTime = time();
$duration = $endTime - $record->start_time;
$record->save([
'status' => 2, // 2-已结束
'end_time' => $endTime,
'duration' => $duration,
'cloud_recording_task_id' => '',
'update_time' => time(),
}
if (!$record) {
// 前端常重复回调 endCallafterCalling + Store idle),第一条已结束则不再告警
$latest = \app\common\model\tcm\CallRecord::where('diagnosis_id', $diagnosisId)
->order('id', 'desc')
->find();
$justEnded = $latest
&& (int)($latest['status'] ?? 0) === 2
&& (int)($latest['end_time'] ?? 0) > 0
&& (time() - (int)$latest['end_time']) < 120;
if (!$justEnded) {
\think\facade\Log::warning('endCall: 无进行中通话记录,未调用 DeleteCloudRecording', [
'diagnosis_id' => $diagnosisId,
'admin_id' => $adminId,
]);
}
return true;
}
$taskId = trim((string)($record['cloud_recording_task_id'] ?? ''));
if ($taskId !== '') {
$stopped = \app\common\service\TrtcCloudRecordingService::stopRecording(
\app\common\service\TrtcCloudRecordingService::trtcSdkAppId(),
$taskId
);
if (empty($stopped['ok'])) {
\think\facade\Log::warning('endCall: DeleteCloudRecording 失败', [
'message' => (string)($stopped['message'] ?? ''),
'task_id' => $taskId,
'call_record_id' => $record['id'] ?? null,
'room_id' => $record['room_id'] ?? '',
]);
}
} else {
\think\facade\Log::warning('endCall: cloud_recording_task_id 为空,未调用 DeleteCloudRecording;控制台「房间尚未结束」常见于录制机器人仍在房或未走 API 合流录制', [
'call_record_id' => $record['id'] ?? null,
'diagnosis_id' => $diagnosisId,
'room_id' => $record['room_id'] ?? '',
]);
}
$endTime = time();
$duration = $endTime - (int)$record->start_time;
// 保留 cloud_recording_task_idVOD 311 回调常在挂断之后到达,需按 TaskId 关联写入 recording_urls
$record->save([
'status' => 2, // 2-已结束
'end_time' => $endTime,
'duration' => $duration,
'update_time' => time(),
]);
return true;
} catch (\Exception $e) {
self::setError($e->getMessage());
return false;
}
}
/**
* @notes 患者端挂断:停止云端录制并结束该诊单下对应通话记录(不依赖管理端浏览器是否触发 endCall)
* @param array{diagnosis_id?:int,patient_id:int,room_id?:string} $params patient_id 须与诊单 tcm_diagnosis.patient_id 一致;room_id 与 bindCallRoom 一致时可精准命中(小程序通话页独立时 chat 页可能已卸载,仅靠 room_id + patient_id 即可)
*/
public static function patientHangupVideoCall(array $params): bool
{
try {
$diagnosisId = (int)($params['diagnosis_id'] ?? 0);
$patientId = (int)($params['patient_id'] ?? 0);
$roomIdRaw = trim((string)($params['room_id'] ?? ''));
if ($patientId <= 0) {
self::setError('参数错误');
return false;
}
if ($diagnosisId <= 0 && $roomIdRaw === '') {
self::setError('诊单ID或房间号须至少传一项');
return false;
}
$record = null;
if ($roomIdRaw !== '') {
$roomCandidates = array_values(array_unique(array_filter([
$roomIdRaw,
ctype_digit($roomIdRaw) ? (string)((int)$roomIdRaw) : '',
])));
$record = \app\common\model\tcm\CallRecord::where('status', 1)
->whereIn('room_id', $roomCandidates)
->order('id', 'desc')
->find();
if ($record) {
$diagByRoom = Diagnosis::find((int)$record['diagnosis_id']);
if (!$diagByRoom || (int)($diagByRoom['patient_id'] ?? 0) !== $patientId) {
$record = null;
} else {
$diagnosisId = (int)$record['diagnosis_id'];
}
}
}
if (!$record && $diagnosisId > 0) {
$diag = Diagnosis::find($diagnosisId);
if (!$diag || (int)($diag['patient_id'] ?? 0) !== $patientId) {
self::setError('无权操作该诊单');
return false;
}
$record = \app\common\model\tcm\CallRecord::where('diagnosis_id', $diagnosisId)
->where('callee_id', $patientId)
->where('status', 1)
->order('id', 'desc')
->find();
if (!$record) {
$cnt = (int)\app\common\model\tcm\CallRecord::where('diagnosis_id', $diagnosisId)->where('status', 1)->count();
if ($cnt === 1) {
$record = \app\common\model\tcm\CallRecord::where('diagnosis_id', $diagnosisId)
->where('status', 1)
->order('id', 'desc')
->find();
}
}
}
if (!$record) {
return true;
}
$taskId = trim((string)($record['cloud_recording_task_id'] ?? ''));
if ($taskId !== '') {
\app\common\service\TrtcCloudRecordingService::stopRecording(
\app\common\service\TrtcCloudRecordingService::trtcSdkAppId(),
$taskId
);
}
$endTime = time();
$duration = $endTime - (int)$record->start_time;
$record->save([
'status' => 2,
'end_time' => $endTime,
'duration' => $duration,
'update_time' => $endTime,
]);
\think\facade\Log::info('patientHangupVideoCall: 已停录并结束通话记录', [
'call_record_id' => $record->id,
'diagnosis_id' => $diagnosisId,
]);
return true;
} catch (\Exception $e) {
self::setError($e->getMessage());
\think\facade\Log::warning('patientHangupVideoCall: ' . $e->getMessage());
return false;
}
}
/**
* @notes 获取通话记录
* @param array $params
@@ -1229,9 +1457,10 @@ class DiagnosisLogic extends BaseLogic
}
/**
* @notes 将 TRTC 房间号写入当前诊单最近一次通话记录,便于云端录制回调按 room_id 关联
* @notes 将 TRTC 房间号写入当前诊单通话记录,并尝试 API 合流云端录制
* @return array{cloud_recording?:array}|false 成功返回 data 数组(供接口带给前端);失败 false
*/
public static function bindCallRoom(array $params): bool
public static function bindCallRoom(array $params)
{
try {
$diagnosisId = (int)($params['diagnosis_id'] ?? 0);
@@ -1241,10 +1470,23 @@ class DiagnosisLogic extends BaseLogic
return false;
}
$record = \app\common\model\tcm\CallRecord::where('diagnosis_id', $diagnosisId)
->where('status', 1)
->order('id', 'desc')
->find();
$adminId = (int)($params['admin_id'] ?? 0);
// 必须与 startCloudRecording 使用同一条「进行中 + 当前管理员」记录写 room_id,否则会写到别的记录上,合流 API 读到 room_id 仍为空 → 关闭全局录制后无任何文件
$record = null;
if ($adminId > 0) {
$record = \app\common\model\tcm\CallRecord::where('diagnosis_id', $diagnosisId)
->where('status', 1)
->where('caller_id', $adminId)
->order('id', 'desc')
->find();
}
if (!$record) {
$record = \app\common\model\tcm\CallRecord::where('diagnosis_id', $diagnosisId)
->where('status', 1)
->order('id', 'desc')
->find();
}
if (!$record) {
$record = \app\common\model\tcm\CallRecord::where('diagnosis_id', $diagnosisId)
->where('room_id', '')
@@ -1261,15 +1503,49 @@ class DiagnosisLogic extends BaseLogic
'update_time' => time(),
]);
$adminId = (int)($params['admin_id'] ?? 0);
$cloudPayload = [
'started' => false,
'task_id' => '',
'message' => '未尝试合流录制(admin_id 为空)',
];
if ($adminId > 0) {
self::startCloudRecording([
$cloudRec = self::startCloudRecording([
'diagnosis_id' => $diagnosisId,
'admin_id' => $adminId,
], true);
if ($cloudRec === false) {
\think\facade\Log::warning('bindCallRoom: startCloudRecording 未执行或异常', [
'diagnosis_id' => $diagnosisId,
'room_id' => $roomId,
]);
$cloudPayload = [
'started' => false,
'task_id' => '',
'message' => '合流录制未启动(无匹配通话记录或异常,见服务端日志)',
];
} elseif (is_array($cloudRec)) {
$cloudPayload = [
'started' => !empty($cloudRec['started']),
'task_id' => (string)($cloudRec['task_id'] ?? ''),
'message' => (string)($cloudRec['message'] ?? ''),
];
if (empty($cloudRec['started'])) {
\think\facade\Log::warning('bindCallRoom: CreateCloudRecording 合流未启动', [
'diagnosis_id' => $diagnosisId,
'room_id' => $roomId,
'message' => $cloudPayload['message'],
]);
} else {
\think\facade\Log::info('bindCallRoom: 合流云端录制已发起', [
'diagnosis_id' => $diagnosisId,
'room_id' => $roomId,
'task_id' => $cloudPayload['task_id'],
]);
}
}
}
return true;
return ['cloud_recording' => $cloudPayload];
} catch (\Exception $e) {
self::setError($e->getMessage());
return false;
@@ -1302,6 +1578,19 @@ class DiagnosisLogic extends BaseLogic
->where('status', 1)
->order('id', 'desc')
->find();
if (!$record) {
$record = \app\common\model\tcm\CallRecord::where('diagnosis_id', $diagnosisId)
->where('status', 1)
->order('id', 'desc')
->find();
if ($record) {
\think\facade\Log::warning('startCloudRecording: 未找到 caller_id 匹配的进行中记录,已回退到该诊单最新进行中记录', [
'diagnosis_id' => $diagnosisId,
'admin_id' => $adminId,
'record_caller_id' => $record['caller_id'] ?? null,
]);
}
}
if (!$record) {
if (!$silent) {
self::setError('没有进行中的通话记录');
@@ -1337,11 +1626,13 @@ class DiagnosisLogic extends BaseLogic
$botSig = \app\common\service\TrtcCloudRecordingService::makeBotUserSig($botUserId);
$sdkAppId = \app\common\service\TrtcCloudRecordingService::trtcSdkAppId();
$vodMixPrefix = 'mix_' . $diagnosisId . '_' . (int)$record['id'];
$r = \app\common\service\TrtcCloudRecordingService::startMixRecording(
$sdkAppId,
$roomId,
$botUserId,
$botSig
$botSig,
$vodMixPrefix
);
if (!$r['ok']) {
return [
@@ -4,13 +4,20 @@ declare(strict_types=1);
namespace app\adminapi\logic\tcm;
use app\common\model\auth\Admin;
use app\common\model\tcm\Prescription;
use app\common\model\tcm\Diagnosis;
use app\common\service\wechat\WechatWorkAppMessageService;
use think\facade\Config;
use think\facade\Log;
class PrescriptionLogic
{
private static $error = '';
/** @var array{ok: bool, message?: string, errcode?: int}|null 最近一次审核成功后的企微通知结果 */
private static ?array $lastAuditWecomNotify = null;
public static function setError(string $msg): void
{
self::$error = $msg;
@@ -21,11 +28,127 @@ class PrescriptionLogic
return self::$error;
}
/**
* 可见角色 ID 存库为逗号分隔字符串
*
* @param array|string $raw
*/
public static function normalizeVisibleRoleIds($raw): string
{
if (is_string($raw)) {
$parts = array_filter(array_map('intval', explode(',', $raw)));
} elseif (is_array($raw)) {
$parts = array_filter(array_map('intval', $raw));
} else {
$parts = [];
}
return implode(',', array_values(array_unique($parts)));
}
/**
* 当前管理员是否可审核处方(通过/驳回)
*/
public static function canAuditPrescription(int $adminId, array $adminInfo): bool
{
if (!empty($adminInfo['root']) && (int) $adminInfo['root'] === 1) {
return true;
}
$allow = Config::get('project.prescription_audit_roles', []);
if ($allow === [] || $allow === null) {
$allow = Config::get('project.prescription_library_manage_all_roles', [0, 3]);
}
$myRoles = array_map('intval', $adminInfo['role_id'] ?? []);
$allow = array_map('intval', $allow);
return count(array_intersect($myRoles, $allow)) > 0;
}
/**
* 是否可查看该处方(列表/详情)
*
* @param Prescription|array<string,mixed> $row
*/
public static function canViewPrescription($row, int $adminId, array $adminInfo): bool
{
if (!empty($adminInfo['root']) && (int) $adminInfo['root'] === 1) {
return true;
}
$creatorId = is_array($row) ? (int) ($row['creator_id'] ?? 0) : (int) $row->creator_id;
if ($creatorId === $adminId) {
return true;
}
$isShared = is_array($row) ? (int) ($row['is_shared'] ?? 0) : (int) $row->is_shared;
if ($isShared === 1) {
return true;
}
$vis = is_array($row) ? (string) ($row['visible_role_ids'] ?? '') : (string) ($row->visible_role_ids ?? '');
$allowed = array_filter(array_map('intval', explode(',', $vis)));
$myRoles = array_map('intval', $adminInfo['role_id'] ?? []);
return count(array_intersect($myRoles, $allowed)) > 0;
}
private static function generateSn(): string
{
return 'RX' . date('Ymd') . str_pad((string)mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
}
/**
* 处方日期统一为 Y-m-d(与库表 prescription_date 一致)
*
* @param mixed $raw
*/
private static function normalizePrescriptionDate($raw): string
{
if ($raw === null || $raw === '') {
return date('Y-m-d');
}
if (is_numeric($raw) && (float) $raw > 1e9) {
return date('Y-m-d', (int) $raw);
}
$s = (string) $raw;
if (preg_match('/^\d{4}-\d{2}-\d{2}/', $s)) {
return substr($s, 0, 10);
}
$ts = strtotime($s);
return $ts ? date('Y-m-d', $ts) : date('Y-m-d');
}
/**
* 同一诊单、同一开方人、同一处方日期:仅允许一张「未作废」的未删除记录;已作废的可再新开一张。
*
* @param int|null $excludeId 编辑时排除自身 id
*/
private static function assertUniquePrescriptionPerDiagnosisDay(int $diagnosisId, int $creatorId, string $prescriptionDateYmd, ?int $excludeId): bool
{
if ($diagnosisId <= 0 || $creatorId <= 0) {
return true;
}
$q = Prescription::where('diagnosis_id', $diagnosisId)
->where('creator_id', $creatorId)
->where('prescription_date', $prescriptionDateYmd)
->where('void_status', 0)
->whereNull('delete_time');
if ($excludeId !== null && $excludeId > 0) {
$q->where('id', '<>', $excludeId);
}
if ($q->count() > 0) {
self::setError('同一诊单同一天已存在未作废处方,请先作废后再新开');
return false;
}
return true;
}
/**
* 添加处方
*/
@@ -40,6 +163,12 @@ class PrescriptionLogic
}
}
$dateYmd = self::normalizePrescriptionDate($params['prescription_date'] ?? date('Y-m-d'));
$diagnosisIdRule = (int) ($params['diagnosis_id'] ?? 0);
if ($diagnosisIdRule > 0 && !self::assertUniquePrescriptionPerDiagnosisDay($diagnosisIdRule, $adminId, $dateYmd, null)) {
return null;
}
$herbs = $params['herbs'] ?? [];
if (empty($herbs) || !is_array($herbs)) {
self::setError('请添加中药');
@@ -70,7 +199,7 @@ class PrescriptionLogic
'age' => (int)($params['age'] ?? 0),
'phone' => $params['phone'] ?? '',
'visit_no' => $params['visit_no'] ?? $sn,
'prescription_date' => $params['prescription_date'] ?? date('Y-m-d'),
'prescription_date' => $dateYmd,
'pulse' => $params['pulse'] ?? '',
'pulse_condition' => $params['pulse_condition'] ?? '',
'tongue' => $params['tongue'] ?? '',
@@ -91,6 +220,13 @@ class PrescriptionLogic
'doctor_signature' => $params['doctor_signature'] ?? '',
'template_id' => (int)($params['template_id'] ?? 0),
'is_shared' => (int)($params['is_shared'] ?? 0),
'visible_role_ids' => self::normalizeVisibleRoleIds($params['visible_role_ids'] ?? []),
// 新开方一律待审核(忽略客户端传入的 audit_status,防止绕过审核)
'audit_status' => 0,
'audit_time' => null,
'audit_by' => null,
'audit_by_name' => '',
'audit_remark' => '',
'creator_id' => $adminId,
];
@@ -111,6 +247,32 @@ class PrescriptionLogic
return false;
}
// 已通过且未作废:不可编辑(与消费者端仅「查看」一致)
if ((int) ($prescription->audit_status ?? 1) === 1 && (int) ($prescription->void_status ?? 0) === 0) {
self::setError('该处方已通过审核,不可编辑');
return false;
}
// 已驳回:仅当该诊单+当天+同一创建人下没有另一条「已通过且未作废」的处方时允许重新编辑(改后待审核、作废一并清除)
if ((int) ($prescription->audit_status ?? 1) === 2) {
$rejDiagnosisId = (int) ($params['diagnosis_id'] ?? $prescription->diagnosis_id);
$rejDateYmd = self::normalizePrescriptionDate($params['prescription_date'] ?? $prescription->prescription_date);
if ($rejDiagnosisId > 0) {
$hasOtherApproved = Prescription::where('diagnosis_id', $rejDiagnosisId)
->where('creator_id', (int) $prescription->creator_id)
->where('prescription_date', $rejDateYmd)
->where('audit_status', 1)
->where('void_status', 0)
->whereNull('delete_time')
->where('id', '<>', (int) $params['id'])
->count() > 0;
if ($hasOtherApproved) {
self::setError('该诊单当天已有审核通过的处方,不可再编辑本条已驳回记录');
return false;
}
}
}
// 检查权限:只有创建者或共享的处方才能编辑
if ($prescription->creator_id != $adminId && $prescription->is_shared != 1) {
self::setError('无权限编辑此处方');
@@ -130,14 +292,23 @@ class PrescriptionLogic
}
}
$newDiagnosisId = (int) ($params['diagnosis_id'] ?? $prescription->diagnosis_id);
$newDateYmd = self::normalizePrescriptionDate($params['prescription_date'] ?? $prescription->prescription_date);
if ($newDiagnosisId > 0 && !self::assertUniquePrescriptionPerDiagnosisDay($newDiagnosisId, (int) $prescription->creator_id, $newDateYmd, (int) $params['id'])) {
return false;
}
$wasVoid = (int) ($prescription->void_status ?? 0) === 1;
$data = [
'diagnosis_id' => $newDiagnosisId,
'prescription_name' => $params['prescription_name'] ?? $prescription->prescription_name,
'prescription_type' => $params['prescription_type'] ?? $prescription->prescription_type,
'patient_name' => $params['patient_name'] ?? $prescription->patient_name,
'gender' => (int)($params['gender'] ?? $prescription->gender),
'age' => (int)($params['age'] ?? $prescription->age),
'visit_no' => $params['visit_no'] ?? $prescription->visit_no,
'prescription_date' => $params['prescription_date'] ?? $prescription->prescription_date,
'prescription_date' => $newDateYmd,
'tongue' => $params['tongue'] ?? $prescription->tongue,
'tongue_image' => $params['tongue_image'] ?? $prescription->tongue_image,
'pulse' => $params['pulse'] ?? $prescription->pulse,
@@ -154,8 +325,24 @@ class PrescriptionLogic
'usage_notes' => $params['usage_notes'] ?? $prescription->usage_notes,
'doctor_name' => $params['doctor_name'] ?? $prescription->doctor_name,
'is_shared' => (int)($params['is_shared'] ?? $prescription->is_shared),
'visible_role_ids' => array_key_exists('visible_role_ids', $params)
? self::normalizeVisibleRoleIds($params['visible_role_ids'])
: (string) ($prescription->visible_role_ids ?? ''),
// 开方医生修改后重新进入待审核
'audit_status' => 0,
'audit_time' => null,
'audit_by' => null,
'audit_by_name' => '',
'audit_remark' => '',
];
if ($wasVoid) {
$data['void_status'] = 0;
$data['void_time'] = null;
$data['void_by'] = null;
$data['void_by_name'] = '';
}
$prescription->save($data);
return true;
} catch (\Exception $e) {
@@ -176,6 +363,11 @@ class PrescriptionLogic
return false;
}
if ((int) ($prescription->audit_status ?? 1) === 1 && (int) ($prescription->void_status ?? 0) === 0) {
self::setError('该处方已通过审核,不可删除');
return false;
}
$prescription->delete();
return true;
} catch (\Exception $e) {
@@ -185,19 +377,180 @@ class PrescriptionLogic
}
/**
* 处方详情
* 处方详情(带查看权限校验,供后台管理端)
*/
public static function detail(int $id): ?array
public static function detail(int $id, int $viewerAdminId, array $viewerAdminInfo): ?array
{
self::$error = '';
$row = Prescription::find($id);
if (!$row) {
return null;
}
if (!self::canViewPrescription($row, $viewerAdminId, $viewerAdminInfo)) {
self::setError('无权限查看此处方');
return null;
}
$arr = $row->toArray();
$arr['gender_desc'] = $arr['gender'] == 1 ? '男' : '女';
$arr['visible_role_ids'] = self::visibleRoleIdsToArray($arr['visible_role_ids'] ?? '');
return $arr;
}
/**
* @return int[]
*/
public static function visibleRoleIdsToArray(string $csv): array
{
if ($csv === '') {
return [];
}
return array_values(array_unique(array_filter(array_map('intval', explode(',', $csv)))));
}
/**
* 审核:通过 / 驳回(驳回同时作废处方)
*/
public static function audit(int $id, string $action, string $remark, int $adminId, array $adminInfo): bool
{
self::$error = '';
self::$lastAuditWecomNotify = null;
if (!self::canAuditPrescription($adminId, $adminInfo)) {
self::setError('无审核权限');
return false;
}
$row = Prescription::find($id);
if (!$row) {
self::setError('处方不存在');
return false;
}
if (!self::canViewPrescription($row, $adminId, $adminInfo)) {
self::setError('无权限查看此处方,无法审核');
return false;
}
if ((int) ($row->audit_status ?? 1) !== 0) {
self::setError('当前状态不可审核');
return false;
}
$name = (string) ($adminInfo['name'] ?? '');
$now = time();
if ($action === 'approve') {
$row->audit_status = 1;
$row->audit_time = $now;
$row->audit_by = $adminId;
$row->audit_by_name = $name;
$row->audit_remark = $remark;
$ok = (bool) $row->save();
if ($ok) {
self::$lastAuditWecomNotify = self::notifyCreatorAuditResult($row, 'approve', $remark, $adminInfo);
}
return $ok;
}
if ($action === 'reject') {
if (trim($remark) === '') {
self::setError('驳回时请填写审核意见');
return false;
}
$row->audit_status = 2;
$row->audit_time = $now;
$row->audit_by = $adminId;
$row->audit_by_name = $name;
$row->audit_remark = $remark;
$row->void_status = 1;
$row->void_time = $now;
$row->void_by = $adminId;
$row->void_by_name = $name;
$ok = (bool) $row->save();
if ($ok) {
self::$lastAuditWecomNotify = self::notifyCreatorAuditResult($row, 'reject', $remark, $adminInfo);
}
return $ok;
}
self::setError('无效的审核操作');
return false;
}
/**
* 审核通过/驳回后,给企业微信中的开方人发一条应用消息(需绑定 work_wechat_userid
*
* @return array{ok: bool, message?: string, errcode?: int}
*/
private static function notifyCreatorAuditResult(Prescription $rx, string $action, string $remark, array $auditorInfo): array
{
try {
$creatorId = (int) ($rx->creator_id ?? 0);
if ($creatorId <= 0) {
return ['ok' => false, 'message' => '无法通知:处方无开方人信息'];
}
$creator = Admin::whereNull('delete_time')->find($creatorId);
if (!$creator) {
return ['ok' => false, 'message' => '无法通知:开方人账号不存在'];
}
$wxId = trim((string) ($creator->work_wechat_userid ?? ''));
if ($wxId === '') {
Log::warning("处方审核企业微信通知跳过: 开方人 admin_id={$creatorId} 未绑定 work_wechat_userid");
return [
'ok' => false,
'message' => '开方人未绑定企业微信账号,无法推送消息(请其在后台「扫码绑定企业微信」后再试)',
];
}
$sn = (string) ($rx->sn ?? '');
$patient = (string) ($rx->patient_name ?? '');
$auditorName = (string) ($auditorInfo['name'] ?? '');
if ($action === 'approve') {
$text = "【处方审核】您开具的处方已通过审核。\n编号:{$sn}\n患者:{$patient}\n审核人:{$auditorName}";
if (trim($remark) !== '') {
$text .= "\n备注:" . trim($remark);
}
} else {
$text = "【处方审核】您开具的处方已被驳回并已作废。\n编号:{$sn}\n患者:{$patient}\n审核人:{$auditorName}\n意见:" . trim($remark);
}
$result = WechatWorkAppMessageService::sendTextToUser($wxId, $text);
if (empty($result['ok'])) {
Log::warning('处方审核企业微信通知失败: ' . ($result['message'] ?? ''));
}
return $result;
} catch (\Throwable $e) {
Log::error('处方审核企业微信通知异常: ' . $e->getMessage());
return ['ok' => false, 'message' => '企业微信通知异常:' . $e->getMessage()];
}
}
/**
* 取出并清空最近一次审核后的企微通知结果(供接口返回给前端提示)
*
* @return array{ok: bool, message?: string, errcode?: int}|null
*/
public static function consumeLastAuditWecomNotify(): ?array
{
$v = self::$lastAuditWecomNotify;
self::$lastAuditWecomNotify = null;
return $v;
}
/**
* 根据诊单ID获取处方列表
*/
@@ -31,9 +31,9 @@ class DiagnosisValidate extends BaseValidate
'phone' => 'require|mobile',
'gender' => 'require|in:0,1',
'age' => 'require|number|between:0,150',
'diagnosis_date' => 'require',
'diagnosis_type' => 'require',
'status' => 'in:0,1',
'current_medications' => 'max:2000',
'tongue_images' => 'array',
'report_files' => 'array',
];
@@ -50,9 +50,9 @@ class DiagnosisValidate extends BaseValidate
'age.require' => '请输入年龄',
'age.number' => '年龄必须为数字',
'age.between' => '年龄范围0-150',
'diagnosis_date.require' => '请选择诊断日期',
'diagnosis_type.require' => '请选择诊断类型',
'status.in' => '状态参数错误',
'current_medications.max' => '在用药物最多2000个字符',
];
public function sceneAdd()
@@ -62,7 +62,7 @@ class DiagnosisValidate extends BaseValidate
public function sceneEdit()
{
return $this->only(['id', 'patient_name', 'id_card', 'phone', 'gender', 'age', 'diagnosis_date', 'diagnosis_type', 'syndrome_type', 'marital_status', 'height', 'weight', 'region', 'systolic_pressure', 'diastolic_pressure', 'fasting_blood_sugar', 'diabetes_discovery_year', 'local_hospital_diagnosis', 'local_hospital_name', 'past_history', 'symptoms', 'tongue_coating', 'pulse', 'treatment_principle', 'prescription', 'doctor_advice', 'remark', 'status', 'tongue_images', 'report_files']);
return $this->only(['id', 'patient_name', 'id_card', 'phone', 'gender', 'age', 'diagnosis_date', 'diagnosis_type', 'syndrome_type', 'marital_status', 'height', 'weight', 'region', 'systolic_pressure', 'diastolic_pressure', 'fasting_blood_sugar', 'diabetes_discovery_year', 'local_hospital_diagnosis', 'local_hospital_name', 'past_history', 'symptoms', 'tongue_coating', 'pulse', 'treatment_principle', 'prescription', 'doctor_advice', 'remark', 'current_medications', 'status', 'tongue_images', 'report_files']);
}
public function sceneId()
@@ -15,6 +15,8 @@ class PrescriptionValidate extends BaseValidate
'patient_name' => 'require',
'clinical_diagnosis' => 'require',
'herbs' => 'require|array',
'action' => 'require|in:approve,reject',
'remark' => 'max:500',
];
protected $message = [
@@ -26,22 +28,23 @@ class PrescriptionValidate extends BaseValidate
public function sceneAdd()
{
return $this->only([
'prescription_name', 'prescription_type', 'patient_name', 'gender', 'age',
'visit_no', 'prescription_date', 'tongue', 'tongue_image', 'pulse',
'pulse_condition', 'clinical_diagnosis', 'herbs', 'dose_count', 'dose_unit',
'usage_days', 'usage_instruction', 'usage_time', 'usage_way', 'dietary_taboo',
'usage_notes', 'doctor_name', 'is_shared', 'diagnosis_id', 'appointment_id'
'prescription_type', 'patient_name', 'gender', 'age',
'visit_no', 'prescription_date', 'tongue', 'tongue_image', 'pulse',
'pulse_condition', 'clinical_diagnosis', 'herbs', 'dose_count', 'dose_unit',
'usage_days', 'usage_instruction', 'usage_time', 'usage_way', 'dietary_taboo',
'usage_notes', 'doctor_name', 'is_shared', 'visible_role_ids',
'diagnosis_id', 'appointment_id', 'audit_status',
]);
}
public function sceneEdit()
{
return $this->only([
'id', 'prescription_name', 'prescription_type', 'patient_name', 'gender', 'age',
'visit_no', 'prescription_date', 'tongue', 'tongue_image', 'pulse',
'pulse_condition', 'clinical_diagnosis', 'herbs', 'dose_count', 'dose_unit',
'usage_days', 'usage_instruction', 'usage_time', 'usage_way', 'dietary_taboo',
'usage_notes', 'doctor_name', 'is_shared'
'id', 'prescription_type', 'patient_name', 'gender', 'age',
'visit_no', 'prescription_date', 'tongue', 'tongue_image', 'pulse',
'pulse_condition', 'clinical_diagnosis', 'herbs', 'dose_count', 'dose_unit',
'usage_days', 'usage_instruction', 'usage_time', 'usage_way', 'dietary_taboo',
'usage_notes', 'doctor_name', 'is_shared', 'visible_role_ids', 'diagnosis_id',
]);
}
@@ -54,4 +57,9 @@ class PrescriptionValidate extends BaseValidate
{
return $this->only(['id']);
}
public function sceneAudit()
{
return $this->only(['id', 'action', 'remark']);
}
}
+27 -2
View File
@@ -28,7 +28,7 @@ class TcmController extends BaseApiController
* @notes 不需要登录的方法
* @var array
*/
public array $notNeedLogin = ['getPatientSignature', 'diagnosisDetail', 'getDict', 'confirmDiagnosis', 'getCardList', 'getOrderByNo'];
public array $notNeedLogin = ['getPatientSignature', 'diagnosisDetail', 'getDict', 'confirmDiagnosis', 'getCardList', 'getOrderByNo', 'patientHangupVideo'];
/**
* @notes 获取患者签名(供小程序调用)
@@ -51,7 +51,32 @@ class TcmController extends BaseApiController
return $this->data($result);
}
/**
* @notes 患者挂断视频:后端 DeleteCloudRecording + 结束通话记录(与诊单 patient_id 校验)
* @return \think\response\Json
*/
public function patientHangupVideo()
{
$params = [
'diagnosis_id' => (int)$this->request->post('diagnosis_id', 0),
'patient_id' => (int)$this->request->post('patient_id', 0),
'room_id' => trim((string)$this->request->post('room_id', '')),
];
if ($params['patient_id'] <= 0) {
return $this->fail('患者ID不能为空');
}
if ($params['diagnosis_id'] <= 0 && $params['room_id'] === '') {
return $this->fail('诊单ID或房间号须至少传一项');
}
$result = DiagnosisLogic::patientHangupVideoCall($params);
if ($result === false) {
return $this->fail(DiagnosisLogic::getError());
}
return $this->success('已结束通话');
}
/**
* @notes 获取诊单详情(供小程序调用)
* @return \think\response\Json
+67 -19
View File
@@ -17,7 +17,7 @@ class TrtcController extends BaseApiController
public array $notNeedLogin = ['recordingNotify'];
/**
* POST /api/trtc/recording-notify
* POST /api/trtc/recording-notify 或 /api/trtc/recordingNotify(与控制台回调 URL 一致即可)
* 可选安全:环境变量 TRTC_RECORDING_CALLBACK_TOKEN 非空时,Query 需带 ?token=xxx
*/
public function recordingNotify()
@@ -37,28 +37,41 @@ class TrtcController extends BaseApiController
return json(['code' => 0, 'msg' => 'ok']);
}
$eventType = (int)($json['EventType'] ?? 0);
$roomId = $this->extractRoomId($json);
$taskId = trim((string)data_get($json, 'EventInfo.TaskId', ''));
$urls = $this->extractRecordingUrls($json);
if ($roomId === '' || $urls === []) {
Log::info('TRTC recording callback: skip (no room or no urls)', [
'roomId' => $roomId,
'eventType' => $json['EventType'] ?? null,
]);
if ($urls === []) {
// 301–308 等为进度事件,无播放地址;311=VOD 上传完成带 VideoUrl(见文档 81113
$mayHaveUrl = in_array($eventType, [309, 310, 311], true);
$payload = data_get($json, 'EventInfo.Payload');
if ($urls === [] && $eventType === 311) {
Log::warning('TRTC recording callback: 311 但未解析到 VideoUrl(可能 Status!=0 或字段名变更)', [
'PayloadStatus' => is_array($payload) ? ($payload['Status'] ?? null) : null,
'Errmsg' => is_array($payload) ? ($payload['Errmsg'] ?? $payload['ErrMsg'] ?? null) : null,
'TaskId' => $taskId !== '' ? $taskId : null,
'roomId' => $roomId !== '' ? $roomId : null,
]);
}
Log::info(
'TRTC recording callback: skip (no playback url in payload) '
. 'EventType=' . $eventType
. ' EventGroupId=' . (string)($json['EventGroupId'] ?? '')
. ' TaskId=' . ($taskId !== '' ? $taskId : '-')
. ' roomId=' . ($roomId !== '' ? $roomId : '-')
. ' ' . ($mayHaveUrl ? 'expect_url' : 'progress_ok')
);
return json(['code' => 0, 'msg' => 'ok']);
}
$record = CallRecord::where('room_id', $roomId)
->order('id', 'desc')
->find();
$record = $this->resolveCallRecordForNotify($roomId, $taskId);
if (!$record) {
// 兼容数字房间号与字符串
$record = CallRecord::where('room_id', (string)(int)$roomId)
->order('id', 'desc')
->find();
}
if (!$record) {
Log::warning('TRTC recording: no call_record for room', ['roomId' => $roomId]);
Log::warning('TRTC recording: no call_record (try room_id + cloud_recording_task_id)', [
'roomId' => $roomId,
'TaskId' => $taskId,
'EventType' => $eventType,
]);
return json(['code' => 0, 'msg' => 'ok']);
}
@@ -88,18 +101,52 @@ class TrtcController extends BaseApiController
$candidates = [
data_get($data, 'EventInfo.RoomId'),
data_get($data, 'EventInfo.RoomIdStr'),
data_get($data, 'EventInfo.StrRoomId'),
data_get($data, 'EventInfo.Payload.RoomId'),
data_get($data, 'EventInfo.Payload.RoomIdStr'),
data_get($data, 'RoomId'),
data_get($data, 'room_id'),
];
foreach ($candidates as $v) {
if ($v !== null && $v !== '') {
return trim((string)$v);
$s = trim((string)$v);
if ($s !== '' && $s !== '0') {
return $s;
}
}
}
return '';
}
/**
* 先按 room_id,再按 CreateCloudRecording 返回的 TaskId(须库中仍保留 cloud_recording_task_id
*/
private function resolveCallRecordForNotify(string $roomId, string $taskId): ?CallRecord
{
if ($roomId !== '') {
$record = CallRecord::where('room_id', $roomId)->order('id', 'desc')->find();
if ($record) {
return $record;
}
if (ctype_digit($roomId)) {
$norm = (string)(int)$roomId;
$record = CallRecord::where('room_id', $norm)->order('id', 'desc')->find();
if ($record) {
return $record;
}
}
}
if ($taskId !== '') {
$record = CallRecord::where('cloud_recording_task_id', $taskId)->order('id', 'desc')->find();
if ($record) {
return $record;
}
}
return null;
}
/**
* 从回调 JSON 中提取录制文件地址(混流/单路字段名在不同版本可能不同)
*/
@@ -117,9 +164,10 @@ class TrtcController extends BaseApiController
return;
}
foreach ($node as $key => $val) {
if (is_string($key) && in_array($key, ['VideoUrl', 'FileUrl', 'MediaUrl', 'Url', 'url'], true) && is_string($val)) {
$keyLower = is_string($key) ? strtolower($key) : '';
if (in_array($keyLower, ['videourl', 'fileurl', 'mediaurl', 'url', 'streamurl', 'playurl'], true) && is_string($val)) {
$v = trim($val);
if ($v !== '' && str_starts_with($v, 'http')) {
if ($v !== '' && preg_match('#^https?://#i', $v) === 1) {
$urls[] = $v;
}
}
@@ -14,16 +14,16 @@ use think\facade\Log;
/**
* 挂号单状态自动更新
* - 预约时间已过:status -> 4(已过号)
* - 预约时间已过超过8小时:status -> 2(已取消)
* - 不处理:status=3(已完成)、未到时间的单子
* - 预约时间已过超过 35 分钟(且未满 8 小时)status -> 4(已过号)
* - 预约时间已过超过 8 小时:status -> 2(已取消)
* - 不处理:status=3(已完成)、未到时间、刚过号未满 35 分钟的单子
*/
class UpdateAppointmentStatus extends Command
{
protected function configure()
{
$this->setName('update_appointment_status')
->setDescription('自动更新挂号单状态:过号->4,超8小时->2(已取消)')
->setDescription('自动更新挂号单状态:过号超35分钟->4,超8小时->2(已取消)')
->addOption('dry', null, Option::VALUE_NONE, '仅预览不执行');
}
@@ -38,8 +38,8 @@ class UpdateAppointmentStatus extends Command
$cancelSql = "UPDATE {$table} SET status = 2, update_time = ? WHERE {$cancelWhere}";
$cancelCount = $dryRun ? 0 : Db::execute($cancelSql, [$now]);
// 2. 已过时间但未超8小时 -> 已过号(status=4)
$missedWhere = "status = 1 AND CONCAT(appointment_date, ' ', IFNULL(appointment_time, '00:00:00')) < NOW() AND CONCAT(appointment_date, ' ', IFNULL(appointment_time, '00:00:00')) > DATE_SUB(NOW(), INTERVAL 8 HOUR)";
// 2. 已过预约时间超过 35 分钟且未满 8 小时 -> 已过号(status=4)
$missedWhere = "status = 1 AND CONCAT(appointment_date, ' ', IFNULL(appointment_time, '00:00:00')) < DATE_SUB(NOW(), INTERVAL 35 MINUTE) AND CONCAT(appointment_date, ' ', IFNULL(appointment_time, '00:00:00')) > DATE_SUB(NOW(), INTERVAL 8 HOUR)";
$missedSql = "UPDATE {$table} SET status = 4, update_time = ? WHERE {$missedWhere}";
$missedCount = $dryRun ? 0 : Db::execute($missedSql, [$now]);
@@ -16,6 +16,8 @@ namespace app\common\model\tcm;
use app\common\model\BaseModel;
use app\common\model\DiagnosisViewRecord;
use think\model\concern\SoftDelete;
/**
* 中医辨房病因诊单模型
* Class Diagnosis
@@ -23,6 +25,8 @@ use app\common\model\DiagnosisViewRecord;
*/
class Diagnosis extends BaseModel
{
use SoftDelete;
protected $name = 'tcm_diagnosis';
// 自动时间戳类型设置为整型
@@ -0,0 +1,15 @@
<?php
namespace app\common\model\tcm;
use app\common\model\BaseModel;
/**
* 诊单指派医助操作记录
*/
class DiagnosisAssignLog extends BaseModel
{
protected $name = 'tcm_diagnosis_assign_log';
protected $autoWriteTimestamp = false;
}
@@ -8,23 +8,65 @@ use think\facade\Log;
/**
* 腾讯云 TRTC 云端录制(CreateCloudRecording / DeleteCloudRecording
* 混流(合流)录制:在 RecordParams 中将 RecordMode 设为 2,并配合 MixLayoutParams / MixTranscodeParams。
* 依赖:composer require tencentcloud/trtc
*/
class TrtcCloudRecordingService
{
/** RecordParams.RecordMode:混流录制(多路合成一个文件) */
public const RECORD_MODE_MIX = 2;
/**
* 在应用启动时调用,避免 Guzzle 首次 defaultCaBundle() 缓存错误路径(Windows 常见 cURL error 60)。
* 也可在发起请求前再次调用(重复 ini_set 无害)。
*/
public static function applyRecordingSslCaBundleEarly(): void
{
$path = self::resolveRecordingCaBundlePath();
if ($path === '') {
if (\function_exists('putenv')) {
@putenv('TRTC_RECORDING_SSL_CAFILE');
}
return;
}
@ini_set('openssl.cafile', $path);
@ini_set('curl.cainfo', $path);
// 腾讯云 SDK 内 Guzzle 会忽略已缓存的 defaultCaBundle;通过环境变量让 HttpConnection 显式 verify
if (\function_exists('putenv')) {
@putenv('TRTC_RECORDING_SSL_CAFILE=' . $path);
}
}
private static function resolveRecordingCaBundlePath(): string
{
$raw = trim((string)config('trtc.recording_ssl_cafile', ''));
$path = trim($raw, " \t\"'");
if ($path !== '' && is_readable($path)) {
return $path;
}
$root = rtrim((string)root_path(), '/\\');
$candidate = $root . DIRECTORY_SEPARATOR . 'cacert.pem';
return is_readable($candidate) ? $candidate : '';
}
public static function sdkAvailable(): bool
{
return class_exists(\TencentCloud\Trtc\V20190722\TrtcClient::class);
}
/**
* @param string|null $vodUserDefineRecordId 云点播文件名前缀(仅字母数字下划线连字符,≤64),便于与控制台单流区分;混流文件会带此前缀
* @return array{ok:bool,task_id?:string,message?:string}
*/
public static function startMixRecording(
int $sdkAppId,
string $roomId,
string $botUserId,
string $botUserSig
string $botUserSig,
?string $vodUserDefineRecordId = null
): array {
if (!self::sdkAvailable()) {
return ['ok' => false, 'message' => '未安装 tencentcloud/trtc,请在 server 目录执行 composer update'];
@@ -41,10 +83,11 @@ class TrtcCloudRecordingService
return ['ok' => false, 'message' => '未配置 TRTC UserSig 密钥(project.trtc.secretKey'];
}
$roomIdType = ctype_digit($roomId) ? 1 : 0;
$roomIdType = self::resolveRecordingRoomIdType((string)$roomId);
$region = (string)config('trtc.recording_api_region', 'ap-guangzhou');
try {
self::applyRecordingSslCaBundleEarly();
$cred = new \TencentCloud\Common\Credential($secretId, $secretKey);
$httpProfile = new \TencentCloud\Common\Profile\HttpProfile();
$httpProfile->setEndpoint('trtc.tencentcloudapi.com');
@@ -60,44 +103,86 @@ class TrtcCloudRecordingService
$req->UserSig = $botUserSig;
$recordParams = new \TencentCloud\Trtc\V20190722\Models\RecordParams();
$recordParams->RecordMode = 2;
// 合流录制:RecordMode=2(见 https://cloud.tencent.com/document/product/647/76497 方案二 API 手动录制)
$recordParams->RecordMode = self::RECORD_MODE_MIX;
$recordParams->StreamType = 0;
$recordParams->MaxIdleTime = 300;
$recordParams->MaxIdleTime = (int)config('trtc.recording_max_idle_time', 300);
// 不订阅录制机器人自身流,避免占混流画面;医患流仍默认全订阅
$subscribe = new \TencentCloud\Trtc\V20190722\Models\SubscribeStreamUserIds();
$subscribe->UnSubscribeAudioUserIds = [$botUserId];
$subscribe->UnSubscribeVideoUserIds = [$botUserId];
$recordParams->SubscribeStreamUserIds = $subscribe;
$req->RecordParams = $recordParams;
$tencentVod = new \TencentCloud\Trtc\V20190722\Models\TencentVod();
$tencentVod->ExpireTime = 0;
$tencentVod->MediaType = 0;
$prefix = self::sanitizeVodUserDefineRecordId($vodUserDefineRecordId);
if ($prefix !== '') {
$tencentVod->UserDefineRecordId = $prefix;
}
$vodSubApp = (int)config('trtc.recording_vod_sub_app_id', 0);
if ($vodSubApp > 0) {
$tencentVod->SubAppId = $vodSubApp;
}
$cloudVod = new \TencentCloud\Trtc\V20190722\Models\CloudVod();
$cloudVod->TencentVod = $tencentVod;
$storage = new \TencentCloud\Trtc\V20190722\Models\StorageParams();
$storage->CloudVod = $cloudVod;
$req->StorageParams = $storage;
// MixTranscodeParamsSDK 说明「若设置该参数则内部字段须填全」。仅填 VideoParams 未填 AudioParams 可能导致合流异常或退化为非预期行为
$videoParams = new \TencentCloud\Trtc\V20190722\Models\VideoParams();
$videoParams->Width = 720;
$videoParams->Height = 1280;
$videoParams->Fps = 15;
$videoParams->BitRate = 1000000;
$videoParams->Gop = 2;
$videoParams->Width = (int)config('trtc.recording_mix_width', 1280);
$videoParams->Height = (int)config('trtc.recording_mix_height', 720);
$videoParams->Fps = (int)config('trtc.recording_mix_fps', 15);
$videoParams->BitRate = (int)config('trtc.recording_mix_video_bitrate', 1500000);
$videoParams->Gop = (int)config('trtc.recording_mix_gop', 2);
$audioParams = new \TencentCloud\Trtc\V20190722\Models\AudioParams();
$audioParams->SampleRate = (int)config('trtc.recording_mix_audio_sample_rate', 1);
$audioParams->Channel = (int)config('trtc.recording_mix_audio_channel', 2);
$audioParams->BitRate = (int)config('trtc.recording_mix_audio_bitrate', 64000);
$mixTc = new \TencentCloud\Trtc\V20190722\Models\MixTranscodeParams();
$mixTc->VideoParams = $videoParams;
$mixTc->AudioParams = $audioParams;
$req->MixTranscodeParams = $mixTc;
$mixLayout = new \TencentCloud\Trtc\V20190722\Models\MixLayoutParams();
$mixLayout->MixLayoutMode = 3;
$layoutMode = (int)config('trtc.recording_mix_layout_mode', 3);
if ($layoutMode < 1 || $layoutMode > 4) {
$layoutMode = 3;
}
$mixLayout->MixLayoutMode = $layoutMode;
$req->MixLayoutParams = $mixLayout;
Log::info('CreateCloudRecording mix', [
'sdkAppId' => $sdkAppId,
'roomId' => $roomId,
'roomIdType' => $roomIdType,
'recordMode' => self::RECORD_MODE_MIX,
'mixLayoutMode' => $layoutMode,
'vodUserDefineRecordId' => $prefix !== '' ? $prefix : null,
]);
$resp = $client->CreateCloudRecording($req);
$taskId = $resp->TaskId ?? '';
if ($taskId === '') {
return ['ok' => false, 'message' => 'CreateCloudRecording 未返回 TaskId'];
}
self::logDescribeCloudRecordingHint($client, $sdkAppId, $taskId, (string)$roomId, $roomIdType);
return ['ok' => true, 'task_id' => $taskId];
} catch (\Throwable $e) {
Log::error('CreateCloudRecording failed: ' . $e->getMessage());
$msg = $e->getMessage();
if (str_contains($msg, 'SSL certificate problem') || str_contains($msg, 'error 60')) {
$msg .= ';请下载 https://curl.se/ca/cacert.pem 保存到本机,在 .env [trtc] 设置 RECORDING_SSL_CAFILE=绝对路径,或在 php.ini 配置 openssl.cafile / curl.cainfo';
}
Log::error('CreateCloudRecording failed: ' . $msg);
return ['ok' => false, 'message' => $e->getMessage()];
return ['ok' => false, 'message' => $msg];
}
}
@@ -120,6 +205,7 @@ class TrtcCloudRecordingService
$region = (string)config('trtc.recording_api_region', 'ap-guangzhou');
try {
self::applyRecordingSslCaBundleEarly();
$cred = new \TencentCloud\Common\Credential($secretId, $secretKey);
$httpProfile = new \TencentCloud\Common\Profile\HttpProfile();
$httpProfile->setEndpoint('trtc.tencentcloudapi.com');
@@ -164,4 +250,90 @@ class TrtcCloudRecordingService
return $api->genUserSig($botUserId, $expire > 0 ? $expire : 86400);
}
/**
* RoomIdType 必须与通话实际房间类型一致,否则录制进错房或只能录到单路(见 CreateCloudRecording RoomIdType 说明)
*/
public static function resolveRecordingRoomIdType(string $roomId): int
{
$cfg = trim((string)config('trtc.recording_room_id_type', ''));
if ($cfg !== '' && strtolower($cfg) !== 'auto') {
return ((int)$cfg) === 1 ? 1 : 0;
}
return ctype_digit($roomId) ? 1 : 0;
}
/**
* TencentVod.UserDefineRecordId:仅 a-zA-Z0-9_-
*/
private static function sanitizeVodUserDefineRecordId(?string $raw): string
{
if ($raw === null || $raw === '') {
return '';
}
$s = preg_replace('/[^a-zA-Z0-9_-]/', '', $raw) ?? '';
return strlen($s) > 64 ? substr($s, 0, 64) : $s;
}
/**
* 混流时 StorageFile.UserId 应为空串;非空则多为单流。用于区分控制台全局单流与 API 合流。
* CreateCloudRecording 后立刻查询常为 Idle,约 2s 后再查一次再下结论。
*/
private static function logDescribeCloudRecordingHint(
\TencentCloud\Trtc\V20190722\TrtcClient $client,
int $sdkAppId,
string $taskId,
string $roomId,
int $roomIdType
): void {
try {
$snap = function () use ($client, $sdkAppId, $taskId, $roomId, $roomIdType): array {
$dreq = new \TencentCloud\Trtc\V20190722\Models\DescribeCloudRecordingRequest();
$dreq->SdkAppId = $sdkAppId;
$dreq->TaskId = $taskId;
$dresp = $client->DescribeCloudRecording($dreq);
$list = $dresp->StorageFileList ?? [];
$firstUid = '';
if (is_array($list) && isset($list[0]) && $list[0] instanceof \TencentCloud\Trtc\V20190722\Models\StorageFile) {
$firstUid = (string)($list[0]->UserId ?? '');
}
return [
'taskId' => $taskId,
'roomId' => $roomId,
'roomIdType' => $roomIdType,
'status' => (string)($dresp->Status ?? ''),
'storageFileCount' => is_array($list) ? count($list) : 0,
'firstFileUserId' => $firstUid,
];
};
$first = $snap();
if (strcasecmp($first['status'], 'Idle') === 0) {
sleep(2);
$second = $snap();
if (strcasecmp($second['status'], 'Idle') !== 0) {
Log::info('DescribeCloudRecording(合流校验): 首次 Idle,约2s 后已非 Idle', $second + [
'hint' => '启动瞬间 Idle 属常见;VOD 成片仍以回调311与点播为准',
]);
return;
}
Log::warning(
'DescribeCloudRecording: 约2s 后仍为 Idle(未拉到流:多因 RoomIdType 与客户端房间类型不一致,或房内无上推)',
$second
);
return;
}
Log::info('DescribeCloudRecording(合流校验)', $first + [
'hint' => $first['firstFileUserId'] === '' ? 'VOD 场景 StorageFileList 常为空,以点播媒资+311 回调为准' : 'firstFileUserId 非空更像单流',
]);
} catch (\Throwable $e) {
Log::info('DescribeCloudRecording 跳过: ' . $e->getMessage());
}
}
}
@@ -0,0 +1,192 @@
<?php
declare(strict_types=1);
namespace app\common\service\wechat;
use think\facade\Cache;
use think\facade\Log;
/**
* 企业微信自建应用:向成员发送应用文本消息
*
* 依赖配置(与登录/绑定可共用 corp_id;发消息必须用「同一自建应用」的 AgentId + Secret):
* - WECHAT_WORK_CORP_ID 或 work_wechat.corp_id
* - WECHAT_WORK_AGENT_ID 或 work_wechat.agent_id
* - WECHAT_WORK_AGENT_SECRET 或 work_wechat.agent_secret(推荐;勿与仅用于网页授权的 secret 混用)
* - 若未配 agent_secret,会回退 work_wechat.secret(若仍无法发消息,请在管理后台复制该应用的 Secret 填到 agent_secret
*
* @see https://developer.work.weixin.qq.com/document/path/90236
*/
class WechatWorkAppMessageService
{
/**
* @return array{0: string, 1: int, 2: string} [corpId, agentId, secret]
*/
private static function resolveMessagingCredentials(): array
{
$corpId = (string) env('WECHAT_WORK_CORP_ID', '');
if ($corpId === '') {
$corpId = (string) env('work_wechat.corp_id', '');
}
$agentIdStr = (string) env('WECHAT_WORK_AGENT_ID', '');
if ($agentIdStr === '') {
$agentIdStr = (string) env('work_wechat.agent_id', '');
}
$agentId = (int) $agentIdStr;
$secret = (string) env('WECHAT_WORK_AGENT_SECRET', '');
if ($secret === '') {
$secret = (string) env('work_wechat.agent_secret', '');
}
if ($secret === '') {
$secret = (string) env('work_wechat.secret', '');
}
return [$corpId, $agentId, $secret];
}
private static function getAccessToken(string $corpId, string $secret): ?string
{
if ($corpId === '' || $secret === '') {
return null;
}
$cacheKey = 'work_wechat_app_msg_token_' . md5($corpId . $secret);
$cached = Cache::get($cacheKey);
if ($cached) {
return (string) $cached;
}
$url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$corpId}&corpsecret={$secret}";
$res = self::httpGetJson($url);
if (!$res || (int) ($res['errcode'] ?? -1) !== 0) {
Log::error('企业微信应用 access_token 失败: ' . ($res['errmsg'] ?? '无响应'));
return null;
}
$token = (string) ($res['access_token'] ?? '');
if ($token === '') {
return null;
}
$ttl = (int) ($res['expires_in'] ?? 7200) - 200;
if ($ttl > 0) {
Cache::set($cacheKey, $token, $ttl);
}
return $token;
}
/**
* @return array<string,mixed>|null
*/
private static function httpGetJson(string $url): ?array
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$result = curl_exec($ch);
curl_close($ch);
if ($result === false || $result === '') {
return null;
}
$decoded = json_decode($result, true);
return is_array($decoded) ? $decoded : null;
}
/**
* @return array<string,mixed>|null
*/
private static function httpPostJson(string $url, array $body): ?array
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body, JSON_UNESCAPED_UNICODE));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$result = curl_exec($ch);
curl_close($ch);
if ($result === false || $result === '') {
return null;
}
$decoded = json_decode($result, true);
return is_array($decoded) ? $decoded : null;
}
/**
* 向指定成员发送文本消息(userid 为企业微信成员账号,与后台 work_wechat_userid 一致)
*
* @return array{ok: bool, message?: string, errcode?: int}
*/
public static function sendTextToUser(string $toUser, string $content): array
{
$toUser = trim($toUser);
$content = trim($content);
if ($toUser === '' || $content === '') {
return ['ok' => false, 'message' => '接收人或消息内容为空'];
}
[$corpId, $agentId, $secret] = self::resolveMessagingCredentials();
if ($corpId === '' || $agentId <= 0 || $secret === '') {
Log::warning('企业微信应用消息未配置完整(corp_id/agent_id/secret),跳过发消息');
return [
'ok' => false,
'message' => '服务端未配置企业微信应用消息(需 corp_id、agent_id 及该应用的 Secret,建议配置 WECHAT_WORK_AGENT_SECRET',
];
}
$token = self::getAccessToken($corpId, $secret);
if (!$token) {
return ['ok' => false, 'message' => '获取企业微信 access_token 失败,请查看服务端日志'];
}
$url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' . urlencode($token);
$body = [
'touser' => $toUser,
'msgtype' => 'text',
'agentid' => $agentId,
'text' => ['content' => $content],
'safe' => 0,
];
$res = self::httpPostJson($url, $body);
if (!$res) {
Log::error('企业微信发消息无响应');
return ['ok' => false, 'message' => '企业微信接口无响应'];
}
$err = (int) ($res['errcode'] ?? -1);
if ($err !== 0) {
$errmsg = (string) ($res['errmsg'] ?? '');
Log::error('企业微信发消息失败: ' . $errmsg . ' errcode=' . $err);
$hint = '';
if ($err === 81013 || $err === 60111) {
$hint = '请核对开方人绑定的 userid 与企业微信成员账号一致,且成员已安装/可见该应用。';
} elseif ($err === 60020) {
$hint = '请将服务器出口 IP 加入企业微信应用可信 IP。';
} elseif ($err === 60011) {
$hint = '请检查应用是否具备发消息能力及可见范围是否包含该成员。';
}
return [
'ok' => false,
'message' => '企业微信返回:' . $errmsg . 'errcode=' . $err . '' . ($hint !== '' ? ' ' . $hint : ''),
'errcode' => $err,
];
}
return ['ok' => true];
}
}