igengx
This commit is contained in:
@@ -10,11 +10,13 @@ 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 app\common\service\assistantservice\WecomArchiveSqlite as Archive;
|
||||
use think\Container;
|
||||
use think\facade\Db;
|
||||
|
||||
if (!in_array('sqlite', PDO::getAvailableDrivers(), true)) { throw new RuntimeException('需要隔离测试 SQLite 扩展'); }
|
||||
new think\App();
|
||||
$temporary = sys_get_temp_dir() . '/assistant-alert-test-' . bin2hex(random_bytes(6));
|
||||
new think\App($temporary);
|
||||
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]]]);
|
||||
@@ -26,7 +28,7 @@ $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' => 'id INTEGER PRIMARY KEY,name TEXT,work_wechat_userid TEXT DEFAULT "",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',
|
||||
@@ -36,7 +38,7 @@ $tables = [
|
||||
'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)',
|
||||
'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 "",archive_tenant_id 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,archive_tenant_id,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],
|
||||
@@ -52,7 +54,6 @@ Db::name('tcm_diagnosis')->insertAll([
|
||||
['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++; };
|
||||
@@ -151,6 +152,7 @@ try {
|
||||
$configure(['alert_enabled' => true, 'alert_batch_size' => 1]);
|
||||
$ok($scanner->tick()['created'] === 1 && $scanner->tick()['state'] === 'waiting', '一批只处理设定条数,下一条等下一轮');
|
||||
$clock += 61;
|
||||
$configure(['alert_enabled' => true, 'wecom_archive_tenant' => 'tenant-a']);
|
||||
$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' => [[
|
||||
@@ -162,26 +164,65 @@ try {
|
||||
$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)");
|
||||
Db::name('admin')->where('id', 11)->update(['work_wechat_userid' => 'staff-a']);
|
||||
Db::name('admin')->where('id', 12)->update(['work_wechat_userid' => 'staff-b']);
|
||||
$archive->exec('CREATE TABLE archive_source_account (id TEXT PRIMARY KEY, tenant_id TEXT, external_account_id TEXT, display_name TEXT)');
|
||||
$archive->exec('CREATE TABLE archive_conversation (id TEXT PRIMARY KEY, tenant_id TEXT, source_account_id TEXT, conversation_type TEXT, name TEXT, last_message_at 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, tenant_id TEXT, sender_person_id TEXT)');
|
||||
$archive->exec('CREATE TABLE archive_person (id TEXT PRIMARY KEY, tenant_id TEXT, display_name TEXT)');
|
||||
$archive->exec('CREATE TABLE archive_patient_binding (tenant_id TEXT, person_id TEXT, patient_id INTEGER, diagnosis_id INTEGER, status TEXT, is_primary INTEGER)');
|
||||
$archive->exec("INSERT INTO archive_source_account VALUES ('a1','tenant-a','staff-a','甲'),('a2','tenant-a','unbound','外来客服'),('a3','tenant-a','staff-b','甲'),('b1','tenant-b','staff-a','甲')");
|
||||
$archive->exec("INSERT INTO archive_conversation VALUES ('c1','tenant-a','a1','direct_wecom','合成甲','3'),('c2','tenant-a','a2','direct_wecom','未建档','3'),('c3','tenant-a','a3','direct_wecom','合成甲','3'),('cb','tenant-b','b1','direct_wecom','乙','3'),('bad','tenant-b','a1','direct_wecom','域外','3')");
|
||||
$archive->exec("INSERT INTO archive_person VALUES ('p1','tenant-a','合成甲'),('pb','tenant-b','其他租户')");
|
||||
$archive->exec("INSERT INTO archive_patient_binding VALUES ('tenant-a','p1',201,101,'active',1),('tenant-b','p1',301,102,'active',1)");
|
||||
$archive->exec("INSERT INTO archive_message VALUES
|
||||
('local1','c1','a1','加我微信','outbound','normal','文本','2026-11-10T03:00:00+00:00',1794268800,'tenant-a','pb'),
|
||||
('local2','c2','a2','私下转账给我','outbound','normal','文本','2026-11-10T03:01:00+00:00',1794268860,'tenant-a',NULL),
|
||||
('peer','c1','a1','合成入站','inbound','normal','文本','2026-11-09',1794268700,'tenant-a','p1'),
|
||||
('foreign','cb','b1','加我微信','outbound','normal','文本','2026-11-09',1794268700,'tenant-b','pb'),
|
||||
('foreign-link','c1','b1','范围外','outbound','normal','文本','2099-01',1794268700,'tenant-b','pb'),
|
||||
('mismatch','c1','a3','其他员工','outbound','normal','文本','2099-02',1794268700,'tenant-a',NULL)");
|
||||
$configure(['alert_enabled' => true, 'wecom_archive_sqlite' => $local, 'wecom_archive_tenant' => '']);
|
||||
$ok(!Archive::configured() && !Archive::page('', 5)['configured'] && Archive::accounts() === []
|
||||
&& Archive::conversations('staff-a') === [] && Archive::messages('c1')['messages'] === [], '未绑定租户时本地归档关闭');
|
||||
$configure(['alert_enabled' => true, 'wecom_archive_sqlite' => $local, 'wecom_archive_tenant' => 'tenant-a']);
|
||||
$directory = Alert::wecomDirectory(11);
|
||||
$ok($directory['ready'] && count($directory['staff']) === 1 && $directory['staff'][0]['conversations'] === 1
|
||||
&& !$directory['accounts'], '按员工范围和稳定账号计算目录,显示名重合不增加计数');
|
||||
$chats = Alert::wecomChats(['assistant_id' => 11], 11)['conversations'];
|
||||
$ok(array_column($chats, 'id') === ['c1'] && $chats[0]['message_count'] === 2 && $chats[0]['preview'] === '加我微信', '会话计数和预览仅包含本租户该员工的消息');
|
||||
$ok(array_column(Alert::wecomMessages(['assistant_id' => 11, 'conversation_id' => 'c1'], 11)['messages'], 'sender_name') === ['合成甲', ''], '正文只含本账号消息,跨租户发言人不显示');
|
||||
$deny(static fn () => Alert::wecomMessages(['assistant_id' => 11, 'conversation_id' => 'c3'], 11), '同名员工不能查看他人正文');
|
||||
$deny(static fn () => Alert::wecomChats(['assistant_id' => 12], 11), '越过部门的医助不可选');
|
||||
$deny(static fn () => Alert::wecomChats(['account' => 'staff-b'], 11), '受限员工不能直接指定账号');
|
||||
$deny(static fn () => Alert::wecomMessages(['account' => 'staff-a', 'conversation_id' => 'cb'], 1), '全范围管理员也不能凭 ID 查看其他租户正文');
|
||||
Db::name('admin')->where('id', 12)->update(['work_wechat_userid' => 'staff-a']);
|
||||
$ok(!Alert::wecomChats(['assistant_id' => 11], 11)['conversations'] && Alert::wecomDirectory(11)['staff'][0]['conversations'] === 0, '稳定账号归属重复时拒绝受限访问');
|
||||
Db::name('admin')->where('id', 11)->update(['work_wechat_userid' => '']);
|
||||
$ok(!Alert::wecomChats(['assistant_id' => 11], 11)['conversations'], '缺少绑定不能按同名查看');
|
||||
Db::name('admin')->where('id', 11)->update(['work_wechat_userid' => 'staff-a']);
|
||||
Db::name('admin')->where('id', 12)->update(['work_wechat_userid' => 'staff-b']);
|
||||
$page = Archive::page('', 1);
|
||||
$ok($page['has_more'] && $page['items'][0]['id'] === 'local1' && $page['items'][0]['patient_id'] === 201
|
||||
&& array_column(Archive::page($page['next_cursor'], 10)['items'], 'id') === ['local2'], '定时分页只含归属租户的发出文字,患者来自明确绑定');
|
||||
$archive->exec("INSERT INTO archive_patient_binding VALUES ('tenant-a','p1',301,102,'active',1)");
|
||||
$ok(Archive::page('', 1)['items'][0]['patient_id'] === 0, '多个有效主绑定不会被用于授权');
|
||||
$archive->exec("DELETE FROM archive_patient_binding WHERE tenant_id='tenant-a' AND patient_id=301");
|
||||
$legacy = Archive::identify([['id' => 'legacy', 'staff_name' => '甲', 'patient_name' => '合成甲']])[0];
|
||||
$ok($legacy['patient_id'] === 0 && $legacy['zyt_user_id'] === '0', '旧版 HTTP 只带名字时保留未归属');
|
||||
$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, '本地归档按姓名对上医助和患者');
|
||||
$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]);
|
||||
$configure(['alert_enabled' => true, 'wecom_archive_sqlite' => $local, 'wecom_archive_tenant' => 'tenant-a', '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'] = '';
|
||||
@@ -192,12 +233,32 @@ try {
|
||||
});
|
||||
$judged = $wording->tick();
|
||||
$ok($judged['created'] === 1 && (int) Db::name('assistant_service_alert')->where('rule_code', 'inappropriate_wording')->count() === 1, '模型指出且原文确实存在的用词才进入预警');
|
||||
$owned = Db::name('assistant_service_alert')->where('source_key', 'local1:201')->find();
|
||||
$foreignStaff = $owned;
|
||||
unset($foreignStaff['id']);
|
||||
$foreignStaff['source_key'] = 'foreign-staff';
|
||||
$foreignStaff['staff_admin_id'] = 12;
|
||||
$outsideId = (int) Db::name('assistant_service_alert')->insertGetId($foreignStaff);
|
||||
$legacyAlert = $foreignStaff;
|
||||
$legacyAlert['archive_tenant_id'] = '';
|
||||
$legacyId = (int) Db::name('assistant_service_alert')->insertGetId($legacyAlert);
|
||||
$ok(!in_array($outsideId, array_column($list(['page_size' => 50], 11)['lists'], 'id'), true), '患者可见也不能查看范围外员工的归档预警');
|
||||
$deny(static fn () => $review(['id' => $outsideId, 'status' => 'confirmed', 'note' => 'test'], 13), '复核校验当前员工范围');
|
||||
$deny(static fn () => $review(['id' => $legacyId, 'status' => 'confirmed', 'note' => 'test'], 1), '历史未标记租户的归档预警不可按 ID 复核');
|
||||
$configure(['alert_enabled' => true, 'wecom_archive_sqlite' => $local, 'wecom_archive_tenant' => 'tenant-b']);
|
||||
$otherScan = $scanner->tick();
|
||||
$ok($otherScan['created'] === 1 && Db::name('assistant_service_alert')->where('archive_tenant_id', 'tenant-b')->count() === 1, '切换租户后两个扫描游标重新起步');
|
||||
$ok(!in_array((int) $owned['id'], array_column($list(['page_size' => 50], 1)['lists'], 'id'), true), '切换租户后全范围账号也看不到原租户预警');
|
||||
$deny(static fn () => $review(['id' => (int) $owned['id'], 'status' => 'confirmed', 'note' => 'test'], 1), '旧租户预警无法按 ID 复核');
|
||||
$configure(['alert_enabled' => true, 'wecom_archive_tenant' => '']);
|
||||
$ok(!in_array('wecom', array_column($list(['page_size' => 50], 1)['lists'], 'channel'), true), '清除租户配置时历史归档预警全部关闭');
|
||||
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 {
|
||||
unset($archive);
|
||||
if (is_dir($temporary)) {
|
||||
foreach (glob($temporary . '/*') ?: [] as $file) { @unlink($file); }
|
||||
@rmdir($temporary);
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
|
||||
use app\adminapi\controller\setting\system\LogController;
|
||||
use app\adminapi\service\DesktopSessionService;
|
||||
use app\common\enum\AdminTerminalEnum;
|
||||
use app\Request;
|
||||
use think\facade\Db;
|
||||
|
||||
// 直接调用报表控制器,使用隔离的内存库,不加载项目环境。
|
||||
$app = new think\App(sys_get_temp_dir() . '/desktop-session-report-test');
|
||||
$manager = new think\DbManager();
|
||||
$manager->setConfig(['default' => 'test', 'connections' => [
|
||||
'test' => ['type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'test_'],
|
||||
]]);
|
||||
$app->instance('think\DbManager', $manager);
|
||||
think\Model::setDb($manager);
|
||||
$config = new think\Config();
|
||||
$config->set(['lists' => ['page_size' => 20, 'page_size_max' => 100],
|
||||
'data_scope' => ['enabled' => true]], 'project');
|
||||
$app->instance('config', $config);
|
||||
think\Validate::maker(static fn ($validate) => $validate->setRequest(request()));
|
||||
|
||||
foreach ([
|
||||
'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',
|
||||
'system_menu' => 'id INTEGER PRIMARY KEY, perms TEXT, is_disable INTEGER DEFAULT 0',
|
||||
'system_role_menu' => 'role_id INTEGER, menu_id INTEGER',
|
||||
'admin_session' => 'id INTEGER PRIMARY KEY, workstation_slot INTEGER, terminal INTEGER, token TEXT, expire_time INTEGER, update_time INTEGER',
|
||||
'desktop_login_session' => 'id INTEGER PRIMARY KEY, admin_id INTEGER, account TEXT, name TEXT, login_time INTEGER,
|
||||
logout_time INTEGER NULL, last_seen_time INTEGER, due_time INTEGER, expires_at INTEGER, duration_seconds INTEGER, end_reason TEXT',
|
||||
] as $table => $fields) {
|
||||
Db::execute("CREATE TABLE test_{$table} ({$fields})");
|
||||
}
|
||||
$pdo = Db::connect()->getPdo();
|
||||
$pdo->sqliteCreateFunction('LEAST', 'min', 2);
|
||||
$pdo->sqliteCreateFunction('GREATEST', 'max', 2);
|
||||
Db::execute("INSERT INTO test_system_role VALUES (10,'医助',4,NULL),(12,'主管',3,NULL),(13,'系统管理员',1,NULL)");
|
||||
Db::execute('INSERT INTO test_admin_role VALUES (20,10),(21,10),(30,12)');
|
||||
Db::execute('INSERT INTO test_admin_dept VALUES (20,1),(21,2),(30,1)');
|
||||
Db::execute("INSERT INTO test_system_menu VALUES (1,'setting.system.log/desktopSessions',0)");
|
||||
Db::execute('INSERT INTO test_system_role_menu VALUES (10,1),(12,1)');
|
||||
|
||||
$tz = new DateTimeZone('Asia/Shanghai');
|
||||
$start = (new DateTimeImmutable('2024-01-02', $tz))->getTimestamp();
|
||||
$insert = static function (int $id, int $owner, int $login, ?int $logout, string $reason, ?int $lastSeen = null): void {
|
||||
$lastSeen ??= $logout ?? $login;
|
||||
Db::name('desktop_login_session')->insert([
|
||||
'id' => $id, 'admin_id' => $owner, 'account' => 'staff' . $owner,
|
||||
'name' => $owner === 20 ? '张医生' : '王医生', 'login_time' => $login, 'logout_time' => $logout,
|
||||
'expires_at' => DesktopSessionService::nextCutoff($login), 'last_seen_time' => $lastSeen,
|
||||
'due_time' => min(DesktopSessionService::nextCutoff($login), $lastSeen + DesktopSessionService::HEARTBEAT_GRACE),
|
||||
'duration_seconds' => $lastSeen - $login, 'end_reason' => $reason,
|
||||
]);
|
||||
};
|
||||
$insert(1, 20, $start - 1800, $start + 1800, 'logout');
|
||||
$insert(2, 20, $start - 200, $start, 'logout');
|
||||
$insert(3, 20, $start, $start, 'replaced');
|
||||
$insert(4, 21, $start + 1200, $start + 2400, 'revoked');
|
||||
$insert(5, 20, $start + 10, null, '', $start + 70);
|
||||
$insert(6, 20, $start + 86400 - 600, $start + 86400 + 1200, 'logout');
|
||||
$due = $start + 70 + DesktopSessionService::HEARTBEAT_GRACE;
|
||||
Db::name('admin_session')->insert(['workstation_slot' => 5, 'terminal' => AdminTerminalEnum::WORKSTATION,
|
||||
'token' => 'expired-test-session', 'expire_time' => $due, 'update_time' => $start + 70]);
|
||||
|
||||
$query = static function (int $viewer, array $params = [], bool $root = false) use ($app): array {
|
||||
$request = (new Request())->withServer(['REQUEST_METHOD' => 'GET'])->withGet($params);
|
||||
$request->adminId = $viewer;
|
||||
// 模拟变更前缓存仍为管理员的情况,数据范围须依据当前角色。
|
||||
$request->adminInfo = ['admin_id' => $viewer, 'role_id' => [13], 'root' => (int) $root];
|
||||
$app->instance('request', $request);
|
||||
try {
|
||||
return (new LogController($app))->desktopSessions()->getData();
|
||||
} catch (think\exception\HttpResponseException $error) {
|
||||
return $error->getResponse()->getData();
|
||||
}
|
||||
};
|
||||
$expect = static function (bool $ok, string $message): void {
|
||||
if (!$ok) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$params = ['date' => '2024-01-02'];
|
||||
$expect($query(99, $params)['code'] === 0, '无菜单权限不能读取报表');
|
||||
$report = $query(1, $params, true)['data'];
|
||||
$expect($report['count'] === 5 && array_column($report['lists'], 'id') === [6,4,5,3,1],
|
||||
'午夜结束应算在前一天、同秒登录退出算在当天,按登录时间倒序');
|
||||
$expect($report['extend']['total_day_seconds'] === 3660, '合计使用自然日内的实际交集');
|
||||
$rows = array_column($report['lists'], null, 'id');
|
||||
$expect($rows[1]['duration_seconds'] === 3600 && $rows[1]['day_seconds'] === 1800
|
||||
&& $rows[1]['login_time'] === '2024-01-01 23:30:00' && $rows[1]['logout_time'] === '2024-01-02 00:30:00',
|
||||
'跨午夜分摊时保留会话完整时长与北京时间');
|
||||
$expect($rows[5]['status'] === 'timeout' && $rows[5]['status_label'] === '连接超时'
|
||||
&& $rows[5]['duration_seconds'] === 60 && $rows[5]['day_seconds'] === 60, '查询可补结算掉线会话');
|
||||
$expect($query(1, ['date' => '2024-01-03'], true)['data']['extend']['total_day_seconds'] === 1200,
|
||||
'跨次日的会话仅计次日部分');
|
||||
$own = $query(20, $params + ['apply_data_scope' => 0, 'page_size' => 1, 'page_no' => 2])['data'];
|
||||
$expect($own['count'] === 4 && $own['extend']['total_day_seconds'] === 2460
|
||||
&& array_column($own['lists'], 'id') === [5], '本人视图的列表、分页计数与合计使用相同范围');
|
||||
$team = $query(30, $params + ['keyword' => '医生'])['data'];
|
||||
$expect($team['count'] === 4 && $team['extend']['total_day_seconds'] === 2460, '主管仅可查询同部门历史');
|
||||
$other = $query(30, $params + ['keyword' => 'staff21'])['data'];
|
||||
$expect($other['count'] === 0 && $other['extend']['total_day_seconds'] === 0, '域外账号搜索不能泄漏计数或汇总');
|
||||
$expect($query(1, $params + ['keyword' => '王医生'], true)['data']['count'] === 1, '按姓名快照搜索');
|
||||
$expect($query(1, $params + ['keyword' => '%'], true)['data']['count'] === 0, '按字面匹配特殊字符');
|
||||
$expect($query(1, ['date' => '2024-02-30'], true)['code'] === 0, '拒绝无效日期');
|
||||
|
||||
$current = time();
|
||||
$insert(7, 20, $current - 10, null, '', $current);
|
||||
$live = $query(20)['data'];
|
||||
$expect($live['count'] === 1 && $live['lists'][0]['status'] === 'online' && $live['lists'][0]['logout_time'] === null
|
||||
&& $live['lists'][0]['duration_seconds'] >= 10, '默认查询北京时间今天,进行中会话实时计时');
|
||||
echo "DesktopSessionReportTest OK\n";
|
||||
@@ -40,7 +40,7 @@ analysisRoutingExpect(
|
||||
'public business logic rejects model names before loading a diagnosis'
|
||||
);
|
||||
analysisRoutingExpect(
|
||||
'AI模型仅支持qwen或openai',
|
||||
'AI模型仅支持qwen、openai或doubao',
|
||||
DiagnosisAiLogic::getError(),
|
||||
'business logic returns a fixed non-secret invalid-model error'
|
||||
);
|
||||
|
||||
@@ -84,8 +84,8 @@ assistantStreamExpect(
|
||||
'request validation and diagnosis authorization precede early start; aggregation follows it'
|
||||
);
|
||||
assistantStreamExpect(
|
||||
str_contains($validate, "return \$this->only(['id', 'task', 'prompt']);"),
|
||||
'stream reuses the strict id/task/prompt assistant scene'
|
||||
str_contains($validate, "return \$this->only(['id', 'task', 'prompt', 'model']);"),
|
||||
'stream reuses the strict id/task/prompt/model assistant scene'
|
||||
);
|
||||
assistantStreamExpect(
|
||||
str_contains($logic, 'self::PERMISSION_ASSISTANT')
|
||||
|
||||
@@ -347,6 +347,61 @@ try {
|
||||
&& $GLOBALS['tongueCalls'][0][CURLOPT_URL] === 'https://dify.fixture.test/v1/files/upload', 'existing Dify base URL forms supported');
|
||||
}
|
||||
|
||||
// 豆包直连火山方舟:同一张截图以 data URI 内联,单次 chat/completions,不经过 Dify 上传。
|
||||
$arkUrl = 'https://ark.fixture.test/api/v3/chat/completions';
|
||||
$doubaoProfile = ['api_key' => 'fixture-only-ark-secret', 'label' => '豆包', 'name' => 'doubao-fixture-model', 'base_url' => $arkUrl];
|
||||
$arkReply = static fn (string $content, int $seconds = 0): array => ['seconds' => $seconds,
|
||||
'body' => json_encode(['choices' => [['message' => ['role' => 'assistant', 'content' => $content]]]], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)];
|
||||
$reset([$arkReply($correctedAnswer)]);
|
||||
$GLOBALS['tongueConfig']['models']['doubao'] = $doubaoProfile;
|
||||
$GLOBALS['tongueReadableCa'] = __FILE__;
|
||||
$GLOBALS['tongueConfig']['required_attachment_upload']['ca_file'] = __FILE__;
|
||||
$file = $upload(); $filePath = $file->getRealPath(); $bytes = file_get_contents($filePath); $digest = hash('sha256', $bytes);
|
||||
$result = $controller(array_replace($body, ['model' => 'doubao']), ['file' => $file]);
|
||||
$expect($result['code'] === 1 && $result['data'] === ['request_id' => $body['request_id'], 'diagnosis_id' => 41,
|
||||
'image_sha256' => $digest, 'analysis' => $valid, 'model' => 'doubao', 'model_label' => '豆包'], 'doubao returns the same response contract');
|
||||
$expect(count($GLOBALS['tongueCalls']) === 1 && $GLOBALS['tongueClosed'] === 1 && !is_file($filePath), 'doubao performs one model call, no Dify upload, and removes the JPEG');
|
||||
$arkCall = $GLOBALS['tongueCalls'][0];
|
||||
$arkPayload = json_decode($arkCall[CURLOPT_POSTFIELDS], true);
|
||||
$expect($arkCall[CURLOPT_URL] === $arkUrl && in_array('Authorization: Bearer fixture-only-ark-secret', $arkCall[CURLOPT_HTTPHEADER], true)
|
||||
&& !str_contains($arkCall[CURLOPT_POSTFIELDS], 'fixture-only-secret'), 'doubao uses its own Ark endpoint and key, never the Dify credentials');
|
||||
$expect($arkPayload['model'] === 'doubao-fixture-model' && count($arkPayload['messages']) === 1
|
||||
&& $arkPayload['messages'][0]['content'][0] === ['type' => 'text', 'text' => \app\common\service\TongueScreenshotAnalysis::prompt()]
|
||||
&& $arkPayload['messages'][0]['content'][1] === ['type' => 'image_url', 'image_url' => ['url' => 'data:image/jpeg;base64,' . base64_encode($bytes)]]
|
||||
&& !isset($arkPayload['thinking']), 'exact screenshot bytes are inlined beside the fixed prompt; thinking follows the model default');
|
||||
$expect(!str_contains($arkCall[CURLOPT_POSTFIELDS], 'patient-secret') && !str_contains($arkCall[CURLOPT_POSTFIELDS], $body['request_id'])
|
||||
&& !isset($arkCall[CURLOPT_CAINFO]) && $arkCall[CURLOPT_SSL_VERIFYPEER] === true && $arkCall[CURLOPT_SSL_VERIFYHOST] === 2
|
||||
&& $arkCall[CURLOPT_FOLLOWLOCATION] === false && $arkCall[CURLOPT_PROXY] === '' && $arkCall[CURLOPT_TIMEOUT_MS] === 50000,
|
||||
'no patient identifiers; public Ark TLS ignores the private attachment CA and keeps every transport protection');
|
||||
|
||||
$reset([$arkReply($rejectedAnswer, 6), $arkReply($correctedAnswer)]);
|
||||
$GLOBALS['tongueConfig']['models']['doubao'] = $doubaoProfile + ['thinking' => 'disabled'];
|
||||
$expect($controller(array_replace($body, ['model' => 'doubao']), ['file' => $upload()])['code'] === 1
|
||||
&& count($GLOBALS['tongueCalls']) === 2, 'doubao parser rejection permits exactly one correction');
|
||||
[$arkFirst, $arkCorrection] = array_map(static fn (array $call): array => json_decode($call[CURLOPT_POSTFIELDS], true), $GLOBALS['tongueCalls']);
|
||||
$expect($arkFirst['thinking'] === ['type' => 'disabled'] && $arkCorrection['thinking'] === ['type' => 'disabled']
|
||||
&& $arkCorrection['messages'][0]['content'][1] === $arkFirst['messages'][0]['content'][1]
|
||||
&& str_starts_with($arkCorrection['messages'][0]['content'][0]['text'], $arkFirst['messages'][0]['content'][0]['text'] . "\n")
|
||||
&& !str_contains($GLOBALS['tongueCalls'][1][CURLOPT_POSTFIELDS], $rejectedMarker)
|
||||
&& $GLOBALS['tongueCalls'][1][CURLOPT_TIMEOUT_MS] === 44000, 'correction resends the same image with the fixed rules, configured thinking and the remaining deadline only');
|
||||
|
||||
foreach ([['status' => 401, 'body' => '{"error":{"message":"fixture-only-ark-secret invalid"}}'], ['body' => '{}'],
|
||||
['body' => '{"choices":[{"message":{"content":null}}]}'], ['body' => 'not-json']] as $arkFailure) {
|
||||
$reset([$arkFailure]); $GLOBALS['tongueConfig']['models']['doubao'] = $doubaoProfile;
|
||||
$file = $upload(); $failed = $controller(array_replace($body, ['model' => 'doubao']), ['file' => $file]);
|
||||
$expect($failed['code'] === 0 && count($GLOBALS['tongueCalls']) === 1 && !is_file($file->getPathname())
|
||||
&& !str_contains(json_encode($failed), 'fixture-only-ark-secret'), 'doubao transport or envelope failure is safe and never retried');
|
||||
}
|
||||
foreach ([['api_key' => ''], ['name' => ''], ['base_url' => 'https://ark.fixture.test/api/v3'],
|
||||
['base_url' => 'http://user:[EMAIL]/api/v3/chat/completions']] as $brokenDoubao) {
|
||||
$reset(); $GLOBALS['tongueConfig']['models']['doubao'] = array_replace($doubaoProfile, $brokenDoubao);
|
||||
$expect($controller(array_replace($body, ['model' => 'doubao']), ['file' => $upload()])['code'] === 0
|
||||
&& $GLOBALS['tongueCalls'] === [], 'incomplete doubao configuration fails before network');
|
||||
}
|
||||
$reset();
|
||||
$expect($controller(array_replace($body, ['model' => 'doubao']), ['file' => $upload()])['code'] === 0
|
||||
&& $GLOBALS['tongueCalls'] === [], 'an unconfigured doubao profile never falls back to Dify');
|
||||
|
||||
// Real auth middleware, with menu lookup deliberately explosive: exact shared grant only.
|
||||
$route = new class {
|
||||
public array $adminInfo = ['admin_id' => 7, 'root' => 0, 'login_ip' => '127.0.0.1'];
|
||||
|
||||
@@ -1,47 +1,47 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use app\adminapi\validate\tcm\DiagnosisValidate;
|
||||
|
||||
function diagnosisAddSceneExpect(bool $condition, string $message): void
|
||||
{
|
||||
if (!$condition) {
|
||||
fwrite(STDERR, "FAIL: {$message}\n");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
$validateSource = file_get_contents(
|
||||
dirname(__DIR__) . '/app/adminapi/validate/tcm/DiagnosisValidate.php'
|
||||
);
|
||||
diagnosisAddSceneExpect(is_string($validateSource), 'DiagnosisValidate source is readable');
|
||||
diagnosisAddSceneExpect(
|
||||
str_contains($validateSource, "->remove('task', true)"),
|
||||
'add scene strips the AI assistant task rule'
|
||||
);
|
||||
diagnosisAddSceneExpect(
|
||||
str_contains($validateSource, "return \$this->only(['id', 'task', 'prompt']);"),
|
||||
'aiAssistant scene still requires a task'
|
||||
);
|
||||
|
||||
$addPayload = [
|
||||
'patient_name' => '张三',
|
||||
'phone' => '13800138000',
|
||||
'gender' => 1,
|
||||
'age' => 50,
|
||||
'diagnosis_type' => 'follow_up',
|
||||
'local_hospital_name' => '某医院',
|
||||
];
|
||||
|
||||
$addScene = (new DiagnosisValidate())->scene('add');
|
||||
$addOk = $addScene->check($addPayload);
|
||||
diagnosisAddSceneExpect(
|
||||
$addOk === true,
|
||||
'add scene accepts a diagnosis payload without an AI assistant task'
|
||||
. ($addOk ? '' : '; got: ' . $addScene->getError())
|
||||
);
|
||||
|
||||
echo "Diagnosis add-scene validation: OK\n";
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use app\adminapi\validate\tcm\DiagnosisValidate;
|
||||
|
||||
function diagnosisAddSceneExpect(bool $condition, string $message): void
|
||||
{
|
||||
if (!$condition) {
|
||||
fwrite(STDERR, "FAIL: {$message}\n");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
$validateSource = file_get_contents(
|
||||
dirname(__DIR__) . '/app/adminapi/validate/tcm/DiagnosisValidate.php'
|
||||
);
|
||||
diagnosisAddSceneExpect(is_string($validateSource), 'DiagnosisValidate source is readable');
|
||||
diagnosisAddSceneExpect(
|
||||
str_contains($validateSource, "->remove('task', true)"),
|
||||
'add scene strips the AI assistant task rule'
|
||||
);
|
||||
diagnosisAddSceneExpect(
|
||||
str_contains($validateSource, "return \$this->only(['id', 'task', 'prompt', 'model']);"),
|
||||
'aiAssistant scene still requires a task'
|
||||
);
|
||||
|
||||
$addPayload = [
|
||||
'patient_name' => '张三',
|
||||
'phone' => '13800138000',
|
||||
'gender' => 1,
|
||||
'age' => 50,
|
||||
'diagnosis_type' => 'follow_up',
|
||||
'local_hospital_name' => '某医院',
|
||||
];
|
||||
|
||||
$addScene = (new DiagnosisValidate())->scene('add');
|
||||
$addOk = $addScene->check($addPayload);
|
||||
diagnosisAddSceneExpect(
|
||||
$addOk === true,
|
||||
'add scene accepts a diagnosis payload without an AI assistant task'
|
||||
. ($addOk ? '' : '; got: ' . $addScene->getError())
|
||||
);
|
||||
|
||||
echo "Diagnosis add-scene validation: OK\n";
|
||||
|
||||
@@ -14,8 +14,11 @@ namespace app\common\service\esign {
|
||||
public static array $identity = ['status' => 'INIT'];
|
||||
public static int $starts = 0;
|
||||
public static int $creates = 0;
|
||||
public static string $newAccountId = 'bound-account';
|
||||
public static string $requestedName = '';
|
||||
public static ?string $mobile = null;
|
||||
public static bool $expired = false;
|
||||
public static ?\Closure $checkCertificate = null;
|
||||
public static ?\Closure $duringStart = null;
|
||||
public static ?\Closure $duringRecipientLookup = null;
|
||||
public static ?string $account = null;
|
||||
@@ -29,6 +32,7 @@ namespace app\common\service\esign {
|
||||
{
|
||||
++self::$starts;
|
||||
self::$account = $accountId;
|
||||
self::$requestedName = $name;
|
||||
if (self::$duringStart) {
|
||||
(self::$duringStart)();
|
||||
}
|
||||
@@ -71,7 +75,7 @@ namespace app\common\service\esign {
|
||||
throw new \RuntimeException('Identity proof mismatch');
|
||||
}
|
||||
++self::$creates;
|
||||
return 'bound-account';
|
||||
return self::$newAccountId;
|
||||
}
|
||||
|
||||
public function signingAccount(string $accountId): array
|
||||
@@ -82,6 +86,9 @@ namespace app\common\service\esign {
|
||||
|
||||
public function certificateValidity(string $accountId): array
|
||||
{
|
||||
if (self::$checkCertificate) {
|
||||
return (self::$checkCertificate)($accountId);
|
||||
}
|
||||
return ['startDate' => '2024-01-01 08:00:00',
|
||||
'endDate' => self::$expired ? '2024-02-01 08:00:00' : '2099-01-01 08:00:00'];
|
||||
}
|
||||
@@ -107,6 +114,7 @@ namespace {
|
||||
use app\common\service\esign\DoctorEsignAuthorizationRequired;
|
||||
use app\common\service\esign\DoctorEsignIdentityService as Enrollment;
|
||||
use app\common\service\esign\EsignClient as Provider;
|
||||
use app\common\service\esign\EsignProviderException;
|
||||
use think\facade\Db;
|
||||
use think\Container;
|
||||
|
||||
@@ -128,7 +136,8 @@ namespace {
|
||||
Db::execute($sql);
|
||||
Db::execute($sql);
|
||||
}
|
||||
Db::execute('CREATE TABLE zyt_admin (id INTEGER PRIMARY KEY,name TEXT,disable INTEGER DEFAULT 0,delete_time INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_config (id INTEGER PRIMARY KEY,type TEXT,name TEXT,value TEXT,create_time INTEGER,update_time INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_admin (id INTEGER PRIMARY KEY,name TEXT,disable INTEGER DEFAULT 0,delete_time INTEGER,root INTEGER DEFAULT 0)');
|
||||
Db::execute('CREATE TABLE zyt_admin_role (admin_id INTEGER,role_id INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_doctor_esign_account (doctor_id INTEGER,environment TEXT,app_id TEXT,account_id TEXT,
|
||||
doctor_name TEXT,create_time INTEGER,UNIQUE(doctor_id,environment,app_id))');
|
||||
@@ -145,7 +154,7 @@ namespace {
|
||||
$throws = static function (callable $operation, string $expected, string $message) use ($assert): void {
|
||||
try {
|
||||
$operation();
|
||||
} catch (DomainException $error) {
|
||||
} catch (Throwable $error) {
|
||||
$assert(is_a($error, $expected), $message);
|
||||
return;
|
||||
}
|
||||
@@ -155,7 +164,8 @@ namespace {
|
||||
$phone = '13800000000';
|
||||
$assert(Enrollment::status(1)['enabled'] === false, 'SMS enrollment defaults off');
|
||||
$config->set(['doctor_sms_enabled' => true], 'esign');
|
||||
$assert(Enrollment::status(1)['status'] === 'unbound', 'doctor starts unbound');
|
||||
$unbound = Enrollment::status(1);
|
||||
$assert($unbound['status'] === 'unbound' && !isset($unbound['certificate_state']), 'doctor starts unbound');
|
||||
$throws(static fn () => Enrollment::status(3), DomainException::class, 'non-physician denied');
|
||||
$throws(static fn () => Enrollment::willingnessRecipient(1, Provider::NAME, ''), DoctorEsignIdentityRequired::class, 'setup-required reason distinguishes an unbound doctor');
|
||||
|
||||
@@ -180,14 +190,46 @@ namespace {
|
||||
$assert($pending['status'] === 'binding_required' && $pending['identity_details_required'] && !isset($pending['auth_url'])
|
||||
&& Provider::$creates === 0, 'successful polling exposes only safe metadata and accepts masked identity as supplemental');
|
||||
$assert(Enrollment::complete(1, 'bad-input')['identity_details_required'] && Provider::$creates === 0, 'invalid supplemental number never reaches SDK');
|
||||
$assert(Enrollment::complete(1, Provider::DOCUMENT)['status'] === 'needs_mobile' && Provider::$creates === 1,
|
||||
$withoutMobile = Enrollment::complete(1, Provider::DOCUMENT);
|
||||
$assert($withoutMobile['status'] === 'needs_mobile' && $withoutMobile['certificate_state'] === 'valid' && Provider::$creates === 1,
|
||||
'successful provider proof binds without signing, but an absent provider authorization is not ready');
|
||||
$assert(Db::name('doctor_esign_identity')->count() === 0 && !str_contains(json_encode(Db::name('doctor_esign_account')->find()), Provider::DOCUMENT),
|
||||
'completed enrollment clears hosted URL and does not persist identity number');
|
||||
|
||||
$throws(static fn () => Enrollment::willingnessRecipient(1, Provider::NAME, 'bound-account'), DoctorEsignIdentityRequired::class, 'willingness requires a current authorized mobile');
|
||||
|
||||
$boundAccount = Db::name('doctor_esign_account')->where('doctor_id', 1)->find();
|
||||
Provider::$checkCertificate = static function (string $accountId) use ($assert): array {
|
||||
$assert($accountId === 'bound-account', 'certificate query uses the current signing account');
|
||||
return ['startDate' => '2098-01-01 08:00:00', 'endDate' => '2099-01-01 08:00:00'];
|
||||
};
|
||||
$futureCertificate = Enrollment::status(1);
|
||||
$assert($futureCertificate['status'] === 'renewal_required' && $futureCertificate['certificate_state'] === 'renewal_required',
|
||||
'certificate validity must have already started');
|
||||
Provider::$checkCertificate = static fn () => ['startDate' => '2024-01-01 08:00:00', 'endDate' => '2024-01-01 08:00:00'];
|
||||
$assert(Enrollment::status(1)['certificate_state'] === 'renewal_required', 'an empty validity period cannot authorize signing');
|
||||
Provider::$checkCertificate = static fn () => ['startDate' => '2024-02-30 08:00:00', 'endDate' => '2099-01-01 08:00:00'];
|
||||
$badCertificate = Enrollment::status(1);
|
||||
$assert($badCertificate['status'] === 'renewal_required' && $badCertificate['certificate_state'] === 'unconfirmed'
|
||||
&& $badCertificate['cert_expires_at'] === 0, 'unparseable dates cannot establish certificate validity');
|
||||
$throws(static fn () => Enrollment::start(1, $phone), DomainException::class, 'malformed dates cannot begin renewal');
|
||||
Provider::$checkCertificate = static fn () => throw new EsignProviderException('certificateValidity', 'TIMEOUT');
|
||||
$timeout = Enrollment::status(1);
|
||||
$assert($timeout['certificate_state'] === 'unconfirmed' && $timeout['cert_expires_at'] === 0 && !isset($timeout['auth_url'])
|
||||
&& !str_contains(json_encode($timeout), 'TIMEOUT'), 'a transient query failure reports uncertainty without provider data');
|
||||
$throws(static fn () => Enrollment::start(1, $phone), EsignProviderException::class, 'a transient failure preserves the retry path');
|
||||
Provider::$checkCertificate = static fn () => throw new EsignProviderException('certificateValidity', 'PROVIDER_123');
|
||||
$providerRejection = Enrollment::status(1);
|
||||
$assert($providerRejection['certificate_state'] === 'unconfirmed' && $providerRejection['cert_expires_at'] === 0
|
||||
&& !str_contains(json_encode($providerRejection), 'PROVIDER_123') && Provider::$starts === 1
|
||||
&& Db::name('doctor_esign_account')->where('doctor_id', 1)->find() === $boundAccount
|
||||
&& Db::name('doctor_esign_identity')->count() === 0, 'recheck does not initiate or mutate enrollment on provider rejection');
|
||||
Provider::$checkCertificate = null;
|
||||
$assert(Enrollment::status(1)['certificate_state'] === 'valid', 'a later recheck can confirm the existing certificate');
|
||||
Provider::$expired = true;
|
||||
$assert(Enrollment::status(1)['status'] === 'renewal_required', 'expired provider certificate requires renewal');
|
||||
$expired = Enrollment::status(1);
|
||||
$assert($expired['status'] === 'renewal_required' && $expired['certificate_state'] === 'renewal_required',
|
||||
'expired provider certificate requires renewal');
|
||||
Provider::$identity = ['status' => 'INIT'];
|
||||
$assert(Enrollment::start(1, $phone)['status'] === 'authenticating' && Provider::$account === 'bound-account', 'renewal reuses canonical account');
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null];
|
||||
@@ -195,7 +237,8 @@ namespace {
|
||||
Provider::$expired = false;
|
||||
$assert(Enrollment::status(1)['identity_details_required'] === false, 'a bound account needs no supplemental input');
|
||||
$ready = Enrollment::complete(1);
|
||||
$assert($ready['status'] === 'ready' && $ready['cert_expires_at'] === strtotime('2099-01-01T00:00:00Z') && Provider::$creates === 1,
|
||||
$assert($ready['status'] === 'ready' && $ready['certificate_state'] === 'valid'
|
||||
&& $ready['cert_expires_at'] === strtotime('2099-01-01T00:00:00Z') && Provider::$creates === 1,
|
||||
'same account becomes ready with certificate date in configured SDK timezone');
|
||||
$assert(!str_contains(json_encode($ready), $phone) && !str_contains(json_encode($ready), Provider::DOCUMENT), 'status never returns provider identity');
|
||||
$recipient = Enrollment::willingnessRecipient(1, Provider::NAME, 'bound-account');
|
||||
@@ -207,6 +250,15 @@ namespace {
|
||||
Provider::$mobile = null;
|
||||
Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'bound-account']);
|
||||
|
||||
Provider::$identity = ['status' => 'INIT'];
|
||||
Provider::$checkCertificate = static fn () => throw new EsignProviderException('certificateValidity', 'PROVIDER_123');
|
||||
$assert(Enrollment::start(1, $phone)['status'] === 'authenticating' && Provider::$account === 'bound-account',
|
||||
'explicit renewal on provider rejection reuses the canonical account');
|
||||
Provider::$checkCertificate = null;
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null];
|
||||
$assert(Enrollment::complete(1)['certificate_state'] === 'valid' && Provider::$creates === 1,
|
||||
'successful same-account recheck does not create another account');
|
||||
|
||||
$assert(!Enrollment::quickEnabled(), 'quick-sign is disabled by default');
|
||||
$config->set(['doctor_sms_enabled' => false, 'doctor_quicksign_enabled' => true], 'esign');
|
||||
$quickReady = Enrollment::status(1);
|
||||
@@ -240,9 +292,9 @@ namespace {
|
||||
'provider face verification alone does not activate grant');
|
||||
$quickGranted = Enrollment::complete(1);
|
||||
$assert($quickGranted['status'] === 'ready' && !$quickGranted['quicksign_authorizing']
|
||||
&& $quickGranted['quicksign_expires_at'] === $now + 86400 && $quickGranted['quicksign_remaining_times'] === 2
|
||||
&& $quickGranted['quicksign_expires_at'] === $now + 3 * 86400 && $quickGranted['quicksign_remaining_times'] === 2
|
||||
&& !str_contains(json_encode($quickGranted), 'quick-proof') && !str_contains(json_encode($quickGranted), Provider::DOCUMENT),
|
||||
'confirmed provider proof is capped to 24 hours and remains server-only');
|
||||
'confirmed provider proof follows provider expiry and remains server-only');
|
||||
$quickRow = Db::name('doctor_esign_quicksign')->where('doctor_id', 1)->find();
|
||||
$assert($quickRow['flow_id'] === 'quick-proof-1' && $quickRow['auth_url'] === null
|
||||
&& Db::name('doctor_esign_identity')->count() === 0 && Provider::$creates === 1, 'grant clears its hosted link and keeps enrollment untouched');
|
||||
@@ -271,7 +323,7 @@ namespace {
|
||||
Provider::$willingnessValid = false;
|
||||
$spent = Enrollment::status(1);
|
||||
$assert($spent['quicksign_expires_at'] === 0 && $spent['quicksign_remaining_times'] === 0
|
||||
&& $spent['quicksign_unavailable_reason'] === 'exhausted' && $spent['status'] === 'ready',
|
||||
&& $spent['quicksign_unavailable_reason'] === 'exhausted' && $spent['status'] === 'ready' && $spent['certificate_state'] === 'valid',
|
||||
'provider exhaustion leaves certificate enrollment valid and reports the spent grant');
|
||||
$throws(static fn () => Enrollment::quickAuthorization(1, Provider::NAME, 'bound-account'), DoctorEsignAuthorizationRequired::class,
|
||||
'provider cancellation/exhaustion blocks dispatch');
|
||||
@@ -291,5 +343,33 @@ namespace {
|
||||
$assert(Enrollment::start(1, '')['quicksign_authorizing'] && Provider::$quickStarts === 2, 'expired grant permits a new standalone grant');
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => null];
|
||||
$assert(Enrollment::complete(1)['quicksign_expires_at'] === $now + 120, 'provider validity is preserved when shorter than the local bound');
|
||||
|
||||
$config->set(['review_enabled' => true], 'esign');
|
||||
Db::name('admin')->insert(['id' => 4, 'name' => 'admin', 'root' => 1]);
|
||||
Provider::$identity = ['status' => 'INIT'];
|
||||
Provider::$newAccountId = 'reviewer-account';
|
||||
$startsBeforeReview = Provider::$starts;
|
||||
$assert(Enrollment::status(4)['can_edit_signer_name'] === true, 'an unbound reviewer can supply a separate legal name');
|
||||
$throws(static fn () => Enrollment::start(2, $phone, Provider::NAME), DomainException::class,
|
||||
'the reviewer-only input does not override a physician roster name');
|
||||
$throws(static fn () => Enrollment::start(4, $phone, '<姓名>'), DomainException::class,
|
||||
'invalid names are rejected before contacting eSign');
|
||||
$oldReview = Enrollment::start(4, $phone);
|
||||
$newReview = Enrollment::start(4, $phone, Provider::NAME);
|
||||
$assert($newReview['auth_url'] !== $oldReview['auth_url'] && Provider::$requestedName === Provider::NAME
|
||||
&& Enrollment::status(4)['can_edit_signer_name'] && Provider::$starts === $startsBeforeReview + 2,
|
||||
'correcting an unfinished reviewer name requests a new provider URL');
|
||||
$assert(Enrollment::start(4, $phone, Provider::NAME) === $newReview && Provider::$starts === $startsBeforeReview + 2,
|
||||
'resubmitting the same name and number restores the pending flow');
|
||||
Provider::$identity = ['status' => 'SUCCESS', 'indivInfo' => ['name' => Provider::NAME,
|
||||
'certType' => 'INDIVIDUAL_CH_IDCARD', 'certNo' => Provider::DOCUMENT]];
|
||||
$assert(Enrollment::start(4, $phone, '错误姓名')['status'] === 'binding_required' && Provider::$starts === $startsBeforeReview + 2,
|
||||
'an already verified identity cannot be replaced on retry');
|
||||
$assert(Enrollment::complete(4)['status'] === 'ready'
|
||||
&& Db::name('doctor_esign_account')->where('doctor_id', 4)->value('doctor_name') === Provider::NAME
|
||||
&& Db::name('admin')->where('id', 4)->value('name') === 'admin',
|
||||
'verified legal name is saved only to the reviewer signing account');
|
||||
$throws(static fn () => Enrollment::start(4, $phone, '不同姓名'), DomainException::class,
|
||||
'a verified signing account cannot be renamed through enrollment');
|
||||
echo "Doctor eSign enrollment: $checks checks passed (SQLite and provider doubles)\n";
|
||||
}
|
||||
|
||||
@@ -2,6 +2,16 @@
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\esign {
|
||||
final class PrescriptionReviewEsignService
|
||||
{
|
||||
public static array $calls = [];
|
||||
public static function confirm(int $id, int $orderId, int $actor, array $info, bool $verifyOnly): array
|
||||
{
|
||||
self::$calls[] = [$id, $orderId, $actor, $verifyOnly];
|
||||
return ['state' => 'signed'];
|
||||
}
|
||||
}
|
||||
|
||||
final class PrescriptionEsignService
|
||||
{
|
||||
public static array $calls = [];
|
||||
@@ -33,6 +43,30 @@ namespace app\common\model {
|
||||
public function save(): bool { self::$saved[] = $this->fields; return true; }
|
||||
}
|
||||
}
|
||||
namespace app\adminapi\logic\tcm {
|
||||
final class PrescriptionLogic
|
||||
{
|
||||
public static bool $auditOk = true;
|
||||
public static ?array $notice = null;
|
||||
|
||||
public static function audit(int $id, string $action, string $remark, int $actor, array $info): bool
|
||||
{
|
||||
return self::$auditOk;
|
||||
}
|
||||
|
||||
public static function getError(): string
|
||||
{
|
||||
return '无审核权限';
|
||||
}
|
||||
|
||||
public static function consumeLastAuditWecomNotify(): ?array
|
||||
{
|
||||
$notice = self::$notice;
|
||||
self::$notice = null;
|
||||
return $notice;
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace app\adminapi\controller {
|
||||
class BaseAdminController
|
||||
{
|
||||
@@ -40,8 +74,17 @@ namespace app\adminapi\controller {
|
||||
public int $adminId = 7;
|
||||
public array $adminInfo = ['admin_id' => 7, 'name' => '测试医师'];
|
||||
public function isNotNeedLogin(): bool { return false; }
|
||||
protected function data(array $data): array { return ['code' => 1, 'data' => $data]; }
|
||||
protected function data(array $data): \ArrayObject
|
||||
{
|
||||
return new class(['code' => 1, 'data' => $data]) extends \ArrayObject {
|
||||
public function header(array $headers): self { return $this; }
|
||||
};
|
||||
}
|
||||
protected function fail(string $message): array { return ['code' => 0, 'msg' => $message]; }
|
||||
protected function success(string $message, array $data = []): array
|
||||
{
|
||||
return ['code' => 1, 'msg' => $message, 'data' => $data];
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace {
|
||||
@@ -68,7 +111,7 @@ namespace {
|
||||
|
||||
think\Container::getInstance()->instance('request', $request);
|
||||
$response = new class($result) {
|
||||
public function __construct(private array $result) {}
|
||||
public function __construct(private \ArrayObject $result) {}
|
||||
public function getContent(): string { return json_encode($this->result); }
|
||||
};
|
||||
(new app\adminapi\listener\OperationLog())->handle($response);
|
||||
@@ -93,6 +136,24 @@ namespace {
|
||||
$expect($controller->esignStart()['code'] === 0 && count(app\common\service\esign\PrescriptionEsignService::$starts) === 1, 'invalid replacement flag cannot change identity flow');
|
||||
}
|
||||
|
||||
foreach ([false, true] as $verifyOnly) {
|
||||
$controller->request = (new app\Request())->setMethod('POST')->withPost([
|
||||
'id' => 42, 'order_id' => 5, 'actor_id' => 7, 'verify_only' => $verifyOnly,
|
||||
]);
|
||||
$expect($controller->esignReviewConfirm()['code'] === 1, 'review accepts a JSON boolean without the global trim filter');
|
||||
}
|
||||
$expect(app\common\service\esign\PrescriptionReviewEsignService::$calls === [[42, 5, 7, false], [42, 5, 7, true]],
|
||||
'review confirmation preserves the explicit sign versus verify choice');
|
||||
foreach ([null, 'false', 'true', 0, 1, []] as $invalid) {
|
||||
$controller->request = (new app\Request())->setMethod('POST')->withPost([
|
||||
'id' => 42, 'actor_id' => 7, 'verify_only' => $invalid,
|
||||
]);
|
||||
$expect($controller->esignReviewConfirm()['code'] === 0, 'malformed review flag never dispatches');
|
||||
}
|
||||
$controller->request = (new app\Request())->setMethod('POST')->withPost(['id' => 42, 'actor_id' => 8, 'verify_only' => false]);
|
||||
$expect($controller->esignReviewConfirm()['code'] === 0
|
||||
&& count(app\common\service\esign\PrescriptionReviewEsignService::$calls) === 2, 'actor mismatch cannot dispatch review');
|
||||
|
||||
$code = '023941';
|
||||
$mobile = '13800000000';
|
||||
$authUrl = 'https://smlt.esign.cn/example/private-auth-url';
|
||||
@@ -123,5 +184,26 @@ namespace {
|
||||
$expect(!str_contains($entry, $mobile) && !str_contains($entry, $number) && !str_contains($entry, $code)
|
||||
&& !str_contains($audit['result'], 'private-auth-url'), "$action audit omits signing secrets and authorization URL");
|
||||
}
|
||||
echo "eSign identity controller/privacy: $checks checks passed (isolated doubles, no DB/network)\n";
|
||||
$auditRequest = (new app\Request())->setMethod('POST');
|
||||
$controller->request = $auditRequest;
|
||||
think\Container::getInstance()->instance('request', $auditRequest);
|
||||
think\Validate::maker(static function (think\Validate $validate) use ($auditRequest, $app): void {
|
||||
$validate->setRequest($auditRequest);
|
||||
$validate->setLang(new think\Lang($app));
|
||||
});
|
||||
foreach (['approve' => '审核通过', 'reject' => '已驳回并作废处方'] as $action => $message) {
|
||||
$auditRequest->withPost(['id' => 42, 'action' => $action, 'remark' => '虚构测试']);
|
||||
app\adminapi\logic\tcm\PrescriptionLogic::$notice = [
|
||||
'ok' => false, 'errcode' => 81013, 'message' => 'user & party & tag all invalid, private provider diagnostic',
|
||||
];
|
||||
$expect($controller->audit() === ['code' => 1, 'msg' => $message, 'data' => ['wecom_notify_ok' => false]],
|
||||
"$action stays successful and never exposes a WeCom notification error");
|
||||
}
|
||||
app\adminapi\logic\tcm\PrescriptionLogic::$notice = ['ok' => true];
|
||||
$auditRequest->withPost(['id' => 42, 'action' => 'approve']);
|
||||
$expect($controller->audit()['data'] === ['wecom_notify_ok' => true], 'successful delivery status remains available');
|
||||
app\adminapi\logic\tcm\PrescriptionLogic::$auditOk = false;
|
||||
$expect($controller->audit() === ['code' => 0, 'msg' => '无审核权限'], 'actual audit denial is still returned');
|
||||
|
||||
echo "eSign identity and prescription audit controller/privacy: $checks checks passed (isolated doubles, no DB/network)\n";
|
||||
}
|
||||
|
||||
@@ -126,7 +126,7 @@ patientSecurityExpect(
|
||||
'invalid model is rejected before database or network access'
|
||||
);
|
||||
patientSecurityExpect(
|
||||
PatientAiReportLogic::getError() === 'AI模型仅支持qwen或openai',
|
||||
PatientAiReportLogic::getError() === 'AI模型仅支持qwen、openai或doubao',
|
||||
'invalid model error is fixed and secret-free'
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
|
||||
use app\adminapi\controller\tcm\PrescriptionController;
|
||||
use app\adminapi\http\middleware\AuthMiddleware;
|
||||
use app\Request;
|
||||
use app\common\service\esign\EsignClient;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
use think\facade\Db;
|
||||
|
||||
$app = new think\App();
|
||||
$manager = new think\DbManager();
|
||||
$manager->setConfig(['default' => 'test', 'connections' => ['test' => [
|
||||
'type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'zyt_', 'fields_strict' => true,
|
||||
]]]);
|
||||
$app->instance('think\DbManager', $manager);
|
||||
$config = new think\Config();
|
||||
$defaults = ['enabled' => true, 'environment' => 'sandbox', 'doctor_quicksign_enabled' => false,
|
||||
'review_enabled' => false, 'app_id' => 'fixture', 'app_secret' => 'fixture-secret',
|
||||
'sdk_url' => 'http://127.0.0.1:8091/paas-sdk-service'];
|
||||
$config->set($defaults, 'esign');
|
||||
$app->instance('config', $config);
|
||||
Db::execute('CREATE TABLE zyt_config (id INTEGER PRIMARY KEY,type TEXT,name TEXT,value TEXT,create_time INTEGER,update_time INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_admin (id INTEGER PRIMARY KEY,root INTEGER,disable INTEGER DEFAULT 0,delete_time INTEGER)');
|
||||
Db::name('admin')->insertAll([['id' => 1, 'root' => 1], ['id' => 2, 'root' => 0]]);
|
||||
|
||||
$checks = 0;
|
||||
$expect = static function (bool $ok, string $message) use (&$checks): void {
|
||||
if (!$ok) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
$checks++;
|
||||
};
|
||||
$invoke = static function (string $method, string $action, array $post, int $actor = 1, int $root = 1) use ($app): array {
|
||||
$request = (new Request())->withServer(['REMOTE_ADDR' => '127.0.0.1', 'REQUEST_METHOD' => $method])
|
||||
->setMethod($method)->setController('tcm.Prescription')->setAction($action)->withPost($post)->filter('trim');
|
||||
$request->adminInfo = ['admin_id' => $actor, 'root' => $root, 'login_ip' => '127.0.0.1'];
|
||||
$app->instance('request', $request);
|
||||
$controller = new PrescriptionController($app);
|
||||
$request->controllerObject = $controller;
|
||||
$response = (new AuthMiddleware())->handle($request, static fn () => $controller->{$action}());
|
||||
return json_decode($response->getContent(), true, flags: JSON_THROW_ON_ERROR);
|
||||
};
|
||||
|
||||
$read = static fn () => $invoke('GET', 'esignConfig', [], 2, 0);
|
||||
$save = static fn (bool $enabled) => $invoke('POST', 'esignSetConfig', ['enabled' => $enabled]);
|
||||
$expect($read()['data'] === ['enabled' => true, 'environment' => 'sandbox'], 'ordinary accounts read the .env fallback');
|
||||
$expect($invoke('GET', 'esignSetConfig', [])['code'] === 0, 'GET cannot change the policy');
|
||||
$expect($invoke('POST', 'esignSetConfig', ['enabled' => false], 2, 0)['code'] === 0, 'middleware denies a non-root writer');
|
||||
$expect($invoke('POST', 'esignSetConfig', ['enabled' => false], 2, 1)['code'] === 0, 'stale root claims cannot write');
|
||||
foreach ([[], ['enabled' => 'false'], ['enabled' => 0], ['enabled' => [true]]] as $malformed) {
|
||||
$expect($invoke('POST', 'esignSetConfig', $malformed)['code'] === 0, 'only a JSON boolean can switch modes');
|
||||
}
|
||||
$expect(Db::name('config')->count() === 0, 'rejected setting changes leave storage untouched');
|
||||
|
||||
$expect($save(false)['data'] === ['enabled' => false, 'environment' => 'sandbox']
|
||||
&& $read()['data']['enabled'] === false && !(new EsignClient())->isEnabled(), 'explicit off overrides enabled .env for clients and SDK');
|
||||
$legacy = ['id' => 17, 'audit_status' => 0, 'review_submitted_at' => 123, 'esign_status' => 'legacy'];
|
||||
$expect(!PrescriptionEsignService::requiresSignature($legacy, PrescriptionEsignService::enabled())
|
||||
&& PrescriptionEsignService::canReview($legacy), 'uploaded handwritten prescriptions use ordinary review');
|
||||
$draft = array_replace($legacy, ['esign_required' => 1, 'esign_status' => 'pending']);
|
||||
$expect(!PrescriptionEsignService::canReview($draft), 'CA-enrolled drafts cannot pass as handwritten');
|
||||
|
||||
$config->set(array_replace($defaults, ['enabled' => false, 'app_secret' => '']), 'esign');
|
||||
$expect($save(true)['code'] === 0 && $read()['data']['enabled'] === false, 'invalid SDK config leaves the previous setting active');
|
||||
$config->set(array_replace($defaults, ['enabled' => false]), 'esign');
|
||||
$enabled = $save(true)['data'];
|
||||
$expect($enabled === ['enabled' => true, 'environment' => 'sandbox', 'review_enabled' => true, 'verification_method' => 'quick'],
|
||||
'explicit on enables quick signing and pharmacist CA independently of previous rollout flags');
|
||||
$expect($read()['data'] === $enabled && (new EsignClient())->isEnabled(), 'saved setting is observed across requests and by SDK');
|
||||
$expect(!PrescriptionEsignService::canReview($legacy), 'eligible unsigned draft must satisfy the CA signature after enablement');
|
||||
$expect($save(true)['data'] === $enabled && Db::name('config')->count() === 1, 'repeated saves keep one setting record');
|
||||
|
||||
echo "Prescription CA setting: {$checks} checks passed (isolated SQLite and offline SDK configuration)\n";
|
||||
@@ -187,6 +187,7 @@ namespace app\common\service\esign {
|
||||
'signature' => ['signatureName' => 'Signature2', 'validate' => true,
|
||||
'signDate' => gmdate('Y-m-d H:i:s', max(time() + 28800, strtotime($original['signature']['signDate'] . ' UTC'))), 'timeFrom' => 'tsa'],
|
||||
'cert' => ['cn' => '测试审核人', 'issuerCN' => 'Test CA', 'sn' => 'b2'],
|
||||
'sealData' => 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/J5cAAAAASUVORK5CYII=',
|
||||
], $original];
|
||||
return ['pdf' => $dual, 'sign_service_id' => 'review-sign-1'];
|
||||
}
|
||||
@@ -196,6 +197,7 @@ namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
use app\adminapi\http\middleware\AuthMiddleware;
|
||||
use app\adminapi\lists\tcm\PrescriptionLists;
|
||||
use app\adminapi\logic\tcm\PrescriptionLogic;
|
||||
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
|
||||
use app\common\service\esign\PrescriptionEsignService as Service;
|
||||
@@ -234,19 +236,27 @@ namespace {
|
||||
'esign_required', 'esign_status', 'is_system_auto', 'delete_time', 'doctor_signature', 'update_time',
|
||||
'create_time', 'template_id', 'is_shared', 'visible_role_ids', 'assistant_id',
|
||||
'audit_status', 'audit_time', 'audit_by', 'audit_by_name', 'audit_remark',
|
||||
'void_status', 'void_time', 'void_by', 'void_by_name',
|
||||
'void_status', 'void_time', 'void_by', 'void_by_name', 'review_submitted_at',
|
||||
]));
|
||||
$columns = array_map(static fn ($field) => match ($field) {
|
||||
'id' => 'id INTEGER PRIMARY KEY',
|
||||
'void_status' => 'void_status INTEGER NOT NULL DEFAULT 0',
|
||||
'review_submitted_at' => 'review_submitted_at INTEGER NOT NULL DEFAULT 0',
|
||||
default => $field . ' TEXT',
|
||||
}, $fields);
|
||||
Db::execute('CREATE TABLE zyt_tcm_prescription (' . implode(',', $columns) . ')');
|
||||
Db::execute('CREATE TABLE zyt_config (id INTEGER PRIMARY KEY,type TEXT,name TEXT,value TEXT,create_time INTEGER,update_time INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_admin (id INTEGER PRIMARY KEY,name TEXT,delete_time INTEGER,disable INTEGER DEFAULT 0,root INTEGER DEFAULT 0)');
|
||||
Db::execute('CREATE TABLE zyt_tcm_prescription_order (
|
||||
id INTEGER PRIMARY KEY, prescription_id INTEGER, prescription_audit_status INTEGER,
|
||||
fulfillment_status INTEGER, delete_time INTEGER, diagnosis_id INTEGER, creator_id INTEGER, create_time INTEGER
|
||||
prescription_audit_remark TEXT, payment_slip_audit_status INTEGER DEFAULT 0,
|
||||
fulfillment_status INTEGER, delete_time INTEGER, diagnosis_id INTEGER, creator_id INTEGER,
|
||||
create_time INTEGER, update_time INTEGER
|
||||
)');
|
||||
Db::execute('CREATE TABLE zyt_tcm_prescription_order_pay_order (id INTEGER PRIMARY KEY, prescription_order_id INTEGER, pay_order_id INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_pharmacy_submission_claim (id INTEGER PRIMARY KEY, prescription_order_id INTEGER, source_revision INTEGER, status TEXT)');
|
||||
Db::execute('CREATE TABLE zyt_tcm_prescription_order_log (id INTEGER PRIMARY KEY, prescription_order_id INTEGER,
|
||||
admin_id INTEGER, admin_name TEXT, action TEXT, summary TEXT, create_time INTEGER)');
|
||||
Db::name('admin')->insert(['id' => 1, 'name' => '测试医师']);
|
||||
$sql = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_17_prescription_esign.sql')
|
||||
. file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_19_doctor_esign_identity.sql')
|
||||
@@ -269,12 +279,13 @@ namespace {
|
||||
}
|
||||
Db::execute('CREATE UNIQUE INDEX uk_doctor ON zyt_doctor_esign_account(doctor_id,environment,app_id)');
|
||||
Db::execute('ALTER TABLE zyt_prescription_esign ADD review_required INTEGER NOT NULL DEFAULT 0');
|
||||
$new = static function (int $id): void {
|
||||
$new = static function (int $id, bool $uploaded = true): void {
|
||||
Db::name('tcm_prescription')->insert([
|
||||
'id' => $id, 'sn' => 'RX-TEST-' . $id, 'creator_id' => 1, 'doctor_name' => '测试医师',
|
||||
'patient_name' => '虚构测试患者', 'gender' => 1, 'age' => 30, 'phone' => '13800000000',
|
||||
'clinical_diagnosis' => '仅用于软件测试', 'herbs' => json_encode([['name' => '测试药材', 'dosage' => 10, 'unit' => 'g']], JSON_UNESCAPED_UNICODE),
|
||||
'prescription_date' => '2026-11-17', 'esign_required' => 1, 'esign_status' => 'pending', 'void_status' => 0,
|
||||
'review_submitted_at' => $uploaded ? time() : 0,
|
||||
]);
|
||||
};
|
||||
$new(1);
|
||||
@@ -700,7 +711,7 @@ namespace {
|
||||
48 => ['clinical_diagnosis' => ''],
|
||||
];
|
||||
foreach ($legacyCases as $id => $values) {
|
||||
$new($id);
|
||||
$new($id, false);
|
||||
Db::name('tcm_prescription')->where('id', $id)->update($values + [
|
||||
'esign_required' => 0, 'esign_status' => 'legacy', 'audit_status' => 0,
|
||||
'doctor_signature' => 'original-handwritten-signature',
|
||||
@@ -713,6 +724,15 @@ namespace {
|
||||
Service::assertSignedById(41, true);
|
||||
$assert(!$disabled['enabled'] && !$disabled['required'] && $disabled['status'] === 'legacy' && !$disabled['can_sign'],
|
||||
'disabled rollout keeps an unenrolled pending prescription compatible');
|
||||
$assert($disabled['can_submit_for_review'] === true && $disabled['review_submitted_at'] === 0,
|
||||
'prescriptions created without required e-sign can still be submitted');
|
||||
$legacySubmission = PrescriptionLogic::submitForReview(47, 1, $root);
|
||||
$assert($legacySubmission['review_submitted_at'] > 0 && $legacySubmission['can_submit_for_review'] === false,
|
||||
'legacy submission records the first upload under existing signature configuration');
|
||||
$assert(Service::status(47, 2, $root)['can_review_prescription']
|
||||
&& PrescriptionLogic::audit(47, 'reject', '测试驳回', 1, $root)
|
||||
&& (int) Db::name('tcm_prescription')->where('id', 47)->value('void_status') === 1,
|
||||
'an uploaded handwritten prescription is reviewable while eSign is disabled');
|
||||
$alreadyEnrolled = Service::status(5, 1, $root);
|
||||
$assert($alreadyEnrolled['required'] && !$alreadyEnrolled['can_sign']
|
||||
&& str_contains($alreadyEnrolled['message'], '尚未启用'), 'disabled rollout explains blocked enrolled signing');
|
||||
@@ -720,27 +740,38 @@ namespace {
|
||||
$config->set($settings, 'esign');
|
||||
$draft = Db::name('tcm_prescription')->find(41);
|
||||
$pending = Service::status(41, 1, $root);
|
||||
$assert($pending['required'] && $pending['status'] === 'pending' && $pending['can_sign']
|
||||
&& !$pending['can_resume_identity'], 'unenrolled pending prescription enters eSign for its doctor');
|
||||
$assert($pending['required'] && $pending['status'] === 'pending' && !$pending['can_sign']
|
||||
&& $pending['awaiting_upload'] && $pending['can_submit_for_review'] && !$pending['can_review_prescription']
|
||||
&& !$pending['can_resume_identity'], 'unenrolled pending prescription offers upload before eSign');
|
||||
$other = Service::status(41, 2, $root);
|
||||
$assert($other['required'] && !$other['can_sign'] && str_contains($other['message'], '开方医生'),
|
||||
'auditor can see that the doctor needs to sign');
|
||||
$assert($other['required'] && !$other['can_sign'] && $other['awaiting_upload'] && !$other['can_submit_for_review']
|
||||
&& !$other['can_review_prescription'] && str_contains($other['message'], '上传处方'),
|
||||
'auditor can see that the doctor needs to upload');
|
||||
$throws(fn () => Service::start(41, 2, $root), 'auditor cannot enroll a different doctor’s pending prescription');
|
||||
$assert(Service::identityStatus(41, 1, $root)['identity_status'] === 'UNAVAILABLE',
|
||||
'pending legacy identity status waits for enrollment');
|
||||
$throws(fn () => Service::complete(41, 1, $root), 'unenrolled draft cannot complete signing before starting');
|
||||
$startsBeforeUpload = Fake::$starts;
|
||||
$throws(fn () => Service::start(41, 1, $root), 'doctor cannot start prescription signing before upload');
|
||||
$throws(fn () => Service::identityStatus(41, 1, $root), 'identity status cannot resume before upload');
|
||||
$throws(fn () => Service::complete(41, 1, $root), 'doctor cannot complete signing before upload');
|
||||
$assert(PrescriptionLogic::audit(41, 'approve', '', 1, $root) === false
|
||||
&& str_contains(PrescriptionLogic::getError(), '电子签署'), 'manual approval blocks an unenrolled pending prescription');
|
||||
&& str_contains(PrescriptionLogic::getError(), '上传处方'), 'manual approval blocks an unsubmitted prescription');
|
||||
$assert(PrescriptionOrderLogic::auditPrescription(41, 'approve', '', 1, $root) === false
|
||||
&& str_contains(PrescriptionOrderLogic::getError(), '电子签署')
|
||||
&& str_contains(PrescriptionOrderLogic::getError(), '上传处方')
|
||||
&& (int) Db::name('tcm_prescription_order')->where('id', 41)->value('prescription_audit_status') === 0,
|
||||
'business order approval blocks an unenrolled pending prescription');
|
||||
'business order approval blocks an unsubmitted prescription');
|
||||
$throws(fn () => PrescriptionLogic::submitForReview(41, 2, $root), 'another doctor cannot upload on behalf of the owner');
|
||||
$throws(fn () => PrescriptionLogic::submitForReview(42, 1, $root), 'closed historical prescription cannot get a new upload timestamp');
|
||||
$throws(fn () => PrescriptionLogic::submitForReview(44, 1, $root), 'system-generated blank prescription cannot upload');
|
||||
$throws(fn () => PrescriptionLogic::submitForReview(45, 1, $root), 'voided prescription cannot upload');
|
||||
$throws(fn () => PrescriptionLogic::submitForReview(46, 1, $root), 'deleted prescription cannot upload');
|
||||
$throws(fn () => PrescriptionLogic::submitForReview(48, 1, $root), 'a prescription awaiting eSign must have a clinical diagnosis before upload');
|
||||
$assert($draft === Db::name('tcm_prescription')->find(41)
|
||||
&& !Db::name('prescription_esign')->where('prescription_id', 41)->find(), 'status and audit checks never enroll or change the draft');
|
||||
&& Fake::$starts === $startsBeforeUpload && !Db::name('prescription_esign')->where('prescription_id', 41)->find(),
|
||||
'blocked checks neither contact the signing provider nor change the draft');
|
||||
|
||||
foreach ([42, 43, 45, 46] as $id) {
|
||||
$historical = Service::describe(Db::name('tcm_prescription')->find($id), 1);
|
||||
$assert(!$historical['required'] && $historical['status'] === 'legacy' && !$historical['can_sign'],
|
||||
$assert(!$historical['required'] && $historical['status'] === 'legacy' && !$historical['can_sign']
|
||||
&& !$historical['awaiting_upload'] && !$historical['can_review_prescription'],
|
||||
'approved, rejected, voided and deleted legacy cases are never auto-enrolled');
|
||||
$throws(fn () => Service::start($id, 1, $root), 'closed historical prescription cannot be enrolled by signing');
|
||||
}
|
||||
@@ -752,9 +783,32 @@ namespace {
|
||||
$throws(fn () => Service::start(48, 1, $root), 'invalid legacy contents fail before enrollment');
|
||||
$assert((int) Db::name('tcm_prescription')->where('id', 48)->value('esign_required') === 0
|
||||
&& !Db::name('prescription_esign')->where('prescription_id', 48)->find(), 'failed preparation keeps the draft unmodified');
|
||||
$assert(PrescriptionLogic::audit(47, 'reject', '测试驳回', 1, $root)
|
||||
&& (int) Db::name('tcm_prescription')->where('id', 47)->value('void_status') === 1,
|
||||
'unsigned pending prescription remains correctable through rejection');
|
||||
$submission = PrescriptionLogic::submitForReview(41, 1, $root);
|
||||
$assert($submission['review_submitted_at'] > 0 && $submission['can_submit_for_review'] === false
|
||||
&& PrescriptionLogic::submitForReview(41, 1, $root) === $submission,
|
||||
'doctor upload persists once before signing and is idempotent');
|
||||
$uploaded = Service::status(41, 1, $root);
|
||||
$assert($uploaded['can_sign'] && !$uploaded['awaiting_upload'] && !$uploaded['can_review_prescription']
|
||||
&& !$uploaded['can_submit_for_review'] && $uploaded['review_submitted_at'] === $submission['review_submitted_at'],
|
||||
'upload enables doctor signing while the prescription remains unavailable for review');
|
||||
$pendingList = static fn () => new class($root) extends PrescriptionLists {
|
||||
public function __construct(array $adminInfo)
|
||||
{
|
||||
$this->adminId = 1;
|
||||
$this->adminInfo = $adminInfo;
|
||||
$this->params = ['audit_filter' => 'pending'];
|
||||
$this->searchWhere = [['id', 'in', [41, 42, 44, 48]]];
|
||||
$this->limitOffset = 0;
|
||||
$this->limitLength = 20;
|
||||
}
|
||||
};
|
||||
$list = $pendingList();
|
||||
$assert($list->count() === 0 && $list->lists() === [],
|
||||
'pending review filter excludes uploaded but unsigned prescriptions from both results and count');
|
||||
$assert(PrescriptionLogic::audit(41, 'reject', '测试驳回', 1, $root) === false
|
||||
&& str_contains(PrescriptionLogic::getError(), '电子签署')
|
||||
&& PrescriptionOrderLogic::auditPrescription(41, 'reject', '测试驳回', 1, $root) === false
|
||||
&& str_contains(PrescriptionOrderLogic::getError(), '电子签署'), 'existing review entry points require doctor signature after upload');
|
||||
|
||||
$started = Service::start(41, 1, $root);
|
||||
$frozen = Db::name('tcm_prescription')->find(41);
|
||||
@@ -764,10 +818,32 @@ namespace {
|
||||
&& $evidence['snapshot_hash'] === Policy::hash($draft) && is_file($dir . '/pdf/' . $evidence['source_path']),
|
||||
'starting eSign freezes the same prescription and preserves its handwritten data');
|
||||
$throws(fn () => Policy::assertMutable($frozen), 'newly enrolled draft is frozen before approval');
|
||||
$assert(Service::complete(41, 1, $root)['status'] === 'signed', 'the enrolled doctor can sign the existing prescription');
|
||||
$signedStatus = Service::complete(41, 1, $root);
|
||||
$signedRx = PrescriptionLogic::withSigningStatus(Db::name('tcm_prescription')->find(41), 2, false);
|
||||
$assert($signedStatus['status'] === 'signed' && $signedStatus['can_review_prescription']
|
||||
&& $signedRx['can_review_prescription'] && $signedRx['esign']['can_review_prescription']
|
||||
&& !$signedStatus['can_submit_for_review'] && $signedStatus['review_submitted_at'] === $submission['review_submitted_at']
|
||||
&& (int) $signedRx['audit_status'] === 0, 'verified signing makes the existing upload available for review without approving it');
|
||||
$list = $pendingList();
|
||||
$assert($list->count() === 1 && array_map('intval', array_column($list->lists(), 'id')) === [41],
|
||||
'pending review filter includes the signed prescription in the actual page and count');
|
||||
$archivePath = $dir . '/pdf/' . Db::name('prescription_esign')->where('prescription_id', 41)->value('signed_path');
|
||||
$archived = file_get_contents($archivePath);
|
||||
file_put_contents($archivePath, $archived . 'changed');
|
||||
$assert(!Service::status(41, 1, $root)['can_review_prescription']
|
||||
&& !PrescriptionOrderLogic::withReviewAvailability(['prescription_audit_status' => 0],
|
||||
Db::name('tcm_prescription')->find(41))['can_review_prescription']
|
||||
&& !PrescriptionLogic::audit(41, 'reject', '测试驳回', 1, $root)
|
||||
&& !PrescriptionOrderLogic::auditPrescription(41, 'approve', '', 1, $root),
|
||||
'a missing or modified original blocks review status and mutations');
|
||||
$assert(!$pendingList()->lists()[0]['can_review_prescription'],
|
||||
'a row with a stored signed state still needs an intact archive to allow review');
|
||||
file_put_contents($archivePath, $archived);
|
||||
$assert(PrescriptionLogic::audit(41, 'approve', '', 1, $root)
|
||||
&& (int) Db::name('tcm_prescription')->where('id', 41)->value('audit_status') === 1,
|
||||
'the same prescription can be approved after verified eSign');
|
||||
$assert(PrescriptionLogic::submitForReview(41, 1, $root) === $submission,
|
||||
'a retry after approval still returns the existing upload receipt');
|
||||
$throws(fn () => Service::assertSignedById(41, true), 'sandbox enrollment permits approval but still blocks formal dispensing');
|
||||
|
||||
$new(49);
|
||||
@@ -797,6 +873,7 @@ namespace {
|
||||
$before = Fake::$signs;
|
||||
$assert(Service::retryVerification(49, 2, $root)['status'] === 'signed' && Fake::$signs === $before,
|
||||
'archive verification uses the frozen signer after configuration changes without signing again');
|
||||
PrescriptionLogic::submitForReview(49, 2, $root);
|
||||
$assert(PrescriptionLogic::audit(49, 'approve', '', 1, $root)
|
||||
&& !empty(Service::download(49, 2, $root)['sha256']), 'verified alias prescription can be audited and downloaded');
|
||||
$assert(PrescriptionLogic::consumeLastAuditWecomNotify() === null, 'a sandbox audit does not send a live WeCom notification');
|
||||
@@ -897,7 +974,6 @@ namespace {
|
||||
Db::execute('INSERT INTO zyt_doctor_appointment VALUES (40, 10, 1, 3)');
|
||||
Db::execute('CREATE TABLE zyt_doctor_note (id INTEGER PRIMARY KEY, diagnosis_id INTEGER, delete_time INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_diagnosis_view_records (id INTEGER PRIMARY KEY, diagnosis_id INTEGER, user_id INTEGER, delete_time INTEGER)');
|
||||
Db::execute('CREATE TABLE zyt_pharmacy_submission_claim (id INTEGER PRIMARY KEY, prescription_order_id INTEGER, source_revision INTEGER, status TEXT)');
|
||||
Db::execute('CREATE TABLE zyt_doctor_medicine (id INTEGER PRIMARY KEY, name TEXT, status INTEGER, delete_time INTEGER)');
|
||||
Db::execute("INSERT INTO zyt_doctor_medicine VALUES (1, '测试药材', 1, NULL)");
|
||||
|
||||
@@ -908,8 +984,11 @@ namespace {
|
||||
$permissionAlias = new \ReflectionMethod(AuthMiddleware::class, 'matchPermissionAlias');
|
||||
foreach (PrescriptionLogic::PRESCRIBE_PERMISSIONS as $grant) {
|
||||
$assert($permissionAlias->invoke(new AuthMiddleware(), 'tcm.prescription/void', [$grant]), 'prescribing grants permit the void route');
|
||||
$assert($permissionAlias->invoke(new AuthMiddleware(), 'tcm.prescription/submitforreview', [$grant]), 'prescribing grants permit the upload route');
|
||||
}
|
||||
$assert(!$permissionAlias->invoke(new AuthMiddleware(), 'tcm.prescription/void', ['cf.prescription/lists']), 'read permission grants no void route');
|
||||
$assert(!$permissionAlias->invoke(new AuthMiddleware(), 'tcm.prescription/submitforreview', ['cf.prescription/lists']), 'read permission grants no upload route');
|
||||
$throws(fn () => PrescriptionLogic::submitForReview(41, 3, $readOnly), 'read-only accounts cannot upload prescriptions');
|
||||
$assert(PrescriptionLogic::detail(2, 1, $doctor)['can_void'], 'creator can void signed prescription through detail');
|
||||
$appointmentPrescription = PrescriptionLogic::getByAppointment(40, 1, $doctor);
|
||||
$assert((int) $appointmentPrescription['id'] === 2 && $appointmentPrescription['can_void'] === true
|
||||
@@ -966,10 +1045,38 @@ namespace {
|
||||
&& (int) $reissued['audit_status'] === 0 && Db::name('prescription_esign')->where('prescription_id', $newId)->count() === 0,
|
||||
'reissue gets a new serial number and its own pending signature and audit');
|
||||
if ($previousState === 'pending') {
|
||||
Db::name('tcm_prescription')->where('id', $newId)->update(['esign_required' => 0, 'esign_status' => 'legacy']);
|
||||
Db::name('tcm_prescription')->where('id', $newId)->update([
|
||||
'esign_required' => 0, 'esign_status' => 'legacy', 'is_system_auto' => 1, 'herbs' => '[]',
|
||||
]);
|
||||
Db::name('tcm_prescription_order')->insert([
|
||||
'id' => 2041, 'prescription_id' => $newId, 'fulfillment_status' => 1,
|
||||
'prescription_audit_status' => 0, 'payment_slip_audit_status' => 1,
|
||||
]);
|
||||
$assert(!PrescriptionLogic::detail($newId, 1, $doctor)['can_void']
|
||||
&& !PrescriptionLogic::void($newId, 1, $doctor, pendingOnly: true),
|
||||
'an approved payment audit still blocks void from the issued list');
|
||||
Db::name('tcm_prescription_order')->where('id', 2041)->update(['payment_slip_audit_status' => 0]);
|
||||
$linkedBefore = Db::name('tcm_prescription_order')->find(2041);
|
||||
$assert(PrescriptionLogic::detail($newId, 1, $doctor)['can_void'],
|
||||
'blank pending prescription can be voided before either linked order audit');
|
||||
}
|
||||
$assert(PrescriptionLogic::void($newId, 1, $doctor) && !PrescriptionLogic::edit(['id' => $newId], 1),
|
||||
if ($previousState === 'signed') {
|
||||
Db::name('tcm_prescription')->where('id', $newId)->update(['audit_status' => 1]);
|
||||
$assert(!PrescriptionLogic::void($newId, 1, $doctor, pendingOnly: true)
|
||||
&& str_contains(PrescriptionLogic::getError(), '审核状态已变化')
|
||||
&& (int) Db::name('tcm_prescription')->where('id', $newId)->value('void_status') === 0,
|
||||
'a stale issued-list action cannot void a prescription that has since been approved');
|
||||
Db::name('tcm_prescription')->where('id', $newId)->update(['audit_status' => 0]);
|
||||
}
|
||||
$assert(PrescriptionLogic::void($newId, 1, $doctor, pendingOnly: true) && !PrescriptionLogic::edit(['id' => $newId], 1),
|
||||
'a manually voided record cannot be edited back into use');
|
||||
if ($previousState === 'pending') {
|
||||
$assert(Db::name('tcm_prescription_order')->find(2041) === $linkedBefore
|
||||
&& PrescriptionOrderLogic::auditPrescription(2041, 'approve', '', 1, $root) === false,
|
||||
'void preserves the linked order and blocks order approval on the voided prescription');
|
||||
$throws(fn () => Service::assertSignedById($newId, true),
|
||||
'voided handwritten prescription cannot be dispatched through a linked order');
|
||||
}
|
||||
$oldId = $newId;
|
||||
}
|
||||
$auditRejected = ['audit_status' => 2, 'void_status' => 1, 'audit_time' => 100, 'void_time' => 100,
|
||||
@@ -1096,6 +1203,13 @@ namespace {
|
||||
Fake::$expiredWillingness = false;
|
||||
$new(88);
|
||||
Service::start(88, 1, $doctor);
|
||||
Db::name('tcm_prescription')->where('id', 88)->update(['audit_status' => 0, 'review_submitted_at' => 0]);
|
||||
$inFlight = Service::status(88, 1, $doctor);
|
||||
$assert($inFlight['can_submit_for_review'] && !$inFlight['can_resume_identity'] && !isset($inFlight['auth_url']),
|
||||
'a signing session prepared before upload is gated until the doctor uploads');
|
||||
$throws(fn () => Service::complete(88, 1, $doctor), 'a pre-existing signing session cannot confirm without upload');
|
||||
PrescriptionLogic::submitForReview(88, 1, $doctor);
|
||||
$assert(Service::status(88, 1, $doctor)['can_resume_identity'], 'upload unlocks a retained doctor signing session');
|
||||
Db::name('doctor_esign_account')->where('doctor_id', 1)->update(['account_id' => 'replacement-account']);
|
||||
Db::name('doctor_esign_quicksign')->where('doctor_id', 1)->update([
|
||||
'account_id' => 'replacement-account', 'flow_id' => 'replacement-grant',
|
||||
@@ -1108,19 +1222,60 @@ namespace {
|
||||
'renewed authorization can prepare an existing prescription without automatic signing');
|
||||
|
||||
$config->set(['review_enabled' => true] + $config->get('esign'), 'esign');
|
||||
Db::name('tcm_prescription')->where('id', 84)->update(['audit_status' => 0]);
|
||||
Db::name('tcm_prescription')->where('id', 84)->update(['audit_status' => 0, 'review_submitted_at' => 0]);
|
||||
Db::name('admin')->insert(['id' => 22, 'name' => '测试审核人', 'root' => 1]);
|
||||
Db::name('admin')->insert(['id' => 23, 'name' => '另一位测试审核人', 'root' => 1]);
|
||||
Db::name('admin')->insert(['id' => 23, 'name' => '另一位测试审核人']);
|
||||
Db::name('admin')->insert(['id' => 24, 'name' => '仅查看订单']);
|
||||
$orderAuditMenu = Db::name('system_menu')->insertGetId(['perms' => Review::ORDER_PERMISSION]);
|
||||
Db::name('system_role_menu')->insert(['role_id' => 3, 'menu_id' => $orderAuditMenu]);
|
||||
Db::name('admin_role')->insert(['admin_id' => 23, 'role_id' => 3]);
|
||||
$auditor = ['root' => 1, 'admin_id' => 22, 'name' => '测试审核人'];
|
||||
$otherAuditor = ['root' => 1, 'admin_id' => 23, 'name' => '另一位测试审核人'];
|
||||
$otherAuditor = ['root' => 0, 'admin_id' => 23, 'name' => '另一位测试审核人', 'role_id' => [3]];
|
||||
$reviewerAccount = ['doctor_id' => 22, 'environment' => 'sandbox', 'app_id' => 'fixture',
|
||||
'doctor_name' => '测试审核人', 'account_id' => 'reviewer-account'];
|
||||
Db::name('doctor_esign_account')->insert($reviewerAccount + ['create_time' => time()]);
|
||||
Db::name('doctor_esign_quicksign')->insert($reviewerAccount + [
|
||||
'flow_id' => 'stored-reviewer-authorization', 'expires_at' => time() + 3600, 'flow_started_at' => time(),
|
||||
]);
|
||||
$new(89, false);
|
||||
Db::name('tcm_prescription')->where('id', 89)->update(['esign_required' => 0, 'esign_status' => 'legacy', 'audit_status' => 0]);
|
||||
Db::name('tcm_prescription_order')->insert(['id' => 89, 'prescription_id' => 89, 'prescription_audit_status' => 0, 'fulfillment_status' => 0]);
|
||||
$waitingForDoctor = Review::status(89, 89, 22, $auditor);
|
||||
$assert($waitingForDoctor['required'] && !$waitingForDoctor['can_setup']
|
||||
&& !$waitingForDoctor['can_confirm'] && !$waitingForDoctor['can_approve']
|
||||
&& str_contains($waitingForDoctor['message'], '上传处方'),
|
||||
'order audit and reviewer signing wait for the doctor to upload');
|
||||
$throws(fn () => Review::confirm(89, 89, 22, $auditor, false), 'reviewer cannot sign an unenrolled pending prescription');
|
||||
PrescriptionLogic::submitForReview(89, 1, $doctor);
|
||||
$waitingForSignature = Review::status(89, 89, 22, $auditor);
|
||||
$assert($waitingForSignature['required'] && !$waitingForSignature['can_setup'] && !$waitingForSignature['can_confirm']
|
||||
&& !$waitingForSignature['can_approve'] && str_contains($waitingForSignature['message'], '有效电子签署'),
|
||||
'an uploaded prescription still needs the doctor signature to enter pharmacist review');
|
||||
$assert(!Db::name('prescription_esign')->where('prescription_id', 89)->find() && Fake::$reviewCalls === [],
|
||||
'order reviewer setup and status checks leave the pending prescription untouched');
|
||||
$original = Service::download(84, 22, $auditor);
|
||||
Db::name('tcm_prescription_order')->insert(['id' => 84, 'prescription_id' => 84, 'creator_id' => 24,
|
||||
'prescription_audit_status' => 0, 'fulfillment_status' => 0]);
|
||||
$assert(!PrescriptionOrderLogic::withReviewAvailability(['prescription_audit_status' => 0], Db::name('tcm_prescription')->find(84))['can_review_prescription'],
|
||||
'signed order prescription remains unavailable for review before upload');
|
||||
$assert(PrescriptionLogic::audit(84, 'reject', '测试驳回', 22, $auditor) === false
|
||||
&& str_contains(PrescriptionLogic::getError(), '上传处方'), 'direct rejection requires upload');
|
||||
$assert(PrescriptionOrderLogic::auditPrescription(84, 'reject', '测试驳回', 23, $otherAuditor) === false
|
||||
&& str_contains(PrescriptionOrderLogic::getError(), '上传处方'), 'business rejection requires upload');
|
||||
foreach ([1, 2] as $status) {
|
||||
$assert(PrescriptionOrderLogic::addLog(['id' => 84, 'summary' => '测试审批', 'prescription_audit_status' => $status], 23, $otherAuditor) === false
|
||||
&& str_contains(PrescriptionOrderLogic::getError(), '上传处方'), 'manual business audit changes require upload');
|
||||
}
|
||||
$throws(fn () => Review::confirm(84, 0, 22, $auditor, false), 'signed prescription still cannot receive a pharmacist signature before upload');
|
||||
$submitted = PrescriptionLogic::submitForReview(84, 1, $doctor);
|
||||
$assert($submitted['review_submitted_at'] > 0 && PrescriptionOrderLogic::withReviewAvailability(
|
||||
['prescription_audit_status' => 0], Db::name('tcm_prescription')->find(84)
|
||||
)['can_review_prescription'] === true && Service::download(84, 22, $auditor) === $original,
|
||||
'a pre-existing signed archive becomes available for review after upload without changing its evidence');
|
||||
$throws(fn () => Service::assertSignedById(84, false, 22), 'doctor signature alone cannot approve');
|
||||
$assert(!Review::status(84, 84, 23, $otherAuditor)['can_approve']
|
||||
&& PrescriptionOrderLogic::auditPrescription(84, 'approve', '', 23, $otherAuditor) === false,
|
||||
'business order remains blocked while there is only one signature');
|
||||
$throws(fn () => Review::confirm(84, 0, 1, $root, false), 'prescriber cannot review their own prescription');
|
||||
$assert(Review::status(84, 0, 22, $auditor)['can_confirm'] && Fake::$reviewCalls === [],
|
||||
'opening the audit verifies access without signing');
|
||||
@@ -1129,6 +1284,21 @@ namespace {
|
||||
$assert($attempt['state'] === 'uncertain' && $attempt['can_retry_verify']
|
||||
&& Fake::$reviewCalls === [['reviewer-account', 'stored-reviewer-authorization', $original['sha256']]],
|
||||
'review uses only reviewer authorization and the original PDF, and retains the signed result on a verification failure');
|
||||
$pendingLog = array_column(Service::status(84, 22, $auditor)['signing_log'], 'event');
|
||||
$assert(in_array('review_confirmed', $pendingLog, true) && in_array('review_uncertain', $pendingLog, true)
|
||||
&& !in_array('review_signed', $pendingLog, true), 'pending verification logs confirmation and the exception without certifying a signature');
|
||||
$reviewRow = Db::name('tcm_prescription')->where('id', 84)->find();
|
||||
$uncertainSummary = Service::describe($reviewRow, 22);
|
||||
$assert($uncertainSummary['review_state'] === 'uncertain' && !isset($uncertainSummary['review_signature_time']),
|
||||
'list reports uncertain pharmacist signing without treating the doctor signature as dual signing');
|
||||
$storedReview = Db::name('prescription_review_esign')->where('prescription_id', 84)->find();
|
||||
foreach ([['failed', time(), 'failed'], ['verifying', time(), 'verifying'], ['signing', time() - 3600, 'uncertain']] as [$state, $updated, $expected]) {
|
||||
Db::name('prescription_review_esign')->where('prescription_id', 84)->update(['state' => $state, 'update_time' => $updated]);
|
||||
$assert(Service::describe($reviewRow, 22)['review_state'] === $expected, "list reports pharmacist $state as $expected");
|
||||
}
|
||||
Db::name('prescription_review_esign')->where('prescription_id', 84)->update([
|
||||
'state' => $storedReview['state'], 'update_time' => $storedReview['update_time'],
|
||||
]);
|
||||
$assert(Service::download(84, 22, $auditor) === $original, 'a pending verification never replaces the original download');
|
||||
$throws(fn () => Review::confirm(84, 0, 23, $otherAuditor, true), 'another reviewer cannot recover or reuse the operation');
|
||||
$throws(fn () => Review::confirm(84, 0, 22, $auditor, false), 'a provider result that is already archived must not sign again');
|
||||
@@ -1136,20 +1306,85 @@ namespace {
|
||||
$result = Review::confirm(84, 0, 22, $auditor, true);
|
||||
$assert($result['state'] === 'signed' && $result['can_approve'] && count(Fake::$reviewCalls) === 1,
|
||||
'retry verifies the archived doctor and reviewer signatures without resubmitting the PDF to the signer');
|
||||
$listMetadata = Service::describe($reviewRow, 22);
|
||||
$assert($listMetadata['review_required'] && $listMetadata['review_state'] === 'signed'
|
||||
&& $listMetadata['review_signature_time'] === $result['signature_time'] && !isset($listMetadata['review_signature'])
|
||||
&& !isset($listMetadata['signing_log']), 'list metadata omits the image and signing log');
|
||||
$combined = Service::download(84, 22, $auditor);
|
||||
$expectedSeal = Fake::$reviewSignatures[$combined['sha256']][0]['sealData'];
|
||||
$reviewMetadata = Service::status(84, 22, $auditor);
|
||||
$assert($reviewMetadata['review_signature'] === 'data:image/png;base64,' . $expectedSeal
|
||||
&& $reviewMetadata['review_signature_time'] === $result['signature_time'],
|
||||
'status exposes the matched reviewer PNG and credible timestamp');
|
||||
$sealFiles = glob($dir . '/pdf/84-*/review-seal-*.png') ?: [];
|
||||
$assert(count($sealFiles) === 1, 'signature verification caches the matched image');
|
||||
unlink($sealFiles[0]);
|
||||
$restoredMetadata = Service::status(84, 22, $auditor);
|
||||
$assert($restoredMetadata['review_signature'] === $reviewMetadata['review_signature'] && count(Fake::$reviewCalls) === 1,
|
||||
'an older archive recovers its actual reviewer PNG without a new signature');
|
||||
$assert(str_ends_with($combined['filename'], '-dual-signed.pdf') && $combined['sha256'] !== $original['sha256']
|
||||
&& str_starts_with(base64_decode($combined['content_base64']), base64_decode($original['content_base64'])),
|
||||
'download returns the verified incremental dual-signed PDF');
|
||||
$throws(fn () => Service::assertSignedById(84, false, 23), 'one reviewer cannot approve with another reviewer signature');
|
||||
$throws(fn () => Service::assertSignedById(84, true), 'the dual-signed sandbox prescription remains blocked from dispensing');
|
||||
$assert(PrescriptionLogic::audit(84, 'approve', '', 22, $auditor)
|
||||
&& (int) Db::name('tcm_prescription')->where('id', 84)->value('audit_by') === 22,
|
||||
'the second signer can approve with the verified dual signature');
|
||||
$assert(!Review::status(84, 0, 23, $otherAuditor)['can_approve']
|
||||
&& !PrescriptionLogic::audit(84, 'approve', '', 23, $otherAuditor),
|
||||
'the independent prescription audit still requires the pharmacist who signed');
|
||||
$viewer = ['root' => 0, 'admin_id' => 24, 'name' => '仅查看订单'];
|
||||
$assert(!Review::status(84, 84, 24, $viewer)['can_approve']
|
||||
&& PrescriptionOrderLogic::auditPrescription(84, 'approve', '', 24, $viewer) === false,
|
||||
'ownership alone does not authorize order approval');
|
||||
$orderReview = Review::status(84, 84, 23, $otherAuditor);
|
||||
$assert($orderReview['can_approve'] && !$orderReview['can_confirm'] && !$orderReview['can_setup']
|
||||
&& $orderReview['signer_name'] === $result['signer_name'],
|
||||
'an authorized order auditor can approve the verified signatures without another signing identity');
|
||||
Db::name('system_menu')->where('id', $orderAuditMenu)->update(['is_disable' => 1]);
|
||||
$assert(!Review::status(84, 84, 23, $otherAuditor)['can_approve']
|
||||
&& PrescriptionOrderLogic::auditPrescription(84, 'approve', '', 23, $otherAuditor) === false,
|
||||
'a disabled order audit grant blocks a previously eligible submitter');
|
||||
Db::name('system_menu')->where('id', $orderAuditMenu)->update(['is_disable' => 0]);
|
||||
$archive = glob($dir . '/pdf/84-*/review-signed.pdf')[0];
|
||||
$archivedBytes = file_get_contents($archive);
|
||||
file_put_contents($archive, $archivedBytes . 'modified');
|
||||
$assert(PrescriptionOrderLogic::auditPrescription(84, 'approve', '', 23, $otherAuditor) === false
|
||||
&& (int) Db::name('tcm_prescription_order')->where('id', 84)->value('prescription_audit_status') === 0,
|
||||
'a changed dual-sign PDF is refused under the order approval transaction');
|
||||
file_put_contents($archive, $archivedBytes);
|
||||
$order = PrescriptionOrderLogic::auditPrescription(84, 'approve', '', 23, $otherAuditor);
|
||||
$assert($order !== false && (int) $order['prescription_audit_status'] === 1
|
||||
&& (int) $order['payment_slip_audit_status'] === 0
|
||||
&& (int) Db::name('tcm_prescription')->where('id', 84)->value('audit_by') === 23
|
||||
&& (int) Db::name('tcm_prescription_order_log')->where('prescription_order_id', 84)->value('admin_id') === 23,
|
||||
'order approval records the actual submitter and synchronizes the prescription without approving payment');
|
||||
$assert(Service::download(84, 22, $auditor) === $combined && count(Fake::$reviewCalls) === 1,
|
||||
'order approval preserves the pharmacist signature and archived original');
|
||||
$signedLog = Service::status(84, 22, $auditor)['signing_log'];
|
||||
$events = array_column($signedLog, null, 'event');
|
||||
$times = array_column($signedLog, 'time');
|
||||
$ordered = $times;
|
||||
sort($ordered);
|
||||
$assert($times === $ordered && isset($events['issued'], $events['doctor_verified'], $events['review_confirmed'],
|
||||
$events['review_verified'], $events['audit_approved']) && !isset($events['review_uncertain']),
|
||||
'signed history orders recorded milestones and replaces the resolved exception');
|
||||
$assert($events['doctor_signed']['time'] === $reviewMetadata['signature_time']
|
||||
&& $events['doctor_signed']['actor_name'] === $reviewMetadata['doctor_signer_name']
|
||||
&& $events['review_signed']['time'] === $result['signature_time']
|
||||
&& $events['review_signed']['actor_name'] === $result['signer_name']
|
||||
&& $events['doctor_signed']['source'] === 'tsa' && $events['review_signed']['source'] === 'tsa'
|
||||
&& $events['review_verified']['source'] === 'system',
|
||||
'signing log preserves the two verified provider times and distinguishes system milestones');
|
||||
$assert(Service::status(89, 22, $auditor)['signing_log'] === [], 'an unenrolled prescription has no fabricated events');
|
||||
$reopened = PrescriptionOrderLogic::revokeRxAudit(84, 23, $otherAuditor);
|
||||
$reopenedPrescription = Db::name('tcm_prescription')->find(84);
|
||||
$assert($reopened !== false && (int) $reopenedPrescription['review_submitted_at'] === 0
|
||||
&& !PrescriptionOrderLogic::withReviewAvailability($reopened, $reopenedPrescription)['can_review_prescription']
|
||||
&& !Review::status(84, 84, 23, $otherAuditor)['can_approve'], 'reopening requires a new doctor upload');
|
||||
file_put_contents(dirname(__DIR__, 2) . '/artifacts/esign-prescription-test.pdf', $pdf);
|
||||
echo "Prescription eSign flow: $checks checks passed (isolated SQLite, fake provider)\n";
|
||||
} finally {
|
||||
$manager->connect()->close();
|
||||
foreach (glob($dir . '/pdf/*/*.pdf') ?: [] as $file) { unlink($file); }
|
||||
foreach (glob($dir . '/pdf/*/review-seal-*.png') ?: [] as $file) { unlink($file); }
|
||||
foreach (glob($dir . '/pdf/*', GLOB_ONLYDIR) ?: [] as $folder) { rmdir($folder); }
|
||||
if (is_dir($dir . '/pdf')) { rmdir($dir . '/pdf'); }
|
||||
if (is_file($dir . '/fixture.sqlite')) { unlink($dir . '/fixture.sqlite'); }
|
||||
|
||||
@@ -7,6 +7,7 @@ require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
|
||||
use app\adminapi\logic\tcm\PrescriptionLogic;
|
||||
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
|
||||
use app\common\service\esign\PrescriptionCaSigningSettings;
|
||||
use app\common\service\esign\PrescriptionEsignService;
|
||||
use app\common\service\esign\PrescriptionEsignPolicy;
|
||||
use app\common\service\pharmacy\PharmacySubmissionClaimService;
|
||||
@@ -39,6 +40,7 @@ $expect = static function (bool $ok, string $message) use (&$checks): void {
|
||||
$checks++;
|
||||
};
|
||||
try {
|
||||
$pdo->exec('CREATE TABLE zyt_config (id INT PRIMARY KEY AUTO_INCREMENT,type VARCHAR(30),name VARCHAR(60),value TEXT,create_time INT,update_time INT)');
|
||||
$pdo->exec('CREATE TABLE zyt_tcm_prescription (
|
||||
id INT UNSIGNED PRIMARY KEY,creator_id INT,doctor_name VARCHAR(100),patient_name VARCHAR(100),phone VARCHAR(30),gender INT,
|
||||
audit_status INT DEFAULT 0,void_status INT DEFAULT 0,delete_time INT NULL,update_time INT DEFAULT 0,
|
||||
@@ -49,8 +51,12 @@ try {
|
||||
$migration = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_17_prescription_esign.sql');
|
||||
$pdo->exec($migration);
|
||||
$pdo->exec($migration);
|
||||
$submissionMigration = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_21_prescription_review_submission.sql');
|
||||
$pdo->exec($submissionMigration);
|
||||
$pdo->exec($submissionMigration);
|
||||
$row = Db::name('tcm_prescription')->find(1);
|
||||
$expect((int) $row['esign_required'] === 0 && $row['esign_status'] === 'legacy', 'migration preserves historical rows and is repeatable');
|
||||
$expect((int) $row['review_submitted_at'] === 0, 'repeatable upload migration leaves legacy records without an upload time');
|
||||
$pdo->exec("INSERT INTO zyt_tcm_prescription (id,creator_id,doctor_name,esign_required,esign_status) VALUES (2,1,'测试医师',1,'pending')");
|
||||
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_04_07_create_tcm_prescription_order.sql'));
|
||||
$pdo->exec('CREATE TABLE zyt_pharmacy_submission_claim (id INT PRIMARY KEY,prescription_order_id INT,source_revision INT,status VARCHAR(40))');
|
||||
@@ -64,8 +70,10 @@ try {
|
||||
$pdo->exec("INSERT INTO zyt_tcm_prescription (id,creator_id,doctor_name,audit_status) VALUES (3,1,'测试医师',1)");
|
||||
PrescriptionEsignService::assertSignedById(3);
|
||||
$expect(PrescriptionEsignService::describe(Db::name('tcm_prescription')->find(3), 1)['status'] === 'legacy', 'previously approved historical prescription remains on record');
|
||||
$expect(PrescriptionOrderLogic::withReviewAvailability(['prescription_audit_status' => 0], Db::name('tcm_prescription')->find(3))['can_review_prescription'],
|
||||
'an already approved historical prescription remains available to an existing order');
|
||||
$expect(PrescriptionLogic::audit(2, 'approve', '', 1, $root) === false, 'manual prescription audit rejects unsigned');
|
||||
$expect(str_contains(PrescriptionLogic::getError(), '电子签署'), 'manual audit explains signature requirement');
|
||||
$expect(str_contains(PrescriptionLogic::getError(), '上传处方'), 'manual audit explains upload requirement');
|
||||
$expect(PrescriptionOrderLogic::auditPrescription(1, 'approve', '', 1, $root) === false, 'order audit rejects unsigned before write');
|
||||
$expect((int) Db::name('tcm_prescription_order')->where('id', 1)->value('prescription_audit_status') === 0, 'order remains pending after rejection');
|
||||
$expect(PrescriptionOrderLogic::addLog(['id' => 1, 'summary' => '测试', 'prescription_audit_status' => 1], 1, $root) === false, 'manual order log cannot bypass signature requirement');
|
||||
@@ -79,6 +87,40 @@ try {
|
||||
|
||||
// Real InnoDB contention: a second connection attempts to void the very
|
||||
// prescription being approved, at the exact model before-write boundary.
|
||||
Db::name('tcm_prescription')->where('id', 2)->update(['esign_status' => 'pending', 'herbs' => '[{"name":"Fixture herb"}]',
|
||||
'clinical_diagnosis' => 'Fixture diagnosis']);
|
||||
$pdo->exec('SET SESSION innodb_lock_wait_timeout=1');
|
||||
$events = new class($pdo, $expect) {
|
||||
public int $attempts = 0;
|
||||
public function __construct(private PDO $otherConnection, private Closure $expect) {}
|
||||
public function trigger(string $event, mixed $model): array {
|
||||
if (!str_ends_with($event, '.BeforeUpdate')) { return []; }
|
||||
$this->attempts++;
|
||||
try {
|
||||
$this->otherConnection->exec('UPDATE zyt_tcm_prescription SET void_status=1 WHERE id=2');
|
||||
($this->expect)(false, 'concurrent void must wait for signature check + audit write');
|
||||
} catch (PDOException $e) {
|
||||
($this->expect)((int) ($e->errorInfo[1] ?? 0) === 1205, 'prescription row lock held at audit write');
|
||||
}
|
||||
throw new DomainException('TEST_LOCK_OBSERVED');
|
||||
}
|
||||
};
|
||||
\think\Model::setEvent($events);
|
||||
try {
|
||||
PrescriptionLogic::submitForReview(2, 1, $root);
|
||||
$expect(false, 'submission must retain its own prescription lock');
|
||||
} catch (DomainException $error) {
|
||||
$expect($error->getMessage() === 'TEST_LOCK_OBSERVED' && (int) Db::name('tcm_prescription')->where('id', 2)->value('review_submitted_at') === 0,
|
||||
'failed concurrent submission rolls back its audit timestamp');
|
||||
}
|
||||
\think\Model::setEvent(null);
|
||||
$submitted = PrescriptionLogic::submitForReview(2, 1, $root);
|
||||
$expect($submitted['review_submitted_at'] > 0 && PrescriptionLogic::submitForReview(2, 1, $root) === $submitted,
|
||||
'actual MySQL upload before signing is persisted once');
|
||||
$expect(!PrescriptionEsignService::status(2, 1, $root)['can_review_prescription']
|
||||
&& !PrescriptionOrderLogic::auditPrescription(1, 'approve', '', 1, $root)
|
||||
&& str_contains(PrescriptionOrderLogic::getError(), '电子签署'),
|
||||
'persistent eSign requirement still gates review after upload when disabled');
|
||||
Db::name('tcm_prescription')->where('id', 2)->update(['esign_status' => 'signed']);
|
||||
$snapshot = PrescriptionEsignPolicy::hash(Db::name('tcm_prescription')->find(2));
|
||||
$storage = sys_get_temp_dir() . '/zyt-' . $database;
|
||||
@@ -101,27 +143,11 @@ try {
|
||||
} catch (DomainException $e) {
|
||||
$expect(str_contains($e->getMessage(), '沙箱'), 'claim boundary enforces production signatures');
|
||||
}
|
||||
$pdo->exec('SET SESSION innodb_lock_wait_timeout=1');
|
||||
$events = new class($pdo, $expect) {
|
||||
public int $attempts = 0;
|
||||
public function __construct(private PDO $otherConnection, private Closure $expect) {}
|
||||
public function trigger(string $event, mixed $model): array {
|
||||
if (!str_ends_with($event, '.BeforeUpdate')) { return []; }
|
||||
$this->attempts++;
|
||||
try {
|
||||
$this->otherConnection->exec('UPDATE zyt_tcm_prescription SET void_status=1 WHERE id=2');
|
||||
($this->expect)(false, 'concurrent void must wait for signature check + audit write');
|
||||
} catch (PDOException $e) {
|
||||
($this->expect)((int) ($e->errorInfo[1] ?? 0) === 1205, 'prescription row lock held at audit write');
|
||||
}
|
||||
throw new DomainException('TEST_LOCK_OBSERVED');
|
||||
}
|
||||
};
|
||||
\think\Model::setEvent($events);
|
||||
$expect(PrescriptionLogic::audit(2, 'approve', '', 1, $root) === false && PrescriptionLogic::getError() === 'TEST_LOCK_OBSERVED', 'manual audit reaches locked write');
|
||||
$expect(PrescriptionOrderLogic::auditPrescription(1, 'approve', '', 1, $root) === false && PrescriptionOrderLogic::getError() === 'TEST_LOCK_OBSERVED', 'order audit reaches locked write');
|
||||
$expect(PrescriptionOrderLogic::addLog(['id' => 1, 'summary' => '测试', 'prescription_audit_status' => 1], 1, $root) === false && PrescriptionOrderLogic::getError() === 'TEST_LOCK_OBSERVED', 'manual status change reaches locked write');
|
||||
$expect($events->attempts === 3 && (int) Db::name('tcm_prescription')->where('id', 2)->value('void_status') === 0, 'all concurrent void attempts blocked');
|
||||
$expect($events->attempts === 4 && (int) Db::name('tcm_prescription')->where('id', 2)->value('void_status') === 0, 'all concurrent void attempts blocked');
|
||||
\think\Model::setEvent(null);
|
||||
Db::name('tcm_prescription_order')->where('id', 1)->update(['fulfillment_status' => 4]);
|
||||
$pdo->exec("INSERT INTO zyt_pharmacy_submission_claim VALUES (1, 1, 1, 'FAILED'), (2, 1, 2, 'PENDING')");
|
||||
@@ -129,7 +155,12 @@ try {
|
||||
'void locks and checks the latest pharmacy claim on a released order');
|
||||
Db::name('pharmacy_submission_claim')->where('id', 2)->update(['status' => 'FAILED']);
|
||||
$expect(PrescriptionLogic::void(2, 1, $root), 'void succeeds when the released order has no active claim');
|
||||
$expect(PrescriptionEsignService::download(2, 1, $root)['sha256'] === hash('sha256', $pdf), 'void preserves downloadable signed evidence');
|
||||
$pdo->exec('CREATE TABLE zyt_admin (id INT PRIMARY KEY,root INT,disable INT DEFAULT 0,delete_time INT)');
|
||||
$pdo->exec('INSERT INTO zyt_admin (id,root) VALUES (1,1)');
|
||||
PrescriptionCaSigningSettings::setEnabled(false, 1);
|
||||
$expect(!PrescriptionEsignService::enabled(), 'persistent admin flag disables CA in MySQL');
|
||||
$expect(PrescriptionEsignService::download(2, 1, $root)['sha256'] === hash('sha256', $pdf),
|
||||
'turning CA off after void preserves downloadable signed evidence');
|
||||
echo "Prescription eSign MySQL migration and business gates: $checks checks passed\n";
|
||||
} finally {
|
||||
\think\Model::setEvent(null);
|
||||
|
||||
@@ -31,6 +31,7 @@ $pdo = new PDO("mysql:host=127.0.0.1;port={$port};charset=utf8mb4", 'root', '',
|
||||
if (!$isWorker) $pdo->exec("CREATE DATABASE `{$database}` CHARACTER SET utf8mb4");
|
||||
$pdo->exec("USE `{$database}`");
|
||||
$testApp = new think\App();
|
||||
$testApp->instance('log', new Psr\Log\NullLogger());
|
||||
$manager = new DbManager();
|
||||
$manager->setConfig([
|
||||
'default' => 'mysql', 'auto_timestamp' => true, 'datetime_format' => false,
|
||||
@@ -63,6 +64,7 @@ if ($isWorker) {
|
||||
}
|
||||
|
||||
try {
|
||||
$pdo->exec('CREATE TABLE zyt_config (id INT PRIMARY KEY AUTO_INCREMENT,type VARCHAR(30),name VARCHAR(60),value TEXT,create_time INT,update_time INT)');
|
||||
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_04_07_create_tcm_prescription_order.sql'));
|
||||
$pdo->exec('ALTER TABLE zyt_tcm_prescription_order
|
||||
ADD agency_collect_amount DECIMAL(10,2) NULL, ADD paid DECIMAL(10,2) DEFAULT 0,
|
||||
@@ -76,6 +78,7 @@ try {
|
||||
audit_time INT NULL, audit_by INT NULL, audit_by_name VARCHAR(100) DEFAULT "", audit_remark VARCHAR(500) DEFAULT "",
|
||||
create_time INT DEFAULT 0, update_time INT DEFAULT 0, delete_time INT NULL
|
||||
) ENGINE=InnoDB');
|
||||
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_21_prescription_review_submission.sql'));
|
||||
$pdo->exec('CREATE TABLE zyt_order (
|
||||
id INT PRIMARY KEY AUTO_INCREMENT, order_no VARCHAR(50), patient_id INT DEFAULT 1,
|
||||
creator_id INT DEFAULT 1, order_type INT DEFAULT 3, amount DECIMAL(10,2), status INT,
|
||||
|
||||
@@ -26,6 +26,7 @@ $pdo = new PDO("mysql:host=127.0.0.1;port={$port};charset=utf8mb4", 'root', '',
|
||||
$pdo->exec("CREATE DATABASE `{$database}` CHARACTER SET utf8mb4");
|
||||
$pdo->exec("USE `{$database}`");
|
||||
$testApp = new think\App();
|
||||
$testApp->instance('log', new Psr\Log\NullLogger());
|
||||
$manager = new DbManager();
|
||||
$manager->setConfig([
|
||||
'default' => 'mysql', 'auto_timestamp' => true, 'datetime_format' => false,
|
||||
@@ -47,6 +48,7 @@ $expect = static function (bool $ok, string $message) use (&$checks): void {
|
||||
};
|
||||
|
||||
try {
|
||||
$pdo->exec('CREATE TABLE zyt_config (id INT PRIMARY KEY AUTO_INCREMENT,type VARCHAR(30),name VARCHAR(60),value TEXT,create_time INT,update_time INT)');
|
||||
$pdo->exec(file_get_contents(dirname(__DIR__) . '/database/migrations/2026_04_07_create_tcm_prescription_order.sql'));
|
||||
$pdo->exec('ALTER TABLE zyt_tcm_prescription_order
|
||||
ADD agency_collect_amount DECIMAL(10,2) NULL, ADD paid DECIMAL(10,2) DEFAULT 0,
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service\assistantservice {
|
||||
// 只截取客户端给 cURL 的 URL 和请求头,全程不创建连接。
|
||||
function curl_init($url) { $GLOBALS['requests'][] = ['url' => $url]; return count($GLOBALS['requests']) - 1; }
|
||||
function curl_setopt_array($handle, $options) { $GLOBALS['requests'][$handle] += ['headers' => $options[CURLOPT_HTTPHEADER], 'options' => $options]; return true; }
|
||||
function curl_exec($handle) {
|
||||
$callback = $GLOBALS['requests'][$handle]['options'][CURLOPT_HEADERFUNCTION];
|
||||
foreach ($GLOBALS['response_headers'] as $header) { $callback($handle, $header . "\r\n"); }
|
||||
return '{}';
|
||||
}
|
||||
function curl_getinfo($handle, $option) { return $GLOBALS['upstream_status']; }
|
||||
function curl_close($handle) {}
|
||||
}
|
||||
|
||||
namespace {
|
||||
use app\common\service\assistantservice\WecomArchiveHttp as Feed;
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
$settings = ['wecom_archive_base_url' => 'https://archive.example.invalid', 'wecom_archive_token' => str_repeat('synthetic', 5)];
|
||||
function config($key, $default = '') { return $GLOBALS['settings'][substr($key, strlen('assistant_service.'))] ?? $default; }
|
||||
$requests = [];
|
||||
$upstream_status = 200;
|
||||
$response_headers = ['HTTP/1.1 100 Continue', 'X-Archive-Tenant: ignored', 'HTTP/1.1 200 OK', 'X-Archive-Tenant: tenant-a'];
|
||||
foreach (['', '*', "one\r\nX-Test: two"] as $tenant) {
|
||||
$settings['wecom_archive_tenant'] = $tenant;
|
||||
if (Feed::configured() || Feed::page('', 1)['configured']) { throw new \RuntimeException('Invalid tenant enabled HTTP'); }
|
||||
try { Feed::accounts(); throw new \LogicException('Expected invalid configuration'); }
|
||||
catch (\RuntimeException $e) { if ($e->getMessage() !== 'WECOM_ARCHIVE') { throw $e; } }
|
||||
}
|
||||
if ($requests) { throw new \RuntimeException('Request sent without a tenant'); }
|
||||
$settings['wecom_archive_tenant'] = 'tenant-a';
|
||||
foreach (['http://archive.example.invalid', 'file:///tmp/example', 'http://localhost@archive.example.invalid',
|
||||
'http://archive.example.invalid\@localhost', 'https://example.invalid/?q=conflict'] as $url) {
|
||||
$settings['wecom_archive_base_url'] = $url;
|
||||
if (Feed::configured()) { throw new \RuntimeException('Unsafe transport accepted'); }
|
||||
try { Feed::accounts(); throw new \LogicException('Expected transport refusal'); }
|
||||
catch (\RuntimeException $e) { if ($e->getMessage() !== 'WECOM_ARCHIVE') { throw $e; } }
|
||||
}
|
||||
foreach (['http://localhost:3210', 'http://[::1]:3210', 'http://127.0.0.1:3210'] as $url) {
|
||||
$settings['wecom_archive_base_url'] = $url;
|
||||
if (!Feed::configured()) { throw new \RuntimeException('Loopback HTTP rejected'); }
|
||||
}
|
||||
Feed::accounts();
|
||||
$settings['wecom_archive_base_url'] = 'https://archive.example.invalid';
|
||||
Feed::conversations('staff-a');
|
||||
Feed::messages('chat-a');
|
||||
$upstream_status = 403;
|
||||
try { Feed::page('', 1); throw new \LogicException('Expected upstream refusal'); }
|
||||
catch (\RuntimeException $e) { if ($e->getMessage() !== 'WECOM_ARCHIVE') { throw $e; } }
|
||||
if (count($requests) !== 4) { throw new \RuntimeException('Unexpected requests'); }
|
||||
foreach ($requests as $request) {
|
||||
if (!in_array('X-Archive-Tenant: tenant-a', $request['headers'], true)
|
||||
|| !in_array('X-Archive-Feed-Token: ' . $settings['wecom_archive_token'], $request['headers'], true)) {
|
||||
throw new \RuntimeException('Missing archive service headers');
|
||||
}
|
||||
}
|
||||
if (!array_key_exists(CURLOPT_PROXY, $requests[0]['options']) || $requests[0]['options'][CURLOPT_PROXY] !== ''
|
||||
|| $requests[0]['options'][CURLOPT_FOLLOWLOCATION] !== false) { throw new \RuntimeException('Loopback transport options'); }
|
||||
$upstream_status = 200;
|
||||
foreach ([[], ['X-Archive-Tenant: tenant-b'], ['X-Archive-Tenant: tenant-a', 'X-Archive-Tenant: tenant-a'],
|
||||
['X-Archive-Tenant: tenant-a', 'HTTP/1.1 200 OK'], ['', 'X-Archive-Tenant: tenant-a']] as $headers) {
|
||||
$response_headers = array_merge(['HTTP/1.1 200 OK'], $headers);
|
||||
try { Feed::accounts(); throw new \LogicException('Expected missing or conflicting response tenant refusal'); }
|
||||
catch (\RuntimeException $e) { if ($e->getMessage() !== 'WECOM_ARCHIVE') { throw $e; } }
|
||||
}
|
||||
echo "WECOM_ARCHIVE_HTTP PASS mocked_transport=1 network=0\n";
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
// 默认仅使用内存 SQLite。可选的本机独立 MySQL 可重复验证生产迁移和旧会话唯一键。
|
||||
namespace {
|
||||
final class WorkstationClock { public static int $now; }
|
||||
}
|
||||
namespace app\adminapi\service { function time(): int { return \WorkstationClock::$now; } }
|
||||
namespace app\adminapi\logic { function time(): int { return \WorkstationClock::$now; } }
|
||||
namespace app\adminapi\http\middleware { function time(): int { return \WorkstationClock::$now; } }
|
||||
namespace app\common\cache {
|
||||
function time(): int { return \WorkstationClock::$now; }
|
||||
// 故意保留过期缓存,验证服务端始终以数据库为准。
|
||||
abstract class BaseCache {
|
||||
private static array $entries = [];
|
||||
public function get($key) { return self::$entries[$key] ?? null; }
|
||||
public function set($key, $value, $ttl = null) { self::$entries[$key] = $value; }
|
||||
public function delete($key): bool { return false; }
|
||||
}
|
||||
}
|
||||
namespace app\common\service {
|
||||
final class FileService {
|
||||
public static function getFileUrl($uri = ''): string { return (string) $uri; }
|
||||
}
|
||||
}
|
||||
namespace {
|
||||
use app\adminapi\controller\LoginController;
|
||||
use app\adminapi\http\middleware\LoginMiddleware;
|
||||
use app\adminapi\logic\LoginLogic;
|
||||
use app\adminapi\service\AdminTokenService;
|
||||
use app\adminapi\service\DesktopSessionService;
|
||||
use app\common\cache\AdminTokenCache;
|
||||
use app\common\enum\AdminTerminalEnum as Terminal;
|
||||
use think\facade\Db;
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
function create_token(string $extra = ''): string { return bin2hex(random_bytes(16)); }
|
||||
function wsExpect(bool $ok, string $label): void {
|
||||
if (!$ok) { throw new RuntimeException($label); }
|
||||
$GLOBALS['wsChecks']++;
|
||||
}
|
||||
final class WorkstationLoginController extends LoginController {
|
||||
public function __construct(think\Request $request) {
|
||||
$this->request = $request;
|
||||
$this->initialize();
|
||||
}
|
||||
}
|
||||
$GLOBALS['wsChecks'] = 0;
|
||||
$port = (int) getenv('ZYT_WORKSTATION_TEST_MYSQL_PORT');
|
||||
$temporaryDb = 'workstation_test_' . bin2hex(random_bytes(8));
|
||||
$app = new think\App(sys_get_temp_dir() . '/' . $temporaryDb);
|
||||
$manager = new think\DbManager();
|
||||
$manager->setConfig(['default' => 'test', 'auto_timestamp' => false, 'datetime_format' => false,
|
||||
'connections' => ['test' => $port
|
||||
? ['type' => 'mysql', 'database' => $temporaryDb, 'prefix' => 'zyt_', 'hostname' => '127.0.0.1',
|
||||
'username' => 'root', 'password' => '', 'hostport' => $port, 'charset' => 'utf8mb4']
|
||||
: ['type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'zyt_']]]);
|
||||
$app->instance('think\DbManager', $manager);
|
||||
$app->instance('log', new Psr\Log\NullLogger());
|
||||
$config = new think\Config();
|
||||
$config->set(['admin_token' => ['expire_duration' => 28800, 'be_expire_duration' => 3600],
|
||||
'default_image' => ['admin_avatar' => '']], 'project');
|
||||
$app->instance('config', $config);
|
||||
$app->env->set('work_wechat.force_bind_login', false);
|
||||
$app->env->set('WORK_WECHAT_FORCE_BIND_LOGIN', false);
|
||||
$request = static function (string $token = '', string $action = 'desktopHeartbeat', string $method = 'POST') use ($app) {
|
||||
$req = (new think\Request())->withServer(['REMOTE_ADDR' => '192.0.2.10', 'REQUEST_METHOD' => $method])
|
||||
->withHeader(['token' => $token]);
|
||||
$req->setController('Login');
|
||||
$req->setAction($action);
|
||||
$req->controllerObject = new WorkstationLoginController($req);
|
||||
$app->instance('request', $req);
|
||||
return $req;
|
||||
};
|
||||
$invoke = static function (string $token, string $action = 'desktopHeartbeat', string $method = 'POST') use ($request) {
|
||||
$req = $request($token, $action, $method);
|
||||
return (new LoginMiddleware())->handle($req, static function ($req) use ($action) {
|
||||
return (new WorkstationLoginController($req))->$action();
|
||||
})->getData();
|
||||
};
|
||||
$login = static function (int $terminal = Terminal::WORKSTATION) use ($request) {
|
||||
$request('', 'account');
|
||||
return (new LoginLogic())->login(['account' => 'doctor.ws', 'terminal' => $terminal]);
|
||||
};
|
||||
$ledger = static fn() => Db::name('desktop_login_session')->order('id', 'desc')->find();
|
||||
$root = null;
|
||||
try {
|
||||
if ($port) {
|
||||
$root = new PDO("mysql:host=127.0.0.1;port=$port;charset=utf8mb4", 'root', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
||||
$root->exec("CREATE DATABASE `$temporaryDb` CHARACTER SET utf8mb4");
|
||||
$root->exec("USE `$temporaryDb`");
|
||||
$root->exec('CREATE TABLE zyt_admin_session (id INT PRIMARY KEY AUTO_INCREMENT, admin_id INT NOT NULL, terminal INT NOT NULL,
|
||||
token VARCHAR(32) UNIQUE, expire_time INT NOT NULL, update_time INT, UNIQUE KEY old_install_index(admin_id,terminal)) ENGINE=InnoDB');
|
||||
$root->exec('CREATE TABLE zyt_dev_crontab (name VARCHAR(64),type INT,`system` INT,remark TEXT,command VARCHAR(64),
|
||||
params VARCHAR(64),status INT,expression VARCHAR(64),last_time INT,create_time INT,update_time INT,delete_time INT)');
|
||||
$root->exec("INSERT INTO zyt_admin_session (admin_id,terminal,token,expire_time) VALUES (77,1,'legacy',123)");
|
||||
$sql = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_11_24_desktop_login_session.sql');
|
||||
for ($run = 0; $run < 2; $run++) {
|
||||
$migration = $root->query($sql);
|
||||
while ($migration->nextRowset()) {
|
||||
// 消费可重复迁移中的所有 SELECT 与 DDL 结果。
|
||||
}
|
||||
$migration->closeCursor();
|
||||
}
|
||||
wsExpect((int) Db::name('dev_crontab')->where('command', 'desktop-session:settle')->count() === 1, 'one scheduled sweep');
|
||||
wsExpect((int) Db::name('admin_session')->where('token', 'legacy')->value('workstation_slot') === 0, 'old tokens retain ordinary slot');
|
||||
$duplicateRejected = false;
|
||||
try { $root->exec("INSERT INTO zyt_admin_session (admin_id,terminal,token,expire_time) VALUES (77,1,'other',123)"); }
|
||||
catch (PDOException $e) { $duplicateRejected = $e->getCode() === '23000'; }
|
||||
wsExpect($duplicateRejected, 'legacy terminals keep unique account-terminal constraint');
|
||||
} else {
|
||||
Db::execute('CREATE TABLE zyt_admin_session (id INTEGER PRIMARY KEY AUTOINCREMENT, admin_id INT, terminal INT, token TEXT UNIQUE,
|
||||
expire_time INT, update_time INT, workstation_slot INT NOT NULL DEFAULT 0, UNIQUE(admin_id, terminal, workstation_slot))');
|
||||
Db::execute("CREATE TABLE zyt_desktop_login_session (id INTEGER PRIMARY KEY AUTOINCREMENT, admin_id INT, account TEXT,
|
||||
name TEXT, login_ip TEXT, login_time INT, last_seen_time INT, expires_at INT, due_time INT, logout_time INT,
|
||||
duration_seconds INT DEFAULT 0, end_reason TEXT DEFAULT '')");
|
||||
}
|
||||
Db::execute('CREATE TABLE zyt_admin (id INT PRIMARY KEY, account VARCHAR(60), name VARCHAR(60), root INT, disable INT,
|
||||
multipoint_login INT, delete_time INT, login_ip VARCHAR(45), login_time INT, update_time INT, avatar VARCHAR(100),
|
||||
is_paw INT, work_wechat_userid VARCHAR(100))');
|
||||
Db::execute('CREATE TABLE zyt_admin_role (admin_id INT, role_id INT)');
|
||||
Db::execute('CREATE TABLE zyt_system_role (id INT PRIMARY KEY, name VARCHAR(60), delete_time INT)');
|
||||
Db::name('admin')->insert(['id' => 7, 'account' => 'doctor.ws', 'name' => '甲医生', 'root' => 0,
|
||||
'disable' => 0, 'multipoint_login' => 1, 'is_paw' => 1, 'avatar' => '', 'work_wechat_userid' => '']);
|
||||
$start = (new DateTimeImmutable('2026-11-24 04:56:00+08:00'))->getTimestamp();
|
||||
$cutoff = $start + 240;
|
||||
WorkstationClock::$now = $start;
|
||||
wsExpect(DesktopSessionService::nextCutoff($cutoff - 1) === $cutoff
|
||||
&& DesktopSessionService::nextCutoff($cutoff) === $cutoff + 86400, 'exact Beijing cutoff independent of PHP timezone');
|
||||
$web = $login(Terminal::PC);
|
||||
wsExpect(!isset($web['desktop_expires_at']) && Db::name('desktop_login_session')->count() === 0, 'web login remains separate');
|
||||
wsExpect($invoke($web['token'])['code'] === -1, 'legacy desktop/web token cannot assert a workstation heartbeat');
|
||||
$first = $login();
|
||||
$firstId = $ledger()['id'];
|
||||
$second = $login();
|
||||
wsExpect($first['desktop_expires_at'] === $cutoff && $first['token'] !== $second['token'], 'parallel desktops get separate tokens');
|
||||
wsExpect($ledger()['account'] === 'doctor.ws' && $ledger()['name'] === '甲医生', 'identity snapshot persisted');
|
||||
wsExpect($invoke($second['token'], 'desktopHeartbeat', 'GET')['code'] === 0, 'heartbeat is POST only');
|
||||
WorkstationClock::$now += 62;
|
||||
wsExpect($invoke($first['token'])['data']['desktop_expires_at'] === $cutoff, 'heartbeat refreshes lease only');
|
||||
wsExpect($invoke($second['token'], 'logout')['code'] === 1 && $ledger()['end_reason'] === 'logout'
|
||||
&& (int) $ledger()['duration_seconds'] === 62, 'explicit logout settles only that instance to the second');
|
||||
wsExpect($invoke($second['token'])['code'] === -1 && !(new AdminTokenCache())->getAdminInfo($second['token']), 'stale cache cannot restore closed device');
|
||||
wsExpect((bool) (new AdminTokenCache())->getAdminInfo($web['token']), 'web token survives desktop logout');
|
||||
WorkstationClock::$now = $cutoff;
|
||||
wsExpect(!AdminTokenService::overtimeToken($first['token']) && $invoke($first['token'])['code'] === -1, 'no request or renewal at 05:00');
|
||||
WorkstationClock::$now += 3600;
|
||||
wsExpect(DesktopSessionService::settleDue() === 1 && DesktopSessionService::settleDue() === 0, 'delayed sweep settles once');
|
||||
$old = Db::name('desktop_login_session')->where('id', $firstId)->find();
|
||||
wsExpect((int) $old['logout_time'] === $cutoff && (int) $old['duration_seconds'] === 240 && $old['end_reason'] === 'daily_cutoff', 'durable daily cutoff even without requests');
|
||||
$idle = $login();
|
||||
WorkstationClock::$now += 52;
|
||||
$invoke($idle['token']);
|
||||
$lastSeen = WorkstationClock::$now;
|
||||
WorkstationClock::$now += 180;
|
||||
wsExpect($invoke($idle['token'])['code'] === -1 && DesktopSessionService::settleDue() === 1, 'expired heartbeat cannot revive a slot');
|
||||
wsExpect((int) $ledger()['logout_time'] === $lastSeen && (int) $ledger()['duration_seconds'] === 52
|
||||
&& $ledger()['end_reason'] === 'timeout', 'disconnected time excluded');
|
||||
Db::name('admin')->where('id', 7)->update(['multipoint_login' => 0]);
|
||||
$replaced = $login();
|
||||
$replacedId = $ledger()['id'];
|
||||
WorkstationClock::$now += 11;
|
||||
$replacement = $login();
|
||||
$old = Db::name('desktop_login_session')->where('id', $replacedId)->find();
|
||||
wsExpect($old['end_reason'] === 'replaced' && (int) $old['duration_seconds'] === 11, 'single-point relog closes old record');
|
||||
wsExpect($invoke($replaced['token'], 'logout')['code'] === -1 && $invoke($replacement['token'])['code'] === 1,
|
||||
'late logout cannot affect replacement');
|
||||
AdminTokenService::revokeNativeSessions(7);
|
||||
wsExpect($ledger()['end_reason'] === 'revoked' && $invoke($replacement['token'])['code'] === -1, 'account credential revocation settles the ledger');
|
||||
echo 'WorkstationSessionTest ' . ($port ? 'MySQL' : 'SQLite') . ': ' . $GLOBALS['wsChecks'] . " checks passed\n";
|
||||
} finally {
|
||||
if ($root) { $root->exec("DROP DATABASE IF EXISTS `$temporaryDb`"); }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user