Files
zyt/server/app/adminapi/lists/tcm/PrescriptionLists.php
T
Your NameandClaude Opus 5 14936cb28a 已开处方列表提速;处方 AI 拒答带全部候选键时按拒答处理
- 置顶风险处方改为从订单表出发计算并缓存 60 秒,分页只查 ID,不再整表扫描与排序
- 列表行不再返回 doctor_signature,查看/编辑仍另取详情
- 模型拒绝开方时把候选键置空返回,不再判为 INVALID_REPORT_OUTPUT,可进入追问

Co-Authored-By: Claude Opus 5 <[EMAIL]>
2026-12-04 15:01:39 +08:00

413 lines
15 KiB
PHP
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace app\adminapi\lists\tcm;
use app\adminapi\lists\BaseAdminDataLists;
use app\common\lists\ListsSearchInterface;
use app\common\lists\Traits\HasDataScopeFilter;
use app\adminapi\logic\tcm\PrescriptionLogic;
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
use app\common\model\tcm\Prescription;
use app\common\model\tcm\PrescriptionOrder;
use app\common\service\esign\PrescriptionEsignService;
use think\db\Query;
use think\facade\Cache;
/**
* 处方列表
*/
class PrescriptionLists extends BaseAdminDataLists implements ListsSearchInterface
{
use HasDataScopeFilter;
/** 置顶风险处方 ID 的缓存键与有效期(秒);只影响置顶顺序,行内警示仍按当前数据实时计算 */
private const RISK_IDS_CACHE_KEY = 'tcm_prescription_lists_risk_ids';
private const RISK_IDS_CACHE_TTL = 60;
/** 列表行不返回的大字段:签名图 base64 动辄数十 KB,查看/编辑都会另取详情 */
private const LIST_OMIT_FIELDS = ['doctor_signature'];
/**
* 识别「有业务订单且处方药材为空白/重复」的处方 ID(用于全局置顶排序)
*
* 风险是处方自身的属性,与筛选条件无关:这里在全库范围计算一次并短时缓存,
* 筛选范围的交集由 pinnedIds() 在当前查询里取。以前每次请求都先把筛选结果的
* 全部 ID 拉出来,再逐个读药材,处方表行很宽(病历快照、签名图),整表扫描
* 是列表慢的主因。
*
* @return array<int,int>
*/
private function collectRiskPrescriptionIds(): array
{
$cached = Cache::get(self::RISK_IDS_CACHE_KEY);
if (is_array($cached)) {
return $cached;
}
// 仅在「存在有效业务订单」的处方里做风险判定;订单表很小,从订单侧出发
$orderRxIds = PrescriptionOrder::whereNull('delete_time')
->whereNotIn('fulfillment_status', PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES)
->column('prescription_id');
$orderRxIds = array_values(array_unique(array_filter(array_map('intval', $orderRxIds), static function (int $id): bool {
return $id > 0;
})));
$riskIds = [];
foreach (array_chunk($orderRxIds, 1000) as $chunk) {
$herbsById = Prescription::whereIn('id', $chunk)
->whereNull('delete_time')
->column('herbs', 'id');
foreach ($herbsById as $rid => $herbs) {
$rid = (int) $rid;
if ($rid > 0 && $this->isRiskHerbs($herbs)) {
$riskIds[] = $rid;
}
}
}
$riskIds = array_values(array_unique($riskIds));
Cache::set(self::RISK_IDS_CACHE_KEY, $riskIds, self::RISK_IDS_CACHE_TTL);
return $riskIds;
}
/**
* 当前页的处方 ID:先排当前筛选范围内的风险处方,再按 ID 倒序排其余处方。
*
* 拆成两段只查 ID,避免对整表做 ORDER BY CASE 的文件排序;第二段可直接沿主键倒序扫描,
* 取够一页即停止。
*
* @return array<int,int>
*/
private function pageIds(Query $query): array
{
$offset = max(0, (int) $this->limitOffset);
$length = max(0, (int) $this->limitLength);
if ($length === 0) {
return [];
}
$riskIds = $this->collectRiskPrescriptionIds();
$pinned = [];
if ($riskIds !== []) {
$pinned = array_map('intval', (clone $query)->whereIn('id', $riskIds)->order('id', 'desc')->column('id'));
}
$ids = array_slice($pinned, $offset, $length);
$remaining = $length - count($ids);
if ($remaining > 0) {
$rest = clone $query;
if ($pinned !== []) {
$rest->whereNotIn('id', $pinned);
}
$restIds = $rest->order('id', 'desc')
->limit(max(0, $offset - count($pinned)), $remaining)
->column('id');
$ids = array_merge($ids, array_map('intval', $restIds));
}
return $ids;
}
/**
* 药材风险判定:空白 or 重复(按名称,忽略空格与大小写)
*/
private function isRiskHerbs($herbsRaw): bool
{
$herbs = [];
if (is_array($herbsRaw)) {
$herbs = $herbsRaw;
} elseif (is_string($herbsRaw) && $herbsRaw !== '') {
$decoded = json_decode($herbsRaw, true);
if (is_array($decoded)) {
$herbs = $decoded;
}
}
$names = [];
foreach ($herbs as $h) {
if (!is_array($h)) {
continue;
}
$name = trim((string) ($h['name'] ?? ''));
if ($name !== '') {
$names[] = $name;
}
}
// 空白药材
if ($names === []) {
return true;
}
// 重复药材
$seen = [];
foreach ($names as $name) {
$key = strtolower(preg_replace('/\s+/', '', $name) ?? '');
if ($key === '') {
continue;
}
if (isset($seen[$key])) {
return true;
}
$seen[$key] = true;
}
return false;
}
/**
* @notes 搜索条件
*/
public function setSearch(): array
{
return [
'%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_filter:passed=已通过,not_passed=未通过(待审+驳回),pending,rejected
*/
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':
$esignEnabled = PrescriptionEsignService::enabled();
$query->where('audit_status', '=', 0)->where('review_submitted_at', '>', 0)->where('void_status', '=', 0)
->where(static function (Query $q) use ($esignEnabled): void {
$q->where('esign_status', 'signed')->whereOr(static function (Query $legacy) use ($esignEnabled): void {
$legacy->where('esign_required', 0);
if ($esignEnabled) {
$legacy->where('esign_status', '<>', 'legacy');
}
});
});
break;
case 'rejected':
$query->where('audit_status', '=', 2);
break;
default:
break;
}
}
private function buildFilteredQuery(): Query
{
$query = Prescription::where($this->searchWhere)->whereNull('delete_time');
$this->applyAuditFilter($query);
$this->applySourceFilter($query);
$this->applyVisibilityScope($query);
$this->applyCreatorIdsFilter($query);
$this->applyDataScopeByOwnerColumns($query, ['creator_id', 'assistant_id']);
return $query;
}
/**
* 来源:system=系统代开(is_system_auto=1),manual=手工(0 或空)
*/
private function applySourceFilter($query): void
{
$sf = (string) ($this->params['source_filter'] ?? '');
if ($sf === '' || $sf === 'all') {
return;
}
if ($sf === 'system') {
$query->where('is_system_auto', 1);
return;
}
if ($sf === 'manual') {
$query->where('is_system_auto', 0);
}
}
private function applyVisibilityScope($query): void
{
$query->where(function ($query) {
// 超级管理员可查看全部
if (!empty($this->adminInfo['root']) && (int) $this->adminInfo['root'] === 1) {
return;
}
// 检查是否属于可查看全部处方的角色
$manageAllRoles = config('project.prescription_library_manage_all_roles', [0, 3]);
$roleIds = array_values(array_unique(array_map('intval', $this->adminInfo['role_id'] ?? [])));
$canSeeAll = false;
foreach ($roleIds as $rid) {
if (in_array($rid, $manageAllRoles, true)) {
$canSeeAll = true;
break;
}
}
// 如果属于可查看全部的角色,不添加任何限制
if ($canSeeAll) {
return;
}
// 其他用户只能查看:共享的、自己创建的、自己是医助的、或指定给自己角色的
$adminId = $this->adminId;
$query->where(function ($q) use ($adminId, $roleIds) {
$q->whereOr('is_shared', '=', 1);
$q->whereOr('creator_id', '=', $adminId);
$q->whereOr('assistant_id', '=', $adminId);
foreach ($roleIds as $rid) {
if ($rid > 0) {
$q->whereOrRaw('FIND_IN_SET(?, `visible_role_ids`)', [(string) $rid]);
}
}
});
});
}
/**
* @notes 获取列表
*/
public function lists(): array
{
// 全局置顶:有业务订单且处方药材为空白/重复
$pageIds = $this->pageIds($this->buildFilteredQuery());
if ($pageIds === []) {
return [];
}
$rowsById = [];
$rows = Prescription::whereIn('id', $pageIds)
->withoutField(self::LIST_OMIT_FIELDS)
->select()
->toArray();
foreach ($rows as $row) {
$rowsById[(int) $row['id']] = $row;
}
$lists = [];
foreach ($pageIds as $pageId) {
if (isset($rowsById[$pageId])) {
$lists[] = $rowsById[$pageId];
}
}
$rxIds = array_column($lists, 'id');
$rxIds = array_map('intval', $rxIds);
$rejectedRx = [];
$bizRejectRemark = [];
$hasBizOrderRx = [];
$ordersByPrescription = [];
if ($rxIds !== []) {
$bizRejectRows = PrescriptionOrder::whereIn('prescription_id', $rxIds)
->where('prescription_audit_status', 2)
->whereNull('delete_time')
->whereNotIn('fulfillment_status', PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES)
->field(['prescription_id', 'prescription_audit_remark', 'id'])
->order('id', 'desc')
->select()
->toArray();
foreach ($bizRejectRows as $br) {
$pid = (int) ($br['prescription_id'] ?? 0);
if ($pid <= 0) {
continue;
}
$rejectedRx[$pid] = true;
if (!isset($bizRejectRemark[$pid])) {
$bizRejectRemark[$pid] = (string) ($br['prescription_audit_remark'] ?? '');
}
}
$orders = PrescriptionOrder::whereIn('prescription_id', $rxIds)
->whereNull('delete_time')
->field(['prescription_id', 'fulfillment_status', 'prescription_audit_status', 'payment_slip_audit_status'])
->select()->toArray();
foreach ($orders as $order) {
$prescriptionId = (int) $order['prescription_id'];
$ordersByPrescription[$prescriptionId][] = $order;
if (!in_array((int) $order['fulfillment_status'], PrescriptionOrder::RELEASED_PRESCRIPTION_STATUSES, true)) {
$hasBizOrderRx[$prescriptionId] = true;
}
}
}
// 获取医助姓名
$assistantIds = array_unique(array_filter(array_map('intval', array_column($lists, 'assistant_id'))));
$assistantNames = [];
if (!empty($assistantIds)) {
$assistantNames = \app\common\model\auth\Admin::whereIn('id', $assistantIds)
->column('name', 'id');
}
// 处理字段格式
$voidAccess = $lists === [] ? [] : PrescriptionLogic::getVoidAccess($this->adminId, $this->adminInfo);
$maySubmit = in_array($this->adminId, array_map('intval', array_column($lists, 'creator_id')), true)
&& PrescriptionLogic::canSubmitForReview($this->adminId, $this->adminInfo);
foreach ($lists as &$item) {
$rid = (int) $item['id'];
$item['can_void'] = empty($item['void_status'])
&& PrescriptionLogic::hasVoidAccess($item, $this->adminId, $this->adminInfo, $voidAccess)
&& (empty($ordersByPrescription[$rid]) || PrescriptionOrderLogic::voidBlockerForPrescription($rid) === null);
$item['can_restore_rejected'] = PrescriptionLogic::canRestoreRejected($item);
$item = PrescriptionLogic::withSigningStatus($item, $this->adminId, $maySubmit);
// 设置默认值
$item['usage_time'] = $item['usage_time'] ?? '饭前';
$item['usage_way'] = $item['usage_way'] ?? '温水送服';
$item['usage_notes'] = $item['usage_notes'] ?? '';
$item['usage_days'] = $item['usage_days'] ?? 7;
$item['is_shared'] = $item['is_shared'] ?? 0;
$item['is_system_auto'] = (int) ($item['is_system_auto'] ?? 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'] ?? ''));
$item['business_prescription_audit_rejected'] = !empty($rejectedRx[$rid]) ? 1 : 0;
$item['business_prescription_audit_remark'] = (string) ($bizRejectRemark[$rid] ?? '');
$item['has_prescription_order'] = !empty($hasBizOrderRx[$rid]) ? 1 : 0;
// 添加医助姓名
$assistantId = (int) ($item['assistant_id'] ?? 0);
$item['assistant_name'] = $assistantId > 0 ? ($assistantNames[$assistantId] ?? '') : '';
// 将 dietary_taboo 从逗号分隔的字符串转换为数组(前端需要数组格式)
if (!empty($item['dietary_taboo']) && is_string($item['dietary_taboo'])) {
$item['dietary_taboo'] = array_filter(explode(',', $item['dietary_taboo']));
} else {
$item['dietary_taboo'] = [];
}
}
return $lists;
}
/**
* @notes 获取数量
*/
public function count(): int
{
return $this->buildFilteredQuery()->count();
}
}