Files
zyt/server/app/common/service/assistantservice/AssistantServiceContext.php
T
2026-11-12 09:07:07 +08:00

157 lines
9.4 KiB
PHP

<?php
declare(strict_types=1);
namespace app\common\service\assistantservice;
use app\adminapi\logic\tcm\PatientAiReportLogic;
use DomainException;
use think\facade\Db;
/** 只聚合有来源与身份边界的服务文字,不读取完整临床病历或触发远程同步。 */
final class AssistantServiceContext
{
public static function build(int $diagnosisId, int $adminId, int $days = 30, int $assistantId = 0): array
{
if (!in_array($days, [7, 30, 90], true)) {
throw new DomainException('请选择 7、30 或 90 天的时间范围');
}
$diagnosis = AssistantServiceAccess::diagnosis($diagnosisId, $adminId);
$actor = AssistantServiceAccess::actor($adminId);
$visible = AssistantServiceAccess::visibleStaffIds($adminId, $actor);
if ($assistantId > 0) {
AssistantServiceAccess::assistant($assistantId, $adminId);
$visible = [$assistantId];
}
$patientId = (int) ($diagnosis['patient_id'] ?? 0);
$since = time() - $days * 86400;
$limit = max(1, (int) config('assistant_service.max_source_rows', 200));
$sources = [];
$coverage = [];
$manualQuery = Db::name('assistant_service_record')->where('diagnosis_id', $diagnosisId)
->where('patient_id', $patientId)->whereNull('delete_time')->where('occurred_at', '>=', $since);
if ($assistantId > 0) { $manualQuery->where('actor_id', $assistantId); }
$manual = $manualQuery
->order('occurred_at', 'asc')->order('id', 'asc')->limit($limit + 1)->lock(true)->select()->toArray();
foreach ($manual as $row) {
// 确认过转写不等于已核验历史服务人员;录入人不能冒充逐句发言人。
$sources[] = self::source('manual:' . $row['id'], 'manual', (string) $row['content'],
(int) $row['occurred_at'], 'unknown', 0,
$row['record_type'] === 'verified_transcript' && (bool) $row['speaker_confirmed']);
}
$coverage[] = self::coverage('manual', count($manual), '人工记录;已确认转写仍需逐句核对说话人与服务人员');
try {
$trackingQuery = Db::name('tracking_note')->where('diagnosis_id', $diagnosisId)->whereNull('delete_time')
->where('note_date', '>=', date('Y-m-d', $since));
if ($assistantId > 0) { $trackingQuery->where('admin_id', $assistantId); }
$tracking = $trackingQuery->order('note_date', 'asc')->order('id', 'asc')
->limit($limit + 1)->lock(true)->select()->toArray();
foreach ($tracking as $row) {
$sources[] = self::source('tracking:' . $row['id'], 'tracking', (string) $row['content'],
(int) strtotime((string) $row['note_date']), 'unknown', 0, false);
}
$coverage[] = self::coverage('tracking', count($tracking), '当前诊单跟踪备注;非逐字对话,不用于员工扣分');
} catch (\Throwable $e) {
$coverage[] = ['channel' => 'tracking', 'status' => 'unavailable', 'count' => 0, 'note' => '跟踪备注来源暂不可读'];
}
if ($patientId <= 0) {
$coverage[] = ['channel' => 'im', 'status' => 'unmapped', 'count' => 0, 'note' => '缺少可靠患者账号映射,未合并 IM'];
} else {
try {
$patientAccount = 'patient_' . $patientId;
$query = Db::name('tcm_im_chat_message')->where('patient_id', $patientId)->where('msg_type', 'text')
->where('msg_time', '>=', $since);
if ($visible !== null) {
$peers = array_map(static fn (int $id): string => 'doctor_' . $id, $visible);
// 同时检查 from/to,不能信历史 doctor_peer_account 单列。
$query->where(function ($q) use ($patientAccount, $peers): void {
$q->where(function ($q) use ($patientAccount, $peers): void {
$q->where('from_account', $patientAccount)->whereIn('to_account', $peers ?: ['__none__']);
})->whereOr(function ($q) use ($patientAccount, $peers): void {
$q->where('to_account', $patientAccount)->whereIn('from_account', $peers ?: ['__none__']);
});
});
} else {
$query->where(function ($q) use ($patientAccount): void {
$q->where('from_account', $patientAccount)->whereOr('to_account', $patientAccount);
});
}
$messages = $query->order('msg_time', 'asc')->order('id', 'asc')->limit($limit + 1)->lock(true)->select()->toArray();
if (count($messages) > $limit) {
throw new DomainException('来源数量超限,请缩小时间范围后重试', 413);
}
$peers = [];
foreach ($messages as $row) {
$peer = self::peerId($row, $patientAccount);
if ($peer > 0) { $peers[] = $peer; }
}
// 历史停用员工仍可归因,但数据库中不存在的账号不猜测身份。
$known = $peers ? array_map('intval', Db::name('admin')->whereIn('id', array_unique($peers))->column('id')) : [];
$imCount = 0;
foreach ($messages as $row) {
$peer = self::peerId($row, $patientAccount);
if ($peer <= 0 || !in_array($peer, $known, true) || ($visible !== null && !in_array($peer, $visible, true))) {
continue;
}
$service = (string) $row['from_account'] === 'doctor_' . $peer;
$sources[] = self::source('im:' . $row['id'], 'im', (string) $row['text'],
(int) $row['msg_time'], $service ? 'service' : 'patient', $service ? $peer : 0, true);
$imCount++;
}
$coverage[] = self::coverage('im', $imCount, '仅已归档、账号配对可靠且在员工权限内的纯文字;不代表完整历史');
} catch (DomainException $e) {
throw $e;
} catch (\Throwable $e) {
$coverage[] = ['channel' => 'im', 'status' => 'unavailable', 'count' => 0, 'note' => 'IM 归档暂不可读,未触发远程同步'];
}
}
$coverage[] = ['channel' => 'wecom', 'status' => 'not_connected', 'count' => 0, 'note' => '企微存档需独立核验授权与患者映射后接入'];
$coverage[] = ['channel' => 'audio', 'status' => 'not_connected', 'count' => 0, 'note' => '未核验音频不参与分析;可人工录入已核对转写'];
$sources = array_values(array_filter($sources, static fn (array $s): bool => $s['text'] !== ''));
usort($sources, static fn (array $a, array $b): int => [$a['occurred_at'], $a['id']] <=> [$b['occurred_at'], $b['id']]);
$characters = array_sum(array_map(static fn (array $s): int => mb_strlen($s['text']), $sources));
if (count($manual) > $limit || count($tracking ?? []) > $limit || count($sources) > $limit
|| $characters > max(1, (int) config('assistant_service.max_source_chars', 30000))) {
throw new DomainException('来源数量或文字超限,请缩小时间范围后重试;系统不会静默截断来源', 413);
}
$patient = ['diagnosis_id' => $diagnosisId, 'patient_id' => $patientId,
'patient_name' => (string) ($diagnosis['patient_name'] ?? ''), 'assistant_id' => (int) ($diagnosis['assistant_id'] ?? 0)];
$scope = [$diagnosisId, $patientId, $patient['assistant_id'], $adminId,
$actor['root'], $actor['role_id'], $actor['permissions'], $visible];
// 不改变未指定目标的历史哈希;新任务显式绑定质检对象。
if ($assistantId > 0) { $scope[2] = 0; $scope[] = $assistantId; }
return ['patient' => $patient, 'sources' => $sources, 'coverage' => $coverage, 'days' => $days,
'subject_admin_id' => $assistantId,
'source_hash' => self::hash($assistantId > 0 ? [$assistantId, $sources] : $sources),
'scope_hash' => self::hash($scope)];
}
private static function peerId(array $row, string $patient): int
{
$from = (string) ($row['from_account'] ?? '');
$to = (string) ($row['to_account'] ?? '');
$peer = $from === $patient ? $to : ($to === $patient ? $from : '');
return preg_match('/^doctor_([1-9][0-9]*)$/D', $peer, $matches) === 1 ? (int) $matches[1] : 0;
}
private static function source(string $id, string $channel, string $text, int $time, string $speaker, int $actor, bool $quality): array
{
$clean = PatientAiReportLogic::redactClinicalSource(['text' => $text]);
return ['id' => $id, 'channel' => $channel, 'text' => trim((string) $clean['text']), 'occurred_at' => $time,
'speaker' => $speaker, 'actor_admin_id' => $actor, 'quality_eligible' => $quality];
}
private static function coverage(string $channel, int $count, string $note): array
{
return ['channel' => $channel, 'status' => $count ? 'available' : 'empty', 'count' => $count, 'note' => $note];
}
private static function hash(array $value): string
{
return hash('sha256', json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
}
}