i
This commit is contained in:
gr
2026-10-22 11:12:29 +08:00
480 changed files with 9840 additions and 953 deletions
@@ -0,0 +1,211 @@
<?php
declare(strict_types=1);
// All identities and records are synthetic. The real controller and middleware
// execute below, while their IO dependencies stay entirely in memory.
namespace app\adminapi\logic {
final class LoginLogic
{
public static function adminMustBindWorkWechat(array $adminInfo): bool { return false; }
}
}
namespace app\common\cache {
final class AdminAuthCache
{
public static array $permissions = [];
public static int $allUriReads = 0;
public static array $actors = [];
public function __construct(int $adminId) { self::$actors[] = $adminId; }
public function getAdminUri(): array { return self::$permissions; }
public function getAllUri(): array { self::$allUriReads++; return []; }
}
}
namespace app\common\service {
final class JsonService
{
public static function fail(string $msg = 'fail', array $data = [], int $code = 0, int $show = 1): array
{
return compact('code', 'show', 'msg', 'data');
}
public static function data(array $data): array
{
return ['code' => 1, 'show' => 0, 'msg' => '', 'data' => $data];
}
}
}
namespace app\adminapi\logic\tcm {
final class DiagnosisLogic
{
public static bool $visible = true;
public static string $error = '';
public static array $events = [];
public static array $records = [];
public static function canViewReadonlyDiagnosis(int $id, int $adminId, array $adminInfo): bool
{
self::$events[] = ['authorize', $id, $adminId, $adminInfo];
return self::$visible;
}
public static function getCallRecords(array $params): array
{
if (!self::$visible) { throw new \RuntimeException('Forbidden records reached the read dependency'); }
self::$events[] = ['read', $params];
return self::$records;
}
public static function getError(): string { return self::$error; }
}
}
namespace app\adminapi\http\middleware {
function request(): object { return $GLOBALS['consultation_transcript_request']; }
function env(...$arguments): never { throw new \RuntimeException('This test must not access environment configuration'); }
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use app\adminapi\controller\tcm\DiagnosisController;
use app\adminapi\http\middleware\AuthMiddleware;
use app\adminapi\logic\tcm\DiagnosisLogic;
use app\common\cache\AdminAuthCache;
use app\common\service\JsonService;
final class ConsultationTranscriptRequest
{
public array $adminInfo;
public object $controllerObject;
public string $actionName = 'getCallRecords';
public string $controllerName = 'tcm.Diagnosis';
public function __construct(public array $query = [], bool $root = false)
{
$this->adminInfo = ['admin_id' => 91, 'root' => $root ? 1 : 0,
'login_ip' => '192.0.2.91', 'work_wechat_userid' => 'synthetic-doctor-91'];
$this->controllerObject = new class {
public function isNotNeedLogin(): bool { return false; }
};
}
public function get(?string $name = null, $default = null)
{
return $name === null ? $this->query : ($this->query[$name] ?? $default);
}
public function param(string $name, $default = null) { return $default; }
public function controller(): string { return $this->controllerName; }
public function action(): string { return $this->actionName; }
public function ip(): string { return '192.0.2.91'; }
}
final class ConsultationTranscriptController extends DiagnosisController
{
public function __construct(ConsultationTranscriptRequest $request)
{
$this->request = $request;
$this->adminId = $request->adminInfo['admin_id'];
$this->adminInfo = $request->adminInfo;
}
protected function data($data) { return JsonService::data($data); }
protected function fail(string $msg = 'fail', array $data = [], int $code = 0, int $show = 1)
{
return JsonService::fail($msg, $data, $code, $show);
}
}
$assertions = 0;
function transcriptAuthorizationExpect(bool $ok, string $label): void
{
global $assertions;
if (!$ok) { throw new RuntimeException('FAIL: ' . $label); }
$assertions++;
}
function transcriptAuthorizationInvoke(array $query, array $permissions, bool $root = false): array
{
AdminAuthCache::$permissions = $permissions;
AdminAuthCache::$allUriReads = 0;
AdminAuthCache::$actors = [];
DiagnosisLogic::$events = [];
$request = new ConsultationTranscriptRequest($query, $root);
$GLOBALS['consultation_transcript_request'] = $request;
$controller = new ConsultationTranscriptController($request);
$request->controllerObject = $controller;
return (new AuthMiddleware())->handle($request, static fn () => $controller->getCallRecords());
}
DiagnosisLogic::$records = [
['id' => 1102, 'diagnosis_id' => 701, 'caller_id' => 202, 'caller_type' => 'doctor',
'transcription_session_id' => 'synthetic-session-1102', 'transcription_status' => 'partial',
'transcription_segment_count' => 2, 'transcript_text' => "医生:合成问题 <test>\n患者:合成回答 & 保留原文。"],
['id' => 1101, 'diagnosis_id' => 701, 'caller_id' => 201, 'caller_type' => 'doctor',
'transcription_session_id' => 'synthetic-session-1101', 'transcription_status' => 'completed',
'transcription_segment_count' => 1, 'transcript_text' => '未知说话人:另一通合成面诊。'],
];
foreach ([[], ['tcm.diagnosis/edit'], ['tcm.diagnosis/detail'], ['tcm.diagnosis/video-call'],
['tcm.diagnosis/huifangOther'], ['tcm.diagnosis/getCallRecordsOther']] as $permissions) {
$result = transcriptAuthorizationInvoke(['diagnosis_id' => 701], $permissions);
transcriptAuthorizationExpect($result['code'] === 0, 'unregistered read rejects unrelated grants ' . json_encode($permissions));
transcriptAuthorizationExpect(DiagnosisLogic::$events === [], 'function permission denial precedes row and transcript reads');
transcriptAuthorizationExpect(AdminAuthCache::$allUriReads === 0, 'transcript route never consults legacy unregistered-route bypass');
}
foreach ([['tcm.diagnosis/huifang'], ['tcm.diagnosis/getCallRecords'],
['TCM.DIAGNOSIS/GETCALLRECORDS'], ['tcm.diagnosis/huifang', 'tcm.diagnosis/getCallRecords']] as $permissions) {
DiagnosisLogic::$visible = true;
$result = transcriptAuthorizationInvoke(['diagnosis_id' => '701', 'call_record_id' => 9999,
'appointment_id' => 9999, 'caller_id' => 91], $permissions);
transcriptAuthorizationExpect($result['code'] === 1, 'either exact read grant allows the controller without edit ' . json_encode($permissions));
transcriptAuthorizationExpect($result['data'] === DiagnosisLogic::$records, 'full transcript and every call identity remain unchanged');
transcriptAuthorizationExpect(DiagnosisLogic::$events === [
['authorize', 701, 91, $GLOBALS['consultation_transcript_request']->adminInfo],
['read', ['diagnosis_id' => 701]],
], 'real controller authorizes trusted actor before a diagnosis-only read, without a caller filter');
transcriptAuthorizationExpect(AdminAuthCache::$allUriReads === 0, 'grant works even with no registered menu routes');
}
$root = transcriptAuthorizationInvoke(['diagnosis_id' => 701], [], true);
transcriptAuthorizationExpect($root['data'] === DiagnosisLogic::$records, 'root retains the existing middleware grant bypass');
transcriptAuthorizationExpect(AdminAuthCache::$actors === [], 'root does not need a permission cache or menu grant');
transcriptAuthorizationExpect(DiagnosisLogic::$events[0][0] === 'authorize', 'root still passes the controller through diagnosis row authorization');
DiagnosisLogic::$visible = false;
foreach (['诊单不存在或无权访问', ''] as $error) {
DiagnosisLogic::$error = $error;
$denied = transcriptAuthorizationInvoke(['diagnosis_id' => 702], ['tcm.diagnosis/huifang']);
transcriptAuthorizationExpect($denied['code'] === 0 && $denied['msg'] === '诊单不存在或无权访问', 'forbidden or missing diagnosis shares the same non-enumerating error');
transcriptAuthorizationExpect(count(DiagnosisLogic::$events) === 1
&& DiagnosisLogic::$events[0][0] === 'authorize'
&& DiagnosisLogic::$events[0][1] === 702, 'row denial happens before transcript records can be read');
}
DiagnosisLogic::$visible = true;
DiagnosisLogic::$error = '';
foreach ([[], ['diagnosis_id' => null], ['diagnosis_id' => 0], ['diagnosis_id' => -1],
['diagnosis_id' => '0'], ['diagnosis_id' => ''], ['diagnosis_id' => 'invalid'],
['diagnosis_id' => '701suffix'], ['diagnosis_id' => '701.5'], ['diagnosis_id' => 701.5],
['diagnosis_id' => true], ['diagnosis_id' => false], ['diagnosis_id' => []],
['diagnosis_id' => ['701']], ['diagnosis_id' => new stdClass()]] as $query) {
$invalid = transcriptAuthorizationInvoke($query, ['tcm.diagnosis/huifang']);
transcriptAuthorizationExpect($invalid['code'] === 0, 'missing or nonpositive diagnosis id is rejected ' . json_encode($query));
transcriptAuthorizationExpect(DiagnosisLogic::$events === [], 'invalid id never reaches row authorization or a record read');
}
$request = new ConsultationTranscriptRequest(['diagnosis_id' => 701]);
$request->controllerName = 'TcM.DiAgNoSiS';
$request->actionName = 'GeTcAlLrEcOrDs';
$GLOBALS['consultation_transcript_request'] = $request;
AdminAuthCache::$permissions = [];
$continued = false;
$caseDenied = (new AuthMiddleware())->handle($request, static function () use (&$continued): array {
$continued = true;
return ['code' => 1];
});
transcriptAuthorizationExpect($caseDenied['code'] === 0 && !$continued, 'route case variations cannot evade the exact protected action');
DiagnosisLogic::$records = [];
$empty = transcriptAuthorizationInvoke(['diagnosis_id' => 701], ['tcm.diagnosis/getCallRecords']);
transcriptAuthorizationExpect($empty['code'] === 1 && $empty['data'] === [], 'authorized empty history retains the original array response');
echo "Consultation transcript authorization: {$assertions} assertions passed (no DB or network)\n";
}
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
require dirname(__DIR__) . '/vendor/autoload.php';
use app\adminapi\logic\setting\DesktopWorkstationLogic;
$assertions = 0;
function downloadExpect(bool $condition, string $message): void
{
global $assertions;
$assertions++;
if (!$condition) throw new RuntimeException($message);
}
$config = [
'enabled' => 0,
'latest_version' => '1.4.8',
'min_version' => '1.4.0',
'force_update' => 1,
'notes' => '管理端配置字段无需暴露给下载页',
'packages' => [
'windows_x64' => ['url' => 'https://cdn.example.test/doctor-setup.exe', 'sha256' => str_repeat('A', 64), 'size' => 123, 'filename' => 'doctor-setup.exe', 'type' => 'inno_setup'],
'macos_arm64' => ['url' => 'https://cdn.example.test/doctor-apple.zip', 'sha256' => str_repeat('b', 64), 'filename' => 'doctor-apple.zip'],
'macos_x64' => ['url' => '', 'sha256' => ''],
],
];
$catalog = DesktopWorkstationLogic::downloadCatalog($config);
downloadExpect(array_keys($catalog) === ['version', 'packages'], 'catalog exposes only version and installer metadata');
downloadExpect($catalog['version'] === '1.4.8', 'latest published version is shown');
downloadExpect(array_column($catalog['packages'], 'platform') === ['windows_x64', 'macos_arm64'], 'only actually configured platforms are available');
downloadExpect($catalog['packages'][0]['sha256'] === str_repeat('a', 64), 'published hashes are normalized');
downloadExpect($catalog['packages'][0]['type'] === 'inno_setup', 'Windows installation type remains accurate');
downloadExpect(str_contains($catalog['packages'][0]['label'], 'Windows'), 'installer names explain which OS to choose');
downloadExpect(!isset($catalog['force_update']) && !isset($catalog['notes']), 'system settings are not part of the public download payload');
downloadExpect(count($catalog['packages']) === 2, 'turning off automatic updates does not remove first-install downloads');
foreach (['javascript:alert(1)', 'data:text/html,test', 'file:///tmp/setup.exe', '//cdn.example.test/setup.exe', 'https://user:password@cdn.example.test/setup.exe', 'https:///missing-host'] as $badUrl) {
$invalid = $config;
$invalid['packages'] = ['windows_x64' => ['url' => $badUrl, 'sha256' => str_repeat('a', 64)]];
downloadExpect(DesktopWorkstationLogic::downloadCatalog($invalid)['packages'] === [], 'unsafe or invalid download URL is not advertised');
}
foreach (['', 'bad', str_repeat('g', 64), str_repeat('a', 63)] as $badHash) {
$invalid = $config;
$invalid['packages'] = ['windows_x64' => ['url' => 'https://cdn.example.test/setup.exe', 'sha256' => $badHash]];
downloadExpect(DesktopWorkstationLogic::downloadCatalog($invalid)['packages'] === [], 'unverified or incomplete uploads are not advertised');
}
downloadExpect(DesktopWorkstationLogic::downloadCatalog([]) === ['version' => '', 'packages' => []], 'an unpublished package has an explicit empty state');
$controller = file_get_contents(dirname(__DIR__) . '/app/adminapi/controller/setting/DesktopWorkstationController.php');
downloadExpect(str_contains($controller, "public array \$notNeedLogin = ['check', 'downloads'];"), 'download listing is available without system configuration permissions');
downloadExpect(str_contains($controller, 'DesktopWorkstationLogic::downloads()'), 'public endpoint uses the existing published package source');
echo "Desktop workstation downloads: {$assertions} assertions passed\n";
@@ -85,7 +85,7 @@ desktopUpdateExpect($quiet['has_update'] === false, 'disabled detection never pr
$controller = file_get_contents(dirname(__DIR__) . '/app/adminapi/controller/setting/DesktopWorkstationController.php');
desktopUpdateExpect(is_string($controller), 'controller source is readable');
desktopUpdateExpect(
str_contains($controller, "public array \$notNeedLogin = ['check']")
str_contains($controller, "public array \$notNeedLogin = ['check', 'downloads']")
&& str_contains($controller, 'public function check()')
&& str_contains($controller, 'DesktopWorkstationLogic::check('),
'check action is public and delegates to logic'
@@ -0,0 +1,232 @@
<?php
declare(strict_types=1);
namespace app\adminapi\service {
// 可控的业务时钟:不启动框架、访问数据库或改变本机时钟。
function time(): int { return $GLOBALS['migration_test_now']; }
}
namespace {
require dirname(__DIR__) . '/app/adminapi/service/DoctorWebConsultationPolicy.php';
require dirname(__DIR__) . '/app/adminapi/http/middleware/DoctorWebConsultationMiddleware.php';
use app\adminapi\service\DoctorWebConsultationPolicy as Policy;
use app\adminapi\http\middleware\DoctorWebConsultationMiddleware;
final class MigrationTestJson
{
public static function fail(string $msg, array $data = [], int $code = 0): array
{
return compact('code', 'msg', 'data');
}
public static function data(array $data): array
{
return ['code' => 1, 'show' => 0, 'msg' => '', 'data' => $data];
}
}
class_alias(MigrationTestJson::class, 'app\common\service\JsonService');
require dirname(__DIR__) . '/vendor/autoload.php';
final class MigrationConfigController extends \app\adminapi\controller\ConfigController
{
public function __construct(string $action = 'doctorWebConsultation')
{
$this->request = (new \think\Request())->setAction($action);
}
}
$assertions = 0;
function migrationExpect(bool $condition, string $message): void
{
global $assertions;
$assertions++;
if (!$condition) throw new \RuntimeException($message);
}
function migrationRejects(array $configuration, string $key): void
{
try {
Policy::publicPolicy(123, $configuration);
} catch (\InvalidArgumentException $error) {
migrationExpect(str_contains($error->getMessage(), 'doctor_web_consultation.' . $key), 'configuration error names the invalid field');
return;
}
migrationExpect(false, 'invalid configuration was accepted: ' . $key);
}
$cutoff = (new \DateTimeImmutable('2026-10-23T16:00:00Z'))->getTimestamp();
$GLOBALS['migration_test_now'] = $cutoff;
date_default_timezone_set('UTC');
migrationExpect(Policy::cutoffTimestamp() === $cutoff, 'cutoff is independent of process timezone');
$defaults = require dirname(__DIR__) . '/config/doctor_web_consultation.php';
$defaultPolicy = Policy::publicPolicy($cutoff);
migrationExpect($defaultPolicy === [
'cutoff_at' => '2026-10-24T00:00:00+08:00',
'approaching_at' => '2026-10-22T00:00:00+08:00',
'urgent_at' => '2026-10-23T00:00:00+08:00',
'server_time' => $cutoff,
], 'default config exposes the cutoff and both reminder boundaries with explicit Beijing offsets');
migrationExpect(Policy::cutoffAt() === $defaultPolicy['cutoff_at'], 'cutoff helper uses the same config');
migrationExpect(str_contains(Policy::message(), '2026年10月24日00:00:00'), 'message derives the exact configured second');
$doctor = ['admin_id' => 101, 'root' => 0, 'role_id' => [1], 'terminal' => 1];
$browser = ['User-Agent' => 'Mozilla/5.0', 'Origin' => 'https://example.test'];
foreach (['getCallSignature', 'startCall', 'getDoctorSignature', 'getPatientSignature'] as $action) {
foreach ([$cutoff - 1 => false, $cutoff => true, $cutoff + 1 => true] as $now => $expected) {
migrationExpect(Policy::blocksRequest($doctor, 'tcm.Diagnosis', $action, $browser, $now) === $expected, "$action boundary $now");
}
}
foreach ([['role_id' => [2]], ['role_id' => [3, 7, 8]], ['root' => 1, 'role_id' => [1]], []] as $identity) {
migrationExpect(!Policy::blocksRequest($identity, 'tcm.diagnosis', 'startCall', $browser), 'only non-root doctors migrate');
}
migrationExpect(Policy::blocksRequest(['role_id' => ['2', '1']], 'tcm.diagnosis', 'startCall', $browser), 'mixed and numeric string roles retain doctor policy');
foreach (['ZytDoctorWorkstation/1.4.8', 'python-httpx/0.27.2', 'python-httpx/0.28.1'] as $ua) {
migrationExpect(!Policy::blocksRequest($doctor, 'tcm.diagnosis', 'getCallSignature', ['User-Agent' => $ua]), 'new and already installed workstations keep working');
foreach (['Origin', 'Referer', 'Sec-Fetch-Mode', 'Sec-Fetch-Site', 'Sec-Fetch-Dest'] as $signal) {
migrationExpect(Policy::blocksRequest($doctor, 'tcm.diagnosis', 'startCall', ['User-Agent' => $ua, $signal => 'same-origin']), 'browser metadata takes priority over desktop UA');
}
}
foreach (['', 'unknown', 'Mozilla/5.0', 'Mozilla/5.0 ZytDoctorWorkstation/1.4.8', 'python-httpx/0.28.1 extra'] as $ua) {
migrationExpect(Policy::blocksRequest($doctor, 'tcm.diagnosis', 'startCall', ['user-agent' => $ua]), 'missing or unknown client never gains a desktop exemption');
}
foreach (['lists', 'detail', 'readonlyDetail', 'edit', 'bindCallRoom', 'endCall', 'watchCall', 'attachLocalCallRecording', 'upsertCallTranscriptSegments', 'finishCallTranscription'] as $action) {
migrationExpect(!Policy::blocksRequest($doctor, 'tcm.diagnosis', $action, $browser), 'history and in-flight cleanup remain available: ' . $action);
}
foreach (['doctor.appointment', 'tcm.prescription', 'auth.admin'] as $controller) {
migrationExpect(!Policy::blocksRequest($doctor, $controller, 'startCall', $browser), 'exact controller scope');
}
$custom = ['cutoff_at' => '2032-01-01 14:30:45', 'approaching_hours' => 72, 'urgent_hours' => 6];
$customCutoff = (new \DateTimeImmutable('2032-01-01T14:30:45+08:00'))->getTimestamp();
$customPolicy = Policy::publicPolicy($customCutoff - 1, $custom);
migrationExpect($customPolicy === [
'cutoff_at' => '2032-01-01T14:30:45+08:00',
'approaching_at' => '2031-12-29T14:30:45+08:00',
'urgent_at' => '2032-01-01T08:30:45+08:00',
'server_time' => $customCutoff - 1,
], 'arbitrary midday/year schedule moves both reminder phases automatically');
foreach ([$customCutoff - 1 => false, $customCutoff => true, $customCutoff + 1 => true] as $now => $expected) {
migrationExpect(Policy::blocksRequest($doctor, 'tcm.Diagnosis', 'startCall', $browser, $now, $custom) === $expected,
'custom schedule controls the exact-second backend cutoff');
}
migrationExpect(str_contains(Policy::message($custom), '2032年1月1日14:30:45'), 'custom schedule also changes backend notice text');
foreach (['UTC', 'America/New_York', 'Asia/Tokyo'] as $processTimezone) {
date_default_timezone_set($processTimezone);
migrationExpect(Policy::publicPolicy(123, $custom)['cutoff_at'] === $customPolicy['cutoff_at'], 'Beijing configuration ignores PHP process timezone');
}
date_default_timezone_set('UTC');
$zeroHours = Policy::publicPolicy(123, array_replace($custom, ['approaching_hours' => 0, 'urgent_hours' => 0]));
migrationExpect($zeroHours['approaching_at'] === $zeroHours['cutoff_at'] && $zeroHours['urgent_at'] === $zeroHours['cutoff_at'], 'zero-hour reminders are valid');
$equalHours = Policy::publicPolicy(123, array_replace($custom, ['approaching_hours' => 6]));
migrationExpect($equalHours['approaching_at'] === $equalHours['urgent_at'], 'equal reminder offsets are valid');
migrationExpect(Policy::publicPolicy(123, array_replace($custom, ['cutoff_at' => '2032-02-29 12:00:01']))['cutoff_at'] === '2032-02-29T12:00:01+08:00', 'valid leap date is retained');
foreach ([null, false, 20320101, [], '', 'tomorrow', '2032-1-01 14:30:45', '2032-01-01 14:30',
'2032-01-01 14:30:45 ', '2031-02-29 14:30:45', '2032-04-31 14:30:45', '2032-01-01 24:00:00',
'2032-01-01 14:60:45', '2032-01-01 14:30:60', '0000-01-01 00:00:00', '1991-04-14 02:30:00',
'2032-01-01T14:30:45+08:00', '2032-01-01 14:30:45+08:00', '2032-01-01T14:30:45+25:00'] as $invalid) {
migrationRejects(array_replace($defaults, ['cutoff_at' => $invalid]), 'cutoff_at');
}
migrationRejects([], 'cutoff_at');
foreach (['approaching_hours', 'urgent_hours'] as $key) {
foreach ([null, -1, 1.5, '24', true, [], PHP_INT_MAX] as $invalid) {
migrationRejects(array_replace($defaults, [$key => $invalid]), $key);
}
$missing = $defaults;
unset($missing[$key]);
migrationRejects($missing, $key);
}
migrationRejects(array_replace($defaults, ['approaching_hours' => 12, 'urgent_hours' => 24]), 'approaching_hours');
migrationRejects(array_replace($defaults, ['approaching_hours' => intdiv(PHP_INT_MAX, 3600)]), 'approaching_hours');
migrationExpect(!Policy::blocksRequest($doctor, 'config', 'doctorWebConsultation', $browser, $cutoff, []), 'invalid migration config never affects unrelated routes');
migrationExpect(!Policy::blocksRequest(['root' => 1, 'role_id' => [1]], 'tcm.diagnosis', 'startCall', $browser, $cutoff, []), 'invalid migration config never affects root exemption');
migrationExpect(!Policy::blocksRequest(['role_id' => [2]], 'tcm.diagnosis', 'startCall', $browser, $cutoff, []), 'invalid migration config never affects other roles');
migrationExpect(!Policy::blocksRequest($doctor, 'tcm.diagnosis', 'startCall', ['User-Agent' => 'python-httpx/0.28.1'], $cutoff, []), 'invalid migration config never affects native exemption');
$request = new class($doctor, $browser) {
public string $actionName = 'getCallSignature';
public function __construct(public array $adminInfo, public array $headers) {}
public function controller(): string { return 'tcm.Diagnosis'; }
public function action(): string { return $this->actionName; }
public function header(): array { return $this->headers; }
};
$executed = 0;
$next = static function ($request) use (&$executed): string { $executed++; return 'business action executed'; };
$middleware = new DoctorWebConsultationMiddleware();
$GLOBALS['migration_test_now'] = $cutoff - 1;
migrationExpect($middleware->handle($request, $next) === 'business action executed', 'middleware allows October 23');
$GLOBALS['migration_test_now'] = $cutoff;
$failure = $middleware->handle($request, $next);
migrationExpect($executed === 1, 'expired doctor request never reaches signature generation');
migrationExpect($failure['code'] === 0 && $failure['data']['reason'] === 'doctor_web_consultation_expired', 'business failure does not log the user out');
migrationExpect(str_contains($failure['msg'], '桌面应用'), 'failure explains migration');
$request->headers = ['User-Agent' => 'python-httpx/0.28.1'];
migrationExpect($middleware->handle($request, $next) === 'business action executed', 'same terminal=1 native session remains usable');
$request->headers = $browser;
$request->actionName = 'endCall';
migrationExpect($middleware->handle($request, $next) === 'business action executed', 'active calls can still finish and persist recordings');
$request->actionName = 'getDoctorSignature';
$customMiddleware = new DoctorWebConsultationMiddleware($custom);
$GLOBALS['migration_test_now'] = $customCutoff - 1;
migrationExpect($customMiddleware->handle($request, $next) === 'business action executed', 'middleware respects configured midday cutoff before its exact second');
$GLOBALS['migration_test_now'] = $customCutoff;
$beforeBlocked = $executed;
$customFailure = $customMiddleware->handle($request, $next);
migrationExpect($executed === $beforeBlocked && $customFailure['data']['cutoff_at'] === $customPolicy['cutoff_at'], 'actual middleware guard and payload use custom config');
migrationExpect(str_contains($customFailure['msg'], '2032年1月1日14:30:45'), 'actual middleware response formats custom config');
foreach (['ZytDoctorWorkstation/1.4.8', 'python-httpx/0.28.1'] as $ua) {
$request->headers = ['User-Agent' => $ua];
migrationExpect($customMiddleware->handle($request, $next) === 'business action executed', 'custom cutoff preserves native client compatibility');
}
$routes = file_get_contents(dirname(__DIR__) . '/app/adminapi/config/route.php');
migrationExpect(strpos($routes, 'AuthMiddleware::class') < strpos($routes, 'DoctorWebConsultationMiddleware::class'), 'migration runs after normal authorization');
$GLOBALS['migration_test_now'] = $cutoff;
migrationExpect(Policy::publicPolicy()['server_time'] === $cutoff, 'profile exposes synchronized server time');
$controller = new MigrationConfigController();
migrationExpect($controller->isNotNeedLogin(), 'public polling endpoint passes the real inherited login whitelist');
migrationExpect(!(new MigrationConfigController('unlistedAction'))->isNotNeedLogin(), 'whitelist only exposes explicitly public actions');
$endpoint = $controller->doctorWebConsultation();
migrationExpect($endpoint['code'] === 1 && $endpoint['data'] === $defaultPolicy, 'actual ConfigController returns the full read-only public policy contract');
$profileSource = file_get_contents(dirname(__DIR__) . '/app/adminapi/logic/auth/AdminLogic.php');
migrationExpect(str_contains($profileSource, "DoctorWebConsultationPolicy::publicPolicy()"), 'logged-in profile keeps sharing the same backend policy');
// 在独立临时目录验证配置热加载;不改仓库配置,也不读取 .env 或项目密钥。
$fixtureRoot = sys_get_temp_dir() . '/zyt-consultation-policy-' . bin2hex(random_bytes(8));
$fixtureServiceDir = $fixtureRoot . '/app/adminapi/service';
$fixtureConfigDir = $fixtureRoot . '/config';
mkdir($fixtureServiceDir, 0700, true);
mkdir($fixtureConfigDir, 0700, true);
$fixtureService = $fixtureServiceDir . '/DoctorWebConsultationPolicy.php';
$fixtureConfig = $fixtureConfigDir . '/doctor_web_consultation.php';
try {
$source = file_get_contents(dirname(__DIR__) . '/app/adminapi/service/DoctorWebConsultationPolicy.php');
file_put_contents($fixtureService, str_replace('namespace app\\adminapi\\service;', 'namespace migration_reload_fixture;', $source));
file_put_contents($fixtureConfig, '<?php return ' . var_export($defaults, true) . ';');
$frameworkConfig = new \think\Config();
$frameworkConfig->set($defaults, 'doctor_web_consultation');
\think\Container::getInstance()->instance('config', $frameworkConfig);
require $fixtureService;
$fixtureClass = \migration_reload_fixture\DoctorWebConsultationPolicy::class;
migrationExpect($fixtureClass::publicPolicy(123)['cutoff_at'] === $defaultPolicy['cutoff_at'], 'direct config loader starts with default fixture');
file_put_contents($fixtureConfig, '<?php return ' . var_export($custom, true) . ';');
migrationExpect($fixtureClass::publicPolicy($customCutoff - 1) === $customPolicy, 'editing only config immediately changes cutoff and both reminders in the same PHP process');
migrationExpect(\think\facade\Config::get('doctor_web_consultation.cutoff_at') === $defaults['cutoff_at'], 'framework config deliberately remains cached at the old date while policy reloads the new file');
migrationExpect(str_contains($fixtureClass::message(), '2032年1月1日14:30:45'), 'hot-loaded config immediately changes backend message');
migrationExpect($fixtureClass::blocksRequest($doctor, 'tcm.diagnosis', 'startCall', $browser, $customCutoff), 'hot-loaded config controls backend enforcement');
file_put_contents($fixtureConfig, '<?php return "invalid";');
try {
$fixtureClass::publicPolicy(123);
migrationExpect(false, 'non-array config must fail clearly');
} catch (\UnexpectedValueException $error) {
migrationExpect(str_contains($error->getMessage(), 'doctor_web_consultation'), 'non-array config has a clear error');
}
} finally {
foreach ([$fixtureConfig, $fixtureService] as $file) {
if (is_file($file)) unlink($file);
}
foreach ([$fixtureServiceDir, dirname($fixtureServiceDir), $fixtureRoot . '/app', $fixtureConfigDir, $fixtureRoot] as $directory) {
if (is_dir($directory)) rmdir($directory);
}
}
echo "Doctor web consultation policy: {$assertions} assertions passed\n";
}
@@ -0,0 +1,231 @@
<?php
declare(strict_types=1);
/**
* Real ORM integration against an explicitly selected disposable local MySQL instance.
* Run: ZYT_PAYMENT_LINK_TEST_MYSQL_PORT=13429 php tests/PaymentPrescriptionOrderLinksTest.php
* Never initializes the application or loads its business database/environment configuration.
*/
require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
use app\adminapi\lists\order\OrderLists;
use app\adminapi\logic\order\OrderLogic;
use app\adminapi\logic\tcm\PrescriptionOrderLogic;
use app\adminapi\service\order\PaymentPrescriptionOrderService;
use think\Container;
use think\DbManager;
use think\facade\Db;
$port = (int) getenv('ZYT_PAYMENT_LINK_TEST_MYSQL_PORT');
if ($port <= 0 || $port === 3306) {
fwrite(STDERR, "Set ZYT_PAYMENT_LINK_TEST_MYSQL_PORT to an isolated local MySQL instance outside port 3306.\n");
exit(1);
}
$database = 'payment_rx_links_test_' . bin2hex(random_bytes(6));
$pdo = new PDO("mysql:host=127.0.0.1;port={$port};charset=utf8mb4", 'root', '', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_TIMEOUT => 2,
]);
$pdo->exec("CREATE DATABASE `{$database}` CHARACTER SET utf8mb4");
$pdo->exec("USE `{$database}`");
$testApp = new think\App(); // Do not initialize: production services/configuration must not be loaded.
$manager = new DbManager();
$manager->setConfig([
'default' => 'mysql', 'auto_timestamp' => true, 'datetime_format' => false,
'connections' => ['mysql' => [
'type' => 'mysql', 'hostname' => '127.0.0.1', 'hostport' => $port,
'database' => $database, 'username' => 'root', 'password' => '',
'charset' => 'utf8mb4', 'prefix' => 'zyt_', 'fields_strict' => true, 'trigger_sql' => true,
]],
]);
$config = new think\Config();
$config->set(['data_scope' => ['enabled' => false]], 'project');
Container::getInstance()->instance('think\DbManager', $manager);
Container::getInstance()->instance('config', $config);
$sqlLog = [];
$manager->listen(static function (string $sql) use (&$sqlLog): void { $sqlLog[] = $sql; });
$checks = 0;
$expect = static function (bool $condition, string $message) use (&$checks): void {
if (!$condition) throw new RuntimeException($message);
++$checks;
};
$admin = ['root' => 1, 'name' => 'Isolated administrator'];
// Bypass request/bootstrap construction while executing the real lists(), count(), and permission filters.
$lists = static function (int $adminId = 1, bool $root = true, int $offset = 0, int $size = 100, array $where = []): OrderLists {
return new class($adminId, $root, $offset, $size, $where) extends OrderLists {
public function __construct(int $adminId, bool $root, int $offset, int $size, array $where)
{
$this->adminId = $adminId;
$this->adminInfo = ['root' => (int) $root];
$this->params = [];
$this->searchWhere = $where;
$this->limitOffset = $offset;
$this->pageSize = $size;
}
};
};
$associationQueries = static fn (array $queries): array => array_values(array_filter($queries,
static fn (string $sql): bool => str_starts_with($sql, 'SELECT')
&& str_contains($sql, 'tcm_prescription_order_pay_order')));
try {
$pdo->exec('CREATE TABLE zyt_order (
id INT PRIMARY KEY AUTO_INCREMENT, order_no VARCHAR(60), patient_id INT DEFAULT 50,
creator_id INT DEFAULT 1, order_type INT DEFAULT 3, amount DECIMAL(10,2) DEFAULT 100,
status INT DEFAULT 2, is_exempt INT DEFAULT 0, remark VARCHAR(500) DEFAULT "",
payment_method VARCHAR(50) DEFAULT "manual", create_type VARCHAR(50) DEFAULT "normal",
payment_time INT NULL, trade_no VARCHAR(100) NULL, payee_userid VARCHAR(100) NULL,
payer_external_userid VARCHAR(100) NULL, create_time INT DEFAULT 0, update_time INT DEFAULT 0,
delete_time INT NULL
) ENGINE=InnoDB');
$pdo->exec('CREATE TABLE zyt_tcm_prescription_order (
id INT PRIMARY KEY AUTO_INCREMENT, order_no VARCHAR(60), diagnosis_id INT DEFAULT 50,
prescription_id INT DEFAULT 1, creator_id INT DEFAULT 1, amount DECIMAL(10,2) DEFAULT 100,
agency_collect_amount DECIMAL(10,2) DEFAULT 0, linked_pay_order_id INT NULL,
prescription_audit_status INT DEFAULT 1, payment_slip_audit_status INT DEFAULT 1,
payment_slip_audit_remark VARCHAR(500) DEFAULT "", fulfillment_status INT DEFAULT 6,
paid DECIMAL(10,2) DEFAULT 100, refund_amount DECIMAL(10,2) DEFAULT 0,
internal_cost DECIMAL(10,2) DEFAULT 20, recipient_name VARCHAR(100) DEFAULT "private fixture",
remark_extra VARCHAR(500) DEFAULT "private note", create_time INT DEFAULT 0,
update_time INT DEFAULT 0, delete_time INT NULL
) ENGINE=InnoDB');
$pdo->exec('CREATE TABLE zyt_tcm_prescription_order_log (
id INT PRIMARY KEY AUTO_INCREMENT, prescription_order_id INT, admin_id INT,
admin_name VARCHAR(64), action VARCHAR(32), summary VARCHAR(500), create_time INT
) ENGINE=InnoDB');
$pdo->exec('CREATE TABLE zyt_admin (id INT PRIMARY KEY, name VARCHAR(100), delete_time INT NULL)');
$pdo->exec('CREATE TABLE zyt_admin_role (admin_id INT, role_id INT)');
$pdo->exec('CREATE TABLE zyt_tcm_diagnosis (id INT PRIMARY KEY, assistant_id INT, delete_time INT NULL)');
$payment = static function (string $no, array $fields = []): int {
return (int) Db::name('order')->insertGetId(array_merge([
'order_no' => $no, 'create_time' => 1800000000 + (int) Db::name('order')->count(),
], $fields));
};
$businessOrder = static fn (string $no, array $fields = []): int => (int) Db::name('tcm_prescription_order')
->insertGetId(array_merge(['order_no' => $no, 'create_time' => 1800000000], $fields));
$link = static fn (int $po, int $pay): int => (int) Db::name('tcm_prescription_order_pay_order')
->insertGetId(['prescription_order_id' => $po, 'pay_order_id' => $pay, 'create_time' => 1800000000]);
$brief = static fn (int $id, string $no): array => ['id' => $id, 'order_no' => $no];
$legacyPay = $payment('PAY-LEGACY');
$legacyPo = $businessOrder('RX-LEGACY', ['linked_pay_order_id' => $legacyPay]);
// Existing schema migration is the supported bridge from legacy primary links.
$migration = file_get_contents(dirname(__DIR__) . '/database/migrations/2026_04_09_prescription_order_pay_links.sql');
$pdo->exec($migration);
$pdo->exec($migration);
$expect(Db::name('tcm_prescription_order_pay_order')->count() === 1, 'Historical migration must remain idempotent');
$expect(PaymentPrescriptionOrderService::forPaymentIds([$legacyPay])[$legacyPay] === [$brief($legacyPo, 'RX-LEGACY')],
'Migrated historical legacy association must be visible');
$singlePay = $payment('PAY-SINGLE');
$singlePo = $businessOrder('RX-SINGLE');
$link($singlePo, $singlePay);
$multiPay = $payment('PAY-MULTI');
$cancelPo = $businessOrder('RX-CANCELLED', ['fulfillment_status' => 4]);
$refundPo = $businessOrder('RX-REFUNDED', ['fulfillment_status' => 10]);
$link($cancelPo, $multiPay);
$link($refundPo, $multiPay);
$refundPay = $payment('PAY-REFUNDED', ['status' => 4]);
$link($refundPo, $refundPay);
$cancelPay = $payment('PAY-CANCELLED', ['status' => 3]);
$link($cancelPo, $cancelPay);
$nonePay = $payment('PAY-NONE');
$businessOrder('RX-SAME-PATIENT'); // Same diagnosis alone is never an association.
$stalePay = $payment('PAY-STALE');
$businessOrder('RX-STALE-PRIMARY', ['linked_pay_order_id' => $stalePay]);
$deletedPoPay = $payment('PAY-DELETED-RX');
$deletedPo = $businessOrder('RX-DELETED', ['delete_time' => 1800000001]);
$link($deletedPo, $deletedPoPay);
$danglingPay = $payment('PAY-DANGLING');
$link(999999, $danglingPay);
$deletedPay = $payment('PAY-DELETED', ['delete_time' => 1800000001]);
$link($singlePo, $deletedPay);
$hiddenPay = $payment('PAY-OTHER-CREATOR', ['creator_id' => 2]);
$link($singlePo, $hiddenPay);
// Tolerate duplicate legacy/corrupt junction rows without duplicating the exposed order.
$pdo->exec('ALTER TABLE zyt_tcm_prescription_order_pay_order DROP INDEX uk_po_pay');
$link($refundPo, $multiPay);
$map = PaymentPrescriptionOrderService::forPaymentIds([$singlePay, $multiPay, $nonePay, $stalePay, $deletedPoPay, $danglingPay, $refundPay, $cancelPay]);
$expect($map[$singlePay] === [$brief($singlePo, 'RX-SINGLE')], 'Single exact junction link must resolve');
$expect($map[$multiPay] === [$brief($cancelPo, 'RX-CANCELLED'), $brief($refundPo, 'RX-REFUNDED')],
'Multiple cancelled/refunded historical business links must be ordered and deduplicated');
foreach ([$nonePay, $stalePay, $deletedPoPay, $danglingPay] as $id) {
$expect($map[$id] === [], 'Unassociated, stale primary, deleted and dangling links must be empty');
}
$expect($map[$refundPay] === [$brief($refundPo, 'RX-REFUNDED')], 'Refunded payment must retain its actual association');
$expect($map[$cancelPay] === [$brief($cancelPo, 'RX-CANCELLED')], 'Cancelled payment must retain its actual association');
$sqlLog = [];
$expect(PaymentPrescriptionOrderService::forPaymentIds([]) === [], 'Empty input must be empty');
$expect($associationQueries($sqlLog) === [], 'Empty input must not execute an association query');
$rootLists = $lists();
$expectedCount = (int) Db::name('order')->whereNull('delete_time')->count();
$sqlLog = [];
$rows = $rootLists->lists();
$expect(count($associationQueries($sqlLog)) === 1, 'A multi-payment page must use exactly one association SELECT');
$expect(count($rows) === $expectedCount && $rootLists->count() === $expectedCount, 'Links must not multiply payment rows/count');
$byId = array_column($rows, null, 'id');
$expect(!isset($byId[$deletedPay]), 'Soft-deleted payments must remain absent from the list');
foreach ($rows as $row) {
$detail = OrderLogic::detail((int) $row['id']);
$expect($row['prescription_orders'] === $detail['prescription_orders'], 'List and detail associations must agree');
foreach ($row['prescription_orders'] as $order) {
$expect(array_keys($order) === ['id', 'order_no'] && is_int($order['id']) && is_string($order['order_no']),
'Association payload must contain only typed id and order_no');
}
}
$expect(OrderLogic::detail($deletedPay) === null && OrderLogic::detail(999999) === null, 'Deleted/missing detail must stay null');
$expect($byId[$nonePay]['prescription_orders'] === [] && $byId[$stalePay]['prescription_orders'] === [],
'List must expose [] for no actual association, including stale legacy-only field');
$sqlLog = [];
$page = $lists(1, true, 2, 3)->lists();
$expect(array_column($page, 'id') === array_column(array_slice($rows, 2, 3), 'id'), 'Pagination order and offset must remain unchanged');
$pageQueries = $associationQueries($sqlLog);
$expect(count($pageQueries) === 1, 'Paginated lookup must execute once');
$expect(preg_match('/`link`\.`pay_order_id` IN \(([^)]+)\)/', $pageQueries[0], $matches) === 1,
'Association query must be bounded by visible payment IDs');
$queryIds = array_map(static fn (string $id): int => (int) trim($id, " '\""), explode(',', $matches[1]));
$expect($queryIds === array_map('intval', array_column($page, 'id')),
'Association query must include exactly current page IDs');
$emptyPage = $lists(1, true, 999, 3);
$sqlLog = [];
$expect($emptyPage->lists() === [] && $associationQueries($sqlLog) === [], 'Empty pages must skip lookup');
$ordinaryLists = $lists(1, false);
$ordinaryRows = $ordinaryLists->lists();
$expect(!in_array($hiddenPay, array_column($ordinaryRows, 'id')), 'Existing creator permission must continue hiding other payments');
$expect($ordinaryLists->count() === $expectedCount - 1, 'Permission-filtered count must be unchanged');
$filtered = $lists(1, true, 0, 100, [['status', '=', 4]]);
$expect(array_column($filtered->lists(), 'id') === [$refundPay] && $filtered->count() === 1, 'Existing status search must be preserved');
$removePay = $payment('PAY-UNLINK');
$removePo = $businessOrder('RX-UNLINK', ['linked_pay_order_id' => $removePay]);
$link($removePo, $removePay);
$expect(OrderLogic::detail($removePay)['prescription_orders'] === [$brief($removePo, 'RX-UNLINK')], 'Link must be visible before unlink');
$removed = PrescriptionOrderLogic::unlinkPayOrder(['id' => $removePo, 'pay_order_id' => $removePay], 1, $admin);
$expect(is_array($removed), 'Real unlink must succeed: ' . PrescriptionOrderLogic::getError());
$expect(OrderLogic::detail($removePay)['prescription_orders'] === [], 'Explicitly removed association must disappear');
$expect(Db::name('tcm_prescription_order')->where('id', $removePo)->value('linked_pay_order_id') === null,
'Existing unlink must clear the legacy primary');
Db::name('tcm_prescription_order')->where('id', $removePo)->update(['linked_pay_order_id' => $removePay]);
$expect(OrderLogic::detail($removePay)['prescription_orders'] === [], 'A stale primary must never resurrect an explicitly removed association');
$splitPay = $payment('PAY-SPLIT', ['amount' => 100]);
$splitPo = $businessOrder('RX-SPLIT', ['linked_pay_order_id' => $splitPay]);
$link($splitPo, $splitPay);
$split = OrderLogic::split($splitPay, [40, 60], [3, 3]);
$expect(is_array($split), 'Real payment split must succeed: ' . OrderLogic::getError());
$expect(OrderLogic::detail($splitPay) === null, 'Split parent must remain soft deleted');
$expect(PaymentPrescriptionOrderService::forPaymentIds([$splitPay])[$splitPay] === [], 'Transferred junction must not remain on stale split parent');
foreach ($split['new_order_ids'] as $id) {
$expect(OrderLogic::detail($id)['prescription_orders'] === [$brief($splitPo, 'RX-SPLIT')], 'Every split child must show the transferred business association');
}
echo "PASS PaymentPrescriptionOrderLinksTest ({$checks} checks; real ORM list/detail, one batch query, legacy migration/unlink/split)\n";
} finally {
$pdo->exec("DROP DATABASE `{$database}`");
}