473 lines
34 KiB
PHP
473 lines
34 KiB
PHP
<?php
|
||
|
||
declare(strict_types=1);
|
||
|
||
namespace app\common\service\assistantservice;
|
||
|
||
use DateTimeImmutable;
|
||
use DateTimeZone;
|
||
use DomainException;
|
||
use RuntimeException;
|
||
use think\facade\Db;
|
||
|
||
/** 当日联系计划与确定性核查。读取不生成计划,不同步来源,不调用模型或发送通知。 */
|
||
final class AssistantServiceDailyContact
|
||
{
|
||
private const TABLE = 'assistant_service_daily_contact';
|
||
private const RULE = '到期复诊(含承诺当日/过号)及明确需联系的到期服务动作;已归档发出记录才计已联系';
|
||
private string $directory;
|
||
private \Closure $clock;
|
||
|
||
public function __construct(?string $directory = null, ?callable $clock = null)
|
||
{
|
||
$this->directory = rtrim($directory ?? root_path('runtime') . 'assistant_service_daily_contact', '/\\');
|
||
$this->clock = $clock === null ? static fn (): int => time() : \Closure::fromCallable($clock);
|
||
}
|
||
|
||
public static function team(array $staff, int $adminId, array $actor): array
|
||
{
|
||
return (new self())->teamReport($staff, $adminId, $actor);
|
||
}
|
||
|
||
public static function patients(array $p, int $adminId): array
|
||
{
|
||
return (new self())->patientReport($p, $adminId);
|
||
}
|
||
|
||
/** 实例入口便于隔离测试注入时钟与 runtime 目录;生产入口仍为上面两个静态方法。 */
|
||
public function teamReport(array $staff, int $adminId, array $actor): array
|
||
{
|
||
$actor = AssistantServiceAccess::actor($adminId);
|
||
$visible = array_column(AssistantServiceAccess::assistantRows($adminId, $actor), null, 'id');
|
||
$staff = array_values(array_filter($staff, static fn (array $s): bool => isset($visible[(int) $s['id']])));
|
||
$report = $this->report(array_map('intval', array_column($staff, 'id')), $adminId, $actor);
|
||
return ['meta' => $report['meta'], 'summary' => $report['summary'], 'by_staff' => $report['by_staff']];
|
||
}
|
||
|
||
public function patientReport(array $p, int $adminId): array
|
||
{
|
||
$assistantId = (int) ($p['assistant_id'] ?? 0);
|
||
$status = (string) ($p['status'] ?? 'pending');
|
||
if ($assistantId <= 0 || !in_array($status, ['all', 'pending', 'reported', 'contacted', 'exempt'], true)) {
|
||
throw new DomainException('今日联系核查参数不正确');
|
||
}
|
||
$staff = AssistantServiceAccess::assistant($assistantId, $adminId);
|
||
$actor = AssistantServiceAccess::actor($adminId);
|
||
$report = $this->report([$assistantId], $adminId, $actor);
|
||
$rows = array_values(array_filter($report['rows'], static fn (array $r): bool => $status === 'all' || $r['status'] === $status));
|
||
$page = max(1, (int) ($p['page_no'] ?? 1)); $size = max(1, min(50, (int) ($p['page_size'] ?? 20)));
|
||
return ['staff' => $staff, 'daily' => $report['meta'], 'summary' => $report['summary'],
|
||
'lists' => array_slice($rows, ($page - 1) * $size, $size), 'count' => count($rows), 'page_no' => $page, 'page_size' => $size];
|
||
}
|
||
|
||
/** 上海自然日,不使用数据库 CURDATE 或 PHP 默认时区。 */
|
||
public static function day(int $now): array
|
||
{
|
||
$start = (new DateTimeImmutable('@' . $now))->setTimezone(new DateTimeZone('Asia/Shanghai'))->setTime(0, 0);
|
||
return ['date' => $start->format('Y-m-d'), 'start' => $start->getTimestamp(), 'end' => $start->modify('+1 day')->getTimestamp()];
|
||
}
|
||
|
||
private function report(array $staffIds, int $adminId, array $actor): array
|
||
{
|
||
$now = ($this->clock)(); $day = self::day($now);
|
||
$meta = ['business_date' => $day['date'], 'timezone' => 'Asia/Shanghai', 'as_of' => $now,
|
||
'state' => 'unavailable', 'reason' => '今日联系核查尚未启用', 'last_scan_at' => 0, 'rule_label' => self::RULE, 'coverage' => []];
|
||
$rows = []; $plans = [];
|
||
try {
|
||
$available = self::availability();
|
||
$meta['coverage'] = self::coverage($available);
|
||
if (!config('assistant_service.daily_contact_enabled', false)) { return self::result($meta, [], $staffIds); }
|
||
if (!$available['plan']) { $meta['reason'] = '今日计划表未就绪,请先执行联系核查迁移'; return self::result($meta, [], $staffIds); }
|
||
$state = $this->readState();
|
||
$meta['last_scan_at'] = (int) ($state['last_scan_at'] ?? 0);
|
||
$meta['state'] = 'waiting'; $meta['reason'] = '等待今日计划首次扫描;不重建启用前的历史日报';
|
||
$scannerId = (int) config('assistant_service.daily_contact_actor_id', 0);
|
||
if ($scannerId <= 0) { $meta['state'] = 'unavailable'; $meta['reason'] = '今日计划尚未绑定有效主管'; }
|
||
else {
|
||
try {
|
||
$scanner = self::scanner($scannerId);
|
||
$scope = self::scope($scannerId, $scanner);
|
||
$currentScope = $scannerId === $adminId ? $scope : self::scope($adminId, $actor);
|
||
$requested = array_filter($currentScope['diagnoses'], static fn (array $d): bool => in_array((int) $d['assistant_id'], $staffIds, true));
|
||
$covered = !array_diff($staffIds, $scope['staff_ids']) && !array_diff(array_keys($requested), array_keys($scope['diagnoses']));
|
||
if (!$covered) { $meta['state'] = 'partial'; $meta['reason'] = '当前可见范围超出计划调度主管覆盖范围'; }
|
||
elseif (($state['business_date'] ?? '') === $day['date'] && (int) ($state['actor_id'] ?? 0) === $scannerId) {
|
||
if (($state['scope_hash'] ?? '') !== $scope['hash']) { $meta['reason'] = '员工或患者范围已变化,等待计划重新覆盖'; }
|
||
elseif (($state['state'] ?? '') === 'error') { $meta['state'] = 'unavailable'; $meta['reason'] = '今日计划扫描失败,等待恢复'; }
|
||
elseif ($meta['last_scan_at'] < $now - max(180, self::interval() * 3) || $meta['last_scan_at'] > $now) {
|
||
$meta['reason'] = '今日计划扫描心跳已过期,等待刷新';
|
||
} elseif (empty($state['completed']['revisit']) || empty($state['completed']['action'])) {
|
||
$meta['state'] = 'partial'; $meta['reason'] = '今日来源仍在分批扫描,人数尚未完整';
|
||
} elseif (min($state['completed']['revisit'], $state['completed']['action']) < $now - max(1800, self::interval() * 30)) {
|
||
$meta['state'] = 'partial'; $meta['reason'] = '来源全量轮询尚未及时完成,等待继续扫描';
|
||
} else { $meta['state'] = 'ready'; $meta['reason'] = '按今日固化计划核查;未发现记录不等于从未联系'; }
|
||
}
|
||
} catch (DomainException $e) { $meta['state'] = 'unavailable'; $meta['reason'] = '计划调度主管已停用、失去权限或不再具备主管角色'; }
|
||
}
|
||
if (in_array(false, $available, true)) { $meta['state'] = 'partial'; $meta['reason'] = '部分计划或联系证据来源不可读,不能判断全员完成'; }
|
||
// 始终实时取当前患者域;换绑旧患者、已删除诊单均不泄露到汇总或明细。
|
||
if ($staffIds) {
|
||
$plans = AssistantServiceAccess::patientQuery($adminId, $actor)
|
||
->join(self::TABLE . ' p', 'p.diagnosis_id = d.id AND p.patient_id = d.patient_id')
|
||
->where('p.business_date', $day['date'])->whereIn('p.assistant_id', $staffIds)
|
||
->field('p.*,d.patient_name,d.assistant_id AS current_assistant_id')->select()->toArray();
|
||
}
|
||
$ids = array_values(array_unique(array_map('intval', array_column($plans, 'diagnosis_id'))));
|
||
$sources = self::sources($ids, $available, self::actionIds($plans));
|
||
$evidence = self::evidence($plans, $sources, $available, $day, $now);
|
||
$rows = self::aggregate($plans, $sources, $available, $evidence, $day);
|
||
} catch (\Throwable $e) {
|
||
// 不把 SQL/患者资料/凭据写进公开状态;错误与真实空集合必须区分。
|
||
$meta['state'] = 'unavailable'; $meta['reason'] = '今日计划或联系证据读取失败,请稍后重试'; $rows = [];
|
||
}
|
||
return self::result($meta, $rows, $staffIds);
|
||
}
|
||
|
||
private static function result(array $meta, array $rows, array $staffIds): array
|
||
{
|
||
$ready = $meta['state'] === 'ready'; $by = [];
|
||
foreach ($staffIds as $id) { $by[$id] = self::counts(array_filter($rows, static fn (array $r): bool => $r['_assistant_id'] === $id), $ready); }
|
||
$summary = self::counts($rows, $ready);
|
||
foreach ($rows as &$row) { unset($row['_assistant_id'], $row['_due_at']); } unset($row);
|
||
return ['meta' => $meta, 'summary' => $summary, 'by_staff' => $by, 'rows' => $rows];
|
||
}
|
||
|
||
private static function counts(array $rows, bool $ready): array
|
||
{
|
||
$counts = ['required' => 0, 'contacted' => 0, 'reported' => 0, 'pending' => 0, 'outstanding' => 0, 'exempt' => 0];
|
||
if (!$ready) { return array_fill_keys(array_keys($counts), null) + ['state' => 'unavailable']; }
|
||
foreach ($rows as $row) { $counts[$row['status']]++; }
|
||
$counts['required'] = $counts['contacted'] + $counts['reported'] + $counts['pending'];
|
||
$counts['outstanding'] = $counts['reported'] + $counts['pending'];
|
||
$counts['state'] = !$counts['required'] ? 'no_tasks' : ($counts['pending'] ? 'pending' : ($counts['reported'] ? 'reported' : 'done'));
|
||
return $counts;
|
||
}
|
||
|
||
private static function aggregate(array $plans, array $sources, array $available, array $evidence, array $day): array
|
||
{
|
||
$groups = [];
|
||
foreach ($plans as $plan) {
|
||
$assistant = (int) $plan['assistant_id']; $patient = (int) $plan['patient_id']; $diagnosis = (int) $plan['diagnosis_id'];
|
||
$key = $assistant . ':' . ($patient > 0 ? 'p' . $patient : 'd' . $diagnosis);
|
||
$exempt = $plan['state'] === 'exempt' ? (string) $plan['exempt_reason'] : self::exemption($plan,
|
||
['id' => $diagnosis, 'patient_id' => $patient, 'assistant_id' => $plan['current_assistant_id']], $sources, $available, $day);
|
||
if (!isset($groups[$key])) {
|
||
$groups[$key] = ['key' => $key, 'patient_id' => $patient, 'patient_name' => (string) $plan['patient_name'],
|
||
'diagnosis_id' => $diagnosis, 'diagnosis_ids' => [], 'status' => 'exempt', 'reasons' => [],
|
||
'last_contact_at' => 0, 'evidence' => [], 'exempt_reason' => '', '_assistant_id' => $assistant, '_due_at' => PHP_INT_MAX];
|
||
}
|
||
$row = &$groups[$key]; $row['diagnosis_ids'][$diagnosis] = $diagnosis;
|
||
$row['reasons'][] = ['type' => $plan['source_type'], 'label' => $plan['reason'], 'due_at' => (int) $plan['due_at'], 'source_id' => (int) $plan['source_id']];
|
||
$row['_due_at'] = min($row['_due_at'], (int) $plan['due_at']);
|
||
if ($exempt !== '') { $row['exempt_reason'] = implode(';', array_filter([$row['exempt_reason'], $exempt])); unset($row); continue; }
|
||
if ($row['status'] === 'exempt') { $row['status'] = 'pending'; }
|
||
$facts = array_merge($evidence['im'][$assistant . ':' . $patient] ?? [], $evidence['revisit'][$assistant . ':' . $diagnosis] ?? []);
|
||
if ($plan['source_type'] === 'action') { $facts = array_merge($facts, $evidence['action'][(int) $plan['source_id']] ?? []); }
|
||
foreach ($facts as $fact) {
|
||
$row['evidence'][$fact['type'] . ':' . $fact['id']] = $fact;
|
||
if ($fact['type'] === 'im') { $row['status'] = 'contacted'; $row['last_contact_at'] = max($row['last_contact_at'], $fact['at']); }
|
||
elseif ($row['status'] !== 'contacted') { $row['status'] = 'reported'; }
|
||
}
|
||
unset($row);
|
||
}
|
||
foreach ($groups as &$row) {
|
||
$row['diagnosis_ids'] = array_values($row['diagnosis_ids']); $row['evidence'] = array_values($row['evidence']);
|
||
// 一个患者尚有有效理由时,其他已豁免理由不把该患者重复计入豁免人数。
|
||
if ($row['status'] !== 'exempt') { $row['exempt_reason'] = ''; }
|
||
} unset($row);
|
||
$rows = array_values($groups); $rank = ['pending' => 0, 'reported' => 1, 'contacted' => 2, 'exempt' => 3];
|
||
usort($rows, static fn (array $a, array $b): int => [$rank[$a['status']], $a['_due_at'], $a['key']] <=> [$rank[$b['status']], $b['_due_at'], $b['key']]);
|
||
return $rows;
|
||
}
|
||
|
||
private static function evidence(array $plans, array $sources, array $available, array $day, int $now): array
|
||
{
|
||
$result = ['im' => [], 'revisit' => [], 'action' => []];
|
||
$staff = array_values(array_unique(array_map('intval', array_column($plans, 'assistant_id'))));
|
||
$patients = array_values(array_unique(array_filter(array_map('intval', array_column($plans, 'patient_id')))));
|
||
$diagnoses = array_values(array_unique(array_map('intval', array_column($plans, 'diagnosis_id'))));
|
||
foreach ($available['im'] ? array_chunk($patients, 200) : [] as $chunk) {
|
||
$messages = Db::name('tcm_im_chat_message')->whereIn('patient_id', $chunk)->where('msg_type', 'text')
|
||
->whereIn('from_account', array_map(static fn (int $id): string => 'doctor_' . $id, $staff))
|
||
->where('msg_time', '>=', $day['start'])->where('msg_time', '<', $day['end'])->where('msg_time', '<=', $now)
|
||
->field('id,patient_id,from_account,to_account,text,msg_time')->select()->toArray();
|
||
foreach ($messages as $message) {
|
||
if ($message['to_account'] !== 'patient_' . $message['patient_id'] || trim((string) $message['text']) === '') { continue; }
|
||
$assistant = (int) substr((string) $message['from_account'], 7);
|
||
// 归档列可能使用不区分大小写的排序规则,SQL 命中不能代替账号严格配对。
|
||
if ($message['from_account'] !== 'doctor_' . $assistant || !in_array($assistant, $staff, true)) { continue; }
|
||
$key = $assistant . ':' . $message['patient_id'];
|
||
// 只需最近一条可靠发出证据;不把全聊天正文和多余消息返回到日报。
|
||
if (($result['im'][$key][0]['at'] ?? 0) > (int) $message['msg_time']) { continue; }
|
||
$result['im'][$key] = [['type' => 'im', 'id' => (int) $message['id'], 'at' => (int) $message['msg_time'], 'label' => '该医助账号今日已归档发出文字']];
|
||
}
|
||
}
|
||
foreach ($available['revisit_log'] ? array_chunk($diagnoses, 200) : [] as $chunk) {
|
||
$logs = Db::name('tcm_diagnosis_revisit_due_log')->whereIn('diagnosis_id', $chunk)->whereIn('assistant_id', $staff)
|
||
->where('event', 2)->whereColumn('operator_id', 'assistant_id')->where('create_time', '>=', $day['start'])
|
||
->where('create_time', '<', $day['end'])->where('create_time', '<=', $now)
|
||
->field('id,diagnosis_id,assistant_id,source_order_id,create_time')->select()->toArray();
|
||
foreach ($logs as $log) {
|
||
// 仅当前真实订单周期的本人登记;旧周期/无订单不能借动作计划混入。
|
||
if ((int) $log['source_order_id'] <= 0 || (int) ($sources['orders'][(int) $log['diagnosis_id']] ?? 0) !== (int) $log['source_order_id']) { continue; }
|
||
$key = $log['assistant_id'] . ':' . $log['diagnosis_id'];
|
||
if (($result['revisit'][$key][0]['at'] ?? 0) > (int) $log['create_time']) { continue; }
|
||
$result['revisit'][$key] = [['type' => 'revisit_contact', 'id' => (int) $log['id'], 'at' => (int) $log['create_time'], 'label' => '医助本人登记已联系,待核实']];
|
||
}
|
||
}
|
||
foreach ($sources['action'] as $action) {
|
||
$at = (int) $action['completed_at'];
|
||
if ((int) $action['contact_required'] !== 1 || $action['business_state'] !== 'completed'
|
||
|| (int) $action['completed_by'] !== (int) $action['assignee_id'] || $at < $day['start'] || $at >= $day['end'] || $at > $now) { continue; }
|
||
$result['action'][(int) $action['id']] = [['type' => 'action_completed', 'id' => (int) $action['id'], 'at' => $at, 'label' => '医助本人登记联系任务完成,待核实']];
|
||
}
|
||
return $result;
|
||
}
|
||
|
||
/** 每来源独立 keyset 游标;既有计划校验也独立推进,不被第一页旧计划饿死。 */
|
||
public function tick(): array
|
||
{
|
||
$counts = ['scanned' => 0, 'created' => 0, 'exempted' => 0];
|
||
if (!config('assistant_service.daily_contact_enabled', false)) { return $counts + ['state' => 'disabled']; }
|
||
$handle = null; $state = [];
|
||
try {
|
||
if (!is_dir($this->directory) && !@mkdir($this->directory, 0700, true) && !is_dir($this->directory)) { throw new RuntimeException('DAILY_STORAGE'); }
|
||
$handle = @fopen($this->directory . DIRECTORY_SEPARATOR . 'scan.lock', 'c+b');
|
||
if (!$handle) { throw new RuntimeException('DAILY_STORAGE'); }
|
||
if (!flock($handle, LOCK_EX | LOCK_NB)) { fclose($handle); $handle = null; return $counts + ['state' => 'waiting']; }
|
||
$now = ($this->clock)(); $day = self::day($now); $state = $this->readState();
|
||
$actorId = (int) config('assistant_service.daily_contact_actor_id', 0);
|
||
$actor = self::scanner($actorId); $scope = self::scope($actorId, $actor);
|
||
if (($state['business_date'] ?? '') !== $day['date'] || (int) ($state['actor_id'] ?? 0) !== $actorId) { $state = []; }
|
||
elseif (($state['scope_hash'] ?? '') !== $scope['hash']) {
|
||
// 新患者/权限变化不能反复把游标拉回第一页;先走完当前尾部,再从头完整覆盖新域。
|
||
$state['completed'] = [];
|
||
foreach (['revisit', 'action'] as $type) { $state['needs_full_start'][$type] = (int) ($state['cursors'][$type] ?? 0) > 0; }
|
||
$state['scope_hash'] = $scope['hash']; $state['next_scan_at'] = 0;
|
||
}
|
||
$state += ['business_date' => $day['date'], 'actor_id' => $actorId, 'scope_hash' => $scope['hash'], 'cursors' => [], 'completed' => []];
|
||
if ((int) ($state['next_scan_at'] ?? 0) > $now && ($state['state'] ?? '') !== 'error') { return $counts + ['state' => 'waiting']; }
|
||
$available = self::availability();
|
||
if (!$available['plan']) { throw new RuntimeException('DAILY_SCHEMA'); }
|
||
$limit = max(1, min(1000, (int) config('assistant_service.daily_contact_batch_size', 500)));
|
||
foreach (['revisit', 'action'] as $type) {
|
||
if (!$available[$type]) { unset($state['completed'][$type]); continue; }
|
||
$candidates = $this->candidates($type, $actorId, $actor, $scope['staff_ids'], (int) ($state['cursors'][$type] ?? 0), $limit, $day);
|
||
$sources = self::sources(array_map('intval', array_column($candidates, 'diagnosis_id')), $available,
|
||
$type === 'action' ? array_map('intval', array_column($candidates, 'source_id')) : []);
|
||
foreach ($candidates as $candidate) {
|
||
$counts['scanned']++; $state['cursors'][$type] = (int) $candidate['source_id'];
|
||
$plan = ['business_date' => $day['date'], 'assistant_id' => (int) $candidate['assistant_id'],
|
||
'diagnosis_id' => (int) $candidate['diagnosis_id'], 'patient_id' => (int) $candidate['patient_id'],
|
||
'source_type' => $type, 'source_id' => (int) $candidate['source_id'], 'source_order_id' => (int) ($candidate['source_order_id'] ?? 0)];
|
||
if (self::exemption($plan, $scope['diagnoses'][$plan['diagnosis_id']] ?? null, $sources, $available, $day) !== '') { continue; }
|
||
$identity = array_intersect_key($plan, array_flip(['business_date', 'assistant_id', 'source_type', 'source_id', 'source_order_id']));
|
||
$existing = Db::name(self::TABLE)->where($identity)->find();
|
||
if ($existing) {
|
||
// 同周期恢复有效责任时仍用原计划;保留首次原因/时间和上次豁免原因以备核查。
|
||
if ($existing['state'] === 'exempt' && (int) $existing['patient_id'] === $plan['patient_id']
|
||
&& (int) $existing['diagnosis_id'] === $plan['diagnosis_id']) {
|
||
Db::name(self::TABLE)->where('id', $existing['id'])->update(['state' => 'active', 'updated_at' => $now]);
|
||
}
|
||
continue;
|
||
}
|
||
$due = $type === 'revisit' ? self::dateTimestamp((string) ($candidate['due_date'] ?? '')) : (int) $candidate['due_at'];
|
||
$reason = $type === 'action' ? '明确需联系的到期服务动作' : ((int) $candidate['appointment_state'] === 4 ? '复诊过号需跟进' : '复诊到期需联系');
|
||
if ($type === 'revisit' && ($candidate['promised_date'] ?? '') === $day['date']) { $reason = '承诺复诊日今日到期'; }
|
||
Db::name(self::TABLE)->insert($plan + ['reason' => $reason, 'due_at' => $due ?: $day['start'], 'state' => 'active',
|
||
'exempt_reason' => '', 'created_at' => $now, 'updated_at' => $now]);
|
||
$counts['created']++;
|
||
}
|
||
if (count($candidates) < $limit) {
|
||
$state['cursors'][$type] = 0;
|
||
if (!empty($state['needs_full_start'][$type])) { $state['needs_full_start'][$type] = false; }
|
||
else { $state['completed'][$type] = $now; }
|
||
}
|
||
}
|
||
$plans = Db::name(self::TABLE)->where('business_date', $day['date'])->where('id', '>', (int) ($state['cursors']['plans'] ?? 0))
|
||
->order('id', 'asc')->limit($limit)->select()->toArray();
|
||
$sources = self::sources(array_map('intval', array_column($plans, 'diagnosis_id')), $available, self::actionIds($plans));
|
||
foreach ($plans as $plan) {
|
||
$state['cursors']['plans'] = (int) $plan['id'];
|
||
if ($plan['state'] === 'exempt') { continue; }
|
||
$diagnosis = $scope['diagnoses'][(int) $plan['diagnosis_id']] ?? null;
|
||
// 不再可见的患者不返回到 GET;保留计划审计而非把失去权限算完成。
|
||
$reason = self::exemption($plan, $diagnosis, $sources, $available, $day);
|
||
if ($reason === '') { continue; }
|
||
Db::name(self::TABLE)->where('id', $plan['id'])->where('state', 'active')->update(['state' => 'exempt', 'exempt_reason' => $reason, 'updated_at' => $now]);
|
||
$counts['exempted']++;
|
||
}
|
||
if (count($plans) < $limit) { $state['cursors']['plans'] = 0; }
|
||
// 最后再核验角色/权限/患者范围,变化时保守标为待重新覆盖。
|
||
$final = self::scope($actorId, self::scanner($actorId));
|
||
if ($final['hash'] !== $scope['hash']) { $state['completed'] = []; $state['scope_hash'] = ''; }
|
||
$state['last_scan_at'] = $now; $state['next_scan_at'] = $now + self::interval();
|
||
$state['state'] = in_array(false, $available, true) || empty($state['completed']['revisit']) || empty($state['completed']['action'])
|
||
? 'partial' : 'ready';
|
||
$this->writeState($state);
|
||
return $counts + ['state' => $state['state']];
|
||
} catch (\Throwable $e) {
|
||
try {
|
||
$state['state'] = 'error'; $state['next_scan_at'] = 0; $state['error_at'] = ($this->clock)();
|
||
if (is_resource($handle)) { $this->writeState($state); }
|
||
} catch (\Throwable $ignored) {}
|
||
return $counts + ['state' => 'error'];
|
||
} finally { if (is_resource($handle)) { flock($handle, LOCK_UN); fclose($handle); } }
|
||
}
|
||
|
||
private function candidates(string $type, int $actorId, array $actor, array $staff, int $cursor, int $limit, array $day): array
|
||
{
|
||
if (!$staff) { return []; }
|
||
$query = AssistantServiceAccess::patientQuery($actorId, $actor)->whereIn('d.assistant_id', $staff);
|
||
if ($type === 'revisit') {
|
||
$query->join('tcm_diagnosis_revisit_due s', 's.diagnosis_id = d.id AND s.assistant_id = d.assistant_id')
|
||
->where('s.closed_state', 0)->where('s.source_order_id', '>', 0)
|
||
->where(static function ($q) use ($day): void { $q->where('s.due_date', '<=', $day['date'])->whereOr('s.appointment_state', 4); })
|
||
->where(static function ($q) use ($day): void { $q->whereNull('s.promised_date')->whereOr('s.promised_date', '<=', $day['date']); });
|
||
$fields = 's.source_order_id,s.due_date,s.appointment_state,s.promised_date';
|
||
} else {
|
||
$query->join('assistant_service_action s', 's.diagnosis_id = d.id AND s.assignee_id = d.assistant_id')
|
||
->join('assistant_service_job j', 'j.id = s.job_id AND j.diagnosis_id = d.id AND j.patient_id = d.patient_id')
|
||
->where('s.contact_required', 1)->where('s.due_at', '>', 0)->where('s.due_at', '<', $day['end'])
|
||
->whereIn('s.business_state', ['pending', 'in_progress', 'completed'])
|
||
->where(static function ($q) use ($day): void { $q->where('s.business_state', '<>', 'completed')->whereOr('s.completed_at', '>=', $day['start']); });
|
||
$fields = 's.due_at';
|
||
}
|
||
return $query->where('s.id', '>', $cursor)->field('s.id AS source_id,d.id AS diagnosis_id,d.patient_id,d.assistant_id,' . $fields)
|
||
->order('s.id', 'asc')->limit($limit)->select()->toArray();
|
||
}
|
||
|
||
private static function exemption(array $plan, ?array $diagnosis, array $sources, array $available, array $day): string
|
||
{
|
||
if (!$diagnosis) { return '诊单已失效或不在调度主管当前患者范围'; }
|
||
if ((int) $diagnosis['patient_id'] !== (int) $plan['patient_id']) { return '诊单患者绑定已变化'; }
|
||
if ((int) $diagnosis['assistant_id'] !== (int) $plan['assistant_id']) { return '诊单责任医助已变更'; }
|
||
$type = $plan['source_type'];
|
||
if (!$available[$type]) { return ''; } // 来源不可读只能标记不完整,不能伪装为取消。
|
||
$source = $sources[$type][(int) $plan['source_id']] ?? null;
|
||
if (!$source) { return '计划来源已移除'; }
|
||
if ($type === 'revisit') {
|
||
if ((int) $source['source_order_id'] !== (int) $plan['source_order_id']
|
||
|| (int) ($sources['orders'][(int) $plan['diagnosis_id']] ?? 0) !== (int) $plan['source_order_id']) { return '复诊订单周期已变化或失效'; }
|
||
if ((int) $source['assistant_id'] !== (int) $plan['assistant_id']) { return '复诊来源责任医助已变更'; }
|
||
if ((int) $source['closed_state'] !== 0) { return '复诊周期已关闭或失效'; }
|
||
// 进入当日计划后,承诺未来日期/延迟/复诊日期变化均不缩小分母。
|
||
} else {
|
||
if ((int) $source['diagnosis_id'] !== (int) $plan['diagnosis_id'] || (int) ($source['job_diagnosis_id'] ?? 0) !== (int) $plan['diagnosis_id']
|
||
|| (int) ($source['job_patient_id'] ?? -1) !== (int) $plan['patient_id']) { return '服务动作的原患者绑定已变化'; }
|
||
if ((int) $source['assignee_id'] !== (int) $plan['assistant_id']) { return '服务动作负责人已变更'; }
|
||
if ((int) $source['contact_required'] !== 1) { return '来源不再要求联系患者'; }
|
||
if ($source['business_state'] === 'cancelled') { return '服务动作已取消'; }
|
||
if ($source['business_state'] === 'completed' && (int) $source['completed_at'] < $day['start']) { return '服务动作已在今日之前完成'; }
|
||
}
|
||
return '';
|
||
}
|
||
|
||
private static function sources(array $diagnoses, array $available, array $actionIds): array
|
||
{
|
||
$result = ['revisit' => [], 'action' => [], 'orders' => []];
|
||
foreach (array_chunk(array_values(array_unique($diagnoses)), 200) as $chunk) {
|
||
if ($available['revisit']) {
|
||
foreach (Db::name('tcm_diagnosis_revisit_due')->whereIn('diagnosis_id', $chunk)->select()->toArray() as $row) { $result['revisit'][(int) $row['id']] = $row; }
|
||
$orders = Db::name('tcm_prescription_order')->whereIn('diagnosis_id', $chunk)->whereNull('delete_time')
|
||
->where(static function ($q): void { $q->whereNull('fulfillment_status')->whereOr('fulfillment_status', 'not in', [4, 9, 10]); })
|
||
->field('diagnosis_id,MAX(id) AS latest_id')->group('diagnosis_id')->select()->toArray();
|
||
foreach ($orders as $order) { $result['orders'][(int) $order['diagnosis_id']] = (int) $order['latest_id']; }
|
||
}
|
||
if ($available['action'] && $actionIds) {
|
||
$actions = Db::name('assistant_service_action')->alias('a')->leftJoin('assistant_service_job j', 'j.id = a.job_id')
|
||
->whereIn('a.diagnosis_id', $chunk)->whereIn('a.id', $actionIds)
|
||
->field('a.*,j.diagnosis_id AS job_diagnosis_id,j.patient_id AS job_patient_id')->select()->toArray();
|
||
foreach ($actions as $row) { $result['action'][(int) $row['id']] = $row; }
|
||
}
|
||
}
|
||
return $result;
|
||
}
|
||
|
||
private static function actionIds(array $plans): array
|
||
{
|
||
return array_map('intval', array_column(array_filter($plans, static fn (array $p): bool => $p['source_type'] === 'action'), 'source_id'));
|
||
}
|
||
|
||
private static function availability(): array
|
||
{
|
||
$fields = [
|
||
'plan' => [[self::TABLE, 'id,business_date,assistant_id,diagnosis_id,patient_id,source_type,source_id,source_order_id,reason,due_at,state,exempt_reason,created_at,updated_at']],
|
||
'revisit' => [['tcm_diagnosis_revisit_due', 'id,diagnosis_id,assistant_id,source_order_id,due_date,promised_date,closed_state,appointment_state'],
|
||
['tcm_prescription_order', 'id,diagnosis_id,fulfillment_status,delete_time']],
|
||
'action' => [['assistant_service_action', 'id,diagnosis_id,job_id,assignee_id,due_at,business_state,completed_at,completed_by,contact_required'], ['assistant_service_job', 'id,diagnosis_id,patient_id']],
|
||
'im' => [['tcm_im_chat_message', 'id,patient_id,from_account,to_account,msg_type,text,msg_time']],
|
||
'revisit_log' => [['tcm_diagnosis_revisit_due_log', 'id,diagnosis_id,assistant_id,source_order_id,event,operator_id,create_time']],
|
||
];
|
||
$result = [];
|
||
foreach ($fields as $source => $tables) {
|
||
$result[$source] = true;
|
||
try { foreach ($tables as [$table, $columns]) { Db::name($table)->field($columns)->whereRaw('1=0')->select(); } }
|
||
catch (\Throwable $e) { $result[$source] = false; }
|
||
}
|
||
return $result;
|
||
}
|
||
|
||
private static function coverage(array $available): array
|
||
{
|
||
$labels = ['plan' => '今日固化计划', 'revisit' => '当前有效复诊到期与订单周期', 'action' => '明确需联系的人工采纳动作',
|
||
'im' => '已归档且账号配对的发出文字;不代表对方已回复', 'revisit_log' => '本人复诊联系登记;日志缺失不代表从未联系'];
|
||
$rows = [];
|
||
foreach ($available as $source => $ready) { $rows[] = ['source' => $source, 'status' => $ready ? 'available' : 'unavailable', 'note' => $labels[$source] . ($ready ? '' : '暂不可读或缺少迁移字段')]; }
|
||
$rows[] = ['source' => 'external', 'status' => 'not_connected', 'note' => '电话、外部企微联系尚未接入;人工登记只计待核实'];
|
||
return $rows;
|
||
}
|
||
|
||
private static function scanner(int $actorId): array
|
||
{
|
||
if ($actorId <= 0) { throw new DomainException('需要有效主管'); }
|
||
$actor = AssistantServiceAccess::actor($actorId, 'view');
|
||
if (!(int) $actor['root'] && !array_intersect($actor['role_id'], [3, 7, 8])) { throw new DomainException('需要有效主管'); }
|
||
return $actor;
|
||
}
|
||
|
||
private static function scope(int $adminId, array $actor): array
|
||
{
|
||
$staff = array_map('intval', array_column(AssistantServiceAccess::assistantRows($adminId, $actor), 'id')); sort($staff);
|
||
// 仅在内存计算访问域指纹;runtime 不保存患者、名字、计划内容或诊单清单。
|
||
$diagnoses = AssistantServiceAccess::patientQuery($adminId, $actor)->field('d.id,d.patient_id,d.assistant_id')->order('d.id', 'asc')->select()->toArray();
|
||
$diagnoses = array_column($diagnoses, null, 'id');
|
||
return ['staff_ids' => $staff, 'diagnoses' => $diagnoses, 'hash' => hash('sha256', json_encode([$staff, $diagnoses]))];
|
||
}
|
||
|
||
private static function dateTimestamp(string $date): int
|
||
{
|
||
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/D', $date)) { return 0; }
|
||
return (new DateTimeImmutable($date . ' 00:00:00', new DateTimeZone('Asia/Shanghai')))->getTimestamp();
|
||
}
|
||
|
||
private static function interval(): int { return max(5, min(3600, (int) config('assistant_service.daily_contact_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('DAILY_STORAGE'); }
|
||
try {
|
||
if (!flock($handle, LOCK_SH)) { throw new RuntimeException('DAILY_STORAGE'); }
|
||
$json = stream_get_contents($handle, 16385);
|
||
if (!is_string($json) || strlen($json) > 16384) { throw new RuntimeException('DAILY_STORAGE'); }
|
||
$state = json_decode($json, true, 16, JSON_THROW_ON_ERROR);
|
||
if (!is_array($state)) { throw new RuntimeException('DAILY_STORAGE'); }
|
||
return $state;
|
||
} finally { flock($handle, LOCK_UN); fclose($handle); }
|
||
}
|
||
|
||
private function writeState(array $state): void
|
||
{
|
||
$path = $this->directory . DIRECTORY_SEPARATOR . 'scan.json'; $handle = @fopen($path, 'c+b');
|
||
if (!$handle) { throw new RuntimeException('DAILY_STORAGE'); }
|
||
try {
|
||
if (!flock($handle, LOCK_EX)) { throw new RuntimeException('DAILY_STORAGE'); }
|
||
$json = json_encode($state, JSON_THROW_ON_ERROR);
|
||
if (!ftruncate($handle, 0) || fwrite($handle, $json) !== strlen($json) || !fflush($handle)) { throw new RuntimeException('DAILY_STORAGE'); }
|
||
@chmod($path, 0600);
|
||
} finally { flock($handle, LOCK_UN); fclose($handle); }
|
||
}
|
||
}
|