This commit is contained in:
Your Name
2026-11-12 09:07:07 +08:00
parent 06afe2c453
commit c737960d4f
1399 changed files with 19163 additions and 3089 deletions
+205
View File
@@ -0,0 +1,205 @@
<?php
declare(strict_types=1);
// 真实 ThinkPHP ORM/权限服务,合成 SQLite 内存库;不初始化应用、不读 .env、不联网。
require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
use app\adminapi\logic\tcm\AssistantServiceLogic as Logic;
use app\adminapi\validate\tcm\AssistantServiceValidate as Validate;
use app\common\service\assistantservice\AssistantServiceAccess as Access;
use app\common\service\assistantservice\AssistantServiceAlert as Alert;
use think\Container;
use think\facade\Db;
if (!in_array('sqlite', PDO::getAvailableDrivers(), true)) { throw new RuntimeException('需要隔离测试 SQLite 扩展'); }
new think\App();
set_exception_handler(static function (Throwable $e): void { fwrite(STDERR, $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL); exit(1); });
$manager = new think\DbManager();
$manager->setConfig(['default' => 'isolated', 'connections' => ['isolated' => ['type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'test_', 'fields_strict' => true]]]);
Container::getInstance()->instance('think\DbManager', $manager);
think\Model::setDb($manager);
$config = new think\Config();
$settings = ['enabled' => false, 'alert_enabled' => false, 'alert_interval_seconds' => 60, 'alert_batch_size' => 200];
$config->set($settings, 'assistant_service');
$config->set(['data_scope' => ['enabled' => true, 'no_dept_fallback_self' => true]], 'project');
Container::getInstance()->instance('config', $config);
$tables = [
'admin' => 'id INTEGER PRIMARY KEY,name TEXT,root INTEGER DEFAULT 0,disable INTEGER DEFAULT 0,delete_time INTEGER NULL',
'admin_role' => 'admin_id INTEGER,role_id INTEGER', 'admin_dept' => 'admin_id INTEGER,dept_id INTEGER',
'dept' => 'id INTEGER PRIMARY KEY,pid INTEGER,status INTEGER DEFAULT 1,delete_time INTEGER NULL',
'system_role' => 'id INTEGER PRIMARY KEY,name TEXT,data_scope INTEGER,delete_time INTEGER NULL',
'system_role_menu' => 'role_id INTEGER,menu_id INTEGER', 'system_menu' => 'id INTEGER PRIMARY KEY,perms TEXT,is_disable INTEGER DEFAULT 0',
'doctor_appointment' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,doctor_id INTEGER,status INTEGER',
'tcm_diagnosis' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,assistant_id INTEGER,patient_name TEXT,phone TEXT,status INTEGER DEFAULT 1,delete_time INTEGER NULL',
'tcm_im_chat_message' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,diagnosis_id INTEGER DEFAULT 0,from_account TEXT COLLATE NOCASE,to_account TEXT,msg_type TEXT,text TEXT,msg_time INTEGER',
'tcm_call_record' => 'id INTEGER PRIMARY KEY,diagnosis_id INTEGER,caller_id INTEGER,caller_type TEXT,callee_id INTEGER,callee_type TEXT,start_time INTEGER,duration INTEGER,delete_time INTEGER NULL',
'tcm_call_transcript_segment' => 'id INTEGER PRIMARY KEY,call_record_id INTEGER,speaker_user_id TEXT,speaker_role TEXT,text TEXT,create_time INTEGER',
'assistant_service_alert' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,staff_admin_id INTEGER,patient_id INTEGER,diagnosis_id INTEGER DEFAULT 0,channel TEXT,source_id INTEGER,source_key TEXT NOT NULL DEFAULT "",external_staff TEXT NOT NULL DEFAULT "",external_patient TEXT NOT NULL DEFAULT "",rule_code TEXT,rule_version INTEGER,severity TEXT,snippet TEXT,status TEXT DEFAULT "open",reviewer_id INTEGER DEFAULT 0,review_note TEXT DEFAULT "",reviewed_at INTEGER DEFAULT 0,occurred_at INTEGER,created_at INTEGER,updated_at INTEGER,UNIQUE(channel,source_id,source_key,rule_code)',
];
foreach ($tables as $name => $schema) { Db::execute('CREATE TABLE test_' . $name . ' (' . $schema . ')'); }
Db::name('admin')->insertAll([['id' => 1, 'name' => 'root', 'root' => 1], ['id' => 11, 'name' => '甲', 'root' => 0],
['id' => 12, 'name' => '域外', 'root' => 0], ['id' => 13, 'name' => '主管', 'root' => 0], ['id' => 14, 'name' => '医生', 'root' => 0]]);
Db::name('system_role')->insertAll([['id' => 1, 'name' => '医生', 'data_scope' => 1], ['id' => 2, 'name' => '医助', 'data_scope' => 4], ['id' => 3, 'name' => '经理', 'data_scope' => 3]]);
Db::name('admin_role')->insertAll([['admin_id' => 11, 'role_id' => 2], ['admin_id' => 12, 'role_id' => 2], ['admin_id' => 13, 'role_id' => 3], ['admin_id' => 14, 'role_id' => 1]]);
Db::name('dept')->insertAll([['id' => 10, 'pid' => 0], ['id' => 20, 'pid' => 0]]);
Db::name('admin_dept')->insertAll([['admin_id' => 11, 'dept_id' => 10], ['admin_id' => 12, 'dept_id' => 20], ['admin_id' => 13, 'dept_id' => 10]]);
Db::name('system_menu')->insertAll([['id' => 1, 'perms' => 'tcm.assistantService/view'], ['id' => 2, 'perms' => 'tcm.assistantService/reviewQuality']]);
Db::name('system_role_menu')->insertAll([['role_id' => 2, 'menu_id' => 1], ['role_id' => 3, 'menu_id' => 1], ['role_id' => 3, 'menu_id' => 2]]);
Db::name('tcm_diagnosis')->insertAll([
['id' => 101, 'patient_id' => 201, 'assistant_id' => 11, 'patient_name' => '合成甲', 'phone' => '', 'status' => 1],
['id' => 102, 'patient_id' => 301, 'assistant_id' => 12, 'patient_name' => '域外患者', 'phone' => '', 'status' => 1],
]);
$clock = (new DateTimeImmutable('2026-11-10 11:00:00', new DateTimeZone('Asia/Shanghai')))->getTimestamp();
$temporary = sys_get_temp_dir() . '/assistant-alert-test-' . bin2hex(random_bytes(6));
$scanner = new Alert($temporary, static function () use (&$clock): int { return $clock; });
$checks = 0;
$ok = static function (bool $pass, string $message) use (&$checks): void { if (!$pass) { throw new RuntimeException($message); } $checks++; };
$deny = static function (callable $call, string $message) use ($ok): void { try { $call(); } catch (DomainException $e) { $ok(true, $message); return; } $ok(false, $message); };
$configure = static function (array $extra) use ($config, $settings): void { $config->set(array_merge($settings, $extra), 'assistant_service'); };
$list = static fn (array $input = [], int $admin = 13): array => Logic::alerts(Validate::parameters('alerts', $input), $admin);
$review = static fn (array $input, int $admin = 13): array => Logic::reviewAlert(Validate::parameters('reviewAlert', $input), $admin);
$im = static function (int $id, int $patient, string $from, string $text, string $type = 'text', ?string $to = null, int $at = 0) use (&$clock): void {
Db::name('tcm_im_chat_message')->insert(['id' => $id, 'patient_id' => $patient, 'diagnosis_id' => $patient === 201 ? 101 : 102,
'from_account' => $from, 'to_account' => $to ?? ('patient_' . $patient), 'msg_type' => $type, 'text' => $text, 'msg_time' => $at ?: $clock]);
};
try {
$ok(Access::permissionForAction('alerts') === 'view' && Access::permissionForAction('reviewAlert') === 'reviewQuality'
&& Access::permissionForAction('wecomChats') === 'view', '预警、企微会话和复核分别使用查看、质检权限');
$ok(Validate::parameters('alerts', [])['status'] === 'open' && Validate::parameters('alerts', [])['severity'] === 'all' && Validate::parameters('alerts', [])['role'] === 'all', '预警列表默认待处理且不预选身份');
$deny(static fn () => Validate::parameters('alerts', ['status' => 'open', 'injected' => 1]), '预警列表拒绝未知字段');
$deny(static fn () => Validate::parameters('reviewAlert', ['id' => 1, 'status' => 'false_positive', 'note' => '']), '误报必须填写原因');
$deny(static fn () => Validate::parameters('reviewAlert', ['id' => 1, 'status' => 'open', 'note' => '']), '不能把预警改回未处理');
$im(1, 201, 'doctor_11', '诊断为糖尿病');
$ok($scanner->tick()['state'] === 'disabled' && Db::name('assistant_service_alert')->count() === 0, '关闭扫描时不写预警');
$configure(['alert_enabled' => true]);
$armed = $scanner->tick();
$ok($armed['state'] === 'ready' && $armed['created'] === 1 && Db::name('assistant_service_alert')->count() === 1, '首次扫描检查已有的员工文字');
$before = Db::name('assistant_service_alert')->count();
$ok($list()['count'] === $before && $list()['schema_ready'] === true, '读取预警不产生新记录');
$quiet = $list([], 12);
$ok($quiet['count'] === 0 && str_contains((string) $quiet['empty_reason'], '当前范围没有待处理预警')
&& $quiet['coverage'][1]['status'] === 'available', '其他患者没有命中时说明当前范围为空,通话转写已接入');
$pad = str_repeat('甲', 100);
$im(2, 201, 'doctor_11', $pad . '诊断为糖尿病,加我微信');
$im(3, 201, 'doctor_11', '这个包治,保证好转');
$im(4, 201, 'doctor_11', '把银行卡和身份证照片发我');
$im(5, 201, 'doctor_11', '你有病吧');
$im(6, 201, 'doctor_11', '明天来换药,记得吃饭');
$im(7, 201, 'doctor_11', '建议服用黄连');
$im(8, 201, 'patient_201', '诊断为糖尿病', 'text', 'doctor_11');
$im(9, 201, 'DOCTOR_11', '诊断为糖尿病');
$im(10, 201, 'doctor_011', '诊断为糖尿病');
$im(11, 201, 'doctor_14', '诊断为糖尿病');
$im(12, 201, 'doctor_13', '诊断为糖尿病');
$im(13, 201, 'doctor_11', ' ');
$im(14, 201, 'doctor_11', '诊断为糖尿病', 'image');
$im(15, 201, 'doctor_11', '诊断为糖尿病', 'text', 'patient_999');
$im(16, 301, 'doctor_12', '私下转账给我');
$ok($scanner->tick()['state'] === 'waiting' && Db::name('assistant_service_alert')->count() === 1, '间隔未到不提前扫描');
Db::name('tcm_call_record')->insert(['id' => 1, 'diagnosis_id' => 101, 'caller_id' => 11, 'caller_type' => 'doctor',
'callee_id' => 201, 'callee_type' => 'patient', 'start_time' => $clock, 'duration' => 30, 'delete_time' => null]);
Db::name('tcm_call_transcript_segment')->insertAll([
['id' => 1, 'call_record_id' => 1, 'speaker_user_id' => 'doctor_11', 'speaker_role' => 'doctor', 'text' => '先停药再观察', 'create_time' => $clock],
['id' => 2, 'call_record_id' => 1, 'speaker_user_id' => 'patient_201', 'speaker_role' => 'patient', 'text' => '我自己停药了', 'create_time' => $clock],
['id' => 3, 'call_record_id' => 1, 'speaker_user_id' => 'doctor_14', 'speaker_role' => 'doctor', 'text' => '加我微信', 'create_time' => $clock],
]);
$clock += 61;
$created = $scanner->tick();
$ok($created['created'] === 11 && Db::name('assistant_service_alert')->count() === 12, '医生、主管的聊天和员工侧通话转写都记,患者发言和不配对账号不计');
$clinical = Db::name('assistant_service_alert')->where('source_id', 2)->where('rule_code', 'clinical_boundary')->find();
$ok($clinical && mb_strlen((string) $clinical['snippet']) <= 80 && str_contains((string) $clinical['snippet'], '诊断为糖尿病')
&& !str_contains((string) $clinical['snippet'], str_repeat('甲', 30)), '摘录只保留命中附近,不保存整段聊天');
$ok(Db::name('assistant_service_alert')->where('source_id', 2)->count() === 2, '同一条消息的诊疗和导流分成两条');
$ok(Db::name('assistant_service_alert')->where('rule_code', 'cure_promise')->value('severity') === 'high'
&& Db::name('assistant_service_alert')->where('rule_code', 'privacy_ask')->value('severity') === 'medium'
&& Db::name('assistant_service_alert')->where('rule_code', 'hostility')->value('severity') === 'low', '规则级别按诊疗承诺、索取、冲突分开');
$ok((int) Db::name('assistant_service_alert')->where('source_id', 7)->count() === 1, '明确的服药建议要进入预警');
$page = $list();
$ok($page['summary']['open'] === 11 && $page['summary']['high_open'] === 9 && $page['summary']['im_open'] === 9 && $page['summary']['call_open'] === 2, '主管汇总范围内聊天和通话预警');
$ok($page['summary']['assistant_open'] > 0 && $page['summary']['doctor_open'] > 0 && $list(['role' => 'doctor'])['summary']['open'] === 11, '待处理按医助和医生分开计数,身份筛选不改总数');
$ok($list(['role' => 'doctor'])['lists'][0]['staff']['role_name'] === '医生' && $list(['role' => 'assistant'])['lists'][0]['staff']['role_name'] === '医助', '可以只看医生或只看医助');
$ok($page['coverage'][1]['channel'] === 'call' && $page['coverage'][1]['status'] === 'available'
&& $page['coverage'][2]['status'] === 'not_connected', '通话转写已接入,企微仍未接入');
$ok($page['empty_reason'] === '' && str_contains((string) $page['coverage'][0]['note'], '医生和医助'), '有命中时不再把列表解释成没有发言');
$doctorCall = null;
foreach ($list([], 1)['lists'] as $row) {
if ($row['channel'] === 'call' && (int) $row['staff']['id'] === 14) { $doctorCall = $row; }
}
$ok($doctorCall && $doctorCall['staff']['assistant'] === false && $doctorCall['staff']['role_name'] === '医生'
&& !Db::name('assistant_service_alert')->where('channel', 'call')->where('source_id', 2)->find(), '医生通话命中进入列表,患者转写不计');
$ok($list(['status' => 'all', 'page_size' => 1])['summary']['open'] === 11 && $list(['status' => 'all', 'page_size' => 1])['count'] === 11, '筛选和分页不缩小总待处理数');
$ok($list(['keyword' => '合成甲'])['count'] === 11 && $list(['keyword' => '域外'])['count'] === 0, '主管搜不到范围外的患者');
$ok($list([], 11)['count'] === 11 && $list([], 12)['count'] === 1 && $list([], 1)['count'] === 12, '可见患者上的医生和医助命中都列出,范围外患者不列出');
$hidden = (int) Db::name('assistant_service_alert')->where('staff_admin_id', 12)->value('id');
$deny(static fn () => $review(['id' => $hidden, 'status' => 'confirmed', 'note' => '']), '不能复核范围外预警');
$deny(static fn () => $review(['id' => (int) $clinical['id'], 'status' => 'confirmed', 'note' => ''], 11), '医助不能把自己的预警改成成立');
$deny(static fn () => $list([], 14), '没有模块权限的医生不能读预警');
$confirmed = $review(['id' => (int) $clinical['id'], 'status' => 'confirmed', 'note' => '']);
$ok($confirmed['status'] === 'confirmed' && $list()['summary']['open'] === 10
&& Db::name('assistant_service_alert')->where('id', $clinical['id'])->value('snippet') === $clinical['snippet'], '成立后离开待处理,摘录保持不变');
$hostility = (int) Db::name('assistant_service_alert')->where('rule_code', 'hostility')->value('id');
$reviewed = $review(['id' => $hostility, 'status' => 'false_positive', 'note' => '患者原话']);
$ok($reviewed['status'] === 'false_positive' && Db::name('assistant_service_alert')->where('id', $hostility)->value('review_note') === '患者原话', '误报保留原因');
$clock += 61;
file_put_contents($temporary . '/scan.json', json_encode(['cursor' => 1, 'last_scan_at' => 0, 'next_scan_at' => 0, 'state' => 'ready', 'rule_version' => 1]));
$ok($scanner->tick()['created'] === 0 && Db::name('assistant_service_alert')->count() === 12, '游标回退后同一来源同一规则不重复入库');
$im(17, 201, 'doctor_11', '开具处方');
$ok($scanner->tick()['state'] === 'waiting' && Db::name('assistant_service_alert')->count() === 12, '刚扫完的间隔内新消息先等待');
$clock += 61;
$configure(['alert_enabled' => true, 'alert_batch_size' => 1]);
$ok($scanner->tick()['created'] === 1 && $scanner->tick()['state'] === 'waiting', '一批只处理设定条数,下一条等下一轮');
$clock += 61;
$wecom = new Alert($temporary, static function () use (&$clock): int { return $clock; }, static function (string $cursor): array {
if ($cursor !== '') { return ['configured' => true, 'items' => [], 'next_cursor' => $cursor, 'has_more' => false]; }
return ['configured' => true, 'has_more' => false, 'next_cursor' => '2026-11-10T03:00:00Z|m1', 'items' => [[
'id' => 'm1', 'sent_at' => '2026-11-10T03:00:00Z', 'patient_id' => 201, 'diagnosis_id' => 101,
'zyt_user_id' => '11', 'content' => '加我微信',
]]];
});
$fed = $wecom->tick();
$ok($fed['created'] === 1 && (int) Db::name('assistant_service_alert')->where('channel', 'wecom')->where('source_key', 'm1:201')->count() === 1, '企微归档里员工发出且已绑定患者的文字进入预警');
$local = $temporary . '/archive.db';
$archive = new PDO('sqlite:' . $local);
$archive->exec('CREATE TABLE archive_source_account (id TEXT PRIMARY KEY, display_name TEXT)');
$archive->exec('CREATE TABLE archive_conversation (id TEXT PRIMARY KEY, conversation_type TEXT, name TEXT)');
$archive->exec('CREATE TABLE archive_message (id TEXT PRIMARY KEY, conversation_id TEXT, source_account_id TEXT, content TEXT, direction TEXT, status TEXT, message_type TEXT, sent_at TEXT, sent_at_epoch INTEGER)');
$archive->exec("INSERT INTO archive_source_account VALUES ('a1','甲'),('a2','外来客服')");
$archive->exec("INSERT INTO archive_conversation VALUES ('c1','direct_wecom','合成甲'),('c2','direct_wecom','未建档')");
$archive->exec("INSERT INTO archive_message VALUES ('local1','c1','a1','加我微信','outbound','normal','文本','2026-11-10T03:00:00+00:00',1794268800),('local2','c2','a2','私下转账给我','outbound','normal','文本','2026-11-10T03:01:00+00:00',1794268860)");
$saved = json_decode((string) file_get_contents($temporary . '/scan.json'), true);
$saved['wecom_cursor'] = '';
$saved['next_scan_at'] = 0;
file_put_contents($temporary . '/scan.json', json_encode($saved));
$configure(['alert_enabled' => true, 'wecom_archive_sqlite' => $local]);
$localScan = (new Alert($temporary, static function () use (&$clock): int { return $clock; }))->tick();
$ok($localScan['created'] === 2 && (int) Db::name('assistant_service_alert')->where('source_key', 'local1:201')->value('staff_admin_id') === 11, '本地归档按姓名对上医助和患者');
$loose = null;
foreach ($list([], 1)['lists'] as $row) { if (($row['patient_name'] ?? '') === '未建档') { $loose = $row; } }
$ok($loose && $loose['staff']['name'] === '外来客服' && $loose['patient_id'] === 0, '对不上的本地会话仍给不受限账号查看');
$hiddenLocal = false;
foreach ($list([], 13)['lists'] as $row) { if ((int) ($row['patient_id'] ?? 1) === 0) { $hiddenLocal = true; } }
$ok(!$hiddenLocal, '部门主管看不到没有患者归属的企微会话');
$configure(['alert_enabled' => true, 'wecom_archive_sqlite' => $local, 'wecom_wording_enabled' => true, 'wecom_wording_interval_seconds' => 60, 'wecom_wording_batch_size' => 6]);
$saved = json_decode((string) file_get_contents($temporary . '/scan.json'), true);
$saved['wording_next_at'] = 0;
$saved['wording_cursor'] = '';
$saved['next_scan_at'] = 0;
file_put_contents($temporary . '/scan.json', json_encode($saved));
$wording = new Alert($temporary, static function () use (&$clock): int { return $clock; }, null, static function (): array {
return ['ok' => true, 'content' => json_encode(['findings' => [['id' => 'local1', 'quote' => '加我微信', 'label' => '脱离平台']]], JSON_UNESCAPED_UNICODE)];
});
$judged = $wording->tick();
$ok($judged['created'] === 1 && (int) Db::name('assistant_service_alert')->where('rule_code', 'inappropriate_wording')->count() === 1, '模型指出且原文确实存在的用词才进入预警');
Db::execute('DROP TABLE test_assistant_service_alert');
$missing = $list();
$ok($missing['schema_ready'] === false && $missing['lists'] === [] && $missing['summary']['open'] === 0, '缺表时显示未就绪,不把空列表当成没有风险');
$ok($scanner->tick()['state'] === 'unavailable', '缺表时扫描停止并说明未就绪');
echo 'ASSISTANT_SERVICE_ALERT assertions=' . $checks . ' PASS sqlite=memory real_access=1 flock=1 model=0 network=0' . PHP_EOL;
} finally {
if (is_dir($temporary)) {
foreach (glob($temporary . '/*') ?: [] as $file) { @unlink($file); }
@rmdir($temporary);
}
}
+313
View File
@@ -0,0 +1,313 @@
<?php
declare(strict_types=1);
// 真实 ORM 与权限/业务代码,临时 SQLite;不初始化应用、不读 .env、不联网。
require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
use app\adminapi\logic\tcm\AssistantServiceLogic as Logic;
use app\adminapi\validate\tcm\AssistantServiceValidate as Validate;
use app\common\service\assistantservice\AssistantServiceAccess as Access;
use app\common\service\assistantservice\AssistantServiceContext as Context;
use think\Container;
use think\facade\Db;
if (!in_array('sqlite', PDO::getAvailableDrivers(), true)) {
throw new RuntimeException('Run: php -d extension=php_pdo_sqlite.dll tests/AssistantServiceApiTest.php');
}
new think\App();
set_exception_handler(static function (Throwable $e): void {
fwrite(STDERR, $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL); exit(1);
});
$manager = new think\DbManager();
$manager->setConfig(['default' => 'isolated', 'connections' => ['isolated' => [
'type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'test_', 'fields_strict' => true,
]]]);
Container::getInstance()->instance('think\DbManager', $manager);
think\Model::setDb($manager);
$config = new think\Config();
$config->set(['enabled' => true, 'profile' => 'qwen', 'timeout' => 120, 'daily_job_limit' => 100,
'max_source_rows' => 200, 'max_source_chars' => 30000, 'max_manual_chars' => 10000, 'max_knowledge_rows' => 40], 'assistant_service');
$config->set(['enable' => true, 'base_url' => 'https://example.invalid', 'models' => [
'qwen' => ['name' => 'synthetic', 'api_key' => 'synthetic-no-network']]], 'prescription_ai');
$config->set(['data_scope' => ['enabled' => true, 'no_dept_fallback_self' => true]], 'project');
Container::getInstance()->instance('config', $config);
$tables = [
'admin' => 'id INTEGER PRIMARY KEY,name TEXT,root INTEGER DEFAULT 0,disable INTEGER DEFAULT 0,delete_time INTEGER NULL',
'admin_role' => 'admin_id INTEGER,role_id INTEGER',
'admin_dept' => 'admin_id INTEGER,dept_id INTEGER',
'dept' => 'id INTEGER PRIMARY KEY,pid INTEGER,status INTEGER DEFAULT 1,delete_time INTEGER NULL',
'system_role' => 'id INTEGER PRIMARY KEY,name TEXT,data_scope INTEGER,delete_time INTEGER NULL',
'system_role_menu' => 'role_id INTEGER,menu_id INTEGER',
'system_menu' => 'id INTEGER PRIMARY KEY,perms TEXT,is_disable INTEGER DEFAULT 0',
'doctor_appointment' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,doctor_id INTEGER,status INTEGER',
'tcm_diagnosis' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,assistant_id INTEGER,patient_name TEXT,phone TEXT,status INTEGER DEFAULT 1,delete_time INTEGER NULL',
'tracking_note' => 'id INTEGER PRIMARY KEY,diagnosis_id INTEGER,admin_id INTEGER,note_date TEXT,content TEXT,create_time INTEGER,update_time INTEGER,delete_time INTEGER NULL',
'tcm_im_chat_message' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,diagnosis_id INTEGER,from_account TEXT,to_account TEXT,doctor_peer_account TEXT,msg_type TEXT,text TEXT,msg_time INTEGER',
'tcm_diagnosis_todo' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,patient_id INTEGER,content TEXT,remind_time INTEGER,status INTEGER,creator_id INTEGER,creator_name TEXT,create_time INTEGER,update_time INTEGER,notified_at INTEGER DEFAULT 0,cancelled_at INTEGER DEFAULT 0,cancelled_by INTEGER DEFAULT 0,delete_time INTEGER NULL',
'assistant_service_record' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,patient_id INTEGER,actor_id INTEGER,content TEXT,record_type TEXT,speaker_confirmed INTEGER,occurred_at INTEGER,created_at INTEGER,delete_time INTEGER NULL',
'assistant_service_job' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,patient_id INTEGER,actor_id INTEGER,type TEXT,scenario TEXT,days INTEGER,status TEXT,version INTEGER,dedupe_key TEXT UNIQUE,source_hash TEXT,scope_hash TEXT,payload_json TEXT,result_json TEXT,claim_token TEXT DEFAULT "",lease_until INTEGER DEFAULT 0,error_code TEXT DEFAULT "",error_message TEXT DEFAULT "",upstream_id TEXT DEFAULT "",created_at INTEGER,updated_at INTEGER,finished_at INTEGER DEFAULT 0',
'assistant_service_review' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,job_id INTEGER,item_key TEXT,reviewer_id INTEGER,decision TEXT,note TEXT,created_at INTEGER',
'assistant_service_action' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,job_id INTEGER,action_key TEXT,todo_id INTEGER,assignee_id INTEGER,content TEXT,due_at INTEGER,business_state TEXT,completion_note TEXT DEFAULT "",completed_at INTEGER DEFAULT 0,created_at INTEGER,updated_at INTEGER,UNIQUE(job_id,action_key)',
'assistant_service_knowledge' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,question TEXT,answer TEXT,category TEXT,source_note TEXT,status TEXT,version INTEGER,created_by INTEGER,published_by INTEGER,created_at INTEGER,updated_at INTEGER',
];
foreach ($tables as $name => $schema) { Db::execute('CREATE TABLE test_' . $name . ' (' . $schema . ')'); }
Db::name('admin')->insertAll([
['id' => 1, 'name' => 'root', 'root' => 1], ['id' => 11, 'name' => 'assistant', 'root' => 0],
['id' => 12, 'name' => 'other', 'root' => 0], ['id' => 13, 'name' => 'team', 'root' => 0], ['id' => 14, 'name' => 'doctor', 'root' => 0],
]);
Db::name('system_role')->insertAll([
['id' => 1, 'name' => '医生', 'data_scope' => 1], ['id' => 2, 'name' => '医助', 'data_scope' => 4], ['id' => 3, 'name' => '经理', 'data_scope' => 3],
]);
Db::name('admin_role')->insertAll([['admin_id' => 11, 'role_id' => 2], ['admin_id' => 12, 'role_id' => 2], ['admin_id' => 13, 'role_id' => 3], ['admin_id' => 14, 'role_id' => 1]]);
Db::name('dept')->insertAll([['id' => 10, 'pid' => 0], ['id' => 20, 'pid' => 0]]);
Db::name('admin_dept')->insertAll([['admin_id' => 11, 'dept_id' => 10], ['admin_id' => 12, 'dept_id' => 20], ['admin_id' => 13, 'dept_id' => 10]]);
foreach (Access::PERMISSIONS as $i => $permission) {
Db::name('system_menu')->insert(['id' => $i + 1, 'perms' => 'tcm.assistantService/' . $permission]);
foreach ([1, 2, 3] as $role) { Db::name('system_role_menu')->insert(['role_id' => $role, 'menu_id' => $i + 1]); }
}
Db::name('tcm_diagnosis')->insertAll([
['id' => 101, 'patient_id' => 201, 'assistant_id' => 11, 'patient_name' => '合成甲', 'phone' => '13800138000'],
['id' => 102, 'patient_id' => 202, 'assistant_id' => 12, 'patient_name' => '合成乙', 'phone' => '13900139000'],
['id' => 103, 'patient_id' => 0, 'assistant_id' => 11, 'patient_name' => '未映射', 'phone' => ''],
]);
Db::name('doctor_appointment')->insert(['id' => 1, 'patient_id' => 101, 'doctor_id' => 14, 'status' => 1]);
$now = time();
Db::name('tracking_note')->insert(['id' => 1, 'diagnosis_id' => 101, 'admin_id' => 11,
'note_date' => date('Y-m-d'), 'content' => '患者要求周六确认预约', 'create_time' => $now, 'update_time' => $now]);
foreach ([
[1, 201, 'patient_201', 'doctor_11', 'text', '请帮我核对预约,电话13800138000'],
[2, 201, 'doctor_11', 'patient_201', 'text', '我将在明天回复可预约时段'],
[3, 201, 'doctor_12', 'patient_201', 'text', '其他部门私有沟通'],
[4, 201, 'doctor_11', 'patient_999', 'text', '错误患者映射'],
[5, 201, 'doctor_11', 'patient_201', 'image', '不可读图片'],
[6, 201, 'doctor_999', 'patient_201', 'text', '不存在的员工'],
] as [$id, $patient, $from, $to, $type, $text]) {
Db::name('tcm_im_chat_message')->insert(['id' => $id, 'patient_id' => $patient, 'diagnosis_id' => 999,
'from_account' => $from, 'to_account' => $to, 'doctor_peer_account' => 'doctor_11', 'msg_type' => $type, 'text' => $text, 'msg_time' => $now - 100]);
}
$checks = 0;
$ok = static function (bool $condition, string $label) use (&$checks): void { if (!$condition) { throw new RuntimeException($label); } $checks++; };
$deny = static function (callable $call, string $label) use ($ok): void {
try { $call(); } catch (DomainException $e) { $ok(true, $label); return; } $ok(false, $label);
};
$call = static fn (string $action, array $p = [], int $actor = 11): array => Logic::$action(Validate::parameters($action, $p), $actor);
$ok(Access::permissionForAction('staffDailyContacts') === 'view', 'daily contacts explicitly require module view');
$dailyParams = Validate::parameters('staffDailyContacts', ['assistant_id' => '11']);
$ok($dailyParams === ['assistant_id' => 11, 'page_no' => 1, 'page_size' => 20, 'status' => 'pending'], 'daily list defaults and numeric GET id');
foreach (['all', 'pending', 'reported', 'contacted', 'exempt'] as $status) {
$ok(Validate::parameters('staffDailyContacts', ['assistant_id' => 11, 'status' => $status])['status'] === $status, 'daily list allows status ' . $status);
}
foreach ([[], ['assistant_id' => 0], ['assistant_id' => true], ['assistant_id' => 1.1], ['assistant_id' => '01'],
['assistant_id' => 11, 'status' => 'done'], ['assistant_id' => 11, 'status' => []], ['assistant_id' => 11, 'page_size' => 51],
['assistant_id' => 11, 'status' => null], ['assistant_id' => 11, 'page_no' => null], ['assistant_id' => 11, 'page_size' => null],
['assistant_id' => 11, 'page_no' => 0], ['assistant_id' => 11, 'page_size' => 1.1], ['assistant_id' => 11, 'days' => 30],
['assistant_id' => 11, 'business_date' => '2026-01-01'], ['assistant_id' => 11, 'actor_id' => 1]] as $input) {
$deny(fn () => Validate::parameters('staffDailyContacts', $input), 'daily list rejects invalid or injected parameters');
}
foreach (['today_pending', 'today_done'] as $filter) {
$ok(Validate::parameters('teamOverview', ['filter' => $filter])['filter'] === $filter, 'team accepts daily filter ' . $filter);
}
$ok($call('capabilities')['ready'], 'capabilities uses configured adapter without contacting network');
$ok($call('patients')['count'] === 2, 'assistant only sees own diagnoses');
$ok($call('patients', [], 13)['count'] === 2, 'manager scoped to department');
$ok($call('patients', [], 14)['count'] === 1, 'doctor ALL config still restricted to own appointment');
Db::name('system_role')->insert(['id' => 7, 'name' => '已删除组长', 'data_scope' => 1, 'delete_time' => 1]);
Db::name('admin_role')->insert(['admin_id' => 11, 'role_id' => 7]);
$ok($call('patients')['count'] === 2, 'deleted role relationship does not permanently block valid actor or expand scope');
$legacy = Db::name('tcm_diagnosis')->alias('d')->whereNull('d.delete_time')->where('d.status', 1);
\app\adminapi\logic\firstvisit\MyPatientLogic::applyScope($legacy, 14, Access::actor(14));
$ok((int) $legacy->count() === 1, 'legacy MyPatient default signature retains doctor scope');
$ok($call('patients')['lists'][1]['phone_masked'] === '138****8000', 'phone masking');
$deny(fn () => Access::diagnosis(102, 11), 'cross-patient read rejected');
$deny(fn () => $call('record', ['diagnosis_id' => 102, 'content' => 'bad', 'occurred_at' => $now, 'record_type' => 'service_note']), 'cross-patient write rejected');
Db::name('admin')->where('id', 11)->update(['disable' => 1]);
$deny(fn () => $call('capabilities'), 'disabled account rejected immediately');
Db::name('admin')->where('id', 11)->update(['disable' => 0]);
Db::name('system_role_menu')->where('role_id', 2)->where('menu_id', 2)->delete();
$deny(fn () => $call('analyze', ['diagnosis_id' => 101, 'scenario' => 'followup']), 'fresh permission revocation');
Db::name('system_role_menu')->insert(['role_id' => 2, 'menu_id' => 2]);
$context = Context::build(101, 11);
$ok(array_column($context['sources'], 'id') === ['im:1', 'im:2', 'tracking:1'] || array_column($context['sources'], 'id') === ['tracking:1', 'im:1', 'im:2'], 'IM verifies patient/staff/type instead of trusting stored peer');
$ok(!str_contains(json_encode($context['sources']), '13800138000'), 'source phone redacted');
$service = array_values(array_filter($context['sources'], static fn ($s) => $s['id'] === 'im:2'))[0];
$ok($service['speaker'] === 'service' && $service['actor_admin_id'] === 11, 'IM exact historical actor attribution');
$ok(Context::build(101, 11)['source_hash'] === $context['source_hash'], 'source hash deterministic');
$ok(Context::build(101, 11)['scope_hash'] === $context['scope_hash'], 'scope hash deterministic');
$ok(count(Context::build(101, 1)['sources']) === 4, 'root can see known other employee but excludes unknown account');
$ok(count(Context::build(101, 14)['sources']) === 1, 'doctor cannot read assistant IM merely because patient appointment visible');
$unmapped = Context::build(103, 11);
$ok(in_array('unmapped', array_column($unmapped['coverage'], 'status'), true), 'unmapped patient has explicit coverage');
$deny(fn () => $call('record', ['diagnosis_id' => 101, 'content' => 'transcript', 'occurred_at' => $now, 'record_type' => 'verified_transcript']), 'transcript explicit confirmation');
$deny(fn () => $call('record', ['diagnosis_id' => 101, 'content' => 'transcript', 'occurred_at' => $now, 'record_type' => 'verified_transcript', 'speaker_confirmed' => 'true']), 'strict JSON boolean');
$config->set(['enabled' => false], 'assistant_service');
$ok(!$call('capabilities')['ready'], 'AI disabled capabilities cannot advertise generation');
$deny(fn () => $call('analyze', ['diagnosis_id' => 101, 'scenario' => 'followup']), 'AI switch blocks analysis');
$deny(fn () => $call('draftReply', ['diagnosis_id' => 101, 'scenario' => 'followup', 'question' => '如何预约?']), 'AI switch blocks reply generation');
$manual = $call('record', ['diagnosis_id' => 101, 'content' => '患者说周六有空;客服说待核实。', 'occurred_at' => $now, 'record_type' => 'verified_transcript', 'speaker_confirmed' => true]);
$ok($manual['id'] > 0, 'AI disabled still permits authorized manual recording');
$config->set(['enabled' => true], 'assistant_service');
$source = array_values(array_filter(Context::build(101, 11)['sources'], static fn ($s) => $s['id'] === 'manual:' . $manual['id']))[0];
$ok($source['speaker'] === 'unknown' && $source['actor_admin_id'] === 0, 'recorder is never assumed historical speaker');
$deny(fn () => $call('draftReply', ['diagnosis_id' => 101, 'scenario' => 'followup', 'question' => '如何预约?']), 'empty published knowledge blocks reply');
$knowledge = $call('saveKnowledge', ['question' => '如何预约?', 'answer' => '请由医助核对可预约时段。', 'category' => '预约', 'source_note' => '合成已审核流程']);
$ok($call('knowledge')['lists'][0]['status'] === 'draft', 'new knowledge draft');
Db::name('system_role_menu')->where('role_id', 2)->where('menu_id', 8)->delete();
$ok($call('knowledge')['count'] === 0, 'view without manage sees published only');
$deny(fn () => $call('publishKnowledge', $knowledge + ['status' => 'published']), 'knowledge requires independent manage privilege');
$published = $call('publishKnowledge', $knowledge + ['status' => 'published'], 1);
$ok($published['version'] === 2 && $call('knowledge')['count'] === 1, 'publish increments version and makes visible');
$deny(fn () => $call('saveKnowledge', ['id' => $knowledge['id'], 'version' => 1, 'question' => 'stale', 'answer' => 'stale'], 1), 'optimistic version conflict');
$job = $call('analyze', ['diagnosis_id' => 101, 'scenario' => 'followup']);
$ok($job['status'] === 'queued' && $job['result'] === null, 'async enqueue does not fabricate result');
$same = $call('analyze', ['diagnosis_id' => 101, 'scenario' => 'followup']);
$ok($same['id'] === $job['id'] && Db::name('assistant_service_job')->count() === 1, 'unchanged request deduplication');
$config->set(['daily_job_limit' => 1], 'assistant_service');
$ok($call('analyze', ['diagnosis_id' => 101, 'scenario' => 'followup'])['id'] === $job['id'], 'dedupe does not consume daily quota');
$deny(fn () => $call('analyze', ['diagnosis_id' => 101, 'scenario' => 'initial']), 'daily limit checked after dedupe');
$config->set(['daily_job_limit' => 100], 'assistant_service');
$result = ['summary' => [['text' => '希望预约周六', 'evidence_ids' => ['im:1']]], 'needs' => [], 'unresolved' => [], 'tags' => [],
'suggested_actions' => [['key' => 'confirm_slot', 'text' => '核对预约时段并回复患者', 'evidence_ids' => ['im:1']]],
'quality_checks' => [['key' => 'next_step', 'label' => '下一步', 'status' => 'met', 'reason' => '已明确下次回复', 'evidence_ids' => ['im:2'], 'actor_admin_id' => 11]]];
Db::name('assistant_service_job')->where('id', $job['id'])->update(['status' => 'ready', 'result_json' => json_encode($result)]);
$ok(!isset($call('job', ['id' => $job['id']])['payload_json']), 'job response excludes private payload');
$ok($call('jobs', ['status' => 'ready'])['count'] === 1, 'fresh ready filter counts matching task');
$deny(fn () => $call('job', ['id' => $job['id']], 12), 'job read repeats patient scope');
$hidden = $call('job', ['id' => $job['id']], 14);
$ok($hidden['stale'] && $hidden['result'] === null && count($hidden['sources']) === 2, 'narrower employee scope cannot see generated facts based on hidden IM');
$config->set(['enabled' => false], 'assistant_service');
$review = $call('reviewQuality', ['job_id' => $job['id'], 'item_key' => 'next_step', 'decision' => 'confirmed', 'note' => '已回看', 'version' => 1], 13);
$ok($review['id'] > 0, 'authorized manager can review existing dimension');
$deny(fn () => $call('reviewQuality', ['job_id' => $job['id'], 'item_key' => 'invented', 'decision' => 'confirmed', 'note' => '', 'version' => 1], 13), 'reject forged review key');
$adopt = ['job_id' => $job['id'], 'action_key' => 'confirm_slot', 'version' => 1, 'due_at' => $now + 3600];
$ok(Validate::parameters('adoptAction', $adopt)['contact_required'] === false, 'contact intent defaults false');
foreach ([0, 1, 'true', 'false', '1', null, [], new stdClass()] as $value) {
$deny(fn () => Validate::parameters('adoptAction', $adopt + ['contact_required' => $value]), 'contact intent requires a real JSON boolean');
}
$beforeContact = Db::name('tcm_diagnosis_todo')->count();
try { $call('adoptAction', $adopt + ['contact_required' => true]); $ok(false, 'contact intent requires migration'); }
catch (DomainException $e) { $ok(str_contains($e->getMessage(), '迁移'), 'missing contact column reports migration requirement'); }
$ok(Db::name('tcm_diagnosis_todo')->count() === $beforeContact && Db::name('assistant_service_action')->count() === 0,
'unavailable contact schema never creates an ordinary fallback reminder');
$action = $call('adoptAction', $adopt);
$repeat = $call('adoptAction', $adopt + ['content' => '重复请求不同内容']);
$ok($action === $repeat && Db::name('tcm_diagnosis_todo')->count() === 1, 'adoption idempotent and one linked reminder');
$ok((int) Db::name('tcm_diagnosis_todo')->where('id', $action['todo_id'])->value('creator_id') === 11, 'responsibility fixed to current actor');
$ok($call('actions')['lists'][0]['notification_status'] === 0, 'notification distinct from pending business state');
$ok($call('actions')['lists'][0]['contact_required'] === false && $call('actions')['lists'][0]['completed_by'] === 0,
'legacy action schema exposes explicit false contact intent and unknown completion actor');
Db::name('system_role_menu')->where('role_id', 1)->where('menu_id', 7)->delete();
$deny(fn () => $call('completeAction', ['id' => $action['id'], 'state' => 'completed', 'note' => '非负责人'], 14), 'visible patient alone does not authorize non-assignee completion');
Db::name('system_role_menu')->insert(['role_id' => 1, 'menu_id' => 7]);
$call('completeAction', ['id' => $action['id'], 'state' => 'in_progress', 'note' => '已着手核对']);
$deny(fn () => $call('completeAction', ['id' => $action['id'], 'state' => 'completed', 'note' => '']), 'completion requires execution note');
$call('completeAction', ['id' => $action['id'], 'state' => 'completed', 'note' => '已核实并人工回复']);
$ok((int) Db::name('tcm_diagnosis_todo')->where('id', $action['todo_id'])->value('status') === 2, 'completion atomically cancels unsent reminder');
$ok($call('completeAction', ['id' => $action['id'], 'state' => 'completed', 'note' => '重复提交'])['id'] === $action['id'], 'terminal same-state replay');
$ok(Db::name('assistant_service_action')->where('id', $action['id'])->value('completion_note') === '已核实并人工回复', 'terminal replay preserves execution record');
$deny(fn () => $call('completeAction', ['id' => $action['id'], 'state' => 'in_progress', 'note' => 'reopen']), 'terminal cannot reopen');
$deny(fn () => $call('completeAction', ['id' => $action['id'], 'state' => 'cancelled', 'note' => 'switch']), 'terminal cannot silently switch');
$ok(!$call('capabilities')['enabled'], 'review, adoption and completion remain available while AI is disabled');
$config->set(['enabled' => true], 'assistant_service');
Db::name('tcm_diagnosis')->where('id', 101)->update(['assistant_id' => 12]);
$deny(fn () => $call('completeAction', ['id' => $action['id'], 'state' => 'completed', 'note' => '撤权后重放']), 'assignment revocation beats idempotence');
Db::name('tcm_diagnosis')->where('id', 101)->update(['assistant_id' => 11]);
$result['suggested_actions'][] = ['key' => 'later_followup', 'text' => '再次核对时段', 'evidence_ids' => ['im:1']];
Db::name('assistant_service_job')->where('id', $job['id'])->update(['result_json' => json_encode($result)]);
$secondAdopt = array_replace($adopt, ['action_key' => 'later_followup']);
Db::execute("CREATE TRIGGER fail_action_insert BEFORE INSERT ON test_assistant_service_action BEGIN SELECT RAISE(ABORT, 'synthetic failure'); END");
$before = Db::name('tcm_diagnosis_todo')->count();
try { $call('adoptAction', $secondAdopt); $ok(false, 'simulated sidecar failure'); }
catch (\think\db\exception\PDOException $e) { $ok(true, 'simulated sidecar failure'); }
$ok(Db::name('tcm_diagnosis_todo')->count() === $before, 'transaction rolls back reminder when sidecar insertion fails');
Db::execute('DROP TRIGGER fail_action_insert');
$sentAction = $call('adoptAction', $secondAdopt);
Db::name('tcm_diagnosis_todo')->where('id', $sentAction['todo_id'])->update(['status' => 1]);
$call('completeAction', ['id' => $sentAction['id'], 'state' => 'completed', 'note' => '主管已核对'], 13);
$ok((int) Db::name('tcm_diagnosis_todo')->where('id', $sentAction['todo_id'])->value('status') === 1, 'supervisor completion preserves already-sent reminder state');
// 在同一内存库升级增量列,验证真实写入与旧记录兼容;不读取部署数据库。
Db::execute('ALTER TABLE test_assistant_service_action ADD COLUMN contact_required INTEGER NOT NULL DEFAULT 0');
Db::execute('ALTER TABLE test_assistant_service_action ADD COLUMN completed_by INTEGER NOT NULL DEFAULT 0');
Db::connect()->getSchemaInfo('test_assistant_service_action', true);
foreach (['contact_self', 'contact_manager', 'ordinary', 'contact_cancel'] as $key) {
$result['suggested_actions'][] = ['key' => $key, 'text' => '合成联系登记', 'evidence_ids' => ['im:1']];
}
Db::name('assistant_service_job')->where('id', $job['id'])->update(['result_json' => json_encode($result)]);
$selfContact = $call('adoptAction', array_replace($adopt, ['action_key' => 'contact_self', 'contact_required' => true]));
$managerContact = $call('adoptAction', array_replace($adopt, ['action_key' => 'contact_manager', 'contact_required' => true]));
$ordinary = $call('adoptAction', array_replace($adopt, ['action_key' => 'ordinary', 'contact_required' => false]));
$cancelContact = $call('adoptAction', array_replace($adopt, ['action_key' => 'contact_cancel', 'contact_required' => true]));
$storedContact = Db::name('assistant_service_action')->where('id', $selfContact['id'])->find();
$ok((int) $storedContact['contact_required'] === 1 && (int) $storedContact['completed_by'] === 0, 'explicit contact intent stored as integer before completion');
$ok((int) Db::name('assistant_service_action')->where('id', $ordinary['id'])->value('contact_required') === 0, 'ordinary adoption keeps contact intent false');
$ok($call('adoptAction', array_replace($adopt, ['action_key' => 'ordinary', 'contact_required' => true])) === $ordinary
&& (int) Db::name('assistant_service_action')->where('id', $ordinary['id'])->value('contact_required') === 0,
'idempotent replay never silently upgrades old ordinary action into daily plan');
$listed = array_column($call('actions')['lists'], null, 'id');
$ok($listed[$selfContact['id']]['contact_required'] === true && $listed[$ordinary['id']]['contact_required'] === false,
'actions return actual boolean contact intent for frontend');
Db::name('tcm_diagnosis_todo')->where('id', $selfContact['todo_id'])->update(['status' => 1]);
$listed = array_column($call('actions')['lists'], null, 'id');
$ok($listed[$selfContact['id']]['business_state'] === 'pending' && $listed[$selfContact['id']]['notification_status'] === 1,
'sent reminder does not mark action completed');
$call('completeAction', ['id' => $selfContact['id'], 'state' => 'in_progress', 'note' => '核对中']);
$ok((int) Db::name('assistant_service_action')->where('id', $selfContact['id'])->value('completed_by') === 0, 'in-progress action has no completing actor');
$call('completeAction', ['id' => $selfContact['id'], 'state' => 'completed', 'note' => '本人登记电话联系']);
$call('completeAction', ['id' => $selfContact['id'], 'state' => 'completed', 'note' => '主管重复请求'], 13);
$selfStored = Db::name('assistant_service_action')->where('id', $selfContact['id'])->find();
$ok((int) $selfStored['completed_by'] === 11 && $selfStored['completion_note'] === '本人登记电话联系', 'terminal replay preserves actual original completing actor');
$ok((int) Db::name('tcm_diagnosis_todo')->where('id', $selfContact['todo_id'])->value('status') === 1, 'contact completion also preserves already-sent notification');
$call('completeAction', ['id' => $managerContact['id'], 'state' => 'completed', 'note' => '主管代登记'], 13);
$call('completeAction', ['id' => $managerContact['id'], 'state' => 'completed', 'note' => '本人重发']);
$ok((int) Db::name('assistant_service_action')->where('id', $managerContact['id'])->value('completed_by') === 13, 'supervisor completion never becomes assignee completion on replay');
$call('completeAction', ['id' => $cancelContact['id'], 'state' => 'cancelled', 'note' => '无需联系']);
$listed = array_column($call('actions')['lists'], null, 'id');
$ok($listed[$managerContact['id']]['completed_by'] === 13 && $listed[$cancelContact['id']]['business_state'] === 'cancelled',
'read response retains supervisor actor and separate cancellation state');
$ok($listed[$sentAction['id']]['completed_by'] === 0 && $listed[$action['id']]['contact_required'] === false,
'migration does not infer old contact intent or old completion actor');
$edited = $call('saveKnowledge', ['id' => $knowledge['id'], 'version' => 2, 'question' => '如何预约?', 'answer' => '请先核对患者身份及可预约时段。', 'category' => '预约', 'source_note' => '合成新流程'], 1);
$ok($edited['version'] === 3 && $call('knowledge')['count'] === 0, 'editing published content returns to draft');
$ok($call('job', ['id' => $job['id']])['stale'], 'knowledge changes invalidate prior task');
$deny(fn () => $call('adoptAction', $adopt), 'knowledge change blocks even repeated adoption');
$deny(fn () => $call('reviewQuality', ['job_id' => $job['id'], 'item_key' => 'next_step', 'decision' => 'dismissed', 'note' => '', 'version' => 1], 13), 'stale review rejected');
$newJob = $call('analyze', ['diagnosis_id' => 101, 'scenario' => 'initial']);
Db::name('assistant_service_job')->where('id', $newJob['id'])->update(['status' => 'ready', 'result_json' => json_encode($result)]);
Db::name('tracking_note')->where('id', 1)->update(['content' => '患者现在希望周日预约']);
$ok($call('job', ['id' => $newJob['id']])['stale'], 'edited original source invalidates ready result');
$deny(fn () => $call('adoptAction', array_replace($adopt, ['job_id' => $newJob['id']])), 'source change blocks action adoption');
$ok($call('jobs', ['status' => 'ready'])['count'] === 0, 'ready filter excludes dynamically stale rows');
$stalePage1 = $call('jobs', ['status' => 'stale', 'page_no' => 1, 'page_size' => 1]);
$stalePage2 = $call('jobs', ['status' => 'stale', 'page_no' => 2, 'page_size' => 1]);
$ok($stalePage1['count'] === 2 && $stalePage2['count'] === 2 && count($stalePage1['lists']) === 1
&& $stalePage1['lists'][0]['id'] !== $stalePage2['lists'][0]['id'], 'dynamic stale filter has exact count and page boundaries');
$retryParams = ['diagnosis_id' => 101, 'days' => 7, 'scenario' => 'revisit'];
$retryJob = $call('analyze', $retryParams);
Db::name('assistant_service_job')->where('id', $retryJob['id'])->update(['status' => 'failed', 'error_code' => 'CONFIG_INVALID']);
$retried = $call('analyze', $retryParams);
$ok($retried['id'] === $retryJob['id'] && $retried['status'] === 'queued' && $retried['version'] === 2,
'explicit request safely requeues known-not-generated config failure with new version');
Db::name('assistant_service_job')->where('id', $retryJob['id'])->update(['status' => 'needs_reconciliation', 'error_code' => 'UPSTREAM_UNCERTAIN']);
$ok($call('analyze', $retryParams)['status'] === 'needs_reconciliation', 'uncertain upstream outcome is never automatically retried');
Db::name('assistant_service_job')->where('id', $retryJob['id'])->update(['status' => 'failed', 'error_code' => 'RESULT_INVALID']);
$ok($call('analyze', $retryParams)['status'] === 'failed', 'already-generated invalid result is not automatically retried');
$config->set(['max_source_rows' => 1], 'assistant_service');
$deny(fn () => Context::build(101, 11), 'oversized sources explicit refusal instead of silent truncation');
$overLimitJob = $call('job', ['id' => $job['id']]);
$ok($overLimitJob['stale'] && $overLimitJob['result'] === null && $overLimitJob['sources'] === [], 'source growth beyond capacity keeps task readable as stale without leaking unchecked snapshot');
$config->set(['max_source_rows' => 200], 'assistant_service');
$deny(fn () => $call('analyze', ['diagnosis_id' => 101, 'scenario' => 'followup', 'actor_id' => 1]), 'client cannot inject actor');
$deny(fn () => $call('job', ['id' => 1.1]), 'float identifiers rejected');
$deny(fn () => $call('adoptAction', $adopt + ['content' => str_repeat('字', 501)]), '500-character reminder constraint');
Db::name('tcm_diagnosis')->where('id', 101)->update(['patient_id' => 888]);
$deny(fn () => $call('job', ['id' => $job['id']], 1), 'patient rebinding protects historical snapshot even for root');
$ok($call('jobs', [], 1)['count'] === 0 && $call('actions', [], 1)['count'] === 0, 'lists exclude old patient binding');
Db::execute('DROP TABLE test_assistant_service_review');
$caps = $call('capabilities');
$ok(!$caps['schema_ready'] && !$caps['ready'] && str_contains($caps['reason'], '迁移'), 'missing schema clearly reported');
echo 'ASSISTANT_SERVICE_API assertions=' . $checks . ' PASS sqlite=memory real_access_context_logic=1 network=0' . PHP_EOL;
@@ -0,0 +1,307 @@
<?php
declare(strict_types=1);
// 真实 ORM 与权限/业务代码,临时 SQLite;不初始化应用、不读 .env、不联网。
require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
use app\adminapi\logic\tcm\AssistantServiceLogic as Logic;
use app\adminapi\validate\tcm\AssistantServiceValidate as Validate;
use app\common\service\assistantservice\AssistantServiceAccess as Access;
use app\common\service\assistantservice\AssistantServiceContext as Context;
use app\common\service\assistantservice\AssistantServiceAutomation as Automation;
use think\Container;
use think\facade\Db;
if (!in_array('sqlite', PDO::getAvailableDrivers(), true)) {
throw new RuntimeException('Run: php -d extension=php_pdo_sqlite.dll tests/AssistantServiceApiTest.php');
}
new think\App();
set_exception_handler(static function (Throwable $e): void {
fwrite(STDERR, $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL); exit(1);
});
$manager = new think\DbManager();
$manager->setConfig(['default' => 'isolated', 'connections' => ['isolated' => [
'type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'test_', 'fields_strict' => true,
]]]);
Container::getInstance()->instance('think\DbManager', $manager);
think\Model::setDb($manager);
$config = new think\Config();
$config->set(['enabled' => true, 'profile' => 'qwen', 'timeout' => 120, 'daily_job_limit' => 100,
'max_source_rows' => 200, 'max_source_chars' => 30000, 'max_manual_chars' => 10000, 'max_knowledge_rows' => 40], 'assistant_service');
$config->set(['enable' => true, 'base_url' => 'https://example.invalid', 'models' => [
'qwen' => ['name' => 'synthetic', 'api_key' => 'synthetic-no-network']]], 'prescription_ai');
$config->set(['data_scope' => ['enabled' => true, 'no_dept_fallback_self' => true]], 'project');
Container::getInstance()->instance('config', $config);
$tables = [
'admin' => 'id INTEGER PRIMARY KEY,name TEXT,root INTEGER DEFAULT 0,disable INTEGER DEFAULT 0,delete_time INTEGER NULL',
'admin_role' => 'admin_id INTEGER,role_id INTEGER',
'admin_dept' => 'admin_id INTEGER,dept_id INTEGER',
'dept' => 'id INTEGER PRIMARY KEY,pid INTEGER,status INTEGER DEFAULT 1,delete_time INTEGER NULL',
'system_role' => 'id INTEGER PRIMARY KEY,name TEXT,data_scope INTEGER,delete_time INTEGER NULL',
'system_role_menu' => 'role_id INTEGER,menu_id INTEGER',
'system_menu' => 'id INTEGER PRIMARY KEY,perms TEXT,is_disable INTEGER DEFAULT 0',
'doctor_appointment' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,doctor_id INTEGER,status INTEGER',
'tcm_diagnosis' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,assistant_id INTEGER,patient_name TEXT,phone TEXT,status INTEGER DEFAULT 1,delete_time INTEGER NULL',
'tracking_note' => 'id INTEGER PRIMARY KEY,diagnosis_id INTEGER,admin_id INTEGER,note_date TEXT,content TEXT,create_time INTEGER,update_time INTEGER,delete_time INTEGER NULL',
'tcm_im_chat_message' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,diagnosis_id INTEGER,from_account TEXT,to_account TEXT,doctor_peer_account TEXT,msg_type TEXT,text TEXT,msg_time INTEGER',
'tcm_diagnosis_todo' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,patient_id INTEGER,content TEXT,remind_time INTEGER,status INTEGER,creator_id INTEGER,creator_name TEXT,create_time INTEGER,update_time INTEGER,notified_at INTEGER DEFAULT 0,cancelled_at INTEGER DEFAULT 0,cancelled_by INTEGER DEFAULT 0,delete_time INTEGER NULL',
'assistant_service_record' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,patient_id INTEGER,actor_id INTEGER,content TEXT,record_type TEXT,speaker_confirmed INTEGER,occurred_at INTEGER,created_at INTEGER,delete_time INTEGER NULL',
'assistant_service_job' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,patient_id INTEGER,actor_id INTEGER,type TEXT,scenario TEXT,days INTEGER,status TEXT,version INTEGER,dedupe_key TEXT UNIQUE,source_hash TEXT,scope_hash TEXT,payload_json TEXT,result_json TEXT,claim_token TEXT DEFAULT "",lease_until INTEGER DEFAULT 0,error_code TEXT DEFAULT "",error_message TEXT DEFAULT "",upstream_id TEXT DEFAULT "",created_at INTEGER,updated_at INTEGER,finished_at INTEGER DEFAULT 0',
'assistant_service_review' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,job_id INTEGER,item_key TEXT,reviewer_id INTEGER,decision TEXT,note TEXT,created_at INTEGER',
'assistant_service_action' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,job_id INTEGER,action_key TEXT,todo_id INTEGER,assignee_id INTEGER,content TEXT,due_at INTEGER,business_state TEXT,completion_note TEXT DEFAULT "",completed_at INTEGER DEFAULT 0,created_at INTEGER,updated_at INTEGER,UNIQUE(job_id,action_key)',
'assistant_service_knowledge' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,question TEXT,answer TEXT,category TEXT,source_note TEXT,status TEXT,version INTEGER,created_by INTEGER,published_by INTEGER,created_at INTEGER,updated_at INTEGER',
];
foreach ($tables as $name => $schema) { Db::execute('CREATE TABLE test_' . $name . ' (' . $schema . ')'); }
Db::name('admin')->insertAll([
['id' => 1, 'name' => 'root', 'root' => 1], ['id' => 11, 'name' => 'assistant', 'root' => 0],
['id' => 12, 'name' => 'other', 'root' => 0], ['id' => 13, 'name' => 'team', 'root' => 0], ['id' => 14, 'name' => 'doctor', 'root' => 0],
]);
Db::name('system_role')->insertAll([
['id' => 1, 'name' => '医生', 'data_scope' => 1], ['id' => 2, 'name' => '医助', 'data_scope' => 4], ['id' => 3, 'name' => '经理', 'data_scope' => 3],
]);
Db::name('admin_role')->insertAll([['admin_id' => 11, 'role_id' => 2], ['admin_id' => 12, 'role_id' => 2], ['admin_id' => 13, 'role_id' => 3], ['admin_id' => 14, 'role_id' => 1]]);
Db::name('dept')->insertAll([['id' => 10, 'pid' => 0], ['id' => 20, 'pid' => 0]]);
Db::name('admin_dept')->insertAll([['admin_id' => 11, 'dept_id' => 10], ['admin_id' => 12, 'dept_id' => 20], ['admin_id' => 13, 'dept_id' => 10]]);
foreach (Access::PERMISSIONS as $i => $permission) {
Db::name('system_menu')->insert(['id' => $i + 1, 'perms' => 'tcm.assistantService/' . $permission]);
foreach ([1, 2, 3] as $role) { Db::name('system_role_menu')->insert(['role_id' => $role, 'menu_id' => $i + 1]); }
}
Db::name('tcm_diagnosis')->insertAll([
['id' => 101, 'patient_id' => 201, 'assistant_id' => 11, 'patient_name' => '合成甲', 'phone' => '13800138000'],
['id' => 102, 'patient_id' => 202, 'assistant_id' => 12, 'patient_name' => '合成乙', 'phone' => '13900139000'],
['id' => 103, 'patient_id' => 0, 'assistant_id' => 11, 'patient_name' => '未映射', 'phone' => ''],
]);
Db::name('doctor_appointment')->insert(['id' => 1, 'patient_id' => 101, 'doctor_id' => 14, 'status' => 1]);
$now = time();
Db::name('tracking_note')->insert(['id' => 1, 'diagnosis_id' => 101, 'admin_id' => 11,
'note_date' => date('Y-m-d'), 'content' => '患者要求周六确认预约', 'create_time' => $now, 'update_time' => $now]);
foreach ([
[1, 201, 'patient_201', 'doctor_11', 'text', '请帮我核对预约,电话13800138000'],
[2, 201, 'doctor_11', 'patient_201', 'text', '我将在明天回复可预约时段'],
[3, 201, 'doctor_12', 'patient_201', 'text', '其他部门私有沟通'],
[4, 201, 'doctor_11', 'patient_999', 'text', '错误患者映射'],
[5, 201, 'doctor_11', 'patient_201', 'image', '不可读图片'],
[6, 201, 'doctor_999', 'patient_201', 'text', '不存在的员工'],
] as [$id, $patient, $from, $to, $type, $text]) {
Db::name('tcm_im_chat_message')->insert(['id' => $id, 'patient_id' => $patient, 'diagnosis_id' => 999,
'from_account' => $from, 'to_account' => $to, 'doctor_peer_account' => 'doctor_11', 'msg_type' => $type, 'text' => $text, 'msg_time' => $now - 100]);
}
$checks = 0;
$ok = static function (bool $condition, string $label) use (&$checks): void {
if (!$condition) { throw new RuntimeException($label); } $checks++;
};
$temporary = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'assistant-auto-test-' . bin2hex(random_bytes(8));
$clock = time();
$automation = new Automation($temporary, static function () use (&$clock): int { return $clock; });
$tick = static function (int $times = 1) use ($automation, &$clock): array {
$result = [];
for ($i = 0; $i < $times; $i++) { $clock += 61; $result = $automation->tick(); }
return $result;
};
$manual = static function (int $diagnosis, int $patient, int $assistant = 11, ?int $at = null) use ($now): int {
return (int) Db::name('assistant_service_record')->insertGetId(['diagnosis_id' => $diagnosis, 'patient_id' => $patient,
'actor_id' => $assistant, 'content' => '合成服务记录 ' . $diagnosis, 'record_type' => 'service_note',
'speaker_confirmed' => 0, 'occurred_at' => $at ?? $now - 1000, 'created_at' => $now - 1000]);
};
$diagnosis = static function (int $id, int $assistant = 11): void {
Db::name('tcm_diagnosis')->insert(['id' => $id, 'patient_id' => $id + 1000, 'assistant_id' => $assistant,
'patient_name' => '合成测试 ' . $id, 'phone' => '']);
};
$jobCount = static fn (): int => (int) Db::name('assistant_service_job')->count();
$clear = static function () use ($temporary): void {
foreach (['assistant_service_job', 'assistant_service_record', 'tracking_note', 'tcm_im_chat_message'] as $table) { Db::name($table)->where('id', '>', 0)->delete(); }
$scan = $temporary . DIRECTORY_SEPARATOR . 'scan.json';
if (is_file($scan)) { unlink($scan); }
};
try {
$ok(Automation::status($temporary)['state'] === 'disabled' && !is_dir($temporary), 'disabled status is read-only and needs no runtime directory');
$ok($automation->tick()['state'] === 'disabled' && !is_dir($temporary), 'default disabled tick never discovers candidates');
$config->set(['auto_enabled' => true, 'auto_actor_id' => 0, 'auto_interval_seconds' => 60,
'auto_quiet_seconds' => 300, 'auto_batch_size' => 10], 'assistant_service');
$ok($tick()['state'] === 'error' && $jobCount() === 0, 'unbound actor does not choose existing root');
$config->set(['auto_actor_id' => 11], 'assistant_service');
$ok($tick()['state'] === 'error', 'analyze-enabled frontline account is not a scheduler manager');
$config->set(['auto_actor_id' => 13], 'assistant_service');
Db::name('admin')->where('id', 13)->update(['disable' => 1]);
$ok($tick()['state'] === 'error', 'disabled configured manager rejected');
Db::name('admin')->where('id', 13)->update(['disable' => 0]);
Db::name('system_role_menu')->where('role_id', 3)->where('menu_id', 2)->delete();
$ok($tick()['state'] === 'error', 'configured manager must retain analyze permission');
Db::name('system_role_menu')->insert(['role_id' => 3, 'menu_id' => 2]);
$config->set(['enabled' => false], 'assistant_service');
$ok($tick()['state'] === 'error', 'model feature switch respected');
$config->set(['enabled' => true], 'assistant_service');
$config->set(['enable' => false], 'prescription_ai');
$ok($tick()['state'] === 'error', 'incomplete model settings do not enqueue');
$config->set(['enable' => true], 'prescription_ai');
$clear();
$ok($tick()['enqueued'] === 0 && $jobCount() === 0, 'assigned empty diagnoses never manufacture tasks');
$ok(str_contains(Automation::status($temporary, $clock)['reason'], '没有新增待分析来源'), 'empty scan explicitly waits for sources');
$ok(Automation::status($temporary, $clock)['state'] === 'waiting', 'scheduler alone is not falsely reported fully running');
Automation::workerHeartbeat('idle', $temporary, $clock);
$ok(Automation::status($temporary, $clock)['state'] === 'running', 'real completed worker polling plus scan heartbeat is running');
$ok(Automation::status($temporary, $clock + 181)['state'] === 'waiting', 'expired scanner heartbeat is waiting');
Automation::workerHeartbeat('stopped', $temporary, $clock);
$ok(Automation::status($temporary, $clock)['state'] === 'waiting', 'stopped worker not reported active');
$ok($automation->tick()['scanned'] === 0, 'persisted interval prevents frequent external ticks');
// 真正第二进程持锁:主进程不能进入扫描,锁释放后恢复。
$pipes = [];
$child = proc_open([PHP_BINARY, '-r', '$h=fopen($argv[1],"c+b");flock($h,LOCK_EX);echo "LOCKED\n";fflush(STDOUT);fgets(STDIN);fclose($h);',
$temporary . DIRECTORY_SEPARATOR . 'scan.lock'], [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
$ok(is_resource($child) && trim((string) fgets($pipes[1])) === 'LOCKED', 'independent process owns real flock');
$blocked = $tick();
$ok($blocked['scanned'] === 0 && str_contains($blocked['reason'], '另一'), 'second process is excluded from scanning');
fwrite($pipes[0], "release\n"); fclose($pipes[0]); fclose($pipes[1]); fclose($pipes[2]);
$ok(proc_close($child) === 0 && $tick()['state'] === 'running', 'process lock releases without stale lease');
// 来源身份只能由可靠账号对/登记作者决定,不能借当前归属推断历史员工。
$manual(101, 201);
$manual(102, 202, 12);
$manual(103, 999); // 旧患者绑定。
$manual(103, 0, 11, $now - 40 * 86400);
Db::name('tcm_im_chat_message')->insert(['id' => 20, 'patient_id' => 201, 'diagnosis_id' => 101,
'from_account' => 'doctor_11', 'to_account' => 'patient_999', 'msg_type' => 'text', 'text' => '错误映射', 'msg_time' => $now - 1000]);
$first = $tick();
$ok($first['enqueued'] === 1 && $jobCount() === 1, 'first scan covers existing 30-day manual source but excludes cross-scope, old and mismapped');
$stored = Db::name('assistant_service_job')->order('id', 'asc')->find();
$payload = json_decode($stored['payload_json'], true);
$ok((int) $stored['actor_id'] === 13 && $payload['context']['subject_admin_id'] === 11 && $payload['trigger'] === 'automatic', 'actual configured actor and explicit subject are preserved');
$ok(!str_contains(json_encode($payload['context']['sources']), '错误映射'), 'false IM mapping never enters context');
$tick(3);
$ok($jobCount() === 1, 'queued snapshot never repeats across cursor cycles');
Db::name('assistant_service_job')->where('id', $stored['id'])->update(['status' => 'failed', 'error_code' => 'INTERNAL_ERROR']);
$tick(3);
$ok($jobCount() === 1 && Db::name('assistant_service_job')->where('id', $stored['id'])->value('status') === 'failed', 'automatic scan never resets even safely retryable failure');
$manual(101, 201);
$tick(3);
$ok($jobCount() === 2, 'new content may create a new snapshot after definite terminal failure');
$latest = Db::name('assistant_service_job')->order('id', 'desc')->find();
Db::name('assistant_service_job')->where('id', $latest['id'])->update(['status' => 'needs_reconciliation']);
$manual(101, 201);
$tick(3);
$ok($jobCount() === 2, 'unknown earlier result blocks new snapshot even when new content exists');
Db::name('assistant_service_job')->where('id', $latest['id'])->update(['status' => 'ready']);
$tick(3);
$ok($jobCount() === 3, 'resolved terminal allows newly arrived content');
Db::name('assistant_service_job')->where('status', 'queued')->update(['status' => 'ready']);
$oldestRecord = Db::name('assistant_service_record')->where('diagnosis_id', 101)->order('id', 'asc')->value('id');
Db::name('assistant_service_record')->where('id', $oldestRecord)->delete();
$tick(3);
$ok($jobCount() === 3, 'shrinking source set does not regenerate merely because hash changed');
$newestRecord = Db::name('assistant_service_record')->where('diagnosis_id', 101)->order('id', 'desc')->value('id');
Db::name('assistant_service_record')->where('id', $newestRecord)->update(['content' => '合成登记内容已修订']);
$tick(3);
$ok($jobCount() === 4, 'changed actual source text receives a new snapshot');
$clear();
$diagnosis(110);
Db::name('admin')->insert(['id' => 15, 'name' => '无菜单目标医助', 'root' => 0]);
Db::name('system_role')->insert(['id' => 22, 'name' => '医助', 'data_scope' => 4]);
Db::name('admin_role')->insert(['admin_id' => 15, 'role_id' => 22]);
Db::name('admin_dept')->insert(['admin_id' => 15, 'dept_id' => 10]);
Db::name('tcm_diagnosis')->insert(['id' => 112, 'patient_id' => 1110, 'assistant_id' => 11, 'patient_name' => '相同患者新诊单', 'phone' => '']);
Db::name('tcm_im_chat_message')->insert(['id' => 30, 'patient_id' => 1110, 'diagnosis_id' => 999,
'from_account' => 'patient_1110', 'to_account' => 'doctor_15', 'msg_type' => 'text', 'text' => '历史医助可靠收信', 'msg_time' => $now - 1000]);
$ok($tick()['enqueued'] === 1, 'reliable incoming IM discovers historical target without menu or current assignment');
$payload = json_decode(Db::name('assistant_service_job')->value('payload_json'), true);
$ok($payload['context']['subject_admin_id'] === 15 && $payload['context']['sources'][0]['speaker'] === 'patient', 'incoming patient words are never attributed to employee');
$tick(3);
$ok($jobCount() === 1 && (int) Db::name('assistant_service_job')->value('diagnosis_id') === 112, 'same patient IM is queued only for latest authorized active diagnosis');
Db::name('assistant_service_job')->where('status', 'queued')->update(['status' => 'ready']);
Db::name('tcm_diagnosis')->insert(['id' => 113, 'patient_id' => 1110, 'assistant_id' => 11, 'patient_name' => '又一新诊单', 'phone' => '']);
$tick(3);
$ok($jobCount() === 1, 'new diagnosis alone cannot replay already analyzed identical patient conversation');
$clear();
$diagnosis(111);
Db::name('tracking_note')->insert(['id' => 40, 'diagnosis_id' => 111, 'admin_id' => 15,
'note_date' => date('Y-m-d', $now - 86400), 'content' => '历史目标跟踪备注', 'create_time' => $now - 1000, 'update_time' => $now - 1000]);
$ok($tick()['enqueued'] === 1, 'authored tracking alone is discovered for historical target');
$payload = json_decode(Db::name('assistant_service_job')->value('payload_json'), true);
$ok($payload['context']['subject_admin_id'] === 15 && !$payload['context']['sources'][0]['quality_eligible'], 'tracking remains non-attributable quality evidence');
$clear();
$clock = time();
$manualId = $manual(101, 201);
Db::name('assistant_service_record')->where('id', $manualId)->update(['created_at' => $clock]);
$quiet = $tick();
$ok($quiet['quiet'] === 1 && $jobCount() === 0, 'backdated manual record respects real insertion quiet window');
$tick(7);
$ok($jobCount() === 1, 'quiet candidates return after cursor wrap and eventually enqueue');
$clear();
Db::name('tracking_note')->insert(['id' => 41, 'diagnosis_id' => 101, 'admin_id' => 11,
'note_date' => date('Y-m-d', $now - 86400), 'content' => '最近追加到旧日期', 'create_time' => $now - 1000, 'update_time' => $clock]);
$ok($tick()['quiet'] === 1 && $jobCount() === 0, 'tracking update time participates in quiet window');
$tick(7);
$ok($jobCount() === 1, 'tracking candidate resumes after quiet window');
$clear();
$manual(101, 201);
Db::name('admin_dept')->where('admin_id', 11)->update(['dept_id' => 20]);
$ok($tick()['enqueued'] === 0 && $jobCount() === 0, 'scope revocation effective on next scan');
Db::name('admin_dept')->where('admin_id', 11)->update(['dept_id' => 10]);
$ok($tick()['enqueued'] === 1, 'restored authorized sources remain discoverable');
$clear();
$manual(101, 201);
Db::name('tcm_diagnosis')->where('id', 101)->update(['delete_time' => $now]);
$ok($tick()['enqueued'] === 0, 'deleted diagnosis excluded at discovery');
Db::name('tcm_diagnosis')->where('id', 101)->update(['delete_time' => null]);
$clear();
$config->set(['auto_batch_size' => 1], 'assistant_service');
for ($i = 200; $i < 240; $i++) { $diagnosis($i); $manual($i, $i + 1000); }
$first = $tick();
$ok($first['enqueued'] === 1 && $first['scanned'] <= 30, 'one-round queue and source scan are bounded');
for ($i = 0; $i < 60; $i++) { $tick(); }
$ids = array_unique(Db::name('assistant_service_job')->column('diagnosis_id'));
$ok(count($ids) === 40 && $jobCount() === 40, 'persistent keyset cursor reaches every source beyond first page without duplicates');
$replacement = new Automation($temporary, static function () use (&$clock): int { return $clock; });
$clock += 61;
$ok($replacement->tick()['enqueued'] === 0 && $jobCount() === 40, 'restart reuses durable cursor and queue dedupe');
$clear();
$config->set(['auto_batch_size' => 10, 'daily_job_limit' => 1], 'assistant_service');
$manual(200, 1200); $manual(201, 1201);
$limited = $tick();
$ok($limited['enqueued'] === 1 && $limited['state'] === 'waiting' && str_contains($limited['reason'], '上限'), 'daily allowance stops explicitly after accepted work');
$config->set(['daily_job_limit' => 100], 'assistant_service');
$ok($tick()['enqueued'] === 1 && $jobCount() === 2, 'quota-blocked source cursor is preserved for next allowed scan');
$clear();
$config->set(['max_source_rows' => 1], 'assistant_service');
$manual(200, 1200); $manual(200, 1200); $manual(201, 1201);
$over = $tick();
$ok($over['source_limit'] === 1 && $over['enqueued'] === 1 && $jobCount() === 1, 'oversized source set is skipped while later valid candidates continue');
Automation::workerHeartbeat('idle', $temporary, $clock);
$ok(str_contains(Automation::status($temporary, $clock)['reason'], '超出分析上限'), 'persistent skipped source limit is clearly surfaced in health reason');
$tick();
Automation::workerHeartbeat('idle', $temporary, $clock);
$ok(str_contains(Automation::status($temporary, $clock)['reason'], '超出分析上限'), 'empty cursor page does not hide unresolved source limit warning');
$config->set(['max_source_rows' => 200], 'assistant_service');
$clear();
Db::execute('DROP TABLE test_tcm_im_chat_message');
$manual(200, 1200);
$partial = $tick();
$ok($partial['unavailable_channels'] === 1 && $partial['enqueued'] === 1, 'missing optional IM archive still processes verified manual sources');
$ok(str_contains($partial['reason'], '来源暂不可用'), 'unavailable source is reported without fabricated zero compliance');
$encoded = json_encode(Automation::status($temporary, $clock), JSON_UNESCAPED_UNICODE);
$ok(!str_contains($encoded, 'actor_id') && !str_contains($encoded, '合成') && !str_contains($encoded, 'patient_id'), 'public status reveals no actor, patient or source text');
file_put_contents($temporary . DIRECTORY_SEPARATOR . 'scan.json', '{broken');
$ok(Automation::status($temporary, $clock)['state'] === 'error', 'damaged heartbeat is explicit error rather than fictional running');
echo 'ASSISTANT_SERVICE_AUTOMATION assertions=' . $checks . ' PASS sqlite=memory real_access_context_enqueue=1 multiprocess_flock=1 network=0' . PHP_EOL;
} finally {
// 只清理本测试生成的确切文件,不递归删除计算路径。
foreach (['scan.json', 'scan.lock', 'workers.json', 'workers.lock'] as $name) {
$path = $temporary . DIRECTORY_SEPARATOR . $name;
if (is_file($path)) { unlink($path); }
}
if (is_dir($temporary)) { rmdir($temporary); }
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
/** 仅显式授权的15339隔离MySQL及已核实目录;不加载框架/.env,不连接业务库。 */
$port = (int) getenv('ASSISTANT_SERVICE_TEST_PORT');
$expectedDirectory = str_replace('\\', '/', (string) getenv('ASSISTANT_SERVICE_TEST_DATADIR'));
if (getenv('ASSISTANT_SERVICE_TEST_ALLOW_DISPOSABLE') !== '1' || $port !== 15339
|| $expectedDirectory === '' || !str_contains(strtolower($expectedDirectory), '/.spool/assistant-service-mysql')) {
throw new RuntimeException('必须显式提供15339隔离测试库端口和项目临时数据目录指纹');
}
$pdo = new PDO("mysql:host=127.0.0.1;port={$port};charset=utf8mb4", 'root', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$actual = str_replace('\\', '/', (string) $pdo->query('SELECT @@datadir')->fetchColumn());
if (strtolower(rtrim($actual, '/')) !== strtolower(rtrim($expectedDirectory, '/'))) { throw new RuntimeException('数据目录不匹配,拒绝创建测试数据库'); }
$database = 'daily_contact_test_' . bin2hex(random_bytes(6)); $checks = 0;
$ok = static function (bool $condition, string $message) use (&$checks): void { if (!$condition) { throw new RuntimeException($message); } $checks++; };
$sql = preg_replace('/^--.*$/m', '', (string) file_get_contents(dirname(__DIR__) . '/sql/1.9.20261110/01_assistant_service_daily_contact.sql'));
$migrate = static function () use ($pdo, $sql): void {
foreach (explode(';', (string) $sql) as $statement) { if (trim($statement) !== '') { $query = $pdo->query($statement); $query->closeCursor(); } }
};
$pdo->exec("CREATE DATABASE `{$database}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
try {
$pdo->exec("USE `{$database}`");
$pdo->exec('CREATE TABLE zyt_assistant_service_action(id BIGINT UNSIGNED PRIMARY KEY,diagnosis_id INT,assignee_id INT,business_state VARCHAR(20),completed_at INT,completion_note VARCHAR(200)) ENGINE=InnoDB');
$pdo->exec("INSERT INTO zyt_assistant_service_action VALUES(1,101,11,'completed',1234,'历史哨兵')");
$pdo->exec('CREATE TABLE zyt_tcm_diagnosis_todo(id INT PRIMARY KEY,status INT,notified_at INT) ENGINE=InnoDB');
$pdo->exec('INSERT INTO zyt_tcm_diagnosis_todo VALUES(1,1,1234)');
$before = $pdo->query('SELECT * FROM zyt_assistant_service_action')->fetchAll(PDO::FETCH_ASSOC);
$todos = $pdo->query('SELECT * FROM zyt_tcm_diagnosis_todo')->fetchAll(PDO::FETCH_ASSOC);
$migrate();
$columns = $pdo->query('SHOW COLUMNS FROM zyt_assistant_service_action')->fetchAll(PDO::FETCH_ASSOC);
$columns = array_column($columns, null, 'Field');
$ok(isset($columns['contact_required'], $columns['completed_by']), '缺少明确联系标记或真实完成操作者字段');
$ok((string) $columns['contact_required']['Default'] === '0' && (string) $columns['completed_by']['Default'] === '0', '旧动作不应自动推断联系属性或操作者');
$row = $pdo->query('SELECT * FROM zyt_assistant_service_action WHERE id=1')->fetch(PDO::FETCH_ASSOC);
$ok((int) $row['contact_required'] === 0 && (int) $row['completed_by'] === 0, '历史动作必须保留未知属性');
unset($row['contact_required'], $row['completed_by']);
$ok($row === $before[0], '迁移不应改写历史执行记录');
$pdo->exec('UPDATE zyt_assistant_service_action SET contact_required=1,completed_by=13 WHERE id=1');
$insert = $pdo->prepare('INSERT INTO zyt_assistant_service_daily_contact(business_date,assistant_id,diagnosis_id,patient_id,source_type,source_id,source_order_id,reason,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?)');
$insert->execute(['2026-11-10',11,101,201,'revisit',1,100,'合成到期',1000,1000]);
$plan = $pdo->query('SELECT * FROM zyt_assistant_service_daily_contact')->fetchAll(PDO::FETCH_ASSOC);
$migrate(); $migrate();
$ok($plan === $pdo->query('SELECT * FROM zyt_assistant_service_daily_contact')->fetchAll(PDO::FETCH_ASSOC), '重复迁移不应改写计划');
$row = $pdo->query('SELECT contact_required,completed_by FROM zyt_assistant_service_action WHERE id=1')->fetch(PDO::FETCH_ASSOC);
$ok((int) $row['contact_required'] === 1 && (int) $row['completed_by'] === 13, '重复迁移不应覆盖新增字段真实值');
$ok($todos === $pdo->query('SELECT * FROM zyt_tcm_diagnosis_todo')->fetchAll(PDO::FETCH_ASSOC), '迁移不应改变提醒status或notified_at');
$duplicate = false;
try { $insert->execute(['2026-11-10',11,101,201,'revisit',1,100,'重复',1001,1001]); }
catch (PDOException $e) { $duplicate = $e->getCode() === '23000'; }
$ok($duplicate, '数据库未保护当日来源幂等');
foreach ([['2026-11-10',11,101,201,'revisit',1,101], ['2026-11-11',11,101,201,'revisit',1,100], ['2026-11-10',15,101,201,'revisit',1,100], ['2026-11-10',11,101,201,'action',1,0]] as $values) {
$insert->execute(array_merge($values, ['独立责任/周期',1001,1001]));
}
$ok((int) $pdo->query('SELECT COUNT(*) FROM zyt_assistant_service_daily_contact')->fetchColumn() === 5, '新周期、新自然日、新责任医助、另一来源须可独立入计划');
$indexes = $pdo->query('SHOW INDEX FROM zyt_assistant_service_daily_contact')->fetchAll(PDO::FETCH_ASSOC);
$ok(in_array('idx_day_cursor', array_column($indexes, 'Key_name'), true) && in_array('idx_day_staff_patient', array_column($indexes, 'Key_name'), true), '缺少日游标或医助患者聚合索引');
echo 'ASSISTANT_SERVICE_DAILY_CONTACT_MIGRATION assertions=' . $checks . ' PASS mysql=' . $pdo->query('SELECT VERSION()')->fetchColumn() . ' disposable=1 migration_runs=3' . PHP_EOL;
} finally {
if (preg_match('/^daily_contact_test_[a-f0-9]{12}$/D', $database)) { $pdo->exec("DROP DATABASE `{$database}`"); }
}
@@ -0,0 +1,214 @@
<?php
declare(strict_types=1);
// 真实 ThinkPHP ORM/权限服务,合成 SQLite 内存库;不初始化应用、不读 .env、不联网。
require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
use app\common\service\assistantservice\AssistantServiceAccess as Access;
use app\common\service\assistantservice\AssistantServiceDailyContact as Daily;
use think\Container;
use think\facade\Db;
if (!in_array('sqlite', PDO::getAvailableDrivers(), true)) { throw new RuntimeException('需要隔离测试 SQLite 扩展'); }
new think\App();
set_exception_handler(static function (Throwable $e): void { fwrite(STDERR, $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL); exit(1); });
$manager = new think\DbManager();
$manager->setConfig(['default' => 'isolated', 'connections' => ['isolated' => ['type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'test_', 'fields_strict' => true]]]);
Container::getInstance()->instance('think\DbManager', $manager); think\Model::setDb($manager);
$config = new think\Config();
$config->set(['enabled' => false, 'daily_contact_enabled' => true, 'daily_contact_actor_id' => 13,
'daily_contact_interval_seconds' => 60, 'daily_contact_batch_size' => 500], 'assistant_service');
$config->set(['data_scope' => ['enabled' => true, 'no_dept_fallback_self' => true]], 'project');
Container::getInstance()->instance('config', $config);
$tables = [
'admin' => 'id INTEGER PRIMARY KEY,name TEXT,root INTEGER DEFAULT 0,disable INTEGER DEFAULT 0,delete_time INTEGER NULL',
'admin_role' => 'admin_id INTEGER,role_id INTEGER', 'admin_dept' => 'admin_id INTEGER,dept_id INTEGER',
'dept' => 'id INTEGER PRIMARY KEY,pid INTEGER,status INTEGER DEFAULT 1,delete_time INTEGER NULL',
'system_role' => 'id INTEGER PRIMARY KEY,name TEXT,data_scope INTEGER,delete_time INTEGER NULL',
'system_role_menu' => 'role_id INTEGER,menu_id INTEGER', 'system_menu' => 'id INTEGER PRIMARY KEY,perms TEXT,is_disable INTEGER DEFAULT 0',
'doctor_appointment' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,doctor_id INTEGER,status INTEGER',
'tcm_diagnosis' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,assistant_id INTEGER,patient_name TEXT,phone TEXT,status INTEGER DEFAULT 1,delete_time INTEGER NULL',
'tcm_prescription_order' => 'id INTEGER PRIMARY KEY,diagnosis_id INTEGER,fulfillment_status INTEGER DEFAULT 1,delete_time INTEGER NULL',
'tcm_diagnosis_revisit_due' => 'id INTEGER PRIMARY KEY,diagnosis_id INTEGER,assistant_id INTEGER,source_order_id INTEGER,due_date TEXT,promised_date TEXT NULL,closed_state INTEGER DEFAULT 0,appointment_state INTEGER DEFAULT 0',
'tcm_diagnosis_revisit_due_log' => 'id INTEGER PRIMARY KEY,diagnosis_id INTEGER,assistant_id INTEGER,source_order_id INTEGER,event INTEGER,operator_id INTEGER,create_time INTEGER',
'tcm_im_chat_message' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,from_account TEXT COLLATE NOCASE,to_account TEXT,msg_type TEXT,text TEXT,msg_time INTEGER',
'assistant_service_job' => 'id INTEGER PRIMARY KEY,diagnosis_id INTEGER,patient_id INTEGER',
'assistant_service_action' => 'id INTEGER PRIMARY KEY,diagnosis_id INTEGER,job_id INTEGER,assignee_id INTEGER,due_at INTEGER,business_state TEXT DEFAULT "pending",completed_at INTEGER DEFAULT 0,completed_by INTEGER DEFAULT 0,contact_required INTEGER DEFAULT 0',
'assistant_service_daily_contact' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,business_date TEXT,assistant_id INTEGER,diagnosis_id INTEGER,patient_id INTEGER,source_type TEXT,source_id INTEGER,source_order_id INTEGER DEFAULT 0,reason TEXT,due_at INTEGER,state TEXT DEFAULT "active",exempt_reason TEXT DEFAULT "",created_at INTEGER,updated_at INTEGER,UNIQUE(business_date,assistant_id,source_type,source_id,source_order_id)',
];
foreach ($tables as $name => $schema) { Db::execute('CREATE TABLE test_' . $name . ' (' . $schema . ')'); }
Db::name('admin')->insertAll([['id' => 1, 'name' => 'root', 'root' => 1], ['id' => 11, 'name' => '甲', 'root' => 0],
['id' => 12, 'name' => '域外', 'root' => 0], ['id' => 13, 'name' => '主管', 'root' => 0], ['id' => 15, 'name' => '乙', 'root' => 0], ['id' => 14, 'name' => '医生', 'root' => 0]]);
Db::name('system_role')->insertAll([['id' => 1, 'name' => '医生', 'data_scope' => 1], ['id' => 2, 'name' => '医助', 'data_scope' => 4], ['id' => 3, 'name' => '经理', 'data_scope' => 3]]);
Db::name('admin_role')->insertAll([['admin_id' => 11, 'role_id' => 2], ['admin_id' => 12, 'role_id' => 2], ['admin_id' => 13, 'role_id' => 3], ['admin_id' => 15, 'role_id' => 2], ['admin_id' => 14, 'role_id' => 1]]);
Db::name('dept')->insertAll([['id' => 10, 'pid' => 0], ['id' => 20, 'pid' => 0]]);
Db::name('admin_dept')->insertAll([['admin_id' => 11, 'dept_id' => 10], ['admin_id' => 12, 'dept_id' => 20], ['admin_id' => 13, 'dept_id' => 10], ['admin_id' => 15, 'dept_id' => 10]]);
Db::name('system_menu')->insert(['id' => 1, 'perms' => 'tcm.assistantService/view']);
Db::name('system_role_menu')->insertAll([['role_id' => 1, 'menu_id' => 1], ['role_id' => 2, 'menu_id' => 1], ['role_id' => 3, 'menu_id' => 1]]);
$clock = (new DateTimeImmutable('2026-11-10 12:00:00', new DateTimeZone('Asia/Shanghai')))->getTimestamp();
$day = Daily::day($clock); $temporary = sys_get_temp_dir() . '/daily-contact-test-' . bin2hex(random_bytes(6));
$daily = new Daily($temporary, static function () use (&$clock): int { return $clock; });
$checks = 0;
$ok = static function (bool $pass, string $message) use (&$checks): void { if (!$pass) { throw new RuntimeException($message); } $checks++; };
$deny = static function (callable $call, string $message) use ($ok): void { try { $call(); } catch (DomainException $e) { $ok(true, $message); return; } $ok(false, $message); };
$team = static function (int $admin = 13, ?array $ids = null) use ($daily): array {
$actor = Access::actor($admin); $staff = Access::assistantRows($admin, $actor);
if ($ids !== null) { $staff = array_values(array_filter($staff, static fn (array $s): bool => in_array($s['id'], $ids, true))); }
return $daily->teamReport($staff, $admin, $actor);
};
$patients = static fn (array $p = [], int $admin = 13): array => $daily->patientReport($p + ['assistant_id' => 11, 'status' => 'all', 'page_no' => 1, 'page_size' => 50], $admin);
$tick = static function () use ($daily, &$clock): array { $clock += 61; return $daily->tick(); };
$diagnosis = static function (int $id, int $patient = -1, int $assistant = 11): void {
Db::name('tcm_diagnosis')->insert(['id' => $id, 'patient_id' => $patient < 0 ? $id + 1000 : $patient, 'assistant_id' => $assistant, 'patient_name' => '合成' . $id, 'phone' => '']);
};
$revisit = static function (int $id, ?string $due = '2026-11-10', ?string $promised = null, int $appointment = 0): void {
$d = Db::name('tcm_diagnosis')->where('id', $id)->find();
Db::name('tcm_prescription_order')->insert(['id' => $id * 10, 'diagnosis_id' => $id]);
Db::name('tcm_diagnosis_revisit_due')->insert(['id' => $id, 'diagnosis_id' => $id, 'assistant_id' => $d['assistant_id'],
'source_order_id' => $id * 10, 'due_date' => $due, 'promised_date' => $promised, 'appointment_state' => $appointment]);
};
$action = static function (int $id, int $diagnosisId, array $extra = []) use (&$clock): void {
$d = Db::name('tcm_diagnosis')->where('id', $diagnosisId)->find();
Db::name('assistant_service_job')->insert(['id' => $id, 'diagnosis_id' => $diagnosisId, 'patient_id' => $d['patient_id']]);
Db::name('assistant_service_action')->insert($extra + ['id' => $id, 'diagnosis_id' => $diagnosisId, 'job_id' => $id,
'assignee_id' => $d['assistant_id'], 'due_at' => $clock - 60, 'contact_required' => 1]);
};
$im = static function (int $id, int $patient, int $at, string $from = 'doctor_11', ?string $to = null, string $text = '合成联系', string $type = 'text'): void {
Db::name('tcm_im_chat_message')->insert(['id' => $id, 'patient_id' => $patient, 'from_account' => $from,
'to_account' => $to ?? 'patient_' . $patient, 'text' => $text, 'msg_type' => $type, 'msg_time' => $at]);
};
$log = static function (int $id, int $diagnosis, int $operator, int $at, int $event = 2, ?int $order = null): void {
Db::name('tcm_diagnosis_revisit_due_log')->insert(['id' => $id, 'diagnosis_id' => $diagnosis, 'assistant_id' => 11,
'source_order_id' => $order ?? $diagnosis * 10, 'operator_id' => $operator, 'event' => $event, 'create_time' => $at]);
};
try {
$ok($team()['meta']['state'] === 'waiting' && $team()['summary']['required'] === null, '无今日扫描不能伪装0任务');
$ok($daily->tick()['state'] === 'ready', '禁用AI仍可生成今日计划');
$ok($team()['summary']['state'] === 'no_tasks' && $team()['summary']['required'] === 0, '真实空来源明确无任务');
$ok($team()['by_staff'][15]['state'] === 'no_tasks', '每个输入医助均返回明确计数');
$deny(fn () => $patients(['assistant_id' => 12]), '明细不能越员工域');
$deny(fn () => $patients(['assistant_id' => 11], 14), '普通医生不能查看其他员工');
foreach ([101, 102, 103, 104, 105, 106, 107, 108, 109] as $id) { $diagnosis($id); }
$revisit(101); $revisit(102, '2026-11-01', '2026-11-10'); $revisit(103, '2026-11-01', '2026-11-11');
$revisit(104, null); $revisit(105, null, null, 4); $revisit(106, '2026-11-11');
$revisit(107); Db::name('tcm_diagnosis_revisit_due')->where('id', 107)->update(['closed_state' => 4]);
$revisit(108); Db::name('tcm_diagnosis_revisit_due')->where('id', 108)->update(['assistant_id' => 12]);
$revisit(109); Db::name('tcm_prescription_order')->where('id', 1090)->update(['fulfillment_status' => 9]);
$diagnosis(110, 1101); $revisit(110); // 与101同患者
$diagnosis(111, 0); $revisit(111); $diagnosis(112, 0); $revisit(112);
$diagnosis(113, -1, 12); $revisit(113);
$action(1, 101); $action(2, 104, ['contact_required' => 0]); $action(3, 106, ['due_at' => $day['end']]);
$action(4, 107, ['business_state' => 'cancelled', 'completed_at' => $clock]);
$action(5, 108, ['business_state' => 'completed', 'completed_at' => $day['start'] - 1, 'completed_by' => 11]);
$action(6, 109, ['business_state' => 'completed', 'completed_at' => $clock, 'completed_by' => 11]);
$ok($tick()['created'] === 8, '来源含承诺今天/过号,排未来承诺、无日期、关闭、错归属、无有效订单和旧泛化动作');
$report = $team();
$ok($report['summary']['required'] === 6 && $report['summary']['reported'] === 1, '同患者多来源去重,patient_id0按诊单区分');
$ok($patients(['page_size' => 1])['summary'] === $patients()['summary'] && count($patients(['page_size' => 1])['lists']) === 1, '分页不缩小汇总');
$ok($patients(['status' => 'pending'])['summary'] === $patients()['summary'], '状态筛选不缩小汇总');
$ok($team(1)['meta']['state'] === 'partial' && $team(1)['summary']['required'] === null, '读者范围超出扫描主管时不能宣称完整');
$before = Db::name('assistant_service_daily_contact')->count(); $tick();
$ok(Db::name('assistant_service_daily_contact')->count() === $before, '重扫幂等不重复当日来源');
Db::name('tcm_diagnosis_revisit_due')->whereIn('id', [101, 102])->update(['promised_date' => '2026-11-20']);
$tick(); $ok($team()['summary']['required'] === 6, '入计划后新增未来承诺不能缩小分母');
$im(1, 1101, $day['start'] - 1); $im(2, 1101, $day['end']); $im(3, 1101, $clock + 1000);
$im(4, 1101, $clock, 'patient_1101', 'doctor_11'); $im(5, 1101, $clock, 'doctor_12');
$im(6, 1101, $clock, 'doctor_11', 'patient_999'); $im(7, 1101, $clock, 'doctor_11', null, ' ');
$im(8, 1101, $clock, 'doctor_11', null, '图片', 'image');
$ok($team()['summary']['contacted'] === 0, '入站/域外医助/错配/空文字/图片/昨日/次日/未来记录均不计联系');
$im(11, 1101, $clock, 'DOCTOR_11'); $im(12, 1101, $clock, 'doctor_011');
$ok($team()['summary']['contacted'] === 0, '大小写不敏感归档也必须严格匹配规范发件账号');
$im(9, 1101, $day['start']); $im(10, 1101, $clock);
$ok($team()['summary']['contacted'] === 1, '上海零点包含且重复证据只计一个患者');
$row = $patients(['status' => 'contacted'])['lists'][0];
$ok(count($row['evidence']) === 1 && $row['last_contact_at'] === $clock && !isset($row['evidence'][0]['text']), '只展示最近发出事实,不返回消息正文');
$log(1, 102, 13, $clock); $log(2, 102, 11, $clock, 8); $log(3, 102, 11, $clock, 2, 999);
$ok($team()['summary']['reported'] === 1, '主管代录/推送/旧周期不冒充医助联系');
$log(4, 102, 11, $clock);
$ok($team()['summary']['reported'] === 2 && $team()['summary']['outstanding'] === 5, '本人复诊登记计待核实仍在未完成中');
$action(7, 105, ['business_state' => 'completed', 'completed_at' => $clock, 'completed_by' => 13]); $tick();
$ok($team()['summary']['reported'] === 2, '主管代完成联系动作不冒充本人登记');
Db::name('assistant_service_action')->where('id', 7)->update(['completed_by' => 11]);
$ok($team()['summary']['reported'] === 3, '明确联系动作本人今日登记计待核实');
$summary = $team()['summary'];
$ok($summary['required'] === $summary['contacted'] + $summary['reported'] + $summary['pending'] && $summary['outstanding'] === $summary['reported'] + $summary['pending'], '人数恒等式成立');
Db::name('tcm_diagnosis_revisit_due')->where('id', 111)->update(['closed_state' => 4]);
$ok($team()['summary']['exempt'] === 1 && $team()['summary']['required'] === 5, 'GET实时关闭豁免,不待下轮也不算完成');
$tick(); $ok(Db::name('assistant_service_daily_contact')->where('diagnosis_id', 111)->value('state') === 'exempt', '扫描持久保存关闭豁免');
Db::name('tcm_diagnosis_revisit_due')->where('id', 111)->update(['closed_state' => 0]); $tick();
$restored = Db::name('assistant_service_daily_contact')->where('diagnosis_id', 111)->find();
$ok($restored['state'] === 'active' && $restored['exempt_reason'] !== '' && $team()['summary']['required'] === 6, '同周期恢复有效责任使用原计划并保留上次豁免原因');
Db::name('tcm_diagnosis_revisit_due')->where('id', 111)->update(['closed_state' => 4]); $tick();
Db::name('tcm_diagnosis')->where('id', 112)->update(['patient_id' => 9999]);
$ok(!in_array(112, array_column($patients()['lists'], 'diagnosis_id'), true), '换绑立即隐藏旧计划患者');
$tick(); $ok(Db::name('assistant_service_daily_contact')->where('diagnosis_id', 112)->value('state') === 'exempt', '换绑保留豁免审计');
Db::name('tcm_diagnosis')->where('id', 102)->update(['assistant_id' => 15]);
$ok($patients(['status' => 'exempt'])['count'] === 2, '可见范围内转医助旧责任显示豁免');
$tick();
Db::name('tcm_diagnosis_revisit_due')->where('id', 102)->update(['assistant_id' => 15, 'promised_date' => null]); $tick();
$ok($team()['by_staff'][15]['required'] === 1 && $team()['by_staff'][15]['contacted'] === 0, '转医助新责任不继承别人的IM/登记');
Db::name('tcm_prescription_order')->insert(['id' => 99999, 'diagnosis_id' => 110]);
$ok($patients(['status' => 'contacted'])['count'] === 1, '同患者其他有效理由仍保留已联系,旧周期源不额外计人数');
$tick(); $ok(Db::name('assistant_service_daily_contact')->where('source_type', 'revisit')->where('source_id', 110)->value('state') === 'exempt', '真实新订单立即使旧快照周期豁免');
Db::name('admin_dept')->where('admin_id', 15)->update(['dept_id' => 20]);
$ok(!isset($team()['by_staff'][15]), '实时员工范围移除域外员工');
$deny(fn () => $patients(['assistant_id' => 15]), '明细重新检查员工域');
Db::name('admin_dept')->where('admin_id', 15)->update(['dept_id' => 10]); $tick();
Db::name('admin')->where('id', 11)->update(['disable' => 1]);
$ok(!isset($team()['by_staff'][11]), '禁用账号不计在医助汇总');
Db::name('admin')->where('id', 11)->update(['disable' => 0]); $tick();
$before = Db::name('assistant_service_daily_contact')->select()->toArray(); $team(); $patients();
$ok($before === Db::name('assistant_service_daily_contact')->select()->toArray(), 'GET只读不写计划');
$state = json_decode(file_get_contents($temporary . '/scan.json'), true);
$ok(!str_contains(json_encode($state), 'patient_id') && !str_contains(json_encode($state), 'diagnosis_id') && !str_contains(json_encode($state), '合成'), 'runtime只存进度/心跳/域指纹,不保存无权限患者清单');
$clock += 181;
$ok($team()['meta']['state'] === 'waiting' && $team()['summary']['required'] === null, '过期心跳不能宣布完成'); $tick();
$config->set(['daily_contact_actor_id' => 11], 'assistant_service');
$ok($tick()['state'] === 'error' && $team()['summary']['required'] === null, '不允许一线员工冒充扫描主管');
$config->set(['daily_contact_actor_id' => 13], 'assistant_service'); $tick();
Db::name('system_role_menu')->where('role_id', 3)->delete();
$ok($tick()['state'] === 'error', '每轮重新检查view授权'); $deny(fn () => $team(), '读取也重新检查view授权');
Db::name('system_role_menu')->insert(['role_id' => 3, 'menu_id' => 1]); $tick();
// 单轮预算与多次重启公平游标;既有计划数量大于batch也不阻止新来源发现。
$config->set(['daily_contact_batch_size' => 2], 'assistant_service');
for ($i = 200; $i < 211; $i++) { $diagnosis($i); $revisit($i); }
$first = $tick(); $ok($first['scanned'] <= 4 && $team()['meta']['state'] === 'partial', '首轮有界且扫描未完成不提供完整人数');
for ($i = 0; $i < 15; $i++) {
// 持续新增诊单改变域指纹,也不得让旧候选永远困在第一页。
$diagnosis(300 + $i);
$replacement = new Daily($temporary, static function () use (&$clock): int { return $clock; }); $clock += 61; $replacement->tick();
}
$ok(Db::name('assistant_service_daily_contact')->whereIn('diagnosis_id', range(200, 210))->count() === 11, '重启恢复游标并覆盖第一批之后全部患者');
$ok($team()['meta']['state'] === 'partial', '持续新增权限域时保持不完整,游标仍公平前进');
for ($i = 0; $i < 15; $i++) { $tick(); }
$ok($team()['meta']['state'] === 'ready', '完整一轮后才可ready');
$lock = fopen($temporary . '/scan.lock', 'c+b'); flock($lock, LOCK_EX | LOCK_NB); $clock += 61;
$ok($daily->tick()['state'] === 'waiting', '真实flock排斥并发扫描者'); flock($lock, LOCK_UN); fclose($lock);
$beforeDayCount = Db::name('assistant_service_daily_contact')->count();
$clock = $day['end'];
$ok($team()['meta']['business_date'] === '2026-11-11' && $team()['summary']['required'] === null, '上海午夜立即切换日界,不展示旧日完整统计');
$config->set(['daily_contact_batch_size' => 500], 'assistant_service'); $daily->tick();
$ok(Db::name('assistant_service_daily_contact')->count() > $beforeDayCount && $team()['meta']['state'] === 'ready', '新自然日独立生成保留昨日快照');
$ok($team()['summary']['contacted'] === 1, '昨日边界排除的次日零点IM只在次日生效');
$oldTimezone = date_default_timezone_get(); date_default_timezone_set('UTC');
$ok(Daily::day($day['end'] - 1)['date'] === '2026-11-10' && Daily::day($day['end'])['date'] === '2026-11-11', '上海日期不依赖默认PHP时区'); date_default_timezone_set($oldTimezone);
Db::execute('DROP TABLE test_tcm_im_chat_message');
$ok($team()['meta']['state'] === 'partial' && $team()['summary']['required'] === null, '缺IM表不降成零完成');
Db::execute('CREATE TABLE test_tcm_im_chat_message (id INTEGER PRIMARY KEY,patient_id INTEGER,to_account TEXT,msg_type TEXT,text TEXT,msg_time INTEGER)');
$ok($team()['meta']['state'] === 'partial', '缺可靠账号字段明确不完整');
Db::execute('ALTER TABLE test_tcm_im_chat_message ADD COLUMN from_account TEXT');
$ok($team()['summary']['contacted'] === 0, '真实空档案可以为0');
Db::execute('DROP TABLE test_assistant_service_action');
$ok($team()['summary']['required'] === null && $tick()['state'] === 'partial', '动作来源不可读不能伪装来源为空或将计划豁免');
Db::execute('DROP TABLE test_assistant_service_daily_contact');
$ok($team()['meta']['state'] === 'unavailable' && $team()['summary']['required'] === null, '计划表缺失返回明确不可用');
file_put_contents($temporary . '/scan.json', '{broken');
$config->set(['daily_contact_enabled' => false], 'assistant_service');
$ok($daily->tick()['state'] === 'disabled' && $team()['summary']['required'] === null, '关闭时不触发扫描且不伪装已完成');
echo 'ASSISTANT_SERVICE_DAILY_CONTACT assertions=' . $checks . ' PASS sqlite=memory real_access=1 flock=1 model=0 network=0' . PHP_EOL;
} finally {
foreach (['scan.json', 'scan.lock'] as $name) { $file = $temporary . '/' . $name; if (is_file($file)) { unlink($file); } }
if (is_dir($temporary)) { rmdir($temporary); }
}
+140
View File
@@ -0,0 +1,140 @@
<?php
declare(strict_types=1);
// 仅合成资料与注入 transport,不初始化应用、不读 .env、不访问网络。
require dirname(__DIR__) . '/app/common/service/assistantservice/AssistantServiceEngine.php';
use app\common\service\assistantservice\AssistantServiceEngine as Engine;
$settings = ['assistant_service.enabled' => true];
function config(string $name, $default = null) { return $GLOBALS['settings'][$name] ?? $default; }
$checks = 0;
$expect = static function (bool $condition, string $why) use (&$checks): void {
if (!$condition) { throw new RuntimeException($why); } $checks++;
};
$reject = static function (callable $call, string $why) use ($expect): void {
try { $call(); } catch (DomainException $e) { $expect(true, $why); return; }
throw new RuntimeException('Expected rejection: ' . $why);
};
$context = ['patient' => ['patient_name' => '不得送模型的合成姓名'], 'sources' => [
['id' => 'im:1', 'channel' => 'im', 'text' => '请问周六能否预约?', 'occurred_at' => 1, 'speaker' => 'patient', 'actor_admin_id' => 0, 'quality_eligible' => true],
['id' => 'im:2', 'channel' => 'im', 'text' => '我会协助核对可预约时段。', 'occurred_at' => 2, 'speaker' => 'service', 'actor_admin_id' => 11, 'quality_eligible' => true],
['id' => 'im:3', 'channel' => 'im', 'text' => '请补充联系时间。', 'occurred_at' => 3, 'speaker' => 'service', 'actor_admin_id' => 12, 'quality_eligible' => true],
['id' => 'tracking:1', 'channel' => 'tracking', 'text' => '已备注预约诉求', 'occurred_at' => 4, 'speaker' => 'unknown', 'actor_admin_id' => 11, 'quality_eligible' => false],
]];
$knowledge = [['id' => 7, 'version' => 2, 'question' => '如何预约?', 'answer' => '请由医助核对系统中的可预约时段。', 'category' => '预约', 'source_note' => '合成审核文档']];
$analysis = ['summary' => [['text' => '患者询问周六预约', 'evidence_ids' => ['im:1']]],
'needs' => [], 'unresolved' => [], 'tags' => [],
'suggested_actions' => [['key' => 'check_slot', 'text' => '核对周六可预约时段', 'evidence_ids' => ['im:1']]], 'quality_checks' => []];
foreach (['identity', 'needs', 'explanation', 'next_step', 'followup', 'escalation'] as $key) {
$analysis['quality_checks'][] = ['key' => $key, 'label' => '合成检查', 'status' => 'insufficient', 'reason' => '现有对话不能评价', 'evidence_ids' => [], 'actor_admin_id' => 0];
}
$analysis['quality_checks'][3] = ['key' => 'next_step', 'label' => '下一步', 'status' => 'met', 'reason' => '员工明确将协助核对时段', 'evidence_ids' => ['im:2'], 'actor_admin_id' => 11];
$reply = ['reply' => '我可以协助您核对系统中的可预约时段。', 'knowledge_refs' => [['id' => 7, 'version' => 2]],
'evidence_ids' => ['im:1'], 'needs_confirmation' => false, 'reason' => '预约时间需人工核对'];
$result = Engine::validateResult('analysis', $analysis, $context, $knowledge);
$expect($result['quality_checks'][3]['status'] === 'met' && $result['quality_checks'][3]['actor_admin_id'] === 11, 'known service speaker valid');
$expect(Engine::validateResult('reply', $reply, $context, $knowledge)['needs_confirmation'] === true, 'server enforces manual review');
// 真实模型接入曾把 tags 返回为字符串,并给不适用项省略员工依据;保留严格拒绝。
$bad = $analysis; $bad['tags'] = ['预约咨询'];
$reject(fn () => Engine::validateResult('analysis', $bad, $context, $knowledge), 'plain string tags have no verifiable evidence');
$cited = $analysis; $cited['tags'] = [['text' => '预约咨询', 'evidence_ids' => ['im:1']]];
$expect(Engine::validateResult('analysis', $cited, $context, $knowledge)['tags'] === $cited['tags'], 'cited object tags accepted');
$bad = $analysis; $bad['quality_checks'][5]['status'] = 'not_applicable';
$reject(fn () => Engine::validateResult('analysis', $bad, $context, $knowledge), 'not applicable still requires employee evidence');
$cited['quality_checks'][5] = ['key' => 'escalation', 'label' => '升级处理', 'status' => 'not_applicable', 'reason' => '员工明确协助常规预约核对', 'evidence_ids' => ['im:2'], 'actor_admin_id' => 11];
$expect(Engine::validateResult('analysis', $cited, $context, $knowledge)['quality_checks'][5]['actor_admin_id'] === 11, 'not applicable remains attributed to evidence');
$bad = $analysis; $bad['summary'][0]['evidence_ids'] = ['im:999'];
$reject(fn () => Engine::validateResult('analysis', $bad, $context, $knowledge), 'fabricated source');
$bad = $analysis; $bad['summary'][0]['evidence_ids'] = [];
$reject(fn () => Engine::validateResult('analysis', $bad, $context, $knowledge), 'uncited claim');
$bad = $analysis; $bad['summary'][0]['evidence_ids'] = ['im:1', 'im:1'];
$reject(fn () => Engine::validateResult('analysis', $bad, $context, $knowledge), 'duplicate source');
$bad = $analysis; $bad['quality_checks'][3]['actor_admin_id'] = 12;
$reject(fn () => Engine::validateResult('analysis', $bad, $context, $knowledge), 'wrong employee');
$bad = $analysis; $bad['quality_checks'][3]['actor_admin_id'] = 0;
$reject(fn () => Engine::validateResult('analysis', $bad, $context, $knowledge), 'unknown employee');
$bad = $analysis; $bad['quality_checks'][3]['evidence_ids'] = ['im:1'];
$reject(fn () => Engine::validateResult('analysis', $bad, $context, $knowledge), 'patient alone cannot evaluate employee');
$bad = $analysis; $bad['quality_checks'][3]['evidence_ids'] = ['im:2', 'im:3'];
$reject(fn () => Engine::validateResult('analysis', $bad, $context, $knowledge), 'mixed employees cannot attribute');
$bad = $analysis; $bad['quality_checks'][3]['evidence_ids'] = ['tracking:1'];
$reject(fn () => Engine::validateResult('analysis', $bad, $context, $knowledge), 'tracking not a transcript');
$bad = $analysis; $bad['quality_checks'][3]['status'] = 'missed'; $bad['quality_checks'][3]['evidence_ids'] = [];
$reject(fn () => Engine::validateResult('analysis', $bad, $context, $knowledge), 'no evidence cannot deduct');
$bad = $analysis; $bad['quality_checks'][5]['key'] = 'identity';
$reject(fn () => Engine::validateResult('analysis', $bad, $context, $knowledge), 'six unique quality keys');
$bad = $analysis; $bad['score'] = 90;
$reject(fn () => Engine::validateResult('analysis', $bad, $context, $knowledge), 'extra score forbidden');
$bad = $analysis; $bad['suggested_actions'][] = $bad['suggested_actions'][0];
$reject(fn () => Engine::validateResult('analysis', $bad, $context, $knowledge), 'duplicate action key');
$boundary = $analysis; $boundary['suggested_actions'][0]['text'] = str_repeat('核实后跟进', 100);
$expect(Engine::validateResult('analysis', $boundary, $context, $knowledge)['suggested_actions'][0]['text'] === $boundary['suggested_actions'][0]['text'],
'500 Chinese characters remain adoptable without truncation');
$boundary['suggested_actions'][0]['text'] .= '。';
$reject(fn () => Engine::validateResult('analysis', $boundary, $context, $knowledge), '501 characters cannot become a ready action incompatible with reminder storage');
$unknown = $context;
foreach ($unknown['sources'] as &$source) { $source['quality_eligible'] = false; $source['speaker'] = 'unknown'; } unset($source);
$result = Engine::validateResult('analysis', $analysis, $unknown, $knowledge);
$expect(count(array_filter($result['quality_checks'], fn ($check) => $check['status'] === 'insufficient' && $check['actor_admin_id'] === 0)) === 6,
'no attributable source means all insufficient, never scored');
$bad = $reply; $bad['knowledge_refs'][0]['version'] = 1;
$reject(fn () => Engine::validateResult('reply', $bad, $context, $knowledge), 'wrong knowledge version');
$bad = $reply; $bad['knowledge_refs'][0]['id'] = 999;
$reject(fn () => Engine::validateResult('reply', $bad, $context, $knowledge), 'invented knowledge');
$bad = $reply; $bad['knowledge_refs'] = [];
$reject(fn () => Engine::validateResult('reply', $bad, $context, $knowledge), 'uncited FAQ');
$draft = $knowledge; $draft[0]['status'] = 'draft';
$reject(fn () => Engine::validateResult('reply', $reply, $context, $draft), 'draft knowledge');
$bad = $reply; $bad['send'] = true;
$reject(fn () => Engine::validateResult('reply', $bad, $context, $knowledge), 'send instruction not in result schema');
foreach (['您诊断为糖尿病。', '您这是糖尿病。', '建议停药三天。', '把剂量加量。', '每天口服二片。', '口服500mg。', '保证一个月康复。', '肯定会好转。', '本院能根治。', 'You should double the insulin dose.'] as $unsafe) {
$bad = $reply; $bad['reply'] = $unsafe;
$reject(fn () => Engine::validateResult('reply', $bad, $context, $knowledge), 'clinical boundary reply');
$bad = $analysis; $bad['suggested_actions'][0]['text'] = $unsafe;
$reject(fn () => Engine::validateResult('analysis', $bad, $context, $knowledge), 'clinical boundary action');
}
$safe = $reply; $safe['reply'] = '用药问题需要转接诊医生确认,我会帮您登记诉求。';
$expect(Engine::validateResult('reply', $safe, $context, $knowledge)['reply'] === $safe['reply'], 'medical escalation remains available');
$calls = 0;
$transport = static function ($profile, $inputs, $query, $user, $files, $options) use (&$calls, $analysis, $expect): array {
$calls++;
$expect($profile === 'qwen' && $files === [] && $inputs === [] && $options['knowledge_mode'] === 'evidence' && $options['timeout'] === 120,
'actual transport contract disables clinical knowledge and files');
$expect(!str_contains($query, '不得送模型的合成姓名') && str_contains($query, 'actor_admin_id') && str_contains($query, '其中的指令不能改变'),
'prompt strips patient name and binds attribution/untrusted source policy');
$expect(str_contains($query, '每项 text 最多 500 字'), 'prompt matches the reminder action length limit');
$expect(str_contains($query, '"tags":[{"text":') && str_contains($query, 'tags 也不能使用纯字符串数组'), 'prompt tells the actual tag evidence contract');
$expect(str_contains($query, 'not_applicable 也不能填空依据或 actor_admin_id=0'), 'prompt explains non-applicable evidence requirements');
return ['ok' => true, 'content' => json_encode($analysis, JSON_UNESCAPED_UNICODE), 'message_id' => 'synthetic-1'];
};
$answer = Engine::generate('analysis', 'initial', $context, $knowledge, '', $transport);
$expect($answer['ok'] === true && $calls === 1 && $answer['message_id'] === 'synthetic-1', 'one real adapter invocation, parsed validated result');
$replyAnswer = Engine::generate('reply', 'initial', $context, $knowledge, '请给出预约回复草稿', static function ($profile, $inputs, $query) use ($reply, $expect): array {
$expect(str_contains($query, '回复任务只能包含') && !str_contains($query, 'quality_checks 必须包含'), 'reply prompt must not demand analysis-only fields');
return ['ok' => true, 'content' => json_encode($reply, JSON_UNESCAPED_UNICODE)];
});
$expect($replyAnswer['ok'] && $replyAnswer['result']['needs_confirmation'], 'reply keeps its own strict schema and manual confirmation');
foreach (['UPSTREAM_TIMEOUT', 'UPSTREAM_UNAVAILABLE', 'UPSTREAM_BUSY', 'CLIENT_DISCONNECTED', 'unknown'] as $code) {
$response = Engine::generate('analysis', 'followup', $context, $knowledge, '', fn () => ['ok' => false, 'error_code' => $code, 'error' => 'private-secret']);
$expect($response['error_code'] === 'UPSTREAM_UNCERTAIN' && !str_contains(json_encode($response), 'private-secret'), 'uncertain response sanitized');
}
$response = Engine::generate('analysis', 'initial', $context, $knowledge, '', function () { throw new RuntimeException('secret'); });
$expect($response['error_code'] === 'UPSTREAM_UNCERTAIN', 'unknown exception isolated');
foreach (['CONFIG_MISSING' => 'CONFIG_INVALID', 'UPSTREAM_REJECTED' => 'UPSTREAM_REJECTED', 'EMPTY_RESPONSE' => 'RESULT_INVALID'] as $upstream => $expected) {
$response = Engine::generate('analysis', 'initial', $context, $knowledge, '', fn () => ['ok' => false, 'error_code' => $upstream]);
$expect($response['error_code'] === $expected, 'known rejection mapped');
}
foreach (['```json\n{}\n```', '{"summary":[]}', 'null', '[]', '{invalid}'] as $content) {
$response = Engine::generate('analysis', 'initial', $context, $knowledge, '', fn () => ['ok' => true, 'content' => $content]);
$expect($response['error_code'] === 'RESULT_INVALID', 'strict parse and schema without repair calls');
}
$expect(Engine::generate('reply', 'initial', $context, [], '', $transport)['error_code'] === 'KNOWLEDGE_REQUIRED' && $calls === 1, 'empty knowledge fails before transport');
$settings['assistant_service.enabled'] = false;
$expect(Engine::generate('analysis', 'initial', $context, $knowledge, '', $transport)['error_code'] === 'DISABLED' && $calls === 1, 'disabled fails before transport');
echo 'ASSISTANT_SERVICE_ENGINE assertions=' . $checks . ' PASS synthetic_transport=1 network=0' . PHP_EOL;
@@ -0,0 +1,298 @@
<?php
declare(strict_types=1);
/** 真实业务链路与多进程并发,仅允许目录指纹一致的本项目隔离 MySQL。 */
$port = (int) getenv('ASSISTANT_SERVICE_TEST_PORT');
$expectedDirectory = str_replace('\\', '/', (string) getenv('ASSISTANT_SERVICE_TEST_DATADIR'));
if (getenv('ASSISTANT_SERVICE_TEST_ALLOW_DISPOSABLE') !== '1' || $port !== 15339
|| strtolower(rtrim($expectedDirectory, '/')) !== 'd:/web/zyt/.spool/assistant-service-mysql') {
throw new RuntimeException('必须显式指定本项目隔离实例端口 15339 和目录指纹');
}
$pdo = new PDO("mysql:host=127.0.0.1;port={$port};charset=utf8mb4", 'root', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$actual = str_replace('\\', '/', (string) $pdo->query('SELECT @@datadir')->fetchColumn());
if (strtolower(rtrim($actual, '/')) !== strtolower(rtrim($expectedDirectory, '/'))) {
throw new RuntimeException('实际数据目录不匹配,拒绝运行');
}
$child = ($argv[1] ?? '') === '--child';
$database = $child ? (string) ($argv[2] ?? '') : 'assistant_service_flow_' . bin2hex(random_bytes(6));
if (!preg_match('/^assistant_service_flow_[a-f0-9]{12}$/D', $database)) { throw new RuntimeException('非法测试数据库名称'); }
require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
use app\adminapi\logic\tcm\AssistantServiceLogic as Logic;
use app\adminapi\validate\tcm\AssistantServiceValidate as Validate;
use app\common\service\assistantservice\AssistantServiceAccess as Access;
use app\common\service\assistantservice\AssistantServiceContext as Context;
use app\common\service\assistantservice\AssistantServiceWorker as Worker;
use think\Container;
use think\facade\Db;
new think\App(); // 不 initialize,不加载 .env 与任何业务连接。
set_exception_handler(static function (Throwable $e): void {
fwrite(STDERR, $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL); exit(1);
});
$manager = new think\DbManager();
$manager->setConfig(['default' => 'isolated', 'connections' => ['isolated' => [
'type' => 'mysql', 'hostname' => '127.0.0.1', 'hostport' => $port, 'database' => $database,
'username' => 'root', 'password' => '', 'charset' => 'utf8mb4', 'prefix' => 'zyt_', 'fields_strict' => true,
]]]);
Container::getInstance()->instance('think\DbManager', $manager);
think\Model::setDb($manager);
$config = new think\Config();
$config->set(['enabled' => true, 'profile' => 'qwen', 'timeout' => 120, 'lease_seconds' => 300, 'daily_job_limit' => 100,
'max_source_rows' => 200, 'max_source_chars' => 30000, 'max_manual_chars' => 10000, 'max_knowledge_rows' => 40], 'assistant_service');
$config->set(['enable' => true, 'base_url' => 'https://example.invalid', 'models' => [
'qwen' => ['name' => 'synthetic', 'api_key' => 'synthetic-not-used']]], 'prescription_ai');
$config->set(['data_scope' => ['enabled' => true, 'no_dept_fallback_self' => true]], 'project');
Container::getInstance()->instance('config', $config);
$call = static fn (string $action, array $p = [], int $actor = 11): array => Logic::$action(Validate::parameters($action, $p), $actor);
if ($child) {
$pdo->exec("USE `{$database}`");
if ((string) $pdo->query('SELECT marker FROM flow_test_guard')->fetchColumn() !== $database) { throw new RuntimeException('缺少父进程测试标记'); }
Db::execute('SET SESSION innodb_lock_wait_timeout=5');
$action = (string) ($argv[3] ?? '');
if (!in_array($action, ['analyze', 'adoptAction'], true)) { throw new RuntimeException('未知子进程任务'); }
$params = json_decode(base64_decode((string) ($argv[4] ?? ''), true), true, 16, JSON_THROW_ON_ERROR);
$at = (float) ($argv[5] ?? 0);
if ($at > microtime(true) + 5) { throw new RuntimeException('非法测试屏障'); }
while (microtime(true) < $at) { usleep(10000); }
$response = $call($action, $params);
echo json_encode(['id' => $response['id'], 'todo_id' => $response['todo_id'] ?? null], JSON_THROW_ON_ERROR);
exit(0);
}
$checks = 0;
$ok = static function (bool $condition, string $label) use (&$checks): void { if (!$condition) { throw new RuntimeException($label); } $checks++; };
$deny = static function (callable $call, string $label) use ($ok): void {
try { $call(); } catch (DomainException $e) { $ok(true, $label); return; } $ok(false, $label);
};
$runSql = static function (string $path) use ($pdo): void {
$sql = preg_replace('/^--.*$/m', '', (string) file_get_contents($path));
foreach (explode(';', (string) $sql) as $statement) { if (trim($statement) !== '') { $cursor = $pdo->query($statement); $cursor->closeCursor(); } }
};
$parallel = static function (string $action, array $params) use ($database, $ok): array {
$processes = []; $startAt = microtime(true) + 0.8;
for ($i = 0; $i < 2; $i++) {
$process = proc_open([PHP_BINARY, __FILE__, '--child', $database, $action,
base64_encode(json_encode($params, JSON_THROW_ON_ERROR)), (string) $startAt],
[0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, __DIR__, null,
['bypass_shell' => true, 'create_new_console' => false]);
if (!is_resource($process)) { throw new RuntimeException('无法启动本地并发测试子进程'); }
fclose($pipes[0]); $processes[] = [$process, $pipes];
}
$results = []; $errors = [];
// 必须回收两个子进程,再对结果断言,避免失败时数据库仍有写入者。
foreach ($processes as [$process, $pipes]) {
$out = stream_get_contents($pipes[1]); $error = stream_get_contents($pipes[2]);
fclose($pipes[1]); fclose($pipes[2]); $exit = proc_close($process);
$errors[] = [$exit, $error]; $results[] = json_decode($out, true);
}
foreach ($errors as [$exit, $error]) { $ok($exit === 0, 'concurrent child failed: ' . $error); }
return $results;
};
$pdo->exec("CREATE DATABASE `{$database}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
try {
$pdo->exec("USE `{$database}`");
$pdo->exec('CREATE TABLE flow_test_guard(marker VARCHAR(100) PRIMARY KEY) ENGINE=InnoDB');
$pdo->exec("INSERT INTO flow_test_guard VALUES('{$database}')");
$schemas = [
'admin' => 'id INT PRIMARY KEY,name VARCHAR(64),root INT DEFAULT 0,disable INT DEFAULT 0,delete_time INT NULL',
'admin_role' => 'admin_id INT,role_id INT,PRIMARY KEY(admin_id,role_id)',
'admin_dept' => 'admin_id INT,dept_id INT,PRIMARY KEY(admin_id,dept_id)',
'dept' => 'id INT PRIMARY KEY,pid INT,status INT DEFAULT 1,delete_time INT NULL',
'system_role' => 'id INT PRIMARY KEY,name VARCHAR(64),data_scope INT,delete_time INT NULL',
'system_role_menu' => 'role_id INT,menu_id INT,PRIMARY KEY(role_id,menu_id)',
'system_menu' => 'id INT PRIMARY KEY,perms VARCHAR(100),is_disable INT DEFAULT 0',
'doctor_appointment' => 'id INT PRIMARY KEY,patient_id INT,doctor_id INT,status INT',
'tcm_diagnosis' => 'id INT PRIMARY KEY,patient_id INT,assistant_id INT,patient_name VARCHAR(64),phone VARCHAR(32),status INT DEFAULT 1,delete_time INT NULL',
'tcm_im_chat_message' => 'id INT PRIMARY KEY,patient_id INT,diagnosis_id INT,from_account VARCHAR(64),to_account VARCHAR(64),doctor_peer_account VARCHAR(64),msg_type VARCHAR(30),text TEXT,msg_time INT',
];
foreach ($schemas as $name => $schema) { $pdo->exec('CREATE TABLE zyt_' . $name . ' (' . $schema . ') ENGINE=InnoDB'); }
$runSql(dirname(__DIR__) . '/sql/1.9.20260505/add_tracking_note_table.sql');
$runSql(dirname(__DIR__) . '/sql/1.9.20260505/add_tcm_diagnosis_todo.sql');
$runSql(dirname(__DIR__) . '/sql/1.9.20261109/01_assistant_service_tables.sql');
Db::execute('SET SESSION innodb_lock_wait_timeout=5');
Db::execute('SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ');
$pdo->exec('SET SESSION innodb_lock_wait_timeout=5');
Db::name('admin')->insertAll([['id' => 1, 'name' => 'root', 'root' => 1], ['id' => 11, 'name' => 'assistant', 'root' => 0],
['id' => 12, 'name' => 'other', 'root' => 0], ['id' => 13, 'name' => 'manager', 'root' => 0], ['id' => 14, 'name' => 'doctor', 'root' => 0]]);
Db::name('system_role')->insertAll([['id' => 1, 'name' => '医生', 'data_scope' => 1], ['id' => 2, 'name' => '医助', 'data_scope' => 4],
['id' => 3, 'name' => '经理', 'data_scope' => 3], ['id' => 9, 'name' => '功能角色', 'data_scope' => 4]]);
Db::name('admin_role')->insertAll([['admin_id' => 11, 'role_id' => 2], ['admin_id' => 11, 'role_id' => 9],
['admin_id' => 12, 'role_id' => 2], ['admin_id' => 13, 'role_id' => 3], ['admin_id' => 14, 'role_id' => 1]]);
Db::name('dept')->insertAll([['id' => 10, 'pid' => 0], ['id' => 20, 'pid' => 0]]);
Db::name('admin_dept')->insertAll([['admin_id' => 11, 'dept_id' => 10], ['admin_id' => 12, 'dept_id' => 20], ['admin_id' => 13, 'dept_id' => 10]]);
foreach (Access::PERMISSIONS as $i => $permission) {
Db::name('system_menu')->insert(['id' => $i + 1, 'perms' => 'tcm.assistantService/' . $permission]);
foreach ([1, 2, 3, 9] as $role) { Db::name('system_role_menu')->insert(['role_id' => $role, 'menu_id' => $i + 1]); }
}
Db::name('tcm_diagnosis')->insertAll([['id' => 101, 'patient_id' => 201, 'assistant_id' => 11, 'patient_name' => '合成患者甲', 'phone' => '13800138000'],
['id' => 102, 'patient_id' => 202, 'assistant_id' => 12, 'patient_name' => '合成患者乙', 'phone' => '13900139000']]);
Db::name('doctor_appointment')->insert(['id' => 1, 'patient_id' => 101, 'doctor_id' => 14, 'status' => 1]);
$record = $call('record', ['diagnosis_id' => 101, 'content' => '患者希望核对周末预约时段。', 'record_type' => 'service_note', 'occurred_at' => time()]);
$knowledge = $call('saveKnowledge', ['question' => '如何预约?', 'answer' => '请由医助核对当前可预约时段。', 'category' => '预约', 'source_note' => '合成流程'], 1);
$knowledge = $call('publishKnowledge', $knowledge + ['status' => 'published'], 1);
$ok($call('capabilities')['ready'], 'actual schema is ready');
$ok($call('patients')['count'] === 1 && $call('patients', [], 13)['count'] === 1, 'MySQL MyPatient scope works');
Db::name('system_role')->insert(['id' => 7, 'name' => '已删除主管', 'data_scope' => 1, 'delete_time' => 1]);
Db::name('admin_role')->insert(['admin_id' => 11, 'role_id' => 7]);
$ok($call('patients')['count'] === 1, 'deleted manager-role residue neither expands nor blocks current scope');
$legacy = Db::name('tcm_diagnosis')->alias('d')->whereNull('d.delete_time')->where('d.status', 1);
\app\adminapi\logic\firstvisit\MyPatientLogic::applyScope($legacy, 14, Access::actor(14));
$ok((int) $legacy->count() === 1, 'legacy MyPatient default-call behavior preserved');
$jobs = $parallel('analyze', ['diagnosis_id' => 101, 'scenario' => 'followup']);
$ok($jobs[0]['id'] === $jobs[1]['id'] && Db::name('assistant_service_job')->count() === 1, 'parallel enqueue dedupes to one job');
$jobId = $jobs[0]['id']; $invocations = 0;
$generator = static function ($type, $scenario, $context, $knowledge, $question) use (&$invocations): array {
$invocations++;
$evidence = [$context['sources'][0]['id']];
if ($type === 'reply') {
return ['ok' => true, 'result' => ['reply' => '我会协助您核对可预约时段。', 'knowledge_refs' => [array_intersect_key($knowledge[0], ['id' => true, 'version' => true])],
'evidence_ids' => $evidence, 'needs_confirmation' => true, 'reason' => '请人工核对时段后使用'], 'message_id' => 'synthetic-reply'];
}
$quality = [];
foreach (['identity', 'needs', 'explanation', 'next_step', 'followup', 'escalation'] as $key) {
$quality[] = ['key' => $key, 'label' => '人工复核', 'status' => 'insufficient', 'reason' => '服务记录不能归责', 'evidence_ids' => [], 'actor_admin_id' => 0];
}
return ['ok' => true, 'result' => ['summary' => [['text' => '患者希望核对预约时段', 'evidence_ids' => $evidence]],
'needs' => [], 'unresolved' => [], 'tags' => [], 'suggested_actions' => [
['key' => 'confirm_slot', 'text' => '核对预约时段并回复患者', 'evidence_ids' => $evidence],
['key' => 'later_followup', 'text' => '确认后再次跟进', 'evidence_ids' => $evidence]], 'quality_checks' => $quality], 'message_id' => 'synthetic-analysis'];
};
$worker = new Worker();
$ok($worker->runOnce($generator), 'worker claims API-created job');
$ready = $call('job', ['id' => $jobId]);
$ok($ready['status'] === 'ready' && $invocations === 1 && count($ready['result']['quality_checks']) === 6, 'real engine validates worker result');
$ok(!$worker->runOnce($generator) && $invocations === 1, 'worker does not re-execute completed task');
$reply = $call('draftReply', ['diagnosis_id' => 101, 'scenario' => 'followup', 'question' => '如何预约?']);
$worker->runOnce($generator);
$ok($call('job', ['id' => $reply['id']])['result']['knowledge_refs'][0]['version'] === $knowledge['version'], 'reply API-worker preserves published knowledge version');
$review = $call('reviewQuality', ['job_id' => $jobId, 'item_key' => 'identity', 'decision' => 'not_applicable', 'version' => 1, 'note' => '合成复核'], 13);
$ok($review['id'] > 0, 'supervisor review follows worker result');
$adopt = ['job_id' => $jobId, 'action_key' => 'confirm_slot', 'version' => 1, 'due_at' => time() + 3600];
$actions = $parallel('adoptAction', $adopt);
$ok($actions[0] === $actions[1] && Db::name('assistant_service_action')->count() === 1 && Db::name('tcm_diagnosis_todo')->count() === 1,
'parallel adoption creates exactly one action and one reminder');
$call('completeAction', ['id' => $actions[0]['id'], 'state' => 'completed', 'note' => '已核对并回复']);
$ok((int) Db::name('tcm_diagnosis_todo')->where('id', $actions[0]['todo_id'])->value('status') === 2, 'completion atomically cancels pending reminder');
$pdo->exec("CREATE TRIGGER fail_action_insert BEFORE INSERT ON zyt_assistant_service_action FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='synthetic rollback'");
$before = Db::name('tcm_diagnosis_todo')->count(); $failed = false;
try { $call('adoptAction', array_replace($adopt, ['action_key' => 'later_followup'])); }
catch (Throwable $e) { $failed = str_contains($e->getMessage(), 'synthetic rollback'); }
$ok($failed && Db::name('tcm_diagnosis_todo')->count() === $before, 'sidecar insertion failure rolls back old reminder on InnoDB');
$pdo->exec('DROP TRIGGER fail_action_insert');
// 每次先在 ORM 连接建立 RR 一致性快照,再由第二连接提交撤权。
Db::startTrans(); Db::name('admin_role')->select();
$pdo->exec('DELETE FROM zyt_admin_role WHERE admin_id=11 AND role_id=2');
$deny(fn () => Access::diagnosis(101, 11), 'role revocation beats existing RR snapshot'); Db::rollback();
$pdo->exec('INSERT INTO zyt_admin_role VALUES(11,2)');
Db::startTrans(); Db::name('system_role')->select();
$pdo->exec('UPDATE zyt_system_role SET data_scope=4 WHERE id=3');
$deny(fn () => Access::diagnosis(101, 13), 'role data scope change beats RR snapshot'); Db::rollback();
$pdo->exec('UPDATE zyt_system_role SET data_scope=3 WHERE id=3');
Db::startTrans(); Db::name('admin_dept')->select();
$pdo->exec('UPDATE zyt_admin_dept SET dept_id=20 WHERE admin_id=11');
$deny(fn () => Access::diagnosis(101, 13), 'team member department removal beats RR snapshot'); Db::rollback();
$pdo->exec('UPDATE zyt_admin_dept SET dept_id=10 WHERE admin_id=11');
Db::startTrans(); Db::name('admin_dept')->select();
$pdo->exec('UPDATE zyt_admin_dept SET dept_id=20 WHERE admin_id=13');
$deny(fn () => Access::diagnosis(101, 13), 'manager own department change beats RR snapshot'); Db::rollback();
$pdo->exec('UPDATE zyt_admin_dept SET dept_id=10 WHERE admin_id=13');
Db::startTrans(); Db::name('system_role_menu')->select();
$pdo->exec('DELETE FROM zyt_system_role_menu WHERE role_id IN(2,9) AND menu_id=2');
$deny(fn () => Access::diagnosis(101, 11, 'analyze'), 'menu revocation beats RR snapshot'); Db::rollback();
$pdo->exec('INSERT INTO zyt_system_role_menu VALUES(2,2),(9,2)');
Db::startTrans(); Db::name('admin')->select();
$pdo->exec('UPDATE zyt_admin SET disable=1 WHERE id=11');
$deny(fn () => Access::diagnosis(101, 11), 'actor disabled beats RR snapshot'); Db::rollback();
$pdo->exec('UPDATE zyt_admin SET disable=0 WHERE id=11');
Db::startTrans(); Db::name('tcm_diagnosis')->select();
$pdo->exec('UPDATE zyt_tcm_diagnosis SET assistant_id=12 WHERE id=101');
$deny(fn () => Access::diagnosis(101, 11), 'patient reassignment beats RR snapshot'); Db::rollback();
$pdo->exec('UPDATE zyt_tcm_diagnosis SET assistant_id=11 WHERE id=101');
Db::startTrans(); Db::name('doctor_appointment')->select();
$pdo->exec('UPDATE zyt_doctor_appointment SET status=2 WHERE id=1');
$deny(fn () => Access::diagnosis(101, 14), 'doctor appointment revocation beats RR snapshot'); Db::rollback();
$pdo->exec('UPDATE zyt_doctor_appointment SET status=1 WHERE id=1');
$beforeHash = Context::build(101, 11)['source_hash'];
Db::startTrans(); Db::name('assistant_service_record')->select();
$pdo->exec("UPDATE zyt_assistant_service_record SET content='患者改为核对下周预约时段。' WHERE id=" . $record['id']);
$ok(Context::build(101, 11)['source_hash'] !== $beforeHash, 'context reads current source despite old RR snapshot');
$deny(fn () => $call('adoptAction', array_replace($adopt, ['action_key' => 'later_followup'])), 'source change blocks adoption inside existing RR transaction');
Db::rollback();
// 生成期间修改来源:真实 worker 提交前复核,禁止旧证据落为 ready。
$changed = $call('analyze', ['diagnosis_id' => 101, 'scenario' => 'revisit']);
$worker->runOnce(static function (...$args) use ($generator, $pdo, $record): array {
$answer = $generator(...$args);
$pdo->exec("UPDATE zyt_assistant_service_record SET content='患者再次调整服务时间。' WHERE id=" . $record['id']);
return $answer;
});
$ok(Db::name('assistant_service_job')->where('id', $changed['id'])->value('status') === 'stale', 'worker refuses source changed during generation');
$fresh = $call('analyze', ['diagnosis_id' => 101, 'scenario' => 'initial']); $worker->runOnce($generator);
Db::startTrans(); Db::name('assistant_service_knowledge')->select();
$pdo->exec("UPDATE zyt_assistant_service_knowledge SET version=version+1,answer='合成更新预约流程' WHERE id=" . $knowledge['id']);
$deny(fn () => $call('adoptAction', array_replace($adopt, ['job_id' => $fresh['id']])), 'knowledge version change beats existing RR snapshot'); Db::rollback();
$ok($call('jobs', ['status' => 'ready'])['count'] === 0, 'ready filter excludes rows freshly invalidated by source or knowledge');
$stale = $call('jobs', ['status' => 'stale', 'page_size' => 1]);
$ok($stale['count'] === 4 && count($stale['lists']) === 1 && $stale['lists'][0]['status'] === 'stale', 'stale filter computes exact count before pagination');
$retryParams = ['diagnosis_id' => 101, 'days' => 7, 'scenario' => 'initial'];
$retryJob = $call('analyze', $retryParams);
$worker->runOnce(static fn (): array => ['ok' => false, 'error_code' => 'CONFIG_INVALID']);
$ok(Db::name('assistant_service_job')->where('id', $retryJob['id'])->value('status') === 'failed', 'known-not-generated configuration failure is terminal failed');
$retried = $call('analyze', $retryParams); $worker->runOnce($generator);
$ok($retried['id'] === $retryJob['id'] && $retried['version'] === 2 && $call('job', ['id' => $retryJob['id']])['status'] === 'ready',
'explicit retry of known config failure completes same versioned job without duplicate row');
Db::name('assistant_service_job')->where('id', $retryJob['id'])->update(['status' => 'needs_reconciliation', 'error_code' => 'UPSTREAM_UNCERTAIN']);
$ok($call('analyze', $retryParams)['status'] === 'needs_reconciliation', 'unknown upstream state is never requeued');
// 主管目标医助入口:使用真实 MySQL 表与 Worker,沿用显式目录指纹防护。
$target = ['assistant_id' => 11, 'days' => 30];
$ok(array_column($call('staff', [], 13)['lists'], 'id') === [11], 'manager staff list excludes other department and manager identity');
$deny(fn () => $call('staffOverview', ['assistant_id' => 12, 'days' => 30], 13), 'staff overview rejects other department');
Db::name('admin')->insert(['id' => 15, 'name' => 'second assistant', 'root' => 0]);
Db::name('admin_role')->insert(['admin_id' => 15, 'role_id' => 2]);
Db::name('admin_dept')->insert(['admin_id' => 15, 'dept_id' => 10]);
Db::name('tcm_diagnosis')->insertAll([
['id' => 103, 'patient_id' => 201, 'assistant_id' => 15, 'patient_name' => '同患者第二诊单', 'phone' => ''],
['id' => 104, 'patient_id' => 204, 'assistant_id' => 11, 'patient_name' => '无来源诊单', 'phone' => ''],
]);
foreach ([[1, 'doctor_11', '目标医助真实发言'], [2, 'doctor_15', '其他医助私有发言']] as [$id, $from, $text]) {
Db::name('tcm_im_chat_message')->insert(['id' => $id, 'patient_id' => 201, 'diagnosis_id' => 101,
'from_account' => $from, 'to_account' => 'patient_201', 'doctor_peer_account' => 'doctor_11', 'msg_type' => 'text', 'text' => $text, 'msg_time' => time()]);
}
$targetContext = $call('context', $target + ['diagnosis_id' => 101], 13);
$ok($targetContext['subject_admin_id'] === 11 && !in_array('im:2', array_column($targetContext['sources'], 'id'), true), 'same patient target context excludes other assistant on MySQL');
$ok($call('staffOverview', $target, 13)['metrics']['im_messages'] === 1, 'same message counted once across multiple diagnoses on MySQL');
$before = (int) Db::name('assistant_service_job')->count();
$deny(fn () => $call('analyzeStaff', $target + ['scenario' => 'followup', 'diagnosis_ids' => [101, 104]], 13), 'target batch missing-source failure');
$ok((int) Db::name('assistant_service_job')->count() === $before, 'InnoDB target batch rolls back earlier nested enqueue');
$batch = $call('analyzeStaff', $target + ['scenario' => 'followup', 'diagnosis_ids' => [101, 103]], 13);
$again = $call('analyzeStaff', $target + ['scenario' => 'followup', 'diagnosis_ids' => [101, 103]], 13);
$ok($batch['count'] === 2 && array_column($batch['jobs'], 'id') === array_column($again['jobs'], 'id'), 'target bulk queue deduplication on MySQL');
$targetGenerator = static function (...$args) use ($generator, $ok): array {
$ok($args[2]['subject_admin_id'] === 11 && !in_array('im:2', array_column($args[2]['sources'], 'id'), true), 'worker preserves target through real MySQL context');
return $generator(...$args);
};
$worker->runOnce($targetGenerator); $worker->runOnce($targetGenerator);
$targetJob = $batch['jobs'][0];
$ok($call('job', ['id' => $targetJob['id']], 13)['status'] === 'ready', 'manager-created target task reaches ready');
$targetAction = $call('adoptAction', ['job_id' => $targetJob['id'], 'action_key' => 'confirm_slot', 'version' => 1, 'due_at' => time() + 3600], 13);
$ok((int) Db::name('assistant_service_action')->where('id', $targetAction['id'])->value('assignee_id') === 11
&& (int) Db::name('tcm_diagnosis_todo')->where('id', $targetAction['todo_id'])->value('creator_id') === 13,
'target action assignee and actual reminder creator are separate on MySQL');
$ok($call('actions', ['assistant_id' => 11], 13)['count'] === 2 && $call('actions', ['assistant_id' => 15], 13)['count'] === 0, 'execution filters by target across patients');
echo 'ASSISTANT_SERVICE_MYSQL_FLOW assertions=' . $checks . ' PASS real_access_context_logic_worker=1 concurrent_processes=2 network_model_calls=0' . PHP_EOL;
} finally {
try { Db::rollback(); } catch (Throwable $ignored) {}
if (preg_match('/^assistant_service_flow_[a-f0-9]{12}$/D', $database)) { $pdo->exec("DROP DATABASE `{$database}`"); }
}
@@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
/** 只连接显式指定、目录指纹已核对的临时 MySQL;不加载应用或 .env。 */
$port = (int) getenv('ASSISTANT_SERVICE_TEST_PORT');
$expectedDirectory = str_replace('\\', '/', (string) getenv('ASSISTANT_SERVICE_TEST_DATADIR'));
if (getenv('ASSISTANT_SERVICE_TEST_ALLOW_DISPOSABLE') !== '1' || $port < 1024
|| $expectedDirectory === '' || !str_contains($expectedDirectory, '/.spool/assistant-service-mysql')) {
throw new RuntimeException('必须显式提供本项目隔离测试库端口和数据目录');
}
$pdo = new PDO("mysql:host=127.0.0.1;port={$port};charset=utf8mb4", 'root', '', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$actual = str_replace('\\', '/', (string) $pdo->query('SELECT @@datadir')->fetchColumn());
if (strtolower(rtrim($actual, '/')) !== strtolower(rtrim($expectedDirectory, '/'))) {
throw new RuntimeException('数据目录不匹配,拒绝创建测试数据库');
}
$database = 'assistant_service_test_' . bin2hex(random_bytes(6));
$checks = 0;
$expect = static function (bool $ok, string $message) use (&$checks): void {
if (!$ok) {
throw new RuntimeException($message);
}
$checks++;
};
$runSql = static function (string $path) use ($pdo): void {
$sql = preg_replace('/^--.*$/m', '', (string) file_get_contents($path));
foreach (explode(';', (string) $sql) as $statement) {
if (trim($statement) !== '') {
$cursor = $pdo->query($statement);
$cursor->closeCursor();
}
}
};
$pdo->exec("CREATE DATABASE `{$database}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
try {
$pdo->exec("USE `{$database}`");
$pdo->exec("CREATE TABLE zyt_system_menu (
id int unsigned AUTO_INCREMENT PRIMARY KEY, pid int NOT NULL, type varchar(1), name varchar(100),
icon varchar(100), sort int, perms varchar(100), paths varchar(100), component varchar(150),
selected varchar(100), params varchar(100), is_cache tinyint, is_show tinyint, is_disable tinyint,
create_time int, update_time int) ENGINE=InnoDB");
$pdo->exec('CREATE TABLE zyt_system_role(id int PRIMARY KEY,name varchar(100),delete_time int NULL) ENGINE=InnoDB');
$pdo->exec('CREATE TABLE zyt_system_role_menu(role_id int,menu_id int,UNIQUE KEY uk_role_menu(role_id,menu_id)) ENGINE=InnoDB');
$pdo->exec("INSERT INTO zyt_system_role VALUES(1,'医生',NULL),(2,'医助',NULL),(3,'经理',NULL),(7,'诊室组长',NULL),(8,'管理员',NULL),(9,'已删除角色',1)");
$runSql(dirname(__DIR__) . '/sql/1.9.20260505/add_tcm_diagnosis_todo.sql');
$pdo->exec("INSERT INTO zyt_tcm_diagnosis_todo(diagnosis_id,content,status) VALUES(99,'历史提醒哨兵',1)");
$beforeTodo = $pdo->query('SELECT * FROM zyt_tcm_diagnosis_todo')->fetchAll(PDO::FETCH_ASSOC);
$migration = dirname(__DIR__) . '/sql/1.9.20261109/';
$runSql($migration . '01_assistant_service_tables.sql');
$runSql($migration . '02_assistant_service_menus.sql');
$beforeMenus = $pdo->query('SELECT * FROM zyt_system_menu ORDER BY id')->fetchAll(PDO::FETCH_ASSOC);
$beforeGrants = $pdo->query('SELECT * FROM zyt_system_role_menu ORDER BY role_id,menu_id')->fetchAll(PDO::FETCH_ASSOC);
$runSql($migration . '01_assistant_service_tables.sql');
$runSql($migration . '02_assistant_service_menus.sql');
$expect($beforeMenus === $pdo->query('SELECT * FROM zyt_system_menu ORDER BY id')->fetchAll(PDO::FETCH_ASSOC), '重复迁移改变菜单');
$expect($beforeGrants === $pdo->query('SELECT * FROM zyt_system_role_menu ORDER BY role_id,menu_id')->fetchAll(PDO::FETCH_ASSOC), '重复迁移改变授权');
$expect($beforeTodo === $pdo->query('SELECT * FROM zyt_tcm_diagnosis_todo')->fetchAll(PDO::FETCH_ASSOC), '迁移改变历史提醒');
$expect(count($beforeMenus) === 9, '模块菜单/权限数量错误');
$grants = $pdo->query('SELECT m.perms FROM zyt_system_role_menu rm JOIN zyt_system_menu m ON m.id=rm.menu_id WHERE rm.role_id=2')->fetchAll(PDO::FETCH_COLUMN);
$expect(in_array('tcm.assistantService/view', $grants, true), '医助缺少工作台权限');
$expect(in_array('tcm.assistantService/analyze', $grants, true), '医助缺少分析权限');
$expect(!in_array('tcm.assistantService/manageKnowledge', $grants, true), '医助被错误授予知识发布权限');
$expect(!in_array('tcm.assistantService/reviewQuality', $grants, true), '医助被错误授予主管质检权限');
$managerGrants = $pdo->query('SELECT m.perms FROM zyt_system_role_menu rm JOIN zyt_system_menu m ON m.id=rm.menu_id WHERE rm.role_id=3')->fetchAll(PDO::FETCH_COLUMN);
$expect(in_array('tcm.assistantService/reviewQuality', $managerGrants, true), '经理缺少质检权限');
$expect(in_array('tcm.assistantService/manageKnowledge', $managerGrants, true), '经理缺少知识发布权限');
$expect((int) $pdo->query('SELECT COUNT(*) FROM zyt_system_role_menu WHERE role_id IN(1,9)')->fetchColumn() === 0, '非目标角色被新增授权');
foreach (['record', 'job', 'review', 'action', 'knowledge'] as $table) {
$expect($pdo->query("SHOW CREATE TABLE zyt_assistant_service_{$table}")->fetch() !== false, '缺少模块表');
}
// 分析任务、动作唯一约束在数据库层生效。
$pdo->exec("INSERT INTO zyt_assistant_service_job(diagnosis_id,actor_id,type,scenario,dedupe_key,source_hash,scope_hash,payload_json,created_at,updated_at)
VALUES(1,2,'analysis','initial',REPEAT('a',64),REPEAT('b',64),REPEAT('c',64),'{}',1,1)");
$duplicateRejected = false;
try {
$pdo->exec("INSERT INTO zyt_assistant_service_job(diagnosis_id,actor_id,type,scenario,dedupe_key,source_hash,scope_hash,payload_json,created_at,updated_at)
VALUES(1,2,'analysis','initial',REPEAT('a',64),REPEAT('b',64),REPEAT('c',64),'{}',1,1)");
} catch (PDOException $e) {
$duplicateRejected = $e->getCode() === '23000';
}
$expect($duplicateRejected, '重复任务未被唯一约束拦截');
$pdo->exec("INSERT INTO zyt_assistant_service_action(diagnosis_id,job_id,action_key,todo_id,assignee_id,content,due_at,created_at,updated_at)
VALUES(1,1,'contact',99,2,'合成跟进',1,1,1)");
$duplicateRejected = false;
try {
$pdo->exec("INSERT INTO zyt_assistant_service_action(diagnosis_id,job_id,action_key,todo_id,assignee_id,content,due_at,created_at,updated_at)
VALUES(1,1,'contact',100,2,'重复跟进',1,1,1)");
} catch (PDOException $e) {
$duplicateRejected = $e->getCode() === '23000';
}
$expect($duplicateRejected, '重复采纳动作未被唯一约束拦截');
echo "AssistantServiceMysqlMigrationTest PASS ({$checks} checks)\n";
} finally {
// 名称由本脚本生成且已核对临时数据目录;只移除本次创建的数据库。
if (preg_match('/^assistant_service_test_[a-f0-9]{12}$/D', $database)) {
$pdo->exec("DROP DATABASE `{$database}`");
}
}
@@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
// 真实 ORM/Access 与合成授权记录;不初始化应用、不联网、不发送企微消息。
require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
use app\common\service\assistantservice\AssistantServiceReminderRecipient as Recipient;
use think\Container;
use think\facade\Db;
new think\App();
set_exception_handler(static function (Throwable $e): void { fwrite(STDERR, $e->getMessage() . PHP_EOL . $e->getTraceAsString()); exit(1); });
$manager = new think\DbManager();
$manager->setConfig(['default' => 'isolated', 'connections' => ['isolated' => [
'type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'test_', 'fields_strict' => true,
]]]);
Container::getInstance()->instance('think\DbManager', $manager);
think\Model::setDb($manager);
Container::getInstance()->instance('config', new think\Config());
$checks = 0;
$expect = static function (bool $ok, string $why) use (&$checks): void { if (!$ok) { throw new RuntimeException($why); } $checks++; };
$deny = static function (callable $action, string $why) use ($expect): void {
try { $action(); } catch (DomainException $e) { $expect(true, $why); return; }
throw new RuntimeException('Expected rejection: ' . $why);
};
$todo = ['id' => 1, 'diagnosis_id' => 101, 'patient_id' => 201, 'creator_id' => 13];
$expect(Recipient::resolve($todo) === 13, 'legacy reminder works before module migration');
$schemas = [
'admin' => 'id INTEGER PRIMARY KEY,name TEXT,root INTEGER DEFAULT 0,disable INTEGER DEFAULT 0,delete_time INTEGER NULL',
'admin_role' => 'admin_id INTEGER,role_id INTEGER',
'admin_dept' => 'admin_id INTEGER,dept_id INTEGER',
'system_role' => 'id INTEGER PRIMARY KEY,name TEXT,data_scope INTEGER,delete_time INTEGER NULL',
'system_role_menu' => 'role_id INTEGER,menu_id INTEGER',
'system_menu' => 'id INTEGER PRIMARY KEY,perms TEXT,is_disable INTEGER DEFAULT 0',
'tcm_diagnosis' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,assistant_id INTEGER,status INTEGER DEFAULT 1,delete_time INTEGER NULL',
'assistant_service_action' => 'id INTEGER PRIMARY KEY,todo_id INTEGER,diagnosis_id INTEGER,job_id INTEGER,assignee_id INTEGER,business_state TEXT',
'assistant_service_job' => 'id INTEGER PRIMARY KEY,diagnosis_id INTEGER,patient_id INTEGER,payload_json TEXT',
];
foreach ($schemas as $table => $schema) { Db::execute('CREATE TABLE test_' . $table . ' (' . $schema . ')'); }
Db::name('admin')->insertAll([['id' => 11, 'name' => '合成医助'], ['id' => 13, 'name' => '合成主管']]);
Db::name('system_role')->insert(['id' => 2, 'name' => '医助', 'data_scope' => 4]);
Db::name('admin_role')->insert(['admin_id' => 11, 'role_id' => 2]);
Db::name('system_menu')->insert(['id' => 1, 'perms' => 'tcm.assistantService/view']);
Db::name('system_role_menu')->insert(['role_id' => 2, 'menu_id' => 1]);
Db::name('tcm_diagnosis')->insert(['id' => 101, 'patient_id' => 201, 'assistant_id' => 11]);
$expect(Recipient::resolve($todo) === 13, 'ordinary reminder keeps creator after module installed');
Db::name('assistant_service_job')->insert(['id' => 5, 'diagnosis_id' => 101, 'patient_id' => 201]);
Db::name('assistant_service_action')->insert(['id' => 7, 'todo_id' => 1, 'diagnosis_id' => 101, 'job_id' => 5, 'assignee_id' => 11, 'business_state' => 'pending']);
$expect(Recipient::resolve($todo) === 11, 'module reminder goes to assignee rather than manager creator');
$expect(Recipient::resolve($todo + ['assignee_id' => 99]) === 11, 'caller cannot override stored responsibility');
Db::name('admin')->where('id', 11)->update(['disable' => 1]);
$deny(fn () => Recipient::resolve($todo), 'disabled assignee not notified');
Db::name('admin')->where('id', 11)->update(['disable' => 0]);
Db::name('system_menu')->where('id', 1)->update(['is_disable' => 1]);
$deny(fn () => Recipient::resolve($todo), 'revoked module permission not notified');
Db::name('system_menu')->where('id', 1)->update(['is_disable' => 0]);
Db::name('tcm_diagnosis')->where('id', 101)->update(['assistant_id' => 12]);
$deny(fn () => Recipient::resolve($todo), 'transferred patient not disclosed to prior assignee');
Db::name('tcm_diagnosis')->where('id', 101)->update(['assistant_id' => 11, 'patient_id' => 202]);
$deny(fn () => Recipient::resolve($todo), 'rebound patient not disclosed through old reminder');
Db::name('tcm_diagnosis')->where('id', 101)->update(['patient_id' => 201]);
Db::name('assistant_service_action')->where('id', 7)->update(['business_state' => 'completed']);
$deny(fn () => Recipient::resolve($todo), 'finished action does not send stale reminder');
Db::name('assistant_service_action')->where('id', 7)->update(['business_state' => 'in_progress']);
$expect(Recipient::resolve($todo) === 11, 'in-progress action remains deliverable');
$deny(fn () => Recipient::resolve(array_replace($todo, ['diagnosis_id' => 102])), 'mismatched reminder link rejected');
Db::name('assistant_service_job')->where('id', 5)->delete();
$deny(fn () => Recipient::resolve($todo), 'orphaned module task does not fall back to manager');
Db::name('assistant_service_job')->insert(['id' => 5, 'diagnosis_id' => 101, 'patient_id' => 201,
'payload_json' => json_encode(['context' => ['subject_admin_id' => 11]])]);
Db::name('system_role_menu')->where('role_id', 2)->delete();
$expect(Recipient::resolve($todo) === 11, 'valid target without module menu receives supervisor-assigned reminder');
Db::name('assistant_service_job')->where('id', 5)->update(['payload_json' => json_encode(['context' => ['subject_admin_id' => 12]])]);
$deny(fn () => Recipient::resolve($todo), 'stored subject must match assigned target');
Db::name('assistant_service_job')->where('id', 5)->update(['payload_json' => json_encode(['context' => ['subject_admin_id' => 11]])]);
Db::name('system_role')->insert(['id' => 1, 'name' => '医生', 'data_scope' => 1]);
Db::name('admin_role')->where('admin_id', 11)->update(['role_id' => 1]);
$deny(fn () => Recipient::resolve($todo), 'former assistant with doctor role is not a valid target recipient');
Db::name('admin_role')->where('admin_id', 11)->update(['role_id' => 2]);
Db::name('tcm_diagnosis')->where('id', 101)->update(['assistant_id' => 12]);
$deny(fn () => Recipient::resolve($todo), 'target reminder rechecks direct patient responsibility');
Db::name('tcm_diagnosis')->where('id', 101)->update(['assistant_id' => 11]);
Db::name('system_role')->where('id', 2)->update(['delete_time' => 1]);
$deny(fn () => Recipient::resolve($todo), 'deleted assistant role cannot receive target reminder');
echo 'ASSISTANT_SERVICE_REMINDER_RECIPIENT assertions=' . $checks . ' PASS real_access_orm=1 sends=0' . PHP_EOL;
+332
View File
@@ -0,0 +1,332 @@
<?php
declare(strict_types=1);
// 真实 ORM 与权限/业务代码,临时 SQLite;不初始化应用、不读 .env、不联网。
require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
use app\adminapi\logic\tcm\AssistantServiceLogic as Logic;
use app\adminapi\validate\tcm\AssistantServiceValidate as Validate;
use app\common\service\assistantservice\AssistantServiceAccess as Access;
use app\common\service\assistantservice\AssistantServiceContext as Context;
use think\Container;
use think\facade\Db;
if (!in_array('sqlite', PDO::getAvailableDrivers(), true)) {
throw new RuntimeException('Run: php -d extension=php_pdo_sqlite.dll tests/AssistantServiceApiTest.php');
}
new think\App();
set_exception_handler(static function (Throwable $e): void {
fwrite(STDERR, $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL); exit(1);
});
$manager = new think\DbManager();
$manager->setConfig(['default' => 'isolated', 'connections' => ['isolated' => [
'type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'test_', 'fields_strict' => true,
]]]);
Container::getInstance()->instance('think\DbManager', $manager);
think\Model::setDb($manager);
$config = new think\Config();
$config->set(['enabled' => true, 'profile' => 'qwen', 'timeout' => 120, 'daily_job_limit' => 100,
'max_source_rows' => 200, 'max_source_chars' => 30000, 'max_manual_chars' => 10000, 'max_knowledge_rows' => 40], 'assistant_service');
$config->set(['enable' => true, 'base_url' => 'https://example.invalid', 'models' => [
'qwen' => ['name' => 'synthetic', 'api_key' => 'synthetic-no-network']]], 'prescription_ai');
$config->set(['data_scope' => ['enabled' => true, 'no_dept_fallback_self' => true]], 'project');
Container::getInstance()->instance('config', $config);
$tables = [
'admin' => 'id INTEGER PRIMARY KEY,name TEXT,root INTEGER DEFAULT 0,disable INTEGER DEFAULT 0,delete_time INTEGER NULL',
'admin_role' => 'admin_id INTEGER,role_id INTEGER',
'admin_dept' => 'admin_id INTEGER,dept_id INTEGER',
'dept' => 'id INTEGER PRIMARY KEY,pid INTEGER,status INTEGER DEFAULT 1,delete_time INTEGER NULL',
'system_role' => 'id INTEGER PRIMARY KEY,name TEXT,data_scope INTEGER,delete_time INTEGER NULL',
'system_role_menu' => 'role_id INTEGER,menu_id INTEGER',
'system_menu' => 'id INTEGER PRIMARY KEY,perms TEXT,is_disable INTEGER DEFAULT 0',
'doctor_appointment' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,doctor_id INTEGER,status INTEGER',
'tcm_diagnosis' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,assistant_id INTEGER,patient_name TEXT,phone TEXT,status INTEGER DEFAULT 1,delete_time INTEGER NULL',
'tracking_note' => 'id INTEGER PRIMARY KEY,diagnosis_id INTEGER,admin_id INTEGER,note_date TEXT,content TEXT,create_time INTEGER,update_time INTEGER,delete_time INTEGER NULL',
'tcm_im_chat_message' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,diagnosis_id INTEGER,from_account TEXT,to_account TEXT,doctor_peer_account TEXT,msg_type TEXT,text TEXT,msg_time INTEGER',
'tcm_diagnosis_todo' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,patient_id INTEGER,content TEXT,remind_time INTEGER,status INTEGER,creator_id INTEGER,creator_name TEXT,create_time INTEGER,update_time INTEGER,notified_at INTEGER DEFAULT 0,cancelled_at INTEGER DEFAULT 0,cancelled_by INTEGER DEFAULT 0,delete_time INTEGER NULL',
'assistant_service_record' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,patient_id INTEGER,actor_id INTEGER,content TEXT,record_type TEXT,speaker_confirmed INTEGER,occurred_at INTEGER,created_at INTEGER,delete_time INTEGER NULL',
'assistant_service_job' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,patient_id INTEGER,actor_id INTEGER,type TEXT,scenario TEXT,days INTEGER,status TEXT,version INTEGER,dedupe_key TEXT UNIQUE,source_hash TEXT,scope_hash TEXT,payload_json TEXT,result_json TEXT,claim_token TEXT DEFAULT "",lease_until INTEGER DEFAULT 0,error_code TEXT DEFAULT "",error_message TEXT DEFAULT "",upstream_id TEXT DEFAULT "",created_at INTEGER,updated_at INTEGER,finished_at INTEGER DEFAULT 0',
'assistant_service_review' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,job_id INTEGER,item_key TEXT,reviewer_id INTEGER,decision TEXT,note TEXT,created_at INTEGER',
'assistant_service_action' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,job_id INTEGER,action_key TEXT,todo_id INTEGER,assignee_id INTEGER,content TEXT,due_at INTEGER,business_state TEXT,completion_note TEXT DEFAULT "",completed_at INTEGER DEFAULT 0,created_at INTEGER,updated_at INTEGER,UNIQUE(job_id,action_key)',
'assistant_service_knowledge' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,question TEXT,answer TEXT,category TEXT,source_note TEXT,status TEXT,version INTEGER,created_by INTEGER,published_by INTEGER,created_at INTEGER,updated_at INTEGER',
];
foreach ($tables as $name => $schema) { Db::execute('CREATE TABLE test_' . $name . ' (' . $schema . ')'); }
Db::name('admin')->insertAll([
['id' => 1, 'name' => 'root', 'root' => 1], ['id' => 11, 'name' => 'assistant', 'root' => 0],
['id' => 12, 'name' => 'other', 'root' => 0], ['id' => 13, 'name' => 'team', 'root' => 0], ['id' => 14, 'name' => 'doctor', 'root' => 0],
]);
Db::name('system_role')->insertAll([
['id' => 1, 'name' => '医生', 'data_scope' => 1], ['id' => 2, 'name' => '医助', 'data_scope' => 4], ['id' => 3, 'name' => '经理', 'data_scope' => 3],
]);
Db::name('admin_role')->insertAll([['admin_id' => 11, 'role_id' => 2], ['admin_id' => 12, 'role_id' => 2], ['admin_id' => 13, 'role_id' => 3], ['admin_id' => 14, 'role_id' => 1]]);
Db::name('dept')->insertAll([['id' => 10, 'pid' => 0], ['id' => 20, 'pid' => 0]]);
Db::name('admin_dept')->insertAll([['admin_id' => 11, 'dept_id' => 10], ['admin_id' => 12, 'dept_id' => 20], ['admin_id' => 13, 'dept_id' => 10]]);
foreach (Access::PERMISSIONS as $i => $permission) {
Db::name('system_menu')->insert(['id' => $i + 1, 'perms' => 'tcm.assistantService/' . $permission]);
foreach ([1, 2, 3] as $role) { Db::name('system_role_menu')->insert(['role_id' => $role, 'menu_id' => $i + 1]); }
}
Db::name('tcm_diagnosis')->insertAll([
['id' => 101, 'patient_id' => 201, 'assistant_id' => 11, 'patient_name' => '合成甲', 'phone' => '13800138000'],
['id' => 102, 'patient_id' => 202, 'assistant_id' => 12, 'patient_name' => '合成乙', 'phone' => '13900139000'],
['id' => 103, 'patient_id' => 0, 'assistant_id' => 11, 'patient_name' => '未映射', 'phone' => ''],
]);
Db::name('doctor_appointment')->insert(['id' => 1, 'patient_id' => 101, 'doctor_id' => 14, 'status' => 1]);
$now = time();
Db::name('tracking_note')->insert(['id' => 1, 'diagnosis_id' => 101, 'admin_id' => 11,
'note_date' => date('Y-m-d'), 'content' => '患者要求周六确认预约', 'create_time' => $now, 'update_time' => $now]);
foreach ([
[1, 201, 'patient_201', 'doctor_11', 'text', '请帮我核对预约,电话13800138000'],
[2, 201, 'doctor_11', 'patient_201', 'text', '我将在明天回复可预约时段'],
[3, 201, 'doctor_12', 'patient_201', 'text', '其他部门私有沟通'],
[4, 201, 'doctor_11', 'patient_999', 'text', '错误患者映射'],
[5, 201, 'doctor_11', 'patient_201', 'image', '不可读图片'],
[6, 201, 'doctor_999', 'patient_201', 'text', '不存在的员工'],
] as [$id, $patient, $from, $to, $type, $text]) {
Db::name('tcm_im_chat_message')->insert(['id' => $id, 'patient_id' => $patient, 'diagnosis_id' => 999,
'from_account' => $from, 'to_account' => $to, 'doctor_peer_account' => 'doctor_11', 'msg_type' => $type, 'text' => $text, 'msg_time' => $now - 100]);
}
// 与 API 测试使用相同合成表;新增目标链路必须走真实 Access/Context/Worker,不能用上下文桩替代。
$checks = 0;
$ok = static function (bool $condition, string $label) use (&$checks): void { if (!$condition) { throw new RuntimeException($label); } $checks++; };
$deny = static function (callable $call, string $label) use ($ok): void {
try { $call(); } catch (DomainException $e) { $ok(true, $label); return; } $ok(false, $label);
};
$call = static fn (string $action, array $p = [], int $actor = 13): array => Logic::$action(Validate::parameters($action, $p), $actor);
$target = ['assistant_id' => 11, 'days' => 30];
$daily = $call('staffDailyContacts', ['assistant_id' => 11]);
$ok($daily['staff']['id'] === 11 && $daily['daily']['state'] === 'unavailable' && $daily['summary']['required'] === null
&& $daily['lists'] === [], 'daily route returns explicit unavailable with old synthetic schema');
$deny(fn () => $call('staffDailyContacts', ['assistant_id' => 12]), 'daily route checks staff scope even when schema unavailable');
Db::name('system_role_menu')->where('role_id', 3)->where('menu_id', 1)->delete();
$deny(fn () => $call('staffDailyContacts', ['assistant_id' => 11]), 'daily route checks live module view permission');
Db::name('system_role_menu')->insert(['role_id' => 3, 'menu_id' => 1]);
Db::name('admin')->insertAll([
['id' => 15, 'name' => '同组医助', 'root' => 0, 'disable' => 0], ['id' => 16, 'name' => '停用医助', 'root' => 0, 'disable' => 1],
['id' => 17, 'name' => '新角色医助', 'root' => 0, 'disable' => 0],
]);
Db::name('system_role')->insert(['id' => 22, 'name' => '医助', 'data_scope' => 4]);
Db::name('admin_role')->insertAll([['admin_id' => 15, 'role_id' => 2], ['admin_id' => 16, 'role_id' => 2], ['admin_id' => 17, 'role_id' => 22],
['admin_id' => 1, 'role_id' => 2], ['admin_id' => 13, 'role_id' => 2]]);
Db::name('admin_dept')->insertAll([['admin_id' => 15, 'dept_id' => 10], ['admin_id' => 16, 'dept_id' => 10], ['admin_id' => 17, 'dept_id' => 10]]);
$ok(array_column($call('staff')['lists'], 'id') === [11, 15, 17], 'manager sees active assistant roles only, never manager or root aliases');
$ok(array_column($call('staff', [], 11)['lists'], 'id') === [11], 'ordinary assistant sees self');
$ok($call('staff', [], 14)['count'] === 0, 'doctor is not an assistant');
$ok(array_column($call('staff', [], 1)['lists'], 'id') === [11, 12, 15, 17], 'root sees assistants without becoming one');
$ok($call('staff', ['keyword' => '新角色'])['lists'][0]['id'] === 17, 'named active assistant role works without module permission');
foreach ([12, 13, 14, 16, 999] as $id) { $deny(fn () => $call('staffOverview', ['assistant_id' => $id, 'days' => 30]), 'invalid or cross-department target ' . $id); }
$deny(fn () => $call('staffOverview', $target, 15), 'peer assistant cannot inspect colleague');
foreach ([0, -1, 1.2, '1.2', true] as $id) { $deny(fn () => $call('staffOverview', ['assistant_id' => $id]), 'strict required assistant id'); }
$deny(fn () => $call('analyzeStaff', $target + ['scenario' => 'followup', 'diagnosis_ids' => []]), 'empty batch rejected');
$deny(fn () => $call('analyzeStaff', $target + ['scenario' => 'followup', 'diagnosis_ids' => range(100, 110)]), 'more than ten rejected');
$deny(fn () => $call('analyzeStaff', $target + ['scenario' => 'followup', 'diagnosis_ids' => [101, 101]]), 'duplicate batch rejected');
$deny(fn () => $call('analyzeStaff', $target + ['scenario' => 'followup', 'diagnosis_ids' => [101.5]]), 'float in batch rejected');
Db::name('tcm_diagnosis')->insertAll([
['id' => 104, 'patient_id' => 201, 'assistant_id' => 15, 'patient_name' => '同患者第二诊单', 'phone' => ''],
['id' => 105, 'patient_id' => 205, 'assistant_id' => 15, 'patient_name' => '无关患者', 'phone' => ''],
['id' => 106, 'patient_id' => 206, 'assistant_id' => 15, 'patient_name' => '仅登记历史', 'phone' => ''],
]);
Db::name('assistant_service_record')->insertAll([
['diagnosis_id' => 101, 'patient_id' => 201, 'actor_id' => 11, 'content' => '目标医助登记', 'record_type' => 'service_note', 'speaker_confirmed' => 0, 'occurred_at' => $now - 50, 'created_at' => $now],
['diagnosis_id' => 101, 'patient_id' => 201, 'actor_id' => 15, 'content' => '同部门他人登记不可混入', 'record_type' => 'service_note', 'speaker_confirmed' => 0, 'occurred_at' => $now - 50, 'created_at' => $now],
['diagnosis_id' => 106, 'patient_id' => 206, 'actor_id' => 11, 'content' => '历史医助登记', 'record_type' => 'service_note', 'speaker_confirmed' => 0, 'occurred_at' => $now - 40, 'created_at' => $now],
['diagnosis_id' => 105, 'patient_id' => 999, 'actor_id' => 11, 'content' => '旧患者绑定不可混入', 'record_type' => 'service_note', 'speaker_confirmed' => 0, 'occurred_at' => $now - 40, 'created_at' => $now],
['diagnosis_id' => 105, 'patient_id' => 205, 'actor_id' => 11, 'content' => '期间外记录', 'record_type' => 'service_note', 'speaker_confirmed' => 0, 'occurred_at' => $now - 40 * 86400, 'created_at' => $now],
]);
Db::name('tracking_note')->insert(['id' => 2, 'diagnosis_id' => 101, 'admin_id' => 15, 'note_date' => date('Y-m-d'),
'content' => '其他医助的跟踪备注', 'create_time' => $now, 'update_time' => $now]);
Db::name('tcm_im_chat_message')->insert(['id' => 7, 'patient_id' => 201, 'diagnosis_id' => 101,
'from_account' => 'doctor_15', 'to_account' => 'patient_201', 'doctor_peer_account' => 'doctor_11', 'msg_type' => 'text', 'text' => '同组其他医助发言', 'msg_time' => $now - 90]);
$context = $call('context', $target + ['diagnosis_id' => 101]);
$ok($context['latest_job'] === null && $context['latest_analysis_job'] === null, 'empty context explicitly has no latest task or analysis');
$ids = array_column($context['sources'], 'id'); sort($ids);
$ok($ids === ['im:1', 'im:2', 'manual:1', 'tracking:1'] && $context['subject_admin_id'] === 11, 'target context includes only target pair, records and authored tracking');
$manual = array_values(array_filter($context['sources'], static fn ($source) => $source['channel'] === 'manual'))[0];
$ok($manual['actor_admin_id'] === 0 && $manual['speaker'] === 'unknown', 'target recorder never becomes historical speaker');
$otherContext = $call('context', ['assistant_id' => 15, 'diagnosis_id' => 101, 'days' => 30]);
$ok($otherContext['source_hash'] !== $context['source_hash'] && $otherContext['scope_hash'] !== $context['scope_hash'], 'target participates in source and scope hashes');
$ok(!str_contains(json_encode($context['sources']), '同组其他') && !str_contains(json_encode($otherContext['sources']), '目标医助登记'), 'same patient target source isolation');
$ok($call('context', ['assistant_id' => 17, 'diagnosis_id' => 101])['subject_admin_id'] === 17, 'target needs valid assistant identity but no module grants or impersonated login');
Db::name('tcm_diagnosis')->insert(['id' => 107, 'patient_id' => 207, 'assistant_id' => 17, 'patient_name' => '命名角色患者', 'phone' => '']);
Db::name('system_role_menu')->insert(['role_id' => 22, 'menu_id' => 1]);
$ok(array_column($call('staffCases', ['assistant_id' => 17, 'days' => 30], 17)['lists'], 'diagnosis_id') === [107], 'named assistant role with view grant retains own assigned patient scope');
$cases = $call('staffCases', $target);
$caseIds = array_column($cases['lists'], 'diagnosis_id'); sort($caseIds);
$ok($caseIds === [101, 103, 104, 106], 'cases are current assignment or target period activity, not all visible patients');
$ok(in_array(105, array_column($call('staffCases', ['assistant_id' => 11, 'days' => 90])['lists'], 'diagnosis_id'), true), 'changing period includes historical own registration without changing current assignee');
$ok($call('staffCases', $target + ['page_size' => 1])['count'] === 4, 'staff case pagination count');
$ok($call('staffCases', $target + ['keyword' => '13800138000'])['lists'][0]['phone_masked'] === '138****8000', 'case phone search preserves masked output');
$overview = $call('staffOverview', $target);
$ok($overview['metrics']['assigned_cases'] === 2, 'assignment stock separately counted');
$ok($overview['metrics']['im_messages'] === 1 && $overview['metrics']['manual_records'] === 2, 'outgoing IM unique across duplicate patient diagnoses; reliable manual binding only');
$ok($overview['metrics']['analyzed_cases'] === 0 && count($overview['quality']) === 6, 'empty analysis is zero, not fabricated');
$legacy = Context::build(101, 13);
$ok($legacy['source_hash'] === hash('sha256', json_encode($legacy['sources'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)), 'no-target legacy source hash unchanged');
$before = (int) Db::name('assistant_service_job')->count();
$deny(fn () => $call('analyzeStaff', $target + ['scenario' => 'followup', 'diagnosis_ids' => [101, 105]]), 'visible but unrelated case cannot enter target batch');
$deny(fn () => $call('analyzeStaff', $target + ['scenario' => 'followup', 'diagnosis_ids' => [101, 102]]), 'cross-department batch refused');
$deny(fn () => $call('analyzeStaff', $target + ['scenario' => 'followup', 'diagnosis_ids' => [101, 103]]), 'missing sources rolls back earlier enqueued case');
$ok((int) Db::name('assistant_service_job')->count() === $before, 'entire batch atomic on no-source failure');
$config->set(['daily_job_limit' => 1], 'assistant_service');
$deny(fn () => $call('analyzeStaff', $target + ['scenario' => 'followup', 'diagnosis_ids' => [101, 106]]), 'batch respects aggregate daily quota');
$ok((int) Db::name('assistant_service_job')->count() === $before, 'quota rejection rolls back first job');
$config->set(['daily_job_limit' => 100], 'assistant_service');
$batch = $call('analyzeStaff', $target + ['scenario' => 'followup', 'diagnosis_ids' => [101, 104]]);
$ok($batch['count'] === 2 && array_column($batch['jobs'], 'subject_admin_id') === [11, 11], 'batch queues explicit target tasks');
$repeat = $call('analyzeStaff', $target + ['scenario' => 'followup', 'diagnosis_ids' => [101, 104]]);
$ok(array_column($batch['jobs'], 'id') === array_column($repeat['jobs'], 'id'), 'batch deduplication reuses jobs');
$jobId = $batch['jobs'][0]['id'];
$stored = Db::name('assistant_service_job')->where('id', $jobId)->find();
$ok((int) $stored['actor_id'] === 13 && json_decode($stored['payload_json'], true)['context']['subject_admin_id'] === 11, 'actual operator is manager; analysis subject is assistant');
$ok($call('jobs', ['assistant_id' => 11])['count'] === 2 && $call('jobs', ['assistant_id' => 15])['count'] === 0, 'jobs filter by payload subject, never operator or current assignment');
$quality = [];
foreach (['identity', 'needs', 'explanation', 'next_step', 'followup', 'escalation'] as $key) {
$quality[] = ['key' => $key, 'label' => '合成质检', 'status' => $key === 'next_step' ? 'missed' : 'met',
'reason' => '仅供人工核对的合成证据', 'evidence_ids' => ['im:2'], 'actor_admin_id' => 11];
}
$result = ['summary' => [['text' => '预约服务记录', 'evidence_ids' => ['im:1']]], 'needs' => [], 'unresolved' => [], 'tags' => [],
'suggested_actions' => [['key' => 'confirm_slot', 'text' => '核对可预约时段', 'evidence_ids' => ['im:1']]], 'quality_checks' => $quality];
$worker = new \app\common\service\assistantservice\AssistantServiceWorker();
$calls = 0;
$generator = static function ($type, $scenario, $ctx, $knowledge, $question) use (&$calls, $ok, $result): array {
$calls++;
$ok($ctx['subject_admin_id'] === 11 && !in_array('im:7', array_column($ctx['sources'], 'id'), true), 'real worker retains target and excludes other assistant sources');
return ['ok' => true, 'result' => $result, 'message_id' => 'synthetic-target'];
};
$ok($worker->runOnce($generator) && $worker->runOnce($generator) && $calls === 2, 'real target worker consumes queued tasks using real context and access');
$view = $call('job', ['id' => $jobId]);
$ok($view['status'] === 'ready' && $view['subject_admin_id'] === 11, 'target remains valid across worker checks and manager read');
$ok($call('context', $target + ['diagnosis_id' => 101])['latest_job']['id'] === $jobId, 'context latest task matches target');
$overview = $call('staffOverview', $target);
$checksByKey = array_column($overview['quality'], null, 'key');
$ok($overview['metrics']['analyzed_cases'] === 2 && $checksByKey['next_step']['missed'] === 2, 'analysis counts distinct diagnoses with attributable evidence');
$ok($call('staffIssues', $target)['count'] === 2, 'target missed issues surfaced across cases');
$ok($call('staffOverview', ['assistant_id' => 11, 'days' => 7])['metrics']['analyzed_cases'] === 0, '30-day analysis never counted as 7-day coverage');
$ok($call('staffOverview', ['assistant_id' => 15, 'days' => 30])['metrics']['analyzed_cases'] === 0, 'analysis not attributed to current other assignee');
$newJob = $call('analyze', $target + ['diagnosis_id' => 101, 'scenario' => 'initial']);
$worker->runOnce($generator);
// 较新回复占满历史第一页时,最新分析仍须由 context 独立返回。
Db::startTrans();
try {
$latestContext = $call('context', $target + ['diagnosis_id' => 101]);
$ok($latestContext['latest_analysis_job']['id'] === $newJob['id']
&& $latestContext['latest_analysis_job'] === $latestContext['latest_job'], 'same latest analysis keeps complete formatted job');
$replyFixture = Db::name('assistant_service_job')->where('id', $newJob['id'])->find();
unset($replyFixture['id']);
$replyFixture['type'] = 'reply';
$replyFixture['status'] = 'queued';
$replyFixture['result_json'] = null;
for ($i = 0; $i < 12; $i++) {
$replyFixture['dedupe_key'] = 'synthetic-context-reply-' . $i;
$replyId = (int) Db::name('assistant_service_job')->insertGetId($replyFixture);
}
$history = $call('jobs', ['assistant_id' => 11, 'diagnosis_id' => 101, 'page_no' => 1, 'page_size' => 10]);
$ok(count($history['lists']) === 10 && array_unique(array_column($history['lists'], 'type')) === ['reply'], 'history first page contains only replies');
$call('analyze', ['assistant_id' => 15, 'diagnosis_id' => 101, 'days' => 30, 'scenario' => 'initial']);
$call('analyze', ['assistant_id' => 11, 'diagnosis_id' => 101, 'days' => 7, 'scenario' => 'initial']);
$call('analyze', $target + ['diagnosis_id' => 104, 'scenario' => 'initial']);
$mismatchedPatient = Db::name('assistant_service_job')->where('id', $newJob['id'])->find();
unset($mismatchedPatient['id']);
$mismatchedPatient['patient_id'] = 999;
$mismatchedPatient['dedupe_key'] = 'synthetic-context-mismatched-patient';
Db::name('assistant_service_job')->insert($mismatchedPatient);
$beforeRead = (int) Db::name('assistant_service_job')->count();
$afterReply = $call('context', $target + ['diagnosis_id' => 101]);
$ok($afterReply['latest_job']['id'] === $replyId && $afterReply['latest_job']['type'] === 'reply', 'generic latest task remains the newest matching reply');
$ok($afterReply['latest_analysis_job']['id'] === $newJob['id']
&& $afterReply['latest_analysis_job'] === $latestContext['latest_analysis_job'], 'latest analysis ignores replies and other subjects, periods, diagnoses and patient bindings');
$ok((int) Db::name('assistant_service_job')->count() === $beforeRead, 'context latest analysis lookup does not enqueue jobs');
} finally {
Db::rollback();
}
$ok($call('staffIssues', $target)['count'] === 2, 'multiple analyses do not inflate same diagnosis key');
$issues = $call('staffIssues', $target)['lists'];
$latest = array_values(array_filter($issues, static fn ($issue) => $issue['diagnosis_id'] === 101))[0];
$ok($latest['job_id'] === $newJob['id'], 'latest valid analysis wins per diagnosis quality item');
$call('reviewQuality', ['job_id' => $newJob['id'], 'item_key' => 'next_step', 'decision' => 'confirmed', 'note' => '核对', 'version' => 1]);
$call('reviewQuality', ['job_id' => $newJob['id'], 'item_key' => 'next_step', 'decision' => 'dismissed', 'note' => '复核排除', 'version' => 1]);
$overview = $call('staffOverview', $target); $checksByKey = array_column($overview['quality'], null, 'key');
$ok($checksByKey['next_step']['dismissed'] === 1 && $checksByKey['next_step']['confirmed'] === 0 && $checksByKey['next_step']['unreviewed'] === 1, 'latest human review controls aggregated review state');
$ok($call('staffIssues', $target)['count'] === 1, 'dismissed issue excluded rather than fallback to old missed analysis');
$insufficient = $result;
$insufficient['quality_checks'][3]['status'] = 'insufficient'; $insufficient['quality_checks'][3]['actor_admin_id'] = 0;
$insufficient['quality_checks'][3]['evidence_ids'] = [];
Db::name('assistant_service_job')->where('id', $newJob['id'])->update(['result_json' => json_encode($insufficient)]);
$overview = $call('staffOverview', $target); $checksByKey = array_column($overview['quality'], null, 'key');
$ok($checksByKey['next_step']['missed'] === 1 && $checksByKey['next_step']['insufficient'] === 0
&& str_contains(implode('', $overview['coverage_notes']), '1 项证据不足'), 'unattributable insufficient coverage is reported separately and replaces older personal claims');
Db::name('assistant_service_job')->where('id', $newJob['id'])->update(['result_json' => json_encode($result)]);
$call('reviewQuality', ['job_id' => $batch['jobs'][1]['id'], 'item_key' => 'next_step', 'decision' => 'not_applicable', 'note' => '不适用', 'version' => 1]);
$ok($call('staffIssues', $target)['count'] === 0, 'human not-applicable excludes the outstanding issue');
$adopt = ['job_id' => $newJob['id'], 'action_key' => 'confirm_slot', 'version' => 1, 'due_at' => $now + 3600];
$action = $call('adoptAction', $adopt);
$actionRow = Db::name('assistant_service_action')->where('id', $action['id'])->find();
$todo = Db::name('tcm_diagnosis_todo')->where('id', $action['todo_id'])->find();
$ok((int) $actionRow['assignee_id'] === 11 && (int) $todo['creator_id'] === 13, 'manager adopts to target while reminder creator preserves real operator');
$ok($call('actions', ['assistant_id' => 11])['count'] === 1 && $call('actions', ['assistant_id' => 15])['count'] === 0, 'cross-patient execution is assignee-filtered');
Db::name('assistant_service_action')->where('id', $action['id'])->update(['due_at' => $now - 1]);
$overview = $call('staffOverview', $target);
$ok($overview['metrics']['pending_actions'] === 1 && $overview['metrics']['overdue_actions'] === 1, 'pending and overdue current stock');
$call('completeAction', ['id' => $action['id'], 'state' => 'completed', 'note' => '已核对'], 11);
$overview = $call('staffOverview', $target);
$ok($overview['metrics']['pending_actions'] === 0 && $overview['metrics']['completed_actions'] === 1, 'completed period separate from notification state');
Db::name('assistant_service_action')->where('id', $action['id'])->update(['completed_at' => $now - 40 * 86400]);
$ok($call('staffOverview', $target)['metrics']['completed_actions'] === 0, 'completed outside selected period excluded');
Db::name('system_role_menu')->where('role_id', 3)->where('menu_id', 7)->delete();
Db::name('admin_role')->where('admin_id', 13)->where('role_id', 2)->delete();
$deny(fn () => $call('adoptAction', $adopt), 'manager reassignment requires review privilege even on replay');
Db::name('system_role_menu')->insert(['role_id' => 3, 'menu_id' => 7]);
// 上述权限变动会使历史 scope_hash 失效;另建新任务验证转派不改变历史员工归因。
$fresh = $call('analyze', $target + ['diagnosis_id' => 101, 'scenario' => 'revisit']); $worker->runOnce($generator);
Db::name('tcm_diagnosis')->where('id', 101)->update(['assistant_id' => 15]);
$ok($call('job', ['id' => $fresh['id']])['status'] === 'ready', 'same-team transfer preserves target historical attribution and valid context');
$overview = $call('staffOverview', $target);
$ok($overview['metrics']['assigned_cases'] === 1 && $overview['metrics']['im_messages'] === 1, 'transfer changes assignment stock but not historical speaking metric');
$deny(fn () => $call('adoptAction', array_replace($adopt, ['job_id' => $fresh['id']])), 'historical target without current patient access cannot receive new assignment');
$call('reviewQuality', ['job_id' => $fresh['id'], 'item_key' => 'next_step', 'decision' => 'confirmed', 'note' => '历史核查', 'version' => 1]);
$ok($call('staffIssues', $target)['lists'][0]['decision'] === 'confirmed', 'historical issue remains reviewable after within-team transfer');
Db::name('tcm_im_chat_message')->where('id', 2)->update(['text' => '原文变更']);
$ok($call('staffOverview', $target)['metrics']['analyzed_cases'] === 0 && $call('staffIssues', $target)['count'] === 0, 'stale source excluded from report and issues');
$revoked = $call('analyze', $target + ['diagnosis_id' => 101, 'scenario' => 'followup']);
Db::name('admin_dept')->where('admin_id', 11)->update(['dept_id' => 20]);
$beforeCalls = $calls; $worker->runOnce($generator);
$ok(Db::name('assistant_service_job')->where('id', $revoked['id'])->value('status') === 'stale' && $calls === $beforeCalls, 'worker rejects target moved outside operator employee domain before generation');
$deny(fn () => $call('job', ['id' => $fresh['id']]), 'job read rechecks target staff domain');
$deny(fn () => $call('actions', ['assistant_id' => 11]), 'actions recheck target staff domain');
Db::name('admin_dept')->where('admin_id', 11)->update(['dept_id' => 10]);
$during = $call('analyze', $target + ['diagnosis_id' => 101, 'scenario' => 'initial']);
$worker->runOnce(static function (...$args) use ($generator): array {
$answer = $generator(...$args);
Db::name('admin')->where('id', 11)->update(['disable' => 1]);
return $answer;
});
$ok(Db::name('assistant_service_job')->where('id', $during['id'])->value('status') === 'stale', 'real worker rechecks target status after generation before result commit');
Db::name('admin')->where('id', 11)->update(['disable' => 1]);
$ok(!in_array(11, array_column($call('staff')['lists'], 'id'), true), 'disabled assistant immediately disappears');
$deny(fn () => $call('context', $target + ['diagnosis_id' => 101]), 'disabled target rejected independently of manager permission');
Db::name('admin')->where('id', 11)->update(['disable' => 0]);
Db::name('system_role')->where('id', 2)->update(['delete_time' => 1]);
$deny(fn () => $call('staffOverview', $target), 'deleted target role immediately rejected');
Db::name('system_role')->where('id', 2)->update(['delete_time' => null]);
Db::name('tcm_diagnosis')->where('id', 101)->update(['assistant_id' => 11]);
Db::execute('DROP TABLE test_tcm_im_chat_message');
$withoutIm = $call('staffOverview', $target);
$ok($withoutIm['metrics']['im_messages'] === null && $withoutIm['metrics']['assigned_cases'] > 0
&& str_contains(implode('', $withoutIm['coverage_notes']), 'IM 来源不可用'), 'missing IM keeps overview available without reporting false zero');
$withoutImCases = $call('staffCases', $target);
$ok($withoutImCases['count'] > 0 && $withoutImCases['lists'][0]['im_messages'] === null, 'missing IM keeps current and manual cases available');
Db::execute('CREATE TABLE test_tcm_im_chat_message (id INTEGER PRIMARY KEY,patient_id INTEGER,msg_type TEXT,msg_time INTEGER,to_account TEXT,text TEXT)');
$ok($call('staffOverview', $target)['metrics']['im_messages'] === null, 'missing IM account field is explicitly unavailable');
Db::execute('ALTER TABLE test_tcm_im_chat_message ADD COLUMN from_account TEXT');
$ok($call('staffOverview', $target)['metrics']['im_messages'] === 0, 'valid empty IM archive is a real zero');
echo 'ASSISTANT_SERVICE_STAFF assertions=' . $checks . ' PASS sqlite=memory real_access_context_worker=1 network=0' . PHP_EOL;
@@ -0,0 +1,170 @@
<?php
declare(strict_types=1);
// 真实 ORM 与权限/业务代码,临时 SQLite;不初始化应用、不读 .env、不联网。
require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
use app\adminapi\logic\tcm\AssistantServiceLogic as Logic;
use app\adminapi\validate\tcm\AssistantServiceValidate as Validate;
use app\common\service\assistantservice\AssistantServiceAccess as Access;
use app\common\service\assistantservice\AssistantServiceContext as Context;
use think\Container;
use think\facade\Db;
if (!in_array('sqlite', PDO::getAvailableDrivers(), true)) {
throw new RuntimeException('Run: php -d extension=php_pdo_sqlite.dll tests/AssistantServiceApiTest.php');
}
new think\App();
set_exception_handler(static function (Throwable $e): void {
fwrite(STDERR, $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL); exit(1);
});
$manager = new think\DbManager();
$manager->setConfig(['default' => 'isolated', 'connections' => ['isolated' => [
'type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'test_', 'fields_strict' => true,
]]]);
Container::getInstance()->instance('think\DbManager', $manager);
think\Model::setDb($manager);
$config = new think\Config();
$config->set(['enabled' => true, 'profile' => 'qwen', 'timeout' => 120, 'daily_job_limit' => 100,
'max_source_rows' => 200, 'max_source_chars' => 30000, 'max_manual_chars' => 10000, 'max_knowledge_rows' => 40], 'assistant_service');
$config->set(['enable' => true, 'base_url' => 'https://example.invalid', 'models' => [
'qwen' => ['name' => 'synthetic', 'api_key' => 'synthetic-no-network']]], 'prescription_ai');
$config->set(['data_scope' => ['enabled' => true, 'no_dept_fallback_self' => true]], 'project');
Container::getInstance()->instance('config', $config);
$tables = [
'admin' => 'id INTEGER PRIMARY KEY,name TEXT,root INTEGER DEFAULT 0,disable INTEGER DEFAULT 0,delete_time INTEGER NULL',
'admin_role' => 'admin_id INTEGER,role_id INTEGER',
'admin_dept' => 'admin_id INTEGER,dept_id INTEGER',
'dept' => 'id INTEGER PRIMARY KEY,pid INTEGER,status INTEGER DEFAULT 1,delete_time INTEGER NULL',
'system_role' => 'id INTEGER PRIMARY KEY,name TEXT,data_scope INTEGER,delete_time INTEGER NULL',
'system_role_menu' => 'role_id INTEGER,menu_id INTEGER',
'system_menu' => 'id INTEGER PRIMARY KEY,perms TEXT,is_disable INTEGER DEFAULT 0',
'doctor_appointment' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,doctor_id INTEGER,status INTEGER',
'tcm_diagnosis' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,assistant_id INTEGER,patient_name TEXT,phone TEXT,status INTEGER DEFAULT 1,delete_time INTEGER NULL',
'tracking_note' => 'id INTEGER PRIMARY KEY,diagnosis_id INTEGER,admin_id INTEGER,note_date TEXT,content TEXT,create_time INTEGER,update_time INTEGER,delete_time INTEGER NULL',
'tcm_im_chat_message' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,diagnosis_id INTEGER,from_account TEXT,to_account TEXT,doctor_peer_account TEXT,msg_type TEXT,text TEXT,msg_time INTEGER',
'tcm_diagnosis_todo' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,patient_id INTEGER,content TEXT,remind_time INTEGER,status INTEGER,creator_id INTEGER,creator_name TEXT,create_time INTEGER,update_time INTEGER,notified_at INTEGER DEFAULT 0,cancelled_at INTEGER DEFAULT 0,cancelled_by INTEGER DEFAULT 0,delete_time INTEGER NULL',
'assistant_service_record' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,patient_id INTEGER,actor_id INTEGER,content TEXT,record_type TEXT,speaker_confirmed INTEGER,occurred_at INTEGER,created_at INTEGER,delete_time INTEGER NULL',
'assistant_service_job' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,patient_id INTEGER,actor_id INTEGER,type TEXT,scenario TEXT,days INTEGER,status TEXT,version INTEGER,dedupe_key TEXT UNIQUE,source_hash TEXT,scope_hash TEXT,payload_json TEXT,result_json TEXT,claim_token TEXT DEFAULT "",lease_until INTEGER DEFAULT 0,error_code TEXT DEFAULT "",error_message TEXT DEFAULT "",upstream_id TEXT DEFAULT "",created_at INTEGER,updated_at INTEGER,finished_at INTEGER DEFAULT 0',
'assistant_service_review' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,job_id INTEGER,item_key TEXT,reviewer_id INTEGER,decision TEXT,note TEXT,created_at INTEGER',
'assistant_service_action' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,job_id INTEGER,action_key TEXT,todo_id INTEGER,assignee_id INTEGER,content TEXT,due_at INTEGER,business_state TEXT,completion_note TEXT DEFAULT "",completed_at INTEGER DEFAULT 0,created_at INTEGER,updated_at INTEGER,UNIQUE(job_id,action_key)',
'assistant_service_knowledge' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,question TEXT,answer TEXT,category TEXT,source_note TEXT,status TEXT,version INTEGER,created_by INTEGER,published_by INTEGER,created_at INTEGER,updated_at INTEGER',
];
foreach ($tables as $name => $schema) { Db::execute('CREATE TABLE test_' . $name . ' (' . $schema . ')'); }
Db::name('admin')->insertAll([
['id' => 1, 'name' => 'root', 'root' => 1], ['id' => 11, 'name' => 'assistant', 'root' => 0],
['id' => 12, 'name' => 'other', 'root' => 0], ['id' => 13, 'name' => 'team', 'root' => 0], ['id' => 14, 'name' => 'doctor', 'root' => 0],
]);
Db::name('system_role')->insertAll([
['id' => 1, 'name' => '医生', 'data_scope' => 1], ['id' => 2, 'name' => '医助', 'data_scope' => 4], ['id' => 3, 'name' => '经理', 'data_scope' => 3],
]);
Db::name('admin_role')->insertAll([['admin_id' => 11, 'role_id' => 2], ['admin_id' => 12, 'role_id' => 2], ['admin_id' => 13, 'role_id' => 3], ['admin_id' => 14, 'role_id' => 1]]);
Db::name('dept')->insertAll([['id' => 10, 'pid' => 0], ['id' => 20, 'pid' => 0]]);
Db::name('admin_dept')->insertAll([['admin_id' => 11, 'dept_id' => 10], ['admin_id' => 12, 'dept_id' => 20], ['admin_id' => 13, 'dept_id' => 10]]);
foreach (Access::PERMISSIONS as $i => $permission) {
Db::name('system_menu')->insert(['id' => $i + 1, 'perms' => 'tcm.assistantService/' . $permission]);
foreach ([1, 2, 3] as $role) { Db::name('system_role_menu')->insert(['role_id' => $role, 'menu_id' => $i + 1]); }
}
Db::name('tcm_diagnosis')->insertAll([
['id' => 101, 'patient_id' => 201, 'assistant_id' => 11, 'patient_name' => '合成甲', 'phone' => '13800138000'],
['id' => 102, 'patient_id' => 202, 'assistant_id' => 12, 'patient_name' => '合成乙', 'phone' => '13900139000'],
['id' => 103, 'patient_id' => 0, 'assistant_id' => 11, 'patient_name' => '未映射', 'phone' => ''],
]);
Db::name('doctor_appointment')->insert(['id' => 1, 'patient_id' => 101, 'doctor_id' => 14, 'status' => 1]);
$now = time();
Db::name('tracking_note')->insert(['id' => 1, 'diagnosis_id' => 101, 'admin_id' => 11,
'note_date' => date('Y-m-d'), 'content' => '患者要求周六确认预约', 'create_time' => $now, 'update_time' => $now]);
foreach ([
[1, 201, 'patient_201', 'doctor_11', 'text', '请帮我核对预约,电话13800138000'],
[2, 201, 'doctor_11', 'patient_201', 'text', '我将在明天回复可预约时段'],
[3, 201, 'doctor_12', 'patient_201', 'text', '其他部门私有沟通'],
[4, 201, 'doctor_11', 'patient_999', 'text', '错误患者映射'],
[5, 201, 'doctor_11', 'patient_201', 'image', '不可读图片'],
[6, 201, 'doctor_999', 'patient_201', 'text', '不存在的员工'],
] as [$id, $patient, $from, $to, $type, $text]) {
Db::name('tcm_im_chat_message')->insert(['id' => $id, 'patient_id' => $patient, 'diagnosis_id' => 999,
'from_account' => $from, 'to_account' => $to, 'doctor_peer_account' => 'doctor_11', 'msg_type' => $type, 'text' => $text, 'msg_time' => $now - 100]);
}
// 与 API 测试使用相同合成表;新增目标链路必须走真实 Access/Context/Worker,不能用上下文桩替代。
$checks = 0;
$ok = static function (bool $condition, string $label) use (&$checks): void { if (!$condition) { throw new RuntimeException($label); } $checks++; };
$deny = static function (callable $call, string $label) use ($ok): void {
try { $call(); } catch (DomainException $e) { $ok(true, $label); return; } $ok(false, $label);
};
$call = static fn (string $action, array $p = [], int $actor = 13): array => Logic::$action(Validate::parameters($action, $p), $actor);
// 仅反射调用调度器的只读候选/去重方法;不运行 tick,不写 runtime,不访问模型。
$automation = new \app\common\service\assistantservice\AssistantServiceAutomation(__DIR__ . '/unused-coverage-runtime');
$candidates = new ReflectionMethod($automation, 'candidates');
$decision = new ReflectionMethod($automation, 'analysisDecision');
$candidateIds = static function (string $channel) use ($automation, $candidates, $now): array {
$rows = $candidates->invoke($automation, $channel, 13, Access::actor(13), [11], [0, 0], 20, $now);
$ids = array_values(array_unique(array_map('intval', array_column($rows, 'diagnosis_id')))); sort($ids); return $ids;
};
$nextDecision = static fn (int $diagnosis): string => $decision->invoke($automation, Context::build($diagnosis, 13, 30, 11), 11);
$team = static fn (): array => $call('teamOverview')['lists'][0];
$complete = static function (int $diagnosis) use ($now): array {
$job = Logic::analyzeAutomatic(['assistant_id' => 11, 'diagnosis_id' => $diagnosis, 'days' => 30, 'scenario' => 'followup'], 13);
$result = ['summary' => [], 'needs' => [], 'unresolved' => [], 'tags' => [], 'suggested_actions' => [], 'quality_checks' => []];
Db::name('assistant_service_job')->where('id', $job['id'])->update(['status' => 'ready', 'result_json' => json_encode($result), 'finished_at' => $now, 'updated_at' => $now]);
return Db::name('assistant_service_job')->where('id', $job['id'])->find();
};
Db::name('tracking_note')->delete(true);
Db::name('tcm_im_chat_message')->delete(true);
Db::name('tcm_im_chat_message')->insertAll([
['id' => 1, 'patient_id' => 201, 'diagnosis_id' => 101, 'from_account' => 'patient_201', 'to_account' => 'doctor_11', 'msg_type' => 'text', 'text' => '请确认预约', 'msg_time' => $now - 1000],
['id' => 2, 'patient_id' => 201, 'diagnosis_id' => 101, 'from_account' => 'doctor_11', 'to_account' => 'patient_201', 'msg_type' => 'text', 'text' => '我会核实可用时段', 'msg_time' => $now - 900],
]);
Db::name('tcm_diagnosis')->insert(['id' => 104, 'patient_id' => 201, 'assistant_id' => 11, 'patient_name' => '同患者第二诊单', 'phone' => '']);
$ok($candidateIds('im') === [104] && $nextDecision(104) === 'new', 'IM candidates select one latest visible diagnosis for the patient');
$ok($team()['analysis_state'] === 'pending' && $team()['metrics']['im_messages'] === 1, 'first multiple diagnoses represent one pending conversation');
$first = $complete(104);
$ok($nextDecision(104) === 'existing', 'completed snapshot is not generated again');
$ok($team()['analysis_state'] === 'ready' && $team()['metrics']['analyzed_cases'] === 1, 'one completed IM analysis covers all duplicate patient diagnoses');
$ok((int) Db::name('assistant_service_job')->count() === 1, 'no task was created for the older diagnosis');
Db::name('tcm_diagnosis')->insert(['id' => 106, 'patient_id' => 201, 'assistant_id' => 11, 'patient_name' => '同患者新建诊单', 'phone' => '']);
$ok($candidateIds('im') === [106] && $nextDecision(106) === 'existing', 'new diagnosis remaps candidate but patient-level snapshot prevents duplicate generation');
$ok($team()['analysis_state'] === 'ready' && $team()['metrics']['analyzed_cases'] === 1, 'new diagnosis alone does not manufacture pending analysis');
$ok((int) Db::name('assistant_service_job')->count() === 1, 'new diagnosis overview stays read-only');
Db::name('tcm_im_chat_message')->insert(['id' => 3, 'patient_id' => 201, 'diagnosis_id' => 101, 'from_account' => 'doctor_11', 'to_account' => 'patient_201',
'msg_type' => 'text', 'text' => '周六下午可以预约', 'msg_time' => $now - 500]);
$ok($candidateIds('im') === [106] && $nextDecision(106) === 'new', 'new conversation goes to latest diagnosis regardless of archival diagnosis hint');
$pending = $team();
$ok($pending['analysis_state'] === 'pending' && $pending['metrics']['analyzed_cases'] === 0 && $pending['attention_jobs'] === 0, 'new text remains pending and cannot be hidden by an obsolete successful snapshot');
$fresh = $complete(106); $freshSources = json_decode($fresh['payload_json'], true)['context']['sources'];
$ok(array_column($freshSources, 'id') === ['im:1', 'im:2', 'im:3'] && (int) $fresh['diagnosis_id'] === 106 && (int) $fresh['patient_id'] === 201,
'new analysis snapshot binds all current conversation evidence to correct patient and current diagnosis');
$ok($team()['analysis_state'] === 'ready' && $team()['metrics']['analyzed_cases'] === 1 && $nextDecision(106) === 'existing', 'new conversation completion returns ready without regenerating old diagnoses');
$manualId = (int) Db::name('assistant_service_record')->insertGetId(['diagnosis_id' => 101, 'patient_id' => 201, 'actor_id' => 11, 'content' => '旧诊单独立服务登记',
'record_type' => 'service_note', 'speaker_confirmed' => 0, 'occurred_at' => $now - 400, 'created_at' => $now - 400]);
$ok($candidateIds('manual') === [101] && $nextDecision(101) === 'new', 'independent manual source keeps its original diagnosis candidate');
$ok($team()['analysis_state'] === 'pending' && $team()['metrics']['manual_records'] === 1, 'patient IM coverage never hides unprocessed manual evidence on another diagnosis');
$manualJob = $complete(101); $manualSources = json_decode($manualJob['payload_json'], true)['context']['sources'];
$ok(in_array('manual:' . $manualId, array_column($manualSources, 'id'), true) && (int) $manualJob['diagnosis_id'] === 101, 'manual analysis preserves exact record and diagnosis binding');
$ok($team()['analysis_state'] === 'ready' && $team()['metrics']['analyzed_cases'] === 2, 'manual completion resolves its own coverage independently');
Db::name('tracking_note')->insert(['id' => 9, 'diagnosis_id' => 104, 'admin_id' => 11, 'note_date' => date('Y-m-d'),
'content' => '另一旧诊单独立跟踪备注', 'create_time' => $now - 400, 'update_time' => $now - 400]);
$ok($candidateIds('tracking') === [104] && $nextDecision(104) === 'new', 'independent tracking note keeps its original diagnosis candidate');
$ok($team()['analysis_state'] === 'pending', 'fresh IM and manual results cannot cover a different diagnosis tracking note');
$trackingJob = $complete(104); $trackingSources = json_decode($trackingJob['payload_json'], true)['context']['sources'];
$ok(in_array('tracking:9', array_column($trackingSources, 'id'), true) && !in_array('manual:' . $manualId, array_column($trackingSources, 'id'), true),
'tracking snapshot includes its exact bound note and excludes other diagnosis manual record');
$ok($team()['analysis_state'] === 'ready' && $team()['metrics']['analyzed_cases'] === 3, 'all actual eligible source groups complete without phantom pending');
$ok((int) Db::name('assistant_service_job')->count() === 4 && $nextDecision(106) === 'existing', 'only new IM or independent diagnosis sources produced the four explicit test tasks');
Db::name('assistant_service_record')->insert(['diagnosis_id' => 101, 'patient_id' => 999, 'actor_id' => 11, 'content' => '换绑患者记录不可使用',
'record_type' => 'service_note', 'speaker_confirmed' => 0, 'occurred_at' => $now - 300, 'created_at' => $now - 300]);
$ok($team()['analysis_state'] === 'ready' && $team()['metrics']['manual_records'] === 1, 'mismatched patient binding cannot manufacture pending sources');
Db::name('system_role_menu')->where('role_id', 3)->where('menu_id', 3)->delete();
$staleScope = $team();
$ok($staleScope['analysis_state'] === 'attention' && $staleScope['attention_jobs'] === 3, 'unchanged source with changed authorization still requires attention rather than promising automatic generation');
$ok((int) Db::name('assistant_service_job')->count() === 4, 'all team queries and scheduler checks stayed read-only');
echo 'ASSISTANT_SERVICE_TEAM_COVERAGE assertions=' . $checks . ' PASS sqlite=memory real_access_context_logic_scheduler=1 network=0' . PHP_EOL;
+338
View File
@@ -0,0 +1,338 @@
<?php
declare(strict_types=1);
// 真实 ORM 与权限/业务代码,临时 SQLite;不初始化应用、不读 .env、不联网。
require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
use app\adminapi\logic\tcm\AssistantServiceLogic as Logic;
use app\adminapi\validate\tcm\AssistantServiceValidate as Validate;
use app\common\service\assistantservice\AssistantServiceAccess as Access;
use app\common\service\assistantservice\AssistantServiceContext as Context;
use think\Container;
use think\facade\Db;
if (!in_array('sqlite', PDO::getAvailableDrivers(), true)) {
throw new RuntimeException('Run: php -d extension=php_pdo_sqlite.dll tests/AssistantServiceApiTest.php');
}
$testRoot = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'assistant-team-' . bin2hex(random_bytes(8));
new think\App($testRoot);
register_shutdown_function(static function () use ($testRoot): void {
$directory = $testRoot . DIRECTORY_SEPARATOR . 'runtime' . DIRECTORY_SEPARATOR . 'assistant_service_daily_contact';
foreach (['scan.json', 'scan.lock'] as $name) { if (is_file($directory . DIRECTORY_SEPARATOR . $name)) { unlink($directory . DIRECTORY_SEPARATOR . $name); } }
foreach ([$directory, $testRoot . DIRECTORY_SEPARATOR . 'runtime', $testRoot] as $path) { if (is_dir($path)) { rmdir($path); } }
});
set_exception_handler(static function (Throwable $e): void {
fwrite(STDERR, $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL); exit(1);
});
$manager = new think\DbManager();
$manager->setConfig(['default' => 'isolated', 'connections' => ['isolated' => [
'type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'test_', 'fields_strict' => true,
]]]);
Container::getInstance()->instance('think\DbManager', $manager);
think\Model::setDb($manager);
$config = new think\Config();
$config->set(['enabled' => true, 'profile' => 'qwen', 'timeout' => 120, 'daily_job_limit' => 100,
'max_source_rows' => 200, 'max_source_chars' => 30000, 'max_manual_chars' => 10000, 'max_knowledge_rows' => 40], 'assistant_service');
$config->set(['enable' => true, 'base_url' => 'https://example.invalid', 'models' => [
'qwen' => ['name' => 'synthetic', 'api_key' => 'synthetic-no-network']]], 'prescription_ai');
$config->set(['data_scope' => ['enabled' => true, 'no_dept_fallback_self' => true]], 'project');
Container::getInstance()->instance('config', $config);
$tables = [
'admin' => 'id INTEGER PRIMARY KEY,name TEXT,root INTEGER DEFAULT 0,disable INTEGER DEFAULT 0,delete_time INTEGER NULL',
'admin_role' => 'admin_id INTEGER,role_id INTEGER',
'admin_dept' => 'admin_id INTEGER,dept_id INTEGER',
'dept' => 'id INTEGER PRIMARY KEY,pid INTEGER,status INTEGER DEFAULT 1,delete_time INTEGER NULL',
'system_role' => 'id INTEGER PRIMARY KEY,name TEXT,data_scope INTEGER,delete_time INTEGER NULL',
'system_role_menu' => 'role_id INTEGER,menu_id INTEGER',
'system_menu' => 'id INTEGER PRIMARY KEY,perms TEXT,is_disable INTEGER DEFAULT 0',
'doctor_appointment' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,doctor_id INTEGER,status INTEGER',
'tcm_diagnosis' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,assistant_id INTEGER,patient_name TEXT,phone TEXT,status INTEGER DEFAULT 1,delete_time INTEGER NULL',
'tracking_note' => 'id INTEGER PRIMARY KEY,diagnosis_id INTEGER,admin_id INTEGER,note_date TEXT,content TEXT,create_time INTEGER,update_time INTEGER,delete_time INTEGER NULL',
'tcm_im_chat_message' => 'id INTEGER PRIMARY KEY,patient_id INTEGER,diagnosis_id INTEGER,from_account TEXT,to_account TEXT,doctor_peer_account TEXT,msg_type TEXT,text TEXT,msg_time INTEGER',
'tcm_diagnosis_todo' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,patient_id INTEGER,content TEXT,remind_time INTEGER,status INTEGER,creator_id INTEGER,creator_name TEXT,create_time INTEGER,update_time INTEGER,notified_at INTEGER DEFAULT 0,cancelled_at INTEGER DEFAULT 0,cancelled_by INTEGER DEFAULT 0,delete_time INTEGER NULL',
'assistant_service_record' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,patient_id INTEGER,actor_id INTEGER,content TEXT,record_type TEXT,speaker_confirmed INTEGER,occurred_at INTEGER,created_at INTEGER,delete_time INTEGER NULL',
'assistant_service_job' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,patient_id INTEGER,actor_id INTEGER,type TEXT,scenario TEXT,days INTEGER,status TEXT,version INTEGER,dedupe_key TEXT UNIQUE,source_hash TEXT,scope_hash TEXT,payload_json TEXT,result_json TEXT,claim_token TEXT DEFAULT "",lease_until INTEGER DEFAULT 0,error_code TEXT DEFAULT "",error_message TEXT DEFAULT "",upstream_id TEXT DEFAULT "",created_at INTEGER,updated_at INTEGER,finished_at INTEGER DEFAULT 0',
'assistant_service_review' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,job_id INTEGER,item_key TEXT,reviewer_id INTEGER,decision TEXT,note TEXT,created_at INTEGER',
'assistant_service_action' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,job_id INTEGER,action_key TEXT,todo_id INTEGER,assignee_id INTEGER,content TEXT,due_at INTEGER,business_state TEXT,completion_note TEXT DEFAULT "",completed_at INTEGER DEFAULT 0,created_at INTEGER,updated_at INTEGER,UNIQUE(job_id,action_key)',
'assistant_service_knowledge' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,question TEXT,answer TEXT,category TEXT,source_note TEXT,status TEXT,version INTEGER,created_by INTEGER,published_by INTEGER,created_at INTEGER,updated_at INTEGER',
];
foreach ($tables as $name => $schema) { Db::execute('CREATE TABLE test_' . $name . ' (' . $schema . ')'); }
Db::name('admin')->insertAll([
['id' => 1, 'name' => 'root', 'root' => 1], ['id' => 11, 'name' => 'assistant', 'root' => 0],
['id' => 12, 'name' => 'other', 'root' => 0], ['id' => 13, 'name' => 'team', 'root' => 0], ['id' => 14, 'name' => 'doctor', 'root' => 0],
]);
Db::name('system_role')->insertAll([
['id' => 1, 'name' => '医生', 'data_scope' => 1], ['id' => 2, 'name' => '医助', 'data_scope' => 4], ['id' => 3, 'name' => '经理', 'data_scope' => 3],
]);
Db::name('admin_role')->insertAll([['admin_id' => 11, 'role_id' => 2], ['admin_id' => 12, 'role_id' => 2], ['admin_id' => 13, 'role_id' => 3], ['admin_id' => 14, 'role_id' => 1]]);
Db::name('dept')->insertAll([['id' => 10, 'pid' => 0], ['id' => 20, 'pid' => 0]]);
Db::name('admin_dept')->insertAll([['admin_id' => 11, 'dept_id' => 10], ['admin_id' => 12, 'dept_id' => 20], ['admin_id' => 13, 'dept_id' => 10]]);
foreach (Access::PERMISSIONS as $i => $permission) {
Db::name('system_menu')->insert(['id' => $i + 1, 'perms' => 'tcm.assistantService/' . $permission]);
foreach ([1, 2, 3] as $role) { Db::name('system_role_menu')->insert(['role_id' => $role, 'menu_id' => $i + 1]); }
}
Db::name('tcm_diagnosis')->insertAll([
['id' => 101, 'patient_id' => 201, 'assistant_id' => 11, 'patient_name' => '合成甲', 'phone' => '13800138000'],
['id' => 102, 'patient_id' => 202, 'assistant_id' => 12, 'patient_name' => '合成乙', 'phone' => '13900139000'],
['id' => 103, 'patient_id' => 0, 'assistant_id' => 11, 'patient_name' => '未映射', 'phone' => ''],
]);
Db::name('doctor_appointment')->insert(['id' => 1, 'patient_id' => 101, 'doctor_id' => 14, 'status' => 1]);
$now = time();
Db::name('tracking_note')->insert(['id' => 1, 'diagnosis_id' => 101, 'admin_id' => 11,
'note_date' => date('Y-m-d'), 'content' => '患者要求周六确认预约', 'create_time' => $now, 'update_time' => $now]);
foreach ([
[1, 201, 'patient_201', 'doctor_11', 'text', '请帮我核对预约,电话13800138000'],
[2, 201, 'doctor_11', 'patient_201', 'text', '我将在明天回复可预约时段'],
[3, 201, 'doctor_12', 'patient_201', 'text', '其他部门私有沟通'],
[4, 201, 'doctor_11', 'patient_999', 'text', '错误患者映射'],
[5, 201, 'doctor_11', 'patient_201', 'image', '不可读图片'],
[6, 201, 'doctor_999', 'patient_201', 'text', '不存在的员工'],
] as [$id, $patient, $from, $to, $type, $text]) {
Db::name('tcm_im_chat_message')->insert(['id' => $id, 'patient_id' => $patient, 'diagnosis_id' => 999,
'from_account' => $from, 'to_account' => $to, 'doctor_peer_account' => 'doctor_11', 'msg_type' => $type, 'text' => $text, 'msg_time' => $now - 100]);
}
// 与 API 测试使用相同合成表;新增目标链路必须走真实 Access/Context/Worker,不能用上下文桩替代。
$checks = 0;
$ok = static function (bool $condition, string $label) use (&$checks): void { if (!$condition) { throw new RuntimeException($label); } $checks++; };
$deny = static function (callable $call, string $label) use ($ok): void {
try { $call(); } catch (DomainException $e) { $ok(true, $label); return; } $ok(false, $label);
};
$call = static fn (string $action, array $p = [], int $actor = 13): array => Logic::$action(Validate::parameters($action, $p), $actor);
$ok(Access::permissionForAction('teamOverview') === 'view' && Access::permissionForAction('analyzeStaff') === 'analyze', 'explicit HTTP action grants');
$deny(fn () => Access::permissionForAction('analyzeAutomatic'), 'automatic enqueue is not an HTTP action');
foreach ([['filter' => 'unknown'], ['keyword' => []], ['page_size' => 51], ['page_no' => 0], ['days' => 7], ['assistant_id' => 11]] as $invalid) {
$deny(fn () => $call('teamOverview', $invalid), 'team parameters reject unrecognized or invalid input');
}
Db::name('admin')->insertAll([
['id' => 15, 'name' => '同组医助', 'root' => 0, 'disable' => 0],
['id' => 16, 'name' => '停用医助', 'root' => 0, 'disable' => 1],
['id' => 17, 'name' => '空白医助', 'root' => 0, 'disable' => 0],
]);
Db::name('admin_role')->insertAll([['admin_id' => 15, 'role_id' => 2], ['admin_id' => 16, 'role_id' => 2], ['admin_id' => 17, 'role_id' => 2]]);
Db::name('admin_dept')->insertAll([['admin_id' => 15, 'dept_id' => 10], ['admin_id' => 16, 'dept_id' => 10], ['admin_id' => 17, 'dept_id' => 10]]);
Db::name('tcm_diagnosis')->insertAll([
['id' => 104, 'patient_id' => 201, 'assistant_id' => 15, 'patient_name' => '同患者另一诊单', 'phone' => ''],
['id' => 105, 'patient_id' => 205, 'assistant_id' => 15, 'patient_name' => '登记患者', 'phone' => ''],
]);
Db::name('assistant_service_record')->insertAll([
['diagnosis_id' => 105, 'patient_id' => 205, 'actor_id' => 15, 'content' => '本人登记', 'record_type' => 'service_note', 'speaker_confirmed' => 0, 'occurred_at' => $now - 60, 'created_at' => $now],
['diagnosis_id' => 105, 'patient_id' => 999, 'actor_id' => 11, 'content' => '患者已换绑', 'record_type' => 'service_note', 'speaker_confirmed' => 0, 'occurred_at' => $now - 60, 'created_at' => $now],
['diagnosis_id' => 102, 'patient_id' => 202, 'actor_id' => 11, 'content' => '跨患者权限域', 'record_type' => 'service_note', 'speaker_confirmed' => 0, 'occurred_at' => $now - 60, 'created_at' => $now],
]);
$overview = $call('teamOverview', ['page_size' => 1]);
$ok($overview['days'] === 30 && $overview['summary']['staff_count'] === 3 && $overview['count'] === 3 && count($overview['lists']) === 1, 'summary and list count are not fabricated from current page');
$ok($overview['summary']['active_staff'] === 2 && $overview['automation']['state'] === 'disabled', 'activity counts true scoped recent sources; disabled automation is explicit');
$ok($overview['daily']['state'] === 'unavailable' && $overview['daily']['timezone'] === 'Asia/Shanghai'
&& $overview['daily_summary']['required'] === null && $overview['daily_summary']['outstanding'] === null,
'legacy schema retains thirty-day overview while daily coverage is explicitly unavailable');
$ok($overview['lists'][0]['today_contact']['state'] === 'unavailable' && $overview['lists'][0]['today_contact']['required'] === null,
'missing daily schema never advertises false-zero per-staff completion');
$ok($call('teamOverview', ['filter' => 'today_done'])['count'] === 0 && $call('teamOverview', ['filter' => 'today_pending'])['count'] === 0,
'unknown daily coverage never matches done or invents pending counts');
$ok($call('teamOverview', ['filter' => 'today_done'])['summary'] === $overview['summary'], 'daily list filtering preserves legacy full-team summary');
$byStaff = static fn (array $overview): array => array_combine(array_column(array_column($overview['lists'], 'staff'), 'id'), $overview['lists']);
$rows = $byStaff($call('teamOverview'));
$staffIds = array_keys($rows); sort($staffIds);
$ok($staffIds === [11, 15, 17], 'team staff scope excludes disabled and other department');
$ok(array_key_first($rows) === 15, 'recent communication appears before older or absent sources');
$ok($rows[11]['metrics']['im_messages'] === 1 && $rows[11]['metrics']['manual_records'] === 0, 'IM dedupes duplicate patient diagnoses and invalid records never leak');
$ok($rows[15]['metrics']['assigned_cases'] === 2 && $rows[15]['metrics']['manual_records'] === 1, 'current assignment and reliable record counts remain separate');
$ok($rows[11]['analysis_state'] === 'pending' && $rows[17]['analysis_state'] === 'no_sources', 'no sources distinguished from awaiting analysis');
$ok($call('teamOverview', ['keyword' => '同组'])['summary']['staff_count'] === 1, 'keyword sets full summary search scope');
$ok($call('teamOverview', [], 11)['summary']['staff_count'] === 1 && $call('teamOverview', [], 14)['count'] === 0, 'ordinary assistant only self; doctor never receives other staff rows');
$ok($call('teamOverview', [], 1)['summary']['staff_count'] === 4, 'root sees eligible assistants without treating itself as one');
Db::name('system_role_menu')->where('role_id', 3)->where('menu_id', 1)->delete();
$deny(fn () => $call('teamOverview'), 'live view permission required');
Db::name('system_role_menu')->insert(['role_id' => 3, 'menu_id' => 1]);
$target = ['assistant_id' => 11, 'diagnosis_id' => 101, 'days' => 30, 'scenario' => 'followup'];
$job = Logic::analyzeAutomatic($target, 13);
$stored = Db::name('assistant_service_job')->where('id', $job['id'])->find();
$ok(json_decode($stored['payload_json'], true)['trigger'] === 'automatic' && (int) $stored['actor_id'] === 13, 'automatic enqueue records trigger and real actor');
$ok(Logic::automationReady(), 'readiness probe uses schema and synthetic configured adapter only');
$deny(fn () => Logic::analyzeAutomatic(array_replace($target, ['days' => 7]), 13), 'automatic window fixed to 30 days');
$deny(fn () => Logic::analyzeAutomatic(array_replace($target, ['assistant_id' => 0]), 13), 'automatic subject must be explicit');
$deny(fn () => Logic::analyzeAutomatic(array_replace($target, ['assistant_id' => 12]), 13), 'automatic subject cannot escape team');
$deny(fn () => Logic::analyzeAutomatic(array_replace($target, ['diagnosis_id' => 102]), 13), 'automatic source cannot escape patient scope');
Db::name('system_role_menu')->where('role_id', 3)->where('menu_id', 2)->delete();
$deny(fn () => Logic::analyzeAutomatic($target, 13), 'automatic never bypasses revoked analyze permission');
Db::name('system_role_menu')->insert(['role_id' => 3, 'menu_id' => 2]);
$queued = $call('teamOverview');
$ok($queued['summary']['queued_jobs'] === 1 && $byStaff($queued)[11]['analysis_state'] === 'queued', 'actual queue shown without GET creating jobs');
$ok(Logic::analyzeAutomatic(array_replace($target, ['scenario' => 'initial']), 13)['id'] === $job['id'], 'active target and diagnosis barrier does not depend on dedupe key');
$ok(Logic::analyzeAutomatic($target, 1)['id'] === $job['id'], 'active barrier also applies to another authorized operator');
foreach (['running', 'needs_reconciliation'] as $state) {
Db::name('assistant_service_job')->where('id', $job['id'])->update(['status' => $state]);
$ok(Logic::analyzeAutomatic(array_replace($target, ['scenario' => 'revisit']), 13)['id'] === $job['id'], 'automatic barrier holds for ' . $state);
$report = $call('teamOverview');
$field = $state === 'running' ? 'running_jobs' : 'attention_jobs';
$ok($report['summary'][$field] === 1, 'visible team counts ' . $state);
}
Db::name('assistant_service_job')->where('id', $job['id'])->update(['status' => 'failed', 'error_code' => 'INTERNAL_ERROR']);
$ok(Logic::analyzeAutomatic($target, 13)['status'] === 'failed', 'automatic never restores previously failed dedupe');
$ok($call('analyze', $target)['status'] === 'queued', 'manual explicit recovery remains compatible');
$quality = [];
foreach (['identity', 'needs', 'explanation', 'next_step', 'followup', 'escalation'] as $key) {
$quality[] = ['key' => $key, 'label' => '合成核查', 'status' => $key === 'next_step' ? 'missed' : 'met',
'reason' => '仅用于测试核查流程', 'evidence_ids' => ['im:2'], 'actor_admin_id' => 11];
}
$result = ['summary' => [], 'needs' => [], 'unresolved' => [], 'tags' => [], 'suggested_actions' => [], 'quality_checks' => $quality];
$ready = static function (int $id, array $result) use ($now): void {
Db::name('assistant_service_job')->where('id', $id)->update(['status' => 'ready', 'result_json' => json_encode($result), 'finished_at' => $now, 'updated_at' => $now]);
};
$ready($job['id'], $result);
$newer = $call('analyze', array_replace($target, ['scenario' => 'initial'])); $ready($newer['id'], $result);
$overview = $call('teamOverview', ['filter' => 'issues', 'page_size' => 1]);
$ok($overview['summary']['analyzed_cases'] === 1 && $overview['summary']['unreviewed_issues'] === 1 && $overview['count'] === 1, 'latest valid quality per diagnosis key prevents duplicate issues');
$ok($overview['summary']['staff_count'] === 3 && $overview['lists'][0]['last_analyzed_at'] === $now, 'filter preserves global search summary and real completion time');
$ok($call('teamOverview', ['page_no' => 4, 'page_size' => 1])['summary'] === $call('teamOverview')['summary']
&& $call('teamOverview', ['page_no' => 4, 'page_size' => 1])['lists'] === [], 'empty later page still reports exact full summary');
$call('reviewQuality', ['job_id' => $newer['id'], 'item_key' => 'next_step', 'decision' => 'confirmed', 'version' => 1]);
$call('reviewQuality', ['job_id' => $newer['id'], 'item_key' => 'next_step', 'decision' => 'dismissed', 'version' => 1]);
$ok($call('teamOverview', ['filter' => 'issues'])['count'] === 0 && $call('teamOverview')['summary']['unreviewed_issues'] === 0, 'latest review wins and never falls back to old missed item');
$insufficient = $result; $insufficient['quality_checks'][3]['status'] = 'insufficient'; $insufficient['quality_checks'][3]['actor_admin_id'] = 0;
$ready($newer['id'], $insufficient);
$ok($call('teamOverview')['summary']['unreviewed_issues'] === 0, 'latest insufficient evidence suppresses older personal attribution');
$ready($newer['id'], $result);
Db::name('assistant_service_action')->insertAll([
['diagnosis_id' => 101, 'job_id' => $newer['id'], 'action_key' => 'pending', 'assignee_id' => 11, 'business_state' => 'pending', 'due_at' => $now - 1, 'completed_at' => 0],
['diagnosis_id' => 101, 'job_id' => $newer['id'], 'action_key' => 'complete', 'assignee_id' => 15, 'business_state' => 'completed', 'due_at' => $now - 1, 'completed_at' => $now],
['diagnosis_id' => 102, 'job_id' => $newer['id'], 'action_key' => 'outside', 'assignee_id' => 11, 'business_state' => 'pending', 'due_at' => $now - 1, 'completed_at' => 0],
['diagnosis_id' => 104, 'job_id' => $newer['id'], 'action_key' => 'mismatch', 'assignee_id' => 11, 'business_state' => 'pending', 'due_at' => $now - 1, 'completed_at' => 0],
]);
$overview = $call('teamOverview', ['filter' => 'overdue']);
$ok($call('teamOverview')['lists'][0]['staff']['id'] === 11, 'pending human attention appears before more recent communication');
$ok($overview['count'] === 1 && $overview['summary']['pending_actions'] === 1 && $overview['summary']['overdue_actions'] === 1, 'actions enforce both patient scope and original diagnosis binding');
$ok($byStaff($call('teamOverview'))[15]['metrics']['completed_actions'] === 1, 'completed period is independent from pending stock');
$ok($call('teamOverview', ['filter' => 'attention'])['count'] === 1, 'attention includes pending human followups');
$ok($call('teamOverview', ['keyword' => '同组', 'filter' => 'overdue'])['summary']['pending_actions'] === 0, 'keyword summary never includes a hidden staff member');
// 其他主管产生的、同一患者上明确属于域外员工的任务,不可借患者可见性混入统计。
$hiddenContext = Context::build(101, 1, 30, 12);
$hiddenJob = Db::name('assistant_service_job')->insertGetId(['diagnosis_id' => 101, 'patient_id' => 201, 'actor_id' => 1,
'type' => 'analysis', 'scenario' => 'followup', 'days' => 30, 'status' => 'queued', 'version' => 1,
'dedupe_key' => 'synthetic-outside-staff', 'source_hash' => $hiddenContext['source_hash'], 'scope_hash' => $hiddenContext['scope_hash'],
'payload_json' => json_encode(['context' => $hiddenContext, 'knowledge' => []]), 'created_at' => $now, 'updated_at' => $now]);
$ok($call('teamOverview')['summary']['queued_jobs'] === 0 && $call('teamOverview', [], 1)['summary']['queued_jobs'] === 1,
'visible patient never permits queue counts for an unauthorized staff subject');
Db::name('assistant_service_job')->where('id', $hiddenJob)->delete();
// 查询监听只计真实 SQL:同一来源快照有许多历史结果时,不应逐任务重读来源正文。
$sourceReads = 0;
$manager->listen(static function (string $sql) use (&$sourceReads): void {
if (preg_match('/^SELECT .*FROM [`"]?test_(assistant_service_record|tracking_note|tcm_im_chat_message)[`"]?/i', $sql)
&& !str_contains(strtoupper($sql), 'GROUP BY') && !str_contains(strtoupper($sql), 'LIMIT 1')
&& !preg_match('/\b1\s*=\s*0\b/', $sql)) { $sourceReads++; }
});
$stored = Db::name('assistant_service_job')->where('id', $newer['id'])->find();
$duplicates = [];
for ($i = 0; $i < 6; $i++) {
$copy = $stored; unset($copy['id']); $copy['dedupe_key'] = 'synthetic-history-' . $i;
$duplicates[] = (int) Db::name('assistant_service_job')->insertGetId($copy);
}
$beforeReads = $sourceReads; $history = $call('teamOverview'); $readCount = $sourceReads - $beforeReads;
$ok($history['summary']['analyzed_cases'] === 1 && $history['summary']['unreviewed_issues'] === 1, 'many history tasks retain one current diagnosis and dimension');
$ok($readCount > 0 && $readCount <= 3, 'request context cache prevents repeated source reads per historical job');
Db::name('assistant_service_job')->whereIn('id', $duplicates)->delete();
Db::name('tcm_im_chat_message')->where('id', 2)->update(['text' => '证据原文修改']);
$stale = $call('teamOverview');
$ok($stale['summary']['analyzed_cases'] === 0 && $stale['summary']['unreviewed_issues'] === 0 && $stale['summary']['attention_jobs'] === 0
&& $byStaff($stale)[11]['analysis_state'] === 'pending', 'changed sources invalidate old quality and await a fresh analysis instead of inventing a failure');
$ok($byStaff($stale)[11]['last_analyzed_at'] === 0, 'old result does not fabricate current analysis coverage');
Db::name('admin_dept')->where('admin_id', 11)->update(['dept_id' => 20]);
$moved = $call('teamOverview');
$ok($moved['summary']['staff_count'] === 2 && $moved['summary']['attention_jobs'] === 0 && $moved['summary']['pending_actions'] === 0, 'staff and patient domain updates remove old team data immediately');
Db::name('admin_dept')->where('admin_id', 11)->update(['dept_id' => 10]);
Db::name('admin')->where('id', 11)->update(['disable' => 1]);
$ok($call('teamOverview')['summary']['staff_count'] === 2, 'disabled target never counted');
Db::name('admin')->where('id', 11)->update(['disable' => 0]);
Db::execute('DROP TABLE test_tcm_im_chat_message');
$ok($byStaff($call('teamOverview'))[11]['metrics']['im_messages'] === null, 'unconnected IM stays unavailable rather than false zero');
Db::execute('CREATE TABLE test_tcm_im_chat_message (id INTEGER PRIMARY KEY,patient_id INTEGER,msg_type TEXT,msg_time INTEGER,to_account TEXT,text TEXT)');
$ok($byStaff($call('teamOverview'))[11]['metrics']['im_messages'] === null, 'missing IM identity column is unavailable');
Db::execute('ALTER TABLE test_tcm_im_chat_message ADD COLUMN from_account TEXT');
$ok($byStaff($call('teamOverview'))[11]['metrics']['im_messages'] === 0, 'valid empty IM archive is zero');
Db::execute('DROP TABLE test_tracking_note');
$ok($call('teamOverview')['summary']['staff_count'] === 3, 'optional tracking source absent does not hide team');
$ok((int) Db::name('assistant_service_job')->count() === 2, 'all dashboard reads stayed read-only');
$config->set(['enabled' => false], 'assistant_service');
$ok(!Logic::automationReady(), 'automation readiness obeys disabled generation');
// 独立临时 runtime 与内存来源表验证真实计划服务贯通 API;AI 保持关闭。
Db::execute('ALTER TABLE test_assistant_service_action ADD COLUMN contact_required INTEGER NOT NULL DEFAULT 0');
Db::execute('ALTER TABLE test_assistant_service_action ADD COLUMN completed_by INTEGER NOT NULL DEFAULT 0');
Db::connect()->getSchemaInfo('test_assistant_service_action', true);
foreach ([
'assistant_service_daily_contact' => 'id INTEGER PRIMARY KEY AUTOINCREMENT,business_date TEXT,assistant_id INTEGER,diagnosis_id INTEGER,patient_id INTEGER,source_type TEXT,source_id INTEGER,source_order_id INTEGER,reason TEXT,due_at INTEGER,state TEXT,exempt_reason TEXT,created_at INTEGER,updated_at INTEGER,UNIQUE(business_date,assistant_id,source_type,source_id,source_order_id)',
'tcm_diagnosis_revisit_due' => 'id INTEGER PRIMARY KEY,diagnosis_id INTEGER,assistant_id INTEGER,source_order_id INTEGER,due_date TEXT,promised_date TEXT,closed_state INTEGER DEFAULT 0,appointment_state INTEGER DEFAULT 0',
'tcm_diagnosis_revisit_due_log' => 'id INTEGER PRIMARY KEY,diagnosis_id INTEGER,assistant_id INTEGER,source_order_id INTEGER,event INTEGER,operator_id INTEGER,create_time INTEGER',
'tcm_prescription_order' => 'id INTEGER PRIMARY KEY,diagnosis_id INTEGER,fulfillment_status INTEGER DEFAULT 1,delete_time INTEGER NULL',
] as $name => $schema) {
Db::execute('CREATE TABLE test_' . $name . ' (' . $schema . ')');
Db::connect()->getSchemaInfo('test_' . $name, true);
}
$now = time(); $day = \app\common\service\assistantservice\AssistantServiceDailyContact::day($now);
$config->set(['daily_contact_enabled' => true, 'daily_contact_actor_id' => 13, 'daily_contact_batch_size' => 100], 'assistant_service');
Db::name('tcm_prescription_order')->insertAll([['id' => 1, 'diagnosis_id' => 101], ['id' => 2, 'diagnosis_id' => 105]]);
Db::name('tcm_diagnosis_revisit_due')->insertAll([
['id' => 1, 'diagnosis_id' => 101, 'assistant_id' => 11, 'source_order_id' => 1, 'due_date' => $day['date']],
['id' => 2, 'diagnosis_id' => 105, 'assistant_id' => 15, 'source_order_id' => 2, 'due_date' => $day['date']],
]);
Db::name('tcm_im_chat_message')->insert(['id' => 31, 'patient_id' => 201, 'from_account' => 'doctor_11', 'to_account' => 'patient_201',
'msg_type' => 'text', 'text' => '今日联系合成记录', 'msg_time' => $now]);
Db::name('tcm_diagnosis')->insert(['id' => 106, 'patient_id' => 206, 'assistant_id' => 15, 'patient_name' => '本人登记合成患者', 'phone' => '']);
$contactJob = Db::name('assistant_service_job')->insertGetId(['diagnosis_id' => 106, 'patient_id' => 206,
'actor_id' => 13, 'type' => 'contact_fixture', 'dedupe_key' => 'daily-contact-api-fixture']);
Db::name('assistant_service_action')->insert(['diagnosis_id' => 106, 'job_id' => $contactJob, 'action_key' => 'daily_contact',
'assignee_id' => 15, 'business_state' => 'completed', 'due_at' => $now, 'completed_at' => $now, 'completed_by' => 15, 'contact_required' => 1]);
$planner = new \app\common\service\assistantservice\AssistantServiceDailyContact();
$scan = $planner->tick();
$ok($scan['state'] === 'ready' && $scan['created'] === 3, 'isolated deterministic scanner prepares three real daily plan sources');
$beforePlans = (int) Db::name('assistant_service_daily_contact')->count();
$beforeJobs = (int) Db::name('assistant_service_job')->count();
$today = $call('teamOverview', ['page_size' => 1]);
$ok($today['daily']['state'] === 'ready' && $today['daily']['business_date'] === $day['date'] && !$config->get('assistant_service.enabled'),
'daily API is ready with server business date while AI remains disabled');
$ok($today['daily_summary'] === ['required' => 3, 'contacted' => 1, 'reported' => 1, 'pending' => 1, 'outstanding' => 2, 'exempt' => 0, 'state' => 'pending'],
'full-team daily counts precede page slicing and keep reported outstanding');
$ok($today['lists'][0]['staff']['id'] === 15 && $today['lists'][0]['today_contact']['outstanding'] === 2,
'today outstanding sorts ahead of older quality action urgency');
$todayPending = $call('teamOverview', ['filter' => 'today_pending']);
$todayDone = $call('teamOverview', ['filter' => 'today_done']);
$ok(array_column(array_column($todayPending['lists'], 'staff'), 'id') === [15]
&& array_column(array_column($todayDone['lists'], 'staff'), 'id') === [11], 'daily filters distinguish outstanding, verified completion and no tasks');
$ok($todayPending['daily_summary'] === $today['daily_summary'] && $todayDone['daily_summary'] === $today['daily_summary']
&& $todayPending['summary'] === $today['summary'], 'daily filters leave both daily and thirty-day full-search summaries intact');
$later = $call('teamOverview', ['page_size' => 1, 'page_no' => 5]);
$ok($later['lists'] === [] && $later['daily_summary'] === $today['daily_summary'] && $later['summary'] === $today['summary'], 'empty page retains both exact summaries');
$keyword = $call('teamOverview', ['keyword' => '同组']);
$ok($keyword['count'] === 1 && $keyword['daily_summary']['required'] === 2 && $keyword['daily_summary']['contacted'] === 0,
'keyword narrows daily summary to matching authorized staff before daily filters');
$pendingPatients = $call('staffDailyContacts', ['assistant_id' => 15]);
$reportedPatients = $call('staffDailyContacts', ['assistant_id' => 15, 'status' => 'reported']);
$allFirst = $call('staffDailyContacts', ['assistant_id' => 15, 'status' => 'all', 'page_size' => 1]);
$allSecond = $call('staffDailyContacts', ['assistant_id' => 15, 'status' => 'all', 'page_size' => 1, 'page_no' => 2]);
$ok($pendingPatients['count'] === 1 && $pendingPatients['lists'][0]['patient_id'] === 205
&& $reportedPatients['count'] === 1 && $reportedPatients['lists'][0]['patient_id'] === 206,
'daily patient route defaults pending and separates self-reported evidence');
$ok($allFirst['count'] === 2 && $allSecond['count'] === 2 && $allFirst['lists'][0]['key'] !== $allSecond['lists'][0]['key']
&& $pendingPatients['summary'] === $reportedPatients['summary'] && $allFirst['summary'] === $pendingPatients['summary'],
'daily patient status filters and pagination never shrink staff summary');
$ok($reportedPatients['lists'][0]['evidence'][0]['type'] === 'action_completed'
&& $call('staffDailyContacts', ['assistant_id' => 11, 'status' => 'contacted'])['lists'][0]['evidence'][0]['type'] === 'im',
'API preserves machine contact versus manual completion evidence types');
$ok($call('staffDailyContacts', ['assistant_id' => 17, 'status' => 'all'])['summary']['state'] === 'no_tasks', 'no-task staff never receives a completed percentage state');
Db::name('tcm_diagnosis_revisit_due')->where('id', 2)->update(['closed_state' => 1]);
$exempt = $call('staffDailyContacts', ['assistant_id' => 15, 'status' => 'exempt']);
$ok($exempt['count'] === 1 && $exempt['summary']['required'] === 1 && $exempt['summary']['exempt'] === 1
&& $exempt['summary']['reported'] === 1, 'daily API immediately separates closed source exemption from verified completion');
$ok((int) Db::name('assistant_service_daily_contact')->count() === $beforePlans
&& (int) Db::name('assistant_service_job')->count() === $beforeJobs, 'all integrated API GET calls remain read-only without additional plans or model jobs');
echo 'ASSISTANT_SERVICE_TEAM assertions=' . $checks . ' PASS sqlite=memory real_access_context_logic=1 network=0' . PHP_EOL;
+145
View File
@@ -0,0 +1,145 @@
<?php
declare(strict_types=1);
namespace app\common\service\assistantservice {
// 用隔离权限/来源适配器驱动真实 worker/ORM,API 权限算法由专门测试覆盖。
final class AssistantServiceAccess {
public static bool $allowed = true;
public static int $patientId = 100;
public static array $calls = [];
public static function diagnosis(int $id, int $admin, string $permission = 'view', bool $lock = false): array {
self::$calls[] = [$id, $admin, $permission, $lock];
if (!self::$allowed || $id !== 1 || $admin !== 11) { throw new \DomainException('synthetic-secret'); }
return ['id' => $id, 'patient_id' => self::$patientId, 'assistant_id' => 11];
}
}
final class AssistantServiceContext {
public static array $context = [];
public static function build(int $id, int $admin, int $days = 30): array { return self::$context; }
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
use app\common\service\assistantservice\AssistantServiceAccess as Access;
use app\common\service\assistantservice\AssistantServiceContext as Context;
use app\common\service\assistantservice\AssistantServiceEngine as Engine;
use app\common\service\assistantservice\AssistantServiceWorker as Worker;
use think\Container;
use think\facade\Db;
if (!in_array('sqlite', PDO::getAvailableDrivers(), true)) {
throw new RuntimeException('SQLite required; Windows: php -d extension=php_pdo_sqlite.dll tests/AssistantServiceWorkerTest.php');
}
new think\App(); // 禁止 initialize,不读环境与业务连接。
$manager = new think\DbManager();
$manager->setConfig(['default' => 'isolated', 'connections' => ['isolated' => [
'type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'test_', 'fields_strict' => true,
]]]);
Container::getInstance()->instance('think\DbManager', $manager);
$config = new think\Config();
$config->set(['enabled' => true, 'timeout' => 120, 'lease_seconds' => 300], 'assistant_service');
Container::getInstance()->instance('config', $config);
Db::execute('CREATE TABLE test_assistant_service_job (id INTEGER PRIMARY KEY AUTOINCREMENT,diagnosis_id INTEGER,patient_id INTEGER,actor_id INTEGER,type TEXT,scenario TEXT,days INTEGER,status TEXT,version INTEGER,dedupe_key TEXT UNIQUE,source_hash TEXT,scope_hash TEXT,payload_json TEXT,result_json TEXT,claim_token TEXT DEFAULT "",lease_until INTEGER DEFAULT 0,error_code TEXT DEFAULT "",error_message TEXT DEFAULT "",upstream_id TEXT DEFAULT "",created_at INTEGER,updated_at INTEGER,finished_at INTEGER DEFAULT 0)');
Db::execute('CREATE TABLE test_assistant_service_knowledge (id INTEGER PRIMARY KEY,question TEXT,answer TEXT,category TEXT,source_note TEXT,status TEXT,version INTEGER)');
$knowledge = [['id' => 7, 'version' => 2, 'question' => '如何预约?', 'answer' => '医助协助核对可预约时段。', 'category' => '预约', 'source_note' => '合成文档']];
Db::name('assistant_service_knowledge')->insert($knowledge[0] + ['status' => 'published']);
$context = ['patient' => ['diagnosis_id' => 1, 'patient_id' => 100, 'assistant_id' => 11],
'source_hash' => hash('sha256', 'synthetic sources'), 'scope_hash' => hash('sha256', 'synthetic scope'),
'sources' => [['id' => 'im:1', 'channel' => 'im', 'text' => '请问能否预约周六?', 'occurred_at' => 1,
'speaker' => 'patient', 'actor_admin_id' => 0, 'quality_eligible' => true]], 'coverage' => [], 'days' => 30];
Context::$context = $context;
$reply = ['reply' => '我会协助核对可预约时段。', 'knowledge_refs' => [['id' => 7, 'version' => 2]],
'evidence_ids' => ['im:1'], 'needs_confirmation' => true, 'reason' => '时间仍需人工核对'];
$checks = 0;
$expect = static function (bool $ok, string $why) use (&$checks): void { if (!$ok) { throw new RuntimeException($why); } $checks++; };
$make = static function (array $changes = []) use ($context, $knowledge): int {
return (int) Db::name('assistant_service_job')->insertGetId(array_replace([
'diagnosis_id' => 1, 'patient_id' => 100, 'actor_id' => 11, 'type' => 'reply', 'scenario' => 'followup', 'days' => 30,
'status' => 'queued', 'version' => 1, 'dedupe_key' => bin2hex(random_bytes(32)),
'source_hash' => $context['source_hash'], 'scope_hash' => $context['scope_hash'],
'payload_json' => json_encode(['context' => $context, 'knowledge' => $knowledge, 'question' => '如何预约?']),
'created_at' => time(), 'updated_at' => time(),
], $changes));
};
$row = static fn (int $id): array => Db::name('assistant_service_job')->where('id', $id)->find();
$calls = 0; $active = 0; $mode = 'success'; $worker = new Worker();
$generator = static function ($type, $scenario, $ctx, $kb, $question) use (&$calls, &$active, &$mode, $reply, $row, $expect, $worker): array {
$calls++;
$claimed = $row($active);
$expect($claimed['status'] === 'running' && strlen($claimed['claim_token']) === 48 && $claimed['lease_until'] > time(), 'durable lease exists before send');
if ($mode === 'revoke') { Access::$allowed = false; }
if ($mode === 'patient') { Access::$patientId = 200; }
if ($mode === 'source') { Context::$context['source_hash'] = hash('sha256', 'changed'); }
if ($mode === 'scope') { Context::$context['scope_hash'] = hash('sha256', 'reassigned'); }
if ($mode === 'knowledge') { Db::name('assistant_service_knowledge')->where('id', 7)->update(['version' => 3]); }
if ($mode === 'withdraw') { Db::name('assistant_service_knowledge')->where('id', 7)->update(['status' => 'disabled']); }
if ($mode === 'body') { Db::name('assistant_service_knowledge')->where('id', 7)->update(['answer' => '未经版本更新的正文']); }
if ($mode === 'newknowledge') { Db::name('assistant_service_knowledge')->insert(['id' => 8, 'question' => '新问题', 'answer' => '新答案', 'category' => '预约', 'source_note' => '合成', 'status' => 'published', 'version' => 1]); }
if ($mode === 'lost') { Db::name('assistant_service_job')->where('id', $active)->update(['claim_token' => str_repeat('b', 48)]); }
if ($mode === 'expired') { Db::name('assistant_service_job')->where('id', $active)->update(['lease_until' => time() - 1]); }
if ($mode === 'second_worker') { $expect(!$worker->runOnce(fn () => throw new RuntimeException('must not send twice')), 'second worker cannot reclaim running job'); }
if ($mode === 'unknown') { return ['ok' => false, 'error_code' => 'UPSTREAM_UNCERTAIN', 'error_message' => 'private-source']; }
if ($mode === 'exception') { throw new RuntimeException('private-source-secret'); }
if ($mode === 'domain_exception') { throw new DomainException('private-source-secret'); }
if ($mode === 'rejected') { return ['ok' => false, 'error_code' => 'UPSTREAM_REJECTED']; }
if ($mode === 'null_result') { return ['ok' => true, 'result' => null]; }
if ($mode === 'invalid') { $reply['evidence_ids'] = ['im:999']; }
// Engine 真实解析和规则复核走合成 transport,绝不发网络请求。
return Engine::generate($type, $scenario, $ctx, $kb, $question,
fn () => ['ok' => true, 'content' => json_encode($reply), 'message_id' => 'synthetic-message']);
};
$active = $make();
$expect($worker->runOnce($generator), 'queued job consumed');
$done = $row($active);
$expect($done['status'] === 'ready' && json_decode($done['result_json'], true)['needs_confirmation'] && $done['claim_token'] === '', 'only validated result persisted');
$expect(count(Access::$calls) === 2 && Access::$calls[0][2] === 'draftReply' && Access::$calls[1][3] === true, 'fresh permission before and within completion transaction');
$expect(!$worker->runOnce($generator) && $calls === 1, 'ready not reissued');
foreach (['revoke', 'patient', 'source', 'scope', 'knowledge', 'withdraw', 'body'] as $mode) {
Access::$allowed = true; Access::$patientId = 100; Context::$context = $context;
Db::name('assistant_service_knowledge')->where('id', 7)->update($knowledge[0] + ['status' => 'published']);
$active = $make(); $worker->runOnce($generator); $done = $row($active);
$expect($done['status'] === 'stale' && $done['result_json'] === null, 'commit rejects changed ' . $mode);
}
Access::$allowed = true; Access::$patientId = 100; Context::$context = $context;
Db::name('assistant_service_knowledge')->where('id', 7)->update($knowledge[0] + ['status' => 'published']);
foreach (['newknowledge' => 'ready', 'second_worker' => 'ready', 'unknown' => 'needs_reconciliation',
'exception' => 'needs_reconciliation', 'domain_exception' => 'needs_reconciliation',
'rejected' => 'failed', 'invalid' => 'failed', 'null_result' => 'failed'] as $mode => $status) {
$active = $make(); $worker->runOnce($generator); $done = $row($active);
$expect($done['status'] === $status, 'terminal classification ' . $mode);
$expect(!str_contains(json_encode($done), 'private-source'), 'exception/upstream details not persisted');
$before = $calls; $expect(!$worker->runOnce($generator) && $calls === $before, 'terminal never blindly retried');
}
foreach (['lost', 'expired'] as $mode) {
$active = $make(); $worker->runOnce($generator); $done = $row($active);
$expect($done['status'] === 'running' && $done['result_json'] === null, 'stale worker cannot persist after ' . $mode);
Db::name('assistant_service_job')->where('id', $active)->update(['lease_until' => time() - 1]);
$before = $calls; $expect(!$worker->runOnce($generator), 'expired running not requeued');
$expect($row($active)['status'] === 'needs_reconciliation' && $calls === $before, 'expired lease fenced without upstream');
}
$mode = 'success'; Access::$allowed = false;
$active = $make(); $before = $calls; $worker->runOnce($generator);
$expect($row($active)['status'] === 'stale' && $calls === $before, 'revoked before send never invokes transport');
Access::$allowed = true;
$active = $make(['diagnosis_id' => 2]); $worker->runOnce($generator);
$expect($row($active)['status'] === 'stale' && $calls === $before, 'cross-patient job rejected before send');
Db::name('assistant_service_knowledge')->where('id', 7)->update(['version' => 4]);
$active = $make(); $worker->runOnce($generator);
$expect($row($active)['status'] === 'stale' && $calls === $before, 'knowledge changed before send');
$active = $make(); $config->set(['enabled' => false], 'assistant_service');
$expect(!$worker->runOnce($generator) && $row($active)['status'] === 'queued', 'disabled queue sends nothing');
$output = new think\console\Output('buffer');
$exit = (new app\command\AssistantServiceWork())->run(new think\console\Input(['--once', '--sleep=3']), $output);
$expect($exit === 0 && str_contains($output->fetch(), 'processed=0'), 'real command once parses and exits while disabled');
Db::execute('DROP TABLE test_assistant_service_job');
$config->set(['enabled' => true], 'assistant_service');
$output = new think\console\Output('buffer');
$exit = (new app\command\AssistantServiceWork())->run(new think\console\Input(['--once']), $output);
$printed = $output->fetch();
$expect($exit === 1 && str_contains($printed, 'storage_or_configuration_error') && !str_contains($printed, 'test_assistant'),
'real command catches missing schema without leaking SQL or names');
echo 'ASSISTANT_SERVICE_WORKER assertions=' . $checks . ' PASS sqlite=memory real_worker_orm=1 network=0' . PHP_EOL;
}