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

783 lines
44 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace app\common\service\assistantservice;
use DomainException;
use RuntimeException;
use think\facade\Db;
/** 员工侧聊天和通话转写的确定性预警。同一来源同一条规则只记一次,人工复核后才改变状态。 */
final class AssistantServiceAlert
{
public const VERSION = 1;
private const TABLE = 'assistant_service_alert';
/** 比草稿拦截更窄,避免把日常的“换药、停用”刷成高风险。 */
private const RULES = [
['code' => 'clinical_boundary', 'label' => '越界诊疗', 'severity' => 'high', 'patterns' => [
'/(?:诊断为|确诊为|辨证为|患有|患上|建议.{0,5}(?:服用|口服|注射|外用))/u',
'/(?:您|你|患者)(?:的病情)?(?:这是|就是|得了|患了|确实是).{0,16}(?:病|炎|癌|症|瘤|感染|证)/u',
'/(?:停药|加药|减药|加大剂量|减少剂量|调整剂量|调整药量|处方建议|推荐处方|开具处方)/u',
'/(?:每日|每天|每次|早晚|睡前).{0,12}(?:服|吃|注射).{0,8}(?:片|粒|丸|毫克|毫升|克|袋)/u',
'/(?:[0-90-9]+(?:\.[0-9]+)?\s*(?:mg|ml|μg|毫克|毫升)|服用.{0,12}[一二三四五六七八九十两\d]+(?:片|粒|丸|袋))/iu',
]],
['code' => 'cure_promise', 'label' => '疗效承诺', 'severity' => 'high', 'patterns' => [
'/(?:包治|根治|保证治愈|能治愈|可以治愈|保证.{0,12}(?:好转|康复|疗效|有效)|(?:一定|肯定|必定).{0,8}(?:康复|治好|好转|有效)|无副作用|百分之百.{0,8}有效|100%.{0,8}有效)/u',
'/guaranteed.{0,12}(?:cure|recovery)/iu',
]],
['code' => 'off_platform', 'label' => '脱离平台', 'severity' => 'high', 'patterns' => [
'/(?:加我微信|加个微信|加微信|私人微信|个人微信|微信号|vx号|v信|私下转账|私下付款|线下收款|转账给我|收款码|别走平台|不要走平台)/iu',
]],
['code' => 'privacy_ask', 'label' => '不当索取', 'severity' => 'medium', 'patterns' => [
'/(?:银行卡|身份证号|身份证照片|身份证正反面|验证码发给我)/u',
]],
['code' => 'hostility', 'label' => '冲突用语', 'severity' => 'low', 'patterns' => [
'/(?:傻逼|傻b|脑残|滚蛋|废物|有病吧)/iu',
]],
['code' => 'inappropriate_wording', 'label' => '不合适用词', 'severity' => 'medium', 'patterns' => []],
];
private string $directory;
/** @var callable():int */
private $clock;
/** @var callable(string,int):array|null */
private $wecomFetch;
/** @var callable(string,array,string,string,array,array):array|null */
private $wording;
/** @param callable(string,int):array|null $wecomFetch @param callable(string,array,string,string,array,array):array|null $wording */
public function __construct(?string $directory = null, ?callable $clock = null, ?callable $wecomFetch = null, ?callable $wording = null)
{
$this->directory = rtrim($directory ?? root_path('runtime') . 'assistant_service_alert', '/\\');
$this->clock = $clock ?? static fn (): int => time();
$this->wecomFetch = $wecomFetch;
$this->wording = $wording;
}
public static function wecomDirectory(int $adminId): array
{
try {
return self::buildWecomDirectory($adminId);
} catch (\PDOException $e) {
throw new DomainException('企微会话暂时读不出来,请稍后重试');
} catch (RuntimeException $e) {
if ($e->getMessage() !== 'WECOM_ARCHIVE') { throw $e; }
throw new DomainException('企微会话暂时读不出来,请稍后重试');
}
}
private static function buildWecomDirectory(int $adminId): array
{
$actor = AssistantServiceAccess::actor($adminId);
$accounts = self::archiveAccounts();
$staff = [];
foreach (AssistantServiceAccess::assistantRows($adminId, $actor) as $row) {
$count = 0;
foreach ($accounts as $account) {
if ($account['name'] !== '' && $account['name'] === $row['name']) { $count += $account['conversations']; }
}
$wechat = trim((string) Db::name('admin')->where('id', $row['id'])->value('work_wechat_userid'));
foreach ($accounts as $account) {
if ($wechat !== '' && $account['external_id'] === $wechat) { $count += $account['conversations']; }
}
$staff[] = $row + ['conversations' => $count];
}
$unmapped = [];
if (AssistantServiceAccess::visibleStaffIds($adminId, $actor) === null) {
$names = array_column($staff, 'name');
$wechatIds = array_map('strval', Db::name('admin')->whereIn('id', array_column($staff, 'id') ?: [0])->column('work_wechat_userid'));
foreach ($accounts as $account) {
if (!in_array($account['name'], $names, true) && !in_array($account['external_id'], $wechatIds, true)) { $unmapped[] = $account; }
}
}
return ['ready' => self::archiveReady(), 'staff' => $staff, 'accounts' => $unmapped];
}
public static function wecomChats(array $p, int $adminId): array
{
$conversations = [];
try {
$actor = AssistantServiceAccess::actor($adminId);
$allowed = self::allowedAccounts($p, $adminId, $actor);
foreach ($allowed as $externalId) {
foreach (self::archiveConversations($externalId) as $row) { $conversations[] = $row + ['account' => $externalId]; }
}
} catch (\PDOException $e) {
throw new DomainException('企微会话暂时读不出来,请稍后重试');
} catch (RuntimeException $e) {
if ($e->getMessage() !== 'WECOM_ARCHIVE') { throw $e; }
throw new DomainException('企微会话暂时读不出来,请稍后重试');
}
return ['conversations' => $conversations];
}
public static function wecomMessages(array $p, int $adminId): array
{
try {
$actor = AssistantServiceAccess::actor($adminId);
$allowed = self::allowedAccounts($p, $adminId, $actor);
$thread = self::archiveMessages((string) $p['conversation_id']);
} catch (\PDOException $e) {
throw new DomainException('企微会话暂时读不出来,请稍后重试');
} catch (RuntimeException $e) {
if ($e->getMessage() !== 'WECOM_ARCHIVE') { throw $e; }
throw new DomainException('企微会话暂时读不出来,请稍后重试');
}
if ($thread['account'] === '' || !in_array($thread['account'], $allowed, true)) {
throw new DomainException('会话不存在或不在当前可见范围');
}
return ['messages' => $thread['messages']];
}
/** @return list<string> */
private static function allowedAccounts(array $p, int $adminId, array $actor): array
{
$account = trim((string) ($p['account'] ?? ''));
if ($account !== '') {
if (AssistantServiceAccess::visibleStaffIds($adminId, $actor) !== null) { throw new DomainException('无权查看未归属的企微账号'); }
foreach (self::archiveAccounts() as $row) {
if ($row['external_id'] === $account) { return [$account]; }
}
throw new DomainException('企微账号不存在');
}
$staffId = (int) ($p['assistant_id'] ?? 0);
$visible = false;
foreach (AssistantServiceAccess::assistantRows($adminId, $actor) as $row) {
if ($row['id'] === $staffId) { $visible = true; break; }
}
if (!$visible) { throw new DomainException('医助不存在、已停用或不在当前员工范围'); }
$name = trim((string) Db::name('admin')->where('id', $staffId)->value('name'));
$wechat = trim((string) Db::name('admin')->where('id', $staffId)->value('work_wechat_userid'));
$allowed = [];
foreach (self::archiveAccounts() as $row) {
if (($name !== '' && $row['name'] === $name) || ($wechat !== '' && $row['external_id'] === $wechat)) { $allowed[] = $row['external_id']; }
}
return array_values(array_unique($allowed));
}
public static function listing(array $p, int $adminId): array
{
$actor = AssistantServiceAccess::actor($adminId);
$page = ['lists' => [], 'count' => 0, 'page_no' => $p['page_no'], 'page_size' => $p['page_size'],
'schema_ready' => self::alertReady(), 'summary' => ['open' => 0, 'high_open' => 0, 'im_open' => 0, 'call_open' => 0, 'assistant_open' => 0, 'doctor_open' => 0],
'scan' => self::scanStatus(), 'coverage' => self::coverage(), 'empty_reason' => ''];
if (!$page['schema_ready']) { return $page; }
$base = self::scoped($adminId, $actor);
$page['summary'] = [
'open' => self::count(clone $base, ['a.status' => 'open']),
'high_open' => self::count(clone $base, ['a.status' => 'open', 'a.severity' => 'high']),
'im_open' => self::count(clone $base, ['a.status' => 'open', 'a.channel' => 'im']),
'call_open' => self::count(clone $base, ['a.status' => 'open', 'a.channel' => 'call']),
'assistant_open' => self::countRole(clone $base, 'assistant'),
'doctor_open' => self::countRole(clone $base, 'doctor'),
];
$query = clone $base;
if ($p['status'] !== 'all') { $query->where('a.status', $p['status']); }
if ($p['severity'] !== 'all') { $query->where('a.severity', $p['severity']); }
self::applyRole($query, (string) ($p['role'] ?? 'all'));
if ($p['keyword'] !== '') { self::keyword($query, $p['keyword'], $adminId, $actor); }
$count = (int) (clone $query)->count('a.id');
$rows = $query->field('a.*')->order('a.occurred_at', 'desc')->order('a.id', 'desc')
->page($p['page_no'], $p['page_size'])->select()->toArray();
$names = self::names(array_map(static fn (array $row): int => (int) $row['patient_id'], $rows), $adminId, $actor);
$people = self::people(array_map(static fn (array $row): int => (int) $row['staff_admin_id'], $rows), $adminId);
$page['count'] = $count;
$page['empty_reason'] = $count === 0 && $p['status'] === 'open' && $p['severity'] === 'all' && $p['keyword'] === ''
? '已检查员工发出的聊天文字,以及通话转写里员工这一侧的发言。当前范围没有待处理预警。'
: '';
$page['lists'] = array_map(static function (array $row) use ($people, $names): array {
$person = $people[(int) $row['staff_admin_id']] ?? ['id' => (int) $row['staff_admin_id'], 'name' => '', 'is_self' => false, 'assistant' => false, 'role_name' => '员工'];
if ($person['name'] === '' && trim((string) ($row['external_staff'] ?? '')) !== '') {
$person['name'] = (string) $row['external_staff'];
$person['role_name'] = '企微';
}
$patientId = (int) $row['patient_id'];
$patientName = (string) ($names[$patientId]['patient_name'] ?? '');
if ($patientName === '') { $patientName = (string) ($row['external_patient'] ?? ''); }
return ['id' => (int) $row['id'], 'staff' => $person, 'patient_id' => $patientId,
'patient_name' => $patientName,
'diagnosis_id' => (int) ($names[$patientId]['id'] ?? $row['diagnosis_id'] ?? 0), 'channel' => (string) $row['channel'],
'rule_code' => (string) $row['rule_code'], 'rule_label' => self::label((string) $row['rule_code']),
'rule_version' => (int) $row['rule_version'], 'severity' => (string) $row['severity'],
'snippet' => (string) $row['snippet'], 'status' => (string) $row['status'],
'occurred_at' => (int) $row['occurred_at'], 'review_note' => (string) $row['review_note'],
'reviewed_at' => (int) $row['reviewed_at']];
}, $rows);
return $page;
}
public static function review(array $p, int $adminId): array
{
$actor = AssistantServiceAccess::actor($adminId, 'reviewQuality');
if (!self::alertReady()) { throw new DomainException('预警表尚未就绪,请先执行模块迁移'); }
$row = Db::name(self::TABLE)->where('id', $p['id'])->lock(true)->find();
if (!$row || !self::visible($row, $adminId, $actor)) { throw new DomainException('预警不存在或已不在当前范围'); }
$now = time();
Db::name(self::TABLE)->where('id', (int) $row['id'])->update(['status' => $p['status'], 'reviewer_id' => $adminId,
'review_note' => $p['note'], 'reviewed_at' => $now, 'updated_at' => $now]);
return ['id' => (int) $row['id'], 'status' => $p['status']];
}
public function tick(): array
{
$counts = ['scanned' => 0, 'created' => 0];
if (!(bool) config('assistant_service.alert_enabled', false)) { return $counts + ['state' => 'disabled']; }
if (!self::alertReady() || !self::imReady()) { return $counts + ['state' => 'unavailable']; }
$handle = null;
$state = [];
try {
if (!is_dir($this->directory) && !@mkdir($this->directory, 0700, true) && !is_dir($this->directory)) { throw new RuntimeException('ALERT_STORAGE'); }
$handle = @fopen($this->directory . DIRECTORY_SEPARATOR . 'scan.lock', 'c+b');
if (!$handle) { throw new RuntimeException('ALERT_STORAGE'); }
if (!flock($handle, LOCK_EX | LOCK_NB)) { fclose($handle); $handle = null; return $counts + ['state' => 'waiting']; }
$now = ($this->clock)();
$state = $this->readState();
if ((int) ($state['source_version'] ?? 0) < 2) {
$state['cursor'] = 0;
$state['call_cursor'] = 0;
$state['next_scan_at'] = 0;
}
if ((int) ($state['source_version'] ?? 0) < 3) {
$state['wecom_cursor'] = '';
$state['source_version'] = 3;
$state['next_scan_at'] = 0;
}
$wording = $this->analyzeWording($state, $now);
$counts['created'] += $wording['created'];
if ((int) ($state['next_scan_at'] ?? 0) > $now && ($state['state'] ?? '') !== 'error') {
if ($wording['wrote']) { $this->writeState($state); }
return $counts + ['state' => 'waiting'];
}
$limit = max(1, min(500, (int) config('assistant_service.alert_batch_size', 200)));
$speakers = self::speakers();
$this->scanMessages($state, $speakers, $now, $limit, $counts);
$this->scanCalls($state, $speakers, $now, $limit, $counts);
$this->scanWecom($state, $speakers, $now, $limit, $counts);
$state['last_scan_at'] = $now;
$state['next_scan_at'] = $now + self::interval();
$state['state'] = 'ready';
$state['rule_version'] = self::VERSION;
$this->writeState($state);
return $counts + ['state' => 'ready'];
} catch (\Throwable $e) {
try {
if (is_resource($handle)) {
$state['state'] = 'error';
$state['next_scan_at'] = 0;
$this->writeState($state);
}
} catch (\Throwable $ignored) {}
return $counts + ['state' => 'error'];
} finally { if (is_resource($handle)) { flock($handle, LOCK_UN); fclose($handle); } }
}
/** @param array<string,mixed> $state @param array<int,string> $speakers @param array{scanned:int,created:int} $counts */
private function scanMessages(array &$state, array $speakers, int $now, int $limit, array &$counts): void
{
for ($round = 0; $round < 100; $round++) {
$messages = Db::name('tcm_im_chat_message')->where('id', '>', (int) $state['cursor'])->where('msg_type', 'text')
->field('id,patient_id,diagnosis_id,from_account,to_account,msg_type,text,msg_time')
->order('id', 'asc')->limit($limit)->select()->toArray();
if (!$messages) { return; }
foreach ($messages as $message) {
$counts['scanned']++;
$state['cursor'] = (int) $message['id'];
$staffId = self::staffId((string) $message['from_account']);
$patientId = (int) $message['patient_id'];
$text = trim((string) $message['text']);
if ($staffId <= 0 || $patientId <= 0 || (int) $message['msg_time'] <= 0 || $text === ''
|| (string) $message['to_account'] !== 'patient_' . $patientId) { continue; }
$this->store('im', (int) $message['id'], $staffId, $patientId, max(0, (int) ($message['diagnosis_id'] ?? 0)),
(int) $message['msg_time'], $text, $speakers, $now, $counts);
}
if (count($messages) < $limit) { return; }
}
}
/** @param array<string,mixed> $state @param array<int,string> $speakers @param array{scanned:int,created:int} $counts */
private function scanCalls(array &$state, array $speakers, int $now, int $limit, array &$counts): void
{
if (!self::callReady()) { return; }
for ($round = 0; $round < 100; $round++) {
$segments = Db::name('tcm_call_transcript_segment')->where('id', '>', (int) ($state['call_cursor'] ?? 0))
->where('speaker_role', 'doctor')
->field('id,call_record_id,speaker_user_id,speaker_role,text,create_time')
->order('id', 'asc')->limit($limit)->select()->toArray();
if (!$segments) { return; }
$callIds = array_values(array_unique(array_map(static fn (array $row): int => (int) $row['call_record_id'], $segments)));
$calls = [];
foreach (Db::name('tcm_call_record')->whereIn('id', $callIds)->whereNull('delete_time')
->field('id,diagnosis_id,caller_type,callee_id,callee_type,start_time')->select()->toArray() as $call) {
$calls[(int) $call['id']] = $call;
}
foreach ($segments as $segment) {
$counts['scanned']++;
$state['call_cursor'] = (int) $segment['id'];
$call = $calls[(int) $segment['call_record_id']] ?? null;
if (!$call) { continue; }
$patientId = (string) $call['callee_type'] === 'patient' ? (int) $call['callee_id']
: ((string) $call['caller_type'] === 'patient' ? (int) $call['caller_id'] : 0);
$occurred = (int) $segment['create_time'] > 0 ? (int) $segment['create_time'] : (int) $call['start_time'];
$this->store('call', (int) $segment['id'], self::staffId((string) $segment['speaker_user_id']), $patientId,
max(0, (int) $call['diagnosis_id']), $occurred, trim((string) $segment['text']), $speakers, $now, $counts);
}
if (count($segments) < $limit) { return; }
}
}
/** @param array<string,mixed> $state @param array<int,string> $speakers @param array{scanned:int,created:int} $counts */
private function scanWecom(array &$state, array $speakers, int $now, int $limit, array &$counts): void
{
$cursor = (string) ($state['wecom_cursor'] ?? '');
for ($round = 0; $round < 100; $round++) {
$page = $this->wecomPage($cursor, $limit);
if (empty($page['configured'])) { return; }
foreach (is_array($page['items'] ?? null) ? $page['items'] : [] as $item) {
if (!is_array($item)) { continue; }
$counts['scanned']++;
$messageId = trim((string) ($item['id'] ?? ''));
$patientId = (int) ($item['patient_id'] ?? 0);
$sourceKey = $messageId . ':' . $patientId;
if ($messageId === '' || strlen($sourceKey) > 80) { continue; }
$occurred = (int) ($item['sent_at_epoch'] ?? 0);
if ($occurred <= 0) { $occurred = self::epoch((string) ($item['sent_at'] ?? '')); }
$this->store('wecom', 0, (int) ($item['zyt_user_id'] ?? 0), $patientId,
max(0, (int) ($item['diagnosis_id'] ?? 0)), $occurred,
trim((string) ($item['content'] ?? '')), $speakers, $now, $counts, $sourceKey,
trim((string) ($item['staff_name'] ?? '')), trim((string) ($item['patient_name'] ?? '')));
}
$next = (string) ($page['next_cursor'] ?? '');
if ($next !== '') { $cursor = $next; $state['wecom_cursor'] = $cursor; }
if (empty($page['has_more'])) { return; }
}
}
/** @return array{configured:bool,items:array,next_cursor:string,has_more:bool} */
private function wecomPage(string $cursor, int $limit): array
{
if ($this->wecomFetch) {
$page = ($this->wecomFetch)($cursor, $limit);
return is_array($page) ? $page + ['configured' => true, 'items' => $page['items'] ?? [], 'next_cursor' => (string) ($page['next_cursor'] ?? ''), 'has_more' => (bool) ($page['has_more'] ?? false)] : ['configured' => false, 'items' => [], 'next_cursor' => $cursor, 'has_more' => false];
}
if (WecomArchiveSqlite::configured()) { return WecomArchiveSqlite::page($cursor, $limit); }
return WecomArchiveHttp::page($cursor, $limit);
}
private static function archiveReady(): bool
{
return WecomArchiveSqlite::configured() || WecomArchiveHttp::configured();
}
/** @return list<array{external_id:string,name:string,conversations:int}> */
private static function archiveAccounts(): array
{
if (WecomArchiveSqlite::configured()) { return WecomArchiveSqlite::accounts(); }
return WecomArchiveHttp::configured() ? WecomArchiveHttp::accounts() : [];
}
/** @return list<array{id:string,name:string,conversation_type:string,last_message_at:string,message_count:int,preview:string}> */
private static function archiveConversations(string $externalId): array
{
if (WecomArchiveSqlite::configured()) { return WecomArchiveSqlite::conversations($externalId); }
return WecomArchiveHttp::configured() ? WecomArchiveHttp::conversations($externalId) : [];
}
/** @return array{account:string,messages:list<array{id:string,sent_at:string,direction:string,message_type:string,sender_name:string,content:string}>} */
private static function archiveMessages(string $conversationId): array
{
if (WecomArchiveSqlite::configured()) { return WecomArchiveSqlite::messages($conversationId); }
return WecomArchiveHttp::configured() ? WecomArchiveHttp::messages($conversationId) : ['account' => '', 'messages' => []];
}
private static function epoch(string $value): int
{
if ($value === '') { return 0; }
$parsed = strtotime($value);
return $parsed === false ? 0 : $parsed;
}
/** @param array<int,string> $speakers @param array{scanned:int,created:int} $counts */
private function store(string $channel, int $sourceId, int $staffId, int $patientId, int $diagnosisId, int $occurredAt, string $text, array $speakers, int $now, array &$counts, string $sourceKey = '', string $staffName = '', string $patientName = ''): void
{
$staffName = mb_substr($staffName, 0, 64);
$patientName = mb_substr($patientName, 0, 64);
if ($occurredAt <= 0 || $text === '' || ($sourceId <= 0 && $sourceKey === '')) { return; }
if ($staffId > 0 && !isset($speakers[$staffId])) { return; }
if ($staffId <= 0 && $staffName === '') { return; }
if ($patientId <= 0 && $patientName === '') { return; }
foreach (self::hits($text) as $hit) {
$identity = ['channel' => $channel, 'source_id' => $sourceId, 'source_key' => $sourceKey, 'rule_code' => $hit['code']];
if (Db::name(self::TABLE)->where($identity)->find()) { continue; }
Db::name(self::TABLE)->insert($identity + ['staff_admin_id' => max(0, $staffId), 'patient_id' => max(0, $patientId),
'diagnosis_id' => $diagnosisId, 'external_staff' => $staffName, 'external_patient' => $patientName,
'rule_version' => self::VERSION, 'severity' => $hit['severity'],
'snippet' => $hit['snippet'], 'status' => 'open', 'reviewer_id' => 0, 'review_note' => '',
'reviewed_at' => 0, 'occurred_at' => $occurredAt, 'created_at' => $now, 'updated_at' => $now]);
$counts['created']++;
}
}
/** @return array<int,array{code:string,label:string,severity:string,snippet:string}> */
private static function hits(string $text): array
{
if (mb_strlen($text) > 30000) { $text = mb_substr($text, 0, 30000); }
$found = [];
foreach (self::RULES as $rule) {
foreach ($rule['patterns'] as $pattern) {
if (preg_match($pattern, $text, $match) !== 1) { continue; }
$found[] = ['code' => $rule['code'], 'label' => $rule['label'], 'severity' => $rule['severity'],
'snippet' => self::snippet($text, (string) $match[0])];
break;
}
}
return $found;
}
private static function snippet(string $text, string $match): string
{
$pos = mb_strpos($text, $match);
$start = max(0, ($pos === false ? 0 : $pos) - 12);
$slice = trim(mb_substr($text, $start, 80));
return $slice !== '' ? $slice : mb_substr($match, 0, 80);
}
private static function staffId(string $account): int
{
if (!preg_match('/\Adoctor_([1-9][0-9]{0,17})\z/', $account, $match)) { return 0; }
$id = (int) $match[1];
return $account === 'doctor_' . $id ? $id : 0;
}
/** @return array<int,string> */
private static function speakers(): array
{
$rows = Db::name('admin')->where('root', 0)->whereNull('delete_time')->column('name', 'id');
$result = [];
foreach ($rows as $id => $name) { $result[(int) $id] = (string) $name; }
return $result;
}
/** @param list<int> $ids @return array<int,array{id:int,name:string,is_self:bool,assistant:bool,role_name:string}> */
private static function people(array $ids, int $viewerId): array
{
$ids = array_values(array_unique(array_filter(array_map('intval', $ids))));
if (!$ids) { return []; }
$names = Db::name('admin')->whereIn('id', $ids)->column('name', 'id');
$links = Db::name('admin_role')->whereIn('admin_id', $ids)->field('admin_id,role_id')->select()->toArray();
$roleIds = array_values(array_unique(array_map(static fn (array $row): int => (int) $row['role_id'], $links)));
$roles = $roleIds ? Db::name('system_role')->whereIn('id', $roleIds)->whereNull('delete_time')->column('name', 'id') : [];
$byAdmin = [];
foreach ($links as $link) {
$roleId = (int) $link['role_id'];
if (!array_key_exists($roleId, $roles)) { continue; }
$byAdmin[(int) $link['admin_id']][$roleId] = trim((string) $roles[$roleId]);
}
$people = [];
foreach ($ids as $id) {
$assigned = $byAdmin[$id] ?? [];
$assistant = false;
$doctor = false;
$manager = false;
foreach ($assigned as $roleId => $name) {
if ($roleId === 2 || $name === '医助') { $assistant = true; }
if ($roleId === 1 || $name === '医生') { $doctor = true; }
if (in_array($roleId, [3, 7, 8], true)) { $manager = true; }
}
$label = $assistant && !$manager ? '医助' : ($doctor ? '医生' : (reset($assigned) ?: '员工'));
$people[$id] = ['id' => $id, 'name' => (string) ($names[$id] ?? ''), 'is_self' => $id === $viewerId,
'assistant' => $assistant && !$manager, 'role_name' => is_string($label) && $label !== '' ? $label : '员工'];
}
return $people;
}
private static function scoped(int $adminId, array $actor)
{
$sql = AssistantServiceAccess::patientQuery($adminId, $actor)->distinct(true)->field('d.patient_id')->buildSql();
$query = Db::name(self::TABLE)->alias('a');
if (AssistantServiceAccess::visibleStaffIds($adminId, $actor) !== null) {
return $query->whereRaw('a.patient_id IN ' . $sql);
}
return $query->where(static function ($nested) use ($sql): void {
$nested->whereRaw('a.patient_id IN ' . $sql)->whereOr(static function ($open): void {
$open->where('a.patient_id', 0)->where('a.channel', 'wecom');
});
});
}
private static function count($query, array $where): int
{
foreach ($where as $field => $value) { $query->where($field, $value); }
return (int) $query->count('a.id');
}
private static function countRole($query, string $role): int
{
$query->where('a.status', 'open');
self::applyRole($query, $role);
return (int) $query->count('a.id');
}
/** @param \think\db\Query $query */
private static function applyRole($query, string $role): void
{
if (!in_array($role, ['assistant', 'doctor'], true)) { return; }
$ids = self::staffIdsForRole($role);
if (!$ids) { $query->whereRaw('1=0'); return; }
$query->whereIn('a.staff_admin_id', $ids);
}
/** @return list<int> */
private static function staffIdsForRole(string $role): array
{
$roles = Db::name('system_role')->whereNull('delete_time')->field('id,name')->select()->toArray();
$assistantRoles = [];
$doctorRoles = [];
foreach ($roles as $row) {
$id = (int) $row['id'];
$name = trim((string) $row['name']);
if ($id === 2 || $name === '医助') { $assistantRoles[] = $id; }
if ($id === 1 || $name === '医生') { $doctorRoles[] = $id; }
}
$assistants = $assistantRoles ? array_map('intval', Db::name('admin_role')->whereIn('role_id', $assistantRoles)->column('admin_id')) : [];
$doctors = $doctorRoles ? array_map('intval', Db::name('admin_role')->whereIn('role_id', $doctorRoles)->column('admin_id')) : [];
$managers = array_map('intval', Db::name('admin_role')->whereIn('role_id', [3, 7, 8])->column('admin_id'));
$assistants = array_values(array_unique(array_diff($assistants, $managers)));
$doctors = array_values(array_unique(array_diff($doctors, $assistants, $managers)));
return $role === 'assistant' ? $assistants : $doctors;
}
private static function keyword($query, string $keyword, int $adminId, array $actor): void
{
$like = '%' . addcslashes($keyword, '%_\\') . '%';
$nameIds = array_values(array_unique(array_map('intval', Db::name('admin')->where('root', 0)->whereLike('name', $like)->column('id'))));
$patientIds = array_values(array_unique(array_map('intval', AssistantServiceAccess::patientQuery($adminId, $actor)
->whereLike('d.patient_name', $like)->column('d.patient_id'))));
$query->where(static function ($nested) use ($nameIds, $patientIds, $like): void {
$started = false;
if ($nameIds) { $nested->whereIn('a.staff_admin_id', $nameIds); $started = true; }
if ($patientIds) {
$started ? $nested->whereOr('a.patient_id', 'in', $patientIds) : $nested->whereIn('a.patient_id', $patientIds);
$started = true;
}
$started ? $nested->whereOr('a.external_staff', 'like', $like) : $nested->where('a.external_staff', 'like', $like);
$nested->whereOr('a.external_patient', 'like', $like);
});
}
/** @return array<int,array{id:int,patient_name:string}> */
private static function names(array $patientIds, int $adminId, array $actor): array
{
$patientIds = array_values(array_unique(array_filter(array_map('intval', $patientIds))));
if (!$patientIds) { return []; }
$rows = AssistantServiceAccess::patientQuery($adminId, $actor)->whereIn('d.patient_id', $patientIds)
->field('d.id,d.patient_id,d.patient_name')->order('d.id', 'desc')->select()->toArray();
$names = [];
foreach ($rows as $row) {
$patientId = (int) $row['patient_id'];
if (!isset($names[$patientId])) { $names[$patientId] = ['id' => (int) $row['id'], 'patient_name' => (string) $row['patient_name']]; }
}
return $names;
}
private static function visible(array $row, int $adminId, array $actor): bool
{
if ((int) $row['patient_id'] === 0 && (string) $row['channel'] === 'wecom') {
return AssistantServiceAccess::visibleStaffIds($adminId, $actor) === null;
}
return (bool) AssistantServiceAccess::patientQuery($adminId, $actor)->where('d.patient_id', (int) $row['patient_id'])->find();
}
private static function label(string $code): string
{
foreach (self::RULES as $rule) { if ($rule['code'] === $code) { return $rule['label']; } }
return '未命名规则';
}
private static function alertReady(): bool
{
return self::readable(self::TABLE, 'id,staff_admin_id,patient_id,diagnosis_id,channel,source_id,source_key,external_staff,external_patient,rule_code,rule_version,severity,snippet,status,reviewer_id,review_note,reviewed_at,occurred_at,created_at,updated_at');
}
private static function imReady(): bool
{
return self::readable('tcm_im_chat_message', 'id,patient_id,diagnosis_id,from_account,to_account,msg_type,text,msg_time');
}
private static function readable(string $table, string $fields): bool
{
try { Db::name($table)->field($fields)->whereRaw('1=0')->select(); return true; }
catch (\Throwable $e) { return false; }
}
private static function coverage(): array
{
$callReady = self::callReady();
$wecom = self::wecomStatus();
return [
['channel' => 'im', 'status' => self::imReady() ? 'available' : 'unavailable', 'note' => '员工账号发出的已归档文字,医生和医助都检查'],
['channel' => 'call', 'status' => $callReady ? 'available' : 'not_connected',
'note' => $callReady ? '通话转写只记员工这一侧的发言;没有转写的通话不记为已检查' : '通话转写尚未接入,有录音也不计为已检查'],
['channel' => 'wecom', 'status' => $wecom['status'], 'note' => $wecom['note']],
];
}
/** @return array{status:string,note:string} */
private static function wecomStatus(): array
{
if (WecomArchiveSqlite::configured()) { return ['status' => 'available', 'note' => '本地企微归档只记员工发出的文字;对不上患者时仍保留会话名']; }
if (WecomArchiveHttp::configured()) { return ['status' => 'available', 'note' => '线上企微归档只记员工发出的文字;对不上患者时仍保留会话名']; }
$base = rtrim((string) config('assistant_service.wecom_archive_base_url', ''), '/');
if ($base !== '') { return ['status' => 'not_connected', 'note' => '企微聊天归档地址已填写,还缺连接令牌']; }
return ['status' => 'not_connected', 'note' => '企微聊天归档尚未接入'];
}
private static function callReady(): bool
{
return self::readable('tcm_call_transcript_segment', 'id,call_record_id,speaker_user_id,speaker_role,text,create_time')
&& self::readable('tcm_call_record', 'id,diagnosis_id,caller_type,callee_id,callee_type,start_time,delete_time');
}
private static function scanStatus(): array
{
$enabled = (bool) config('assistant_service.alert_enabled', false);
if (!self::alertReady()) { return ['enabled' => $enabled, 'state' => 'unavailable', 'last_scan_at' => 0, 'reason' => '预警表尚未就绪,请先执行模块迁移']; }
if (!$enabled) { return ['enabled' => false, 'state' => 'disabled', 'last_scan_at' => 0, 'reason' => '预警扫描尚未开启']; }
try {
$directory = rtrim(root_path('runtime') . 'assistant_service_alert', '/\\');
$path = $directory . DIRECTORY_SEPARATOR . 'scan.json';
if (!is_file($path)) { return ['enabled' => true, 'state' => 'waiting', 'last_scan_at' => 0, 'reason' => '尚未完成首次扫描']; }
$json = file_get_contents($path);
$state = is_string($json) ? json_decode($json, true) : null;
if (!is_array($state)) { return ['enabled' => true, 'state' => 'error', 'last_scan_at' => 0, 'reason' => '最近一次扫描状态无法读取']; }
$ready = ($state['state'] ?? '') === 'ready';
return ['enabled' => true, 'state' => $ready ? 'ready' : (string) ($state['state'] ?? 'error'),
'last_scan_at' => (int) ($state['last_scan_at'] ?? 0),
'reason' => $ready ? '' : '最近一次扫描未完成,请查看扫描进程'];
} catch (\Throwable $e) {
return ['enabled' => true, 'state' => 'error', 'last_scan_at' => 0, 'reason' => '最近一次扫描状态无法读取'];
}
}
private static function interval(): int
{
return max(5, min(3600, (int) config('assistant_service.alert_interval_seconds', 60)));
}
private function readState(): array
{
$path = $this->directory . DIRECTORY_SEPARATOR . 'scan.json';
if (!is_file($path)) { return []; }
$handle = @fopen($path, 'rb');
if (!$handle) { throw new RuntimeException('ALERT_STORAGE'); }
try {
if (!flock($handle, LOCK_SH)) { throw new RuntimeException('ALERT_STORAGE'); }
$json = stream_get_contents($handle, 16385);
if (!is_string($json) || strlen($json) > 16384) { throw new RuntimeException('ALERT_STORAGE'); }
$state = json_decode($json, true, 16, JSON_THROW_ON_ERROR);
if (!is_array($state)) { throw new RuntimeException('ALERT_STORAGE'); }
return $state;
} finally { flock($handle, LOCK_UN); fclose($handle); }
}
/** @return array{created:int,wrote:bool} */
private function analyzeWording(array &$state, int $now): array
{
$idle = ['created' => 0, 'wrote' => false];
if (!(bool) config('assistant_service.wecom_wording_enabled', false) || !self::archiveReady()) { return $idle; }
if ((int) ($state['wording_next_at'] ?? 0) > $now) { return $idle; }
$interval = max(60, min(86400, (int) config('assistant_service.wecom_wording_interval_seconds', 600)));
$batch = max(1, min(20, (int) config('assistant_service.wecom_wording_batch_size', 6)));
$state['wording_next_at'] = $now + $interval;
$page = $this->wecomPage((string) ($state['wording_cursor'] ?? ''), $batch);
if (!$page['items']) {
if (($page['next_cursor'] ?? '') !== '') { $state['wording_cursor'] = (string) $page['next_cursor']; }
return ['created' => 0, 'wrote' => true];
}
$payload = [];
foreach ($page['items'] as $item) {
$text = trim((string) ($item['content'] ?? ''));
if ($text !== '') { $payload[] = ['id' => (string) $item['id'], 'text' => mb_substr($text, 0, 500)]; }
}
$call = $this->wording ?? [\app\common\service\DifyChatService::class, 'chat'];
try {
$upstream = $call((string) config('assistant_service.profile', 'qwen'), [], self::wordingPrompt($payload), 'assistant-wecom-wording', [], [
'knowledge_mode' => 'evidence', 'timeout' => (int) config('assistant_service.timeout', 120),
]);
} catch (\Throwable $e) {
return ['created' => 0, 'wrote' => true];
}
if (!is_array($upstream) || ($upstream['ok'] ?? null) !== true) { return ['created' => 0, 'wrote' => true]; }
$decoded = json_decode((string) ($upstream['content'] ?? ''), true);
$findings = is_array($decoded) && is_array($decoded['findings'] ?? null) ? $decoded['findings'] : [];
$byId = [];
foreach ($page['items'] as $item) { $byId[(string) $item['id']] = $item; }
$created = 0;
foreach ($findings as $finding) {
if (!is_array($finding)) { continue; }
$item = $byId[(string) ($finding['id'] ?? '')] ?? null;
$quote = trim((string) ($finding['quote'] ?? ''));
$label = (string) ($finding['label'] ?? '');
if (!$item || $quote === '' || mb_strlen($quote) > 40 || mb_strpos((string) $item['content'], $quote) === false
|| !in_array($label, ['辱骂威胁', '讽刺挖苦', '不当承诺', '索取隐私', '脱离平台'], true)) { continue; }
$patientId = (int) ($item['patient_id'] ?? 0);
$created += $this->recordWording($item, $quote, $now, $patientId);
}
if (($page['next_cursor'] ?? '') !== '') { $state['wording_cursor'] = (string) $page['next_cursor']; }
return ['created' => $created, 'wrote' => true];
}
/** @param array<string,mixed> $item */
private function recordWording(array $item, string $quote, int $now, int $patientId): int
{
$messageId = (string) ($item['id'] ?? '');
$sourceKey = $messageId . ':' . $patientId . ':wording';
if ($messageId === '' || strlen($sourceKey) > 80) { return 0; }
$staffId = (int) ($item['zyt_user_id'] ?? 0);
$staffName = trim((string) ($item['staff_name'] ?? ''));
$patientName = trim((string) ($item['patient_name'] ?? ''));
if ($staffId <= 0 && $staffName === '') { return 0; }
if ($patientId <= 0 && $patientName === '') { return 0; }
if ($staffId > 0 && !isset(self::speakers()[$staffId])) { return 0; }
$identity = ['channel' => 'wecom', 'source_id' => 0, 'source_key' => $sourceKey, 'rule_code' => 'inappropriate_wording'];
if (Db::name(self::TABLE)->where($identity)->find()) { return 0; }
$occurred = (int) ($item['sent_at_epoch'] ?? 0);
if ($occurred <= 0) { $occurred = self::epoch((string) ($item['sent_at'] ?? '')); }
if ($occurred <= 0) { return 0; }
Db::name(self::TABLE)->insert($identity + ['staff_admin_id' => max(0, $staffId), 'patient_id' => max(0, $patientId),
'diagnosis_id' => max(0, (int) ($item['diagnosis_id'] ?? 0)), 'external_staff' => mb_substr($staffName, 0, 64),
'external_patient' => mb_substr($patientName, 0, 64), 'rule_version' => self::VERSION, 'severity' => 'medium',
'snippet' => mb_substr($quote, 0, 80), 'status' => 'open', 'reviewer_id' => 0, 'review_note' => '',
'reviewed_at' => 0, 'occurred_at' => $occurred, 'created_at' => $now, 'updated_at' => $now]);
return 1;
}
/** @param list<array{id:string,text:string}> $payload */
private static function wordingPrompt(array $payload): string
{
return "你只判断医务人员发出的文字里有没有不合适的用词。只输出一个 JSON 对象:"
. "{\"findings\":[{\"id\":\"消息id\",\"quote\":\"原文连续短句\",\"label\":\"辱骂威胁\"}]}。\n"
. "label 只能是辱骂威胁、讽刺挖苦、不当承诺、索取隐私、脱离平台之一。quote 必须是原文里连续出现的不超过 40 字,不能改写。没有问题时 findings 为空数组,不要输出解释。\n"
. '消息:' . json_encode($payload, JSON_UNESCAPED_UNICODE);
}
private function writeState(array $state): void
{
$path = $this->directory . DIRECTORY_SEPARATOR . 'scan.json';
$handle = @fopen($path, 'c+b');
if (!$handle) { throw new RuntimeException('ALERT_STORAGE'); }
try {
if (!flock($handle, LOCK_EX)) { throw new RuntimeException('ALERT_STORAGE'); }
$json = json_encode(['cursor' => (int) ($state['cursor'] ?? 0), 'call_cursor' => (int) ($state['call_cursor'] ?? 0),
'wecom_cursor' => substr((string) ($state['wecom_cursor'] ?? ''), 0, 200),
'wording_cursor' => substr((string) ($state['wording_cursor'] ?? ''), 0, 200),
'wording_next_at' => (int) ($state['wording_next_at'] ?? 0),
'source_version' => (int) ($state['source_version'] ?? 3), 'last_scan_at' => (int) ($state['last_scan_at'] ?? 0),
'next_scan_at' => (int) ($state['next_scan_at'] ?? 0), 'state' => (string) ($state['state'] ?? 'error'),
'rule_version' => self::VERSION], JSON_THROW_ON_ERROR);
if (!ftruncate($handle, 0) || fwrite($handle, $json) !== strlen($json) || !fflush($handle)) { throw new RuntimeException('ALERT_STORAGE'); }
@chmod($path, 0600);
} finally { flock($handle, LOCK_UN); fclose($handle); }
}
}