222 lines
15 KiB
PHP
222 lines
15 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace app\common\service\assistantservice;
|
|
|
|
use DomainException;
|
|
use think\facade\Db;
|
|
|
|
/** 团队统计以操作者的员工域、患者域交集为边界;GET 只读,不产生分析任务。 */
|
|
final class AssistantServiceTeam
|
|
{
|
|
public static function overview(array $p, int $adminId, callable $formatJob): array
|
|
{
|
|
$actor = AssistantServiceAccess::actor($adminId);
|
|
$staff = AssistantServiceAccess::assistantRows($adminId, $actor);
|
|
if ($p['keyword'] !== '') {
|
|
$staff = array_values(array_filter($staff, static fn (array $row): bool => mb_stripos($row['name'], $p['keyword']) !== false));
|
|
}
|
|
// 今日执行独立于近期质检,先汇总关键词下全部医助,再做列表筛选与分页。
|
|
$daily = AssistantServiceDailyContact::team($staff, $adminId, $actor);
|
|
$now = time(); $since = $now - 30 * 86400;
|
|
$imAvailable = AssistantServiceStaff::imAvailable();
|
|
$rows = []; $activity = []; $analyzed = []; $covered = []; $seen = []; $latest = [];
|
|
foreach ($staff as $person) {
|
|
$id = $person['id'];
|
|
$rows[$id] = ['staff' => $person, 'today_contact' => $daily['by_staff'][$id],
|
|
'metrics' => ['assigned_cases' => 0, 'im_messages' => $imAvailable ? 0 : null, 'manual_records' => 0,
|
|
'analyzed_cases' => 0, 'pending_actions' => 0, 'overdue_actions' => 0, 'completed_actions' => 0],
|
|
'unreviewed_issues' => 0, 'last_analyzed_at' => 0, 'analysis_state' => 'no_sources',
|
|
'queued_jobs' => 0, 'running_jobs' => 0, 'attention_jobs' => 0];
|
|
$activity[$id] = []; $analyzed[$id] = []; $covered[$id] = []; $seen[$id] = []; $latest[$id] = [];
|
|
}
|
|
if ($rows) {
|
|
// 整个团队只取得一次可见诊单;不能按医助重复遍历全部患者。
|
|
$diagnoses = AssistantServiceAccess::patientQuery($adminId, $actor)
|
|
->field('d.id,d.patient_id,d.assistant_id')->select()->toArray();
|
|
$patients = []; $byDiagnosis = [];
|
|
foreach ($diagnoses as $diagnosis) {
|
|
$id = (int) $diagnosis['id']; $patient = (int) $diagnosis['patient_id']; $assigned = (int) $diagnosis['assistant_id'];
|
|
$byDiagnosis[$id] = $patient;
|
|
if ($patient > 0) { $patients[$patient][] = $id; }
|
|
if (isset($rows[$assigned])) { $rows[$assigned]['metrics']['assigned_cases']++; }
|
|
}
|
|
self::sources($rows, $activity, $patients, $byDiagnosis, $since, $imAvailable);
|
|
self::actions($rows, $adminId, $actor, $since, $now);
|
|
self::jobs($rows, $analyzed, $covered, $seen, $latest, $adminId, $actor, $since, $formatJob);
|
|
}
|
|
$summary = ['staff_count' => count($rows), 'active_staff' => 0, 'analyzed_cases' => 0, 'unreviewed_issues' => 0,
|
|
'pending_actions' => 0, 'overdue_actions' => 0, 'queued_jobs' => 0, 'running_jobs' => 0, 'attention_jobs' => 0];
|
|
foreach ($rows as $id => &$row) {
|
|
$row['metrics']['analyzed_cases'] = count($analyzed[$id]);
|
|
if ($activity[$id]) { $summary['active_staff']++; }
|
|
$pending = array_diff_key($activity[$id], $covered[$id]);
|
|
$row['analysis_state'] = $row['attention_jobs'] > 0 || $row['unreviewed_issues'] > 0 ? 'attention'
|
|
: ($row['running_jobs'] > 0 ? 'running' : ($row['queued_jobs'] > 0 ? 'queued'
|
|
: ($pending ? 'pending' : ($analyzed[$id] ? 'ready' : 'no_sources'))));
|
|
foreach (['analyzed_cases', 'pending_actions', 'overdue_actions'] as $metric) { $summary[$metric] += $row['metrics'][$metric]; }
|
|
foreach (['unreviewed_issues', 'queued_jobs', 'running_jobs', 'attention_jobs'] as $metric) { $summary[$metric] += $row[$metric]; }
|
|
}
|
|
unset($row);
|
|
// 汇总对应 keyword 下全部授权医助,待关注过滤及分页均不改变团队汇总。
|
|
$lists = array_values(array_filter($rows, static function (array $row) use ($p): bool {
|
|
if ($p['filter'] === 'today_pending') { return ($row['today_contact']['outstanding'] ?? 0) > 0; }
|
|
if ($p['filter'] === 'today_done') {
|
|
return ($row['today_contact']['required'] ?? 0) > 0 && $row['today_contact']['state'] === 'done';
|
|
}
|
|
if ($p['filter'] === 'issues') { return $row['unreviewed_issues'] > 0; }
|
|
if ($p['filter'] === 'overdue') { return $row['metrics']['overdue_actions'] > 0; }
|
|
if ($p['filter'] === 'attention') {
|
|
return $row['unreviewed_issues'] > 0 || $row['attention_jobs'] > 0 || $row['metrics']['pending_actions'] > 0;
|
|
}
|
|
return true;
|
|
}));
|
|
// 今日待维护和待核实优先,再沿用近期质检顺序;只决定处理顺序,不对医助评分。
|
|
usort($lists, static function (array $a, array $b) use ($activity): int {
|
|
$priority = static fn (array $row): array => [($row['today_contact']['outstanding'] ?? 0) > 0,
|
|
$row['metrics']['overdue_actions'] > 0, $row['unreviewed_issues'] > 0,
|
|
$row['attention_jobs'] > 0, $row['metrics']['pending_actions'] > 0,
|
|
$activity[$row['staff']['id']] ? max($activity[$row['staff']['id']]) : 0];
|
|
return ($priority($b) <=> $priority($a)) ?: ($a['staff']['id'] <=> $b['staff']['id']);
|
|
});
|
|
return ['days' => 30, 'summary' => $summary, 'daily' => $daily['meta'], 'daily_summary' => $daily['summary'],
|
|
'lists' => array_slice($lists, ($p['page_no'] - 1) * $p['page_size'], $p['page_size']),
|
|
'count' => count($lists), 'page_no' => $p['page_no'], 'page_size' => $p['page_size']];
|
|
}
|
|
|
|
private static function sources(array &$rows, array &$activity, array $patients, array $diagnoses, int $since, bool $imAvailable): void
|
|
{
|
|
$staffIds = array_keys($rows);
|
|
foreach ($imAvailable ? array_chunk(array_keys($patients), 200) : [] as $patientIds) {
|
|
$messages = Db::name('tcm_im_chat_message')->whereIn('patient_id', $patientIds)->where('msg_type', 'text')
|
|
->where('msg_time', '>=', $since)->whereRaw('LENGTH(TRIM(text)) > 0')
|
|
->field('patient_id,from_account,to_account,COUNT(*) AS messages,MAX(msg_time) AS last_at')
|
|
->group('patient_id,from_account,to_account')->select()->toArray();
|
|
foreach ($messages as $message) {
|
|
$patient = (int) $message['patient_id']; $account = 'patient_' . $patient;
|
|
$outgoing = $message['to_account'] === $account;
|
|
$peer = $outgoing ? $message['from_account'] : ($message['from_account'] === $account ? $message['to_account'] : '');
|
|
if (preg_match('/^doctor_([1-9][0-9]*)$/D', (string) $peer, $match) !== 1 || !isset($rows[(int) $match[1]])) { continue; }
|
|
$staff = (int) $match[1];
|
|
// 自动 IM 分析按患者去重、落到最新可见诊单;旧诊单不额外制造待分析量。
|
|
if ($outgoing) { $rows[$staff]['metrics']['im_messages'] += (int) $message['messages']; }
|
|
$key = 'im:' . $patient;
|
|
$activity[$staff][$key] = max($activity[$staff][$key] ?? 0, (int) $message['last_at']);
|
|
}
|
|
}
|
|
$trackingAvailable = self::trackingAvailable();
|
|
foreach (array_chunk(array_keys($diagnoses), 200) as $ids) {
|
|
$records = Db::name('assistant_service_record')->whereIn('diagnosis_id', $ids)->whereIn('actor_id', $staffIds)
|
|
->whereNull('delete_time')->where('occurred_at', '>=', $since)
|
|
->field('diagnosis_id,patient_id,actor_id,COUNT(*) AS records,MAX(occurred_at) AS last_at,SUM(CASE WHEN LENGTH(TRIM(content)) > 0 THEN 1 ELSE 0 END) AS sources')
|
|
->group('diagnosis_id,patient_id,actor_id')->select()->toArray();
|
|
foreach ($records as $record) {
|
|
$diagnosis = (int) $record['diagnosis_id']; $staff = (int) $record['actor_id'];
|
|
if ((int) $record['patient_id'] !== $diagnoses[$diagnosis]) { continue; }
|
|
$rows[$staff]['metrics']['manual_records'] += (int) $record['records'];
|
|
$key = 'case:' . $diagnosis;
|
|
if ((int) $record['sources'] > 0) { $activity[$staff][$key] = max($activity[$staff][$key] ?? 0, (int) $record['last_at']); }
|
|
}
|
|
if (!$trackingAvailable) { continue; }
|
|
$notes = Db::name('tracking_note')->whereIn('diagnosis_id', $ids)->whereIn('admin_id', $staffIds)
|
|
->whereNull('delete_time')->where('note_date', '>=', date('Y-m-d', $since))->whereRaw('LENGTH(TRIM(content)) > 0')
|
|
->field('diagnosis_id,admin_id,MAX(note_date) AS last_at')->group('diagnosis_id,admin_id')->select()->toArray();
|
|
foreach ($notes as $note) {
|
|
$staff = (int) $note['admin_id']; $diagnosis = (int) $note['diagnosis_id'];
|
|
$key = 'case:' . $diagnosis;
|
|
$activity[$staff][$key] = max($activity[$staff][$key] ?? 0, (int) strtotime((string) $note['last_at']));
|
|
}
|
|
}
|
|
}
|
|
|
|
private static function actions(array &$rows, int $adminId, array $actor, int $since, int $now): void
|
|
{
|
|
$query = Db::name('assistant_service_action')->alias('a')->join('tcm_diagnosis d', 'd.id = a.diagnosis_id')
|
|
->join('assistant_service_job j', 'j.id = a.job_id')->whereColumn('j.patient_id', 'd.patient_id')
|
|
->whereColumn('j.diagnosis_id', 'd.id')->whereNull('d.delete_time')->where('d.status', 1)->whereIn('a.assignee_id', array_keys($rows));
|
|
AssistantServiceAccess::applyScope($query, $adminId, $actor);
|
|
// 常量时间来自服务端,不包含请求插值;一次聚合全部跟进存量。
|
|
$actions = $query->field('a.assignee_id,'
|
|
. "SUM(CASE WHEN a.business_state IN ('pending','in_progress') THEN 1 ELSE 0 END) AS pending_actions,"
|
|
. "SUM(CASE WHEN a.business_state IN ('pending','in_progress') AND a.due_at < " . $now . ' THEN 1 ELSE 0 END) AS overdue_actions,'
|
|
. "SUM(CASE WHEN a.business_state = 'completed' AND a.completed_at >= " . $since . ' THEN 1 ELSE 0 END) AS completed_actions')
|
|
->group('a.assignee_id')->select()->toArray();
|
|
foreach ($actions as $action) {
|
|
foreach (['pending_actions', 'overdue_actions', 'completed_actions'] as $key) { $rows[(int) $action['assignee_id']]['metrics'][$key] = (int) $action[$key]; }
|
|
}
|
|
}
|
|
|
|
private static function jobs(array &$rows, array &$analyzed, array &$covered, array &$seen, array &$latest,
|
|
int $adminId, array $actor, int $since, callable $formatJob): void
|
|
{
|
|
$query = Db::name('assistant_service_job')->alias('j')->join('tcm_diagnosis d', 'd.id = j.diagnosis_id')
|
|
->whereNull('d.delete_time')->where('d.status', 1)->whereColumn('j.patient_id', 'd.patient_id')
|
|
->where('j.type', 'analysis')->where('j.days', 30)
|
|
->where(static function ($q) use ($since): void {
|
|
$q->where('j.created_at', '>=', $since)->whereOr('j.status', 'in', ['queued', 'running', 'needs_reconciliation']);
|
|
});
|
|
AssistantServiceAccess::applyScope($query, $adminId, $actor);
|
|
$cursor = null;
|
|
do {
|
|
$batch = clone $query;
|
|
if ($cursor !== null) { $batch->where('j.id', '<', $cursor); }
|
|
$jobs = $batch->field('j.*')->order('j.id', 'desc')->limit(100)->select()->toArray();
|
|
$reviews = [];
|
|
$reviewIds = array_column(array_filter($jobs, static fn (array $job): bool => $job['status'] === 'ready'
|
|
&& isset($rows[(int) (json_decode((string) $job['payload_json'], true)['context']['subject_admin_id'] ?? 0)])), 'id');
|
|
if ($reviewIds) {
|
|
foreach (Db::name('assistant_service_review')->whereIn('job_id', $reviewIds)->field('job_id,item_key,decision')
|
|
->order('id', 'asc')->select()->toArray() as $review) { $reviews[(int) $review['job_id']][] = $review; }
|
|
}
|
|
foreach ($jobs as $job) {
|
|
$staff = (int) (json_decode((string) $job['payload_json'], true)['context']['subject_admin_id'] ?? 0);
|
|
if (!isset($rows[$staff])) { continue; }
|
|
$diagnosis = (int) $job['diagnosis_id']; $isLatest = !isset($latest[$staff][$diagnosis]);
|
|
$latest[$staff][$diagnosis] = true;
|
|
try { $view = $formatJob($job); } catch (DomainException $e) { continue; }
|
|
// 真正新增/变更来源应等候下一轮分析;仅权限、知识或来源移除导致的过期仍需核对。
|
|
// 只对最新过期结果额外核查,历史有效任务继续复用请求内来源缓存。
|
|
$refreshable = $isLatest && $view['stale'] && in_array($job['status'], ['ready', 'stale', 'queued', 'running'], true)
|
|
&& self::hasNewSources($job, $staff, $adminId);
|
|
if (!$view['stale'] && in_array($view['status'], ['queued', 'running'], true)) { $rows[$staff][$view['status'] . '_jobs']++; }
|
|
elseif ($job['status'] === 'needs_reconciliation' || ($isLatest && ($job['status'] === 'failed' || ($view['stale'] && !$refreshable)))) {
|
|
$rows[$staff]['attention_jobs']++;
|
|
}
|
|
if ($view['stale'] || $view['status'] !== 'ready' || !is_array($view['result']) || (int) $job['created_at'] < $since) { continue; }
|
|
$analyzed[$staff][$diagnosis] = true;
|
|
// 有效结果可覆盖同患者已分析的 IM;人工记录/备注只覆盖其绑定诊单。
|
|
$covered[$staff]['case:' . $diagnosis] = true;
|
|
if (array_filter($view['sources'], static fn (array $source): bool => $source['channel'] === 'im')) {
|
|
$covered[$staff]['im:' . (int) $job['patient_id']] = true;
|
|
}
|
|
$rows[$staff]['last_analyzed_at'] = max($rows[$staff]['last_analyzed_at'], (int) ($job['finished_at'] ?: $job['updated_at']));
|
|
$view['reviews'] = $reviews[(int) $job['id']] ?? [];
|
|
foreach (AssistantServiceStaff::qualityItems($job, $view, $staff, $seen[$staff]) as $item) {
|
|
if ($item['status'] === 'missed' && $item['decision'] === '') { $rows[$staff]['unreviewed_issues']++; }
|
|
}
|
|
}
|
|
if ($jobs) { $cursor = (int) end($jobs)['id']; }
|
|
} while (count($jobs) === 100);
|
|
}
|
|
|
|
private static function hasNewSources(array $job, int $staff, int $adminId): bool
|
|
{
|
|
try { $current = AssistantServiceContext::build((int) $job['diagnosis_id'], $adminId, 30, $staff); }
|
|
catch (DomainException $e) { return false; }
|
|
$payload = json_decode((string) $job['payload_json'], true);
|
|
$previous = array_column($payload['context']['sources'] ?? [], null, 'id');
|
|
foreach ($current['sources'] as $source) {
|
|
if (!isset($previous[$source['id']]) || $previous[$source['id']] !== $source) { return true; }
|
|
}
|
|
return false;
|
|
}
|
|
|
|
private static function trackingAvailable(): bool
|
|
{
|
|
$connection = Db::connect(); $table = Db::name('tracking_note')->getTable();
|
|
if (!in_array($table, $connection->getTables(), true)) { return false; }
|
|
return array_diff(['diagnosis_id', 'admin_id', 'note_date', 'content', 'delete_time'], array_keys($connection->getFields($table))) === [];
|
|
}
|
|
}
|